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