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