1 //===- ModuleTranslation.cpp - MLIR to LLVM conversion --------------------===//
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 translation between an MLIR LLVM dialect module and
10 // the corresponding LLVMIR module. It only handles core LLVM IR operations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "mlir/Target/LLVMIR/ModuleTranslation.h"
15 
16 #include "DebugTranslation.h"
17 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
18 #include "mlir/Dialect/LLVMIR/Transforms/LegalizeForExport.h"
19 #include "mlir/Dialect/OpenMP/OpenMPDialect.h"
20 #include "mlir/IR/Attributes.h"
21 #include "mlir/IR/BuiltinOps.h"
22 #include "mlir/IR/BuiltinTypes.h"
23 #include "mlir/IR/RegionGraphTraits.h"
24 #include "mlir/Support/LLVM.h"
25 #include "mlir/Target/LLVMIR/LLVMTranslationInterface.h"
26 #include "mlir/Target/LLVMIR/TypeTranslation.h"
27 #include "llvm/ADT/TypeSwitch.h"
28 
29 #include "llvm/ADT/PostOrderIterator.h"
30 #include "llvm/ADT/SetVector.h"
31 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
32 #include "llvm/IR/BasicBlock.h"
33 #include "llvm/IR/CFG.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DerivedTypes.h"
36 #include "llvm/IR/IRBuilder.h"
37 #include "llvm/IR/InlineAsm.h"
38 #include "llvm/IR/LLVMContext.h"
39 #include "llvm/IR/MDBuilder.h"
40 #include "llvm/IR/Module.h"
41 #include "llvm/IR/Verifier.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Transforms/Utils/Cloning.h"
44 
45 using namespace mlir;
46 using namespace mlir::LLVM;
47 using namespace mlir::LLVM::detail;
48 
49 #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc"
50 
51 /// Builds a constant of a sequential LLVM type `type`, potentially containing
52 /// other sequential types recursively, from the individual constant values
53 /// provided in `constants`. `shape` contains the number of elements in nested
54 /// sequential types. Reports errors at `loc` and returns nullptr on error.
55 static llvm::Constant *
56 buildSequentialConstant(ArrayRef<llvm::Constant *> &constants,
57                         ArrayRef<int64_t> shape, llvm::Type *type,
58                         Location loc) {
59   if (shape.empty()) {
60     llvm::Constant *result = constants.front();
61     constants = constants.drop_front();
62     return result;
63   }
64 
65   llvm::Type *elementType;
66   if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
67     elementType = arrayTy->getElementType();
68   } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
69     elementType = vectorTy->getElementType();
70   } else {
71     emitError(loc) << "expected sequential LLVM types wrapping a scalar";
72     return nullptr;
73   }
74 
75   SmallVector<llvm::Constant *, 8> nested;
76   nested.reserve(shape.front());
77   for (int64_t i = 0; i < shape.front(); ++i) {
78     nested.push_back(buildSequentialConstant(constants, shape.drop_front(),
79                                              elementType, loc));
80     if (!nested.back())
81       return nullptr;
82   }
83 
84   if (shape.size() == 1 && type->isVectorTy())
85     return llvm::ConstantVector::get(nested);
86   return llvm::ConstantArray::get(
87       llvm::ArrayType::get(elementType, shape.front()), nested);
88 }
89 
90 /// Returns the first non-sequential type nested in sequential types.
91 static llvm::Type *getInnermostElementType(llvm::Type *type) {
92   do {
93     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
94       type = arrayTy->getElementType();
95     } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
96       type = vectorTy->getElementType();
97     } else {
98       return type;
99     }
100   } while (true);
101 }
102 
103 /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
104 /// This currently supports integer, floating point, splat and dense element
105 /// attributes and combinations thereof.  In case of error, report it to `loc`
106 /// and return nullptr.
107 llvm::Constant *mlir::LLVM::detail::getLLVMConstant(
108     llvm::Type *llvmType, Attribute attr, Location loc,
109     const ModuleTranslation &moduleTranslation) {
110   if (!attr)
111     return llvm::UndefValue::get(llvmType);
112   if (llvmType->isStructTy()) {
113     emitError(loc, "struct types are not supported in constants");
114     return nullptr;
115   }
116   // For integer types, we allow a mismatch in sizes as the index type in
117   // MLIR might have a different size than the index type in the LLVM module.
118   if (auto intAttr = attr.dyn_cast<IntegerAttr>())
119     return llvm::ConstantInt::get(
120         llvmType,
121         intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth()));
122   if (auto floatAttr = attr.dyn_cast<FloatAttr>())
123     return llvm::ConstantFP::get(llvmType, floatAttr.getValue());
124   if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>())
125     return llvm::ConstantExpr::getBitCast(
126         moduleTranslation.lookupFunction(funcAttr.getValue()), llvmType);
127   if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) {
128     llvm::Type *elementType;
129     uint64_t numElements;
130     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) {
131       elementType = arrayTy->getElementType();
132       numElements = arrayTy->getNumElements();
133     } else {
134       auto *vectorTy = cast<llvm::FixedVectorType>(llvmType);
135       elementType = vectorTy->getElementType();
136       numElements = vectorTy->getNumElements();
137     }
138     // Splat value is a scalar. Extract it only if the element type is not
139     // another sequence type. The recursion terminates because each step removes
140     // one outer sequential type.
141     bool elementTypeSequential =
142         isa<llvm::ArrayType, llvm::VectorType>(elementType);
143     llvm::Constant *child = getLLVMConstant(
144         elementType,
145         elementTypeSequential ? splatAttr : splatAttr.getSplatValue(), loc,
146         moduleTranslation);
147     if (!child)
148       return nullptr;
149     if (llvmType->isVectorTy())
150       return llvm::ConstantVector::getSplat(
151           llvm::ElementCount::get(numElements, /*Scalable=*/false), child);
152     if (llvmType->isArrayTy()) {
153       auto *arrayType = llvm::ArrayType::get(elementType, numElements);
154       SmallVector<llvm::Constant *, 8> constants(numElements, child);
155       return llvm::ConstantArray::get(arrayType, constants);
156     }
157   }
158 
159   if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) {
160     assert(elementsAttr.getType().hasStaticShape());
161     assert(elementsAttr.getNumElements() != 0 &&
162            "unexpected empty elements attribute");
163     assert(!elementsAttr.getType().getShape().empty() &&
164            "unexpected empty elements attribute shape");
165 
166     SmallVector<llvm::Constant *, 8> constants;
167     constants.reserve(elementsAttr.getNumElements());
168     llvm::Type *innermostType = getInnermostElementType(llvmType);
169     for (auto n : elementsAttr.getValues<Attribute>()) {
170       constants.push_back(
171           getLLVMConstant(innermostType, n, loc, moduleTranslation));
172       if (!constants.back())
173         return nullptr;
174     }
175     ArrayRef<llvm::Constant *> constantsRef = constants;
176     llvm::Constant *result = buildSequentialConstant(
177         constantsRef, elementsAttr.getType().getShape(), llvmType, loc);
178     assert(constantsRef.empty() && "did not consume all elemental constants");
179     return result;
180   }
181 
182   if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
183     return llvm::ConstantDataArray::get(
184         moduleTranslation.getLLVMContext(),
185         ArrayRef<char>{stringAttr.getValue().data(),
186                        stringAttr.getValue().size()});
187   }
188   emitError(loc, "unsupported constant value");
189   return nullptr;
190 }
191 
192 ModuleTranslation::ModuleTranslation(Operation *module,
193                                      std::unique_ptr<llvm::Module> llvmModule)
194     : mlirModule(module), llvmModule(std::move(llvmModule)),
195       debugTranslation(
196           std::make_unique<DebugTranslation>(module, *this->llvmModule)),
197       typeTranslator(this->llvmModule->getContext()),
198       iface(module->getContext()) {
199   assert(satisfiesLLVMModule(mlirModule) &&
200          "mlirModule should honor LLVM's module semantics.");
201 }
202 ModuleTranslation::~ModuleTranslation() {
203   if (ompBuilder)
204     ompBuilder->finalize();
205 }
206 
207 /// Get the SSA value passed to the current block from the terminator operation
208 /// of its predecessor.
209 static Value getPHISourceValue(Block *current, Block *pred,
210                                unsigned numArguments, unsigned index) {
211   Operation &terminator = *pred->getTerminator();
212   if (isa<LLVM::BrOp>(terminator))
213     return terminator.getOperand(index);
214 
215   SuccessorRange successors = terminator.getSuccessors();
216   assert(std::adjacent_find(successors.begin(), successors.end()) ==
217              successors.end() &&
218          "successors with arguments in LLVM branches must be different blocks");
219   (void)successors;
220 
221   // For instructions that branch based on a condition value, we need to take
222   // the operands for the branch that was taken.
223   if (auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator)) {
224     // For conditional branches, we take the operands from either the "true" or
225     // the "false" branch.
226     return condBranchOp.getSuccessor(0) == current
227                ? condBranchOp.trueDestOperands()[index]
228                : condBranchOp.falseDestOperands()[index];
229   }
230 
231   if (auto switchOp = dyn_cast<LLVM::SwitchOp>(terminator)) {
232     // For switches, we take the operands from either the default case, or from
233     // the case branch that was taken.
234     if (switchOp.defaultDestination() == current)
235       return switchOp.defaultOperands()[index];
236     for (auto i : llvm::enumerate(switchOp.caseDestinations()))
237       if (i.value() == current)
238         return switchOp.getCaseOperands(i.index())[index];
239   }
240 
241   llvm_unreachable("only branch or switch operations can be terminators of a "
242                    "block that has successors");
243 }
244 
245 /// Connect the PHI nodes to the results of preceding blocks.
246 void mlir::LLVM::detail::connectPHINodes(Region &region,
247                                          const ModuleTranslation &state) {
248   // Skip the first block, it cannot be branched to and its arguments correspond
249   // to the arguments of the LLVM function.
250   for (auto it = std::next(region.begin()), eit = region.end(); it != eit;
251        ++it) {
252     Block *bb = &*it;
253     llvm::BasicBlock *llvmBB = state.lookupBlock(bb);
254     auto phis = llvmBB->phis();
255     auto numArguments = bb->getNumArguments();
256     assert(numArguments == std::distance(phis.begin(), phis.end()));
257     for (auto &numberedPhiNode : llvm::enumerate(phis)) {
258       auto &phiNode = numberedPhiNode.value();
259       unsigned index = numberedPhiNode.index();
260       for (auto *pred : bb->getPredecessors()) {
261         // Find the LLVM IR block that contains the converted terminator
262         // instruction and use it in the PHI node. Note that this block is not
263         // necessarily the same as state.lookupBlock(pred), some operations
264         // (in particular, OpenMP operations using OpenMPIRBuilder) may have
265         // split the blocks.
266         llvm::Instruction *terminator =
267             state.lookupBranch(pred->getTerminator());
268         assert(terminator && "missing the mapping for a terminator");
269         phiNode.addIncoming(
270             state.lookupValue(getPHISourceValue(bb, pred, numArguments, index)),
271             terminator->getParent());
272       }
273     }
274   }
275 }
276 
277 /// Sort function blocks topologically.
278 SetVector<Block *>
279 mlir::LLVM::detail::getTopologicallySortedBlocks(Region &region) {
280   // For each block that has not been visited yet (i.e. that has no
281   // predecessors), add it to the list as well as its successors.
282   SetVector<Block *> blocks;
283   for (Block &b : region) {
284     if (blocks.count(&b) == 0) {
285       llvm::ReversePostOrderTraversal<Block *> traversal(&b);
286       blocks.insert(traversal.begin(), traversal.end());
287     }
288   }
289   assert(blocks.size() == region.getBlocks().size() &&
290          "some blocks are not sorted");
291 
292   return blocks;
293 }
294 
295 llvm::Value *mlir::LLVM::detail::createIntrinsicCall(
296     llvm::IRBuilderBase &builder, llvm::Intrinsic::ID intrinsic,
297     ArrayRef<llvm::Value *> args, ArrayRef<llvm::Type *> tys) {
298   llvm::Module *module = builder.GetInsertBlock()->getModule();
299   llvm::Function *fn = llvm::Intrinsic::getDeclaration(module, intrinsic, tys);
300   return builder.CreateCall(fn, args);
301 }
302 
303 /// Given a single MLIR operation, create the corresponding LLVM IR operation
304 /// using the `builder`.
305 LogicalResult
306 ModuleTranslation::convertOperation(Operation &op,
307                                     llvm::IRBuilderBase &builder) {
308   const LLVMTranslationDialectInterface *opIface = iface.getInterfaceFor(&op);
309   if (!opIface)
310     return op.emitError("cannot be converted to LLVM IR: missing "
311                         "`LLVMTranslationDialectInterface` registration for "
312                         "dialect for op: ")
313            << op.getName();
314 
315   if (failed(opIface->convertOperation(&op, builder, *this)))
316     return op.emitError("LLVM Translation failed for operation: ")
317            << op.getName();
318 
319   return convertDialectAttributes(&op);
320 }
321 
322 /// Convert block to LLVM IR.  Unless `ignoreArguments` is set, emit PHI nodes
323 /// to define values corresponding to the MLIR block arguments.  These nodes
324 /// are not connected to the source basic blocks, which may not exist yet.  Uses
325 /// `builder` to construct the LLVM IR. Expects the LLVM IR basic block to have
326 /// been created for `bb` and included in the block mapping.  Inserts new
327 /// instructions at the end of the block and leaves `builder` in a state
328 /// suitable for further insertion into the end of the block.
329 LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments,
330                                               llvm::IRBuilderBase &builder) {
331   builder.SetInsertPoint(lookupBlock(&bb));
332   auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram();
333 
334   // Before traversing operations, make block arguments available through
335   // value remapping and PHI nodes, but do not add incoming edges for the PHI
336   // nodes just yet: those values may be defined by this or following blocks.
337   // This step is omitted if "ignoreArguments" is set.  The arguments of the
338   // first block have been already made available through the remapping of
339   // LLVM function arguments.
340   if (!ignoreArguments) {
341     auto predecessors = bb.getPredecessors();
342     unsigned numPredecessors =
343         std::distance(predecessors.begin(), predecessors.end());
344     for (auto arg : bb.getArguments()) {
345       auto wrappedType = arg.getType();
346       if (!isCompatibleType(wrappedType))
347         return emitError(bb.front().getLoc(),
348                          "block argument does not have an LLVM type");
349       llvm::Type *type = convertType(wrappedType);
350       llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors);
351       mapValue(arg, phi);
352     }
353   }
354 
355   // Traverse operations.
356   for (auto &op : bb) {
357     // Set the current debug location within the builder.
358     builder.SetCurrentDebugLocation(
359         debugTranslation->translateLoc(op.getLoc(), subprogram));
360 
361     if (failed(convertOperation(op, builder)))
362       return failure();
363   }
364 
365   return success();
366 }
367 
368 /// A helper method to get the single Block in an operation honoring LLVM's
369 /// module requirements.
370 static Block &getModuleBody(Operation *module) {
371   return module->getRegion(0).front();
372 }
373 
374 /// A helper method to decide if a constant must not be set as a global variable
375 /// initializer.
376 static bool shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage,
377                                         llvm::Constant *cst) {
378   return (linkage == llvm::GlobalVariable::ExternalLinkage &&
379           isa<llvm::UndefValue>(cst)) ||
380          linkage == llvm::GlobalVariable::ExternalWeakLinkage;
381 }
382 
383 /// Create named global variables that correspond to llvm.mlir.global
384 /// definitions.
385 LogicalResult ModuleTranslation::convertGlobals() {
386   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
387     llvm::Type *type = convertType(op.getType());
388     llvm::Constant *cst = llvm::UndefValue::get(type);
389     if (op.getValueOrNull()) {
390       // String attributes are treated separately because they cannot appear as
391       // in-function constants and are thus not supported by getLLVMConstant.
392       if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) {
393         cst = llvm::ConstantDataArray::getString(
394             llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
395         type = cst->getType();
396       } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(),
397                                          *this))) {
398         return failure();
399       }
400     }
401 
402     auto linkage = convertLinkageToLLVM(op.linkage());
403     auto addrSpace = op.addr_space();
404     auto *var = new llvm::GlobalVariable(
405         *llvmModule, type, op.constant(), linkage,
406         shouldDropGlobalInitializer(linkage, cst) ? nullptr : cst,
407         op.sym_name(),
408         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace);
409 
410     globalsMapping.try_emplace(op, var);
411   }
412 
413   // Convert global variable bodies. This is done after all global variables
414   // have been created in LLVM IR because a global body may refer to another
415   // global or itself. So all global variables need to be mapped first.
416   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
417     if (Block *initializer = op.getInitializerBlock()) {
418       llvm::IRBuilder<> builder(llvmModule->getContext());
419       for (auto &op : initializer->without_terminator()) {
420         if (failed(convertOperation(op, builder)) ||
421             !isa<llvm::Constant>(lookupValue(op.getResult(0))))
422           return emitError(op.getLoc(), "unemittable constant value");
423       }
424       ReturnOp ret = cast<ReturnOp>(initializer->getTerminator());
425       llvm::Constant *cst =
426           cast<llvm::Constant>(lookupValue(ret.getOperand(0)));
427       auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op));
428       if (!shouldDropGlobalInitializer(global->getLinkage(), cst))
429         global->setInitializer(cst);
430     }
431   }
432 
433   return success();
434 }
435 
436 /// Attempts to add an attribute identified by `key`, optionally with the given
437 /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the
438 /// attribute has a kind known to LLVM IR, create the attribute of this kind,
439 /// otherwise keep it as a string attribute. Performs additional checks for
440 /// attributes known to have or not have a value in order to avoid assertions
441 /// inside LLVM upon construction.
442 static LogicalResult checkedAddLLVMFnAttribute(Location loc,
443                                                llvm::Function *llvmFunc,
444                                                StringRef key,
445                                                StringRef value = StringRef()) {
446   auto kind = llvm::Attribute::getAttrKindFromName(key);
447   if (kind == llvm::Attribute::None) {
448     llvmFunc->addFnAttr(key, value);
449     return success();
450   }
451 
452   if (llvm::Attribute::doesAttrKindHaveArgument(kind)) {
453     if (value.empty())
454       return emitError(loc) << "LLVM attribute '" << key << "' expects a value";
455 
456     int result;
457     if (!value.getAsInteger(/*Radix=*/0, result))
458       llvmFunc->addFnAttr(
459           llvm::Attribute::get(llvmFunc->getContext(), kind, result));
460     else
461       llvmFunc->addFnAttr(key, value);
462     return success();
463   }
464 
465   if (!value.empty())
466     return emitError(loc) << "LLVM attribute '" << key
467                           << "' does not expect a value, found '" << value
468                           << "'";
469 
470   llvmFunc->addFnAttr(kind);
471   return success();
472 }
473 
474 /// Attaches the attributes listed in the given array attribute to `llvmFunc`.
475 /// Reports error to `loc` if any and returns immediately. Expects `attributes`
476 /// to be an array attribute containing either string attributes, treated as
477 /// value-less LLVM attributes, or array attributes containing two string
478 /// attributes, with the first string being the name of the corresponding LLVM
479 /// attribute and the second string beings its value. Note that even integer
480 /// attributes are expected to have their values expressed as strings.
481 static LogicalResult
482 forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes,
483                              llvm::Function *llvmFunc) {
484   if (!attributes)
485     return success();
486 
487   for (Attribute attr : *attributes) {
488     if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
489       if (failed(
490               checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue())))
491         return failure();
492       continue;
493     }
494 
495     auto arrayAttr = attr.dyn_cast<ArrayAttr>();
496     if (!arrayAttr || arrayAttr.size() != 2)
497       return emitError(loc)
498              << "expected 'passthrough' to contain string or array attributes";
499 
500     auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>();
501     auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>();
502     if (!keyAttr || !valueAttr)
503       return emitError(loc)
504              << "expected arrays within 'passthrough' to contain two strings";
505 
506     if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(),
507                                          valueAttr.getValue())))
508       return failure();
509   }
510   return success();
511 }
512 
513 LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) {
514   // Clear the block, branch value mappings, they are only relevant within one
515   // function.
516   blockMapping.clear();
517   valueMapping.clear();
518   branchMapping.clear();
519   llvm::Function *llvmFunc = lookupFunction(func.getName());
520 
521   // Translate the debug information for this function.
522   debugTranslation->translate(func, *llvmFunc);
523 
524   // Add function arguments to the value remapping table.
525   // If there was noalias info then we decorate each argument accordingly.
526   unsigned int argIdx = 0;
527   for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) {
528     llvm::Argument &llvmArg = std::get<1>(kvp);
529     BlockArgument mlirArg = std::get<0>(kvp);
530 
531     if (auto attr = func.getArgAttrOfType<BoolAttr>(
532             argIdx, LLVMDialect::getNoAliasAttrName())) {
533       // NB: Attribute already verified to be boolean, so check if we can indeed
534       // attach the attribute to this argument, based on its type.
535       auto argTy = mlirArg.getType();
536       if (!argTy.isa<LLVM::LLVMPointerType>())
537         return func.emitError(
538             "llvm.noalias attribute attached to LLVM non-pointer argument");
539       if (attr.getValue())
540         llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias);
541     }
542 
543     if (auto attr = func.getArgAttrOfType<IntegerAttr>(
544             argIdx, LLVMDialect::getAlignAttrName())) {
545       // NB: Attribute already verified to be int, so check if we can indeed
546       // attach the attribute to this argument, based on its type.
547       auto argTy = mlirArg.getType();
548       if (!argTy.isa<LLVM::LLVMPointerType>())
549         return func.emitError(
550             "llvm.align attribute attached to LLVM non-pointer argument");
551       llvmArg.addAttrs(
552           llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt())));
553     }
554 
555     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) {
556       auto argTy = mlirArg.getType();
557       if (!argTy.isa<LLVM::LLVMPointerType>())
558         return func.emitError(
559             "llvm.sret attribute attached to LLVM non-pointer argument");
560       llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr(
561           llvmArg.getType()->getPointerElementType()));
562     }
563 
564     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) {
565       auto argTy = mlirArg.getType();
566       if (!argTy.isa<LLVM::LLVMPointerType>())
567         return func.emitError(
568             "llvm.byval attribute attached to LLVM non-pointer argument");
569       llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr(
570           llvmArg.getType()->getPointerElementType()));
571     }
572 
573     mapValue(mlirArg, &llvmArg);
574     argIdx++;
575   }
576 
577   // Check the personality and set it.
578   if (func.personality().hasValue()) {
579     llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext());
580     if (llvm::Constant *pfunc =
581             getLLVMConstant(ty, func.personalityAttr(), func.getLoc(), *this))
582       llvmFunc->setPersonalityFn(pfunc);
583   }
584 
585   // First, create all blocks so we can jump to them.
586   llvm::LLVMContext &llvmContext = llvmFunc->getContext();
587   for (auto &bb : func) {
588     auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
589     llvmBB->insertInto(llvmFunc);
590     mapBlock(&bb, llvmBB);
591   }
592 
593   // Then, convert blocks one by one in topological order to ensure defs are
594   // converted before uses.
595   auto blocks = detail::getTopologicallySortedBlocks(func.getBody());
596   for (Block *bb : blocks) {
597     llvm::IRBuilder<> builder(llvmContext);
598     if (failed(convertBlock(*bb, bb->isEntryBlock(), builder)))
599       return failure();
600   }
601 
602   // After all blocks have been traversed and values mapped, connect the PHI
603   // nodes to the results of preceding blocks.
604   detail::connectPHINodes(func.getBody(), *this);
605 
606   // Finally, convert dialect attributes attached to the function.
607   return convertDialectAttributes(func);
608 }
609 
610 LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) {
611   for (NamedAttribute attribute : op->getDialectAttrs())
612     if (failed(iface.amendOperation(op, attribute, *this)))
613       return failure();
614   return success();
615 }
616 
617 /// Check whether the module contains only supported ops directly in its body.
618 static LogicalResult checkSupportedModuleOps(Operation *m) {
619   for (Operation &o : getModuleBody(m).getOperations())
620     if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::MetadataOp>(&o) &&
621         !o.hasTrait<OpTrait::IsTerminator>())
622       return o.emitOpError("unsupported module-level operation");
623   return success();
624 }
625 
626 LogicalResult ModuleTranslation::convertFunctionSignatures() {
627   // Declare all functions first because there may be function calls that form a
628   // call graph with cycles, or global initializers that reference functions.
629   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
630     llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction(
631         function.getName(),
632         cast<llvm::FunctionType>(convertType(function.getType())));
633     llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee());
634     llvmFunc->setLinkage(convertLinkageToLLVM(function.linkage()));
635     mapFunction(function.getName(), llvmFunc);
636 
637     // Forward the pass-through attributes to LLVM.
638     if (failed(forwardPassthroughAttributes(function.getLoc(),
639                                             function.passthrough(), llvmFunc)))
640       return failure();
641   }
642 
643   return success();
644 }
645 
646 LogicalResult ModuleTranslation::convertFunctions() {
647   // Convert functions.
648   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
649     // Ignore external functions.
650     if (function.isExternal())
651       continue;
652 
653     if (failed(convertOneFunction(function)))
654       return failure();
655   }
656 
657   return success();
658 }
659 
660 llvm::MDNode *
661 ModuleTranslation::getAccessGroup(Operation &opInst,
662                                   SymbolRefAttr accessGroupRef) const {
663   auto metadataName = accessGroupRef.getRootReference();
664   auto accessGroupName = accessGroupRef.getLeafReference();
665   auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>(
666       opInst.getParentOp(), metadataName);
667   auto *accessGroupOp =
668       SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName);
669   return accessGroupMetadataMapping.lookup(accessGroupOp);
670 }
671 
672 LogicalResult ModuleTranslation::createAccessGroupMetadata() {
673   mlirModule->walk([&](LLVM::MetadataOp metadatas) {
674     metadatas.walk([&](LLVM::AccessGroupMetadataOp op) {
675       llvm::LLVMContext &ctx = llvmModule->getContext();
676       llvm::MDNode *accessGroup = llvm::MDNode::getDistinct(ctx, {});
677       accessGroupMetadataMapping.insert({op, accessGroup});
678     });
679   });
680   return success();
681 }
682 
683 void ModuleTranslation::setAccessGroupsMetadata(Operation *op,
684                                                 llvm::Instruction *inst) {
685   auto accessGroups =
686       op->getAttrOfType<ArrayAttr>(LLVMDialect::getAccessGroupsAttrName());
687   if (accessGroups && !accessGroups.empty()) {
688     llvm::Module *module = inst->getModule();
689     SmallVector<llvm::Metadata *> metadatas;
690     for (SymbolRefAttr accessGroupRef :
691          accessGroups.getAsRange<SymbolRefAttr>())
692       metadatas.push_back(getAccessGroup(*op, accessGroupRef));
693 
694     llvm::MDNode *unionMD = nullptr;
695     if (metadatas.size() == 1)
696       unionMD = llvm::cast<llvm::MDNode>(metadatas.front());
697     else if (metadatas.size() >= 2)
698       unionMD = llvm::MDNode::get(module->getContext(), metadatas);
699 
700     inst->setMetadata(module->getMDKindID("llvm.access.group"), unionMD);
701   }
702 }
703 
704 llvm::Type *ModuleTranslation::convertType(Type type) {
705   return typeTranslator.translateType(type);
706 }
707 
708 /// A helper to look up remapped operands in the value remapping table.`
709 SmallVector<llvm::Value *, 8>
710 ModuleTranslation::lookupValues(ValueRange values) {
711   SmallVector<llvm::Value *, 8> remapped;
712   remapped.reserve(values.size());
713   for (Value v : values)
714     remapped.push_back(lookupValue(v));
715   return remapped;
716 }
717 
718 const llvm::DILocation *
719 ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) {
720   return debugTranslation->translateLoc(loc, scope);
721 }
722 
723 llvm::NamedMDNode *
724 ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) {
725   return llvmModule->getOrInsertNamedMetadata(name);
726 }
727 
728 static std::unique_ptr<llvm::Module>
729 prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext,
730                   StringRef name) {
731   m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>();
732   auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext);
733   if (auto dataLayoutAttr =
734           m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName()))
735     llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue());
736   if (auto targetTripleAttr =
737           m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName()))
738     llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue());
739 
740   // Inject declarations for `malloc` and `free` functions that can be used in
741   // memref allocation/deallocation coming from standard ops lowering.
742   llvm::IRBuilder<> builder(llvmContext);
743   llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(),
744                                   builder.getInt64Ty());
745   llvmModule->getOrInsertFunction("free", builder.getVoidTy(),
746                                   builder.getInt8PtrTy());
747 
748   return llvmModule;
749 }
750 
751 std::unique_ptr<llvm::Module>
752 mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext,
753                               StringRef name) {
754   if (!satisfiesLLVMModule(module))
755     return nullptr;
756   if (failed(checkSupportedModuleOps(module)))
757     return nullptr;
758   std::unique_ptr<llvm::Module> llvmModule =
759       prepareLLVMModule(module, llvmContext, name);
760 
761   LLVM::ensureDistinctSuccessors(module);
762 
763   ModuleTranslation translator(module, std::move(llvmModule));
764   if (failed(translator.convertFunctionSignatures()))
765     return nullptr;
766   if (failed(translator.convertGlobals()))
767     return nullptr;
768   if (failed(translator.createAccessGroupMetadata()))
769     return nullptr;
770   if (failed(translator.convertFunctions()))
771     return nullptr;
772   if (llvm::verifyModule(*translator.llvmModule, &llvm::errs()))
773     return nullptr;
774 
775   return std::move(translator.llvmModule);
776 }
777