41#include "llvm/ADT/DepthFirstIterator.h"
42#include "llvm/ADT/PostOrderIterator.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/ScopeExit.h"
45#include "llvm/ADT/SmallPtrSet.h"
46#include "llvm/ADT/StringExtras.h"
47#include "llvm/ADT/TypeSwitch.h"
48#include "llvm/IR/Comdat.h"
49#include "llvm/IR/Constants.h"
50#include "llvm/IR/DebugProgramInstruction.h"
51#include "llvm/IR/InlineAsm.h"
52#include "llvm/IR/InstIterator.h"
53#include "llvm/IR/Instructions.h"
54#include "llvm/IR/IntrinsicInst.h"
55#include "llvm/IR/Metadata.h"
56#include "llvm/IR/ModuleSlotTracker.h"
57#include "llvm/IR/Operator.h"
58#include "llvm/Support/LogicalResult.h"
59#include "llvm/Support/ModRef.h"
66#include "mlir/Dialect/LLVMIR/LLVMConversionEnumsFromLLVM.inc"
81 str +=
"... <truncated>";
88 llvm::ModuleSlotTracker &tracker,
89 const llvm::Module *module) {
91 llvm::raw_string_ostream os(str);
92 node->print(os, tracker, module,
true);
96llvm::ModuleSlotTracker &ModuleImport::getDiagSlotTracker() {
101 if (!diagSlotTracker)
103 std::make_unique<llvm::ModuleSlotTracker>(llvmModule.get());
104 return *diagSlotTracker;
107std::string ModuleImport::renderValue(
const llvm::Value &value) {
109 llvm::raw_string_ostream os(str);
112 if (
const auto *global = llvm::dyn_cast<llvm::GlobalValue>(&value)) {
113 global->printAsOperand(os,
false, getDiagSlotTracker());
116 value.print(os, getDiagSlotTracker());
120std::string ModuleImport::renderMetadata(
const llvm::Metadata *node) {
127 return "llvm.global_ctors";
132 return "mlir.llvm.nameless_global";
137 return "llvm.global_dtors";
143 return "__llvm_global_comdat";
152 std::optional<llvm::SyncScope::ID> syncScopeID =
153 llvm::getAtomicSyncScopeID(inst);
160 llvm::LLVMContext &llvmContext = inst->getContext();
161 llvmContext.getSyncScopeNames(syncScopeName);
162 auto *it = llvm::find_if(syncScopeName, [&](StringRef name) {
163 return *syncScopeID == llvmContext.getOrInsertSyncScopeID(name);
165 if (it != syncScopeName.end())
167 llvm_unreachable(
"incorrect sync scope identifier");
173 llvm::append_range(position,
indices);
184 llvm::Instruction *inst,
197#include "mlir/Dialect/LLVMIR/LLVMOpFromLLVMIRConversions.inc"
203ModuleImport::getMetadataGlobalValueSymbolRef(llvm::GlobalValue *global) {
204 if (
auto *globalVar = dyn_cast<llvm::GlobalVariable>(global)) {
205 StringRef name = globalVar->getName();
207 return getOrCreateNamelessSymbolName(globalVar);
212 if (
auto *func = dyn_cast<llvm::Function>(global)) {
215 if (func->isIntrinsic() &&
216 iface.isConvertibleIntrinsic(func->getIntrinsicID()))
220 if (global->getName().empty())
226ModuleImport::getMetadataOperandSymbolRef(
const llvm::Metadata *md) {
227 auto *valueAsMD = dyn_cast_or_null<llvm::ValueAsMetadata>(md);
230 llvm::Value *value = valueAsMD->getValue();
231 llvm::GlobalValue *gv = dyn_cast<llvm::GlobalValue>(value);
233 gv = dyn_cast<llvm::GlobalValue>(value->stripPointerCastsAndAliases());
236 return getMetadataGlobalValueSymbolRef(gv);
248Attribute ModuleImport::convertMetadataToAttrImpl(
249 const llvm::Metadata *md, SmallPtrSetImpl<const llvm::Metadata *> &path,
253 if (
auto *mdStr = dyn_cast<llvm::MDString>(md))
254 return MDStringAttr::get(context,
255 StringAttr::get(context, mdStr->getString()));
256 if (
auto *cam = dyn_cast<llvm::ConstantAsMetadata>(md)) {
257 llvm::Constant *constant = cam->getValue();
258 if (
auto *global = dyn_cast<llvm::GlobalValue>(constant)) {
259 if (FlatSymbolRefAttr symbolRef = getMetadataGlobalValueSymbolRef(global))
260 return MDGlobalValueAttr::get(context, symbolRef);
262 if (
auto *ci = dyn_cast<llvm::ConstantInt>(constant)) {
263 auto intType = IntegerType::get(context, ci->getBitWidth());
264 return MDConstantAttr::get(context,
265 IntegerAttr::get(intType, ci->getValue()));
267 if (
auto *nullPtr = dyn_cast<llvm::ConstantPointerNull>(constant))
268 return MDNullAttr::get(context,
269 nullPtr->getType()->getPointerAddressSpace());
270 if (
auto *constExpr = dyn_cast<llvm::ConstantExpr>(constant)) {
273 if (constExpr->getOpcode() != llvm::Instruction::AddrSpaceCast)
275 Attribute argAttr = convertMetadataToAttrImpl(
276 llvm::ConstantAsMetadata::get(constExpr->getOperand(0)), path,
280 return MDAddrSpaceCastAttr::get(
281 context, argAttr, constExpr->getType()->getPointerAddressSpace());
285 if (
auto *node = dyn_cast<llvm::MDNode>(md)) {
287 if (node->isDistinct())
289 if (Attribute cached = attrMap.lookup(node))
293 if (!path.insert(node).second)
295 SmallVector<Attribute> operands;
296 operands.reserve(node->getNumOperands());
297 for (
const llvm::MDOperand &op : node->operands()) {
298 Attribute opAttr = convertMetadataToAttrImpl(op.get(), path, attrMap);
301 operands.push_back(opAttr);
304 Attribute nodeAttr = MDNodeAttr::get(context, operands);
305 attrMap.try_emplace(node, nodeAttr);
316Attribute ModuleImport::convertMetadataToAttr(
const llvm::Metadata *md) {
317 SmallPtrSet<const llvm::Metadata *, 8> path;
319 return convertMetadataToAttrImpl(md, path, attrMap);
326 for (llvm::BasicBlock *basicBlock : basicBlocks) {
327 if (!blocks.contains(basicBlock)) {
328 llvm::ReversePostOrderTraversal<llvm::BasicBlock *> traversal(basicBlock);
329 blocks.insert_range(traversal);
332 assert(blocks.size() == basicBlocks.size() &&
"some blocks are not sorted");
339 std::unique_ptr<llvm::Module> llvmModule,
340 bool emitExpensiveWarnings,
341 bool importEmptyDICompositeTypes,
342 bool preferUnregisteredIntrinsics,
343 bool importStructsAsLiterals)
345 mlirModule(mlirModule), llvmModule(std::move(llvmModule)),
347 typeTranslator(*mlirModule->
getContext(), importStructsAsLiterals),
349 mlirModule, importEmptyDICompositeTypes)),
350 loopAnnotationImporter(
352 emitExpensiveWarnings(emitExpensiveWarnings),
353 preferUnregisteredIntrinsics(preferUnregisteredIntrinsics) {
354 builder.setInsertionPointToStart(mlirModule.getBody());
357ComdatOp ModuleImport::getGlobalComdatOp() {
359 return globalComdatOp;
365 globalInsertionOp = globalComdatOp;
366 return globalComdatOp;
369LogicalResult ModuleImport::processTBAAMetadata(
const llvm::MDNode *node) {
374 auto getIdentityIfRootNode =
375 [&](
const llvm::MDNode *node) -> FailureOr<std::optional<StringRef>> {
379 if (node->getNumOperands() > 1)
382 if (node->getNumOperands() == 1)
383 if (
const auto *op0 = dyn_cast<const llvm::MDString>(node->getOperand(0)))
384 return std::optional<StringRef>{op0->getString()};
385 return std::optional<StringRef>{};
395 auto isTypeDescriptorNode = [&](
const llvm::MDNode *node,
396 StringRef *identity =
nullptr,
397 SmallVectorImpl<TBAAMemberAttr> *members =
398 nullptr) -> std::optional<bool> {
399 unsigned numOperands = node->getNumOperands();
408 const auto *identityNode =
409 dyn_cast<const llvm::MDString>(node->getOperand(0));
415 *identity = identityNode->getString();
417 for (
unsigned pairNum = 0, e = numOperands / 2; pairNum < e; ++pairNum) {
418 const auto *memberNode =
419 dyn_cast<const llvm::MDNode>(node->getOperand(2 * pairNum + 1));
421 emitError(loc) <<
"operand '" << 2 * pairNum + 1
422 <<
"' must be MDNode: " << renderMetadata(node);
426 if (2 * pairNum + 2 >= numOperands) {
428 if (numOperands != 2) {
429 emitError(loc) <<
"missing member offset: " << renderMetadata(node);
433 auto *offsetCI = llvm::mdconst::dyn_extract<llvm::ConstantInt>(
434 node->getOperand(2 * pairNum + 2));
436 emitError(loc) <<
"operand '" << 2 * pairNum + 2
437 <<
"' must be ConstantInt: " << renderMetadata(node);
440 offset = offsetCI->getZExtValue();
444 members->push_back(TBAAMemberAttr::get(
445 cast<TBAANodeAttr>(tbaaMapping.lookup(memberNode)), offset));
458 auto isTagNode = [&](
const llvm::MDNode *node,
459 TBAATypeDescriptorAttr *baseAttr =
nullptr,
460 TBAATypeDescriptorAttr *accessAttr =
nullptr,
461 int64_t *offset =
nullptr,
462 bool *isConstant =
nullptr) -> std::optional<bool> {
470 unsigned numOperands = node->getNumOperands();
471 if (numOperands != 3 && numOperands != 4)
473 const auto *baseMD = dyn_cast<const llvm::MDNode>(node->getOperand(0));
474 const auto *accessMD = dyn_cast<const llvm::MDNode>(node->getOperand(1));
476 llvm::mdconst::dyn_extract<llvm::ConstantInt>(node->getOperand(2));
477 if (!baseMD || !accessMD || !offsetCI)
484 if (accessMD->getNumOperands() < 1 ||
485 !isa<llvm::MDString>(accessMD->getOperand(0)))
487 bool isConst =
false;
488 if (numOperands == 4) {
490 llvm::mdconst::dyn_extract<llvm::ConstantInt>(node->getOperand(3));
492 emitError(loc) <<
"operand '3' must be ConstantInt: "
493 << renderMetadata(node);
496 isConst = isConstantCI->getValue()[0];
499 *baseAttr = cast<TBAATypeDescriptorAttr>(tbaaMapping.lookup(baseMD));
501 *accessAttr = cast<TBAATypeDescriptorAttr>(tbaaMapping.lookup(accessMD));
503 *offset = offsetCI->getZExtValue();
505 *isConstant = isConst;
513 SmallVector<const llvm::MDNode *> workList;
514 workList.push_back(node);
515 while (!workList.empty()) {
516 const llvm::MDNode *current = workList.back();
517 if (tbaaMapping.contains(current)) {
526 bool anyChildNotConverted =
false;
527 for (
const llvm::MDOperand &operand : current->operands())
528 if (
auto *childNode = dyn_cast_or_null<const llvm::MDNode>(operand.get()))
529 if (!tbaaMapping.contains(childNode)) {
530 workList.push_back(childNode);
531 anyChildNotConverted =
true;
534 if (anyChildNotConverted) {
539 if (!seen.insert(current).second)
541 <<
"has cycle in TBAA graph: " << renderMetadata(current);
549 FailureOr<std::optional<StringRef>> rootNodeIdentity =
550 getIdentityIfRootNode(current);
551 if (succeeded(rootNodeIdentity)) {
552 StringAttr stringAttr = *rootNodeIdentity
553 ? builder.getStringAttr(**rootNodeIdentity)
557 tbaaMapping.insert({current, builder.getAttr<TBAARootAttr>(stringAttr)});
562 SmallVector<TBAAMemberAttr> members;
563 if (std::optional<bool> isValid =
564 isTypeDescriptorNode(current, &identity, &members)) {
565 assert(isValid.value() &&
"type descriptor node must be valid");
567 tbaaMapping.insert({current, builder.getAttr<TBAATypeDescriptorAttr>(
568 identity, members)});
572 TBAATypeDescriptorAttr baseAttr, accessAttr;
575 if (std::optional<bool> isValid =
576 isTagNode(current, &baseAttr, &accessAttr, &offset, &isConstant)) {
577 assert(isValid.value() &&
"access tag node must be valid");
579 {current, builder.getAttr<TBAATagAttr>(baseAttr, accessAttr, offset,
584 return emitError(loc) <<
"unsupported TBAA node format: "
585 << renderMetadata(current);
590Attribute ModuleImport::convertTBAAStructMetadata(
const llvm::MDNode *node) {
592 if (node->getNumOperands() == 0 || node->getNumOperands() % 3 != 0)
595 SmallVector<Attribute> fields;
596 fields.reserve(node->getNumOperands() / 3);
597 for (
unsigned i = 0, e = node->getNumOperands(); i != e; i += 3) {
598 auto *offset = llvm::mdconst::dyn_extract_or_null<llvm::ConstantInt>(
599 node->getOperand(i));
600 auto *size = llvm::mdconst::dyn_extract_or_null<llvm::ConstantInt>(
601 node->getOperand(i + 1));
602 if (!offset || !size)
609 const APInt &offsetAP = offset->getValue();
610 const APInt &sizeAP = size->getValue();
611 if (offsetAP.getActiveBits() > 64 || sizeAP.getActiveBits() > 64)
613 auto *tagNode = dyn_cast_if_present<llvm::MDNode>(node->getOperand(i + 2));
616 auto tag = dyn_cast_if_present<TBAATagAttr>(
lookupTBAAAttr(tagNode));
619 fields.push_back(builder.getAttr<TBAAStructFieldAttr>(
620 offsetAP.getZExtValue(), sizeAP.getZExtValue(), tag));
623 return builder.getArrayAttr(fields);
627ModuleImport::processAccessGroupMetadata(
const llvm::MDNode *node) {
628 Location loc = mlirModule.getLoc();
629 if (
failed(loopAnnotationImporter->translateAccessGroup(node, loc)))
630 return emitError(loc) <<
"unsupported access group node: "
631 << renderMetadata(node);
636ModuleImport::processAliasScopeMetadata(
const llvm::MDNode *node) {
637 Location loc = mlirModule.getLoc();
639 auto verifySelfRef = [](
const llvm::MDNode *node) {
640 return node->getNumOperands() != 0 &&
641 node == dyn_cast<llvm::MDNode>(node->getOperand(0));
643 auto verifySelfRefOrString = [](
const llvm::MDNode *node) {
644 return node->getNumOperands() != 0 &&
645 (node == dyn_cast<llvm::MDNode>(node->getOperand(0)) ||
646 isa<llvm::MDString>(node->getOperand(0)));
649 auto verifyDescription = [](
const llvm::MDNode *node,
unsigned idx) {
650 return idx >= node->getNumOperands() ||
651 isa<llvm::MDString>(node->getOperand(idx));
654 auto getIdAttr = [&](
const llvm::MDNode *node) -> Attribute {
655 if (verifySelfRef(node))
658 auto *name = cast<llvm::MDString>(node->getOperand(0));
659 return builder.getStringAttr(name->getString());
663 auto createAliasScopeDomainOp = [&](
const llvm::MDNode *aliasDomain) {
664 StringAttr description =
nullptr;
665 StringRef descriptionStr =
666 llvm::AliasScopeDomainNode(aliasDomain).getDescription();
667 if (!descriptionStr.empty())
668 description = builder.getStringAttr(descriptionStr);
669 Attribute idAttr = getIdAttr(aliasDomain);
670 return builder.getAttr<AliasScopeDomainAttr>(idAttr, description);
674 for (
const llvm::MDOperand &operand : node->operands()) {
675 if (
const auto *scope = dyn_cast<llvm::MDNode>(operand)) {
676 llvm::AliasScopeNode aliasScope(scope);
677 const llvm::MDNode *domain = aliasScope.getDomain();
683 if (!verifySelfRefOrString(scope) || !domain ||
684 !verifyDescription(scope, 2))
686 <<
"unsupported alias scope node: " << renderMetadata(scope);
687 if (!verifySelfRefOrString(domain) || !verifyDescription(domain, 2))
689 <<
"unsupported alias domain node: " << renderMetadata(domain);
691 if (aliasScopeMapping.contains(scope))
695 auto it = aliasScopeMapping.find(aliasScope.getDomain());
696 if (it == aliasScopeMapping.end()) {
697 auto aliasScopeDomainOp = createAliasScopeDomainOp(domain);
698 it = aliasScopeMapping.try_emplace(domain, aliasScopeDomainOp).first;
702 StringAttr description =
nullptr;
703 if (!aliasScope.getName().empty())
704 description = builder.getStringAttr(aliasScope.getName());
705 Attribute idAttr = getIdAttr(scope);
706 auto aliasScopeOp = builder.getAttr<AliasScopeAttr>(
707 idAttr, cast<AliasScopeDomainAttr>(it->second), description);
709 aliasScopeMapping.try_emplace(aliasScope.getNode(), aliasScopeOp);
715FailureOr<SmallVector<AliasScopeAttr>>
718 aliasScopes.reserve(node->getNumOperands());
719 for (
const llvm::MDOperand &operand : node->operands()) {
720 auto *node = cast<llvm::MDNode>(operand.get());
721 aliasScopes.push_back(
722 dyn_cast_or_null<AliasScopeAttr>(aliasScopeMapping.lookup(node)));
725 if (llvm::is_contained(aliasScopes,
nullptr))
731 debugIntrinsics.insert(intrinsic);
735 if (!dbgRecords.contains(dbgRecord))
736 dbgRecords.insert(dbgRecord);
740 llvm::MDTuple *mdTuple) {
741 auto getLLVMFunction =
742 [&](
const llvm::MDOperand &funcMDO) -> llvm::Function * {
743 auto *f = cast_or_null<llvm::ValueAsMetadata>(funcMDO);
747 auto *llvmFn = cast<llvm::Function>(f->getValue()->stripPointerCasts());
753 for (
unsigned i = 0; i < mdTuple->getNumOperands(); i++) {
754 const llvm::MDOperand &mdo = mdTuple->getOperand(i);
755 auto *cgEntry = cast<llvm::MDNode>(mdo);
756 llvm::Constant *llvmConstant =
757 cast<llvm::ConstantAsMetadata>(cgEntry->getOperand(2))->getValue();
758 uint64_t count = cast<llvm::ConstantInt>(llvmConstant)->getZExtValue();
759 auto *fromFn = getLLVMFunction(cgEntry->getOperand(0));
760 auto *toFn = getLLVMFunction(cgEntry->getOperand(1));
762 cgProfile.push_back(ModuleFlagCGProfileEntryAttr::get(
763 mlirModule->getContext(),
771 return ArrayAttr::get(mlirModule->getContext(), cgProfile);
777 const llvm::Module *llvmModule,
778 const llvm::MDOperand &md,
779 llvm::ModuleSlotTracker &tracker) {
780 auto *tupleEntry = dyn_cast_or_null<llvm::MDTuple>(md);
781 if (!tupleEntry || tupleEntry->getNumOperands() != 2)
783 <<
"expected 2-element tuple metadata: "
792 ModuleOp mlirModule,
const llvm::Module *llvmModule,
793 const llvm::MDOperand &md, StringRef matchKey,
794 llvm::ModuleSlotTracker &tracker,
bool optional =
false) {
795 llvm::MDTuple *tupleEntry =
799 auto *keyMD = dyn_cast<llvm::MDString>(tupleEntry->getOperand(0));
800 if (!keyMD || keyMD->getString() != matchKey) {
803 <<
"expected '" << matchKey <<
"' key, but found: "
809 return dyn_cast<llvm::ConstantAsMetadata>(tupleEntry->getOperand(1));
815static FailureOr<uint64_t>
817 const llvm::Module *llvmModule,
818 const llvm::MDOperand &md, StringRef matchKey,
819 llvm::ModuleSlotTracker &tracker) {
821 mlirModule, llvmModule, md, matchKey, tracker);
825 if (
auto *cstInt = dyn_cast<llvm::ConstantInt>(valMD->getValue()))
826 return cstInt->getZExtValue();
829 <<
"expected integer metadata value for key '" << matchKey
834static std::optional<ProfileSummaryFormatKind>
836 const llvm::MDOperand &formatMD,
837 llvm::ModuleSlotTracker &tracker) {
843 llvm::MDString *keyMD = dyn_cast<llvm::MDString>(tupleEntry->getOperand(0));
844 if (!keyMD || keyMD->getString() !=
"ProfileFormat") {
846 <<
"expected 'ProfileFormat' key: "
852 llvm::Metadata *valueMD = tupleEntry->getOperand(1).get();
855 <<
"expected string metadata value for key 'ProfileFormat': null";
859 llvm::MDString *valMD = dyn_cast<llvm::MDString>(valueMD);
862 <<
"expected string metadata value for key 'ProfileFormat': "
866 std::optional<ProfileSummaryFormatKind> fmtKind =
867 symbolizeProfileSummaryFormatKind(valMD->getString());
870 <<
"expected 'SampleProfile', 'InstrProf' or 'CSInstrProf' values, "
879static FailureOr<SmallVector<ModuleFlagProfileSummaryDetailedAttr>>
881 const llvm::Module *llvmModule,
882 const llvm::MDOperand &summaryMD,
883 llvm::ModuleSlotTracker &tracker) {
889 llvm::MDString *keyMD = dyn_cast<llvm::MDString>(tupleEntry->getOperand(0));
890 if (!keyMD || keyMD->getString() !=
"DetailedSummary") {
892 <<
"expected 'DetailedSummary' key: "
898 llvm::MDTuple *entriesMD = dyn_cast<llvm::MDTuple>(tupleEntry->getOperand(1));
901 <<
"expected tuple value for 'DetailedSummary' key: "
908 for (
auto &&entry : entriesMD->operands()) {
909 llvm::MDTuple *entryMD = dyn_cast<llvm::MDTuple>(entry);
910 if (!entryMD || entryMD->getNumOperands() != 3) {
912 <<
"'DetailedSummary' entry expects 3 operands: "
917 auto *op0 = dyn_cast<llvm::ConstantAsMetadata>(entryMD->getOperand(0));
918 auto *op1 = dyn_cast<llvm::ConstantAsMetadata>(entryMD->getOperand(1));
919 auto *op2 = dyn_cast<llvm::ConstantAsMetadata>(entryMD->getOperand(2));
920 if (!op0 || !op1 || !op2) {
922 <<
"expected only integer entries in 'DetailedSummary': "
927 auto detaildSummaryEntry = ModuleFlagProfileSummaryDetailedAttr::get(
928 mlirModule->getContext(),
929 cast<llvm::ConstantInt>(op0->getValue())->getZExtValue(),
930 cast<llvm::ConstantInt>(op1->getValue())->getZExtValue(),
931 cast<llvm::ConstantInt>(op2->getValue())->getZExtValue());
932 detailedSummary.push_back(detaildSummaryEntry);
934 return detailedSummary;
938 ModuleOp mlirModule,
const llvm::Module *llvmModule, llvm::MDTuple *mdTuple,
939 llvm::ModuleSlotTracker &tracker) {
940 unsigned profileNumEntries = mdTuple->getNumOperands();
941 if (profileNumEntries < 8) {
943 <<
"expected at 8 entries in 'ProfileSummary': "
948 unsigned summayIdx = 0;
949 auto checkOptionalPosition = [&](
const llvm::MDOperand &md,
950 StringRef matchKey) -> LogicalResult {
954 if (summayIdx + 1 >= profileNumEntries) {
956 <<
"the last summary entry is '" << matchKey
957 <<
"', expected 'DetailedSummary': "
965 auto getOptIntValue =
966 [&](
const llvm::MDOperand &md,
967 StringRef matchKey) -> FailureOr<std::optional<uint64_t>> {
971 return FailureOr<std::optional<uint64_t>>(std::nullopt);
972 if (checkOptionalPosition(md, matchKey).failed())
975 mlirModule, llvmModule, md, matchKey, tracker);
981 auto getOptDoubleValue = [&](
const llvm::MDOperand &md,
982 StringRef matchKey) -> FailureOr<FloatAttr> {
988 if (
auto *cstFP = dyn_cast<llvm::ConstantFP>(valMD->getValue())) {
989 if (checkOptionalPosition(md, matchKey).failed())
991 return FloatAttr::get(Float64Type::get(mlirModule.getContext()),
992 cstFP->getValueAPF());
995 <<
"expected double metadata value for key '" << matchKey
1003 mlirModule, llvmModule, mdTuple->getOperand(summayIdx++), tracker);
1004 if (!format.has_value())
1008 mlirModule, llvmModule, mdTuple->getOperand(summayIdx++),
"TotalCount",
1010 if (failed(totalCount))
1014 mlirModule, llvmModule, mdTuple->getOperand(summayIdx++),
"MaxCount",
1016 if (failed(maxCount))
1020 mlirModule, llvmModule, mdTuple->getOperand(summayIdx++),
1021 "MaxInternalCount", tracker);
1022 if (failed(maxInternalCount))
1026 mlirModule, llvmModule, mdTuple->getOperand(summayIdx++),
1027 "MaxFunctionCount", tracker);
1028 if (failed(maxFunctionCount))
1032 mlirModule, llvmModule, mdTuple->getOperand(summayIdx++),
"NumCounts",
1034 if (failed(numCounts))
1038 mlirModule, llvmModule, mdTuple->getOperand(summayIdx++),
"NumFunctions",
1040 if (failed(numFunctions))
1044 FailureOr<std::optional<uint64_t>> isPartialProfile =
1045 getOptIntValue(mdTuple->getOperand(summayIdx),
"IsPartialProfile");
1046 if (failed(isPartialProfile))
1048 if (isPartialProfile->has_value())
1051 FailureOr<FloatAttr> partialProfileRatio =
1052 getOptDoubleValue(mdTuple->getOperand(summayIdx),
"PartialProfileRatio");
1053 if (failed(partialProfileRatio))
1055 if (*partialProfileRatio)
1059 FailureOr<SmallVector<ModuleFlagProfileSummaryDetailedAttr>> detailed =
1061 mdTuple->getOperand(summayIdx), tracker);
1062 if (failed(detailed))
1066 return ModuleFlagProfileSummaryAttr::get(
1067 mlirModule->getContext(), *format, *totalCount, *maxCount,
1068 *maxInternalCount, *maxFunctionCount, *numCounts, *numFunctions,
1069 *isPartialProfile, *partialProfileRatio, *detailed);
1075 ModuleOp mlirModule,
const llvm::Module *llvmModule, StringRef key,
1076 llvm::MDTuple *mdTuple, llvm::ModuleSlotTracker &tracker) {
1077 if (key == LLVMDialect::getModuleFlagKeyCGProfileName())
1079 if (key == LLVMDialect::getModuleFlagKeyProfileSummaryName())
1084 Builder builder(mlirModule->getContext());
1086 strings.reserve(mdTuple->getNumOperands());
1087 for (
const llvm::MDOperand &operand : mdTuple->operands()) {
1088 auto *mdString = dyn_cast_if_present<llvm::MDString>(operand.get());
1091 strings.push_back(builder.
getStringAttr(mdString->getString()));
1098 llvmModule->getModuleFlagsMetadata(llvmModuleFlags);
1101 for (
const auto [behavior, key, val] : llvmModuleFlags) {
1103 if (
auto *constInt = llvm::mdconst::dyn_extract<llvm::ConstantInt>(val)) {
1104 valAttr = builder.getI32IntegerAttr(constInt->getZExtValue());
1105 }
else if (
auto *mdString = dyn_cast<llvm::MDString>(val)) {
1106 valAttr = builder.getStringAttr(mdString->getString());
1107 }
else if (
auto *mdTuple = dyn_cast<llvm::MDTuple>(val)) {
1109 key->getString(), mdTuple,
1110 getDiagSlotTracker());
1115 <<
"unsupported module flag value for key '" << key->getString()
1116 <<
"' : " << renderMetadata(val);
1120 moduleFlags.push_back(builder.getAttr<ModuleFlagAttr>(
1121 convertModFlagBehaviorFromLLVM(behavior),
1122 builder.getStringAttr(key->getString()), valAttr));
1125 if (!moduleFlags.empty())
1126 LLVM::ModuleFlagsOp::create(builder, mlirModule.getLoc(),
1127 builder.getArrayAttr(moduleFlags));
1133 for (
const llvm::NamedMDNode &named : llvmModule->named_metadata()) {
1134 if (named.getName() !=
"llvm.linker.options")
1137 for (
const llvm::MDNode *node : named.operands()) {
1139 options.reserve(node->getNumOperands());
1140 for (
const llvm::MDOperand &option : node->operands())
1141 options.push_back(cast<llvm::MDString>(option)->getString());
1142 LLVM::LinkerOptionsOp::create(builder, mlirModule.getLoc(),
1143 builder.getStrArrayAttr(
options));
1150 for (
const llvm::NamedMDNode &named : llvmModule->named_metadata()) {
1151 if (named.getName() !=
"llvm.dependent-libraries")
1154 for (
const llvm::MDNode *node : named.operands()) {
1155 if (node->getNumOperands() == 1)
1156 if (
auto *mdString = dyn_cast<llvm::MDString>(node->getOperand(0)))
1157 libraries.push_back(mdString->getString());
1159 if (!libraries.empty())
1160 mlirModule->setDiscardableAttr(
1161 LLVM::LLVMDialect::getDependentLibrariesAttrName(),
1162 builder.getStrArrayAttr(libraries));
1168 for (
const llvm::NamedMDNode &named : llvmModule->named_metadata()) {
1171 if (named.getName() != LLVMDialect::getIdentAttrName())
1174 if (named.getNumOperands() == 1)
1175 if (
auto *md = dyn_cast<llvm::MDNode>(named.getOperand(0)))
1176 if (md->getNumOperands() == 1)
1177 if (
auto *mdStr = dyn_cast<llvm::MDString>(md->getOperand(0)))
1178 mlirModule->setDiscardableAttr(
1179 LLVMDialect::getIdentAttrName(),
1180 builder.getStringAttr(mdStr->getString()));
1186 for (
const llvm::NamedMDNode &nmd : llvmModule->named_metadata()) {
1189 if (nmd.getName() != LLVMDialect::getCommandlineAttrName())
1192 if (nmd.getNumOperands() == 1)
1193 if (
auto *md = dyn_cast<llvm::MDNode>(nmd.getOperand(0)))
1194 if (md->getNumOperands() == 1)
1195 if (
auto *mdStr = dyn_cast<llvm::MDString>(md->getOperand(0)))
1196 mlirModule->setDiscardableAttr(
1197 LLVMDialect::getCommandlineAttrName(),
1198 builder.getStringAttr(mdStr->getString()));
1205 builder.setInsertionPointToEnd(mlirModule.getBody());
1206 for (
const llvm::Function &
func : llvmModule->functions()) {
1207 for (
const llvm::Instruction &inst : llvm::instructions(
func)) {
1209 if (llvm::MDNode *node =
1210 inst.getMetadata(llvm::LLVMContext::MD_access_group))
1211 if (failed(processAccessGroupMetadata(node)))
1215 llvm::AAMDNodes aliasAnalysisNodes = inst.getAAMetadata();
1216 if (!aliasAnalysisNodes)
1218 if (aliasAnalysisNodes.TBAA)
1219 if (failed(processTBAAMetadata(aliasAnalysisNodes.TBAA)))
1224 if (aliasAnalysisNodes.TBAAStruct) {
1225 const llvm::MDNode *structNode = aliasAnalysisNodes.TBAAStruct;
1229 bool wellFormed = structNode->getNumOperands() % 3 == 0;
1231 for (
unsigned i = 2, e = structNode->getNumOperands(); i < e; i += 3)
1232 if (
auto *tag = dyn_cast_if_present<llvm::MDNode>(
1233 structNode->getOperand(i)))
1234 if (failed(processTBAAMetadata(tag)))
1241 if (!tbaaStructMapping.contains(structNode))
1242 tbaaStructMapping.insert(
1243 {structNode, convertTBAAStructMetadata(structNode)});
1245 if (aliasAnalysisNodes.Scope)
1246 if (failed(processAliasScopeMetadata(aliasAnalysisNodes.Scope)))
1248 if (aliasAnalysisNodes.NoAlias)
1249 if (failed(processAliasScopeMetadata(aliasAnalysisNodes.NoAlias)))
1266void ModuleImport::processComdat(
const llvm::Comdat *comdat) {
1267 if (comdatMapping.contains(comdat))
1270 ComdatOp comdatOp = getGlobalComdatOp();
1273 auto selectorOp = ComdatSelectorOp::create(
1274 builder, mlirModule.getLoc(), comdat->getName(),
1275 convertComdatFromLLVM(comdat->getSelectionKind()),
1280 comdatMapping.try_emplace(comdat, symbolRef);
1284 for (llvm::GlobalVariable &globalVar : llvmModule->globals())
1285 if (globalVar.hasComdat())
1286 processComdat(globalVar.getComdat());
1287 for (llvm::Function &
func : llvmModule->functions())
1288 if (
func.hasComdat())
1289 processComdat(
func.getComdat());
1294 for (llvm::GlobalVariable &globalVar : llvmModule->globals()) {
1297 if (failed(convertGlobalCtorsAndDtors(&globalVar))) {
1298 return emitError(UnknownLoc::get(context))
1299 <<
"unhandled global variable: " << renderValue(globalVar);
1303 if (failed(convertGlobal(&globalVar))) {
1304 return emitError(UnknownLoc::get(context))
1305 <<
"unhandled global variable: " << renderValue(globalVar);
1312 for (llvm::GlobalAlias &alias : llvmModule->aliases()) {
1313 if (failed(convertAlias(&alias))) {
1314 return emitError(UnknownLoc::get(context))
1315 <<
"unhandled global alias: " << renderValue(alias);
1322 for (llvm::GlobalIFunc &ifunc : llvmModule->ifuncs()) {
1323 if (failed(convertIFunc(&ifunc))) {
1324 return emitError(UnknownLoc::get(context))
1325 <<
"unhandled global ifunc: " << renderValue(ifunc);
1332 Location loc = mlirModule.getLoc();
1334 context, llvmModule->getDataLayout().getStringRepresentation());
1336 return emitError(loc,
"cannot translate data layout: ")
1340 emitWarning(loc,
"unhandled data layout token: ") << token;
1342 mlirModule->setDiscardableAttr(DLTIDialect::kDataLayoutAttrName,
1348 mlirModule->setDiscardableAttr(
1349 LLVM::LLVMDialect::getTargetTripleAttrName(),
1350 builder.getStringAttr(llvmModule->getTargetTriple().str()));
1356 for (
const llvm::Module::GlobalAsmFragment &Frag :
1357 llvmModule->getModuleInlineAsm()) {
1359 for (llvm::StringRef line : llvm::split(Frag.Asm,
'\n'))
1361 asmArrayAttr.push_back(builder.getStringAttr(line));
1364 mlirModule->setDiscardableAttr(LLVM::LLVMDialect::getModuleLevelAsmAttrName(),
1365 builder.getArrayAttr(asmArrayAttr));
1369 for (llvm::Function &
func : llvmModule->functions())
1375void ModuleImport::setNonDebugMetadataAttrs(llvm::Instruction *inst,
1378 inst->getAllMetadataOtherThanDebugLoc(allMetadata);
1379 for (
auto &[kind, node] : allMetadata) {
1383 if (emitExpensiveWarnings) {
1384 Location loc = debugImporter->translateLoc(inst->getDebugLoc());
1385 emitWarning(loc) <<
"unhandled metadata: " << renderMetadata(node)
1386 <<
" on " << renderValue(*inst);
1394 auto iface = cast<IntegerOverflowFlagsInterface>(op);
1396 IntegerOverflowFlags value = {};
1397 value = bitEnumSet(value, IntegerOverflowFlags::nsw, inst->hasNoSignedWrap());
1399 bitEnumSet(value, IntegerOverflowFlags::nuw, inst->hasNoUnsignedWrap());
1401 iface.setOverflowFlags(value);
1405 auto iface = cast<ExactFlagInterface>(op);
1407 iface.setIsExact(inst->isExact());
1412 auto iface = cast<DisjointFlagInterface>(op);
1413 auto *instDisjoint = cast<llvm::PossiblyDisjointInst>(inst);
1415 iface.setIsDisjoint(instDisjoint->isDisjoint());
1419 auto iface = cast<NonNegFlagInterface>(op);
1421 iface.setNonNeg(inst->hasNonNeg());
1426 auto iface = cast<FastmathFlagsInterface>(op);
1432 if (!isa<llvm::FPMathOperator>(inst))
1434 llvm::FastMathFlags flags = inst->getFastMathFlags();
1437 FastmathFlags value = {};
1438 value = bitEnumSet(value, FastmathFlags::nnan, flags.noNaNs());
1439 value = bitEnumSet(value, FastmathFlags::ninf, flags.noInfs());
1440 value = bitEnumSet(value, FastmathFlags::nsz, flags.noSignedZeros());
1441 value = bitEnumSet(value, FastmathFlags::arcp, flags.allowReciprocal());
1442 value = bitEnumSet(value, FastmathFlags::contract, flags.allowContract());
1443 value = bitEnumSet(value, FastmathFlags::afn, flags.approxFunc());
1444 value = bitEnumSet(value, FastmathFlags::reassoc, flags.allowReassoc());
1445 FastmathFlagsAttr attr = FastmathFlagsAttr::get(builder.getContext(), value);
1446 iface.setFastmathAttr(attr);
1458 if (numElements.isScalable()) {
1460 <<
"scalable vectors not supported";
1465 Type elementType = cast<VectorType>(type).getElementType();
1469 SmallVector<int64_t> shape(arrayShape);
1470 shape.push_back(numElements.getKnownMinValue());
1471 return VectorType::get(shape, elementType);
1474Type ModuleImport::getBuiltinTypeForAttr(Type type) {
1488 SmallVector<int64_t> arrayShape;
1489 while (
auto arrayType = dyn_cast<LLVMArrayType>(type)) {
1490 arrayShape.push_back(arrayType.getNumElements());
1491 type = arrayType.getElementType();
1494 return RankedTensorType::get(arrayShape, type);
1501 llvm::Constant *constScalar) {
1504 if (constScalar->getType()->isVectorTy())
1508 if (
auto *constInt = dyn_cast<llvm::ConstantInt>(constScalar)) {
1510 IntegerType::get(context, constInt->getBitWidth()),
1511 constInt->getValue());
1515 if (
auto *constFloat = dyn_cast<llvm::ConstantFP>(constScalar)) {
1516 llvm::Type *type = constFloat->getType();
1517 FloatType floatType =
1519 ? BFloat16Type::get(context)
1523 <<
"unexpected floating-point type";
1526 return builder.
getFloatAttr(floatType, constFloat->getValueAPF());
1533static SmallVector<Attribute>
1535 llvm::ConstantDataSequential *constSequence) {
1537 elementAttrs.reserve(constSequence->getNumElements());
1538 for (
auto idx : llvm::seq<int64_t>(0, constSequence->getNumElements())) {
1539 llvm::Constant *constElement = constSequence->getElementAsConstant(idx);
1542 return elementAttrs;
1545Attribute ModuleImport::getConstantAsAttr(llvm::Constant *constant) {
1551 auto getConstantShape = [&](llvm::Type *type) {
1552 return llvm::dyn_cast_if_present<ShapedType>(
1557 if (isa<llvm::ConstantInt, llvm::ConstantFP>(constant)) {
1558 assert(constant->getType()->isVectorTy() &&
"expected a vector splat");
1559 auto shape = getConstantShape(constant->getType());
1562 Attribute splatAttr =
1569 if (
auto *constArray = dyn_cast<llvm::ConstantDataSequential>(constant)) {
1570 if (constArray->isString())
1571 return builder.getStringAttr(constArray->getAsString());
1572 auto shape = getConstantShape(constArray->getType());
1576 auto *constVector = dyn_cast<llvm::ConstantDataVector>(constant);
1577 if (constVector && constVector->isSplat()) {
1580 builder, constVector->getElementAsConstant(0));
1584 SmallVector<Attribute> elementAttrs =
1591 if (
auto *constAggregate = dyn_cast<llvm::ConstantAggregate>(constant)) {
1592 auto shape = getConstantShape(constAggregate->getType());
1596 SmallVector<Attribute> elementAttrs;
1597 SmallVector<llvm::Constant *> workList = {constAggregate};
1598 while (!workList.empty()) {
1599 llvm::Constant *current = workList.pop_back_val();
1602 if (
auto *constAggregate = dyn_cast<llvm::ConstantAggregate>(current)) {
1604 reverse(llvm::seq<int64_t>(0, constAggregate->getNumOperands())))
1605 workList.push_back(constAggregate->getAggregateElement(idx));
1610 if (
auto *constArray = dyn_cast<llvm::ConstantDataSequential>(current)) {
1611 SmallVector<Attribute> attrs =
1613 elementAttrs.append(attrs.begin(), attrs.end());
1619 elementAttrs.push_back(scalarAttr);
1630 if (
auto *constZero = dyn_cast<llvm::ConstantAggregateZero>(constant)) {
1631 auto shape = llvm::dyn_cast_if_present<ShapedType>(
1632 getBuiltinTypeForAttr(
convertType(constZero->getType())));
1636 Attribute splatAttr = builder.getZeroAttr(shape.getElementType());
1637 assert(splatAttr &&
"expected non-null zero attribute for scalar types");
1644ModuleImport::getOrCreateNamelessSymbolName(llvm::GlobalVariable *globalVar) {
1645 assert(globalVar->getName().empty() &&
1646 "expected to work with a nameless global");
1647 auto [it,
success] = namelessGlobals.try_emplace(globalVar);
1654 [
this](StringRef newName) {
return llvmModule->getNamedValue(newName); },
1657 it->getSecond() = symbolRef;
1661OpBuilder::InsertionGuard ModuleImport::setGlobalInsertionPoint() {
1662 OpBuilder::InsertionGuard guard(builder);
1663 if (globalInsertionOp)
1664 builder.setInsertionPointAfter(globalInsertionOp);
1666 builder.setInsertionPointToStart(mlirModule.getBody());
1670LogicalResult ModuleImport::convertAlias(llvm::GlobalAlias *alias) {
1672 OpBuilder::InsertionGuard guard = setGlobalInsertionPoint();
1675 AliasOp aliasOp = AliasOp::create(
1676 builder, mlirModule.getLoc(), type,
1677 convertLinkageFromLLVM(alias->getLinkage()), alias->getName(),
1678 alias->isDSOLocal(),
1679 convertThreadLocalModeFromLLVM(alias->getThreadLocalMode()),
1680 ArrayRef<NamedAttribute>());
1681 globalInsertionOp = aliasOp;
1684 Block *block = builder.createBlock(&aliasOp.getInitializerRegion());
1685 setConstantInsertionPointToStart(block);
1686 FailureOr<Value> initializer = convertConstantExpr(alias->getAliasee());
1689 ReturnOp::create(builder, aliasOp.getLoc(), *initializer);
1691 if (alias->hasAtLeastLocalUnnamedAddr())
1692 aliasOp.setUnnamedAddr(convertUnnamedAddrFromLLVM(alias->getUnnamedAddr()));
1693 aliasOp.setVisibility_(convertVisibilityFromLLVM(alias->getVisibility()));
1698LogicalResult ModuleImport::convertIFunc(llvm::GlobalIFunc *ifunc) {
1699 OpBuilder::InsertionGuard guard = setGlobalInsertionPoint();
1702 llvm::Constant *resolver = ifunc->getResolver();
1703 Type resolverType =
convertType(resolver->getType());
1704 IFuncOp::create(builder, mlirModule.getLoc(), ifunc->getName(), type,
1705 resolver->getName(), resolverType,
1706 convertLinkageFromLLVM(ifunc->getLinkage()),
1707 ifunc->isDSOLocal(), ifunc->getAddressSpace(),
1708 convertUnnamedAddrFromLLVM(ifunc->getUnnamedAddr()),
1709 convertVisibilityFromLLVM(ifunc->getVisibility()),
1720 ArrayRef<StringLiteral> attributePrefixesToSkip = {}) {
1721 SmallVector<Attribute> mlirAttributes;
1722 for (llvm::Attribute attr : attributes) {
1724 if (attr.isStringAttribute())
1725 attrName = attr.getKindAsString();
1727 attrName = llvm::Attribute::getNameFromAttrKind(attr.getKindAsEnum());
1728 if (llvm::is_contained(attributesToSkip, attrName))
1731 auto attrNameStartsWith = [attrName](StringLiteral sl) {
1732 return attrName.starts_with(sl);
1734 if (attributePrefixesToSkip.end() !=
1735 llvm::find_if(attributePrefixesToSkip, attrNameStartsWith))
1738 auto keyAttr = StringAttr::get(context, attrName);
1739 if (attr.isStringAttribute()) {
1740 StringRef val = attr.getValueAsString();
1743 mlirAttributes.push_back(keyAttr);
1747 mlirAttributes.push_back(
1748 ArrayAttr::get(context, {keyAttr, StringAttr::get(context, val)}));
1751 if (attr.isIntAttribute()) {
1754 auto val = std::to_string(attr.getValueAsInt());
1755 mlirAttributes.push_back(
1756 ArrayAttr::get(context, {keyAttr, StringAttr::get(context, val)}));
1759 if (attr.isEnumAttribute()) {
1761 mlirAttributes.push_back(keyAttr);
1767 <<
"' attribute is invalid on current operation, skipping it";
1769 return ArrayAttr::get(context, mlirAttributes);
1775 GlobalOp globalOp) {
1777 globalOp.getLoc(), globalOp.getContext(), globalVar->getAttributes());
1778 if (!targetSpecificAttrs.empty())
1779 globalOp.setTargetSpecificAttrsAttr(targetSpecificAttrs);
1782LogicalResult ModuleImport::convertGlobal(llvm::GlobalVariable *globalVar) {
1784 OpBuilder::InsertionGuard guard = setGlobalInsertionPoint();
1786 Attribute valueAttr;
1787 if (globalVar->hasInitializer())
1788 valueAttr = getConstantAsAttr(globalVar->getInitializer());
1789 Type type =
convertType(globalVar->getValueType());
1791 uint64_t alignment = 0;
1792 llvm::MaybeAlign maybeAlign = globalVar->getAlign();
1793 if (maybeAlign.has_value()) {
1794 llvm::Align align = *maybeAlign;
1795 alignment = align.value();
1800 SmallVector<Attribute> globalExpressionAttrs;
1801 SmallVector<llvm::DIGlobalVariableExpression *> globalExpressions;
1802 globalVar->getDebugInfo(globalExpressions);
1804 for (llvm::DIGlobalVariableExpression *expr : globalExpressions) {
1805 DIGlobalVariableExpressionAttr globalExpressionAttr =
1806 debugImporter->translateGlobalVariableExpression(expr);
1807 globalExpressionAttrs.push_back(globalExpressionAttr);
1812 StringRef globalName = globalVar->getName();
1813 if (globalName.empty())
1814 globalName = getOrCreateNamelessSymbolName(globalVar).getValue();
1816 GlobalOp globalOp = GlobalOp::create(
1817 builder, mlirModule.getLoc(), type, globalVar->isConstant(),
1818 convertLinkageFromLLVM(globalVar->getLinkage()), StringRef(globalName),
1819 valueAttr, alignment, globalVar->getAddressSpace(),
1820 globalVar->isDSOLocal(),
1821 convertThreadLocalModeFromLLVM(globalVar->getThreadLocalMode()),
1823 ArrayRef<NamedAttribute>(), globalExpressionAttrs);
1824 globalInsertionOp = globalOp;
1826 if (globalVar->hasInitializer() && !valueAttr) {
1828 Block *block = builder.createBlock(&globalOp.getInitializerRegion());
1829 setConstantInsertionPointToStart(block);
1830 FailureOr<Value> initializer =
1831 convertConstantExpr(globalVar->getInitializer());
1834 ReturnOp::create(builder, globalOp.getLoc(), *initializer);
1836 if (globalVar->hasAtLeastLocalUnnamedAddr()) {
1837 globalOp.setUnnamedAddr(
1838 convertUnnamedAddrFromLLVM(globalVar->getUnnamedAddr()));
1840 if (globalVar->hasSection())
1841 globalOp.setSection(globalVar->getSection());
1842 globalOp.setVisibility_(
1843 convertVisibilityFromLLVM(globalVar->getVisibility()));
1845 if (globalVar->hasComdat())
1846 globalOp.setComdatAttr(comdatMapping.lookup(globalVar->getComdat()));
1848 if (llvm::MDNode *associatedMD =
1849 globalVar->getMetadata(llvm::LLVMContext::MD_associated)) {
1850 FlatSymbolRefAttr symbolRef;
1851 if (associatedMD->getNumOperands() == 1)
1853 getMetadataOperandSymbolRef(associatedMD->getOperand(0).get());
1856 <<
"unhandled associated metadata: " << renderMetadata(associatedMD)
1857 <<
" on " << renderValue(*globalVar);
1859 globalOp.setAssociatedAttr(symbolRef);
1863 if (llvm::MDNode *absSymMD =
1864 globalVar->getMetadata(llvm::LLVMContext::MD_absolute_symbol)) {
1865 unsigned numOps = absSymMD->getNumOperands();
1866 if (numOps >= 2 && numOps % 2 == 0) {
1867 SmallVector<Attribute> rangeAttrs;
1868 rangeAttrs.reserve(numOps);
1870 for (
const llvm::MDOperand &op : absSymMD->operands()) {
1871 auto *constInt = llvm::mdconst::dyn_extract<llvm::ConstantInt>(op);
1875 auto intType = IntegerType::get(context, constInt->getBitWidth());
1876 rangeAttrs.push_back(IntegerAttr::get(intType, constInt->getValue()));
1879 if (rangeAttrs.size() == numOps)
1880 globalOp.setAbsoluteSymbolAttr(ArrayAttr::get(context, rangeAttrs));
1890ModuleImport::convertGlobalCtorsAndDtors(llvm::GlobalVariable *globalVar) {
1891 if (!globalVar->hasInitializer() || !globalVar->hasAppendingLinkage())
1893 llvm::Constant *initializer = globalVar->getInitializer();
1895 bool knownInit = isa<llvm::ConstantArray>(initializer) ||
1896 isa<llvm::ConstantAggregateZero>(initializer);
1903 if (
auto *caz = dyn_cast<llvm::ConstantAggregateZero>(initializer)) {
1904 if (caz->getElementCount().getFixedValue() != 0)
1908 SmallVector<Attribute> funcs;
1909 SmallVector<int32_t> priorities;
1910 SmallVector<Attribute> dataList;
1911 for (llvm::Value *operand : initializer->operands()) {
1912 auto *aggregate = dyn_cast<llvm::ConstantAggregate>(operand);
1913 if (!aggregate || aggregate->getNumOperands() != 3)
1916 auto *priority = dyn_cast<llvm::ConstantInt>(aggregate->getOperand(0));
1917 auto *func = dyn_cast<llvm::Function>(aggregate->getOperand(1));
1918 auto *data = dyn_cast<llvm::Constant>(aggregate->getOperand(2));
1919 if (!priority || !func || !data)
1922 auto *gv = dyn_cast_or_null<llvm::GlobalValue>(data);
1926 else if (data->isNullValue())
1927 dataAttr = ZeroAttr::get(context);
1932 priorities.push_back(priority->getValue().getZExtValue());
1933 dataList.push_back(dataAttr);
1937 OpBuilder::InsertionGuard guard = setGlobalInsertionPoint();
1940 globalInsertionOp = LLVM::GlobalCtorsOp::create(
1941 builder, mlirModule.getLoc(), builder.getArrayAttr(funcs),
1942 builder.getI32ArrayAttr(priorities), builder.getArrayAttr(dataList));
1945 globalInsertionOp = LLVM::GlobalDtorsOp::create(
1946 builder, mlirModule.getLoc(), builder.getArrayAttr(funcs),
1947 builder.getI32ArrayAttr(priorities), builder.getArrayAttr(dataList));
1952ModuleImport::getConstantsToConvert(llvm::Constant *constant) {
1954 if (valueMapping.contains(constant))
1963 workList.insert(constant);
1964 while (!workList.empty()) {
1965 llvm::Constant *current = workList.back();
1968 if (isa<llvm::GlobalObject>(current) || isa<llvm::GlobalAlias>(current)) {
1969 orderedSet.insert(current);
1970 workList.pop_back();
1976 auto [adjacencyIt,
inserted] = adjacencyLists.try_emplace(current);
1980 for (llvm::Value *operand : current->operands())
1981 if (
auto *constDependency = dyn_cast<llvm::Constant>(operand))
1982 adjacencyIt->getSecond().push_back(constDependency);
1985 if (
auto *constAgg = dyn_cast<llvm::ConstantAggregateZero>(current)) {
1986 unsigned numElements = constAgg->getElementCount().getFixedValue();
1987 for (
unsigned i = 0, e = numElements; i != e; ++i)
1988 adjacencyIt->getSecond().push_back(constAgg->getElementValue(i));
1994 if (adjacencyIt->getSecond().empty()) {
1995 orderedSet.insert(current);
1996 workList.pop_back();
2004 llvm::Constant *dependency = adjacencyIt->getSecond().pop_back_val();
2005 if (valueMapping.contains(dependency) || workList.contains(dependency) ||
2006 orderedSet.contains(dependency))
2008 workList.insert(dependency);
2014FailureOr<Value> ModuleImport::convertConstant(llvm::Constant *constant) {
2015 Location loc = UnknownLoc::get(context);
2018 if (Attribute attr = getConstantAsAttr(constant)) {
2020 if (
auto symbolRef = dyn_cast<FlatSymbolRefAttr>(attr)) {
2021 return AddressOfOp::create(builder, loc, type, symbolRef.
getValue())
2024 return ConstantOp::create(builder, loc, type, attr).getResult();
2028 if (
auto *nullPtr = dyn_cast<llvm::ConstantPointerNull>(constant)) {
2030 return ZeroOp::create(builder, loc, type).getResult();
2034 if (isa<llvm::ConstantTokenNone>(constant)) {
2035 return NoneTokenOp::create(builder, loc).getResult();
2039 if (
auto *poisonVal = dyn_cast<llvm::PoisonValue>(constant)) {
2041 return PoisonOp::create(builder, loc, type).getResult();
2045 if (
auto *undefVal = dyn_cast<llvm::UndefValue>(constant)) {
2047 return UndefOp::create(builder, loc, type).getResult();
2051 if (
auto *dsoLocalEquivalent = dyn_cast<llvm::DSOLocalEquivalent>(constant)) {
2052 Type type =
convertType(dsoLocalEquivalent->getType());
2053 return DSOLocalEquivalentOp::create(
2056 builder.getContext(),
2057 dsoLocalEquivalent->getGlobalValue()->getName()))
2062 if (
auto *globalObj = dyn_cast<llvm::GlobalObject>(constant)) {
2064 StringRef globalName = globalObj->getName();
2065 FlatSymbolRefAttr symbolRef;
2067 if (globalName.empty())
2069 getOrCreateNamelessSymbolName(cast<llvm::GlobalVariable>(globalObj));
2072 return AddressOfOp::create(builder, loc, type, symbolRef).getResult();
2076 if (
auto *globalAliasObj = dyn_cast<llvm::GlobalAlias>(constant)) {
2077 Type type =
convertType(globalAliasObj->getType());
2078 StringRef aliaseeName = globalAliasObj->getName();
2080 return AddressOfOp::create(builder, loc, type, symbolRef).getResult();
2084 if (
auto *constExpr = dyn_cast<llvm::ConstantExpr>(constant)) {
2090 llvm::Instruction *inst = constExpr->getAsInstruction();
2091 llvm::scope_exit guard([&]() {
2092 assert(!noResultOpMapping.contains(inst) &&
2093 "expected constant expression to return a result");
2094 valueMapping.erase(inst);
2095 inst->deleteValue();
2099 assert(llvm::all_of(inst->operands(), [&](llvm::Value *value) {
2100 return valueMapping.contains(value);
2102 if (
failed(processInstruction(inst)))
2107 if (constExpr->getOpcode() == llvm::Instruction::GetElementPtr) {
2108 auto *gepOperator = llvm::cast<llvm::GEPOperator>(constExpr);
2109 if (std::optional<llvm::ConstantRange> inRange =
2110 gepOperator->getInRange()) {
2111 auto gepOp =
result.getDefiningOp<GEPOp>();
2112 assert(gepOp &&
"expected GEPOp for getelementptr constexpr");
2116 unsigned indexWidth =
2117 llvmModule->getDataLayout().getIndexTypeSizeInBits(
2118 gepOperator->getPointerOperandType());
2119 gepOp.setInrangeAttr(LLVM::ConstantRangeAttr::get(
2120 context, inRange->getLower().sextOrTrunc(indexWidth),
2121 inRange->getUpper().sextOrTrunc(indexWidth)));
2128 if (
auto *aggregateZero = dyn_cast<llvm::ConstantAggregateZero>(constant)) {
2129 Type type =
convertType(aggregateZero->getType());
2130 return ZeroOp::create(builder, loc, type).getResult();
2134 if (
auto *constAgg = dyn_cast<llvm::ConstantAggregate>(constant)) {
2136 SmallVector<Value> elementValues;
2138 elementValues.reserve(constAgg->getNumOperands());
2139 for (llvm::Value *operand : constAgg->operands())
2142 assert(llvm::count(elementValues,
nullptr) == 0 &&
2143 "expected all elements have been converted before");
2147 bool isArrayOrStruct = isa<LLVMArrayType, LLVMStructType>(rootType);
2149 "unrecognized aggregate type");
2150 Value root = UndefOp::create(builder, loc, rootType);
2151 for (
const auto &it : llvm::enumerate(elementValues)) {
2152 if (isArrayOrStruct) {
2154 InsertValueOp::create(builder, loc, root, it.value(), it.index());
2156 Attribute indexAttr = builder.getI32IntegerAttr(it.index());
2158 ConstantOp::create(builder, loc, builder.getI32Type(), indexAttr);
2159 root = InsertElementOp::create(builder, loc, rootType, root, it.value(),
2166 if (
auto *constTargetNone = dyn_cast<llvm::ConstantTargetNone>(constant)) {
2167 LLVMTargetExtType targetExtType =
2168 cast<LLVMTargetExtType>(
convertType(constTargetNone->getType()));
2169 assert(targetExtType.hasProperty(LLVMTargetExtType::HasZeroInit) &&
2170 "target extension type does not support zero-initialization");
2173 return LLVM::ZeroOp::create(builder, loc, targetExtType).getRes();
2176 if (
auto *blockAddr = dyn_cast<llvm::BlockAddress>(constant)) {
2180 BlockTagAttr::get(context, blockAddr->getBasicBlock()->getNumber());
2181 return BlockAddressOp::create(
2183 BlockAddressAttr::get(context, fnSym, blockTag))
2187 StringRef error =
"";
2189 if (isa<llvm::ConstantPtrAuth>(constant))
2190 error =
" since ptrauth(...) is unsupported";
2192 if (isa<llvm::NoCFIValue>(constant))
2193 error =
" since no_cfi is unsupported";
2195 if (isa<llvm::GlobalValue>(constant))
2196 error =
" since global value is unsupported";
2198 return emitError(loc) <<
"unhandled constant: " << renderValue(*constant)
2202FailureOr<Value> ModuleImport::convertConstantExpr(llvm::Constant *constant) {
2206 assert(!valueMapping.contains(constant) &&
2207 "expected constant has not been converted before");
2208 assert(constantInsertionBlock &&
2209 "expected the constant insertion block to be non-null");
2212 OpBuilder::InsertionGuard guard(builder);
2213 if (!constantInsertionOp)
2214 builder.setInsertionPointToStart(constantInsertionBlock);
2216 builder.setInsertionPointAfter(constantInsertionOp);
2220 getConstantsToConvert(constant);
2221 for (llvm::Constant *constantToConvert : constantsToConvert) {
2222 FailureOr<Value> converted = convertConstant(constantToConvert);
2225 mapValue(constantToConvert, *converted);
2230 constantInsertionOp =
result.getDefiningOp();
2236 auto it = valueMapping.find(value);
2237 if (it != valueMapping.end())
2238 return it->getSecond();
2245 if (
auto *mdAsVal = dyn_cast<llvm::MetadataAsValue>(value)) {
2246 llvm::Metadata *md = mdAsVal->getMetadata();
2247 Attribute mdAttr = convertMetadataToAttr(md);
2250 <<
"unsupported metadata: " << renderMetadata(md);
2253 builder.setInsertionPointToStart(constantInsertionBlock);
2255 MetadataAsValueOp::create(builder, UnknownLoc::get(context), mdAttr)
2262 if (
auto *constant = dyn_cast<llvm::Constant>(value))
2263 return convertConstantExpr(constant);
2265 Location loc = UnknownLoc::get(context);
2266 if (
auto *inst = dyn_cast<llvm::Instruction>(value))
2268 return emitError(loc) <<
"unhandled value: " << renderValue(*value);
2274 auto *nodeAsVal = dyn_cast<llvm::MetadataAsValue>(value);
2277 auto *node = dyn_cast<llvm::ValueAsMetadata>(nodeAsVal->getMetadata());
2280 value = node->getValue();
2283 auto it = valueMapping.find(value);
2284 if (it != valueMapping.end())
2285 return it->getSecond();
2288 if (
auto *constant = dyn_cast<llvm::Constant>(value))
2289 return convertConstantExpr(constant);
2293FailureOr<SmallVector<Value>>
2296 remapped.reserve(values.size());
2297 for (llvm::Value *value : values) {
2299 if (failed(converted))
2301 remapped.push_back(*converted);
2306FailureOr<ModuleImport::OperandBundles>
2311 sizes.reserve(bundles.size());
2312 tags.reserve(bundles.size());
2313 for (
const llvm::OperandBundleUse &bundle : bundles) {
2315 convertValues(llvm::to_vector_of<llvm::Value *>(bundle.Inputs));
2316 if (failed(converted))
2318 llvm::append_range(operands, *converted);
2319 sizes.push_back(converted->size());
2322 return OperandBundles{std::move(operands),
2332 assert(immArgPositions.size() == immArgAttrNames.size() &&
2333 "LLVM `immArgPositions` and MLIR `immArgAttrNames` should have equal "
2337 for (
auto [immArgPos, immArgName] :
2338 llvm::zip(immArgPositions, immArgAttrNames)) {
2339 auto &value = operands[immArgPos];
2340 auto *constant = llvm::cast<llvm::Constant>(value);
2342 assert(attr && attr.getType().isIntOrFloat() &&
2343 "expected immarg to be float or integer constant");
2344 auto nameAttr = StringAttr::get(attr.getContext(), immArgName);
2345 attrsOut.push_back({nameAttr, attr});
2350 for (llvm::Value *value : operands) {
2354 if (failed(mlirValue))
2356 valuesOut.push_back(*mlirValue);
2359 if (requiresOpBundles) {
2360 FailureOr<OperandBundles> bundles = convertOperandBundles(opBundles);
2361 if (failed(bundles))
2363 llvm::append_range(valuesOut, bundles->operands);
2364 attrsOut.push_back(builder.getNamedAttr(
2365 LLVMDialect::getOpBundleSizesAttrName(), bundles->sizes));
2366 attrsOut.push_back(builder.getNamedAttr(
2367 LLVMDialect::getOpBundleTagsAttrName(), bundles->tags));
2374 IntegerAttr integerAttr;
2376 bool success = succeeded(converted) &&
2378 assert(
success &&
"expected a constant integer value");
2384 FloatAttr floatAttr;
2388 assert(
success &&
"expected a constant float value");
2395 llvm::DILocalVariable *node =
nullptr;
2396 if (
auto *value = dyn_cast<llvm::Value *>(valOrVariable)) {
2397 auto *nodeAsVal = cast<llvm::MetadataAsValue>(value);
2398 node = cast<llvm::DILocalVariable>(nodeAsVal->getMetadata());
2400 node = cast<llvm::DILocalVariable *>(valOrVariable);
2402 return debugImporter->translate(node);
2406 auto *nodeAsVal = cast<llvm::MetadataAsValue>(value);
2407 auto *node = cast<llvm::DILabel>(nodeAsVal->getMetadata());
2408 return debugImporter->translate(node);
2411FPExceptionBehaviorAttr
2413 auto *metadata = cast<llvm::MetadataAsValue>(value);
2414 auto *mdstr = cast<llvm::MDString>(metadata->getMetadata());
2415 std::optional<llvm::fp::ExceptionBehavior> optLLVM =
2416 llvm::convertStrToExceptionBehavior(mdstr->getString());
2417 assert(optLLVM &&
"Expecting FP exception behavior");
2418 return builder.getAttr<FPExceptionBehaviorAttr>(
2419 convertFPExceptionBehaviorFromLLVM(*optLLVM));
2423 auto *metadata = cast<llvm::MetadataAsValue>(value);
2424 auto *mdstr = cast<llvm::MDString>(metadata->getMetadata());
2425 std::optional<llvm::RoundingMode> optLLVM =
2426 llvm::convertStrToRoundingMode(mdstr->getString());
2427 assert(optLLVM &&
"Expecting rounding mode");
2428 return builder.getAttr<RoundingModeAttr>(
2429 convertRoundingModeFromLLVM(*optLLVM));
2432FailureOr<SmallVector<AliasScopeAttr>>
2434 auto *nodeAsVal = cast<llvm::MetadataAsValue>(value);
2435 auto *node = cast<llvm::MDNode>(nodeAsVal->getMetadata());
2440 return debugImporter->translateLoc(loc);
2444ModuleImport::convertBranchArgs(llvm::Instruction *branch,
2445 llvm::BasicBlock *
target,
2447 for (
auto inst =
target->begin(); isa<llvm::PHINode>(inst); ++inst) {
2448 auto *phiInst = cast<llvm::PHINode>(&*inst);
2449 llvm::Value *value = phiInst->getIncomingValueForBlock(branch->getParent());
2451 if (failed(converted))
2453 blockArguments.push_back(*converted);
2458FailureOr<SmallVector<Value>>
2459ModuleImport::convertCallOperands(llvm::CallBase *callInst,
2460 bool allowInlineAsm) {
2461 bool isInlineAsm = callInst->isInlineAsm();
2462 if (isInlineAsm && !allowInlineAsm)
2472 llvm::Value *calleeOperand = callInst->getCalledOperand();
2473 if (!isa<llvm::Function, llvm::GlobalIFunc>(calleeOperand) && !isInlineAsm) {
2477 operands.push_back(*called);
2480 SmallVector<llvm::Value *> args(callInst->args());
2481 FailureOr<SmallVector<Value>> arguments =
convertValues(args);
2485 llvm::append_range(operands, *arguments);
2493 LLVMFunctionType calleeType) {
2494 if (callType.getReturnType() != calleeType.getReturnType())
2497 if (calleeType.isVarArg()) {
2500 if (callType.getNumParams() < calleeType.getNumParams())
2505 if (callType.getNumParams() != calleeType.getNumParams())
2510 for (
auto [operandType, argumentType] :
2511 llvm::zip(callType.getParams(), calleeType.getParams()))
2512 if (operandType != argumentType)
2518FailureOr<LLVMFunctionType>
2519ModuleImport::convertFunctionType(llvm::CallBase *callInst,
2520 bool &isIncompatibleCall) {
2521 isIncompatibleCall =
false;
2522 auto castOrFailure = [](Type convertedType) -> FailureOr<LLVMFunctionType> {
2523 auto funcTy = dyn_cast_or_null<LLVMFunctionType>(convertedType);
2529 llvm::Value *calledOperand = callInst->getCalledOperand();
2530 FailureOr<LLVMFunctionType> callType =
2531 castOrFailure(
convertType(callInst->getFunctionType()));
2534 auto *callee = dyn_cast<llvm::Function>(calledOperand);
2536 llvm::FunctionType *origCalleeType =
nullptr;
2538 origCalleeType = callee->getFunctionType();
2539 }
else if (
auto *ifunc = dyn_cast<llvm::GlobalIFunc>(calledOperand)) {
2540 origCalleeType = cast<llvm::FunctionType>(ifunc->getValueType());
2544 if (!origCalleeType)
2547 FailureOr<LLVMFunctionType> calleeType =
2555 isIncompatibleCall =
true;
2557 emitWarning(loc) <<
"incompatible call and callee types: " << *callType
2558 <<
" and " << *calleeType;
2565FlatSymbolRefAttr ModuleImport::convertCalleeName(llvm::CallBase *callInst) {
2566 llvm::Value *calledOperand = callInst->getCalledOperand();
2567 if (isa<llvm::Function, llvm::GlobalIFunc>(calledOperand))
2568 return SymbolRefAttr::get(context, calledOperand->getName());
2572LogicalResult ModuleImport::convertIntrinsic(llvm::CallInst *inst) {
2573 if (succeeded(iface.convertIntrinsic(builder, inst, *
this)))
2577 return emitError(loc) <<
"unhandled intrinsic: " << renderValue(*inst);
2581ModuleImport::convertAsmInlineOperandAttrs(
const llvm::CallBase &llvmCall) {
2582 const auto *ia = cast<llvm::InlineAsm>(llvmCall.getCalledOperand());
2583 unsigned argIdx = 0;
2584 SmallVector<mlir::Attribute> opAttrs;
2585 bool hasIndirect =
false;
2587 for (
const llvm::InlineAsm::ConstraintInfo &ci : ia->ParseConstraints()) {
2589 if (ci.Type == llvm::InlineAsm::isLabel || !ci.hasArg())
2594 if (ci.isIndirect) {
2595 if (llvm::Type *paramEltType = llvmCall.getParamElementType(argIdx)) {
2596 SmallVector<mlir::NamedAttribute> attrs;
2597 attrs.push_back(builder.getNamedAttr(
2598 mlir::LLVM::InlineAsmOp::getElementTypeAttrName(),
2600 opAttrs.push_back(builder.getDictionaryAttr(attrs));
2604 opAttrs.push_back(builder.getDictionaryAttr({}));
2610 return hasIndirect ? ArrayAttr::get(mlirModule->getContext(), opAttrs)
2614LogicalResult ModuleImport::convertInstruction(llvm::Instruction *inst) {
2617 if (
auto *brInst = dyn_cast<llvm::UncondBrInst>(inst)) {
2618 llvm::BasicBlock *succ = brInst->getSuccessor();
2619 SmallVector<Value> blockArgs;
2620 if (
failed(convertBranchArgs(brInst, succ, blockArgs)))
2623 auto brOp = LLVM::BrOp::create(builder, loc, blockArgs,
lookupBlock(succ));
2627 if (
auto *brInst = dyn_cast<llvm::CondBrInst>(inst)) {
2628 SmallVector<Block *> succBlocks;
2629 SmallVector<SmallVector<Value>> succBlockArgs;
2630 for (
auto i : llvm::seq<unsigned>(0, brInst->getNumSuccessors())) {
2631 llvm::BasicBlock *succ = brInst->getSuccessor(i);
2632 SmallVector<Value> blockArgs;
2633 if (
failed(convertBranchArgs(brInst, succ, blockArgs)))
2636 succBlockArgs.push_back(blockArgs);
2639 FailureOr<Value> condition =
convertValue(brInst->getCondition());
2642 auto condBrOp = LLVM::CondBrOp::create(
2643 builder, loc, *condition, succBlocks.front(), succBlockArgs.front(),
2644 succBlocks.back(), succBlockArgs.back());
2648 if (inst->getOpcode() == llvm::Instruction::Switch) {
2649 auto *swInst = cast<llvm::SwitchInst>(inst);
2651 FailureOr<Value> condition =
convertValue(swInst->getCondition());
2654 SmallVector<Value> defaultBlockArgs;
2656 llvm::BasicBlock *defaultBB = swInst->getDefaultDest();
2657 if (
failed(convertBranchArgs(swInst, defaultBB, defaultBlockArgs)))
2661 unsigned numCases = swInst->getNumCases();
2662 SmallVector<SmallVector<Value>> caseOperands(numCases);
2663 SmallVector<ValueRange> caseOperandRefs(numCases);
2664 SmallVector<APInt> caseValues(numCases);
2665 SmallVector<Block *> caseBlocks(numCases);
2666 for (
const auto &it : llvm::enumerate(swInst->cases())) {
2667 const llvm::SwitchInst::CaseHandle &caseHandle = it.value();
2668 llvm::BasicBlock *succBB = caseHandle.getCaseSuccessor();
2669 if (
failed(convertBranchArgs(swInst, succBB, caseOperands[it.index()])))
2671 caseOperandRefs[it.index()] = caseOperands[it.index()];
2672 caseValues[it.index()] = caseHandle.getCaseValue()->getValue();
2676 auto switchOp = SwitchOp::create(builder, loc, *condition,
2678 caseValues, caseBlocks, caseOperandRefs);
2682 if (inst->getOpcode() == llvm::Instruction::PHI) {
2684 mapValue(inst, builder.getInsertionBlock()->addArgument(
2688 if (inst->getOpcode() == llvm::Instruction::Call) {
2689 auto *callInst = cast<llvm::CallInst>(inst);
2690 llvm::Value *calledOperand = callInst->getCalledOperand();
2692 FailureOr<SmallVector<Value>> operands =
2693 convertCallOperands(callInst,
true);
2697 auto callOp = [&]() -> FailureOr<Operation *> {
2698 if (
auto *asmI = dyn_cast<llvm::InlineAsm>(calledOperand)) {
2699 if (callInst->hasOperandBundles())
2700 emitWarning(loc,
"dropping operand bundles on inline assembly");
2704 ArrayAttr operandAttrs = convertAsmInlineOperandAttrs(*callInst);
2705 return InlineAsmOp::create(
2706 builder, loc, resultTy, *operands,
2707 builder.getStringAttr(asmI->getAsmString()),
2708 builder.getStringAttr(asmI->getConstraintString()),
2709 asmI->hasSideEffects(), asmI->isAlignStack(),
2710 convertTailCallKindFromLLVM(callInst->getTailCallKind()),
2711 callInst->hasFnAttr(llvm::Attribute::Convergent),
2712 AsmDialectAttr::get(
2713 mlirModule.getContext(),
2714 convertAsmDialectFromLLVM(asmI->getDialect())),
2716 callInst->getAttributes().hasFnAttr(
2717 llvm::Attribute::StrictFP))
2720 bool isIncompatibleCall;
2721 FailureOr<LLVMFunctionType> funcTy =
2722 convertFunctionType(callInst, isIncompatibleCall);
2726 FlatSymbolRefAttr callee =
nullptr;
2727 if (isIncompatibleCall) {
2731 FlatSymbolRefAttr calleeSym = convertCalleeName(callInst);
2732 Value indirectCallVal = LLVM::AddressOfOp::create(
2733 builder, loc, LLVM::LLVMPointerType::get(context), calleeSym);
2734 operands->insert(operands->begin(), indirectCallVal);
2737 callee = convertCalleeName(callInst);
2739 CallOp callOp = CallOp::create(builder, loc, *funcTy, callee, *operands);
2740 if (callInst->hasOperandBundles()) {
2741 FailureOr<OperandBundles> bundles =
2742 convertOperandBundles(llvm::to_vector(callInst->operand_bundles()));
2745 callOp.getOpBundleOperandsMutable().join().assign(bundles->operands);
2746 callOp.setOpBundleSizesAttr(bundles->sizes);
2747 callOp.setOpBundleTagsAttr(bundles->tags);
2750 if (
failed(convertCallAttributes(callInst, callOp)))
2755 if (!isIncompatibleCall)
2757 return callOp.getOperation();
2763 if (!callInst->getType()->isVoidTy())
2764 mapValue(inst, (*callOp)->getResult(0));
2769 if (inst->getOpcode() == llvm::Instruction::LandingPad) {
2770 auto *lpInst = cast<llvm::LandingPadInst>(inst);
2772 SmallVector<Value> operands;
2773 operands.reserve(lpInst->getNumClauses());
2774 for (
auto i : llvm::seq<unsigned>(0, lpInst->getNumClauses())) {
2775 FailureOr<Value> operand =
convertValue(lpInst->getClause(i));
2778 operands.push_back(*operand);
2783 LandingpadOp::create(builder, loc, type, lpInst->isCleanup(), operands);
2787 if (inst->getOpcode() == llvm::Instruction::Invoke) {
2788 auto *invokeInst = cast<llvm::InvokeInst>(inst);
2790 if (invokeInst->isInlineAsm())
2791 return emitError(loc) <<
"invoke of inline assembly is not supported";
2793 FailureOr<SmallVector<Value>> operands = convertCallOperands(invokeInst);
2799 bool invokeResultUsedInPhi = llvm::any_of(
2800 invokeInst->getNormalDest()->phis(), [&](
const llvm::PHINode &phi) {
2801 return phi.getIncomingValueForBlock(invokeInst->getParent()) ==
2806 Block *directNormalDest = normalDest;
2807 if (invokeResultUsedInPhi) {
2812 OpBuilder::InsertionGuard g(builder);
2813 directNormalDest = builder.createBlock(normalDest);
2816 SmallVector<Value> unwindArgs;
2817 if (
failed(convertBranchArgs(invokeInst, invokeInst->getUnwindDest(),
2821 bool isIncompatibleInvoke;
2822 FailureOr<LLVMFunctionType> funcTy =
2823 convertFunctionType(invokeInst, isIncompatibleInvoke);
2827 FlatSymbolRefAttr calleeName =
nullptr;
2828 if (isIncompatibleInvoke) {
2832 FlatSymbolRefAttr calleeSym = convertCalleeName(invokeInst);
2833 Value indirectInvokeVal = LLVM::AddressOfOp::create(
2834 builder, loc, LLVM::LLVMPointerType::get(context), calleeSym);
2835 operands->insert(operands->begin(), indirectInvokeVal);
2838 calleeName = convertCalleeName(invokeInst);
2843 auto invokeOp = InvokeOp::create(
2844 builder, loc, *funcTy, calleeName, *operands, directNormalDest,
2846 if (invokeInst->hasOperandBundles()) {
2847 FailureOr<OperandBundles> bundles =
2848 convertOperandBundles(llvm::to_vector(invokeInst->operand_bundles()));
2851 invokeOp.getOpBundleOperandsMutable().join().assign(bundles->operands);
2852 invokeOp.setOpBundleSizesAttr(bundles->sizes);
2853 invokeOp.setOpBundleTagsAttr(bundles->tags);
2856 if (
failed(convertInvokeAttributes(invokeInst, invokeOp)))
2861 if (!isIncompatibleInvoke)
2864 if (!invokeInst->getType()->isVoidTy())
2865 mapValue(inst, invokeOp.getResults().front());
2869 SmallVector<Value> normalArgs;
2870 if (
failed(convertBranchArgs(invokeInst, invokeInst->getNormalDest(),
2874 if (invokeResultUsedInPhi) {
2878 OpBuilder::InsertionGuard g(builder);
2879 builder.setInsertionPointToStart(directNormalDest);
2880 LLVM::BrOp::create(builder, loc, normalArgs, normalDest);
2884 assert(llvm::none_of(
2886 [&](Value val) {
return val.
getDefiningOp() == invokeOp; }) &&
2887 "An llvm.invoke operation cannot pass its result as a block "
2889 invokeOp.getNormalDestOperandsMutable().append(normalArgs);
2894 if (inst->getOpcode() == llvm::Instruction::GetElementPtr) {
2895 auto *gepInst = cast<llvm::GetElementPtrInst>(inst);
2896 Type sourceElementType =
convertType(gepInst->getSourceElementType());
2897 FailureOr<Value> basePtr =
convertValue(gepInst->getOperand(0));
2906 for (llvm::Value *operand : llvm::drop_begin(gepInst->operand_values())) {
2914 auto gepOp = GEPOp::create(
2915 builder, loc, type, sourceElementType, *basePtr,
indices,
2916 static_cast<GEPNoWrapFlags
>(gepInst->getNoWrapFlags().getRaw()));
2921 if (inst->getOpcode() == llvm::Instruction::IndirectBr) {
2922 auto *indBrInst = cast<llvm::IndirectBrInst>(inst);
2924 FailureOr<Value> basePtr =
convertValue(indBrInst->getAddress());
2928 SmallVector<Block *> succBlocks;
2929 SmallVector<SmallVector<Value>> succBlockArgs;
2930 for (
auto i : llvm::seq<unsigned>(0, indBrInst->getNumSuccessors())) {
2931 llvm::BasicBlock *succ = indBrInst->getSuccessor(i);
2932 SmallVector<Value> blockArgs;
2933 if (
failed(convertBranchArgs(indBrInst, succ, blockArgs)))
2936 succBlockArgs.push_back(blockArgs);
2938 SmallVector<ValueRange> succBlockArgsRange =
2939 llvm::to_vector_of<ValueRange>(succBlockArgs);
2941 auto indBrOp = LLVM::IndirectBrOp::create(builder, loc, *basePtr,
2942 succBlockArgsRange, succBlocks);
2952 return emitError(loc) <<
"unhandled instruction: " << renderValue(*inst);
2955LogicalResult ModuleImport::processInstruction(llvm::Instruction *inst) {
2962 if (
auto *intrinsic = dyn_cast<llvm::IntrinsicInst>(inst))
2963 return convertIntrinsic(intrinsic);
2968 if (inst->getDbgMarker()) {
2969 for (llvm::DbgRecord &dbgRecord :
2970 inst->getDbgMarker()->getDbgRecordRange()) {
2972 if (
auto *dbgVariableRecord =
2973 dyn_cast<llvm::DbgVariableRecord>(&dbgRecord)) {
2978 auto emitUnsupportedWarning = [&]() -> LogicalResult {
2979 if (!emitExpensiveWarnings)
2982 llvm::raw_string_ostream optionsStream(
options);
2983 dbgRecord.print(optionsStream);
2984 emitWarning(loc) <<
"unhandled debug record " << optionsStream.str();
2988 if (
auto *dbgLabelRecord = dyn_cast<llvm::DbgLabelRecord>(&dbgRecord)) {
2989 DILabelAttr labelAttr =
2990 debugImporter->translate(dbgLabelRecord->getLabel());
2992 return emitUnsupportedWarning();
2993 LLVM::DbgLabelOp::create(builder, loc, labelAttr);
2997 return emitUnsupportedWarning();
3002 return convertInstruction(inst);
3005FlatSymbolRefAttr ModuleImport::getPersonalityAsAttr(llvm::Function *f) {
3006 if (!f->hasPersonalityFn())
3009 llvm::Constant *pf = f->getPersonalityFn();
3013 return SymbolRefAttr::get(builder.getContext(), pf->getName());
3017 if (
auto *ce = dyn_cast<llvm::ConstantExpr>(pf)) {
3018 if (ce->getOpcode() == llvm::Instruction::BitCast &&
3019 ce->getType() == llvm::PointerType::getUnqual(f->getContext())) {
3020 if (
auto *func = dyn_cast<llvm::Function>(ce->getOperand(0)))
3021 return SymbolRefAttr::get(builder.getContext(), func->getName());
3024 return FlatSymbolRefAttr();
3028 llvm::MemoryEffects memEffects =
func->getMemoryEffects();
3030 auto othermem = convertModRefInfoFromLLVM(
3031 memEffects.getModRef(llvm::MemoryEffects::Location::Other));
3032 auto argMem = convertModRefInfoFromLLVM(
3033 memEffects.getModRef(llvm::MemoryEffects::Location::ArgMem));
3034 auto inaccessibleMem = convertModRefInfoFromLLVM(
3035 memEffects.getModRef(llvm::MemoryEffects::Location::InaccessibleMem));
3036 auto errnoMem = convertModRefInfoFromLLVM(
3037 memEffects.getModRef(llvm::MemoryEffects::Location::ErrnoMem));
3038 auto targetMem0 = convertModRefInfoFromLLVM(
3039 memEffects.getModRef(llvm::MemoryEffects::Location::TargetMem0));
3040 auto targetMem1 = convertModRefInfoFromLLVM(
3041 memEffects.getModRef(llvm::MemoryEffects::Location::TargetMem1));
3043 MemoryEffectsAttr::get(funcOp.getContext(), othermem, argMem,
3044 inaccessibleMem, errnoMem, targetMem0, targetMem1);
3046 if (memAttr.isReadWrite())
3048 funcOp.setMemoryEffectsAttr(memAttr);
3052 llvm::DenormalFPEnv denormalFpEnv =
func->getDenormalFPEnv();
3054 if (denormalFpEnv == llvm::DenormalFPEnv::getDefault())
3057 llvm::DenormalMode defaultMode = denormalFpEnv.DefaultMode;
3058 llvm::DenormalMode floatMode = denormalFpEnv.F32Mode;
3060 auto denormalFpEnvAttr = DenormalFPEnvAttr::get(
3061 funcOp.getContext(), convertDenormalModeKindFromLLVM(defaultMode.Output),
3062 convertDenormalModeKindFromLLVM(defaultMode.Input),
3063 convertDenormalModeKindFromLLVM(floatMode.Output),
3064 convertDenormalModeKindFromLLVM(floatMode.Input));
3065 funcOp.setDenormalFpenvAttr(denormalFpEnvAttr);
3071 StringLiteral(
"aarch64_in_za"),
3072 StringLiteral(
"aarch64_inout_za"),
3073 StringLiteral(
"aarch64_new_za"),
3074 StringLiteral(
"aarch64_out_za"),
3075 StringLiteral(
"aarch64_preserves_za"),
3076 StringLiteral(
"aarch64_pstate_sm_body"),
3077 StringLiteral(
"aarch64_pstate_sm_compatible"),
3078 StringLiteral(
"aarch64_pstate_sm_enabled"),
3079 StringLiteral(
"allocsize"),
3080 StringLiteral(
"alwaysinline"),
3081 StringLiteral(
"cold"),
3082 StringLiteral(
"convergent"),
3083 StringLiteral(
"disable-tail-calls"),
3084 StringLiteral(
"fp-contract"),
3085 StringLiteral(
"frame-pointer"),
3086 StringLiteral(
"hot"),
3087 StringLiteral(
"inlinehint"),
3088 StringLiteral(
"instrument-function-entry"),
3089 StringLiteral(
"instrument-function-exit"),
3090 StringLiteral(
"modular-format"),
3091 StringLiteral(
"memory"),
3092 StringLiteral(
"minsize"),
3093 StringLiteral(
"no_caller_saved_registers"),
3094 StringLiteral(
"no-signed-zeros-fp-math"),
3095 StringLiteral(
"no-builtins"),
3096 StringLiteral(
"nocallback"),
3097 StringLiteral(
"noduplicate"),
3098 StringLiteral(
"noinline"),
3099 StringLiteral(
"noreturn"),
3100 StringLiteral(
"nounwind"),
3101 StringLiteral(
"optnone"),
3102 StringLiteral(
"optsize"),
3103 StringLiteral(
"returns_twice"),
3104 StringLiteral(
"save-reg-params"),
3105 StringLiteral(
"strictfp"),
3106 StringLiteral(
"target-features"),
3107 StringLiteral(
"trap-func-name"),
3108 StringLiteral(
"sample-profile-suffix-elision-policy"),
3109 StringLiteral(
"tune-cpu"),
3110 StringLiteral(
"uniform-work-group-size"),
3111 StringLiteral(
"uwtable"),
3112 StringLiteral(
"vscale_range"),
3113 StringLiteral(
"willreturn"),
3114 StringLiteral(
"zero-call-used-regs"),
3115 StringLiteral(
"denormal_fpenv"),
3121 StringLiteral(
"no-builtin-"),
3124template <
typename OpTy>
3126 const llvm::AttributeSet &attrs,
3129 if (attrs.hasAttribute(
"no-builtins")) {
3130 target.setNobuiltinsAttr(ArrayAttr::get(ctx, {}));
3135 for (llvm::Attribute attr : attrs) {
3138 if (attr.hasKindAsEnum())
3141 StringRef val = attr.getKindAsString();
3143 if (val.starts_with(
"no-builtin-"))
3145 StringAttr::get(ctx, val.drop_front(
sizeof(
"no-builtin-") - 1)));
3148 if (!nbAttrs.empty())
3149 target.setNobuiltinsAttr(ArrayAttr::get(ctx, nbAttrs.getArrayRef()));
3152template <
typename OpTy>
3154 const llvm::AttributeSet &attrs, OpTy
target) {
3155 llvm::Attribute attr = attrs.getAttribute(llvm::Attribute::AllocSize);
3156 if (!attr.isValid())
3159 auto [elemSize, numElems] = attr.getAllocSizeArgs();
3163 static_cast<int32_t
>(*numElems)}));
3174 llvm::AttributeSet funcAttrs =
func->getAttributes().getAttributes(
3175 llvm::AttributeList::AttrIndex::FunctionIndex);
3177 funcOp.getLoc(), funcOp.getContext(), funcAttrs,
3179 if (!passthroughAttr.empty())
3180 funcOp.setPassthroughAttr(passthroughAttr);
3184 LLVMFuncOp funcOp) {
3189 if (
func->hasFnAttribute(llvm::Attribute::NoInline))
3190 funcOp.setNoInline(
true);
3191 if (
func->hasFnAttribute(llvm::Attribute::AlwaysInline))
3192 funcOp.setAlwaysInline(
true);
3193 if (
func->hasFnAttribute(llvm::Attribute::InlineHint))
3194 funcOp.setInlineHint(
true);
3195 if (
func->hasFnAttribute(llvm::Attribute::OptimizeNone))
3196 funcOp.setOptimizeNone(
true);
3197 if (
func->hasFnAttribute(llvm::Attribute::Convergent))
3198 funcOp.setConvergent(
true);
3199 if (
func->hasFnAttribute(llvm::Attribute::NoUnwind))
3200 funcOp.setNoUnwind(
true);
3201 if (
func->hasFnAttribute(llvm::Attribute::WillReturn))
3202 funcOp.setWillReturn(
true);
3203 if (
func->hasFnAttribute(llvm::Attribute::StrictFP))
3204 funcOp.setStrictfp(
true);
3205 if (
func->hasFnAttribute(llvm::Attribute::NoReturn))
3206 funcOp.setNoreturn(
true);
3207 if (
func->hasFnAttribute(llvm::Attribute::OptimizeForSize))
3208 funcOp.setOptsize(
true);
3209 if (
func->hasFnAttribute(
"save-reg-params"))
3210 funcOp.setSaveRegParams(
true);
3211 if (
func->hasFnAttribute(
"uniform-work-group-size"))
3212 funcOp.setUniformWorkGroupSize(
true);
3213 if (
func->hasFnAttribute(llvm::Attribute::MinSize))
3214 funcOp.setMinsize(
true);
3215 if (
func->hasFnAttribute(llvm::Attribute::ReturnsTwice))
3216 funcOp.setReturnsTwice(
true);
3217 if (
func->hasFnAttribute(llvm::Attribute::Cold))
3218 funcOp.setCold(
true);
3219 if (
func->hasFnAttribute(llvm::Attribute::Hot))
3220 funcOp.setHot(
true);
3221 if (
func->hasFnAttribute(llvm::Attribute::NoDuplicate))
3222 funcOp.setNoduplicate(
true);
3223 if (
func->hasFnAttribute(
"no_caller_saved_registers"))
3224 funcOp.setNoCallerSavedRegisters(
true);
3225 if (
func->hasFnAttribute(llvm::Attribute::NoCallback))
3226 funcOp.setNocallback(
true);
3227 if (llvm::Attribute attr =
func->getFnAttribute(
"modular-format");
3228 attr.isStringAttribute())
3229 funcOp.setModularFormat(StringAttr::get(context, attr.getValueAsString()));
3230 if (llvm::Attribute attr =
func->getFnAttribute(
"zero-call-used-regs");
3231 attr.isStringAttribute())
3232 funcOp.setZeroCallUsedRegsAttr(
3233 StringAttr::get(context, attr.getValueAsString()));
3235 if (
func->hasFnAttribute(
"aarch64_pstate_sm_enabled"))
3236 funcOp.setArmStreaming(
true);
3237 else if (
func->hasFnAttribute(
"aarch64_pstate_sm_body"))
3238 funcOp.setArmLocallyStreaming(
true);
3239 else if (
func->hasFnAttribute(
"aarch64_pstate_sm_compatible"))
3240 funcOp.setArmStreamingCompatible(
true);
3242 if (
func->hasFnAttribute(
"aarch64_new_za"))
3243 funcOp.setArmNewZa(
true);
3244 else if (
func->hasFnAttribute(
"aarch64_in_za"))
3245 funcOp.setArmInZa(
true);
3246 else if (
func->hasFnAttribute(
"aarch64_out_za"))
3247 funcOp.setArmOutZa(
true);
3248 else if (
func->hasFnAttribute(
"aarch64_inout_za"))
3249 funcOp.setArmInoutZa(
true);
3250 else if (
func->hasFnAttribute(
"aarch64_preserves_za"))
3251 funcOp.setArmPreservesZa(
true);
3256 llvm::Attribute attr =
func->getFnAttribute(llvm::Attribute::VScaleRange);
3257 if (attr.isValid()) {
3259 auto intTy = IntegerType::get(context, 32);
3260 funcOp.setVscaleRangeAttr(LLVM::VScaleRangeAttr::get(
3261 context, IntegerAttr::get(intTy, attr.getVScaleRangeMin()),
3262 IntegerAttr::get(intTy, attr.getVScaleRangeMax().value_or(0))));
3266 if (
func->hasFnAttribute(
"frame-pointer")) {
3267 StringRef stringRefFramePointerKind =
3268 func->getFnAttribute(
"frame-pointer").getValueAsString();
3269 funcOp.setFramePointerAttr(LLVM::FramePointerKindAttr::get(
3270 funcOp.getContext(), LLVM::framePointerKind::symbolizeFramePointerKind(
3271 stringRefFramePointerKind)
3275 if (
func->hasFnAttribute(
"use-sample-profile"))
3276 funcOp.setUseSampleProfile(
true);
3278 if (llvm::Attribute attr =
func->getFnAttribute(
"disable-tail-calls");
3279 attr.isStringAttribute()) {
3280 StringRef val = attr.getValueAsString();
3282 funcOp.setDisableTailCalls(
true);
3283 else if (val !=
"false")
3285 <<
"unknown value '" << val <<
"' for 'disable-tail-calls' attribute";
3288 if (llvm::Attribute attr =
3289 func->getFnAttribute(
"sample-profile-suffix-elision-policy");
3290 attr.isStringAttribute())
3291 funcOp.setSampleProfileSuffixElisionPolicy(
3292 StringAttr::get(context, attr.getValueAsString()));
3294 if (llvm::Attribute attr =
func->getFnAttribute(
"target-cpu");
3295 attr.isStringAttribute())
3296 funcOp.setTargetCpuAttr(StringAttr::get(context, attr.getValueAsString()));
3298 if (llvm::Attribute attr =
func->getFnAttribute(
"tune-cpu");
3299 attr.isStringAttribute())
3300 funcOp.setTuneCpuAttr(StringAttr::get(context, attr.getValueAsString()));
3302 if (llvm::Attribute attr =
func->getFnAttribute(
"target-features");
3303 attr.isStringAttribute())
3304 funcOp.setTargetFeaturesAttr(
3305 LLVM::TargetFeaturesAttr::get(context, attr.getValueAsString()));
3307 if (llvm::Attribute attr =
func->getFnAttribute(
"reciprocal-estimates");
3308 attr.isStringAttribute())
3309 funcOp.setReciprocalEstimatesAttr(
3310 StringAttr::get(context, attr.getValueAsString()));
3312 if (llvm::Attribute attr =
func->getFnAttribute(
"prefer-vector-width");
3313 attr.isStringAttribute())
3314 funcOp.setPreferVectorWidth(attr.getValueAsString());
3316 if (llvm::Attribute attr =
func->getFnAttribute(
"instrument-function-entry");
3317 attr.isStringAttribute())
3318 funcOp.setInstrumentFunctionEntry(
3319 StringAttr::get(context, attr.getValueAsString()));
3321 if (llvm::Attribute attr =
func->getFnAttribute(
"instrument-function-exit");
3322 attr.isStringAttribute())
3323 funcOp.setInstrumentFunctionExit(
3324 StringAttr::get(context, attr.getValueAsString()));
3326 if (llvm::Attribute attr =
func->getFnAttribute(
"no-signed-zeros-fp-math");
3327 attr.isStringAttribute())
3328 funcOp.setNoSignedZerosFpMath(attr.getValueAsBool());
3330 if (llvm::Attribute attr =
func->getFnAttribute(
"fp-contract");
3331 attr.isStringAttribute())
3332 funcOp.setFpContractAttr(StringAttr::get(context, attr.getValueAsString()));
3334 if (
func->hasUWTable()) {
3335 ::llvm::UWTableKind uwtableKind =
func->getUWTableKind();
3336 funcOp.setUwtableKindAttr(LLVM::UWTableKindAttr::get(
3337 funcOp.getContext(), convertUWTableKindFromLLVM(uwtableKind)));
3342ModuleImport::convertArgOrResultAttrSet(llvm::AttributeSet llvmAttrSet) {
3345 auto llvmAttr = llvmAttrSet.getAttribute(llvmKind);
3347 if (!llvmAttr.isValid())
3352 if (llvmAttr.hasKindAsEnum() &&
3353 llvmAttr.getKindAsEnum() == llvm::Attribute::Captures) {
3354 if (llvm::capturesNothing(llvmAttr.getCaptureInfo()))
3355 paramAttrs.push_back(
3361 if (llvmAttr.isTypeAttribute())
3362 mlirAttr = TypeAttr::get(
convertType(llvmAttr.getValueAsType()));
3363 else if (llvmAttr.isIntAttribute())
3365 else if (llvmAttr.isEnumAttribute())
3367 else if (llvmAttr.isConstantRangeAttribute()) {
3368 const llvm::ConstantRange &value = llvmAttr.getValueAsConstantRange();
3369 mlirAttr = builder.
getAttr<LLVM::ConstantRangeAttr>(value.getLower(),
3372 llvm_unreachable(
"unexpected parameter attribute kind");
3374 paramAttrs.push_back(builder.getNamedAttr(mlirName, mlirAttr));
3377 return builder.getDictionaryAttr(paramAttrs);
3381 LLVMFuncOp funcOp) {
3382 auto llvmAttrs = func->getAttributes();
3383 for (
size_t i = 0, e = funcOp.getNumArguments(); i < e; ++i) {
3384 llvm::AttributeSet llvmArgAttrs = llvmAttrs.getParamAttrs(i);
3385 funcOp.setArgAttrs(i, convertArgOrResultAttrSet(llvmArgAttrs));
3389 llvm::AttributeSet llvmResAttr = llvmAttrs.getRetAttrs();
3390 if (!llvmResAttr.hasAttributes())
3392 funcOp.setResAttrsAttr(
3393 builder.getArrayAttr({convertArgOrResultAttrSet(llvmResAttr)}));
3397 llvm::CallBase *call, ArgAndResultAttrsOpInterface attrsOp,
3400 llvm::SmallDenseSet<unsigned> immArgPositionsSet(immArgPositions.begin(),
3401 immArgPositions.end());
3403 llvm::AttributeList llvmAttrs = call->getAttributes();
3405 bool anyArgAttrs =
false;
3406 for (
size_t i = 0, e = call->arg_size(); i < e; ++i) {
3408 if (immArgPositionsSet.contains(i))
3410 llvmArgAttrsSet.emplace_back(llvmAttrs.getParamAttrs(i));
3411 if (llvmArgAttrsSet.back().hasAttributes())
3416 for (
auto &dict : dictAttrs)
3417 attrs.push_back(dict ? dict : builder.getDictionaryAttr({}));
3418 return builder.getArrayAttr(attrs);
3422 for (
auto &llvmArgAttrs : llvmArgAttrsSet)
3423 argAttrs.emplace_back(convertArgOrResultAttrSet(llvmArgAttrs));
3424 attrsOp.setArgAttrsAttr(getArrayAttr(argAttrs));
3428 llvm::AttributeSet llvmResAttr = llvmAttrs.getRetAttrs();
3429 if (!llvmResAttr.hasAttributes())
3431 DictionaryAttr resAttrs = convertArgOrResultAttrSet(llvmResAttr);
3432 attrsOp.setResAttrsAttr(getArrayAttr({resAttrs}));
3435template <
typename Op>
3437 op.setCConv(convertCConvFromLLVM(inst->getCallingConv()));
3438 op.setStrictfp(inst->getAttributes().hasFnAttr(llvm::Attribute::StrictFP));
3442LogicalResult ModuleImport::convertInvokeAttributes(llvm::InvokeInst *inst,
3444 llvm::AttributeList invokeAttrs = inst->getAttributes();
3445 op.setUniformWorkGroupSize(
3446 invokeAttrs.getFnAttr(
"uniform-work-group-size").isValid());
3450LogicalResult ModuleImport::convertCallAttributes(llvm::CallInst *inst,
3456 llvm::AttributeList callAttrs = inst->getAttributes();
3458 op.setTailCallKind(convertTailCallKindFromLLVM(inst->getTailCallKind()));
3459 op.setConvergent(callAttrs.getFnAttr(llvm::Attribute::Convergent).isValid());
3460 op.setNoUnwind(callAttrs.getFnAttr(llvm::Attribute::NoUnwind).isValid());
3461 op.setWillReturn(callAttrs.getFnAttr(llvm::Attribute::WillReturn).isValid());
3462 op.setNoreturn(callAttrs.getFnAttr(llvm::Attribute::NoReturn).isValid());
3464 callAttrs.getFnAttr(llvm::Attribute::OptimizeForSize).isValid());
3465 op.setSaveRegParams(callAttrs.getFnAttr(
"save-reg-params").isValid());
3466 op.setUniformWorkGroupSize(
3467 callAttrs.getFnAttr(
"uniform-work-group-size").isValid());
3468 op.setBuiltin(callAttrs.getFnAttr(llvm::Attribute::Builtin).isValid());
3469 op.setNobuiltin(callAttrs.getFnAttr(llvm::Attribute::NoBuiltin).isValid());
3470 op.setMinsize(callAttrs.getFnAttr(llvm::Attribute::MinSize).isValid());
3473 callAttrs.getFnAttr(llvm::Attribute::ReturnsTwice).isValid());
3474 op.setHot(callAttrs.getFnAttr(llvm::Attribute::Hot).isValid());
3475 op.setCold(callAttrs.getFnAttr(llvm::Attribute::Cold).isValid());
3477 callAttrs.getFnAttr(llvm::Attribute::NoDuplicate).isValid());
3478 op.setNoCallerSavedRegisters(
3479 callAttrs.getFnAttr(
"no_caller_saved_registers").isValid());
3480 op.setNocallback(callAttrs.getFnAttr(llvm::Attribute::NoCallback).isValid());
3482 if (llvm::Attribute attr = callAttrs.getFnAttr(
"modular-format");
3483 attr.isStringAttribute())
3484 op.setModularFormat(StringAttr::get(context, attr.getValueAsString()));
3485 if (llvm::Attribute attr = callAttrs.getFnAttr(
"zero-call-used-regs");
3486 attr.isStringAttribute())
3487 op.setZeroCallUsedRegsAttr(
3488 StringAttr::get(context, attr.getValueAsString()));
3489 if (llvm::Attribute attr = callAttrs.getFnAttr(
"trap-func-name");
3490 attr.isStringAttribute())
3491 op.setTrapFuncNameAttr(StringAttr::get(context, attr.getValueAsString()));
3492 op.setNoInline(callAttrs.getFnAttr(llvm::Attribute::NoInline).isValid());
3494 callAttrs.getFnAttr(llvm::Attribute::AlwaysInline).isValid());
3495 op.setInlineHint(callAttrs.getFnAttr(llvm::Attribute::InlineHint).isValid());
3497 llvm::MemoryEffects memEffects = inst->getMemoryEffects();
3498 ModRefInfo othermem = convertModRefInfoFromLLVM(
3499 memEffects.getModRef(llvm::MemoryEffects::Location::Other));
3500 ModRefInfo argMem = convertModRefInfoFromLLVM(
3501 memEffects.getModRef(llvm::MemoryEffects::Location::ArgMem));
3502 ModRefInfo inaccessibleMem = convertModRefInfoFromLLVM(
3503 memEffects.getModRef(llvm::MemoryEffects::Location::InaccessibleMem));
3504 ModRefInfo errnoMem = convertModRefInfoFromLLVM(
3505 memEffects.getModRef(llvm::MemoryEffects::Location::ErrnoMem));
3506 ModRefInfo targetMem0 = convertModRefInfoFromLLVM(
3507 memEffects.getModRef(llvm::MemoryEffects::Location::TargetMem0));
3508 ModRefInfo targetMem1 = convertModRefInfoFromLLVM(
3509 memEffects.getModRef(llvm::MemoryEffects::Location::TargetMem1));
3511 MemoryEffectsAttr::get(op.getContext(), othermem, argMem, inaccessibleMem,
3512 errnoMem, targetMem0, targetMem1);
3514 if (!memAttr.isReadWrite())
3515 op.setMemoryEffectsAttr(memAttr);
3528 if (
func->isIntrinsic() &&
3529 iface.isConvertibleIntrinsic(
func->getIntrinsicID()))
3532 bool dsoLocal =
func->isDSOLocal();
3533 CConv cconv = convertCConvFromLLVM(
func->getCallingConv());
3537 builder.setInsertionPointToEnd(mlirModule.getBody());
3539 Location loc = debugImporter->translateFuncLocation(
func);
3540 LLVMFuncOp funcOp = LLVMFuncOp::create(
3541 builder, loc,
func->getName(), functionType,
3542 convertLinkageFromLLVM(
func->getLinkage()), dsoLocal, cconv);
3547 funcOp.setPersonalityAttr(personality);
3548 else if (
func->hasPersonalityFn())
3549 emitWarning(funcOp.getLoc(),
"could not deduce personality, skipping it");
3552 funcOp.setGarbageCollector(StringRef(
func->getGC()));
3554 if (
func->hasAtLeastLocalUnnamedAddr())
3555 funcOp.setUnnamedAddr(convertUnnamedAddrFromLLVM(
func->getUnnamedAddr()));
3557 if (
func->hasSection())
3558 funcOp.setSection(StringRef(
func->getSection()));
3560 funcOp.setVisibility_(convertVisibilityFromLLVM(
func->getVisibility()));
3562 if (
func->hasComdat())
3563 funcOp.setComdatAttr(comdatMapping.lookup(
func->getComdat()));
3565 if (llvm::MaybeAlign maybeAlign =
func->getAlign())
3566 funcOp.setAlignment(maybeAlign->value());
3575 func->getAllMetadata(allMetadata);
3577 llvmModule->getMDKindNames(metadataNames);
3579 for (
auto &[kind, node] : allMetadata) {
3580 if (kind == llvm::LLVMContext::MD_dbg)
3583 llvm::MDNode *metadataNode = node;
3584 auto emitUnhandledFunctionMetadataWarning = [&]() {
3585 if (!emitExpensiveWarnings)
3588 <<
"unhandled function metadata: " << renderMetadata(metadataNode)
3589 <<
" on " << renderValue(*
func);
3592 if (iface.isConvertibleMetadata(kind)) {
3593 if (succeeded(iface.setMetadataAttrs(builder, kind, metadataNode, funcOp,
3596 emitUnhandledFunctionMetadataWarning();
3600 Attribute nodeAttr = convertMetadataToAttr(metadataNode);
3601 auto mdNodeAttr = dyn_cast_if_present<LLVM::MDNodeAttr>(nodeAttr);
3602 if (!mdNodeAttr || kind >= metadataNames.size()) {
3603 emitUnhandledFunctionMetadataWarning();
3607 functionMetadata.push_back(LLVM::FunctionMetadataAttr::get(
3608 context, builder.getStringAttr(metadataNames[kind]), mdNodeAttr));
3610 if (!functionMetadata.empty())
3611 funcOp.setFunctionMetadataAttr(builder.getArrayAttr(functionMetadata));
3613 if (
func->isDeclaration())
3622 llvm::df_iterator_default_set<llvm::BasicBlock *> reachable;
3623 for (llvm::BasicBlock *basicBlock : llvm::depth_first_ext(
func, reachable))
3628 for (llvm::BasicBlock &basicBlock : *
func) {
3630 if (!reachable.contains(&basicBlock)) {
3631 if (basicBlock.hasAddressTaken())
3633 <<
"unreachable block '" << basicBlock.getName()
3634 <<
"' with address taken";
3637 Region &body = funcOp.getBody();
3638 Block *block = builder.createBlock(&body, body.
end());
3640 reachableBasicBlocks.push_back(&basicBlock);
3644 for (
const auto &it : llvm::enumerate(
func->args())) {
3645 BlockArgument blockArg = funcOp.getFunctionBody().addArgument(
3646 functionType.getParamType(it.index()), funcOp.getLoc());
3655 setConstantInsertionPointToStart(
lookupBlock(blocks.front()));
3656 for (llvm::BasicBlock *basicBlock : blocks)
3657 if (failed(processBasicBlock(basicBlock,
lookupBlock(basicBlock))))
3662 if (failed(processDebugIntrinsics()))
3667 if (failed(processDebugRecords()))
3676 if (!dbgIntr->isKillLocation())
3678 llvm::Value *value = dbgIntr->getArgOperand(0);
3679 auto *nodeAsVal = dyn_cast<llvm::MetadataAsValue>(value);
3682 return !isa<llvm::ValueAsMetadata>(nodeAsVal->getMetadata());
3694 auto dominatedBlocks = domInfo.
getNode(op->getBlock())->children();
3697 if (dominatedBlocks.empty())
3701 Block *dominatedBlock = (*dominatedBlocks.begin())->getBlock();
3704 Value insertPt = argOperand;
3705 if (
auto blockArg = dyn_cast<BlockArgument>(argOperand)) {
3711 if (!insertionBlock->
empty() &&
3712 isa<LandingpadOp>(insertionBlock->
front()))
3713 insertPt = cast<LandingpadOp>(insertionBlock->
front()).getRes();
3721std::tuple<DILocalVariableAttr, DIExpressionAttr, Value>
3722ModuleImport::processDebugOpArgumentsAndInsertionPt(
3724 llvm::function_ref<FailureOr<Value>()> convertArgOperandToValue,
3725 llvm::Value *address,
3726 llvm::PointerUnion<llvm::Value *, llvm::DILocalVariable *> variable,
3727 llvm::DIExpression *expression, DominanceInfo &domInfo) {
3733 FailureOr<Value> argOperand = convertArgOperandToValue();
3734 if (
failed(argOperand)) {
3735 emitError(loc) <<
"failed to convert a debug operand: "
3736 << renderValue(*address);
3744 return {localVarAttr, debugImporter->translateExpression(expression),
3749ModuleImport::processDebugIntrinsic(llvm::DbgVariableIntrinsic *dbgIntr,
3750 DominanceInfo &domInfo) {
3752 auto emitUnsupportedWarning = [&]() {
3753 if (emitExpensiveWarnings)
3754 emitWarning(loc) <<
"dropped intrinsic: " << renderValue(*dbgIntr);
3758 OpBuilder::InsertionGuard guard(builder);
3759 auto convertArgOperandToValue = [&]() {
3765 if (dbgIntr->hasArgList())
3766 return emitUnsupportedWarning();
3773 return emitUnsupportedWarning();
3775 auto [localVariableAttr, locationExprAttr, locVal] =
3776 processDebugOpArgumentsAndInsertionPt(
3777 loc, convertArgOperandToValue, dbgIntr->getArgOperand(0),
3778 dbgIntr->getArgOperand(1), dbgIntr->getExpression(), domInfo);
3780 if (!localVariableAttr)
3781 return emitUnsupportedWarning();
3786 Operation *op =
nullptr;
3787 if (isa<llvm::DbgDeclareInst>(dbgIntr))
3788 op = LLVM::DbgDeclareOp::create(builder, loc, locVal, localVariableAttr,
3790 else if (isa<llvm::DbgValueInst>(dbgIntr))
3791 op = LLVM::DbgValueOp::create(builder, loc, locVal, localVariableAttr,
3794 return emitUnsupportedWarning();
3797 setNonDebugMetadataAttrs(dbgIntr, op);
3802ModuleImport::processDebugRecord(llvm::DbgVariableRecord &dbgRecord,
3803 DominanceInfo &domInfo) {
3804 OpBuilder::InsertionGuard guard(builder);
3806 auto emitUnsupportedWarning = [&]() -> LogicalResult {
3807 if (!emitExpensiveWarnings)
3810 llvm::raw_string_ostream optionsStream(
options);
3811 dbgRecord.print(optionsStream);
3812 emitWarning(loc) <<
"unhandled debug variable record "
3813 << optionsStream.str();
3819 if (dbgRecord.hasArgList())
3820 return emitUnsupportedWarning();
3825 if (!dbgRecord.getAddress())
3826 return emitUnsupportedWarning();
3828 auto convertArgOperandToValue = [&]() -> FailureOr<Value> {
3829 llvm::Value *value = dbgRecord.getAddress();
3832 auto it = valueMapping.find(value);
3833 if (it != valueMapping.end())
3834 return it->getSecond();
3837 if (
auto *constant = dyn_cast<llvm::Constant>(value))
3838 return convertConstantExpr(constant);
3842 auto [localVariableAttr, locationExprAttr, locVal] =
3843 processDebugOpArgumentsAndInsertionPt(
3844 loc, convertArgOperandToValue, dbgRecord.getAddress(),
3845 dbgRecord.getVariable(), dbgRecord.getExpression(), domInfo);
3847 if (!localVariableAttr)
3848 return emitUnsupportedWarning();
3853 if (dbgRecord.isDbgDeclare())
3854 LLVM::DbgDeclareOp::create(builder, loc, locVal, localVariableAttr,
3856 else if (dbgRecord.isDbgValue())
3857 LLVM::DbgValueOp::create(builder, loc, locVal, localVariableAttr,
3860 return emitUnsupportedWarning();
3865LogicalResult ModuleImport::processDebugIntrinsics() {
3866 DominanceInfo domInfo;
3867 for (llvm::Instruction *inst : debugIntrinsics) {
3868 auto *intrCall = cast<llvm::DbgVariableIntrinsic>(inst);
3869 if (
failed(processDebugIntrinsic(intrCall, domInfo)))
3875LogicalResult ModuleImport::processDebugRecords() {
3876 DominanceInfo domInfo;
3877 for (llvm::DbgVariableRecord *dbgRecord : dbgRecords)
3878 if (
failed(processDebugRecord(*dbgRecord, domInfo)))
3884LogicalResult ModuleImport::processBasicBlock(llvm::BasicBlock *bb,
3886 builder.setInsertionPointToStart(block);
3887 for (llvm::Instruction &inst : *bb) {
3888 if (
failed(processInstruction(&inst)))
3893 if (debugIntrinsics.contains(&inst))
3900 setNonDebugMetadataAttrs(&inst, op);
3901 }
else if (inst.getOpcode() != llvm::Instruction::PHI) {
3902 if (emitExpensiveWarnings) {
3903 Location loc = debugImporter->translateLoc(inst.getDebugLoc());
3904 emitWarning(loc) <<
"dropped instruction: " << renderValue(inst);
3909 if (bb->hasAddressTaken()) {
3910 OpBuilder::InsertionGuard guard(builder);
3911 builder.setInsertionPointToStart(block);
3913 BlockTagAttr::get(context, bb->getNumber()));
3918FailureOr<SmallVector<AccessGroupAttr>>
3920 return loopAnnotationImporter->lookupAccessGroupAttrs(node);
3926 return loopAnnotationImporter->translateLoopAnnotation(node, loc);
3929FailureOr<DereferenceableAttr>
3932 Location loc = mlirModule.getLoc();
3936 if (node->getNumOperands() != 1)
3937 return emitError(loc) <<
"dereferenceable metadata must have one operand: "
3938 << renderMetadata(node);
3940 auto *numBytesMD = dyn_cast<llvm::ConstantAsMetadata>(node->getOperand(0));
3941 auto *numBytesCst = dyn_cast<llvm::ConstantInt>(numBytesMD->getValue());
3942 if (!numBytesCst || !numBytesCst->getValue().isNonNegative())
3943 return emitError(loc) <<
"dereferenceable metadata operand must be a "
3944 "non-negative constant integer: "
3945 << renderMetadata(node);
3947 bool mayBeNull = kindID == llvm::LLVMContext::MD_dereferenceable_or_null;
3948 auto derefAttr = builder.getAttr<DereferenceableAttr>(
3949 numBytesCst->getZExtValue(), mayBeNull);
3955 std::unique_ptr<llvm::Module> llvmModule,
MLIRContext *context,
3956 bool emitExpensiveWarnings,
bool dropDICompositeTypeElements,
3957 bool loadAllDialects,
bool preferUnregisteredIntrinsics,
3958 bool importStructsAsLiterals) {
3965 LLVMDialect::getDialectNamespace()));
3967 DLTIDialect::getDialectNamespace()));
3968 if (loadAllDialects)
3971 StringAttr::get(context, llvmModule->getSourceFileName()), 0,
3975 emitExpensiveWarnings, dropDICompositeTypeElements,
3976 preferUnregisteredIntrinsics,
3977 importStructsAsLiterals);
return MutableOperandRange * this
*if copies could not be generated due to yet unimplemented cases *copyInPlacementStart and copyOutPlacementStart in copyPlacementBlock *specify the insertion points where the incoming copies and outgoing should be inserted(the insertion happens right before the *insertion point). Since `begin` can itself be invalidated due to the memref *rewriting done from this method
static ArrayAttr convertLLVMAttributesToMLIR(Location loc, MLIRContext *context, llvm::AttributeSet attributes, ArrayRef< StringLiteral > attributesToSkip={}, ArrayRef< StringLiteral > attributePrefixesToSkip={})
Converts LLVM string, integer, and enum attributes into MLIR attributes, skipping those in attributes...
static StringRef getLLVMSyncScope(llvm::Instruction *inst)
Converts the sync scope identifier of inst to the string representation necessary to build an atomic ...
static void processPassthroughAttrs(llvm::Function *func, LLVMFuncOp funcOp)
Converts LLVM attributes from func into MLIR attributes and adds them to funcOp as passthrough attrib...
static constexpr size_t kMaxDiagLength
Upper bound on the characters a diagnostic renders for an LLVM entity.
static SmallVector< Attribute > getSequenceConstantAsAttrs(OpBuilder &builder, llvm::ConstantDataSequential *constSequence)
Returns an integer or float attribute array for the provided constant sequence constSequence or nullp...
static LogicalResult convertCallBaseAttributes(llvm::CallBase *inst, Op op)
static void processMemoryEffects(llvm::Function *func, LLVMFuncOp funcOp)
static Attribute convertCGProfileModuleFlagValue(ModuleOp mlirModule, llvm::MDTuple *mdTuple)
static FailureOr< uint64_t > convertInt64FromKeyValueTuple(ModuleOp mlirModule, const llvm::Module *llvmModule, const llvm::MDOperand &md, StringRef matchKey, llvm::ModuleSlotTracker &tracker)
Extract an integer value from a two element tuple (<key, value>).
static constexpr std::array kExplicitLLVMFuncOpAttributePrefixes
static llvm::ConstantAsMetadata * getConstantMDFromKeyValueTuple(ModuleOp mlirModule, const llvm::Module *llvmModule, const llvm::MDOperand &md, StringRef matchKey, llvm::ModuleSlotTracker &tracker, bool optional=false)
Extract a constant metadata value from a two element tuple (<key, value>).
static constexpr StringRef getGlobalDtorsVarName()
Returns the name of the global_dtors global variables.
static Type getVectorTypeForAttr(Type type, ArrayRef< int64_t > arrayShape={})
Returns type if it is a builtin integer or floating-point vector type that can be used to create an a...
static LogicalResult convertInstructionImpl(OpBuilder &odsBuilder, llvm::Instruction *inst, ModuleImport &moduleImport, LLVMImportInterface &iface)
Converts the LLVM instructions that have a generated MLIR builder.
static constexpr StringRef getNamelessGlobalPrefix()
Prefix used for symbols of nameless llvm globals.
static constexpr std::array kExplicitLLVMFuncOpAttributes
static constexpr StringRef getGlobalComdatOpName()
Returns the symbol name for the module-level comdat operation.
static std::optional< ProfileSummaryFormatKind > convertProfileSummaryFormat(ModuleOp mlirModule, const llvm::Module *llvmModule, const llvm::MDOperand &formatMD, llvm::ModuleSlotTracker &tracker)
static void convertNoBuiltinAttrs(MLIRContext *ctx, const llvm::AttributeSet &attrs, OpTy target)
static SmallVector< int64_t > getPositionFromIndices(ArrayRef< unsigned > indices)
Converts an array of unsigned indices to a signed integer position array.
static LogicalResult setDebugIntrinsicBuilderInsertionPoint(mlir::OpBuilder &builder, DominanceInfo &domInfo, Value argOperand)
Ensure that the debug intrinsic is inserted right after the operand definition.
static LogicalResult checkFunctionTypeCompatibility(LLVMFunctionType callType, LLVMFunctionType calleeType)
Checks if callType and calleeType are compatible and can be represented in MLIR.
static void processDenormalFPEnv(llvm::Function *func, LLVMFuncOp funcOp)
static constexpr StringRef getGlobalCtorsVarName()
Returns the name of the global_ctors global variables.
static void processTargetSpecificAttrs(llvm::GlobalVariable *globalVar, GlobalOp globalOp)
Converts LLVM attributes from globalVar into MLIR attributes and adds them to globalOp as target-spec...
static llvm::MDTuple * getTwoElementMDTuple(ModuleOp mlirModule, const llvm::Module *llvmModule, const llvm::MDOperand &md, llvm::ModuleSlotTracker &tracker)
Extract a two element MDTuple from a MDOperand.
static bool isMetadataKillLocation(llvm::DbgVariableIntrinsic *dbgIntr)
Checks if dbgIntr is a kill location that holds metadata instead of an SSA value.
static TypedAttr getScalarConstantAsAttr(OpBuilder &builder, llvm::Constant *constScalar)
Returns an integer or float attribute for the provided scalar constant constScalar or nullptr if the ...
static void convertAllocsizeAttr(MLIRContext *ctx, const llvm::AttributeSet &attrs, OpTy target)
static Attribute convertProfileSummaryModuleFlagValue(ModuleOp mlirModule, const llvm::Module *llvmModule, llvm::MDTuple *mdTuple, llvm::ModuleSlotTracker &tracker)
static std::string truncateDiag(std::string str)
static Attribute convertModuleFlagValueFromMDTuple(ModuleOp mlirModule, const llvm::Module *llvmModule, StringRef key, llvm::MDTuple *mdTuple, llvm::ModuleSlotTracker &tracker)
Invoke specific handlers for each known module flag value, returns nullptr if the key is unknown or u...
static std::string renderMetadataWithTracker(const llvm::Metadata *node, llvm::ModuleSlotTracker &tracker, const llvm::Module *module)
Prints a metadata node through a caller-provided tracker so module-flag conversion shares the importe...
static FailureOr< SmallVector< ModuleFlagProfileSummaryDetailedAttr > > convertProfileSummaryDetailed(ModuleOp mlirModule, const llvm::Module *llvmModule, const llvm::MDOperand &summaryMD, llvm::ModuleSlotTracker &tracker)
static SetVector< llvm::BasicBlock * > getTopologicallySortedBlocks(ArrayRef< llvm::BasicBlock * > basicBlocks)
Get a topologically sorted list of blocks for the given basic blocks.
static llvm::ManagedStatic< PassManagerOptions > options
Attributes are known-constant values of operations.
This class represents an argument of a Block.
Block represents an ordered list of Operations.
Operation * getTerminator()
Get the terminator operation of this block.
Operation * getParentOp()
Returns the closest surrounding operation that contains this block.
This class is a general helper class for creating context-global objects like types,...
DenseI32ArrayAttr getDenseI32ArrayAttr(ArrayRef< int32_t > values)
IntegerAttr getIntegerAttr(Type type, int64_t value)
FloatAttr getFloatAttr(Type type, double value)
IntegerAttr getI64IntegerAttr(int64_t value)
StringAttr getStringAttr(const Twine &bytes)
ArrayAttr getArrayAttr(ArrayRef< Attribute > value)
MLIRContext * getContext() const
NamedAttribute getNamedAttr(StringRef name, Attribute val)
Attr getAttr(Args &&...args)
Get or construct an instance of the attribute Attr with provided arguments.
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
static DistinctAttr create(Attribute referencedAttr)
Creates a distinct attribute that associates a referenced attribute with a unique identifier.
A class for computing basic dominance information.
static FileLineColLoc get(StringAttr filename, unsigned line, unsigned column)
A symbol reference with a reference path containing a single element.
static FlatSymbolRefAttr get(StringAttr value)
Construct a symbol reference for the given value name.
StringRef getValue() const
Returns the name of the held symbol reference.
Interface collection for the import of LLVM IR that dispatches to a concrete dialect interface implem...
LogicalResult convertInstruction(OpBuilder &builder, llvm::Instruction *inst, ArrayRef< llvm::Value * > llvmOperands, LLVM::ModuleImport &moduleImport) const
Converts the LLVM instruction to an MLIR operation if a conversion exists.
LogicalResult setMetadataAttrs(OpBuilder &builder, unsigned kind, llvm::MDNode *node, Operation *op, LLVM::ModuleImport &moduleImport) const
Attaches the given LLVM metadata to the imported operation if a conversion to one or more MLIR dialec...
bool isConvertibleMetadata(unsigned kind)
Returns true if the given LLVM IR metadata is convertible to an MLIR attribute.
bool isConvertibleInstruction(unsigned id)
Returns true if the given LLVM IR instruction is convertible to an MLIR operation.
Module import implementation class that provides methods to import globals and functions from an LLVM...
LogicalResult convertIFuncs()
Converts all ifuncs of the LLVM module to MLIR variables.
LogicalResult convertIntrinsicArguments(ArrayRef< llvm::Value * > values, ArrayRef< llvm::OperandBundleUse > opBundles, bool requiresOpBundles, ArrayRef< unsigned > immArgPositions, ArrayRef< StringLiteral > immArgAttrNames, SmallVectorImpl< Value > &valuesOut, SmallVectorImpl< NamedAttribute > &attrsOut)
Converts the LLVM values for an intrinsic to mixed MLIR values and attributes for LLVM_IntrOpBase.
Location translateLoc(llvm::DILocation *loc)
Translates the debug location.
LogicalResult convertComdats()
Converts all comdat selectors of the LLVM module to MLIR comdat operations.
LogicalResult convertAliases()
Converts all aliases of the LLVM module to MLIR variables.
LogicalResult convertFunctions()
Converts all functions of the LLVM module to MLIR functions.
FailureOr< SmallVector< Value > > convertValues(ArrayRef< llvm::Value * > values)
Converts a range of LLVM values to a range of MLIR values using the convertValue method,...
Attribute lookupTBAAAttr(const llvm::MDNode *node) const
Returns the MLIR attribute mapped to the given LLVM TBAA metadata node.
LogicalResult convertLinkerOptionsMetadata()
Converts !llvm.linker.options metadata to the llvm.linker.options LLVM dialect operation.
Block * lookupBlock(llvm::BasicBlock *block) const
Returns the MLIR block mapped to the given LLVM block.
void mapBlock(llvm::BasicBlock *llvm, Block *mlir)
Stores the mapping between an LLVM block and its MLIR counterpart.
DILocalVariableAttr matchLocalVariableAttr(llvm::PointerUnion< llvm::Value *, llvm::DILocalVariable * > valOrVariable)
Converts valOrVariable to a local variable attribute.
void processFunctionAttributes(llvm::Function *func, LLVMFuncOp funcOp)
Converts function attributes of LLVM Function func into LLVM dialect attributes of LLVMFuncOp funcOp.
LogicalResult convertMetadata()
Converts all LLVM metadata nodes that translate to attributes such as alias analysis or access group ...
FailureOr< Value > convertValue(llvm::Value *value)
Converts an LLVM value to an MLIR value, or returns failure if the conversion fails.
LogicalResult initializeImportInterface()
Calls the LLVMImportInterface initialization that queries the registered dialect interfaces for the s...
void addDebugIntrinsic(llvm::CallInst *intrinsic)
Adds a debug intrinsics to the list of intrinsics that should be converted after the function convers...
LogicalResult convertIdentMetadata()
Converts !llvm.ident metadata to the llvm.ident LLVM ModuleOp attribute.
FailureOr< Value > convertMetadataValue(llvm::Value *value)
Converts an LLVM metadata value to an MLIR value, or returns failure if the conversion fails.
FailureOr< SmallVector< AliasScopeAttr > > lookupAliasScopeAttrs(const llvm::MDNode *node) const
Returns the alias scope attributes that map to the alias scope nodes starting from the metadata node.
void setDisjointFlag(llvm::Instruction *inst, Operation *op) const
Sets the disjoint flag attribute for the imported operation op given the original instruction inst.
void mapNoResultOp(llvm::Instruction *llvm, Operation *mlir)
Stores a mapping between an LLVM instruction and the imported MLIR operation if the operation returns...
void convertModuleLevelAsm()
Converts the module level asm of the LLVM module to an MLIR module level asm specification.
void setExactFlag(llvm::Instruction *inst, Operation *op) const
Sets the exact flag attribute for the imported operation op given the original instruction inst.
Type convertType(llvm::Type *type)
Converts the type from LLVM to MLIR LLVM dialect.
ModuleImport(ModuleOp mlirModule, std::unique_ptr< llvm::Module > llvmModule, bool emitExpensiveWarnings, bool importEmptyDICompositeTypes, bool preferUnregisteredIntrinsics, bool importStructsAsLiterals)
DILabelAttr matchLabelAttr(llvm::Value *value)
Converts value to a label attribute. Asserts if the matching fails.
FloatAttr matchFloatAttr(llvm::Value *value)
Converts value to a float attribute. Asserts if the matching fails.
LoopAnnotationAttr translateLoopAnnotationAttr(const llvm::MDNode *node, Location loc) const
Returns the loop annotation attribute that corresponds to the given LLVM loop metadata node.
void setFastmathFlagsAttr(llvm::Instruction *inst, Operation *op) const
Sets the fastmath flags attribute for the imported operation op given the original instruction inst.
FailureOr< SmallVector< AliasScopeAttr > > matchAliasScopeAttrs(llvm::Value *value)
Converts value to an array of alias scopes or returns failure if the conversion fails.
Value lookupValue(llvm::Value *value)
Returns the MLIR value mapped to the given LLVM value.
Operation * lookupOperation(llvm::Instruction *inst)
Returns the MLIR operation mapped to the given LLVM instruction.
LogicalResult processFunction(llvm::Function *func)
Imports func into the current module.
LogicalResult convertDependentLibrariesMetadata()
Converts !llvm.dependent-libraries metadata to llvm.dependent_libraries LLVM ModuleOp attribute.
RoundingModeAttr matchRoundingModeAttr(llvm::Value *value)
Converts value to a rounding mode attribute.
void convertTargetTriple()
Converts target triple of the LLVM module to an MLIR target triple specification.
void addDebugRecord(llvm::DbgVariableRecord *dbgRecord)
Adds a debug record to the list of debug records that need to be imported after the function conversi...
void convertArgAndResultAttrs(llvm::CallBase *call, ArgAndResultAttrsOpInterface attrsOp, ArrayRef< unsigned > immArgPositions={})
Converts the argument and result attributes attached to call and adds them to attrsOp.
LogicalResult convertModuleFlagsMetadata()
Converts !llvm.module.flags metadata.
void mapValue(llvm::Value *llvm, Value mlir)
Stores the mapping between an LLVM value and its MLIR counterpart.
FailureOr< SmallVector< AccessGroupAttr > > lookupAccessGroupAttrs(const llvm::MDNode *node) const
Returns the access group attributes that map to the access group nodes starting from the access group...
LogicalResult convertGlobals()
Converts all global variables of the LLVM module to MLIR global variables.
void setIntegerOverflowFlags(llvm::Instruction *inst, Operation *op) const
Sets the integer overflow flags (nsw/nuw) attribute for the imported operation op given the original ...
LogicalResult convertCommandlineMetadata()
Converts !llvm.commandline metadata to the llvm.commandline LLVM ModuleOp attribute.
FPExceptionBehaviorAttr matchFPExceptionBehaviorAttr(llvm::Value *value)
Converts value to a FP exception behavior attribute.
void setNonNegFlag(llvm::Instruction *inst, Operation *op) const
Sets the nneg flag attribute for the imported operation op given the original instruction inst.
FailureOr< DereferenceableAttr > translateDereferenceableAttr(const llvm::MDNode *node, unsigned kindID)
Returns the dereferenceable attribute that corresponds to the given LLVM dereferenceable or dereferen...
LogicalResult convertDataLayout()
Converts the data layout of the LLVM module to an MLIR data layout specification.
IntegerAttr matchIntegerAttr(llvm::Value *value)
Converts value to an integer attribute. Asserts if the matching fails.
Helper class that translates an LLVM data layout string to an MLIR data layout specification.
StringRef getLastToken() const
Returns the last data layout token that has been processed before the data layout translation failed.
ArrayRef< StringRef > getUnhandledTokens() const
Returns the data layout tokens that have not been handled during the data layout translation.
DataLayoutSpecInterface getDataLayoutSpec() const
Returns the MLIR data layout specification translated from the LLVM data layout.
A helper class that converts llvm.loop metadata nodes into corresponding LoopAnnotationAttrs and llvm...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
MLIRContext is the top-level object for a collection of MLIR operations.
std::vector< StringRef > getAvailableDialects()
Return information about all available dialects in the registry in this context.
void loadAllAvailableDialects()
Load all dialects available in the registry in this context.
RAII guard to reset the insertion point of the builder when destroyed.
This class helps build Operations.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
void setInsertionPointToEnd(Block *block)
Sets the insertion point to the end of the specified block.
void setInsertionPointAfterValue(Value val)
Sets the insertion point to the node after the specified value.
This class provides the API for ops that are known to be terminators.
This provides public APIs that all operations should have.
Operation is the basic unit of execution within MLIR.
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Location getLoc()
The source location the operation was defined or derived from.
This class acts as an owning reference to an op, and will automatically destroy the held op on destru...
OpTy get() const
Allow accessing the internal op.
This class contains a list of basic blocks and a link to the parent operation it is attached to.
static SmallString< N > generateSymbolName(StringRef name, UniqueChecker uniqueChecker, unsigned &uniquingCounter)
Generate a unique symbol name.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Block * getParentBlock()
Return the Block in which this Value is defined.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef< int32_t > content)
DominanceInfoNode * getNode(Block *a)
Return the dominance node from the Region containing block A.
static llvm::ArrayRef< std::pair< llvm::Attribute::AttrKind, llvm::StringRef > > getAttrKindToNameMapping()
Returns a list of pairs that each hold a mapping from LLVM attribute kinds to their corresponding str...
FloatType getFloatType(MLIRContext *context, unsigned width)
Returns a supported MLIR floating point type of the given bit width or null if the bit width is not s...
bool isCompatibleVectorType(Type type)
Returns true if the given type is a vector type compatible with the LLVM dialect.
llvm::ElementCount getVectorNumElements(Type type)
Returns the element count of any LLVM-compatible vector type.
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
InFlightDiagnostic emitWarning(Location loc)
Utility method to emit a warning message using this location.
llvm::DenseSet< ValueT, ValueInfoT > DenseSet
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
llvm::SetVector< T, Vector, Set, N > SetVector
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
OwningOpRef< ModuleOp > translateLLVMIRToModule(std::unique_ptr< llvm::Module > llvmModule, MLIRContext *context, bool emitExpensiveWarnings=true, bool dropDICompositeTypeElements=false, bool loadAllDialects=true, bool preferUnregisteredIntrinsics=false, bool importStructsAsLiterals=false)
Translates the LLVM module into an MLIR module living in the given context.