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 "mlir/Dialect/LLVMIR/LLVMDialect.h"
17 #include "mlir/IR/Attributes.h"
18 #include "mlir/IR/Module.h"
19 #include "mlir/IR/StandardTypes.h"
20 #include "mlir/Support/LLVM.h"
21 
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/IR/BasicBlock.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/LLVMContext.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Transforms/Utils/Cloning.h"
30 
31 using namespace mlir;
32 using namespace mlir::LLVM;
33 
34 #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc"
35 
36 /// Builds a constant of a sequential LLVM type `type`, potentially containing
37 /// other sequential types recursively, from the individual constant values
38 /// provided in `constants`. `shape` contains the number of elements in nested
39 /// sequential types. Reports errors at `loc` and returns nullptr on error.
40 static llvm::Constant *
41 buildSequentialConstant(ArrayRef<llvm::Constant *> &constants,
42                         ArrayRef<int64_t> shape, llvm::Type *type,
43                         Location loc) {
44   if (shape.empty()) {
45     llvm::Constant *result = constants.front();
46     constants = constants.drop_front();
47     return result;
48   }
49 
50   if (!isa<llvm::SequentialType>(type)) {
51     emitError(loc) << "expected sequential LLVM types wrapping a scalar";
52     return nullptr;
53   }
54 
55   llvm::Type *elementType = type->getSequentialElementType();
56   SmallVector<llvm::Constant *, 8> nested;
57   nested.reserve(shape.front());
58   for (int64_t i = 0; i < shape.front(); ++i) {
59     nested.push_back(buildSequentialConstant(constants, shape.drop_front(),
60                                              elementType, loc));
61     if (!nested.back())
62       return nullptr;
63   }
64 
65   if (shape.size() == 1 && type->isVectorTy())
66     return llvm::ConstantVector::get(nested);
67   return llvm::ConstantArray::get(
68       llvm::ArrayType::get(elementType, shape.front()), nested);
69 }
70 
71 /// Returns the first non-sequential type nested in sequential types.
72 static llvm::Type *getInnermostElementType(llvm::Type *type) {
73   while (isa<llvm::SequentialType>(type))
74     type = type->getSequentialElementType();
75   return type;
76 }
77 
78 /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
79 /// This currently supports integer, floating point, splat and dense element
80 /// attributes and combinations thereof.  In case of error, report it to `loc`
81 /// and return nullptr.
82 llvm::Constant *ModuleTranslation::getLLVMConstant(llvm::Type *llvmType,
83                                                    Attribute attr,
84                                                    Location loc) {
85   if (!attr)
86     return llvm::UndefValue::get(llvmType);
87   if (llvmType->isStructTy()) {
88     emitError(loc, "struct types are not supported in constants");
89     return nullptr;
90   }
91   if (auto intAttr = attr.dyn_cast<IntegerAttr>())
92     return llvm::ConstantInt::get(llvmType, intAttr.getValue());
93   if (auto floatAttr = attr.dyn_cast<FloatAttr>())
94     return llvm::ConstantFP::get(llvmType, floatAttr.getValue());
95   if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>())
96     return functionMapping.lookup(funcAttr.getValue());
97   if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) {
98     auto *sequentialType = cast<llvm::SequentialType>(llvmType);
99     auto elementType = sequentialType->getElementType();
100     uint64_t numElements = sequentialType->getNumElements();
101     // Splat value is a scalar. Extract it only if the element type is not
102     // another sequence type. The recursion terminates because each step removes
103     // one outer sequential type.
104     llvm::Constant *child = getLLVMConstant(
105         elementType,
106         isa<llvm::SequentialType>(elementType) ? splatAttr
107                                                : splatAttr.getSplatValue(),
108         loc);
109     if (!child)
110       return nullptr;
111     if (llvmType->isVectorTy())
112       return llvm::ConstantVector::getSplat(numElements, child);
113     if (llvmType->isArrayTy()) {
114       auto arrayType = llvm::ArrayType::get(elementType, numElements);
115       SmallVector<llvm::Constant *, 8> constants(numElements, child);
116       return llvm::ConstantArray::get(arrayType, constants);
117     }
118   }
119 
120   if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) {
121     assert(elementsAttr.getType().hasStaticShape());
122     assert(elementsAttr.getNumElements() != 0 &&
123            "unexpected empty elements attribute");
124     assert(!elementsAttr.getType().getShape().empty() &&
125            "unexpected empty elements attribute shape");
126 
127     SmallVector<llvm::Constant *, 8> constants;
128     constants.reserve(elementsAttr.getNumElements());
129     llvm::Type *innermostType = getInnermostElementType(llvmType);
130     for (auto n : elementsAttr.getValues<Attribute>()) {
131       constants.push_back(getLLVMConstant(innermostType, n, loc));
132       if (!constants.back())
133         return nullptr;
134     }
135     ArrayRef<llvm::Constant *> constantsRef = constants;
136     llvm::Constant *result = buildSequentialConstant(
137         constantsRef, elementsAttr.getType().getShape(), llvmType, loc);
138     assert(constantsRef.empty() && "did not consume all elemental constants");
139     return result;
140   }
141 
142   if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
143     return llvm::ConstantDataArray::get(
144         llvmModule->getContext(), ArrayRef<char>{stringAttr.getValue().data(),
145                                                  stringAttr.getValue().size()});
146   }
147   emitError(loc, "unsupported constant value");
148   return nullptr;
149 }
150 
151 /// Convert MLIR integer comparison predicate to LLVM IR comparison predicate.
152 static llvm::CmpInst::Predicate getLLVMCmpPredicate(ICmpPredicate p) {
153   switch (p) {
154   case LLVM::ICmpPredicate::eq:
155     return llvm::CmpInst::Predicate::ICMP_EQ;
156   case LLVM::ICmpPredicate::ne:
157     return llvm::CmpInst::Predicate::ICMP_NE;
158   case LLVM::ICmpPredicate::slt:
159     return llvm::CmpInst::Predicate::ICMP_SLT;
160   case LLVM::ICmpPredicate::sle:
161     return llvm::CmpInst::Predicate::ICMP_SLE;
162   case LLVM::ICmpPredicate::sgt:
163     return llvm::CmpInst::Predicate::ICMP_SGT;
164   case LLVM::ICmpPredicate::sge:
165     return llvm::CmpInst::Predicate::ICMP_SGE;
166   case LLVM::ICmpPredicate::ult:
167     return llvm::CmpInst::Predicate::ICMP_ULT;
168   case LLVM::ICmpPredicate::ule:
169     return llvm::CmpInst::Predicate::ICMP_ULE;
170   case LLVM::ICmpPredicate::ugt:
171     return llvm::CmpInst::Predicate::ICMP_UGT;
172   case LLVM::ICmpPredicate::uge:
173     return llvm::CmpInst::Predicate::ICMP_UGE;
174   }
175   llvm_unreachable("incorrect comparison predicate");
176 }
177 
178 static llvm::CmpInst::Predicate getLLVMCmpPredicate(FCmpPredicate p) {
179   switch (p) {
180   case LLVM::FCmpPredicate::_false:
181     return llvm::CmpInst::Predicate::FCMP_FALSE;
182   case LLVM::FCmpPredicate::oeq:
183     return llvm::CmpInst::Predicate::FCMP_OEQ;
184   case LLVM::FCmpPredicate::ogt:
185     return llvm::CmpInst::Predicate::FCMP_OGT;
186   case LLVM::FCmpPredicate::oge:
187     return llvm::CmpInst::Predicate::FCMP_OGE;
188   case LLVM::FCmpPredicate::olt:
189     return llvm::CmpInst::Predicate::FCMP_OLT;
190   case LLVM::FCmpPredicate::ole:
191     return llvm::CmpInst::Predicate::FCMP_OLE;
192   case LLVM::FCmpPredicate::one:
193     return llvm::CmpInst::Predicate::FCMP_ONE;
194   case LLVM::FCmpPredicate::ord:
195     return llvm::CmpInst::Predicate::FCMP_ORD;
196   case LLVM::FCmpPredicate::ueq:
197     return llvm::CmpInst::Predicate::FCMP_UEQ;
198   case LLVM::FCmpPredicate::ugt:
199     return llvm::CmpInst::Predicate::FCMP_UGT;
200   case LLVM::FCmpPredicate::uge:
201     return llvm::CmpInst::Predicate::FCMP_UGE;
202   case LLVM::FCmpPredicate::ult:
203     return llvm::CmpInst::Predicate::FCMP_ULT;
204   case LLVM::FCmpPredicate::ule:
205     return llvm::CmpInst::Predicate::FCMP_ULE;
206   case LLVM::FCmpPredicate::une:
207     return llvm::CmpInst::Predicate::FCMP_UNE;
208   case LLVM::FCmpPredicate::uno:
209     return llvm::CmpInst::Predicate::FCMP_UNO;
210   case LLVM::FCmpPredicate::_true:
211     return llvm::CmpInst::Predicate::FCMP_TRUE;
212   }
213   llvm_unreachable("incorrect comparison predicate");
214 }
215 
216 static llvm::AtomicRMWInst::BinOp getLLVMAtomicBinOp(AtomicBinOp op) {
217   switch (op) {
218   case LLVM::AtomicBinOp::xchg:
219     return llvm::AtomicRMWInst::BinOp::Xchg;
220   case LLVM::AtomicBinOp::add:
221     return llvm::AtomicRMWInst::BinOp::Add;
222   case LLVM::AtomicBinOp::sub:
223     return llvm::AtomicRMWInst::BinOp::Sub;
224   case LLVM::AtomicBinOp::_and:
225     return llvm::AtomicRMWInst::BinOp::And;
226   case LLVM::AtomicBinOp::nand:
227     return llvm::AtomicRMWInst::BinOp::Nand;
228   case LLVM::AtomicBinOp::_or:
229     return llvm::AtomicRMWInst::BinOp::Or;
230   case LLVM::AtomicBinOp::_xor:
231     return llvm::AtomicRMWInst::BinOp::Xor;
232   case LLVM::AtomicBinOp::max:
233     return llvm::AtomicRMWInst::BinOp::Max;
234   case LLVM::AtomicBinOp::min:
235     return llvm::AtomicRMWInst::BinOp::Min;
236   case LLVM::AtomicBinOp::umax:
237     return llvm::AtomicRMWInst::BinOp::UMax;
238   case LLVM::AtomicBinOp::umin:
239     return llvm::AtomicRMWInst::BinOp::UMin;
240   case LLVM::AtomicBinOp::fadd:
241     return llvm::AtomicRMWInst::BinOp::FAdd;
242   case LLVM::AtomicBinOp::fsub:
243     return llvm::AtomicRMWInst::BinOp::FSub;
244   }
245   llvm_unreachable("incorrect atomic binary operator");
246 }
247 
248 static llvm::AtomicOrdering getLLVMAtomicOrdering(AtomicOrdering ordering) {
249   switch (ordering) {
250   case LLVM::AtomicOrdering::not_atomic:
251     return llvm::AtomicOrdering::NotAtomic;
252   case LLVM::AtomicOrdering::unordered:
253     return llvm::AtomicOrdering::Unordered;
254   case LLVM::AtomicOrdering::monotonic:
255     return llvm::AtomicOrdering::Monotonic;
256   case LLVM::AtomicOrdering::acquire:
257     return llvm::AtomicOrdering::Acquire;
258   case LLVM::AtomicOrdering::release:
259     return llvm::AtomicOrdering::Release;
260   case LLVM::AtomicOrdering::acq_rel:
261     return llvm::AtomicOrdering::AcquireRelease;
262   case LLVM::AtomicOrdering::seq_cst:
263     return llvm::AtomicOrdering::SequentiallyConsistent;
264   }
265   llvm_unreachable("incorrect atomic ordering");
266 }
267 
268 /// Given a single MLIR operation, create the corresponding LLVM IR operation
269 /// using the `builder`.  LLVM IR Builder does not have a generic interface so
270 /// this has to be a long chain of `if`s calling different functions with a
271 /// different number of arguments.
272 LogicalResult ModuleTranslation::convertOperation(Operation &opInst,
273                                                   llvm::IRBuilder<> &builder) {
274   auto extractPosition = [](ArrayAttr attr) {
275     SmallVector<unsigned, 4> position;
276     position.reserve(attr.size());
277     for (Attribute v : attr)
278       position.push_back(v.cast<IntegerAttr>().getValue().getZExtValue());
279     return position;
280   };
281 
282 #include "mlir/Dialect/LLVMIR/LLVMConversions.inc"
283 
284   // Emit function calls.  If the "callee" attribute is present, this is a
285   // direct function call and we also need to look up the remapped function
286   // itself.  Otherwise, this is an indirect call and the callee is the first
287   // operand, look it up as a normal value.  Return the llvm::Value representing
288   // the function result, which may be of llvm::VoidTy type.
289   auto convertCall = [this, &builder](Operation &op) -> llvm::Value * {
290     auto operands = lookupValues(op.getOperands());
291     ArrayRef<llvm::Value *> operandsRef(operands);
292     if (auto attr = op.getAttrOfType<FlatSymbolRefAttr>("callee")) {
293       return builder.CreateCall(functionMapping.lookup(attr.getValue()),
294                                 operandsRef);
295     } else {
296       return builder.CreateCall(operandsRef.front(), operandsRef.drop_front());
297     }
298   };
299 
300   // Emit calls.  If the called function has a result, remap the corresponding
301   // value.  Note that LLVM IR dialect CallOp has either 0 or 1 result.
302   if (isa<LLVM::CallOp>(opInst)) {
303     llvm::Value *result = convertCall(opInst);
304     if (opInst.getNumResults() != 0) {
305       valueMapping[opInst.getResult(0)] = result;
306       return success();
307     }
308     // Check that LLVM call returns void for 0-result functions.
309     return success(result->getType()->isVoidTy());
310   }
311 
312   if (auto invOp = dyn_cast<LLVM::InvokeOp>(opInst)) {
313     auto operands = lookupValues(opInst.getOperands());
314     ArrayRef<llvm::Value *> operandsRef(operands);
315     if (auto attr = opInst.getAttrOfType<FlatSymbolRefAttr>("callee"))
316       builder.CreateInvoke(functionMapping.lookup(attr.getValue()),
317                            blockMapping[invOp.getSuccessor(0)],
318                            blockMapping[invOp.getSuccessor(1)], operandsRef);
319     else
320       builder.CreateInvoke(
321           operandsRef.front(), blockMapping[invOp.getSuccessor(0)],
322           blockMapping[invOp.getSuccessor(1)], operandsRef.drop_front());
323     return success();
324   }
325 
326   if (auto lpOp = dyn_cast<LLVM::LandingpadOp>(opInst)) {
327     llvm::Type *ty = lpOp.getType().dyn_cast<LLVMType>().getUnderlyingType();
328     llvm::LandingPadInst *lpi =
329         builder.CreateLandingPad(ty, lpOp.getNumOperands());
330 
331     // Add clauses
332     for (auto operand : lookupValues(lpOp.getOperands())) {
333       // All operands should be constant - checked by verifier
334       if (auto constOperand = dyn_cast<llvm::Constant>(operand))
335         lpi->addClause(constOperand);
336     }
337     return success();
338   }
339 
340   // Emit branches.  We need to look up the remapped blocks and ignore the block
341   // arguments that were transformed into PHI nodes.
342   if (auto brOp = dyn_cast<LLVM::BrOp>(opInst)) {
343     builder.CreateBr(blockMapping[brOp.getSuccessor(0)]);
344     return success();
345   }
346   if (auto condbrOp = dyn_cast<LLVM::CondBrOp>(opInst)) {
347     builder.CreateCondBr(valueMapping.lookup(condbrOp.getOperand(0)),
348                          blockMapping[condbrOp.getSuccessor(0)],
349                          blockMapping[condbrOp.getSuccessor(1)]);
350     return success();
351   }
352 
353   // Emit addressof.  We need to look up the global value referenced by the
354   // operation and store it in the MLIR-to-LLVM value mapping.  This does not
355   // emit any LLVM instruction.
356   if (auto addressOfOp = dyn_cast<LLVM::AddressOfOp>(opInst)) {
357     LLVM::GlobalOp global = addressOfOp.getGlobal();
358     // The verifier should not have allowed this.
359     assert(global && "referencing an undefined global");
360 
361     valueMapping[addressOfOp.getResult()] = globalsMapping.lookup(global);
362     return success();
363   }
364 
365   return opInst.emitError("unsupported or non-LLVM operation: ")
366          << opInst.getName();
367 }
368 
369 /// Convert block to LLVM IR.  Unless `ignoreArguments` is set, emit PHI nodes
370 /// to define values corresponding to the MLIR block arguments.  These nodes
371 /// are not connected to the source basic blocks, which may not exist yet.
372 LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments) {
373   llvm::IRBuilder<> builder(blockMapping[&bb]);
374 
375   // Before traversing operations, make block arguments available through
376   // value remapping and PHI nodes, but do not add incoming edges for the PHI
377   // nodes just yet: those values may be defined by this or following blocks.
378   // This step is omitted if "ignoreArguments" is set.  The arguments of the
379   // first block have been already made available through the remapping of
380   // LLVM function arguments.
381   if (!ignoreArguments) {
382     auto predecessors = bb.getPredecessors();
383     unsigned numPredecessors =
384         std::distance(predecessors.begin(), predecessors.end());
385     for (auto arg : bb.getArguments()) {
386       auto wrappedType = arg.getType().dyn_cast<LLVM::LLVMType>();
387       if (!wrappedType)
388         return emitError(bb.front().getLoc(),
389                          "block argument does not have an LLVM type");
390       llvm::Type *type = wrappedType.getUnderlyingType();
391       llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors);
392       valueMapping[arg] = phi;
393     }
394   }
395 
396   // Traverse operations.
397   for (auto &op : bb) {
398     if (failed(convertOperation(op, builder)))
399       return failure();
400   }
401 
402   return success();
403 }
404 
405 /// Create named global variables that correspond to llvm.mlir.global
406 /// definitions.
407 void ModuleTranslation::convertGlobals() {
408   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
409     llvm::Type *type = op.getType().getUnderlyingType();
410     llvm::Constant *cst = llvm::UndefValue::get(type);
411     if (op.getValueOrNull()) {
412       // String attributes are treated separately because they cannot appear as
413       // in-function constants and are thus not supported by getLLVMConstant.
414       if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) {
415         cst = llvm::ConstantDataArray::getString(
416             llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
417         type = cst->getType();
418       } else {
419         cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc());
420       }
421     } else if (Block *initializer = op.getInitializerBlock()) {
422       llvm::IRBuilder<> builder(llvmModule->getContext());
423       for (auto &op : initializer->without_terminator()) {
424         if (failed(convertOperation(op, builder)) ||
425             !isa<llvm::Constant>(valueMapping.lookup(op.getResult(0)))) {
426           emitError(op.getLoc(), "unemittable constant value");
427           return;
428         }
429       }
430       ReturnOp ret = cast<ReturnOp>(initializer->getTerminator());
431       cst = cast<llvm::Constant>(valueMapping.lookup(ret.getOperand(0)));
432     }
433 
434     auto linkage = convertLinkageToLLVM(op.linkage());
435     bool anyExternalLinkage =
436         (linkage == llvm::GlobalVariable::ExternalLinkage ||
437          linkage == llvm::GlobalVariable::ExternalWeakLinkage);
438     auto addrSpace = op.addr_space().getLimitedValue();
439     auto *var = new llvm::GlobalVariable(
440         *llvmModule, type, op.constant(), linkage,
441         anyExternalLinkage ? nullptr : cst, op.sym_name(),
442         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace);
443 
444     globalsMapping.try_emplace(op, var);
445   }
446 }
447 
448 /// Get the SSA value passed to the current block from the terminator operation
449 /// of its predecessor.
450 static Value getPHISourceValue(Block *current, Block *pred,
451                                unsigned numArguments, unsigned index) {
452   auto &terminator = *pred->getTerminator();
453   if (isa<LLVM::BrOp>(terminator)) {
454     return terminator.getOperand(index);
455   }
456 
457   // For conditional branches, we need to check if the current block is reached
458   // through the "true" or the "false" branch and take the relevant operands.
459   auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator);
460   assert(condBranchOp &&
461          "only branch operations can be terminators of a block that "
462          "has successors");
463   assert((condBranchOp.getSuccessor(0) != condBranchOp.getSuccessor(1)) &&
464          "successors with arguments in LLVM conditional branches must be "
465          "different blocks");
466 
467   return condBranchOp.getSuccessor(0) == current
468              ? terminator.getSuccessorOperand(0, index)
469              : terminator.getSuccessorOperand(1, index);
470 }
471 
472 void ModuleTranslation::connectPHINodes(LLVMFuncOp func) {
473   // Skip the first block, it cannot be branched to and its arguments correspond
474   // to the arguments of the LLVM function.
475   for (auto it = std::next(func.begin()), eit = func.end(); it != eit; ++it) {
476     Block *bb = &*it;
477     llvm::BasicBlock *llvmBB = blockMapping.lookup(bb);
478     auto phis = llvmBB->phis();
479     auto numArguments = bb->getNumArguments();
480     assert(numArguments == std::distance(phis.begin(), phis.end()));
481     for (auto &numberedPhiNode : llvm::enumerate(phis)) {
482       auto &phiNode = numberedPhiNode.value();
483       unsigned index = numberedPhiNode.index();
484       for (auto *pred : bb->getPredecessors()) {
485         phiNode.addIncoming(valueMapping.lookup(getPHISourceValue(
486                                 bb, pred, numArguments, index)),
487                             blockMapping.lookup(pred));
488       }
489     }
490   }
491 }
492 
493 // TODO(mlir-team): implement an iterative version
494 static void topologicalSortImpl(llvm::SetVector<Block *> &blocks, Block *b) {
495   blocks.insert(b);
496   for (Block *bb : b->getSuccessors()) {
497     if (blocks.count(bb) == 0)
498       topologicalSortImpl(blocks, bb);
499   }
500 }
501 
502 /// Sort function blocks topologically.
503 static llvm::SetVector<Block *> topologicalSort(LLVMFuncOp f) {
504   // For each blocks that has not been visited yet (i.e. that has no
505   // predecessors), add it to the list and traverse its successors in DFS
506   // preorder.
507   llvm::SetVector<Block *> blocks;
508   for (Block &b : f.getBlocks()) {
509     if (blocks.count(&b) == 0)
510       topologicalSortImpl(blocks, &b);
511   }
512   assert(blocks.size() == f.getBlocks().size() && "some blocks are not sorted");
513 
514   return blocks;
515 }
516 
517 LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) {
518   // Clear the block and value mappings, they are only relevant within one
519   // function.
520   blockMapping.clear();
521   valueMapping.clear();
522   llvm::Function *llvmFunc = functionMapping.lookup(func.getName());
523   // Add function arguments to the value remapping table.
524   // If there was noalias info then we decorate each argument accordingly.
525   unsigned int argIdx = 0;
526   for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) {
527     llvm::Argument &llvmArg = std::get<1>(kvp);
528     BlockArgument mlirArg = std::get<0>(kvp);
529 
530     if (auto attr = func.getArgAttrOfType<BoolAttr>(argIdx, "llvm.noalias")) {
531       // NB: Attribute already verified to be boolean, so check if we can indeed
532       // attach the attribute to this argument, based on its type.
533       auto argTy = mlirArg.getType().dyn_cast<LLVM::LLVMType>();
534       if (!argTy.getUnderlyingType()->isPointerTy())
535         return func.emitError(
536             "llvm.noalias attribute attached to LLVM non-pointer argument");
537       if (attr.getValue())
538         llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias);
539     }
540     valueMapping[mlirArg] = &llvmArg;
541     argIdx++;
542   }
543 
544   // First, create all blocks so we can jump to them.
545   llvm::LLVMContext &llvmContext = llvmFunc->getContext();
546   for (auto &bb : func) {
547     auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
548     llvmBB->insertInto(llvmFunc);
549     blockMapping[&bb] = llvmBB;
550   }
551 
552   // Then, convert blocks one by one in topological order to ensure defs are
553   // converted before uses.
554   auto blocks = topologicalSort(func);
555   for (auto indexedBB : llvm::enumerate(blocks)) {
556     auto *bb = indexedBB.value();
557     if (failed(convertBlock(*bb, /*ignoreArguments=*/indexedBB.index() == 0)))
558       return failure();
559   }
560 
561   // Finally, after all blocks have been traversed and values mapped, connect
562   // the PHI nodes to the results of preceding blocks.
563   connectPHINodes(func);
564   return success();
565 }
566 
567 LogicalResult ModuleTranslation::checkSupportedModuleOps(Operation *m) {
568   for (Operation &o : getModuleBody(m).getOperations())
569     if (!isa<LLVM::LLVMFuncOp>(&o) && !isa<LLVM::GlobalOp>(&o) &&
570         !o.isKnownTerminator())
571       return o.emitOpError("unsupported module-level operation");
572   return success();
573 }
574 
575 LogicalResult ModuleTranslation::convertFunctions() {
576   // Declare all functions first because there may be function calls that form a
577   // call graph with cycles.
578   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
579     llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction(
580         function.getName(),
581         cast<llvm::FunctionType>(function.getType().getUnderlyingType()));
582     assert(isa<llvm::Function>(llvmFuncCst.getCallee()));
583     functionMapping[function.getName()] =
584         cast<llvm::Function>(llvmFuncCst.getCallee());
585   }
586 
587   // Convert functions.
588   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
589     // Ignore external functions.
590     if (function.isExternal())
591       continue;
592 
593     if (failed(convertOneFunction(function)))
594       return failure();
595   }
596 
597   return success();
598 }
599 
600 /// A helper to look up remapped operands in the value remapping table.`
601 SmallVector<llvm::Value *, 8>
602 ModuleTranslation::lookupValues(ValueRange values) {
603   SmallVector<llvm::Value *, 8> remapped;
604   remapped.reserve(values.size());
605   for (Value v : values)
606     remapped.push_back(valueMapping.lookup(v));
607   return remapped;
608 }
609 
610 std::unique_ptr<llvm::Module>
611 ModuleTranslation::prepareLLVMModule(Operation *m) {
612   auto *dialect = m->getContext()->getRegisteredDialect<LLVM::LLVMDialect>();
613   assert(dialect && "LLVM dialect must be registered");
614 
615   auto llvmModule = llvm::CloneModule(dialect->getLLVMModule());
616   if (!llvmModule)
617     return nullptr;
618 
619   llvm::LLVMContext &llvmContext = llvmModule->getContext();
620   llvm::IRBuilder<> builder(llvmContext);
621 
622   // Inject declarations for `malloc` and `free` functions that can be used in
623   // memref allocation/deallocation coming from standard ops lowering.
624   llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(),
625                                   builder.getInt64Ty());
626   llvmModule->getOrInsertFunction("free", builder.getVoidTy(),
627                                   builder.getInt8PtrTy());
628 
629   return llvmModule;
630 }
631