xref: /llvm-project/mlir/lib/Target/LLVMIR/ModuleImport.cpp (revision d8fadad07c952c4aea967aefb0900e4e43ad0555)
1 //===- ModuleImport.cpp - LLVM to MLIR conversion ---------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the import of an LLVM IR module into an LLVM dialect
10 // module.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/Target/LLVMIR/ModuleImport.h"
15 #include "mlir/IR/BuiltinAttributes.h"
16 #include "mlir/Target/LLVMIR/Import.h"
17 
18 #include "AttrKindDetail.h"
19 #include "DataLayoutImporter.h"
20 #include "DebugImporter.h"
21 #include "LoopAnnotationImporter.h"
22 
23 #include "mlir/Dialect/DLTI/DLTI.h"
24 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
25 #include "mlir/IR/Builders.h"
26 #include "mlir/IR/Matchers.h"
27 #include "mlir/Interfaces/DataLayoutInterfaces.h"
28 #include "mlir/Tools/mlir-translate/Translation.h"
29 
30 #include "llvm/ADT/DepthFirstIterator.h"
31 #include "llvm/ADT/PostOrderIterator.h"
32 #include "llvm/ADT/ScopeExit.h"
33 #include "llvm/ADT/StringSet.h"
34 #include "llvm/ADT/TypeSwitch.h"
35 #include "llvm/IR/Comdat.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/InlineAsm.h"
38 #include "llvm/IR/InstIterator.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/IntrinsicInst.h"
41 #include "llvm/IR/Metadata.h"
42 #include "llvm/IR/Operator.h"
43 #include "llvm/Support/ModRef.h"
44 
45 using namespace mlir;
46 using namespace mlir::LLVM;
47 using namespace mlir::LLVM::detail;
48 
49 #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsFromLLVM.inc"
50 
51 // Utility to print an LLVM value as a string for passing to emitError().
52 // FIXME: Diagnostic should be able to natively handle types that have
53 // operator << (raw_ostream&) defined.
54 static std::string diag(const llvm::Value &value) {
55   std::string str;
56   llvm::raw_string_ostream os(str);
57   os << value;
58   return str;
59 }
60 
61 // Utility to print an LLVM metadata node as a string for passing
62 // to emitError(). The module argument is needed to print the nodes
63 // canonically numbered.
64 static std::string diagMD(const llvm::Metadata *node,
65                           const llvm::Module *module) {
66   std::string str;
67   llvm::raw_string_ostream os(str);
68   node->print(os, module, /*IsForDebug=*/true);
69   return str;
70 }
71 
72 /// Returns the name of the global_ctors global variables.
73 static constexpr StringRef getGlobalCtorsVarName() {
74   return "llvm.global_ctors";
75 }
76 
77 /// Prefix used for symbols of nameless llvm globals.
78 static constexpr StringRef getNamelessGlobalPrefix() {
79   return "mlir.llvm.nameless_global";
80 }
81 
82 /// Returns the name of the global_dtors global variables.
83 static constexpr StringRef getGlobalDtorsVarName() {
84   return "llvm.global_dtors";
85 }
86 
87 /// Returns the symbol name for the module-level comdat operation. It must not
88 /// conflict with the user namespace.
89 static constexpr StringRef getGlobalComdatOpName() {
90   return "__llvm_global_comdat";
91 }
92 
93 /// Converts the sync scope identifier of `inst` to the string representation
94 /// necessary to build an atomic LLVM dialect operation. Returns the empty
95 /// string if the operation has either no sync scope or the default system-level
96 /// sync scope attached. The atomic operations only set their sync scope
97 /// attribute if they have a non-default sync scope attached.
98 static StringRef getLLVMSyncScope(llvm::Instruction *inst) {
99   std::optional<llvm::SyncScope::ID> syncScopeID =
100       llvm::getAtomicSyncScopeID(inst);
101   if (!syncScopeID)
102     return "";
103 
104   // Search the sync scope name for the given identifier. The default
105   // system-level sync scope thereby maps to the empty string.
106   SmallVector<StringRef> syncScopeName;
107   llvm::LLVMContext &llvmContext = inst->getContext();
108   llvmContext.getSyncScopeNames(syncScopeName);
109   auto *it = llvm::find_if(syncScopeName, [&](StringRef name) {
110     return *syncScopeID == llvmContext.getOrInsertSyncScopeID(name);
111   });
112   if (it != syncScopeName.end())
113     return *it;
114   llvm_unreachable("incorrect sync scope identifier");
115 }
116 
117 /// Converts an array of unsigned indices to a signed integer position array.
118 static SmallVector<int64_t> getPositionFromIndices(ArrayRef<unsigned> indices) {
119   SmallVector<int64_t> position;
120   llvm::append_range(position, indices);
121   return position;
122 }
123 
124 /// Converts the LLVM instructions that have a generated MLIR builder. Using a
125 /// static implementation method called from the module import ensures the
126 /// builders have to use the `moduleImport` argument and cannot directly call
127 /// import methods. As a result, both the intrinsic and the instruction MLIR
128 /// builders have to use the `moduleImport` argument and none of them has direct
129 /// access to the private module import methods.
130 static LogicalResult convertInstructionImpl(OpBuilder &odsBuilder,
131                                             llvm::Instruction *inst,
132                                             ModuleImport &moduleImport,
133                                             LLVMImportInterface &iface) {
134   // Copy the operands to an LLVM operands array reference for conversion.
135   SmallVector<llvm::Value *> operands(inst->operands());
136   ArrayRef<llvm::Value *> llvmOperands(operands);
137 
138   // Convert all instructions that provide an MLIR builder.
139   if (iface.isConvertibleInstruction(inst->getOpcode()))
140     return iface.convertInstruction(odsBuilder, inst, llvmOperands,
141                                     moduleImport);
142     // TODO: Implement the `convertInstruction` hooks in the
143     // `LLVMDialectLLVMIRImportInterface` and move the following include there.
144 #include "mlir/Dialect/LLVMIR/LLVMOpFromLLVMIRConversions.inc"
145   return failure();
146 }
147 
148 /// Get a topologically sorted list of blocks for the given basic blocks.
149 static SetVector<llvm::BasicBlock *>
150 getTopologicallySortedBlocks(ArrayRef<llvm::BasicBlock *> basicBlocks) {
151   SetVector<llvm::BasicBlock *> blocks;
152   for (llvm::BasicBlock *basicBlock : basicBlocks) {
153     if (!blocks.contains(basicBlock)) {
154       llvm::ReversePostOrderTraversal<llvm::BasicBlock *> traversal(basicBlock);
155       blocks.insert(traversal.begin(), traversal.end());
156     }
157   }
158   assert(blocks.size() == basicBlocks.size() && "some blocks are not sorted");
159   return blocks;
160 }
161 
162 ModuleImport::ModuleImport(ModuleOp mlirModule,
163                            std::unique_ptr<llvm::Module> llvmModule,
164                            bool emitExpensiveWarnings,
165                            bool importEmptyDICompositeTypes)
166     : builder(mlirModule->getContext()), context(mlirModule->getContext()),
167       mlirModule(mlirModule), llvmModule(std::move(llvmModule)),
168       iface(mlirModule->getContext()),
169       typeTranslator(*mlirModule->getContext()),
170       debugImporter(std::make_unique<DebugImporter>(
171           mlirModule, importEmptyDICompositeTypes)),
172       loopAnnotationImporter(
173           std::make_unique<LoopAnnotationImporter>(*this, builder)),
174       emitExpensiveWarnings(emitExpensiveWarnings) {
175   builder.setInsertionPointToStart(mlirModule.getBody());
176 }
177 
178 ComdatOp ModuleImport::getGlobalComdatOp() {
179   if (globalComdatOp)
180     return globalComdatOp;
181 
182   OpBuilder::InsertionGuard guard(builder);
183   builder.setInsertionPointToEnd(mlirModule.getBody());
184   globalComdatOp =
185       builder.create<ComdatOp>(mlirModule.getLoc(), getGlobalComdatOpName());
186   globalInsertionOp = globalComdatOp;
187   return globalComdatOp;
188 }
189 
190 LogicalResult ModuleImport::processTBAAMetadata(const llvm::MDNode *node) {
191   Location loc = mlirModule.getLoc();
192 
193   // If `node` is a valid TBAA root node, then return its optional identity
194   // string, otherwise return failure.
195   auto getIdentityIfRootNode =
196       [&](const llvm::MDNode *node) -> FailureOr<std::optional<StringRef>> {
197     // Root node, e.g.:
198     //   !0 = !{!"Simple C/C++ TBAA"}
199     //   !1 = !{}
200     if (node->getNumOperands() > 1)
201       return failure();
202     // If the operand is MDString, then assume that this is a root node.
203     if (node->getNumOperands() == 1)
204       if (const auto *op0 = dyn_cast<const llvm::MDString>(node->getOperand(0)))
205         return std::optional<StringRef>{op0->getString()};
206     return std::optional<StringRef>{};
207   };
208 
209   // If `node` looks like a TBAA type descriptor metadata,
210   // then return true, if it is a valid node, and false otherwise.
211   // If it does not look like a TBAA type descriptor metadata, then
212   // return std::nullopt.
213   // If `identity` and `memberTypes/Offsets` are non-null, then they will
214   // contain the converted metadata operands for a valid TBAA node (i.e. when
215   // true is returned).
216   auto isTypeDescriptorNode = [&](const llvm::MDNode *node,
217                                   StringRef *identity = nullptr,
218                                   SmallVectorImpl<TBAAMemberAttr> *members =
219                                       nullptr) -> std::optional<bool> {
220     unsigned numOperands = node->getNumOperands();
221     // Type descriptor, e.g.:
222     //   !1 = !{!"int", !0, /*optional*/i64 0} /* scalar int type */
223     //   !2 = !{!"agg_t", !1, i64 0} /* struct agg_t { int x; } */
224     if (numOperands < 2)
225       return std::nullopt;
226 
227     // TODO: support "new" format (D41501) for type descriptors,
228     //       where the first operand is an MDNode.
229     const auto *identityNode =
230         dyn_cast<const llvm::MDString>(node->getOperand(0));
231     if (!identityNode)
232       return std::nullopt;
233 
234     // This should be a type descriptor node.
235     if (identity)
236       *identity = identityNode->getString();
237 
238     for (unsigned pairNum = 0, e = numOperands / 2; pairNum < e; ++pairNum) {
239       const auto *memberNode =
240           dyn_cast<const llvm::MDNode>(node->getOperand(2 * pairNum + 1));
241       if (!memberNode) {
242         emitError(loc) << "operand '" << 2 * pairNum + 1 << "' must be MDNode: "
243                        << diagMD(node, llvmModule.get());
244         return false;
245       }
246       int64_t offset = 0;
247       if (2 * pairNum + 2 >= numOperands) {
248         // Allow for optional 0 offset in 2-operand nodes.
249         if (numOperands != 2) {
250           emitError(loc) << "missing member offset: "
251                          << diagMD(node, llvmModule.get());
252           return false;
253         }
254       } else {
255         auto *offsetCI = llvm::mdconst::dyn_extract<llvm::ConstantInt>(
256             node->getOperand(2 * pairNum + 2));
257         if (!offsetCI) {
258           emitError(loc) << "operand '" << 2 * pairNum + 2
259                          << "' must be ConstantInt: "
260                          << diagMD(node, llvmModule.get());
261           return false;
262         }
263         offset = offsetCI->getZExtValue();
264       }
265 
266       if (members)
267         members->push_back(TBAAMemberAttr::get(
268             cast<TBAANodeAttr>(tbaaMapping.lookup(memberNode)), offset));
269     }
270 
271     return true;
272   };
273 
274   // If `node` looks like a TBAA access tag metadata,
275   // then return true, if it is a valid node, and false otherwise.
276   // If it does not look like a TBAA access tag metadata, then
277   // return std::nullopt.
278   // If the other arguments are non-null, then they will contain
279   // the converted metadata operands for a valid TBAA node (i.e. when true is
280   // returned).
281   auto isTagNode = [&](const llvm::MDNode *node,
282                        TBAATypeDescriptorAttr *baseAttr = nullptr,
283                        TBAATypeDescriptorAttr *accessAttr = nullptr,
284                        int64_t *offset = nullptr,
285                        bool *isConstant = nullptr) -> std::optional<bool> {
286     // Access tag, e.g.:
287     //   !3 = !{!1, !1, i64 0} /* scalar int access */
288     //   !4 = !{!2, !1, i64 0} /* agg_t::x access */
289     //
290     // Optional 4th argument is ConstantInt 0/1 identifying whether
291     // the location being accessed is "constant" (see for details:
292     // https://llvm.org/docs/LangRef.html#representation).
293     unsigned numOperands = node->getNumOperands();
294     if (numOperands != 3 && numOperands != 4)
295       return std::nullopt;
296     const auto *baseMD = dyn_cast<const llvm::MDNode>(node->getOperand(0));
297     const auto *accessMD = dyn_cast<const llvm::MDNode>(node->getOperand(1));
298     auto *offsetCI =
299         llvm::mdconst::dyn_extract<llvm::ConstantInt>(node->getOperand(2));
300     if (!baseMD || !accessMD || !offsetCI)
301       return std::nullopt;
302     // TODO: support "new" TBAA format, if needed (see D41501).
303     // In the "old" format the first operand of the access type
304     // metadata is MDString. We have to distinguish the formats,
305     // because access tags have the same structure, but different
306     // meaning for the operands.
307     if (accessMD->getNumOperands() < 1 ||
308         !isa<llvm::MDString>(accessMD->getOperand(0)))
309       return std::nullopt;
310     bool isConst = false;
311     if (numOperands == 4) {
312       auto *isConstantCI =
313           llvm::mdconst::dyn_extract<llvm::ConstantInt>(node->getOperand(3));
314       if (!isConstantCI) {
315         emitError(loc) << "operand '3' must be ConstantInt: "
316                        << diagMD(node, llvmModule.get());
317         return false;
318       }
319       isConst = isConstantCI->getValue()[0];
320     }
321     if (baseAttr)
322       *baseAttr = cast<TBAATypeDescriptorAttr>(tbaaMapping.lookup(baseMD));
323     if (accessAttr)
324       *accessAttr = cast<TBAATypeDescriptorAttr>(tbaaMapping.lookup(accessMD));
325     if (offset)
326       *offset = offsetCI->getZExtValue();
327     if (isConstant)
328       *isConstant = isConst;
329     return true;
330   };
331 
332   // Do a post-order walk over the TBAA Graph. Since a correct TBAA Graph is a
333   // DAG, a post-order walk guarantees that we convert any metadata node we
334   // depend on, prior to converting the current node.
335   DenseSet<const llvm::MDNode *> seen;
336   SmallVector<const llvm::MDNode *> workList;
337   workList.push_back(node);
338   while (!workList.empty()) {
339     const llvm::MDNode *current = workList.back();
340     if (tbaaMapping.contains(current)) {
341       // Already converted. Just pop from the worklist.
342       workList.pop_back();
343       continue;
344     }
345 
346     // If any child of this node is not yet converted, don't pop the current
347     // node from the worklist but push the not-yet-converted children in the
348     // front of the worklist.
349     bool anyChildNotConverted = false;
350     for (const llvm::MDOperand &operand : current->operands())
351       if (auto *childNode = dyn_cast_or_null<const llvm::MDNode>(operand.get()))
352         if (!tbaaMapping.contains(childNode)) {
353           workList.push_back(childNode);
354           anyChildNotConverted = true;
355         }
356 
357     if (anyChildNotConverted) {
358       // If this is the second time we failed to convert an element in the
359       // worklist it must be because a child is dependent on it being converted
360       // and we have a cycle in the graph. Cycles are not allowed in TBAA
361       // graphs.
362       if (!seen.insert(current).second)
363         return emitError(loc) << "has cycle in TBAA graph: "
364                               << diagMD(current, llvmModule.get());
365 
366       continue;
367     }
368 
369     // Otherwise simply import the current node.
370     workList.pop_back();
371 
372     FailureOr<std::optional<StringRef>> rootNodeIdentity =
373         getIdentityIfRootNode(current);
374     if (succeeded(rootNodeIdentity)) {
375       StringAttr stringAttr = *rootNodeIdentity
376                                   ? builder.getStringAttr(**rootNodeIdentity)
377                                   : nullptr;
378       // The root nodes do not have operands, so we can create
379       // the TBAARootAttr on the first walk.
380       tbaaMapping.insert({current, builder.getAttr<TBAARootAttr>(stringAttr)});
381       continue;
382     }
383 
384     StringRef identity;
385     SmallVector<TBAAMemberAttr> members;
386     if (std::optional<bool> isValid =
387             isTypeDescriptorNode(current, &identity, &members)) {
388       assert(isValid.value() && "type descriptor node must be valid");
389 
390       tbaaMapping.insert({current, builder.getAttr<TBAATypeDescriptorAttr>(
391                                        identity, members)});
392       continue;
393     }
394 
395     TBAATypeDescriptorAttr baseAttr, accessAttr;
396     int64_t offset;
397     bool isConstant;
398     if (std::optional<bool> isValid =
399             isTagNode(current, &baseAttr, &accessAttr, &offset, &isConstant)) {
400       assert(isValid.value() && "access tag node must be valid");
401       tbaaMapping.insert(
402           {current, builder.getAttr<TBAATagAttr>(baseAttr, accessAttr, offset,
403                                                  isConstant)});
404       continue;
405     }
406 
407     return emitError(loc) << "unsupported TBAA node format: "
408                           << diagMD(current, llvmModule.get());
409   }
410   return success();
411 }
412 
413 LogicalResult
414 ModuleImport::processAccessGroupMetadata(const llvm::MDNode *node) {
415   Location loc = mlirModule.getLoc();
416   if (failed(loopAnnotationImporter->translateAccessGroup(node, loc)))
417     return emitError(loc) << "unsupported access group node: "
418                           << diagMD(node, llvmModule.get());
419   return success();
420 }
421 
422 LogicalResult
423 ModuleImport::processAliasScopeMetadata(const llvm::MDNode *node) {
424   Location loc = mlirModule.getLoc();
425   // Helper that verifies the node has a self reference operand.
426   auto verifySelfRef = [](const llvm::MDNode *node) {
427     return node->getNumOperands() != 0 &&
428            node == dyn_cast<llvm::MDNode>(node->getOperand(0));
429   };
430   // Helper that verifies the given operand is a string or does not exist.
431   auto verifyDescription = [](const llvm::MDNode *node, unsigned idx) {
432     return idx >= node->getNumOperands() ||
433            isa<llvm::MDString>(node->getOperand(idx));
434   };
435   // Helper that creates an alias scope domain attribute.
436   auto createAliasScopeDomainOp = [&](const llvm::MDNode *aliasDomain) {
437     StringAttr description = nullptr;
438     if (aliasDomain->getNumOperands() >= 2)
439       if (auto *operand = dyn_cast<llvm::MDString>(aliasDomain->getOperand(1)))
440         description = builder.getStringAttr(operand->getString());
441     return builder.getAttr<AliasScopeDomainAttr>(
442         DistinctAttr::create(builder.getUnitAttr()), description);
443   };
444 
445   // Collect the alias scopes and domains to translate them.
446   for (const llvm::MDOperand &operand : node->operands()) {
447     if (const auto *scope = dyn_cast<llvm::MDNode>(operand)) {
448       llvm::AliasScopeNode aliasScope(scope);
449       const llvm::MDNode *domain = aliasScope.getDomain();
450 
451       // Verify the scope node points to valid scope metadata which includes
452       // verifying its domain. Perform the verification before looking it up in
453       // the alias scope mapping since it could have been inserted as a domain
454       // node before.
455       if (!verifySelfRef(scope) || !domain || !verifyDescription(scope, 2))
456         return emitError(loc) << "unsupported alias scope node: "
457                               << diagMD(scope, llvmModule.get());
458       if (!verifySelfRef(domain) || !verifyDescription(domain, 1))
459         return emitError(loc) << "unsupported alias domain node: "
460                               << diagMD(domain, llvmModule.get());
461 
462       if (aliasScopeMapping.contains(scope))
463         continue;
464 
465       // Convert the domain metadata node if it has not been translated before.
466       auto it = aliasScopeMapping.find(aliasScope.getDomain());
467       if (it == aliasScopeMapping.end()) {
468         auto aliasScopeDomainOp = createAliasScopeDomainOp(domain);
469         it = aliasScopeMapping.try_emplace(domain, aliasScopeDomainOp).first;
470       }
471 
472       // Convert the scope metadata node if it has not been converted before.
473       StringAttr description = nullptr;
474       if (!aliasScope.getName().empty())
475         description = builder.getStringAttr(aliasScope.getName());
476       auto aliasScopeOp = builder.getAttr<AliasScopeAttr>(
477           DistinctAttr::create(builder.getUnitAttr()),
478           cast<AliasScopeDomainAttr>(it->second), description);
479       aliasScopeMapping.try_emplace(aliasScope.getNode(), aliasScopeOp);
480     }
481   }
482   return success();
483 }
484 
485 FailureOr<SmallVector<AliasScopeAttr>>
486 ModuleImport::lookupAliasScopeAttrs(const llvm::MDNode *node) const {
487   SmallVector<AliasScopeAttr> aliasScopes;
488   aliasScopes.reserve(node->getNumOperands());
489   for (const llvm::MDOperand &operand : node->operands()) {
490     auto *node = cast<llvm::MDNode>(operand.get());
491     aliasScopes.push_back(
492         dyn_cast_or_null<AliasScopeAttr>(aliasScopeMapping.lookup(node)));
493   }
494   // Return failure if one of the alias scope lookups failed.
495   if (llvm::is_contained(aliasScopes, nullptr))
496     return failure();
497   return aliasScopes;
498 }
499 
500 void ModuleImport::addDebugIntrinsic(llvm::CallInst *intrinsic) {
501   debugIntrinsics.insert(intrinsic);
502 }
503 
504 LogicalResult ModuleImport::convertLinkerOptionsMetadata() {
505   for (const llvm::NamedMDNode &named : llvmModule->named_metadata()) {
506     if (named.getName() != "llvm.linker.options")
507       continue;
508     // llvm.linker.options operands are lists of strings.
509     for (const llvm::MDNode *node : named.operands()) {
510       SmallVector<StringRef> options;
511       options.reserve(node->getNumOperands());
512       for (const llvm::MDOperand &option : node->operands())
513         options.push_back(cast<llvm::MDString>(option)->getString());
514       builder.create<LLVM::LinkerOptionsOp>(mlirModule.getLoc(),
515                                             builder.getStrArrayAttr(options));
516     }
517   }
518   return success();
519 }
520 
521 LogicalResult ModuleImport::convertIdentMetadata() {
522   for (const llvm::NamedMDNode &named : llvmModule->named_metadata()) {
523     // llvm.ident should have a single operand. That operand is itself an
524     // MDNode with a single string operand.
525     if (named.getName() != LLVMDialect::getIdentAttrName())
526       continue;
527 
528     if (named.getNumOperands() == 1)
529       if (auto *md = dyn_cast<llvm::MDNode>(named.getOperand(0)))
530         if (md->getNumOperands() == 1)
531           if (auto *mdStr = dyn_cast<llvm::MDString>(md->getOperand(0)))
532             mlirModule->setAttr(LLVMDialect::getIdentAttrName(),
533                                 builder.getStringAttr(mdStr->getString()));
534   }
535   return success();
536 }
537 
538 LogicalResult ModuleImport::convertCommandlineMetadata() {
539   for (const llvm::NamedMDNode &nmd : llvmModule->named_metadata()) {
540     // llvm.commandline should have a single operand. That operand is itself an
541     // MDNode with a single string operand.
542     if (nmd.getName() != LLVMDialect::getCommandlineAttrName())
543       continue;
544 
545     if (nmd.getNumOperands() == 1)
546       if (auto *md = dyn_cast<llvm::MDNode>(nmd.getOperand(0)))
547         if (md->getNumOperands() == 1)
548           if (auto *mdStr = dyn_cast<llvm::MDString>(md->getOperand(0)))
549             mlirModule->setAttr(LLVMDialect::getCommandlineAttrName(),
550                                 builder.getStringAttr(mdStr->getString()));
551   }
552   return success();
553 }
554 
555 LogicalResult ModuleImport::convertMetadata() {
556   OpBuilder::InsertionGuard guard(builder);
557   builder.setInsertionPointToEnd(mlirModule.getBody());
558   for (const llvm::Function &func : llvmModule->functions()) {
559     for (const llvm::Instruction &inst : llvm::instructions(func)) {
560       // Convert access group metadata nodes.
561       if (llvm::MDNode *node =
562               inst.getMetadata(llvm::LLVMContext::MD_access_group))
563         if (failed(processAccessGroupMetadata(node)))
564           return failure();
565 
566       // Convert alias analysis metadata nodes.
567       llvm::AAMDNodes aliasAnalysisNodes = inst.getAAMetadata();
568       if (!aliasAnalysisNodes)
569         continue;
570       if (aliasAnalysisNodes.TBAA)
571         if (failed(processTBAAMetadata(aliasAnalysisNodes.TBAA)))
572           return failure();
573       if (aliasAnalysisNodes.Scope)
574         if (failed(processAliasScopeMetadata(aliasAnalysisNodes.Scope)))
575           return failure();
576       if (aliasAnalysisNodes.NoAlias)
577         if (failed(processAliasScopeMetadata(aliasAnalysisNodes.NoAlias)))
578           return failure();
579     }
580   }
581   if (failed(convertLinkerOptionsMetadata()))
582     return failure();
583   if (failed(convertIdentMetadata()))
584     return failure();
585   if (failed(convertCommandlineMetadata()))
586     return failure();
587   return success();
588 }
589 
590 void ModuleImport::processComdat(const llvm::Comdat *comdat) {
591   if (comdatMapping.contains(comdat))
592     return;
593 
594   ComdatOp comdatOp = getGlobalComdatOp();
595   OpBuilder::InsertionGuard guard(builder);
596   builder.setInsertionPointToEnd(&comdatOp.getBody().back());
597   auto selectorOp = builder.create<ComdatSelectorOp>(
598       mlirModule.getLoc(), comdat->getName(),
599       convertComdatFromLLVM(comdat->getSelectionKind()));
600   auto symbolRef =
601       SymbolRefAttr::get(builder.getContext(), getGlobalComdatOpName(),
602                          FlatSymbolRefAttr::get(selectorOp.getSymNameAttr()));
603   comdatMapping.try_emplace(comdat, symbolRef);
604 }
605 
606 LogicalResult ModuleImport::convertComdats() {
607   for (llvm::GlobalVariable &globalVar : llvmModule->globals())
608     if (globalVar.hasComdat())
609       processComdat(globalVar.getComdat());
610   for (llvm::Function &func : llvmModule->functions())
611     if (func.hasComdat())
612       processComdat(func.getComdat());
613   return success();
614 }
615 
616 LogicalResult ModuleImport::convertGlobals() {
617   for (llvm::GlobalVariable &globalVar : llvmModule->globals()) {
618     if (globalVar.getName() == getGlobalCtorsVarName() ||
619         globalVar.getName() == getGlobalDtorsVarName()) {
620       if (failed(convertGlobalCtorsAndDtors(&globalVar))) {
621         return emitError(UnknownLoc::get(context))
622                << "unhandled global variable: " << diag(globalVar);
623       }
624       continue;
625     }
626     if (failed(convertGlobal(&globalVar))) {
627       return emitError(UnknownLoc::get(context))
628              << "unhandled global variable: " << diag(globalVar);
629     }
630   }
631   return success();
632 }
633 
634 LogicalResult ModuleImport::convertDataLayout() {
635   Location loc = mlirModule.getLoc();
636   DataLayoutImporter dataLayoutImporter(context, llvmModule->getDataLayout());
637   if (!dataLayoutImporter.getDataLayout())
638     return emitError(loc, "cannot translate data layout: ")
639            << dataLayoutImporter.getLastToken();
640 
641   for (StringRef token : dataLayoutImporter.getUnhandledTokens())
642     emitWarning(loc, "unhandled data layout token: ") << token;
643 
644   mlirModule->setAttr(DLTIDialect::kDataLayoutAttrName,
645                       dataLayoutImporter.getDataLayout());
646   return success();
647 }
648 
649 LogicalResult ModuleImport::convertFunctions() {
650   for (llvm::Function &func : llvmModule->functions())
651     if (failed(processFunction(&func)))
652       return failure();
653   return success();
654 }
655 
656 void ModuleImport::setNonDebugMetadataAttrs(llvm::Instruction *inst,
657                                             Operation *op) {
658   SmallVector<std::pair<unsigned, llvm::MDNode *>> allMetadata;
659   inst->getAllMetadataOtherThanDebugLoc(allMetadata);
660   for (auto &[kind, node] : allMetadata) {
661     if (!iface.isConvertibleMetadata(kind))
662       continue;
663     if (failed(iface.setMetadataAttrs(builder, kind, node, op, *this))) {
664       if (emitExpensiveWarnings) {
665         Location loc = debugImporter->translateLoc(inst->getDebugLoc());
666         emitWarning(loc) << "unhandled metadata: "
667                          << diagMD(node, llvmModule.get()) << " on "
668                          << diag(*inst);
669       }
670     }
671   }
672 }
673 
674 void ModuleImport::setIntegerOverflowFlags(llvm::Instruction *inst,
675                                            Operation *op) const {
676   auto iface = cast<IntegerOverflowFlagsInterface>(op);
677 
678   IntegerOverflowFlags value = {};
679   value = bitEnumSet(value, IntegerOverflowFlags::nsw, inst->hasNoSignedWrap());
680   value =
681       bitEnumSet(value, IntegerOverflowFlags::nuw, inst->hasNoUnsignedWrap());
682 
683   iface.setOverflowFlags(value);
684 }
685 
686 void ModuleImport::setFastmathFlagsAttr(llvm::Instruction *inst,
687                                         Operation *op) const {
688   auto iface = cast<FastmathFlagsInterface>(op);
689 
690   // Even if the imported operation implements the fastmath interface, the
691   // original instruction may not have fastmath flags set. Exit if an
692   // instruction, such as a non floating-point function call, does not have
693   // fastmath flags.
694   if (!isa<llvm::FPMathOperator>(inst))
695     return;
696   llvm::FastMathFlags flags = inst->getFastMathFlags();
697 
698   // Set the fastmath bits flag-by-flag.
699   FastmathFlags value = {};
700   value = bitEnumSet(value, FastmathFlags::nnan, flags.noNaNs());
701   value = bitEnumSet(value, FastmathFlags::ninf, flags.noInfs());
702   value = bitEnumSet(value, FastmathFlags::nsz, flags.noSignedZeros());
703   value = bitEnumSet(value, FastmathFlags::arcp, flags.allowReciprocal());
704   value = bitEnumSet(value, FastmathFlags::contract, flags.allowContract());
705   value = bitEnumSet(value, FastmathFlags::afn, flags.approxFunc());
706   value = bitEnumSet(value, FastmathFlags::reassoc, flags.allowReassoc());
707   FastmathFlagsAttr attr = FastmathFlagsAttr::get(builder.getContext(), value);
708   iface->setAttr(iface.getFastmathAttrName(), attr);
709 }
710 
711 /// Returns if `type` is a scalar integer or floating-point type.
712 static bool isScalarType(Type type) {
713   return isa<IntegerType, FloatType>(type);
714 }
715 
716 /// Returns `type` if it is a builtin integer or floating-point vector type that
717 /// can be used to create an attribute or nullptr otherwise. If provided,
718 /// `arrayShape` is added to the shape of the vector to create an attribute that
719 /// matches an array of vectors.
720 static Type getVectorTypeForAttr(Type type, ArrayRef<int64_t> arrayShape = {}) {
721   if (!LLVM::isCompatibleVectorType(type))
722     return {};
723 
724   llvm::ElementCount numElements = LLVM::getVectorNumElements(type);
725   if (numElements.isScalable()) {
726     emitError(UnknownLoc::get(type.getContext()))
727         << "scalable vectors not supported";
728     return {};
729   }
730 
731   // An LLVM dialect vector can only contain scalars.
732   Type elementType = LLVM::getVectorElementType(type);
733   if (!isScalarType(elementType))
734     return {};
735 
736   SmallVector<int64_t> shape(arrayShape);
737   shape.push_back(numElements.getKnownMinValue());
738   return VectorType::get(shape, elementType);
739 }
740 
741 Type ModuleImport::getBuiltinTypeForAttr(Type type) {
742   if (!type)
743     return {};
744 
745   // Return builtin integer and floating-point types as is.
746   if (isScalarType(type))
747     return type;
748 
749   // Return builtin vectors of integer and floating-point types as is.
750   if (Type vectorType = getVectorTypeForAttr(type))
751     return vectorType;
752 
753   // Multi-dimensional array types are converted to tensors or vectors,
754   // depending on the innermost type being a scalar or a vector.
755   SmallVector<int64_t> arrayShape;
756   while (auto arrayType = dyn_cast<LLVMArrayType>(type)) {
757     arrayShape.push_back(arrayType.getNumElements());
758     type = arrayType.getElementType();
759   }
760   if (isScalarType(type))
761     return RankedTensorType::get(arrayShape, type);
762   return getVectorTypeForAttr(type, arrayShape);
763 }
764 
765 /// Returns an integer or float attribute for the provided scalar constant
766 /// `constScalar` or nullptr if the conversion fails.
767 static TypedAttr getScalarConstantAsAttr(OpBuilder &builder,
768                                          llvm::Constant *constScalar) {
769   MLIRContext *context = builder.getContext();
770 
771   // Convert scalar intergers.
772   if (auto *constInt = dyn_cast<llvm::ConstantInt>(constScalar)) {
773     return builder.getIntegerAttr(
774         IntegerType::get(context, constInt->getBitWidth()),
775         constInt->getValue());
776   }
777 
778   // Convert scalar floats.
779   if (auto *constFloat = dyn_cast<llvm::ConstantFP>(constScalar)) {
780     llvm::Type *type = constFloat->getType();
781     FloatType floatType =
782         type->isBFloatTy()
783             ? FloatType::getBF16(context)
784             : LLVM::detail::getFloatType(context, type->getScalarSizeInBits());
785     if (!floatType) {
786       emitError(UnknownLoc::get(builder.getContext()))
787           << "unexpected floating-point type";
788       return {};
789     }
790     return builder.getFloatAttr(floatType, constFloat->getValueAPF());
791   }
792   return {};
793 }
794 
795 /// Returns an integer or float attribute array for the provided constant
796 /// sequence `constSequence` or nullptr if the conversion fails.
797 static SmallVector<Attribute>
798 getSequenceConstantAsAttrs(OpBuilder &builder,
799                            llvm::ConstantDataSequential *constSequence) {
800   SmallVector<Attribute> elementAttrs;
801   elementAttrs.reserve(constSequence->getNumElements());
802   for (auto idx : llvm::seq<int64_t>(0, constSequence->getNumElements())) {
803     llvm::Constant *constElement = constSequence->getElementAsConstant(idx);
804     elementAttrs.push_back(getScalarConstantAsAttr(builder, constElement));
805   }
806   return elementAttrs;
807 }
808 
809 Attribute ModuleImport::getConstantAsAttr(llvm::Constant *constant) {
810   // Convert scalar constants.
811   if (Attribute scalarAttr = getScalarConstantAsAttr(builder, constant))
812     return scalarAttr;
813 
814   // Returns the static shape of the provided type if possible.
815   auto getConstantShape = [&](llvm::Type *type) {
816     return llvm::dyn_cast_if_present<ShapedType>(
817         getBuiltinTypeForAttr(convertType(type)));
818   };
819 
820   // Convert one-dimensional constant arrays or vectors that store 1/2/4/8-byte
821   // integer or half/bfloat/float/double values.
822   if (auto *constArray = dyn_cast<llvm::ConstantDataSequential>(constant)) {
823     if (constArray->isString())
824       return builder.getStringAttr(constArray->getAsString());
825     auto shape = getConstantShape(constArray->getType());
826     if (!shape)
827       return {};
828     // Convert splat constants to splat elements attributes.
829     auto *constVector = dyn_cast<llvm::ConstantDataVector>(constant);
830     if (constVector && constVector->isSplat()) {
831       // A vector is guaranteed to have at least size one.
832       Attribute splatAttr = getScalarConstantAsAttr(
833           builder, constVector->getElementAsConstant(0));
834       return SplatElementsAttr::get(shape, splatAttr);
835     }
836     // Convert non-splat constants to dense elements attributes.
837     SmallVector<Attribute> elementAttrs =
838         getSequenceConstantAsAttrs(builder, constArray);
839     return DenseElementsAttr::get(shape, elementAttrs);
840   }
841 
842   // Convert multi-dimensional constant aggregates that store all kinds of
843   // integer and floating-point types.
844   if (auto *constAggregate = dyn_cast<llvm::ConstantAggregate>(constant)) {
845     auto shape = getConstantShape(constAggregate->getType());
846     if (!shape)
847       return {};
848     // Collect the aggregate elements in depths first order.
849     SmallVector<Attribute> elementAttrs;
850     SmallVector<llvm::Constant *> workList = {constAggregate};
851     while (!workList.empty()) {
852       llvm::Constant *current = workList.pop_back_val();
853       // Append any nested aggregates in reverse order to ensure the head
854       // element of the nested aggregates is at the back of the work list.
855       if (auto *constAggregate = dyn_cast<llvm::ConstantAggregate>(current)) {
856         for (auto idx :
857              reverse(llvm::seq<int64_t>(0, constAggregate->getNumOperands())))
858           workList.push_back(constAggregate->getAggregateElement(idx));
859         continue;
860       }
861       // Append the elements of nested constant arrays or vectors that store
862       // 1/2/4/8-byte integer or half/bfloat/float/double values.
863       if (auto *constArray = dyn_cast<llvm::ConstantDataSequential>(current)) {
864         SmallVector<Attribute> attrs =
865             getSequenceConstantAsAttrs(builder, constArray);
866         elementAttrs.append(attrs.begin(), attrs.end());
867         continue;
868       }
869       // Append nested scalar constants that store all kinds of integer and
870       // floating-point types.
871       if (Attribute scalarAttr = getScalarConstantAsAttr(builder, current)) {
872         elementAttrs.push_back(scalarAttr);
873         continue;
874       }
875       // Bail if the aggregate contains a unsupported constant type such as a
876       // constant expression.
877       return {};
878     }
879     return DenseElementsAttr::get(shape, elementAttrs);
880   }
881 
882   // Convert zero aggregates.
883   if (auto *constZero = dyn_cast<llvm::ConstantAggregateZero>(constant)) {
884     auto shape = llvm::dyn_cast_if_present<ShapedType>(
885         getBuiltinTypeForAttr(convertType(constZero->getType())));
886     if (!shape)
887       return {};
888     // Convert zero aggregates with a static shape to splat elements attributes.
889     Attribute splatAttr = builder.getZeroAttr(shape.getElementType());
890     assert(splatAttr && "expected non-null zero attribute for scalar types");
891     return SplatElementsAttr::get(shape, splatAttr);
892   }
893   return {};
894 }
895 
896 FlatSymbolRefAttr
897 ModuleImport::getOrCreateNamelessSymbolName(llvm::GlobalVariable *globalVar) {
898   assert(globalVar->getName().empty() &&
899          "expected to work with a nameless global");
900   auto [it, success] = namelessGlobals.try_emplace(globalVar);
901   if (!success)
902     return it->second;
903 
904   // Make sure the symbol name does not clash with an existing symbol.
905   SmallString<128> globalName = SymbolTable::generateSymbolName<128>(
906       getNamelessGlobalPrefix(),
907       [this](StringRef newName) { return llvmModule->getNamedValue(newName); },
908       namelessGlobalId);
909   auto symbolRef = FlatSymbolRefAttr::get(context, globalName);
910   it->getSecond() = symbolRef;
911   return symbolRef;
912 }
913 
914 LogicalResult ModuleImport::convertGlobal(llvm::GlobalVariable *globalVar) {
915   // Insert the global after the last one or at the start of the module.
916   OpBuilder::InsertionGuard guard(builder);
917   if (!globalInsertionOp)
918     builder.setInsertionPointToStart(mlirModule.getBody());
919   else
920     builder.setInsertionPointAfter(globalInsertionOp);
921 
922   Attribute valueAttr;
923   if (globalVar->hasInitializer())
924     valueAttr = getConstantAsAttr(globalVar->getInitializer());
925   Type type = convertType(globalVar->getValueType());
926 
927   uint64_t alignment = 0;
928   llvm::MaybeAlign maybeAlign = globalVar->getAlign();
929   if (maybeAlign.has_value()) {
930     llvm::Align align = *maybeAlign;
931     alignment = align.value();
932   }
933 
934   // Get the global expression associated with this global variable and convert
935   // it.
936   SmallVector<Attribute> globalExpressionAttrs;
937   SmallVector<llvm::DIGlobalVariableExpression *> globalExpressions;
938   globalVar->getDebugInfo(globalExpressions);
939 
940   for (llvm::DIGlobalVariableExpression *expr : globalExpressions) {
941     DIGlobalVariableExpressionAttr globalExpressionAttr =
942         debugImporter->translateGlobalVariableExpression(expr);
943     globalExpressionAttrs.push_back(globalExpressionAttr);
944   }
945 
946   // Workaround to support LLVM's nameless globals. MLIR, in contrast to LLVM,
947   // always requires a symbol name.
948   StringRef globalName = globalVar->getName();
949   if (globalName.empty())
950     globalName = getOrCreateNamelessSymbolName(globalVar).getValue();
951 
952   GlobalOp globalOp = builder.create<GlobalOp>(
953       mlirModule.getLoc(), type, globalVar->isConstant(),
954       convertLinkageFromLLVM(globalVar->getLinkage()), StringRef(globalName),
955       valueAttr, alignment, /*addr_space=*/globalVar->getAddressSpace(),
956       /*dso_local=*/globalVar->isDSOLocal(),
957       /*thread_local=*/globalVar->isThreadLocal(), /*comdat=*/SymbolRefAttr(),
958       /*attrs=*/ArrayRef<NamedAttribute>(), /*dbgExprs=*/globalExpressionAttrs);
959   globalInsertionOp = globalOp;
960 
961   if (globalVar->hasInitializer() && !valueAttr) {
962     clearRegionState();
963     Block *block = builder.createBlock(&globalOp.getInitializerRegion());
964     setConstantInsertionPointToStart(block);
965     FailureOr<Value> initializer =
966         convertConstantExpr(globalVar->getInitializer());
967     if (failed(initializer))
968       return failure();
969     builder.create<ReturnOp>(globalOp.getLoc(), *initializer);
970   }
971   if (globalVar->hasAtLeastLocalUnnamedAddr()) {
972     globalOp.setUnnamedAddr(
973         convertUnnamedAddrFromLLVM(globalVar->getUnnamedAddr()));
974   }
975   if (globalVar->hasSection())
976     globalOp.setSection(globalVar->getSection());
977   globalOp.setVisibility_(
978       convertVisibilityFromLLVM(globalVar->getVisibility()));
979 
980   if (globalVar->hasComdat())
981     globalOp.setComdatAttr(comdatMapping.lookup(globalVar->getComdat()));
982 
983   return success();
984 }
985 
986 LogicalResult
987 ModuleImport::convertGlobalCtorsAndDtors(llvm::GlobalVariable *globalVar) {
988   if (!globalVar->hasInitializer() || !globalVar->hasAppendingLinkage())
989     return failure();
990   auto *initializer =
991       dyn_cast<llvm::ConstantArray>(globalVar->getInitializer());
992   if (!initializer)
993     return failure();
994 
995   SmallVector<Attribute> funcs;
996   SmallVector<int32_t> priorities;
997   for (llvm::Value *operand : initializer->operands()) {
998     auto *aggregate = dyn_cast<llvm::ConstantAggregate>(operand);
999     if (!aggregate || aggregate->getNumOperands() != 3)
1000       return failure();
1001 
1002     auto *priority = dyn_cast<llvm::ConstantInt>(aggregate->getOperand(0));
1003     auto *func = dyn_cast<llvm::Function>(aggregate->getOperand(1));
1004     auto *data = dyn_cast<llvm::Constant>(aggregate->getOperand(2));
1005     if (!priority || !func || !data)
1006       return failure();
1007 
1008     // GlobalCtorsOps and GlobalDtorsOps do not support non-null data fields.
1009     if (!data->isNullValue())
1010       return failure();
1011 
1012     funcs.push_back(FlatSymbolRefAttr::get(context, func->getName()));
1013     priorities.push_back(priority->getValue().getZExtValue());
1014   }
1015 
1016   OpBuilder::InsertionGuard guard(builder);
1017   if (!globalInsertionOp)
1018     builder.setInsertionPointToStart(mlirModule.getBody());
1019   else
1020     builder.setInsertionPointAfter(globalInsertionOp);
1021 
1022   if (globalVar->getName() == getGlobalCtorsVarName()) {
1023     globalInsertionOp = builder.create<LLVM::GlobalCtorsOp>(
1024         mlirModule.getLoc(), builder.getArrayAttr(funcs),
1025         builder.getI32ArrayAttr(priorities));
1026     return success();
1027   }
1028   globalInsertionOp = builder.create<LLVM::GlobalDtorsOp>(
1029       mlirModule.getLoc(), builder.getArrayAttr(funcs),
1030       builder.getI32ArrayAttr(priorities));
1031   return success();
1032 }
1033 
1034 SetVector<llvm::Constant *>
1035 ModuleImport::getConstantsToConvert(llvm::Constant *constant) {
1036   // Return the empty set if the constant has been translated before.
1037   if (valueMapping.contains(constant))
1038     return {};
1039 
1040   // Traverse the constants in post-order and stop the traversal if a constant
1041   // already has a `valueMapping` from an earlier constant translation or if the
1042   // constant is traversed a second time.
1043   SetVector<llvm::Constant *> orderedSet;
1044   SetVector<llvm::Constant *> workList;
1045   DenseMap<llvm::Constant *, SmallVector<llvm::Constant *>> adjacencyLists;
1046   workList.insert(constant);
1047   while (!workList.empty()) {
1048     llvm::Constant *current = workList.back();
1049     // References of global objects are just pointers to the object. Avoid
1050     // walking the elements of these here.
1051     if (isa<llvm::GlobalObject>(current)) {
1052       orderedSet.insert(current);
1053       workList.pop_back();
1054       continue;
1055     }
1056 
1057     // Collect all dependencies of the current constant and add them to the
1058     // adjacency list if none has been computed before.
1059     auto [adjacencyIt, inserted] = adjacencyLists.try_emplace(current);
1060     if (inserted) {
1061       // Add all constant operands to the adjacency list and skip any other
1062       // values such as basic block addresses.
1063       for (llvm::Value *operand : current->operands())
1064         if (auto *constDependency = dyn_cast<llvm::Constant>(operand))
1065           adjacencyIt->getSecond().push_back(constDependency);
1066       // Use the getElementValue method to add the dependencies of zero
1067       // initialized aggregate constants since they do not take any operands.
1068       if (auto *constAgg = dyn_cast<llvm::ConstantAggregateZero>(current)) {
1069         unsigned numElements = constAgg->getElementCount().getFixedValue();
1070         for (unsigned i = 0, e = numElements; i != e; ++i)
1071           adjacencyIt->getSecond().push_back(constAgg->getElementValue(i));
1072       }
1073     }
1074     // Add the current constant to the `orderedSet` of the traversed nodes if
1075     // all its dependencies have been traversed before. Additionally, remove the
1076     // constant from the `workList` and continue the traversal.
1077     if (adjacencyIt->getSecond().empty()) {
1078       orderedSet.insert(current);
1079       workList.pop_back();
1080       continue;
1081     }
1082     // Add the next dependency from the adjacency list to the `workList` and
1083     // continue the traversal. Remove the dependency from the adjacency list to
1084     // mark that it has been processed. Only enqueue the dependency if it has no
1085     // `valueMapping` from an earlier translation and if it has not been
1086     // enqueued before.
1087     llvm::Constant *dependency = adjacencyIt->getSecond().pop_back_val();
1088     if (valueMapping.contains(dependency) || workList.contains(dependency) ||
1089         orderedSet.contains(dependency))
1090       continue;
1091     workList.insert(dependency);
1092   }
1093 
1094   return orderedSet;
1095 }
1096 
1097 FailureOr<Value> ModuleImport::convertConstant(llvm::Constant *constant) {
1098   Location loc = UnknownLoc::get(context);
1099 
1100   // Convert constants that can be represented as attributes.
1101   if (Attribute attr = getConstantAsAttr(constant)) {
1102     Type type = convertType(constant->getType());
1103     if (auto symbolRef = dyn_cast<FlatSymbolRefAttr>(attr)) {
1104       return builder.create<AddressOfOp>(loc, type, symbolRef.getValue())
1105           .getResult();
1106     }
1107     return builder.create<ConstantOp>(loc, type, attr).getResult();
1108   }
1109 
1110   // Convert null pointer constants.
1111   if (auto *nullPtr = dyn_cast<llvm::ConstantPointerNull>(constant)) {
1112     Type type = convertType(nullPtr->getType());
1113     return builder.create<ZeroOp>(loc, type).getResult();
1114   }
1115 
1116   // Convert none token constants.
1117   if (isa<llvm::ConstantTokenNone>(constant)) {
1118     return builder.create<NoneTokenOp>(loc).getResult();
1119   }
1120 
1121   // Convert poison.
1122   if (auto *poisonVal = dyn_cast<llvm::PoisonValue>(constant)) {
1123     Type type = convertType(poisonVal->getType());
1124     return builder.create<PoisonOp>(loc, type).getResult();
1125   }
1126 
1127   // Convert undef.
1128   if (auto *undefVal = dyn_cast<llvm::UndefValue>(constant)) {
1129     Type type = convertType(undefVal->getType());
1130     return builder.create<UndefOp>(loc, type).getResult();
1131   }
1132 
1133   // Convert global variable accesses.
1134   if (auto *globalObj = dyn_cast<llvm::GlobalObject>(constant)) {
1135     Type type = convertType(globalObj->getType());
1136     StringRef globalName = globalObj->getName();
1137     FlatSymbolRefAttr symbolRef;
1138     // Empty names are only allowed for global variables.
1139     if (globalName.empty())
1140       symbolRef =
1141           getOrCreateNamelessSymbolName(cast<llvm::GlobalVariable>(globalObj));
1142     else
1143       symbolRef = FlatSymbolRefAttr::get(context, globalName);
1144     return builder.create<AddressOfOp>(loc, type, symbolRef).getResult();
1145   }
1146 
1147   // Convert constant expressions.
1148   if (auto *constExpr = dyn_cast<llvm::ConstantExpr>(constant)) {
1149     // Convert the constant expression to a temporary LLVM instruction and
1150     // translate it using the `processInstruction` method. Delete the
1151     // instruction after the translation and remove it from `valueMapping`,
1152     // since later calls to `getAsInstruction` may return the same address
1153     // resulting in a conflicting `valueMapping` entry.
1154     llvm::Instruction *inst = constExpr->getAsInstruction();
1155     auto guard = llvm::make_scope_exit([&]() {
1156       assert(!noResultOpMapping.contains(inst) &&
1157              "expected constant expression to return a result");
1158       valueMapping.erase(inst);
1159       inst->deleteValue();
1160     });
1161     // Note: `processInstruction` does not call `convertConstant` recursively
1162     // since all constant dependencies have been converted before.
1163     assert(llvm::all_of(inst->operands(), [&](llvm::Value *value) {
1164       return valueMapping.contains(value);
1165     }));
1166     if (failed(processInstruction(inst)))
1167       return failure();
1168     return lookupValue(inst);
1169   }
1170 
1171   // Convert aggregate constants.
1172   if (isa<llvm::ConstantAggregate>(constant) ||
1173       isa<llvm::ConstantAggregateZero>(constant)) {
1174     // Lookup the aggregate elements that have been converted before.
1175     SmallVector<Value> elementValues;
1176     if (auto *constAgg = dyn_cast<llvm::ConstantAggregate>(constant)) {
1177       elementValues.reserve(constAgg->getNumOperands());
1178       for (llvm::Value *operand : constAgg->operands())
1179         elementValues.push_back(lookupValue(operand));
1180     }
1181     if (auto *constAgg = dyn_cast<llvm::ConstantAggregateZero>(constant)) {
1182       unsigned numElements = constAgg->getElementCount().getFixedValue();
1183       elementValues.reserve(numElements);
1184       for (unsigned i = 0, e = numElements; i != e; ++i)
1185         elementValues.push_back(lookupValue(constAgg->getElementValue(i)));
1186     }
1187     assert(llvm::count(elementValues, nullptr) == 0 &&
1188            "expected all elements have been converted before");
1189 
1190     // Generate an UndefOp as root value and insert the aggregate elements.
1191     Type rootType = convertType(constant->getType());
1192     bool isArrayOrStruct = isa<LLVMArrayType, LLVMStructType>(rootType);
1193     assert((isArrayOrStruct || LLVM::isCompatibleVectorType(rootType)) &&
1194            "unrecognized aggregate type");
1195     Value root = builder.create<UndefOp>(loc, rootType);
1196     for (const auto &it : llvm::enumerate(elementValues)) {
1197       if (isArrayOrStruct) {
1198         root = builder.create<InsertValueOp>(loc, root, it.value(), it.index());
1199       } else {
1200         Attribute indexAttr = builder.getI32IntegerAttr(it.index());
1201         Value indexValue =
1202             builder.create<ConstantOp>(loc, builder.getI32Type(), indexAttr);
1203         root = builder.create<InsertElementOp>(loc, rootType, root, it.value(),
1204                                                indexValue);
1205       }
1206     }
1207     return root;
1208   }
1209 
1210   if (auto *constTargetNone = dyn_cast<llvm::ConstantTargetNone>(constant)) {
1211     LLVMTargetExtType targetExtType =
1212         cast<LLVMTargetExtType>(convertType(constTargetNone->getType()));
1213     assert(targetExtType.hasProperty(LLVMTargetExtType::HasZeroInit) &&
1214            "target extension type does not support zero-initialization");
1215     // Create llvm.mlir.zero operation to represent zero-initialization of
1216     // target extension type.
1217     return builder.create<LLVM::ZeroOp>(loc, targetExtType).getRes();
1218   }
1219 
1220   StringRef error = "";
1221   if (isa<llvm::BlockAddress>(constant))
1222     error = " since blockaddress(...) is unsupported";
1223 
1224   return emitError(loc) << "unhandled constant: " << diag(*constant) << error;
1225 }
1226 
1227 FailureOr<Value> ModuleImport::convertConstantExpr(llvm::Constant *constant) {
1228   // Only call the function for constants that have not been translated before
1229   // since it updates the constant insertion point assuming the converted
1230   // constant has been introduced at the end of the constant section.
1231   assert(!valueMapping.contains(constant) &&
1232          "expected constant has not been converted before");
1233   assert(constantInsertionBlock &&
1234          "expected the constant insertion block to be non-null");
1235 
1236   // Insert the constant after the last one or at the start of the entry block.
1237   OpBuilder::InsertionGuard guard(builder);
1238   if (!constantInsertionOp)
1239     builder.setInsertionPointToStart(constantInsertionBlock);
1240   else
1241     builder.setInsertionPointAfter(constantInsertionOp);
1242 
1243   // Convert all constants of the expression and add them to `valueMapping`.
1244   SetVector<llvm::Constant *> constantsToConvert =
1245       getConstantsToConvert(constant);
1246   for (llvm::Constant *constantToConvert : constantsToConvert) {
1247     FailureOr<Value> converted = convertConstant(constantToConvert);
1248     if (failed(converted))
1249       return failure();
1250     mapValue(constantToConvert, *converted);
1251   }
1252 
1253   // Update the constant insertion point and return the converted constant.
1254   Value result = lookupValue(constant);
1255   constantInsertionOp = result.getDefiningOp();
1256   return result;
1257 }
1258 
1259 FailureOr<Value> ModuleImport::convertValue(llvm::Value *value) {
1260   assert(!isa<llvm::MetadataAsValue>(value) &&
1261          "expected value to not be metadata");
1262 
1263   // Return the mapped value if it has been converted before.
1264   auto it = valueMapping.find(value);
1265   if (it != valueMapping.end())
1266     return it->getSecond();
1267 
1268   // Convert constants such as immediate values that have no mapping yet.
1269   if (auto *constant = dyn_cast<llvm::Constant>(value))
1270     return convertConstantExpr(constant);
1271 
1272   Location loc = UnknownLoc::get(context);
1273   if (auto *inst = dyn_cast<llvm::Instruction>(value))
1274     loc = translateLoc(inst->getDebugLoc());
1275   return emitError(loc) << "unhandled value: " << diag(*value);
1276 }
1277 
1278 FailureOr<Value> ModuleImport::convertMetadataValue(llvm::Value *value) {
1279   // A value may be wrapped as metadata, for example, when passed to a debug
1280   // intrinsic. Unwrap these values before the conversion.
1281   auto *nodeAsVal = dyn_cast<llvm::MetadataAsValue>(value);
1282   if (!nodeAsVal)
1283     return failure();
1284   auto *node = dyn_cast<llvm::ValueAsMetadata>(nodeAsVal->getMetadata());
1285   if (!node)
1286     return failure();
1287   value = node->getValue();
1288 
1289   // Return the mapped value if it has been converted before.
1290   auto it = valueMapping.find(value);
1291   if (it != valueMapping.end())
1292     return it->getSecond();
1293 
1294   // Convert constants such as immediate values that have no mapping yet.
1295   if (auto *constant = dyn_cast<llvm::Constant>(value))
1296     return convertConstantExpr(constant);
1297   return failure();
1298 }
1299 
1300 FailureOr<SmallVector<Value>>
1301 ModuleImport::convertValues(ArrayRef<llvm::Value *> values) {
1302   SmallVector<Value> remapped;
1303   remapped.reserve(values.size());
1304   for (llvm::Value *value : values) {
1305     FailureOr<Value> converted = convertValue(value);
1306     if (failed(converted))
1307       return failure();
1308     remapped.push_back(*converted);
1309   }
1310   return remapped;
1311 }
1312 
1313 LogicalResult ModuleImport::convertIntrinsicArguments(
1314     ArrayRef<llvm::Value *> values, ArrayRef<llvm::OperandBundleUse> opBundles,
1315     bool requiresOpBundles, ArrayRef<unsigned> immArgPositions,
1316     ArrayRef<StringLiteral> immArgAttrNames, SmallVectorImpl<Value> &valuesOut,
1317     SmallVectorImpl<NamedAttribute> &attrsOut) {
1318   assert(immArgPositions.size() == immArgAttrNames.size() &&
1319          "LLVM `immArgPositions` and MLIR `immArgAttrNames` should have equal "
1320          "length");
1321 
1322   SmallVector<llvm::Value *> operands(values);
1323   for (auto [immArgPos, immArgName] :
1324        llvm::zip(immArgPositions, immArgAttrNames)) {
1325     auto &value = operands[immArgPos];
1326     auto *constant = llvm::cast<llvm::Constant>(value);
1327     auto attr = getScalarConstantAsAttr(builder, constant);
1328     assert(attr && attr.getType().isIntOrFloat() &&
1329            "expected immarg to be float or integer constant");
1330     auto nameAttr = StringAttr::get(attr.getContext(), immArgName);
1331     attrsOut.push_back({nameAttr, attr});
1332     // Mark matched attribute values as null (so they can be removed below).
1333     value = nullptr;
1334   }
1335 
1336   for (llvm::Value *value : operands) {
1337     if (!value)
1338       continue;
1339     auto mlirValue = convertValue(value);
1340     if (failed(mlirValue))
1341       return failure();
1342     valuesOut.push_back(*mlirValue);
1343   }
1344 
1345   SmallVector<int> opBundleSizes;
1346   SmallVector<Attribute> opBundleTagAttrs;
1347   if (requiresOpBundles) {
1348     opBundleSizes.reserve(opBundles.size());
1349     opBundleTagAttrs.reserve(opBundles.size());
1350 
1351     for (const llvm::OperandBundleUse &bundle : opBundles) {
1352       opBundleSizes.push_back(bundle.Inputs.size());
1353       opBundleTagAttrs.push_back(StringAttr::get(context, bundle.getTagName()));
1354 
1355       for (const llvm::Use &opBundleOperand : bundle.Inputs) {
1356         auto operandMlirValue = convertValue(opBundleOperand.get());
1357         if (failed(operandMlirValue))
1358           return failure();
1359         valuesOut.push_back(*operandMlirValue);
1360       }
1361     }
1362 
1363     auto opBundleSizesAttr = DenseI32ArrayAttr::get(context, opBundleSizes);
1364     auto opBundleSizesAttrNameAttr =
1365         StringAttr::get(context, LLVMDialect::getOpBundleSizesAttrName());
1366     attrsOut.push_back({opBundleSizesAttrNameAttr, opBundleSizesAttr});
1367 
1368     auto opBundleTagsAttr = ArrayAttr::get(context, opBundleTagAttrs);
1369     auto opBundleTagsAttrNameAttr =
1370         StringAttr::get(context, LLVMDialect::getOpBundleTagsAttrName());
1371     attrsOut.push_back({opBundleTagsAttrNameAttr, opBundleTagsAttr});
1372   }
1373 
1374   return success();
1375 }
1376 
1377 IntegerAttr ModuleImport::matchIntegerAttr(llvm::Value *value) {
1378   IntegerAttr integerAttr;
1379   FailureOr<Value> converted = convertValue(value);
1380   bool success = succeeded(converted) &&
1381                  matchPattern(*converted, m_Constant(&integerAttr));
1382   assert(success && "expected a constant integer value");
1383   (void)success;
1384   return integerAttr;
1385 }
1386 
1387 FloatAttr ModuleImport::matchFloatAttr(llvm::Value *value) {
1388   FloatAttr floatAttr;
1389   FailureOr<Value> converted = convertValue(value);
1390   bool success =
1391       succeeded(converted) && matchPattern(*converted, m_Constant(&floatAttr));
1392   assert(success && "expected a constant float value");
1393   (void)success;
1394   return floatAttr;
1395 }
1396 
1397 DILocalVariableAttr ModuleImport::matchLocalVariableAttr(llvm::Value *value) {
1398   auto *nodeAsVal = cast<llvm::MetadataAsValue>(value);
1399   auto *node = cast<llvm::DILocalVariable>(nodeAsVal->getMetadata());
1400   return debugImporter->translate(node);
1401 }
1402 
1403 DILabelAttr ModuleImport::matchLabelAttr(llvm::Value *value) {
1404   auto *nodeAsVal = cast<llvm::MetadataAsValue>(value);
1405   auto *node = cast<llvm::DILabel>(nodeAsVal->getMetadata());
1406   return debugImporter->translate(node);
1407 }
1408 
1409 FPExceptionBehaviorAttr
1410 ModuleImport::matchFPExceptionBehaviorAttr(llvm::Value *value) {
1411   auto *metadata = cast<llvm::MetadataAsValue>(value);
1412   auto *mdstr = cast<llvm::MDString>(metadata->getMetadata());
1413   std::optional<llvm::fp::ExceptionBehavior> optLLVM =
1414       llvm::convertStrToExceptionBehavior(mdstr->getString());
1415   assert(optLLVM && "Expecting FP exception behavior");
1416   return builder.getAttr<FPExceptionBehaviorAttr>(
1417       convertFPExceptionBehaviorFromLLVM(*optLLVM));
1418 }
1419 
1420 RoundingModeAttr ModuleImport::matchRoundingModeAttr(llvm::Value *value) {
1421   auto *metadata = cast<llvm::MetadataAsValue>(value);
1422   auto *mdstr = cast<llvm::MDString>(metadata->getMetadata());
1423   std::optional<llvm::RoundingMode> optLLVM =
1424       llvm::convertStrToRoundingMode(mdstr->getString());
1425   assert(optLLVM && "Expecting rounding mode");
1426   return builder.getAttr<RoundingModeAttr>(
1427       convertRoundingModeFromLLVM(*optLLVM));
1428 }
1429 
1430 FailureOr<SmallVector<AliasScopeAttr>>
1431 ModuleImport::matchAliasScopeAttrs(llvm::Value *value) {
1432   auto *nodeAsVal = cast<llvm::MetadataAsValue>(value);
1433   auto *node = cast<llvm::MDNode>(nodeAsVal->getMetadata());
1434   return lookupAliasScopeAttrs(node);
1435 }
1436 
1437 Location ModuleImport::translateLoc(llvm::DILocation *loc) {
1438   return debugImporter->translateLoc(loc);
1439 }
1440 
1441 LogicalResult
1442 ModuleImport::convertBranchArgs(llvm::Instruction *branch,
1443                                 llvm::BasicBlock *target,
1444                                 SmallVectorImpl<Value> &blockArguments) {
1445   for (auto inst = target->begin(); isa<llvm::PHINode>(inst); ++inst) {
1446     auto *phiInst = cast<llvm::PHINode>(&*inst);
1447     llvm::Value *value = phiInst->getIncomingValueForBlock(branch->getParent());
1448     FailureOr<Value> converted = convertValue(value);
1449     if (failed(converted))
1450       return failure();
1451     blockArguments.push_back(*converted);
1452   }
1453   return success();
1454 }
1455 
1456 LogicalResult
1457 ModuleImport::convertCallTypeAndOperands(llvm::CallBase *callInst,
1458                                          SmallVectorImpl<Type> &types,
1459                                          SmallVectorImpl<Value> &operands) {
1460   if (!callInst->getType()->isVoidTy())
1461     types.push_back(convertType(callInst->getType()));
1462 
1463   if (!callInst->getCalledFunction()) {
1464     FailureOr<Value> called = convertValue(callInst->getCalledOperand());
1465     if (failed(called))
1466       return failure();
1467     operands.push_back(*called);
1468   }
1469   SmallVector<llvm::Value *> args(callInst->args());
1470   FailureOr<SmallVector<Value>> arguments = convertValues(args);
1471   if (failed(arguments))
1472     return failure();
1473   llvm::append_range(operands, *arguments);
1474   return success();
1475 }
1476 
1477 LogicalResult ModuleImport::convertIntrinsic(llvm::CallInst *inst) {
1478   if (succeeded(iface.convertIntrinsic(builder, inst, *this)))
1479     return success();
1480 
1481   Location loc = translateLoc(inst->getDebugLoc());
1482   return emitError(loc) << "unhandled intrinsic: " << diag(*inst);
1483 }
1484 
1485 LogicalResult ModuleImport::convertInstruction(llvm::Instruction *inst) {
1486   // Convert all instructions that do not provide an MLIR builder.
1487   Location loc = translateLoc(inst->getDebugLoc());
1488   if (inst->getOpcode() == llvm::Instruction::Br) {
1489     auto *brInst = cast<llvm::BranchInst>(inst);
1490 
1491     SmallVector<Block *> succBlocks;
1492     SmallVector<SmallVector<Value>> succBlockArgs;
1493     for (auto i : llvm::seq<unsigned>(0, brInst->getNumSuccessors())) {
1494       llvm::BasicBlock *succ = brInst->getSuccessor(i);
1495       SmallVector<Value> blockArgs;
1496       if (failed(convertBranchArgs(brInst, succ, blockArgs)))
1497         return failure();
1498       succBlocks.push_back(lookupBlock(succ));
1499       succBlockArgs.push_back(blockArgs);
1500     }
1501 
1502     if (!brInst->isConditional()) {
1503       auto brOp = builder.create<LLVM::BrOp>(loc, succBlockArgs.front(),
1504                                              succBlocks.front());
1505       mapNoResultOp(inst, brOp);
1506       return success();
1507     }
1508     FailureOr<Value> condition = convertValue(brInst->getCondition());
1509     if (failed(condition))
1510       return failure();
1511     auto condBrOp = builder.create<LLVM::CondBrOp>(
1512         loc, *condition, succBlocks.front(), succBlockArgs.front(),
1513         succBlocks.back(), succBlockArgs.back());
1514     mapNoResultOp(inst, condBrOp);
1515     return success();
1516   }
1517   if (inst->getOpcode() == llvm::Instruction::Switch) {
1518     auto *swInst = cast<llvm::SwitchInst>(inst);
1519     // Process the condition value.
1520     FailureOr<Value> condition = convertValue(swInst->getCondition());
1521     if (failed(condition))
1522       return failure();
1523     SmallVector<Value> defaultBlockArgs;
1524     // Process the default case.
1525     llvm::BasicBlock *defaultBB = swInst->getDefaultDest();
1526     if (failed(convertBranchArgs(swInst, defaultBB, defaultBlockArgs)))
1527       return failure();
1528 
1529     // Process the cases.
1530     unsigned numCases = swInst->getNumCases();
1531     SmallVector<SmallVector<Value>> caseOperands(numCases);
1532     SmallVector<ValueRange> caseOperandRefs(numCases);
1533     SmallVector<APInt> caseValues(numCases);
1534     SmallVector<Block *> caseBlocks(numCases);
1535     for (const auto &it : llvm::enumerate(swInst->cases())) {
1536       const llvm::SwitchInst::CaseHandle &caseHandle = it.value();
1537       llvm::BasicBlock *succBB = caseHandle.getCaseSuccessor();
1538       if (failed(convertBranchArgs(swInst, succBB, caseOperands[it.index()])))
1539         return failure();
1540       caseOperandRefs[it.index()] = caseOperands[it.index()];
1541       caseValues[it.index()] = caseHandle.getCaseValue()->getValue();
1542       caseBlocks[it.index()] = lookupBlock(succBB);
1543     }
1544 
1545     auto switchOp = builder.create<SwitchOp>(
1546         loc, *condition, lookupBlock(defaultBB), defaultBlockArgs, caseValues,
1547         caseBlocks, caseOperandRefs);
1548     mapNoResultOp(inst, switchOp);
1549     return success();
1550   }
1551   if (inst->getOpcode() == llvm::Instruction::PHI) {
1552     Type type = convertType(inst->getType());
1553     mapValue(inst, builder.getInsertionBlock()->addArgument(
1554                        type, translateLoc(inst->getDebugLoc())));
1555     return success();
1556   }
1557   if (inst->getOpcode() == llvm::Instruction::Call) {
1558     auto *callInst = cast<llvm::CallInst>(inst);
1559 
1560     SmallVector<Type> types;
1561     SmallVector<Value> operands;
1562     if (failed(convertCallTypeAndOperands(callInst, types, operands)))
1563       return failure();
1564 
1565     auto funcTy =
1566         dyn_cast<LLVMFunctionType>(convertType(callInst->getFunctionType()));
1567     if (!funcTy)
1568       return failure();
1569 
1570     CallOp callOp;
1571 
1572     if (llvm::Function *callee = callInst->getCalledFunction()) {
1573       callOp = builder.create<CallOp>(
1574           loc, funcTy, SymbolRefAttr::get(context, callee->getName()),
1575           operands);
1576     } else {
1577       callOp = builder.create<CallOp>(loc, funcTy, operands);
1578     }
1579     callOp.setCConv(convertCConvFromLLVM(callInst->getCallingConv()));
1580     callOp.setTailCallKind(
1581         convertTailCallKindFromLLVM(callInst->getTailCallKind()));
1582     setFastmathFlagsAttr(inst, callOp);
1583 
1584     // Handle function attributes.
1585     if (callInst->hasFnAttr(llvm::Attribute::Convergent))
1586       callOp.setConvergent(true);
1587     if (callInst->hasFnAttr(llvm::Attribute::NoUnwind))
1588       callOp.setNoUnwind(true);
1589     if (callInst->hasFnAttr(llvm::Attribute::WillReturn))
1590       callOp.setWillReturn(true);
1591 
1592     llvm::MemoryEffects memEffects = callInst->getMemoryEffects();
1593     ModRefInfo othermem = convertModRefInfoFromLLVM(
1594         memEffects.getModRef(llvm::MemoryEffects::Location::Other));
1595     ModRefInfo argMem = convertModRefInfoFromLLVM(
1596         memEffects.getModRef(llvm::MemoryEffects::Location::ArgMem));
1597     ModRefInfo inaccessibleMem = convertModRefInfoFromLLVM(
1598         memEffects.getModRef(llvm::MemoryEffects::Location::InaccessibleMem));
1599     auto memAttr = MemoryEffectsAttr::get(callOp.getContext(), othermem, argMem,
1600                                           inaccessibleMem);
1601     // Only set the attribute when it does not match the default value.
1602     if (!memAttr.isReadWrite())
1603       callOp.setMemoryEffectsAttr(memAttr);
1604 
1605     if (!callInst->getType()->isVoidTy())
1606       mapValue(inst, callOp.getResult());
1607     else
1608       mapNoResultOp(inst, callOp);
1609     return success();
1610   }
1611   if (inst->getOpcode() == llvm::Instruction::LandingPad) {
1612     auto *lpInst = cast<llvm::LandingPadInst>(inst);
1613 
1614     SmallVector<Value> operands;
1615     operands.reserve(lpInst->getNumClauses());
1616     for (auto i : llvm::seq<unsigned>(0, lpInst->getNumClauses())) {
1617       FailureOr<Value> operand = convertValue(lpInst->getClause(i));
1618       if (failed(operand))
1619         return failure();
1620       operands.push_back(*operand);
1621     }
1622 
1623     Type type = convertType(lpInst->getType());
1624     auto lpOp =
1625         builder.create<LandingpadOp>(loc, type, lpInst->isCleanup(), operands);
1626     mapValue(inst, lpOp);
1627     return success();
1628   }
1629   if (inst->getOpcode() == llvm::Instruction::Invoke) {
1630     auto *invokeInst = cast<llvm::InvokeInst>(inst);
1631 
1632     SmallVector<Type> types;
1633     SmallVector<Value> operands;
1634     if (failed(convertCallTypeAndOperands(invokeInst, types, operands)))
1635       return failure();
1636 
1637     // Check whether the invoke result is an argument to the normal destination
1638     // block.
1639     bool invokeResultUsedInPhi = llvm::any_of(
1640         invokeInst->getNormalDest()->phis(), [&](const llvm::PHINode &phi) {
1641           return phi.getIncomingValueForBlock(invokeInst->getParent()) ==
1642                  invokeInst;
1643         });
1644 
1645     Block *normalDest = lookupBlock(invokeInst->getNormalDest());
1646     Block *directNormalDest = normalDest;
1647     if (invokeResultUsedInPhi) {
1648       // The invoke result cannot be an argument to the normal destination
1649       // block, as that would imply using the invoke operation result in its
1650       // definition, so we need to create a dummy block to serve as an
1651       // intermediate destination.
1652       OpBuilder::InsertionGuard g(builder);
1653       directNormalDest = builder.createBlock(normalDest);
1654     }
1655 
1656     SmallVector<Value> unwindArgs;
1657     if (failed(convertBranchArgs(invokeInst, invokeInst->getUnwindDest(),
1658                                  unwindArgs)))
1659       return failure();
1660 
1661     auto funcTy =
1662         dyn_cast<LLVMFunctionType>(convertType(invokeInst->getFunctionType()));
1663     if (!funcTy)
1664       return failure();
1665 
1666     // Create the invoke operation. Normal destination block arguments will be
1667     // added later on to handle the case in which the operation result is
1668     // included in this list.
1669     InvokeOp invokeOp;
1670     if (llvm::Function *callee = invokeInst->getCalledFunction()) {
1671       invokeOp = builder.create<InvokeOp>(
1672           loc, funcTy,
1673           SymbolRefAttr::get(builder.getContext(), callee->getName()), operands,
1674           directNormalDest, ValueRange(),
1675           lookupBlock(invokeInst->getUnwindDest()), unwindArgs);
1676     } else {
1677       invokeOp = builder.create<InvokeOp>(
1678           loc, funcTy, /*callee=*/nullptr, operands, directNormalDest,
1679           ValueRange(), lookupBlock(invokeInst->getUnwindDest()), unwindArgs);
1680     }
1681     invokeOp.setCConv(convertCConvFromLLVM(invokeInst->getCallingConv()));
1682     if (!invokeInst->getType()->isVoidTy())
1683       mapValue(inst, invokeOp.getResults().front());
1684     else
1685       mapNoResultOp(inst, invokeOp);
1686 
1687     SmallVector<Value> normalArgs;
1688     if (failed(convertBranchArgs(invokeInst, invokeInst->getNormalDest(),
1689                                  normalArgs)))
1690       return failure();
1691 
1692     if (invokeResultUsedInPhi) {
1693       // The dummy normal dest block will just host an unconditional branch
1694       // instruction to the normal destination block passing the required block
1695       // arguments (including the invoke operation's result).
1696       OpBuilder::InsertionGuard g(builder);
1697       builder.setInsertionPointToStart(directNormalDest);
1698       builder.create<LLVM::BrOp>(loc, normalArgs, normalDest);
1699     } else {
1700       // If the invoke operation's result is not a block argument to the normal
1701       // destination block, just add the block arguments as usual.
1702       assert(llvm::none_of(
1703                  normalArgs,
1704                  [&](Value val) { return val.getDefiningOp() == invokeOp; }) &&
1705              "An llvm.invoke operation cannot pass its result as a block "
1706              "argument.");
1707       invokeOp.getNormalDestOperandsMutable().append(normalArgs);
1708     }
1709 
1710     return success();
1711   }
1712   if (inst->getOpcode() == llvm::Instruction::GetElementPtr) {
1713     auto *gepInst = cast<llvm::GetElementPtrInst>(inst);
1714     Type sourceElementType = convertType(gepInst->getSourceElementType());
1715     FailureOr<Value> basePtr = convertValue(gepInst->getOperand(0));
1716     if (failed(basePtr))
1717       return failure();
1718 
1719     // Treat every indices as dynamic since GEPOp::build will refine those
1720     // indices into static attributes later. One small downside of this
1721     // approach is that many unused `llvm.mlir.constant` would be emitted
1722     // at first place.
1723     SmallVector<GEPArg> indices;
1724     for (llvm::Value *operand : llvm::drop_begin(gepInst->operand_values())) {
1725       FailureOr<Value> index = convertValue(operand);
1726       if (failed(index))
1727         return failure();
1728       indices.push_back(*index);
1729     }
1730 
1731     Type type = convertType(inst->getType());
1732     auto gepOp = builder.create<GEPOp>(loc, type, sourceElementType, *basePtr,
1733                                        indices, gepInst->isInBounds());
1734     mapValue(inst, gepOp);
1735     return success();
1736   }
1737 
1738   // Convert all instructions that have an mlirBuilder.
1739   if (succeeded(convertInstructionImpl(builder, inst, *this, iface)))
1740     return success();
1741 
1742   return emitError(loc) << "unhandled instruction: " << diag(*inst);
1743 }
1744 
1745 LogicalResult ModuleImport::processInstruction(llvm::Instruction *inst) {
1746   // FIXME: Support uses of SubtargetData.
1747   // FIXME: Add support for call / operand attributes.
1748   // FIXME: Add support for the indirectbr, cleanupret, catchret, catchswitch,
1749   // callbr, vaarg, catchpad, cleanuppad instructions.
1750 
1751   // Convert LLVM intrinsics calls to MLIR intrinsics.
1752   if (auto *intrinsic = dyn_cast<llvm::IntrinsicInst>(inst))
1753     return convertIntrinsic(intrinsic);
1754 
1755   // Convert all remaining LLVM instructions to MLIR operations.
1756   return convertInstruction(inst);
1757 }
1758 
1759 FlatSymbolRefAttr ModuleImport::getPersonalityAsAttr(llvm::Function *f) {
1760   if (!f->hasPersonalityFn())
1761     return nullptr;
1762 
1763   llvm::Constant *pf = f->getPersonalityFn();
1764 
1765   // If it directly has a name, we can use it.
1766   if (pf->hasName())
1767     return SymbolRefAttr::get(builder.getContext(), pf->getName());
1768 
1769   // If it doesn't have a name, currently, only function pointers that are
1770   // bitcast to i8* are parsed.
1771   if (auto *ce = dyn_cast<llvm::ConstantExpr>(pf)) {
1772     if (ce->getOpcode() == llvm::Instruction::BitCast &&
1773         ce->getType() == llvm::PointerType::getUnqual(f->getContext())) {
1774       if (auto *func = dyn_cast<llvm::Function>(ce->getOperand(0)))
1775         return SymbolRefAttr::get(builder.getContext(), func->getName());
1776     }
1777   }
1778   return FlatSymbolRefAttr();
1779 }
1780 
1781 static void processMemoryEffects(llvm::Function *func, LLVMFuncOp funcOp) {
1782   llvm::MemoryEffects memEffects = func->getMemoryEffects();
1783 
1784   auto othermem = convertModRefInfoFromLLVM(
1785       memEffects.getModRef(llvm::MemoryEffects::Location::Other));
1786   auto argMem = convertModRefInfoFromLLVM(
1787       memEffects.getModRef(llvm::MemoryEffects::Location::ArgMem));
1788   auto inaccessibleMem = convertModRefInfoFromLLVM(
1789       memEffects.getModRef(llvm::MemoryEffects::Location::InaccessibleMem));
1790   auto memAttr = MemoryEffectsAttr::get(funcOp.getContext(), othermem, argMem,
1791                                         inaccessibleMem);
1792   // Only set the attr when it does not match the default value.
1793   if (memAttr.isReadWrite())
1794     return;
1795   funcOp.setMemoryEffectsAttr(memAttr);
1796 }
1797 
1798 // List of LLVM IR attributes that map to an explicit attribute on the MLIR
1799 // LLVMFuncOp.
1800 static constexpr std::array kExplicitAttributes{
1801     StringLiteral("aarch64_in_za"),
1802     StringLiteral("aarch64_inout_za"),
1803     StringLiteral("aarch64_new_za"),
1804     StringLiteral("aarch64_out_za"),
1805     StringLiteral("aarch64_preserves_za"),
1806     StringLiteral("aarch64_pstate_sm_body"),
1807     StringLiteral("aarch64_pstate_sm_compatible"),
1808     StringLiteral("aarch64_pstate_sm_enabled"),
1809     StringLiteral("alwaysinline"),
1810     StringLiteral("approx-func-fp-math"),
1811     StringLiteral("convergent"),
1812     StringLiteral("denormal-fp-math"),
1813     StringLiteral("denormal-fp-math-f32"),
1814     StringLiteral("fp-contract"),
1815     StringLiteral("frame-pointer"),
1816     StringLiteral("no-infs-fp-math"),
1817     StringLiteral("no-nans-fp-math"),
1818     StringLiteral("no-signed-zeros-fp-math"),
1819     StringLiteral("noinline"),
1820     StringLiteral("nounwind"),
1821     StringLiteral("optnone"),
1822     StringLiteral("target-features"),
1823     StringLiteral("tune-cpu"),
1824     StringLiteral("unsafe-fp-math"),
1825     StringLiteral("vscale_range"),
1826     StringLiteral("willreturn"),
1827 };
1828 
1829 static void processPassthroughAttrs(llvm::Function *func, LLVMFuncOp funcOp) {
1830   MLIRContext *context = funcOp.getContext();
1831   SmallVector<Attribute> passthroughs;
1832   llvm::AttributeSet funcAttrs = func->getAttributes().getAttributes(
1833       llvm::AttributeList::AttrIndex::FunctionIndex);
1834   for (llvm::Attribute attr : funcAttrs) {
1835     // Skip the memory attribute since the LLVMFuncOp has an explicit memory
1836     // attribute.
1837     if (attr.hasAttribute(llvm::Attribute::Memory))
1838       continue;
1839 
1840     // Skip invalid type attributes.
1841     if (attr.isTypeAttribute()) {
1842       emitWarning(funcOp.getLoc(),
1843                   "type attributes on a function are invalid, skipping it");
1844       continue;
1845     }
1846 
1847     StringRef attrName;
1848     if (attr.isStringAttribute())
1849       attrName = attr.getKindAsString();
1850     else
1851       attrName = llvm::Attribute::getNameFromAttrKind(attr.getKindAsEnum());
1852     auto keyAttr = StringAttr::get(context, attrName);
1853 
1854     // Skip attributes that map to an explicit attribute on the LLVMFuncOp.
1855     if (llvm::is_contained(kExplicitAttributes, attrName))
1856       continue;
1857 
1858     if (attr.isStringAttribute()) {
1859       StringRef val = attr.getValueAsString();
1860       if (val.empty()) {
1861         passthroughs.push_back(keyAttr);
1862         continue;
1863       }
1864       passthroughs.push_back(
1865           ArrayAttr::get(context, {keyAttr, StringAttr::get(context, val)}));
1866       continue;
1867     }
1868     if (attr.isIntAttribute()) {
1869       auto val = std::to_string(attr.getValueAsInt());
1870       passthroughs.push_back(
1871           ArrayAttr::get(context, {keyAttr, StringAttr::get(context, val)}));
1872       continue;
1873     }
1874     if (attr.isEnumAttribute()) {
1875       passthroughs.push_back(keyAttr);
1876       continue;
1877     }
1878 
1879     llvm_unreachable("unexpected attribute kind");
1880   }
1881 
1882   if (!passthroughs.empty())
1883     funcOp.setPassthroughAttr(ArrayAttr::get(context, passthroughs));
1884 }
1885 
1886 void ModuleImport::processFunctionAttributes(llvm::Function *func,
1887                                              LLVMFuncOp funcOp) {
1888   processMemoryEffects(func, funcOp);
1889   processPassthroughAttrs(func, funcOp);
1890 
1891   if (func->hasFnAttribute(llvm::Attribute::NoInline))
1892     funcOp.setNoInline(true);
1893   if (func->hasFnAttribute(llvm::Attribute::AlwaysInline))
1894     funcOp.setAlwaysInline(true);
1895   if (func->hasFnAttribute(llvm::Attribute::OptimizeNone))
1896     funcOp.setOptimizeNone(true);
1897   if (func->hasFnAttribute(llvm::Attribute::Convergent))
1898     funcOp.setConvergent(true);
1899   if (func->hasFnAttribute(llvm::Attribute::NoUnwind))
1900     funcOp.setNoUnwind(true);
1901   if (func->hasFnAttribute(llvm::Attribute::WillReturn))
1902     funcOp.setWillReturn(true);
1903 
1904   if (func->hasFnAttribute("aarch64_pstate_sm_enabled"))
1905     funcOp.setArmStreaming(true);
1906   else if (func->hasFnAttribute("aarch64_pstate_sm_body"))
1907     funcOp.setArmLocallyStreaming(true);
1908   else if (func->hasFnAttribute("aarch64_pstate_sm_compatible"))
1909     funcOp.setArmStreamingCompatible(true);
1910 
1911   if (func->hasFnAttribute("aarch64_new_za"))
1912     funcOp.setArmNewZa(true);
1913   else if (func->hasFnAttribute("aarch64_in_za"))
1914     funcOp.setArmInZa(true);
1915   else if (func->hasFnAttribute("aarch64_out_za"))
1916     funcOp.setArmOutZa(true);
1917   else if (func->hasFnAttribute("aarch64_inout_za"))
1918     funcOp.setArmInoutZa(true);
1919   else if (func->hasFnAttribute("aarch64_preserves_za"))
1920     funcOp.setArmPreservesZa(true);
1921 
1922   llvm::Attribute attr = func->getFnAttribute(llvm::Attribute::VScaleRange);
1923   if (attr.isValid()) {
1924     MLIRContext *context = funcOp.getContext();
1925     auto intTy = IntegerType::get(context, 32);
1926     funcOp.setVscaleRangeAttr(LLVM::VScaleRangeAttr::get(
1927         context, IntegerAttr::get(intTy, attr.getVScaleRangeMin()),
1928         IntegerAttr::get(intTy, attr.getVScaleRangeMax().value_or(0))));
1929   }
1930 
1931   // Process frame-pointer attribute.
1932   if (func->hasFnAttribute("frame-pointer")) {
1933     StringRef stringRefFramePointerKind =
1934         func->getFnAttribute("frame-pointer").getValueAsString();
1935     funcOp.setFramePointerAttr(LLVM::FramePointerKindAttr::get(
1936         funcOp.getContext(), LLVM::framePointerKind::symbolizeFramePointerKind(
1937                                  stringRefFramePointerKind)
1938                                  .value()));
1939   }
1940 
1941   if (llvm::Attribute attr = func->getFnAttribute("target-cpu");
1942       attr.isStringAttribute())
1943     funcOp.setTargetCpuAttr(StringAttr::get(context, attr.getValueAsString()));
1944 
1945   if (llvm::Attribute attr = func->getFnAttribute("tune-cpu");
1946       attr.isStringAttribute())
1947     funcOp.setTuneCpuAttr(StringAttr::get(context, attr.getValueAsString()));
1948 
1949   if (llvm::Attribute attr = func->getFnAttribute("target-features");
1950       attr.isStringAttribute())
1951     funcOp.setTargetFeaturesAttr(
1952         LLVM::TargetFeaturesAttr::get(context, attr.getValueAsString()));
1953 
1954   if (llvm::Attribute attr = func->getFnAttribute("unsafe-fp-math");
1955       attr.isStringAttribute())
1956     funcOp.setUnsafeFpMath(attr.getValueAsBool());
1957 
1958   if (llvm::Attribute attr = func->getFnAttribute("no-infs-fp-math");
1959       attr.isStringAttribute())
1960     funcOp.setNoInfsFpMath(attr.getValueAsBool());
1961 
1962   if (llvm::Attribute attr = func->getFnAttribute("no-nans-fp-math");
1963       attr.isStringAttribute())
1964     funcOp.setNoNansFpMath(attr.getValueAsBool());
1965 
1966   if (llvm::Attribute attr = func->getFnAttribute("approx-func-fp-math");
1967       attr.isStringAttribute())
1968     funcOp.setApproxFuncFpMath(attr.getValueAsBool());
1969 
1970   if (llvm::Attribute attr = func->getFnAttribute("no-signed-zeros-fp-math");
1971       attr.isStringAttribute())
1972     funcOp.setNoSignedZerosFpMath(attr.getValueAsBool());
1973 
1974   if (llvm::Attribute attr = func->getFnAttribute("denormal-fp-math");
1975       attr.isStringAttribute())
1976     funcOp.setDenormalFpMathAttr(
1977         StringAttr::get(context, attr.getValueAsString()));
1978 
1979   if (llvm::Attribute attr = func->getFnAttribute("denormal-fp-math-f32");
1980       attr.isStringAttribute())
1981     funcOp.setDenormalFpMathF32Attr(
1982         StringAttr::get(context, attr.getValueAsString()));
1983 
1984   if (llvm::Attribute attr = func->getFnAttribute("fp-contract");
1985       attr.isStringAttribute())
1986     funcOp.setFpContractAttr(StringAttr::get(context, attr.getValueAsString()));
1987 }
1988 
1989 DictionaryAttr
1990 ModuleImport::convertParameterAttribute(llvm::AttributeSet llvmParamAttrs,
1991                                         OpBuilder &builder) {
1992   SmallVector<NamedAttribute> paramAttrs;
1993   for (auto [llvmKind, mlirName] : getAttrKindToNameMapping()) {
1994     auto llvmAttr = llvmParamAttrs.getAttribute(llvmKind);
1995     // Skip attributes that are not attached.
1996     if (!llvmAttr.isValid())
1997       continue;
1998     Attribute mlirAttr;
1999     if (llvmAttr.isTypeAttribute())
2000       mlirAttr = TypeAttr::get(convertType(llvmAttr.getValueAsType()));
2001     else if (llvmAttr.isIntAttribute())
2002       mlirAttr = builder.getI64IntegerAttr(llvmAttr.getValueAsInt());
2003     else if (llvmAttr.isEnumAttribute())
2004       mlirAttr = builder.getUnitAttr();
2005     else
2006       llvm_unreachable("unexpected parameter attribute kind");
2007     paramAttrs.push_back(builder.getNamedAttr(mlirName, mlirAttr));
2008   }
2009 
2010   return builder.getDictionaryAttr(paramAttrs);
2011 }
2012 
2013 void ModuleImport::convertParameterAttributes(llvm::Function *func,
2014                                               LLVMFuncOp funcOp,
2015                                               OpBuilder &builder) {
2016   auto llvmAttrs = func->getAttributes();
2017   for (size_t i = 0, e = funcOp.getNumArguments(); i < e; ++i) {
2018     llvm::AttributeSet llvmArgAttrs = llvmAttrs.getParamAttrs(i);
2019     funcOp.setArgAttrs(i, convertParameterAttribute(llvmArgAttrs, builder));
2020   }
2021   // Convert the result attributes and attach them wrapped in an ArrayAttribute
2022   // to the funcOp.
2023   llvm::AttributeSet llvmResAttr = llvmAttrs.getRetAttrs();
2024   if (!llvmResAttr.hasAttributes())
2025     return;
2026   funcOp.setResAttrsAttr(
2027       builder.getArrayAttr(convertParameterAttribute(llvmResAttr, builder)));
2028 }
2029 
2030 LogicalResult ModuleImport::processFunction(llvm::Function *func) {
2031   clearRegionState();
2032 
2033   auto functionType =
2034       dyn_cast<LLVMFunctionType>(convertType(func->getFunctionType()));
2035   if (func->isIntrinsic() &&
2036       iface.isConvertibleIntrinsic(func->getIntrinsicID()))
2037     return success();
2038 
2039   bool dsoLocal = func->hasLocalLinkage();
2040   CConv cconv = convertCConvFromLLVM(func->getCallingConv());
2041 
2042   // Insert the function at the end of the module.
2043   OpBuilder::InsertionGuard guard(builder);
2044   builder.setInsertionPoint(mlirModule.getBody(), mlirModule.getBody()->end());
2045 
2046   Location loc = debugImporter->translateFuncLocation(func);
2047   LLVMFuncOp funcOp = builder.create<LLVMFuncOp>(
2048       loc, func->getName(), functionType,
2049       convertLinkageFromLLVM(func->getLinkage()), dsoLocal, cconv);
2050 
2051   convertParameterAttributes(func, funcOp, builder);
2052 
2053   if (FlatSymbolRefAttr personality = getPersonalityAsAttr(func))
2054     funcOp.setPersonalityAttr(personality);
2055   else if (func->hasPersonalityFn())
2056     emitWarning(funcOp.getLoc(), "could not deduce personality, skipping it");
2057 
2058   if (func->hasGC())
2059     funcOp.setGarbageCollector(StringRef(func->getGC()));
2060 
2061   if (func->hasAtLeastLocalUnnamedAddr())
2062     funcOp.setUnnamedAddr(convertUnnamedAddrFromLLVM(func->getUnnamedAddr()));
2063 
2064   if (func->hasSection())
2065     funcOp.setSection(StringRef(func->getSection()));
2066 
2067   funcOp.setVisibility_(convertVisibilityFromLLVM(func->getVisibility()));
2068 
2069   if (func->hasComdat())
2070     funcOp.setComdatAttr(comdatMapping.lookup(func->getComdat()));
2071 
2072   if (llvm::MaybeAlign maybeAlign = func->getAlign())
2073     funcOp.setAlignment(maybeAlign->value());
2074 
2075   // Handle Function attributes.
2076   processFunctionAttributes(func, funcOp);
2077 
2078   // Convert non-debug metadata by using the dialect interface.
2079   SmallVector<std::pair<unsigned, llvm::MDNode *>> allMetadata;
2080   func->getAllMetadata(allMetadata);
2081   for (auto &[kind, node] : allMetadata) {
2082     if (!iface.isConvertibleMetadata(kind))
2083       continue;
2084     if (failed(iface.setMetadataAttrs(builder, kind, node, funcOp, *this))) {
2085       emitWarning(funcOp.getLoc())
2086           << "unhandled function metadata: " << diagMD(node, llvmModule.get())
2087           << " on " << diag(*func);
2088     }
2089   }
2090 
2091   if (func->isDeclaration())
2092     return success();
2093 
2094   // Collect the set of basic blocks reachable from the function's entry block.
2095   // This step is crucial as LLVM IR can contain unreachable blocks that
2096   // self-dominate. As a result, an operation might utilize a variable it
2097   // defines, which the import does not support. Given that MLIR lacks block
2098   // label support, we can safely remove unreachable blocks, as there are no
2099   // indirect branch instructions that could potentially target these blocks.
2100   llvm::df_iterator_default_set<llvm::BasicBlock *> reachable;
2101   for (llvm::BasicBlock *basicBlock : llvm::depth_first_ext(func, reachable))
2102     (void)basicBlock;
2103 
2104   // Eagerly create all reachable blocks.
2105   SmallVector<llvm::BasicBlock *> reachableBasicBlocks;
2106   for (llvm::BasicBlock &basicBlock : *func) {
2107     // Skip unreachable blocks.
2108     if (!reachable.contains(&basicBlock))
2109       continue;
2110     Region &body = funcOp.getBody();
2111     Block *block = builder.createBlock(&body, body.end());
2112     mapBlock(&basicBlock, block);
2113     reachableBasicBlocks.push_back(&basicBlock);
2114   }
2115 
2116   // Add function arguments to the entry block.
2117   for (const auto &it : llvm::enumerate(func->args())) {
2118     BlockArgument blockArg = funcOp.getFunctionBody().addArgument(
2119         functionType.getParamType(it.index()), funcOp.getLoc());
2120     mapValue(&it.value(), blockArg);
2121   }
2122 
2123   // Process the blocks in topological order. The ordered traversal ensures
2124   // operands defined in a dominating block have a valid mapping to an MLIR
2125   // value once a block is translated.
2126   SetVector<llvm::BasicBlock *> blocks =
2127       getTopologicallySortedBlocks(reachableBasicBlocks);
2128   setConstantInsertionPointToStart(lookupBlock(blocks.front()));
2129   for (llvm::BasicBlock *basicBlock : blocks)
2130     if (failed(processBasicBlock(basicBlock, lookupBlock(basicBlock))))
2131       return failure();
2132 
2133   // Process the debug intrinsics that require a delayed conversion after
2134   // everything else was converted.
2135   if (failed(processDebugIntrinsics()))
2136     return failure();
2137 
2138   return success();
2139 }
2140 
2141 /// Checks if `dbgIntr` is a kill location that holds metadata instead of an SSA
2142 /// value.
2143 static bool isMetadataKillLocation(llvm::DbgVariableIntrinsic *dbgIntr) {
2144   if (!dbgIntr->isKillLocation())
2145     return false;
2146   llvm::Value *value = dbgIntr->getArgOperand(0);
2147   auto *nodeAsVal = dyn_cast<llvm::MetadataAsValue>(value);
2148   if (!nodeAsVal)
2149     return false;
2150   return !isa<llvm::ValueAsMetadata>(nodeAsVal->getMetadata());
2151 }
2152 
2153 LogicalResult
2154 ModuleImport::processDebugIntrinsic(llvm::DbgVariableIntrinsic *dbgIntr,
2155                                     DominanceInfo &domInfo) {
2156   Location loc = translateLoc(dbgIntr->getDebugLoc());
2157   auto emitUnsupportedWarning = [&]() {
2158     if (emitExpensiveWarnings)
2159       emitWarning(loc) << "dropped intrinsic: " << diag(*dbgIntr);
2160     return success();
2161   };
2162   // Drop debug intrinsics with arg lists.
2163   // TODO: Support debug intrinsics that have arg lists.
2164   if (dbgIntr->hasArgList())
2165     return emitUnsupportedWarning();
2166   // Kill locations can have metadata nodes as location operand. This
2167   // cannot be converted to poison as the type cannot be reconstructed.
2168   // TODO: find a way to support this case.
2169   if (isMetadataKillLocation(dbgIntr))
2170     return emitUnsupportedWarning();
2171   // Drop debug intrinsics if the associated variable information cannot be
2172   // translated due to cyclic debug metadata.
2173   // TODO: Support cyclic debug metadata.
2174   DILocalVariableAttr localVariableAttr =
2175       matchLocalVariableAttr(dbgIntr->getArgOperand(1));
2176   if (!localVariableAttr)
2177     return emitUnsupportedWarning();
2178   FailureOr<Value> argOperand = convertMetadataValue(dbgIntr->getArgOperand(0));
2179   if (failed(argOperand))
2180     return emitError(loc) << "failed to convert a debug intrinsic operand: "
2181                           << diag(*dbgIntr);
2182 
2183   // Ensure that the debug instrinsic is inserted right after its operand is
2184   // defined. Otherwise, the operand might not necessarily dominate the
2185   // intrinsic. If the defining operation is a terminator, insert the intrinsic
2186   // into a dominated block.
2187   OpBuilder::InsertionGuard guard(builder);
2188   if (Operation *op = argOperand->getDefiningOp();
2189       op && op->hasTrait<OpTrait::IsTerminator>()) {
2190     // Find a dominated block that can hold the debug intrinsic.
2191     auto dominatedBlocks = domInfo.getNode(op->getBlock())->children();
2192     // If no block is dominated by the terminator, this intrinisc cannot be
2193     // converted.
2194     if (dominatedBlocks.empty())
2195       return emitUnsupportedWarning();
2196     // Set insertion point before the terminator, to avoid inserting something
2197     // before landingpads.
2198     Block *dominatedBlock = (*dominatedBlocks.begin())->getBlock();
2199     builder.setInsertionPoint(dominatedBlock->getTerminator());
2200   } else {
2201     builder.setInsertionPointAfterValue(*argOperand);
2202   }
2203   auto locationExprAttr =
2204       debugImporter->translateExpression(dbgIntr->getExpression());
2205   Operation *op =
2206       llvm::TypeSwitch<llvm::DbgVariableIntrinsic *, Operation *>(dbgIntr)
2207           .Case([&](llvm::DbgDeclareInst *) {
2208             return builder.create<LLVM::DbgDeclareOp>(
2209                 loc, *argOperand, localVariableAttr, locationExprAttr);
2210           })
2211           .Case([&](llvm::DbgValueInst *) {
2212             return builder.create<LLVM::DbgValueOp>(
2213                 loc, *argOperand, localVariableAttr, locationExprAttr);
2214           });
2215   mapNoResultOp(dbgIntr, op);
2216   setNonDebugMetadataAttrs(dbgIntr, op);
2217   return success();
2218 }
2219 
2220 LogicalResult ModuleImport::processDebugIntrinsics() {
2221   DominanceInfo domInfo;
2222   for (llvm::Instruction *inst : debugIntrinsics) {
2223     auto *intrCall = cast<llvm::DbgVariableIntrinsic>(inst);
2224     if (failed(processDebugIntrinsic(intrCall, domInfo)))
2225       return failure();
2226   }
2227   return success();
2228 }
2229 
2230 LogicalResult ModuleImport::processBasicBlock(llvm::BasicBlock *bb,
2231                                               Block *block) {
2232   builder.setInsertionPointToStart(block);
2233   for (llvm::Instruction &inst : *bb) {
2234     if (failed(processInstruction(&inst)))
2235       return failure();
2236 
2237     // Skip additional processing when the instructions is a debug intrinsics
2238     // that was not yet converted.
2239     if (debugIntrinsics.contains(&inst))
2240       continue;
2241 
2242     // Set the non-debug metadata attributes on the imported operation and emit
2243     // a warning if an instruction other than a phi instruction is dropped
2244     // during the import.
2245     if (Operation *op = lookupOperation(&inst)) {
2246       setNonDebugMetadataAttrs(&inst, op);
2247     } else if (inst.getOpcode() != llvm::Instruction::PHI) {
2248       if (emitExpensiveWarnings) {
2249         Location loc = debugImporter->translateLoc(inst.getDebugLoc());
2250         emitWarning(loc) << "dropped instruction: " << diag(inst);
2251       }
2252     }
2253   }
2254   return success();
2255 }
2256 
2257 FailureOr<SmallVector<AccessGroupAttr>>
2258 ModuleImport::lookupAccessGroupAttrs(const llvm::MDNode *node) const {
2259   return loopAnnotationImporter->lookupAccessGroupAttrs(node);
2260 }
2261 
2262 LoopAnnotationAttr
2263 ModuleImport::translateLoopAnnotationAttr(const llvm::MDNode *node,
2264                                           Location loc) const {
2265   return loopAnnotationImporter->translateLoopAnnotation(node, loc);
2266 }
2267 
2268 OwningOpRef<ModuleOp>
2269 mlir::translateLLVMIRToModule(std::unique_ptr<llvm::Module> llvmModule,
2270                               MLIRContext *context, bool emitExpensiveWarnings,
2271                               bool dropDICompositeTypeElements) {
2272   // Preload all registered dialects to allow the import to iterate the
2273   // registered LLVMImportDialectInterface implementations and query the
2274   // supported LLVM IR constructs before starting the translation. Assumes the
2275   // LLVM and DLTI dialects that convert the core LLVM IR constructs have been
2276   // registered before.
2277   assert(llvm::is_contained(context->getAvailableDialects(),
2278                             LLVMDialect::getDialectNamespace()));
2279   assert(llvm::is_contained(context->getAvailableDialects(),
2280                             DLTIDialect::getDialectNamespace()));
2281   context->loadAllAvailableDialects();
2282   OwningOpRef<ModuleOp> module(ModuleOp::create(FileLineColLoc::get(
2283       StringAttr::get(context, llvmModule->getSourceFileName()), /*line=*/0,
2284       /*column=*/0)));
2285 
2286   ModuleImport moduleImport(module.get(), std::move(llvmModule),
2287                             emitExpensiveWarnings, dropDICompositeTypeElements);
2288   if (failed(moduleImport.initializeImportInterface()))
2289     return {};
2290   if (failed(moduleImport.convertDataLayout()))
2291     return {};
2292   if (failed(moduleImport.convertComdats()))
2293     return {};
2294   if (failed(moduleImport.convertMetadata()))
2295     return {};
2296   if (failed(moduleImport.convertGlobals()))
2297     return {};
2298   if (failed(moduleImport.convertFunctions()))
2299     return {};
2300 
2301   return module;
2302 }
2303