1 //===- ModuleTranslation.cpp - MLIR to LLVM conversion --------------------===//
2 //
3 // Copyright 2019 The MLIR Authors.
4 //
5 // Licensed under the Apache License, Version 2.0 (the "License");
6 // you may not use this file except in compliance with the License.
7 // You may obtain a copy of the License at
8 //
9 //   http://www.apache.org/licenses/LICENSE-2.0
10 //
11 // Unless required by applicable law or agreed to in writing, software
12 // distributed under the License is distributed on an "AS IS" BASIS,
13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 // See the License for the specific language governing permissions and
15 // limitations under the License.
16 // =============================================================================
17 //
18 // This file implements the translation between an MLIR LLVM dialect module and
19 // the corresponding LLVMIR module. It only handles core LLVM IR operations.
20 //
21 //===----------------------------------------------------------------------===//
22 
23 #include "mlir/Target/LLVMIR/ModuleTranslation.h"
24 
25 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
26 #include "mlir/IR/Attributes.h"
27 #include "mlir/IR/Module.h"
28 #include "mlir/Support/LLVM.h"
29 
30 #include "llvm/ADT/SetVector.h"
31 #include "llvm/IR/BasicBlock.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DerivedTypes.h"
34 #include "llvm/IR/IRBuilder.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/Transforms/Utils/Cloning.h"
38 
39 namespace mlir {
40 namespace LLVM {
41 
42 // Create an LLVM IR constant of `llvmType` from the MLIR attribute `attr`.
43 // This currently supports integer, floating point, splat and dense element
44 // attributes and combinations thereof.  In case of error, report it to `loc`
45 // and return nullptr.
46 llvm::Constant *ModuleTranslation::getLLVMConstant(llvm::Type *llvmType,
47                                                    Attribute attr,
48                                                    Location loc) {
49   if (!attr)
50     return llvm::UndefValue::get(llvmType);
51   if (auto intAttr = attr.dyn_cast<IntegerAttr>())
52     return llvm::ConstantInt::get(llvmType, intAttr.getValue());
53   if (auto floatAttr = attr.dyn_cast<FloatAttr>())
54     return llvm::ConstantFP::get(llvmType, floatAttr.getValue());
55   if (auto funcAttr = attr.dyn_cast<SymbolRefAttr>())
56     return functionMapping.lookup(funcAttr.getValue());
57   if (auto splatAttr = attr.dyn_cast<SplatElementsAttr>()) {
58     auto *sequentialType = cast<llvm::SequentialType>(llvmType);
59     auto elementType = sequentialType->getElementType();
60     uint64_t numElements = sequentialType->getNumElements();
61     auto *child = getLLVMConstant(elementType, splatAttr.getSplatValue(), loc);
62     if (llvmType->isVectorTy())
63       return llvm::ConstantVector::getSplat(numElements, child);
64     if (llvmType->isArrayTy()) {
65       auto arrayType = llvm::ArrayType::get(elementType, numElements);
66       SmallVector<llvm::Constant *, 8> constants(numElements, child);
67       return llvm::ConstantArray::get(arrayType, constants);
68     }
69   }
70   if (auto elementsAttr = attr.dyn_cast<ElementsAttr>()) {
71     auto *sequentialType = cast<llvm::SequentialType>(llvmType);
72     auto elementType = sequentialType->getElementType();
73     uint64_t numElements = sequentialType->getNumElements();
74     SmallVector<llvm::Constant *, 8> constants;
75     constants.reserve(numElements);
76     for (auto n : elementsAttr.getValues<Attribute>()) {
77       constants.push_back(getLLVMConstant(elementType, n, loc));
78       if (!constants.back())
79         return nullptr;
80     }
81     if (llvmType->isVectorTy())
82       return llvm::ConstantVector::get(constants);
83     if (llvmType->isArrayTy()) {
84       auto arrayType = llvm::ArrayType::get(elementType, numElements);
85       return llvm::ConstantArray::get(arrayType, constants);
86     }
87   }
88   if (auto stringAttr = attr.dyn_cast<StringAttr>()) {
89     return llvm::ConstantDataArray::get(
90         llvmModule->getContext(), ArrayRef<char>{stringAttr.getValue().data(),
91                                                  stringAttr.getValue().size()});
92   }
93   emitError(loc, "unsupported constant value");
94   return nullptr;
95 }
96 
97 // Convert MLIR integer comparison predicate to LLVM IR comparison predicate.
98 static llvm::CmpInst::Predicate getLLVMCmpPredicate(ICmpPredicate p) {
99   switch (p) {
100   case LLVM::ICmpPredicate::eq:
101     return llvm::CmpInst::Predicate::ICMP_EQ;
102   case LLVM::ICmpPredicate::ne:
103     return llvm::CmpInst::Predicate::ICMP_NE;
104   case LLVM::ICmpPredicate::slt:
105     return llvm::CmpInst::Predicate::ICMP_SLT;
106   case LLVM::ICmpPredicate::sle:
107     return llvm::CmpInst::Predicate::ICMP_SLE;
108   case LLVM::ICmpPredicate::sgt:
109     return llvm::CmpInst::Predicate::ICMP_SGT;
110   case LLVM::ICmpPredicate::sge:
111     return llvm::CmpInst::Predicate::ICMP_SGE;
112   case LLVM::ICmpPredicate::ult:
113     return llvm::CmpInst::Predicate::ICMP_ULT;
114   case LLVM::ICmpPredicate::ule:
115     return llvm::CmpInst::Predicate::ICMP_ULE;
116   case LLVM::ICmpPredicate::ugt:
117     return llvm::CmpInst::Predicate::ICMP_UGT;
118   case LLVM::ICmpPredicate::uge:
119     return llvm::CmpInst::Predicate::ICMP_UGE;
120   }
121   llvm_unreachable("incorrect comparison predicate");
122 }
123 
124 static llvm::CmpInst::Predicate getLLVMCmpPredicate(FCmpPredicate p) {
125   switch (p) {
126   case LLVM::FCmpPredicate::_false:
127     return llvm::CmpInst::Predicate::FCMP_FALSE;
128   case LLVM::FCmpPredicate::oeq:
129     return llvm::CmpInst::Predicate::FCMP_OEQ;
130   case LLVM::FCmpPredicate::ogt:
131     return llvm::CmpInst::Predicate::FCMP_OGT;
132   case LLVM::FCmpPredicate::oge:
133     return llvm::CmpInst::Predicate::FCMP_OGE;
134   case LLVM::FCmpPredicate::olt:
135     return llvm::CmpInst::Predicate::FCMP_OLT;
136   case LLVM::FCmpPredicate::ole:
137     return llvm::CmpInst::Predicate::FCMP_OLE;
138   case LLVM::FCmpPredicate::one:
139     return llvm::CmpInst::Predicate::FCMP_ONE;
140   case LLVM::FCmpPredicate::ord:
141     return llvm::CmpInst::Predicate::FCMP_ORD;
142   case LLVM::FCmpPredicate::ueq:
143     return llvm::CmpInst::Predicate::FCMP_UEQ;
144   case LLVM::FCmpPredicate::ugt:
145     return llvm::CmpInst::Predicate::FCMP_UGT;
146   case LLVM::FCmpPredicate::uge:
147     return llvm::CmpInst::Predicate::FCMP_UGE;
148   case LLVM::FCmpPredicate::ult:
149     return llvm::CmpInst::Predicate::FCMP_ULT;
150   case LLVM::FCmpPredicate::ule:
151     return llvm::CmpInst::Predicate::FCMP_ULE;
152   case LLVM::FCmpPredicate::une:
153     return llvm::CmpInst::Predicate::FCMP_UNE;
154   case LLVM::FCmpPredicate::uno:
155     return llvm::CmpInst::Predicate::FCMP_UNO;
156   case LLVM::FCmpPredicate::_true:
157     return llvm::CmpInst::Predicate::FCMP_TRUE;
158   }
159   llvm_unreachable("incorrect comparison predicate");
160 }
161 
162 // A helper to look up remapped operands in the value remapping table.
163 template <typename Range>
164 SmallVector<llvm::Value *, 8> ModuleTranslation::lookupValues(Range &&values) {
165   SmallVector<llvm::Value *, 8> remapped;
166   remapped.reserve(llvm::size(values));
167   for (Value *v : values) {
168     remapped.push_back(valueMapping.lookup(v));
169   }
170   return remapped;
171 }
172 
173 // Given a single MLIR operation, create the corresponding LLVM IR operation
174 // using the `builder`.  LLVM IR Builder does not have a generic interface so
175 // this has to be a long chain of `if`s calling different functions with a
176 // different number of arguments.
177 LogicalResult ModuleTranslation::convertOperation(Operation &opInst,
178                                                   llvm::IRBuilder<> &builder) {
179   auto extractPosition = [](ArrayAttr attr) {
180     SmallVector<unsigned, 4> position;
181     position.reserve(attr.size());
182     for (Attribute v : attr)
183       position.push_back(v.cast<IntegerAttr>().getValue().getZExtValue());
184     return position;
185   };
186 
187 #include "mlir/Dialect/LLVMIR/LLVMConversions.inc"
188 
189   // Emit function calls.  If the "callee" attribute is present, this is a
190   // direct function call and we also need to look up the remapped function
191   // itself.  Otherwise, this is an indirect call and the callee is the first
192   // operand, look it up as a normal value.  Return the llvm::Value representing
193   // the function result, which may be of llvm::VoidTy type.
194   auto convertCall = [this, &builder](Operation &op) -> llvm::Value * {
195     auto operands = lookupValues(op.getOperands());
196     ArrayRef<llvm::Value *> operandsRef(operands);
197     if (auto attr = op.getAttrOfType<SymbolRefAttr>("callee")) {
198       return builder.CreateCall(functionMapping.lookup(attr.getValue()),
199                                 operandsRef);
200     } else {
201       return builder.CreateCall(operandsRef.front(), operandsRef.drop_front());
202     }
203   };
204 
205   // Emit calls.  If the called function has a result, remap the corresponding
206   // value.  Note that LLVM IR dialect CallOp has either 0 or 1 result.
207   if (isa<LLVM::CallOp>(opInst)) {
208     llvm::Value *result = convertCall(opInst);
209     if (opInst.getNumResults() != 0) {
210       valueMapping[opInst.getResult(0)] = result;
211       return success();
212     }
213     // Check that LLVM call returns void for 0-result functions.
214     return success(result->getType()->isVoidTy());
215   }
216 
217   // Emit branches.  We need to look up the remapped blocks and ignore the block
218   // arguments that were transformed into PHI nodes.
219   if (auto brOp = dyn_cast<LLVM::BrOp>(opInst)) {
220     builder.CreateBr(blockMapping[brOp.getSuccessor(0)]);
221     return success();
222   }
223   if (auto condbrOp = dyn_cast<LLVM::CondBrOp>(opInst)) {
224     builder.CreateCondBr(valueMapping.lookup(condbrOp.getOperand(0)),
225                          blockMapping[condbrOp.getSuccessor(0)],
226                          blockMapping[condbrOp.getSuccessor(1)]);
227     return success();
228   }
229 
230   // Emit addressof.  We need to look up the global value referenced by the
231   // operation and store it in the MLIR-to-LLVM value mapping.  This does not
232   // emit any LLVM instruction.
233   if (auto addressOfOp = dyn_cast<LLVM::AddressOfOp>(opInst)) {
234     LLVM::GlobalOp global = addressOfOp.getGlobal();
235     // The verifier should not have allowed this.
236     assert(global && "referencing an undefined global");
237 
238     valueMapping[addressOfOp.getResult()] = globalsMapping.lookup(global);
239     return success();
240   }
241 
242   return opInst.emitError("unsupported or non-LLVM operation: ")
243          << opInst.getName();
244 }
245 
246 // Convert block to LLVM IR.  Unless `ignoreArguments` is set, emit PHI nodes
247 // to define values corresponding to the MLIR block arguments.  These nodes
248 // are not connected to the source basic blocks, which may not exist yet.
249 LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments) {
250   llvm::IRBuilder<> builder(blockMapping[&bb]);
251 
252   // Before traversing operations, make block arguments available through
253   // value remapping and PHI nodes, but do not add incoming edges for the PHI
254   // nodes just yet: those values may be defined by this or following blocks.
255   // This step is omitted if "ignoreArguments" is set.  The arguments of the
256   // first block have been already made available through the remapping of
257   // LLVM function arguments.
258   if (!ignoreArguments) {
259     auto predecessors = bb.getPredecessors();
260     unsigned numPredecessors =
261         std::distance(predecessors.begin(), predecessors.end());
262     for (auto *arg : bb.getArguments()) {
263       auto wrappedType = arg->getType().dyn_cast<LLVM::LLVMType>();
264       if (!wrappedType)
265         return emitError(bb.front().getLoc(),
266                          "block argument does not have an LLVM type");
267       llvm::Type *type = wrappedType.getUnderlyingType();
268       llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors);
269       valueMapping[arg] = phi;
270     }
271   }
272 
273   // Traverse operations.
274   for (auto &op : bb) {
275     if (failed(convertOperation(op, builder)))
276       return failure();
277   }
278 
279   return success();
280 }
281 
282 // Create named global variables that correspond to llvm.mlir.global
283 // definitions.
284 void ModuleTranslation::convertGlobals() {
285   for (auto op : mlirModule.getOps<LLVM::GlobalOp>()) {
286     llvm::Constant *cst;
287     llvm::Type *type;
288     // String attributes are treated separately because they cannot appear as
289     // in-function constants and are thus not supported by getLLVMConstant.
290     if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) {
291       cst = llvm::ConstantDataArray::getString(
292           llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false);
293       type = cst->getType();
294     } else {
295       type = op.getType().getUnderlyingType();
296       cst = getLLVMConstant(type, op.getValueOrNull(), op.getLoc());
297     }
298 
299     auto addrSpace = op.addr_space().getLimitedValue();
300     auto *var = new llvm::GlobalVariable(
301         *llvmModule, type, op.constant(), llvm::GlobalValue::InternalLinkage,
302         cst, op.sym_name(), /*InsertBefore=*/nullptr,
303         llvm::GlobalValue::NotThreadLocal, addrSpace);
304 
305     globalsMapping.try_emplace(op, var);
306   }
307 }
308 
309 // Get the SSA value passed to the current block from the terminator operation
310 // of its predecessor.
311 static Value *getPHISourceValue(Block *current, Block *pred,
312                                 unsigned numArguments, unsigned index) {
313   auto &terminator = *pred->getTerminator();
314   if (isa<LLVM::BrOp>(terminator)) {
315     return terminator.getOperand(index);
316   }
317 
318   // For conditional branches, we need to check if the current block is reached
319   // through the "true" or the "false" branch and take the relevant operands.
320   auto condBranchOp = dyn_cast<LLVM::CondBrOp>(terminator);
321   assert(condBranchOp &&
322          "only branch operations can be terminators of a block that "
323          "has successors");
324   assert((condBranchOp.getSuccessor(0) != condBranchOp.getSuccessor(1)) &&
325          "successors with arguments in LLVM conditional branches must be "
326          "different blocks");
327 
328   return condBranchOp.getSuccessor(0) == current
329              ? terminator.getSuccessorOperand(0, index)
330              : terminator.getSuccessorOperand(1, index);
331 }
332 
333 void ModuleTranslation::connectPHINodes(LLVMFuncOp func) {
334   // Skip the first block, it cannot be branched to and its arguments correspond
335   // to the arguments of the LLVM function.
336   for (auto it = std::next(func.begin()), eit = func.end(); it != eit; ++it) {
337     Block *bb = &*it;
338     llvm::BasicBlock *llvmBB = blockMapping.lookup(bb);
339     auto phis = llvmBB->phis();
340     auto numArguments = bb->getNumArguments();
341     assert(numArguments == std::distance(phis.begin(), phis.end()));
342     for (auto &numberedPhiNode : llvm::enumerate(phis)) {
343       auto &phiNode = numberedPhiNode.value();
344       unsigned index = numberedPhiNode.index();
345       for (auto *pred : bb->getPredecessors()) {
346         phiNode.addIncoming(valueMapping.lookup(getPHISourceValue(
347                                 bb, pred, numArguments, index)),
348                             blockMapping.lookup(pred));
349       }
350     }
351   }
352 }
353 
354 // TODO(mlir-team): implement an iterative version
355 static void topologicalSortImpl(llvm::SetVector<Block *> &blocks, Block *b) {
356   blocks.insert(b);
357   for (Block *bb : b->getSuccessors()) {
358     if (blocks.count(bb) == 0)
359       topologicalSortImpl(blocks, bb);
360   }
361 }
362 
363 // Sort function blocks topologically.
364 static llvm::SetVector<Block *> topologicalSort(LLVMFuncOp f) {
365   // For each blocks that has not been visited yet (i.e. that has no
366   // predecessors), add it to the list and traverse its successors in DFS
367   // preorder.
368   llvm::SetVector<Block *> blocks;
369   for (Block &b : f.getBlocks()) {
370     if (blocks.count(&b) == 0)
371       topologicalSortImpl(blocks, &b);
372   }
373   assert(blocks.size() == f.getBlocks().size() && "some blocks are not sorted");
374 
375   return blocks;
376 }
377 
378 LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) {
379   // Clear the block and value mappings, they are only relevant within one
380   // function.
381   blockMapping.clear();
382   valueMapping.clear();
383   llvm::Function *llvmFunc = functionMapping.lookup(func.getName());
384   // Add function arguments to the value remapping table.
385   // If there was noalias info then we decorate each argument accordingly.
386   unsigned int argIdx = 0;
387   for (const auto &kvp : llvm::zip(func.getArguments(), llvmFunc->args())) {
388     llvm::Argument &llvmArg = std::get<1>(kvp);
389     BlockArgument *mlirArg = std::get<0>(kvp);
390 
391     if (auto attr = func.getArgAttrOfType<BoolAttr>(argIdx, "llvm.noalias")) {
392       // NB: Attribute already verified to be boolean, so check if we can indeed
393       // attach the attribute to this argument, based on its type.
394       auto argTy = mlirArg->getType().dyn_cast<LLVM::LLVMType>();
395       if (!argTy.getUnderlyingType()->isPointerTy())
396         return func.emitError(
397             "llvm.noalias attribute attached to LLVM non-pointer argument");
398       if (attr.getValue())
399         llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias);
400     }
401     valueMapping[mlirArg] = &llvmArg;
402     argIdx++;
403   }
404 
405   // First, create all blocks so we can jump to them.
406   llvm::LLVMContext &llvmContext = llvmFunc->getContext();
407   for (auto &bb : func) {
408     auto *llvmBB = llvm::BasicBlock::Create(llvmContext);
409     llvmBB->insertInto(llvmFunc);
410     blockMapping[&bb] = llvmBB;
411   }
412 
413   // Then, convert blocks one by one in topological order to ensure defs are
414   // converted before uses.
415   auto blocks = topologicalSort(func);
416   for (auto indexedBB : llvm::enumerate(blocks)) {
417     auto *bb = indexedBB.value();
418     if (failed(convertBlock(*bb, /*ignoreArguments=*/indexedBB.index() == 0)))
419       return failure();
420   }
421 
422   // Finally, after all blocks have been traversed and values mapped, connect
423   // the PHI nodes to the results of preceding blocks.
424   connectPHINodes(func);
425   return success();
426 }
427 
428 LogicalResult ModuleTranslation::checkSupportedModuleOps(ModuleOp m) {
429   for (Operation &o : m.getBody()->getOperations())
430     if (!isa<LLVM::LLVMFuncOp>(&o) && !isa<LLVM::GlobalOp>(&o) &&
431         !isa<ModuleTerminatorOp>(&o))
432       return o.emitOpError("unsupported module-level operation");
433   return success();
434 }
435 
436 LogicalResult ModuleTranslation::convertFunctions() {
437   // Declare all functions first because there may be function calls that form a
438   // call graph with cycles.
439   for (auto function : mlirModule.getOps<LLVMFuncOp>()) {
440     llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction(
441         function.getName(),
442         llvm::cast<llvm::FunctionType>(function.getType().getUnderlyingType()));
443     assert(isa<llvm::Function>(llvmFuncCst.getCallee()));
444     functionMapping[function.getName()] =
445         cast<llvm::Function>(llvmFuncCst.getCallee());
446   }
447 
448   // Convert functions.
449   for (auto function : mlirModule.getOps<LLVMFuncOp>()) {
450     // Ignore external functions.
451     if (function.isExternal())
452       continue;
453 
454     if (failed(convertOneFunction(function)))
455       return failure();
456   }
457 
458   return success();
459 }
460 
461 std::unique_ptr<llvm::Module> ModuleTranslation::prepareLLVMModule(ModuleOp m) {
462   auto *dialect = m.getContext()->getRegisteredDialect<LLVM::LLVMDialect>();
463   assert(dialect && "LLVM dialect must be registered");
464 
465   auto llvmModule = llvm::CloneModule(dialect->getLLVMModule());
466   if (!llvmModule)
467     return nullptr;
468 
469   llvm::LLVMContext &llvmContext = llvmModule->getContext();
470   llvm::IRBuilder<> builder(llvmContext);
471 
472   // Inject declarations for `malloc` and `free` functions that can be used in
473   // memref allocation/deallocation coming from standard ops lowering.
474   llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(),
475                                   builder.getInt64Ty());
476   llvmModule->getOrInsertFunction("free", builder.getVoidTy(),
477                                   builder.getInt8PtrTy());
478 
479   return llvmModule;
480 }
481 
482 } // namespace LLVM
483 } // namespace mlir
484