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