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/OpenMP/OpenMPDialect.h"
19 #include "mlir/IR/Attributes.h"
20 #include "mlir/IR/BuiltinOps.h"
21 #include "mlir/IR/RegionGraphTraits.h"
22 #include "mlir/IR/StandardTypes.h"
23 #include "mlir/Support/LLVM.h"
24 #include "mlir/Target/LLVMIR/TypeTranslation.h"
25 #include "llvm/ADT/TypeSwitch.h"
26 
27 #include "llvm/ADT/PostOrderIterator.h"
28 #include "llvm/ADT/SetVector.h"
29 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h"
30 #include "llvm/IR/BasicBlock.h"
31 #include "llvm/IR/CFG.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/IRBuilder.h"
35 #include "llvm/IR/InlineAsm.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/MDBuilder.h"
38 #include "llvm/IR/Module.h"
39 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
40 #include "llvm/Transforms/Utils/Cloning.h"
41 
42 using namespace mlir;
43 using namespace mlir::LLVM;
44 using namespace mlir::LLVM::detail;
45 
46 #include "mlir/Dialect/LLVMIR/LLVMConversionEnumsToLLVM.inc"
47 
48 /// Builds a constant of a sequential LLVM type `type`, potentially containing
49 /// other sequential types recursively, from the individual constant values
50 /// provided in `constants`. `shape` contains the number of elements in nested
51 /// sequential types. Reports errors at `loc` and returns nullptr on error.
52 static llvm::Constant *
53 buildSequentialConstant(ArrayRef<llvm::Constant *> &constants,
54                         ArrayRef<int64_t> shape, llvm::Type *type,
55                         Location loc) {
56   if (shape.empty()) {
57     llvm::Constant *result = constants.front();
58     constants = constants.drop_front();
59     return result;
60   }
61 
62   llvm::Type *elementType;
63   if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
64     elementType = arrayTy->getElementType();
65   } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
66     elementType = vectorTy->getElementType();
67   } else {
68     emitError(loc) << "expected sequential LLVM types wrapping a scalar";
69     return nullptr;
70   }
71 
72   SmallVector<llvm::Constant *, 8> nested;
73   nested.reserve(shape.front());
74   for (int64_t i = 0; i < shape.front(); ++i) {
75     nested.push_back(buildSequentialConstant(constants, shape.drop_front(),
76                                              elementType, loc));
77     if (!nested.back())
78       return nullptr;
79   }
80 
81   if (shape.size() == 1 && type->isVectorTy())
82     return llvm::ConstantVector::get(nested);
83   return llvm::ConstantArray::get(
84       llvm::ArrayType::get(elementType, shape.front()), nested);
85 }
86 
87 /// Returns the first non-sequential type nested in sequential types.
88 static llvm::Type *getInnermostElementType(llvm::Type *type) {
89   do {
90     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(type)) {
91       type = arrayTy->getElementType();
92     } else if (auto *vectorTy = dyn_cast<llvm::VectorType>(type)) {
93       type = vectorTy->getElementType();
94     } else {
95       return type;
96     }
97   } while (1);
98 }
99 
100 /// Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
101 /// This currently supports integer, floating point, splat and dense element
102 /// attributes and combinations thereof.  In case of error, report it to `loc`
103 /// and return nullptr.
104 llvm::Constant *ModuleTranslation::getLLVMConstant(llvm::Type *llvmType,
105                                                    Attribute attr,
106                                                    Location loc) {
107   if (!attr)
108     return llvm::UndefValue::get(llvmType);
109   if (llvmType->isStructTy()) {
110     emitError(loc, "struct types are not supported in constants");
111     return nullptr;
112   }
113   // For integer types, we allow a mismatch in sizes as the index type in
114   // MLIR might have a different size than the index type in the LLVM module.
115   if (auto intAttr = attr.dyn_cast<IntegerAttr>())
116     return llvm::ConstantInt::get(
117         llvmType,
118         intAttr.getValue().sextOrTrunc(llvmType->getIntegerBitWidth()));
119   if (auto floatAttr = attr.dyn_cast<FloatAttr>())
120     return llvm::ConstantFP::get(llvmType, floatAttr.getValue());
121   if (auto funcAttr = attr.dyn_cast<FlatSymbolRefAttr>())
122     return llvm::ConstantExpr::getBitCast(
123         functionMapping.lookup(funcAttr.getValue()), llvmType);
124   if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) {
125     llvm::Type *elementType;
126     uint64_t numElements;
127     if (auto *arrayTy = dyn_cast<llvm::ArrayType>(llvmType)) {
128       elementType = arrayTy->getElementType();
129       numElements = arrayTy->getNumElements();
130     } else {
131       auto *vectorTy = cast<llvm::FixedVectorType>(llvmType);
132       elementType = vectorTy->getElementType();
133       numElements = vectorTy->getNumElements();
134     }
135     // Splat value is a scalar. Extract it only if the element type is not
136     // another sequence type. The recursion terminates because each step removes
137     // one outer sequential type.
138     bool elementTypeSequential =
139         isa<llvm::ArrayType, llvm::VectorType>(elementType);
140     llvm::Constant *child = getLLVMConstant(
141         elementType,
142         elementTypeSequential ? splatAttr : splatAttr.getSplatValue(), loc);
143     if (!child)
144       return nullptr;
145     if (llvmType->isVectorTy())
146       return llvm::ConstantVector::getSplat(
147           llvm::ElementCount::get(numElements, /*Scalable=*/false), child);
148     if (llvmType->isArrayTy()) {
149       auto *arrayType = llvm::ArrayType::get(elementType, numElements);
150       SmallVector<llvm::Constant *, 8> constants(numElements, child);
151       return llvm::ConstantArray::get(arrayType, constants);
152     }
153   }
154 
155   if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) {
156     assert(elementsAttr.getType().hasStaticShape());
157     assert(elementsAttr.getNumElements() != 0 &&
158            "unexpected empty elements attribute");
159     assert(!elementsAttr.getType().getShape().empty() &&
160            "unexpected empty elements attribute shape");
161 
162     SmallVector<llvm::Constant *, 8> constants;
163     constants.reserve(elementsAttr.getNumElements());
164     llvm::Type *innermostType = getInnermostElementType(llvmType);
165     for (auto n : elementsAttr.getValues<Attribute>()) {
166       constants.push_back(getLLVMConstant(innermostType, n, loc));
167       if (!constants.back())
168         return nullptr;
169     }
170     ArrayRef<llvm::Constant *> constantsRef = constants;
171     llvm::Constant *result = buildSequentialConstant(
172         constantsRef, elementsAttr.getType().getShape(), llvmType, loc);
173     assert(constantsRef.empty() && "did not consume all elemental constants");
174     return result;
175   }
176 
177   if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
178     return llvm::ConstantDataArray::get(
179         llvmModule->getContext(), ArrayRef<char>{stringAttr.getValue().data(),
180                                                  stringAttr.getValue().size()});
181   }
182   emitError(loc, "unsupported constant value");
183   return nullptr;
184 }
185 
186 /// Convert MLIR integer comparison predicate to LLVM IR comparison predicate.
187 static llvm::CmpInst::Predicate getLLVMCmpPredicate(ICmpPredicate p) {
188   switch (p) {
189   case LLVM::ICmpPredicate::eq:
190     return llvm::CmpInst::Predicate::ICMP_EQ;
191   case LLVM::ICmpPredicate::ne:
192     return llvm::CmpInst::Predicate::ICMP_NE;
193   case LLVM::ICmpPredicate::slt:
194     return llvm::CmpInst::Predicate::ICMP_SLT;
195   case LLVM::ICmpPredicate::sle:
196     return llvm::CmpInst::Predicate::ICMP_SLE;
197   case LLVM::ICmpPredicate::sgt:
198     return llvm::CmpInst::Predicate::ICMP_SGT;
199   case LLVM::ICmpPredicate::sge:
200     return llvm::CmpInst::Predicate::ICMP_SGE;
201   case LLVM::ICmpPredicate::ult:
202     return llvm::CmpInst::Predicate::ICMP_ULT;
203   case LLVM::ICmpPredicate::ule:
204     return llvm::CmpInst::Predicate::ICMP_ULE;
205   case LLVM::ICmpPredicate::ugt:
206     return llvm::CmpInst::Predicate::ICMP_UGT;
207   case LLVM::ICmpPredicate::uge:
208     return llvm::CmpInst::Predicate::ICMP_UGE;
209   }
210   llvm_unreachable("incorrect comparison predicate");
211 }
212 
213 static llvm::CmpInst::Predicate getLLVMCmpPredicate(FCmpPredicate p) {
214   switch (p) {
215   case LLVM::FCmpPredicate::_false:
216     return llvm::CmpInst::Predicate::FCMP_FALSE;
217   case LLVM::FCmpPredicate::oeq:
218     return llvm::CmpInst::Predicate::FCMP_OEQ;
219   case LLVM::FCmpPredicate::ogt:
220     return llvm::CmpInst::Predicate::FCMP_OGT;
221   case LLVM::FCmpPredicate::oge:
222     return llvm::CmpInst::Predicate::FCMP_OGE;
223   case LLVM::FCmpPredicate::olt:
224     return llvm::CmpInst::Predicate::FCMP_OLT;
225   case LLVM::FCmpPredicate::ole:
226     return llvm::CmpInst::Predicate::FCMP_OLE;
227   case LLVM::FCmpPredicate::one:
228     return llvm::CmpInst::Predicate::FCMP_ONE;
229   case LLVM::FCmpPredicate::ord:
230     return llvm::CmpInst::Predicate::FCMP_ORD;
231   case LLVM::FCmpPredicate::ueq:
232     return llvm::CmpInst::Predicate::FCMP_UEQ;
233   case LLVM::FCmpPredicate::ugt:
234     return llvm::CmpInst::Predicate::FCMP_UGT;
235   case LLVM::FCmpPredicate::uge:
236     return llvm::CmpInst::Predicate::FCMP_UGE;
237   case LLVM::FCmpPredicate::ult:
238     return llvm::CmpInst::Predicate::FCMP_ULT;
239   case LLVM::FCmpPredicate::ule:
240     return llvm::CmpInst::Predicate::FCMP_ULE;
241   case LLVM::FCmpPredicate::une:
242     return llvm::CmpInst::Predicate::FCMP_UNE;
243   case LLVM::FCmpPredicate::uno:
244     return llvm::CmpInst::Predicate::FCMP_UNO;
245   case LLVM::FCmpPredicate::_true:
246     return llvm::CmpInst::Predicate::FCMP_TRUE;
247   }
248   llvm_unreachable("incorrect comparison predicate");
249 }
250 
251 static llvm::AtomicRMWInst::BinOp getLLVMAtomicBinOp(AtomicBinOp op) {
252   switch (op) {
253   case LLVM::AtomicBinOp::xchg:
254     return llvm::AtomicRMWInst::BinOp::Xchg;
255   case LLVM::AtomicBinOp::add:
256     return llvm::AtomicRMWInst::BinOp::Add;
257   case LLVM::AtomicBinOp::sub:
258     return llvm::AtomicRMWInst::BinOp::Sub;
259   case LLVM::AtomicBinOp::_and:
260     return llvm::AtomicRMWInst::BinOp::And;
261   case LLVM::AtomicBinOp::nand:
262     return llvm::AtomicRMWInst::BinOp::Nand;
263   case LLVM::AtomicBinOp::_or:
264     return llvm::AtomicRMWInst::BinOp::Or;
265   case LLVM::AtomicBinOp::_xor:
266     return llvm::AtomicRMWInst::BinOp::Xor;
267   case LLVM::AtomicBinOp::max:
268     return llvm::AtomicRMWInst::BinOp::Max;
269   case LLVM::AtomicBinOp::min:
270     return llvm::AtomicRMWInst::BinOp::Min;
271   case LLVM::AtomicBinOp::umax:
272     return llvm::AtomicRMWInst::BinOp::UMax;
273   case LLVM::AtomicBinOp::umin:
274     return llvm::AtomicRMWInst::BinOp::UMin;
275   case LLVM::AtomicBinOp::fadd:
276     return llvm::AtomicRMWInst::BinOp::FAdd;
277   case LLVM::AtomicBinOp::fsub:
278     return llvm::AtomicRMWInst::BinOp::FSub;
279   }
280   llvm_unreachable("incorrect atomic binary operator");
281 }
282 
283 static llvm::AtomicOrdering getLLVMAtomicOrdering(AtomicOrdering ordering) {
284   switch (ordering) {
285   case LLVM::AtomicOrdering::not_atomic:
286     return llvm::AtomicOrdering::NotAtomic;
287   case LLVM::AtomicOrdering::unordered:
288     return llvm::AtomicOrdering::Unordered;
289   case LLVM::AtomicOrdering::monotonic:
290     return llvm::AtomicOrdering::Monotonic;
291   case LLVM::AtomicOrdering::acquire:
292     return llvm::AtomicOrdering::Acquire;
293   case LLVM::AtomicOrdering::release:
294     return llvm::AtomicOrdering::Release;
295   case LLVM::AtomicOrdering::acq_rel:
296     return llvm::AtomicOrdering::AcquireRelease;
297   case LLVM::AtomicOrdering::seq_cst:
298     return llvm::AtomicOrdering::SequentiallyConsistent;
299   }
300   llvm_unreachable("incorrect atomic ordering");
301 }
302 
303 ModuleTranslation::ModuleTranslation(Operation *module,
304                                      std::unique_ptr<llvm::Module> llvmModule)
305     : mlirModule(module), llvmModule(std::move(llvmModule)),
306       debugTranslation(
307           std::make_unique<DebugTranslation>(module, *this->llvmModule)),
308       ompDialect(module->getContext()->getLoadedDialect("omp")),
309       typeTranslator(this->llvmModule->getContext()) {
310   assert(satisfiesLLVMModule(mlirModule) &&
311          "mlirModule should honor LLVM's module semantics.");
312 }
313 ModuleTranslation::~ModuleTranslation() {
314   if (ompBuilder)
315     ompBuilder->finalize();
316 }
317 
318 /// Get the SSA value passed to the current block from the terminator operation
319 /// of its predecessor.
320 static Value getPHISourceValue(Block *current, Block *pred,
321                                unsigned numArguments, unsigned index) {
322   Operation &terminator = *pred->getTerminator();
323   if (isa<LLVM::BrOp>(terminator))
324     return terminator.getOperand(index);
325 
326   // For conditional branches, we need to check if the current block is reached
327   // through the "true" or the "false" branch and take the relevant operands.
328   auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator);
329   assert(condBranchOp &&
330          "only branch operations can be terminators of a block that "
331          "has successors");
332   assert((condBranchOp.getSuccessor(0) != condBranchOp.getSuccessor(1)) &&
333          "successors with arguments in LLVM conditional branches must be "
334          "different blocks");
335 
336   return condBranchOp.getSuccessor(0) == current
337              ? condBranchOp.trueDestOperands()[index]
338              : condBranchOp.falseDestOperands()[index];
339 }
340 
341 /// Connect the PHI nodes to the results of preceding blocks.
342 template <typename T>
343 static void
344 connectPHINodes(T &func, const DenseMap<Value, llvm::Value *> &valueMapping,
345                 const DenseMap<Block *, llvm::BasicBlock *> &blockMapping) {
346   // Skip the first block, it cannot be branched to and its arguments correspond
347   // to the arguments of the LLVM function.
348   for (auto it = std::next(func.begin()), eit = func.end(); it != eit; ++it) {
349     Block *bb = &*it;
350     llvm::BasicBlock *llvmBB = blockMapping.lookup(bb);
351     auto phis = llvmBB->phis();
352     auto numArguments = bb->getNumArguments();
353     assert(numArguments == std::distance(phis.begin(), phis.end()));
354     for (auto &numberedPhiNode : llvm::enumerate(phis)) {
355       auto &phiNode = numberedPhiNode.value();
356       unsigned index = numberedPhiNode.index();
357       for (auto *pred : bb->getPredecessors()) {
358         phiNode.addIncoming(valueMapping.lookup(getPHISourceValue(
359                                 bb, pred, numArguments, index)),
360                             blockMapping.lookup(pred));
361       }
362     }
363   }
364 }
365 
366 /// Sort function blocks topologically.
367 template <typename T>
368 static llvm::SetVector<Block *> topologicalSort(T &f) {
369   // For each block that has not been visited yet (i.e. that has no
370   // predecessors), add it to the list as well as its successors.
371   llvm::SetVector<Block *> blocks;
372   for (Block &b : f) {
373     if (blocks.count(&b) == 0) {
374       llvm::ReversePostOrderTraversal<Block *> traversal(&b);
375       blocks.insert(traversal.begin(), traversal.end());
376     }
377   }
378   assert(blocks.size() == f.getBlocks().size() && "some blocks are not sorted");
379 
380   return blocks;
381 }
382 
383 /// Convert the OpenMP parallel Operation to LLVM IR.
384 LogicalResult
385 ModuleTranslation::convertOmpParallel(Operation &opInst,
386                                       llvm::IRBuilder<> &builder) {
387   using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
388 
389   auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
390                        llvm::BasicBlock &continuationIP) {
391     llvm::LLVMContext &llvmContext = llvmModule->getContext();
392 
393     llvm::BasicBlock *codeGenIPBB = codeGenIP.getBlock();
394     llvm::Instruction *codeGenIPBBTI = codeGenIPBB->getTerminator();
395     ompContinuationIPStack.push_back(&continuationIP);
396 
397     // ParallelOp has only `1` region associated with it.
398     auto &region = cast<omp::ParallelOp>(opInst).getRegion();
399     for (auto &bb : region) {
400       auto *llvmBB = llvm::BasicBlock::Create(
401           llvmContext, "omp.par.region", codeGenIP.getBlock()->getParent());
402       blockMapping[&bb] = llvmBB;
403     }
404 
405     // Then, convert blocks one by one in topological order to ensure
406     // defs are converted before uses.
407     llvm::SetVector<Block *> blocks = topologicalSort(region);
408     for (auto indexedBB : llvm::enumerate(blocks)) {
409       Block *bb = indexedBB.value();
410       llvm::BasicBlock *curLLVMBB = blockMapping[bb];
411       if (bb->isEntryBlock()) {
412         assert(codeGenIPBBTI->getNumSuccessors() == 1 &&
413                "OpenMPIRBuilder provided entry block has multiple successors");
414         assert(codeGenIPBBTI->getSuccessor(0) == &continuationIP &&
415                "ContinuationIP is not the successor of OpenMPIRBuilder "
416                "provided entry block");
417         codeGenIPBBTI->setSuccessor(0, curLLVMBB);
418       }
419 
420       // TODO: Error not returned up the hierarchy
421       if (failed(convertBlock(*bb, /*ignoreArguments=*/indexedBB.index() == 0)))
422         return;
423     }
424 
425     ompContinuationIPStack.pop_back();
426 
427     // Finally, after all blocks have been traversed and values mapped,
428     // connect the PHI nodes to the results of preceding blocks.
429     connectPHINodes(region, valueMapping, blockMapping);
430   };
431 
432   // TODO: Perform appropriate actions according to the data-sharing
433   // attribute (shared, private, firstprivate, ...) of variables.
434   // Currently defaults to shared.
435   auto privCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP,
436                     llvm::Value &, llvm::Value &vPtr,
437                     llvm::Value *&replacementValue) -> InsertPointTy {
438     replacementValue = &vPtr;
439 
440     return codeGenIP;
441   };
442 
443   // TODO: Perform finalization actions for variables. This has to be
444   // called for variables which have destructors/finalizers.
445   auto finiCB = [&](InsertPointTy codeGenIP) {};
446 
447   llvm::Value *ifCond = nullptr;
448   if (auto ifExprVar = cast<omp::ParallelOp>(opInst).if_expr_var())
449     ifCond = valueMapping.lookup(ifExprVar);
450   llvm::Value *numThreads = nullptr;
451   if (auto numThreadsVar = cast<omp::ParallelOp>(opInst).num_threads_var())
452     numThreads = valueMapping.lookup(numThreadsVar);
453   llvm::omp::ProcBindKind pbKind = llvm::omp::OMP_PROC_BIND_default;
454   if (auto bind = cast<omp::ParallelOp>(opInst).proc_bind_val())
455     pbKind = llvm::omp::getProcBindKind(bind.getValue());
456   // TODO: Is the Parallel construct cancellable?
457   bool isCancellable = false;
458   // TODO: Determine the actual alloca insertion point, e.g., the function
459   // entry or the alloca insertion point as provided by the body callback
460   // above.
461   llvm::OpenMPIRBuilder::InsertPointTy allocaIP(builder.saveIP());
462   builder.restoreIP(
463       ompBuilder->createParallel(builder, allocaIP, bodyGenCB, privCB, finiCB,
464                                  ifCond, numThreads, pbKind, isCancellable));
465   return success();
466 }
467 
468 /// Given an OpenMP MLIR operation, create the corresponding LLVM IR
469 /// (including OpenMP runtime calls).
470 LogicalResult
471 ModuleTranslation::convertOmpOperation(Operation &opInst,
472                                        llvm::IRBuilder<> &builder) {
473   if (!ompBuilder) {
474     ompBuilder = std::make_unique<llvm::OpenMPIRBuilder>(*llvmModule);
475     ompBuilder->initialize();
476   }
477   return llvm::TypeSwitch<Operation *, LogicalResult>(&opInst)
478       .Case([&](omp::BarrierOp) {
479         ompBuilder->createBarrier(builder.saveIP(), llvm::omp::OMPD_barrier);
480         return success();
481       })
482       .Case([&](omp::TaskwaitOp) {
483         ompBuilder->createTaskwait(builder.saveIP());
484         return success();
485       })
486       .Case([&](omp::TaskyieldOp) {
487         ompBuilder->createTaskyield(builder.saveIP());
488         return success();
489       })
490       .Case([&](omp::FlushOp) {
491         // No support in Openmp runtime function (__kmpc_flush) to accept
492         // the argument list.
493         // OpenMP standard states the following:
494         //  "An implementation may implement a flush with a list by ignoring
495         //   the list, and treating it the same as a flush without a list."
496         //
497         // The argument list is discarded so that, flush with a list is treated
498         // same as a flush without a list.
499         ompBuilder->createFlush(builder.saveIP());
500         return success();
501       })
502       .Case([&](omp::TerminatorOp) {
503         builder.CreateBr(ompContinuationIPStack.back());
504         return success();
505       })
506       .Case(
507           [&](omp::ParallelOp) { return convertOmpParallel(opInst, builder); })
508       .Default([&](Operation *inst) {
509         return inst->emitError("unsupported OpenMP operation: ")
510                << inst->getName();
511       });
512 }
513 
514 /// Given a single MLIR operation, create the corresponding LLVM IR operation
515 /// using the `builder`.  LLVM IR Builder does not have a generic interface so
516 /// this has to be a long chain of `if`s calling different functions with a
517 /// different number of arguments.
518 LogicalResult ModuleTranslation::convertOperation(Operation &opInst,
519                                                   llvm::IRBuilder<> &builder) {
520   auto extractPosition = [](ArrayAttr attr) {
521     SmallVector<unsigned, 4> position;
522     position.reserve(attr.size());
523     for (Attribute v : attr)
524       position.push_back(v.cast<IntegerAttr>().getValue().getZExtValue());
525     return position;
526   };
527 
528 #include "mlir/Dialect/LLVMIR/LLVMConversions.inc"
529 
530   // Emit function calls.  If the "callee" attribute is present, this is a
531   // direct function call and we also need to look up the remapped function
532   // itself.  Otherwise, this is an indirect call and the callee is the first
533   // operand, look it up as a normal value.  Return the llvm::Value representing
534   // the function result, which may be of llvm::VoidTy type.
535   auto convertCall = [this, &builder](Operation &op) -> llvm::Value * {
536     auto operands = lookupValues(op.getOperands());
537     ArrayRef<llvm::Value *> operandsRef(operands);
538     if (auto attr = op.getAttrOfType<FlatSymbolRefAttr>("callee")) {
539       return builder.CreateCall(functionMapping.lookup(attr.getValue()),
540                                 operandsRef);
541     } else {
542       auto *calleePtrType =
543           cast<llvm::PointerType>(operandsRef.front()->getType());
544       auto *calleeType =
545           cast<llvm::FunctionType>(calleePtrType->getElementType());
546       return builder.CreateCall(calleeType, operandsRef.front(),
547                                 operandsRef.drop_front());
548     }
549   };
550 
551   // Emit calls.  If the called function has a result, remap the corresponding
552   // value.  Note that LLVM IR dialect CallOp has either 0 or 1 result.
553   if (isa<LLVM::CallOp>(opInst)) {
554     llvm::Value *result = convertCall(opInst);
555     if (opInst.getNumResults() != 0) {
556       valueMapping[opInst.getResult(0)] = result;
557       return success();
558     }
559     // Check that LLVM call returns void for 0-result functions.
560     return success(result->getType()->isVoidTy());
561   }
562 
563   if (auto inlineAsmOp = dyn_cast<LLVM::InlineAsmOp>(opInst)) {
564     // TODO: refactor function type creation which usually occurs in std-LLVM
565     // conversion.
566     SmallVector<LLVM::LLVMType, 8> operandTypes;
567     operandTypes.reserve(inlineAsmOp.operands().size());
568     for (auto t : inlineAsmOp.operands().getTypes())
569       operandTypes.push_back(t.cast<LLVM::LLVMType>());
570 
571     LLVM::LLVMType resultType;
572     if (inlineAsmOp.getNumResults() == 0) {
573       resultType = LLVM::LLVMType::getVoidTy(mlirModule->getContext());
574     } else {
575       assert(inlineAsmOp.getNumResults() == 1);
576       resultType = inlineAsmOp.getResultTypes()[0].cast<LLVM::LLVMType>();
577     }
578     auto ft = LLVM::LLVMType::getFunctionTy(resultType, operandTypes,
579                                             /*isVarArg=*/false);
580     llvm::InlineAsm *inlineAsmInst =
581         inlineAsmOp.asm_dialect().hasValue()
582             ? llvm::InlineAsm::get(
583                   static_cast<llvm::FunctionType *>(convertType(ft)),
584                   inlineAsmOp.asm_string(), inlineAsmOp.constraints(),
585                   inlineAsmOp.has_side_effects(), inlineAsmOp.is_align_stack(),
586                   convertAsmDialectToLLVM(*inlineAsmOp.asm_dialect()))
587             : llvm::InlineAsm::get(
588                   static_cast<llvm::FunctionType *>(convertType(ft)),
589                   inlineAsmOp.asm_string(), inlineAsmOp.constraints(),
590                   inlineAsmOp.has_side_effects(), inlineAsmOp.is_align_stack());
591     llvm::Value *result =
592         builder.CreateCall(inlineAsmInst, lookupValues(inlineAsmOp.operands()));
593     if (opInst.getNumResults() != 0)
594       valueMapping[opInst.getResult(0)] = result;
595     return success();
596   }
597 
598   if (auto invOp = dyn_cast<LLVM::InvokeOp>(opInst)) {
599     auto operands = lookupValues(opInst.getOperands());
600     ArrayRef<llvm::Value *> operandsRef(operands);
601     if (auto attr = opInst.getAttrOfType<FlatSymbolRefAttr>("callee")) {
602       builder.CreateInvoke(functionMapping.lookup(attr.getValue()),
603                            blockMapping[invOp.getSuccessor(0)],
604                            blockMapping[invOp.getSuccessor(1)], operandsRef);
605     } else {
606       auto *calleePtrType =
607           cast<llvm::PointerType>(operandsRef.front()->getType());
608       auto *calleeType =
609           cast<llvm::FunctionType>(calleePtrType->getElementType());
610       builder.CreateInvoke(
611           calleeType, operandsRef.front(), blockMapping[invOp.getSuccessor(0)],
612           blockMapping[invOp.getSuccessor(1)], operandsRef.drop_front());
613     }
614     return success();
615   }
616 
617   if (auto lpOp = dyn_cast<LLVM::LandingpadOp>(opInst)) {
618     llvm::Type *ty = convertType(lpOp.getType().cast<LLVMType>());
619     llvm::LandingPadInst *lpi =
620         builder.CreateLandingPad(ty, lpOp.getNumOperands());
621 
622     // Add clauses
623     for (auto operand : lookupValues(lpOp.getOperands())) {
624       // All operands should be constant - checked by verifier
625       if (auto constOperand = dyn_cast<llvm::Constant>(operand))
626         lpi->addClause(constOperand);
627     }
628     valueMapping[lpOp.getResult()] = lpi;
629     return success();
630   }
631 
632   // Emit branches.  We need to look up the remapped blocks and ignore the block
633   // arguments that were transformed into PHI nodes.
634   if (auto brOp = dyn_cast<LLVM::BrOp>(opInst)) {
635     builder.CreateBr(blockMapping[brOp.getSuccessor()]);
636     return success();
637   }
638   if (auto condbrOp = dyn_cast<LLVM::CondBrOp>(opInst)) {
639     auto weights = condbrOp.branch_weights();
640     llvm::MDNode *branchWeights = nullptr;
641     if (weights) {
642       // Map weight attributes to LLVM metadata.
643       auto trueWeight =
644           weights.getValue().getValue(0).cast<IntegerAttr>().getInt();
645       auto falseWeight =
646           weights.getValue().getValue(1).cast<IntegerAttr>().getInt();
647       branchWeights =
648           llvm::MDBuilder(llvmModule->getContext())
649               .createBranchWeights(static_cast<uint32_t>(trueWeight),
650                                    static_cast<uint32_t>(falseWeight));
651     }
652     builder.CreateCondBr(valueMapping.lookup(condbrOp.getOperand(0)),
653                          blockMapping[condbrOp.getSuccessor(0)],
654                          blockMapping[condbrOp.getSuccessor(1)], branchWeights);
655     return success();
656   }
657 
658   // Emit addressof.  We need to look up the global value referenced by the
659   // operation and store it in the MLIR-to-LLVM value mapping.  This does not
660   // emit any LLVM instruction.
661   if (auto addressOfOp = dyn_cast<LLVM::AddressOfOp>(opInst)) {
662     LLVM::GlobalOp global = addressOfOp.getGlobal();
663     LLVM::LLVMFuncOp function = addressOfOp.getFunction();
664 
665     // The verifier should not have allowed this.
666     assert((global || function) &&
667            "referencing an undefined global or function");
668 
669     valueMapping[addressOfOp.getResult()] =
670         global ? globalsMapping.lookup(global)
671                : functionMapping.lookup(function.getName());
672     return success();
673   }
674 
675   if (ompDialect && opInst.getDialect() == ompDialect)
676     return convertOmpOperation(opInst, builder);
677 
678   return opInst.emitError("unsupported or non-LLVM operation: ")
679          << opInst.getName();
680 }
681 
682 /// Convert block to LLVM IR.  Unless `ignoreArguments` is set, emit PHI nodes
683 /// to define values corresponding to the MLIR block arguments.  These nodes
684 /// are not connected to the source basic blocks, which may not exist yet.
685 LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments) {
686   llvm::IRBuilder<> builder(blockMapping[&bb]);
687   auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram();
688 
689   // Before traversing operations, make block arguments available through
690   // value remapping and PHI nodes, but do not add incoming edges for the PHI
691   // nodes just yet: those values may be defined by this or following blocks.
692   // This step is omitted if "ignoreArguments" is set.  The arguments of the
693   // first block have been already made available through the remapping of
694   // LLVM function arguments.
695   if (!ignoreArguments) {
696     auto predecessors = bb.getPredecessors();
697     unsigned numPredecessors =
698         std::distance(predecessors.begin(), predecessors.end());
699     for (auto arg : bb.getArguments()) {
700       auto wrappedType = arg.getType().dyn_cast<LLVM::LLVMType>();
701       if (!wrappedType)
702         return emitError(bb.front().getLoc(),
703                          "block argument does not have an LLVM type");
704       llvm::Type *type = convertType(wrappedType);
705       llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors);
706       valueMapping[arg] = phi;
707     }
708   }
709 
710   // Traverse operations.
711   for (auto &op : bb) {
712     // Set the current debug location within the builder.
713     builder.SetCurrentDebugLocation(
714         debugTranslation->translateLoc(op.getLoc(), subprogram));
715 
716     if (failed(convertOperation(op, builder)))
717       return failure();
718   }
719 
720   return success();
721 }
722 
723 /// Create named global variables that correspond to llvm.mlir.global
724 /// definitions.
725 LogicalResult ModuleTranslation::convertGlobals() {
726   for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) {
727     llvm::Type *type = convertType(op.getType());
728     llvm::Constant *cst = llvm::UndefValue::get(type);
729     if (op.getValueOrNull()) {
730       // String attributes are treated separately because they cannot appear as
731       // in-function constants and are thus not supported by getLLVMConstant.
732       if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) {
733         cst = llvm::ConstantDataArray::getString(
734             llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
735         type = cst->getType();
736       } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(),
737                                          op.getLoc()))) {
738         return failure();
739       }
740     } else if (Block *initializer = op.getInitializerBlock()) {
741       llvm::IRBuilder<> builder(llvmModule->getContext());
742       for (auto &op : initializer->without_terminator()) {
743         if (failed(convertOperation(op, builder)) ||
744             !isa<llvm::Constant>(valueMapping.lookup(op.getResult(0))))
745           return emitError(op.getLoc(), "unemittable constant value");
746       }
747       ReturnOp ret = cast<ReturnOp>(initializer->getTerminator());
748       cst = cast<llvm::Constant>(valueMapping.lookup(ret.getOperand(0)));
749     }
750 
751     auto linkage = convertLinkageToLLVM(op.linkage());
752     bool anyExternalLinkage =
753         ((linkage == llvm::GlobalVariable::ExternalLinkage &&
754           isa<llvm::UndefValue>(cst)) ||
755          linkage == llvm::GlobalVariable::ExternalWeakLinkage);
756     auto addrSpace = op.addr_space();
757     auto *var = new llvm::GlobalVariable(
758         *llvmModule, type, op.constant(), linkage,
759         anyExternalLinkage ? nullptr : cst, op.sym_name(),
760         /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace);
761 
762     globalsMapping.try_emplace(op, var);
763   }
764 
765   return success();
766 }
767 
768 /// Attempts to add an attribute identified by `key`, optionally with the given
769 /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the
770 /// attribute has a kind known to LLVM IR, create the attribute of this kind,
771 /// otherwise keep it as a string attribute. Performs additional checks for
772 /// attributes known to have or not have a value in order to avoid assertions
773 /// inside LLVM upon construction.
774 static LogicalResult checkedAddLLVMFnAttribute(Location loc,
775                                                llvm::Function *llvmFunc,
776                                                StringRef key,
777                                                StringRef value = StringRef()) {
778   auto kind = llvm::Attribute::getAttrKindFromName(key);
779   if (kind == llvm::Attribute::None) {
780     llvmFunc->addFnAttr(key, value);
781     return success();
782   }
783 
784   if (llvm::Attribute::doesAttrKindHaveArgument(kind)) {
785     if (value.empty())
786       return emitError(loc) << "LLVM attribute '" << key << "' expects a value";
787 
788     int result;
789     if (!value.getAsInteger(/*Radix=*/0, result))
790       llvmFunc->addFnAttr(
791           llvm::Attribute::get(llvmFunc->getContext(), kind, result));
792     else
793       llvmFunc->addFnAttr(key, value);
794     return success();
795   }
796 
797   if (!value.empty())
798     return emitError(loc) << "LLVM attribute '" << key
799                           << "' does not expect a value, found '" << value
800                           << "'";
801 
802   llvmFunc->addFnAttr(kind);
803   return success();
804 }
805 
806 /// Attaches the attributes listed in the given array attribute to `llvmFunc`.
807 /// Reports error to `loc` if any and returns immediately. Expects `attributes`
808 /// to be an array attribute containing either string attributes, treated as
809 /// value-less LLVM attributes, or array attributes containing two string
810 /// attributes, with the first string being the name of the corresponding LLVM
811 /// attribute and the second string beings its value. Note that even integer
812 /// attributes are expected to have their values expressed as strings.
813 static LogicalResult
814 forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes,
815                              llvm::Function *llvmFunc) {
816   if (!attributes)
817     return success();
818 
819   for (Attribute attr : *attributes) {
820     if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
821       if (failed(
822               checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue())))
823         return failure();
824       continue;
825     }
826 
827     auto arrayAttr = attr.dyn_cast<ArrayAttr>();
828     if (!arrayAttr || arrayAttr.size() != 2)
829       return emitError(loc)
830              << "expected 'passthrough' to contain string or array attributes";
831 
832     auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>();
833     auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>();
834     if (!keyAttr || !valueAttr)
835       return emitError(loc)
836              << "expected arrays within 'passthrough' to contain two strings";
837 
838     if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(),
839                                          valueAttr.getValue())))
840       return failure();
841   }
842   return success();
843 }
844 
845 LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) {
846   // Clear the block and value mappings, they are only relevant within one
847   // function.
848   blockMapping.clear();
849   valueMapping.clear();
850   llvm::Function *llvmFunc = functionMapping.lookup(func.getName());
851 
852   // Translate the debug information for this function.
853   debugTranslation->translate(func, *llvmFunc);
854 
855   // Add function arguments to the value remapping table.
856   // If there was noalias info then we decorate each argument accordingly.
857   unsigned int argIdx = 0;
858   for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) {
859     llvm::Argument &llvmArg = std::get<1>(kvp);
860     BlockArgument mlirArg = std::get<0>(kvp);
861 
862     if (auto attr = func.getArgAttrOfType<BoolAttr>(
863             argIdx, LLVMDialect::getNoAliasAttrName())) {
864       // NB: Attribute already verified to be boolean, so check if we can indeed
865       // attach the attribute to this argument, based on its type.
866       auto argTy = mlirArg.getType().dyn_cast<LLVM::LLVMType>();
867       if (!argTy.isPointerTy())
868         return func.emitError(
869             "llvm.noalias attribute attached to LLVM non-pointer argument");
870       if (attr.getValue())
871         llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias);
872     }
873 
874     if (auto attr = func.getArgAttrOfType<IntegerAttr>(
875             argIdx, LLVMDialect::getAlignAttrName())) {
876       // NB: Attribute already verified to be int, so check if we can indeed
877       // attach the attribute to this argument, based on its type.
878       auto argTy = mlirArg.getType().dyn_cast<LLVM::LLVMType>();
879       if (!argTy.isPointerTy())
880         return func.emitError(
881             "llvm.align attribute attached to LLVM non-pointer argument");
882       llvmArg.addAttrs(
883           llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt())));
884     }
885 
886     valueMapping[mlirArg] = &llvmArg;
887     argIdx++;
888   }
889 
890   // Check the personality and set it.
891   if (func.personality().hasValue()) {
892     llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext());
893     if (llvm::Constant *pfunc =
894             getLLVMConstant(ty, func.personalityAttr(), func.getLoc()))
895       llvmFunc->setPersonalityFn(pfunc);
896   }
897 
898   // First, create all blocks so we can jump to them.
899   llvm::LLVMContext &llvmContext = llvmFunc->getContext();
900   for (auto &bb : func) {
901     auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
902     llvmBB->insertInto(llvmFunc);
903     blockMapping[&bb] = llvmBB;
904   }
905 
906   // Then, convert blocks one by one in topological order to ensure defs are
907   // converted before uses.
908   auto blocks = topologicalSort(func);
909   for (auto indexedBB : llvm::enumerate(blocks)) {
910     auto *bb = indexedBB.value();
911     if (failed(convertBlock(*bb, /*ignoreArguments=*/indexedBB.index() == 0)))
912       return failure();
913   }
914 
915   // Finally, after all blocks have been traversed and values mapped, connect
916   // the PHI nodes to the results of preceding blocks.
917   connectPHINodes(func, valueMapping, blockMapping);
918   return success();
919 }
920 
921 LogicalResult ModuleTranslation::checkSupportedModuleOps(Operation *m) {
922   for (Operation &o : getModuleBody(m).getOperations())
923     if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp>(&o) && !o.isKnownTerminator())
924       return o.emitOpError("unsupported module-level operation");
925   return success();
926 }
927 
928 LogicalResult ModuleTranslation::convertFunctionSignatures() {
929   // Declare all functions first because there may be function calls that form a
930   // call graph with cycles, or global initializers that reference functions.
931   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
932     llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction(
933         function.getName(),
934         cast<llvm::FunctionType>(convertType(function.getType())));
935     llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee());
936     llvmFunc->setLinkage(convertLinkageToLLVM(function.linkage()));
937     functionMapping[function.getName()] = llvmFunc;
938 
939     // Forward the pass-through attributes to LLVM.
940     if (failed(forwardPassthroughAttributes(function.getLoc(),
941                                             function.passthrough(), llvmFunc)))
942       return failure();
943   }
944 
945   return success();
946 }
947 
948 LogicalResult ModuleTranslation::convertFunctions() {
949   // Convert functions.
950   for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) {
951     // Ignore external functions.
952     if (function.isExternal())
953       continue;
954 
955     if (failed(convertOneFunction(function)))
956       return failure();
957   }
958 
959   return success();
960 }
961 
962 llvm::Type *ModuleTranslation::convertType(LLVMType type) {
963   return typeTranslator.translateType(type);
964 }
965 
966 /// A helper to look up remapped operands in the value remapping table.`
967 SmallVector<llvm::Value *, 8>
968 ModuleTranslation::lookupValues(ValueRange values) {
969   SmallVector<llvm::Value *, 8> remapped;
970   remapped.reserve(values.size());
971   for (Value v : values) {
972     assert(valueMapping.count(v) && "referencing undefined value");
973     remapped.push_back(valueMapping.lookup(v));
974   }
975   return remapped;
976 }
977 
978 std::unique_ptr<llvm::Module> ModuleTranslation::prepareLLVMModule(
979     Operation *m, llvm::LLVMContext &llvmContext, StringRef name) {
980   m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>();
981   auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext);
982   if (auto dataLayoutAttr =
983           m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName()))
984     llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue());
985   if (auto targetTripleAttr =
986           m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName()))
987     llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue());
988 
989   // Inject declarations for `malloc` and `free` functions that can be used in
990   // memref allocation/deallocation coming from standard ops lowering.
991   llvm::IRBuilder<> builder(llvmContext);
992   llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(),
993                                   builder.getInt64Ty());
994   llvmModule->getOrInsertFunction("free", builder.getVoidTy(),
995                                   builder.getInt8PtrTy());
996 
997   return llvmModule;
998 }
999