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