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