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.
419 static bool shouldDropGlobalInitializer(llvm::GlobalValue::LinkageTypes linkage,
420                                         llvm::Constant *cst) {
421   return (linkage == llvm::GlobalVariable::ExternalLinkage &&
422           isa<llvm::UndefValue>(cst)) ||
423          linkage == llvm::GlobalVariable::ExternalWeakLinkage;
424 }
425 
426 /// Sets the runtime preemption specifier of `gv` to dso_local if
427 /// `dsoLocalRequested` is true, otherwise it is left unchanged.
428 static void addRuntimePreemptionSpecifier(bool dsoLocalRequested,
429                                           llvm::GlobalValue *gv) {
430   if (dsoLocalRequested)
431     gv->setDSOLocal(true);
432 }
433 
434 /// Create named global variables that correspond to llvm.mlir.global
435 /// definitions.
436 LogicalResult ModuleTranslation::convertGlobals() {
437   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
438     llvm::Type *type = convertType(op.getType());
439     llvm::Constant *cst = llvm::UndefValue::get(type);
440     if (op.getValueOrNull()) {
441       // String attributes are treated separately because they cannot appear as
442       // in-function constants and are thus not supported by getLLVMConstant.
443       if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) {
444         cst = llvm::ConstantDataArray::getString(
445             llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
446         type = cst->getType();
447       } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc(),
448                                          *this))) {
449         return failure();
450       }
451     }
452 
453     auto linkage = convertLinkageToLLVM(op.linkage());
454     auto addrSpace = op.addr_space();
455     auto *var = new llvm::GlobalVariable(
456         *llvmModule, type, op.constant(), linkage,
457         shouldDropGlobalInitializer(linkage, cst) ? nullptr : cst,
458         op.sym_name(),
459         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace);
460 
461     if (op.unnamed_addr().hasValue())
462       var->setUnnamedAddr(convertUnnamedAddrToLLVM(*op.unnamed_addr()));
463 
464     if (op.section().hasValue())
465       var->setSection(*op.section());
466 
467     addRuntimePreemptionSpecifier(op.dso_local(), var);
468 
469     Optional<uint64_t> alignment = op.alignment();
470     if (alignment.hasValue())
471       var->setAlignment(llvm::MaybeAlign(alignment.getValue()));
472 
473     globalsMapping.try_emplace(op, var);
474   }
475 
476   // Convert global variable bodies. This is done after all global variables
477   // have been created in LLVM IR because a global body may refer to another
478   // global or itself. So all global variables need to be mapped first.
479   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
480     if (Block *initializer = op.getInitializerBlock()) {
481       llvm::IRBuilder<> builder(llvmModule->getContext());
482       for (auto &op : initializer->without_terminator()) {
483         if (failed(convertOperation(op, builder)) ||
484             !isa<llvm::Constant>(lookupValue(op.getResult(0))))
485           return emitError(op.getLoc(), "unemittable constant value");
486       }
487       ReturnOp ret = cast<ReturnOp>(initializer->getTerminator());
488       llvm::Constant *cst =
489           cast<llvm::Constant>(lookupValue(ret.getOperand(0)));
490       auto *global = cast<llvm::GlobalVariable>(lookupGlobal(op));
491       if (!shouldDropGlobalInitializer(global->getLinkage(), cst))
492         global->setInitializer(cst);
493     }
494   }
495 
496   return success();
497 }
498 
499 /// Attempts to add an attribute identified by `key`, optionally with the given
500 /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the
501 /// attribute has a kind known to LLVM IR, create the attribute of this kind,
502 /// otherwise keep it as a string attribute. Performs additional checks for
503 /// attributes known to have or not have a value in order to avoid assertions
504 /// inside LLVM upon construction.
505 static LogicalResult checkedAddLLVMFnAttribute(Location loc,
506                                                llvm::Function *llvmFunc,
507                                                StringRef key,
508                                                StringRef value = StringRef()) {
509   auto kind = llvm::Attribute::getAttrKindFromName(key);
510   if (kind == llvm::Attribute::None) {
511     llvmFunc->addFnAttr(key, value);
512     return success();
513   }
514 
515   if (llvm::Attribute::doesAttrKindHaveArgument(kind)) {
516     if (value.empty())
517       return emitError(loc) << "LLVM attribute '" << key << "' expects a value";
518 
519     int result;
520     if (!value.getAsInteger(/*Radix=*/0, result))
521       llvmFunc->addFnAttr(
522           llvm::Attribute::get(llvmFunc->getContext(), kind, result));
523     else
524       llvmFunc->addFnAttr(key, value);
525     return success();
526   }
527 
528   if (!value.empty())
529     return emitError(loc) << "LLVM attribute '" << key
530                           << "' does not expect a value, found '" << value
531                           << "'";
532 
533   llvmFunc->addFnAttr(kind);
534   return success();
535 }
536 
537 /// Attaches the attributes listed in the given array attribute to `llvmFunc`.
538 /// Reports error to `loc` if any and returns immediately. Expects `attributes`
539 /// to be an array attribute containing either string attributes, treated as
540 /// value-less LLVM attributes, or array attributes containing two string
541 /// attributes, with the first string being the name of the corresponding LLVM
542 /// attribute and the second string beings its value. Note that even integer
543 /// attributes are expected to have their values expressed as strings.
544 static LogicalResult
545 forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes,
546                              llvm::Function *llvmFunc) {
547   if (!attributes)
548     return success();
549 
550   for (Attribute attr : *attributes) {
551     if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
552       if (failed(
553               checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue())))
554         return failure();
555       continue;
556     }
557 
558     auto arrayAttr = attr.dyn_cast<ArrayAttr>();
559     if (!arrayAttr || arrayAttr.size() != 2)
560       return emitError(loc)
561              << "expected 'passthrough' to contain string or array attributes";
562 
563     auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>();
564     auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>();
565     if (!keyAttr || !valueAttr)
566       return emitError(loc)
567              << "expected arrays within 'passthrough' to contain two strings";
568 
569     if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(),
570                                          valueAttr.getValue())))
571       return failure();
572   }
573   return success();
574 }
575 
576 LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) {
577   // Clear the block, branch value mappings, they are only relevant within one
578   // function.
579   blockMapping.clear();
580   valueMapping.clear();
581   branchMapping.clear();
582   llvm::Function *llvmFunc = lookupFunction(func.getName());
583 
584   // Translate the debug information for this function.
585   debugTranslation->translate(func, *llvmFunc);
586 
587   // Add function arguments to the value remapping table.
588   // If there was noalias info then we decorate each argument accordingly.
589   unsigned int argIdx = 0;
590   for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) {
591     llvm::Argument &llvmArg = std::get<1>(kvp);
592     BlockArgument mlirArg = std::get<0>(kvp);
593 
594     if (auto attr = func.getArgAttrOfType<UnitAttr>(
595             argIdx, LLVMDialect::getNoAliasAttrName())) {
596       // NB: Attribute already verified to be boolean, so check if we can indeed
597       // attach the attribute to this argument, based on its type.
598       auto argTy = mlirArg.getType();
599       if (!argTy.isa<LLVM::LLVMPointerType>())
600         return func.emitError(
601             "llvm.noalias attribute attached to LLVM non-pointer argument");
602       llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias);
603     }
604 
605     if (auto attr = func.getArgAttrOfType<IntegerAttr>(
606             argIdx, LLVMDialect::getAlignAttrName())) {
607       // NB: Attribute already verified to be int, so check if we can indeed
608       // attach the attribute to this argument, based on its type.
609       auto argTy = mlirArg.getType();
610       if (!argTy.isa<LLVM::LLVMPointerType>())
611         return func.emitError(
612             "llvm.align attribute attached to LLVM non-pointer argument");
613       llvmArg.addAttrs(
614           llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt())));
615     }
616 
617     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.sret")) {
618       auto argTy = mlirArg.getType();
619       if (!argTy.isa<LLVM::LLVMPointerType>())
620         return func.emitError(
621             "llvm.sret attribute attached to LLVM non-pointer argument");
622       llvmArg.addAttrs(llvm::AttrBuilder().addStructRetAttr(
623           llvmArg.getType()->getPointerElementType()));
624     }
625 
626     if (auto attr = func.getArgAttrOfType<UnitAttr>(argIdx, "llvm.byval")) {
627       auto argTy = mlirArg.getType();
628       if (!argTy.isa<LLVM::LLVMPointerType>())
629         return func.emitError(
630             "llvm.byval attribute attached to LLVM non-pointer argument");
631       llvmArg.addAttrs(llvm::AttrBuilder().addByValAttr(
632           llvmArg.getType()->getPointerElementType()));
633     }
634 
635     mapValue(mlirArg, &llvmArg);
636     argIdx++;
637   }
638 
639   // Check the personality and set it.
640   if (func.personality().hasValue()) {
641     llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext());
642     if (llvm::Constant *pfunc =
643             getLLVMConstant(ty, func.personalityAttr(), func.getLoc(), *this))
644       llvmFunc->setPersonalityFn(pfunc);
645   }
646 
647   // First, create all blocks so we can jump to them.
648   llvm::LLVMContext &llvmContext = llvmFunc->getContext();
649   for (auto &bb : func) {
650     auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
651     llvmBB->insertInto(llvmFunc);
652     mapBlock(&bb, llvmBB);
653   }
654 
655   // Then, convert blocks one by one in topological order to ensure defs are
656   // converted before uses.
657   auto blocks = detail::getTopologicallySortedBlocks(func.getBody());
658   for (Block *bb : blocks) {
659     llvm::IRBuilder<> builder(llvmContext);
660     if (failed(convertBlock(*bb, bb->isEntryBlock(), builder)))
661       return failure();
662   }
663 
664   // After all blocks have been traversed and values mapped, connect the PHI
665   // nodes to the results of preceding blocks.
666   detail::connectPHINodes(func.getBody(), *this);
667 
668   // Finally, convert dialect attributes attached to the function.
669   return convertDialectAttributes(func);
670 }
671 
672 LogicalResult ModuleTranslation::convertDialectAttributes(Operation *op) {
673   for (NamedAttribute attribute : op->getDialectAttrs())
674     if (failed(iface.amendOperation(op, attribute, *this)))
675       return failure();
676   return success();
677 }
678 
679 /// Check whether the module contains only supported ops directly in its body.
680 static LogicalResult checkSupportedModuleOps(Operation *m) {
681   for (Operation &o : getModuleBody(m).getOperations())
682     if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp, LLVM::MetadataOp>(&o) &&
683         !o.hasTrait<OpTrait::IsTerminator>())
684       return o.emitOpError("unsupported module-level operation");
685   return success();
686 }
687 
688 LogicalResult ModuleTranslation::convertFunctionSignatures() {
689   // Declare all functions first because there may be function calls that form a
690   // call graph with cycles, or global initializers that reference functions.
691   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
692     llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction(
693         function.getName(),
694         cast<llvm::FunctionType>(convertType(function.getType())));
695     llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee());
696     llvmFunc->setLinkage(convertLinkageToLLVM(function.linkage()));
697     mapFunction(function.getName(), llvmFunc);
698     addRuntimePreemptionSpecifier(function.dso_local(), llvmFunc);
699 
700     // Forward the pass-through attributes to LLVM.
701     if (failed(forwardPassthroughAttributes(function.getLoc(),
702                                             function.passthrough(), llvmFunc)))
703       return failure();
704   }
705 
706   return success();
707 }
708 
709 LogicalResult ModuleTranslation::convertFunctions() {
710   // Convert functions.
711   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
712     // Ignore external functions.
713     if (function.isExternal())
714       continue;
715 
716     if (failed(convertOneFunction(function)))
717       return failure();
718   }
719 
720   return success();
721 }
722 
723 llvm::MDNode *
724 ModuleTranslation::getAccessGroup(Operation &opInst,
725                                   SymbolRefAttr accessGroupRef) const {
726   auto metadataName = accessGroupRef.getRootReference();
727   auto accessGroupName = accessGroupRef.getLeafReference();
728   auto metadataOp = SymbolTable::lookupNearestSymbolFrom<LLVM::MetadataOp>(
729       opInst.getParentOp(), metadataName);
730   auto *accessGroupOp =
731       SymbolTable::lookupNearestSymbolFrom(metadataOp, accessGroupName);
732   return accessGroupMetadataMapping.lookup(accessGroupOp);
733 }
734 
735 LogicalResult ModuleTranslation::createAccessGroupMetadata() {
736   mlirModule->walk([&](LLVM::MetadataOp metadatas) {
737     metadatas.walk([&](LLVM::AccessGroupMetadataOp op) {
738       llvm::LLVMContext &ctx = llvmModule->getContext();
739       llvm::MDNode *accessGroup = llvm::MDNode::getDistinct(ctx, {});
740       accessGroupMetadataMapping.insert({op, accessGroup});
741     });
742   });
743   return success();
744 }
745 
746 void ModuleTranslation::setAccessGroupsMetadata(Operation *op,
747                                                 llvm::Instruction *inst) {
748   auto accessGroups =
749       op->getAttrOfType<ArrayAttr>(LLVMDialect::getAccessGroupsAttrName());
750   if (accessGroups && !accessGroups.empty()) {
751     llvm::Module *module = inst->getModule();
752     SmallVector<llvm::Metadata *> metadatas;
753     for (SymbolRefAttr accessGroupRef :
754          accessGroups.getAsRange<SymbolRefAttr>())
755       metadatas.push_back(getAccessGroup(*op, accessGroupRef));
756 
757     llvm::MDNode *unionMD = nullptr;
758     if (metadatas.size() == 1)
759       unionMD = llvm::cast<llvm::MDNode>(metadatas.front());
760     else if (metadatas.size() >= 2)
761       unionMD = llvm::MDNode::get(module->getContext(), metadatas);
762 
763     inst->setMetadata(module->getMDKindID("llvm.access.group"), unionMD);
764   }
765 }
766 
767 llvm::Type *ModuleTranslation::convertType(Type type) {
768   return typeTranslator.translateType(type);
769 }
770 
771 /// A helper to look up remapped operands in the value remapping table.`
772 SmallVector<llvm::Value *, 8>
773 ModuleTranslation::lookupValues(ValueRange values) {
774   SmallVector<llvm::Value *, 8> remapped;
775   remapped.reserve(values.size());
776   for (Value v : values)
777     remapped.push_back(lookupValue(v));
778   return remapped;
779 }
780 
781 const llvm::DILocation *
782 ModuleTranslation::translateLoc(Location loc, llvm::DILocalScope *scope) {
783   return debugTranslation->translateLoc(loc, scope);
784 }
785 
786 llvm::NamedMDNode *
787 ModuleTranslation::getOrInsertNamedModuleMetadata(StringRef name) {
788   return llvmModule->getOrInsertNamedMetadata(name);
789 }
790 
791 void ModuleTranslation::StackFrame::anchor() {}
792 
793 static std::unique_ptr<llvm::Module>
794 prepareLLVMModule(Operation *m, llvm::LLVMContext &llvmContext,
795                   StringRef name) {
796   m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>();
797   auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext);
798   if (auto dataLayoutAttr =
799           m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName()))
800     llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue());
801   if (auto targetTripleAttr =
802           m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName()))
803     llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue());
804 
805   // Inject declarations for `malloc` and `free` functions that can be used in
806   // memref allocation/deallocation coming from standard ops lowering.
807   llvm::IRBuilder<> builder(llvmContext);
808   llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(),
809                                   builder.getInt64Ty());
810   llvmModule->getOrInsertFunction("free", builder.getVoidTy(),
811                                   builder.getInt8PtrTy());
812 
813   return llvmModule;
814 }
815 
816 std::unique_ptr<llvm::Module>
817 mlir::translateModuleToLLVMIR(Operation *module, llvm::LLVMContext &llvmContext,
818                               StringRef name) {
819   if (!satisfiesLLVMModule(module))
820     return nullptr;
821   if (failed(checkSupportedModuleOps(module)))
822     return nullptr;
823   std::unique_ptr<llvm::Module> llvmModule =
824       prepareLLVMModule(module, llvmContext, name);
825 
826   LLVM::ensureDistinctSuccessors(module);
827 
828   ModuleTranslation translator(module, std::move(llvmModule));
829   if (failed(translator.convertFunctionSignatures()))
830     return nullptr;
831   if (failed(translator.convertGlobals()))
832     return nullptr;
833   if (failed(translator.createAccessGroupMetadata()))
834     return nullptr;
835   if (failed(translator.convertFunctions()))
836     return nullptr;
837   if (llvm::verifyModule(*translator.llvmModule, &llvm::errs()))
838     return nullptr;
839 
840   return std::move(translator.llvmModule);
841 }
842