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/BuiltinTypes.h" 22 #include "mlir/IR/RegionGraphTraits.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 connectPHINodes( 344 T &func, const DenseMap<Value, llvm::Value *> &valueMapping, 345 const DenseMap<Block *, llvm::BasicBlock *> &blockMapping, 346 const DenseMap<Operation *, llvm::Instruction *> &branchMapping) { 347 // Skip the first block, it cannot be branched to and its arguments correspond 348 // to the arguments of the LLVM function. 349 for (auto it = std::next(func.begin()), eit = func.end(); it != eit; ++it) { 350 Block *bb = &*it; 351 llvm::BasicBlock *llvmBB = blockMapping.lookup(bb); 352 auto phis = llvmBB->phis(); 353 auto numArguments = bb->getNumArguments(); 354 assert(numArguments == std::distance(phis.begin(), phis.end())); 355 for (auto &numberedPhiNode : llvm::enumerate(phis)) { 356 auto &phiNode = numberedPhiNode.value(); 357 unsigned index = numberedPhiNode.index(); 358 for (auto *pred : bb->getPredecessors()) { 359 // Find the LLVM IR block that contains the converted terminator 360 // instruction and use it in the PHI node. Note that this block is not 361 // necessarily the same as blockMapping.lookup(pred), some operations 362 // (in particular, OpenMP operations using OpenMPIRBuilder) may have 363 // split the blocks. 364 llvm::Instruction *terminator = 365 branchMapping.lookup(pred->getTerminator()); 366 assert(terminator && "missing the mapping for a terminator"); 367 phiNode.addIncoming(valueMapping.lookup(getPHISourceValue( 368 bb, pred, numArguments, index)), 369 terminator->getParent()); 370 } 371 } 372 } 373 } 374 375 /// Sort function blocks topologically. 376 template <typename T> 377 static llvm::SetVector<Block *> topologicalSort(T &f) { 378 // For each block that has not been visited yet (i.e. that has no 379 // predecessors), add it to the list as well as its successors. 380 llvm::SetVector<Block *> blocks; 381 for (Block &b : f) { 382 if (blocks.count(&b) == 0) { 383 llvm::ReversePostOrderTraversal<Block *> traversal(&b); 384 blocks.insert(traversal.begin(), traversal.end()); 385 } 386 } 387 assert(blocks.size() == f.getBlocks().size() && "some blocks are not sorted"); 388 389 return blocks; 390 } 391 392 /// Convert the OpenMP parallel Operation to LLVM IR. 393 LogicalResult 394 ModuleTranslation::convertOmpParallel(Operation &opInst, 395 llvm::IRBuilder<> &builder) { 396 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 397 // TODO: support error propagation in OpenMPIRBuilder and use it instead of 398 // relying on captured variables. 399 LogicalResult bodyGenStatus = success(); 400 401 auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP, 402 llvm::BasicBlock &continuationIP) { 403 llvm::LLVMContext &llvmContext = llvmModule->getContext(); 404 405 llvm::BasicBlock *codeGenIPBB = codeGenIP.getBlock(); 406 llvm::Instruction *codeGenIPBBTI = codeGenIPBB->getTerminator(); 407 ompContinuationIPStack.push_back(&continuationIP); 408 409 // ParallelOp has only `1` region associated with it. 410 auto ®ion = cast<omp::ParallelOp>(opInst).getRegion(); 411 for (auto &bb : region) { 412 auto *llvmBB = llvm::BasicBlock::Create( 413 llvmContext, "omp.par.region", codeGenIP.getBlock()->getParent()); 414 blockMapping[&bb] = llvmBB; 415 } 416 417 convertOmpOpRegions(region, valueMapping, blockMapping, codeGenIPBBTI, 418 continuationIP, builder, bodyGenStatus); 419 ompContinuationIPStack.pop_back(); 420 421 }; 422 423 // TODO: Perform appropriate actions according to the data-sharing 424 // attribute (shared, private, firstprivate, ...) of variables. 425 // Currently defaults to shared. 426 auto privCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP, 427 llvm::Value &, llvm::Value &vPtr, 428 llvm::Value *&replacementValue) -> InsertPointTy { 429 replacementValue = &vPtr; 430 431 return codeGenIP; 432 }; 433 434 // TODO: Perform finalization actions for variables. This has to be 435 // called for variables which have destructors/finalizers. 436 auto finiCB = [&](InsertPointTy codeGenIP) {}; 437 438 llvm::Value *ifCond = nullptr; 439 if (auto ifExprVar = cast<omp::ParallelOp>(opInst).if_expr_var()) 440 ifCond = valueMapping.lookup(ifExprVar); 441 llvm::Value *numThreads = nullptr; 442 if (auto numThreadsVar = cast<omp::ParallelOp>(opInst).num_threads_var()) 443 numThreads = valueMapping.lookup(numThreadsVar); 444 llvm::omp::ProcBindKind pbKind = llvm::omp::OMP_PROC_BIND_default; 445 if (auto bind = cast<omp::ParallelOp>(opInst).proc_bind_val()) 446 pbKind = llvm::omp::getProcBindKind(bind.getValue()); 447 // TODO: Is the Parallel construct cancellable? 448 bool isCancellable = false; 449 // TODO: Determine the actual alloca insertion point, e.g., the function 450 // entry or the alloca insertion point as provided by the body callback 451 // above. 452 llvm::OpenMPIRBuilder::InsertPointTy allocaIP(builder.saveIP()); 453 if (failed(bodyGenStatus)) 454 return failure(); 455 builder.restoreIP( 456 ompBuilder->createParallel(builder, allocaIP, bodyGenCB, privCB, finiCB, 457 ifCond, numThreads, pbKind, isCancellable)); 458 return success(); 459 } 460 461 void ModuleTranslation::convertOmpOpRegions( 462 Region ®ion, DenseMap<Value, llvm::Value *> &valueMapping, 463 DenseMap<Block *, llvm::BasicBlock *> &blockMapping, 464 llvm::Instruction *codeGenIPBBTI, llvm::BasicBlock &continuationIP, 465 llvm::IRBuilder<> &builder, LogicalResult &bodyGenStatus) { 466 // Convert blocks one by one in topological order to ensure 467 // defs are converted before uses. 468 llvm::SetVector<Block *> blocks = topologicalSort(region); 469 for (auto indexedBB : llvm::enumerate(blocks)) { 470 Block *bb = indexedBB.value(); 471 llvm::BasicBlock *curLLVMBB = blockMapping[bb]; 472 if (bb->isEntryBlock()) { 473 assert(codeGenIPBBTI->getNumSuccessors() == 1 && 474 "OpenMPIRBuilder provided entry block has multiple successors"); 475 assert(codeGenIPBBTI->getSuccessor(0) == &continuationIP && 476 "ContinuationIP is not the successor of OpenMPIRBuilder " 477 "provided entry block"); 478 codeGenIPBBTI->setSuccessor(0, curLLVMBB); 479 } 480 481 if (failed(convertBlock(*bb, /*ignoreArguments=*/indexedBB.index() == 0))) { 482 bodyGenStatus = failure(); 483 return; 484 } 485 } 486 // Finally, after all blocks have been traversed and values mapped, 487 // connect the PHI nodes to the results of preceding blocks. 488 connectPHINodes(region, valueMapping, blockMapping, branchMapping); 489 } 490 491 LogicalResult ModuleTranslation::convertOmpMaster(Operation &opInst, 492 llvm::IRBuilder<> &builder) { 493 using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy; 494 // TODO: support error propagation in OpenMPIRBuilder and use it instead of 495 // relying on captured variables. 496 LogicalResult bodyGenStatus = success(); 497 498 auto bodyGenCB = [&](InsertPointTy allocaIP, InsertPointTy codeGenIP, 499 llvm::BasicBlock &continuationIP) { 500 llvm::LLVMContext &llvmContext = llvmModule->getContext(); 501 502 llvm::BasicBlock *codeGenIPBB = codeGenIP.getBlock(); 503 llvm::Instruction *codeGenIPBBTI = codeGenIPBB->getTerminator(); 504 ompContinuationIPStack.push_back(&continuationIP); 505 506 // MasterOp has only `1` region associated with it. 507 auto ®ion = cast<omp::MasterOp>(opInst).getRegion(); 508 for (auto &bb : region) { 509 auto *llvmBB = llvm::BasicBlock::Create( 510 llvmContext, "omp.master.region", codeGenIP.getBlock()->getParent()); 511 blockMapping[&bb] = llvmBB; 512 } 513 convertOmpOpRegions(region, valueMapping, blockMapping, codeGenIPBBTI, 514 continuationIP, builder, bodyGenStatus); 515 ompContinuationIPStack.pop_back(); 516 }; 517 518 // TODO: Perform finalization actions for variables. This has to be 519 // called for variables which have destructors/finalizers. 520 auto finiCB = [&](InsertPointTy codeGenIP) {}; 521 522 builder.restoreIP(ompBuilder->createMaster(builder, bodyGenCB, finiCB)); 523 return success(); 524 } 525 526 /// Given an OpenMP MLIR operation, create the corresponding LLVM IR 527 /// (including OpenMP runtime calls). 528 LogicalResult 529 ModuleTranslation::convertOmpOperation(Operation &opInst, 530 llvm::IRBuilder<> &builder) { 531 if (!ompBuilder) { 532 ompBuilder = std::make_unique<llvm::OpenMPIRBuilder>(*llvmModule); 533 ompBuilder->initialize(); 534 } 535 return llvm::TypeSwitch<Operation *, LogicalResult>(&opInst) 536 .Case([&](omp::BarrierOp) { 537 ompBuilder->createBarrier(builder.saveIP(), llvm::omp::OMPD_barrier); 538 return success(); 539 }) 540 .Case([&](omp::TaskwaitOp) { 541 ompBuilder->createTaskwait(builder.saveIP()); 542 return success(); 543 }) 544 .Case([&](omp::TaskyieldOp) { 545 ompBuilder->createTaskyield(builder.saveIP()); 546 return success(); 547 }) 548 .Case([&](omp::FlushOp) { 549 // No support in Openmp runtime function (__kmpc_flush) to accept 550 // the argument list. 551 // OpenMP standard states the following: 552 // "An implementation may implement a flush with a list by ignoring 553 // the list, and treating it the same as a flush without a list." 554 // 555 // The argument list is discarded so that, flush with a list is treated 556 // same as a flush without a list. 557 ompBuilder->createFlush(builder.saveIP()); 558 return success(); 559 }) 560 .Case([&](omp::TerminatorOp) { 561 builder.CreateBr(ompContinuationIPStack.back()); 562 return success(); 563 }) 564 .Case( 565 [&](omp::ParallelOp) { return convertOmpParallel(opInst, builder); }) 566 .Case([&](omp::MasterOp) { return convertOmpMaster(opInst, builder); }) 567 .Default([&](Operation *inst) { 568 return inst->emitError("unsupported OpenMP operation: ") 569 << inst->getName(); 570 }); 571 } 572 573 /// Given a single MLIR operation, create the corresponding LLVM IR operation 574 /// using the `builder`. LLVM IR Builder does not have a generic interface so 575 /// this has to be a long chain of `if`s calling different functions with a 576 /// different number of arguments. 577 LogicalResult ModuleTranslation::convertOperation(Operation &opInst, 578 llvm::IRBuilder<> &builder) { 579 auto extractPosition = [](ArrayAttr attr) { 580 SmallVector<unsigned, 4> position; 581 position.reserve(attr.size()); 582 for (Attribute v : attr) 583 position.push_back(v.cast<IntegerAttr>().getValue().getZExtValue()); 584 return position; 585 }; 586 587 #include "mlir/Dialect/LLVMIR/LLVMConversions.inc" 588 589 // Emit function calls. If the "callee" attribute is present, this is a 590 // direct function call and we also need to look up the remapped function 591 // itself. Otherwise, this is an indirect call and the callee is the first 592 // operand, look it up as a normal value. Return the llvm::Value representing 593 // the function result, which may be of llvm::VoidTy type. 594 auto convertCall = [this, &builder](Operation &op) -> llvm::Value * { 595 auto operands = lookupValues(op.getOperands()); 596 ArrayRef<llvm::Value *> operandsRef(operands); 597 if (auto attr = op.getAttrOfType<FlatSymbolRefAttr>("callee")) { 598 return builder.CreateCall(functionMapping.lookup(attr.getValue()), 599 operandsRef); 600 } else { 601 auto *calleePtrType = 602 cast<llvm::PointerType>(operandsRef.front()->getType()); 603 auto *calleeType = 604 cast<llvm::FunctionType>(calleePtrType->getElementType()); 605 return builder.CreateCall(calleeType, operandsRef.front(), 606 operandsRef.drop_front()); 607 } 608 }; 609 610 // Emit calls. If the called function has a result, remap the corresponding 611 // value. Note that LLVM IR dialect CallOp has either 0 or 1 result. 612 if (isa<LLVM::CallOp>(opInst)) { 613 llvm::Value *result = convertCall(opInst); 614 if (opInst.getNumResults() != 0) { 615 valueMapping[opInst.getResult(0)] = result; 616 return success(); 617 } 618 // Check that LLVM call returns void for 0-result functions. 619 return success(result->getType()->isVoidTy()); 620 } 621 622 if (auto inlineAsmOp = dyn_cast<LLVM::InlineAsmOp>(opInst)) { 623 // TODO: refactor function type creation which usually occurs in std-LLVM 624 // conversion. 625 SmallVector<LLVM::LLVMType, 8> operandTypes; 626 operandTypes.reserve(inlineAsmOp.operands().size()); 627 for (auto t : inlineAsmOp.operands().getTypes()) 628 operandTypes.push_back(t.cast<LLVM::LLVMType>()); 629 630 LLVM::LLVMType resultType; 631 if (inlineAsmOp.getNumResults() == 0) { 632 resultType = LLVM::LLVMType::getVoidTy(mlirModule->getContext()); 633 } else { 634 assert(inlineAsmOp.getNumResults() == 1); 635 resultType = inlineAsmOp.getResultTypes()[0].cast<LLVM::LLVMType>(); 636 } 637 auto ft = LLVM::LLVMType::getFunctionTy(resultType, operandTypes, 638 /*isVarArg=*/false); 639 llvm::InlineAsm *inlineAsmInst = 640 inlineAsmOp.asm_dialect().hasValue() 641 ? llvm::InlineAsm::get( 642 static_cast<llvm::FunctionType *>(convertType(ft)), 643 inlineAsmOp.asm_string(), inlineAsmOp.constraints(), 644 inlineAsmOp.has_side_effects(), inlineAsmOp.is_align_stack(), 645 convertAsmDialectToLLVM(*inlineAsmOp.asm_dialect())) 646 : llvm::InlineAsm::get( 647 static_cast<llvm::FunctionType *>(convertType(ft)), 648 inlineAsmOp.asm_string(), inlineAsmOp.constraints(), 649 inlineAsmOp.has_side_effects(), inlineAsmOp.is_align_stack()); 650 llvm::Value *result = 651 builder.CreateCall(inlineAsmInst, lookupValues(inlineAsmOp.operands())); 652 if (opInst.getNumResults() != 0) 653 valueMapping[opInst.getResult(0)] = result; 654 return success(); 655 } 656 657 if (auto invOp = dyn_cast<LLVM::InvokeOp>(opInst)) { 658 auto operands = lookupValues(opInst.getOperands()); 659 ArrayRef<llvm::Value *> operandsRef(operands); 660 if (auto attr = opInst.getAttrOfType<FlatSymbolRefAttr>("callee")) { 661 builder.CreateInvoke(functionMapping.lookup(attr.getValue()), 662 blockMapping[invOp.getSuccessor(0)], 663 blockMapping[invOp.getSuccessor(1)], operandsRef); 664 } else { 665 auto *calleePtrType = 666 cast<llvm::PointerType>(operandsRef.front()->getType()); 667 auto *calleeType = 668 cast<llvm::FunctionType>(calleePtrType->getElementType()); 669 builder.CreateInvoke( 670 calleeType, operandsRef.front(), blockMapping[invOp.getSuccessor(0)], 671 blockMapping[invOp.getSuccessor(1)], operandsRef.drop_front()); 672 } 673 return success(); 674 } 675 676 if (auto lpOp = dyn_cast<LLVM::LandingpadOp>(opInst)) { 677 llvm::Type *ty = convertType(lpOp.getType().cast<LLVMType>()); 678 llvm::LandingPadInst *lpi = 679 builder.CreateLandingPad(ty, lpOp.getNumOperands()); 680 681 // Add clauses 682 for (auto operand : lookupValues(lpOp.getOperands())) { 683 // All operands should be constant - checked by verifier 684 if (auto constOperand = dyn_cast<llvm::Constant>(operand)) 685 lpi->addClause(constOperand); 686 } 687 valueMapping[lpOp.getResult()] = lpi; 688 return success(); 689 } 690 691 // Emit branches. We need to look up the remapped blocks and ignore the block 692 // arguments that were transformed into PHI nodes. 693 if (auto brOp = dyn_cast<LLVM::BrOp>(opInst)) { 694 llvm::BranchInst *branch = 695 builder.CreateBr(blockMapping[brOp.getSuccessor()]); 696 branchMapping.try_emplace(&opInst, branch); 697 return success(); 698 } 699 if (auto condbrOp = dyn_cast<LLVM::CondBrOp>(opInst)) { 700 auto weights = condbrOp.branch_weights(); 701 llvm::MDNode *branchWeights = nullptr; 702 if (weights) { 703 // Map weight attributes to LLVM metadata. 704 auto trueWeight = 705 weights.getValue().getValue(0).cast<IntegerAttr>().getInt(); 706 auto falseWeight = 707 weights.getValue().getValue(1).cast<IntegerAttr>().getInt(); 708 branchWeights = 709 llvm::MDBuilder(llvmModule->getContext()) 710 .createBranchWeights(static_cast<uint32_t>(trueWeight), 711 static_cast<uint32_t>(falseWeight)); 712 } 713 llvm::BranchInst *branch = builder.CreateCondBr( 714 valueMapping.lookup(condbrOp.getOperand(0)), 715 blockMapping[condbrOp.getSuccessor(0)], 716 blockMapping[condbrOp.getSuccessor(1)], branchWeights); 717 branchMapping.try_emplace(&opInst, branch); 718 return success(); 719 } 720 721 // Emit addressof. We need to look up the global value referenced by the 722 // operation and store it in the MLIR-to-LLVM value mapping. This does not 723 // emit any LLVM instruction. 724 if (auto addressOfOp = dyn_cast<LLVM::AddressOfOp>(opInst)) { 725 LLVM::GlobalOp global = addressOfOp.getGlobal(); 726 LLVM::LLVMFuncOp function = addressOfOp.getFunction(); 727 728 // The verifier should not have allowed this. 729 assert((global || function) && 730 "referencing an undefined global or function"); 731 732 valueMapping[addressOfOp.getResult()] = 733 global ? globalsMapping.lookup(global) 734 : functionMapping.lookup(function.getName()); 735 return success(); 736 } 737 738 if (ompDialect && opInst.getDialect() == ompDialect) 739 return convertOmpOperation(opInst, builder); 740 741 return opInst.emitError("unsupported or non-LLVM operation: ") 742 << opInst.getName(); 743 } 744 745 /// Convert block to LLVM IR. Unless `ignoreArguments` is set, emit PHI nodes 746 /// to define values corresponding to the MLIR block arguments. These nodes 747 /// are not connected to the source basic blocks, which may not exist yet. 748 LogicalResult ModuleTranslation::convertBlock(Block &bb, bool ignoreArguments) { 749 llvm::IRBuilder<> builder(blockMapping[&bb]); 750 auto *subprogram = builder.GetInsertBlock()->getParent()->getSubprogram(); 751 752 // Before traversing operations, make block arguments available through 753 // value remapping and PHI nodes, but do not add incoming edges for the PHI 754 // nodes just yet: those values may be defined by this or following blocks. 755 // This step is omitted if "ignoreArguments" is set. The arguments of the 756 // first block have been already made available through the remapping of 757 // LLVM function arguments. 758 if (!ignoreArguments) { 759 auto predecessors = bb.getPredecessors(); 760 unsigned numPredecessors = 761 std::distance(predecessors.begin(), predecessors.end()); 762 for (auto arg : bb.getArguments()) { 763 auto wrappedType = arg.getType().dyn_cast<LLVM::LLVMType>(); 764 if (!wrappedType) 765 return emitError(bb.front().getLoc(), 766 "block argument does not have an LLVM type"); 767 llvm::Type *type = convertType(wrappedType); 768 llvm::PHINode *phi = builder.CreatePHI(type, numPredecessors); 769 valueMapping[arg] = phi; 770 } 771 } 772 773 // Traverse operations. 774 for (auto &op : bb) { 775 // Set the current debug location within the builder. 776 builder.SetCurrentDebugLocation( 777 debugTranslation->translateLoc(op.getLoc(), subprogram)); 778 779 if (failed(convertOperation(op, builder))) 780 return failure(); 781 } 782 783 return success(); 784 } 785 786 /// Create named global variables that correspond to llvm.mlir.global 787 /// definitions. 788 LogicalResult ModuleTranslation::convertGlobals() { 789 for (auto op : getModuleBody(mlirModule).getOps<LLVM::GlobalOp>()) { 790 llvm::Type *type = convertType(op.getType()); 791 llvm::Constant *cst = llvm::UndefValue::get(type); 792 if (op.getValueOrNull()) { 793 // String attributes are treated separately because they cannot appear as 794 // in-function constants and are thus not supported by getLLVMConstant. 795 if (auto strAttr = op.getValueOrNull().dyn_cast_or_null<StringAttr>()) { 796 cst = llvm::ConstantDataArray::getString( 797 llvmModule->getContext(), strAttr.getValue(), /*AddNull=*/false); 798 type = cst->getType(); 799 } else if (!(cst = getLLVMConstant(type, op.getValueOrNull(), 800 op.getLoc()))) { 801 return failure(); 802 } 803 } else if (Block *initializer = op.getInitializerBlock()) { 804 llvm::IRBuilder<> builder(llvmModule->getContext()); 805 for (auto &op : initializer->without_terminator()) { 806 if (failed(convertOperation(op, builder)) || 807 !isa<llvm::Constant>(valueMapping.lookup(op.getResult(0)))) 808 return emitError(op.getLoc(), "unemittable constant value"); 809 } 810 ReturnOp ret = cast<ReturnOp>(initializer->getTerminator()); 811 cst = cast<llvm::Constant>(valueMapping.lookup(ret.getOperand(0))); 812 } 813 814 auto linkage = convertLinkageToLLVM(op.linkage()); 815 bool anyExternalLinkage = 816 ((linkage == llvm::GlobalVariable::ExternalLinkage && 817 isa<llvm::UndefValue>(cst)) || 818 linkage == llvm::GlobalVariable::ExternalWeakLinkage); 819 auto addrSpace = op.addr_space(); 820 auto *var = new llvm::GlobalVariable( 821 *llvmModule, type, op.constant(), linkage, 822 anyExternalLinkage ? nullptr : cst, op.sym_name(), 823 /*InsertBefore=*/nullptr, llvm::GlobalValue::NotThreadLocal, addrSpace); 824 825 globalsMapping.try_emplace(op, var); 826 } 827 828 return success(); 829 } 830 831 /// Attempts to add an attribute identified by `key`, optionally with the given 832 /// `value` to LLVM function `llvmFunc`. Reports errors at `loc` if any. If the 833 /// attribute has a kind known to LLVM IR, create the attribute of this kind, 834 /// otherwise keep it as a string attribute. Performs additional checks for 835 /// attributes known to have or not have a value in order to avoid assertions 836 /// inside LLVM upon construction. 837 static LogicalResult checkedAddLLVMFnAttribute(Location loc, 838 llvm::Function *llvmFunc, 839 StringRef key, 840 StringRef value = StringRef()) { 841 auto kind = llvm::Attribute::getAttrKindFromName(key); 842 if (kind == llvm::Attribute::None) { 843 llvmFunc->addFnAttr(key, value); 844 return success(); 845 } 846 847 if (llvm::Attribute::doesAttrKindHaveArgument(kind)) { 848 if (value.empty()) 849 return emitError(loc) << "LLVM attribute '" << key << "' expects a value"; 850 851 int result; 852 if (!value.getAsInteger(/*Radix=*/0, result)) 853 llvmFunc->addFnAttr( 854 llvm::Attribute::get(llvmFunc->getContext(), kind, result)); 855 else 856 llvmFunc->addFnAttr(key, value); 857 return success(); 858 } 859 860 if (!value.empty()) 861 return emitError(loc) << "LLVM attribute '" << key 862 << "' does not expect a value, found '" << value 863 << "'"; 864 865 llvmFunc->addFnAttr(kind); 866 return success(); 867 } 868 869 /// Attaches the attributes listed in the given array attribute to `llvmFunc`. 870 /// Reports error to `loc` if any and returns immediately. Expects `attributes` 871 /// to be an array attribute containing either string attributes, treated as 872 /// value-less LLVM attributes, or array attributes containing two string 873 /// attributes, with the first string being the name of the corresponding LLVM 874 /// attribute and the second string beings its value. Note that even integer 875 /// attributes are expected to have their values expressed as strings. 876 static LogicalResult 877 forwardPassthroughAttributes(Location loc, Optional<ArrayAttr> attributes, 878 llvm::Function *llvmFunc) { 879 if (!attributes) 880 return success(); 881 882 for (Attribute attr : *attributes) { 883 if (auto stringAttr = attr.dyn_cast<StringAttr>()) { 884 if (failed( 885 checkedAddLLVMFnAttribute(loc, llvmFunc, stringAttr.getValue()))) 886 return failure(); 887 continue; 888 } 889 890 auto arrayAttr = attr.dyn_cast<ArrayAttr>(); 891 if (!arrayAttr || arrayAttr.size() != 2) 892 return emitError(loc) 893 << "expected 'passthrough' to contain string or array attributes"; 894 895 auto keyAttr = arrayAttr[0].dyn_cast<StringAttr>(); 896 auto valueAttr = arrayAttr[1].dyn_cast<StringAttr>(); 897 if (!keyAttr || !valueAttr) 898 return emitError(loc) 899 << "expected arrays within 'passthrough' to contain two strings"; 900 901 if (failed(checkedAddLLVMFnAttribute(loc, llvmFunc, keyAttr.getValue(), 902 valueAttr.getValue()))) 903 return failure(); 904 } 905 return success(); 906 } 907 908 LogicalResult ModuleTranslation::convertOneFunction(LLVMFuncOp func) { 909 // Clear the block, branch value mappings, they are only relevant within one 910 // function. 911 blockMapping.clear(); 912 valueMapping.clear(); 913 branchMapping.clear(); 914 llvm::Function *llvmFunc = functionMapping.lookup(func.getName()); 915 916 // Translate the debug information for this function. 917 debugTranslation->translate(func, *llvmFunc); 918 919 // Add function arguments to the value remapping table. 920 // If there was noalias info then we decorate each argument accordingly. 921 unsigned int argIdx = 0; 922 for (auto kvp : llvm::zip(func.getArguments(), llvmFunc->args())) { 923 llvm::Argument &llvmArg = std::get<1>(kvp); 924 BlockArgument mlirArg = std::get<0>(kvp); 925 926 if (auto attr = func.getArgAttrOfType<BoolAttr>( 927 argIdx, LLVMDialect::getNoAliasAttrName())) { 928 // NB: Attribute already verified to be boolean, so check if we can indeed 929 // attach the attribute to this argument, based on its type. 930 auto argTy = mlirArg.getType().dyn_cast<LLVM::LLVMType>(); 931 if (!argTy.isPointerTy()) 932 return func.emitError( 933 "llvm.noalias attribute attached to LLVM non-pointer argument"); 934 if (attr.getValue()) 935 llvmArg.addAttr(llvm::Attribute::AttrKind::NoAlias); 936 } 937 938 if (auto attr = func.getArgAttrOfType<IntegerAttr>( 939 argIdx, LLVMDialect::getAlignAttrName())) { 940 // NB: Attribute already verified to be int, so check if we can indeed 941 // attach the attribute to this argument, based on its type. 942 auto argTy = mlirArg.getType().dyn_cast<LLVM::LLVMType>(); 943 if (!argTy.isPointerTy()) 944 return func.emitError( 945 "llvm.align attribute attached to LLVM non-pointer argument"); 946 llvmArg.addAttrs( 947 llvm::AttrBuilder().addAlignmentAttr(llvm::Align(attr.getInt()))); 948 } 949 950 valueMapping[mlirArg] = &llvmArg; 951 argIdx++; 952 } 953 954 // Check the personality and set it. 955 if (func.personality().hasValue()) { 956 llvm::Type *ty = llvm::Type::getInt8PtrTy(llvmFunc->getContext()); 957 if (llvm::Constant *pfunc = 958 getLLVMConstant(ty, func.personalityAttr(), func.getLoc())) 959 llvmFunc->setPersonalityFn(pfunc); 960 } 961 962 // First, create all blocks so we can jump to them. 963 llvm::LLVMContext &llvmContext = llvmFunc->getContext(); 964 for (auto &bb : func) { 965 auto *llvmBB = llvm::BasicBlock::Create(llvmContext); 966 llvmBB->insertInto(llvmFunc); 967 blockMapping[&bb] = llvmBB; 968 } 969 970 // Then, convert blocks one by one in topological order to ensure defs are 971 // converted before uses. 972 auto blocks = topologicalSort(func); 973 for (auto indexedBB : llvm::enumerate(blocks)) { 974 auto *bb = indexedBB.value(); 975 if (failed(convertBlock(*bb, /*ignoreArguments=*/indexedBB.index() == 0))) 976 return failure(); 977 } 978 979 // Finally, after all blocks have been traversed and values mapped, connect 980 // the PHI nodes to the results of preceding blocks. 981 connectPHINodes(func, valueMapping, blockMapping, branchMapping); 982 return success(); 983 } 984 985 LogicalResult ModuleTranslation::checkSupportedModuleOps(Operation *m) { 986 for (Operation &o : getModuleBody(m).getOperations()) 987 if (!isa<LLVM::LLVMFuncOp, LLVM::GlobalOp>(&o) && !o.isKnownTerminator()) 988 return o.emitOpError("unsupported module-level operation"); 989 return success(); 990 } 991 992 LogicalResult ModuleTranslation::convertFunctionSignatures() { 993 // Declare all functions first because there may be function calls that form a 994 // call graph with cycles, or global initializers that reference functions. 995 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 996 llvm::FunctionCallee llvmFuncCst = llvmModule->getOrInsertFunction( 997 function.getName(), 998 cast<llvm::FunctionType>(convertType(function.getType()))); 999 llvm::Function *llvmFunc = cast<llvm::Function>(llvmFuncCst.getCallee()); 1000 llvmFunc->setLinkage(convertLinkageToLLVM(function.linkage())); 1001 functionMapping[function.getName()] = llvmFunc; 1002 1003 // Forward the pass-through attributes to LLVM. 1004 if (failed(forwardPassthroughAttributes(function.getLoc(), 1005 function.passthrough(), llvmFunc))) 1006 return failure(); 1007 } 1008 1009 return success(); 1010 } 1011 1012 LogicalResult ModuleTranslation::convertFunctions() { 1013 // Convert functions. 1014 for (auto function : getModuleBody(mlirModule).getOps<LLVMFuncOp>()) { 1015 // Ignore external functions. 1016 if (function.isExternal()) 1017 continue; 1018 1019 if (failed(convertOneFunction(function))) 1020 return failure(); 1021 } 1022 1023 return success(); 1024 } 1025 1026 llvm::Type *ModuleTranslation::convertType(LLVMType type) { 1027 return typeTranslator.translateType(type); 1028 } 1029 1030 /// A helper to look up remapped operands in the value remapping table.` 1031 SmallVector<llvm::Value *, 8> 1032 ModuleTranslation::lookupValues(ValueRange values) { 1033 SmallVector<llvm::Value *, 8> remapped; 1034 remapped.reserve(values.size()); 1035 for (Value v : values) { 1036 assert(valueMapping.count(v) && "referencing undefined value"); 1037 remapped.push_back(valueMapping.lookup(v)); 1038 } 1039 return remapped; 1040 } 1041 1042 std::unique_ptr<llvm::Module> ModuleTranslation::prepareLLVMModule( 1043 Operation *m, llvm::LLVMContext &llvmContext, StringRef name) { 1044 m->getContext()->getOrLoadDialect<LLVM::LLVMDialect>(); 1045 auto llvmModule = std::make_unique<llvm::Module>(name, llvmContext); 1046 if (auto dataLayoutAttr = 1047 m->getAttr(LLVM::LLVMDialect::getDataLayoutAttrName())) 1048 llvmModule->setDataLayout(dataLayoutAttr.cast<StringAttr>().getValue()); 1049 if (auto targetTripleAttr = 1050 m->getAttr(LLVM::LLVMDialect::getTargetTripleAttrName())) 1051 llvmModule->setTargetTriple(targetTripleAttr.cast<StringAttr>().getValue()); 1052 1053 // Inject declarations for `malloc` and `free` functions that can be used in 1054 // memref allocation/deallocation coming from standard ops lowering. 1055 llvm::IRBuilder<> builder(llvmContext); 1056 llvmModule->getOrInsertFunction("malloc", builder.getInt8PtrTy(), 1057 builder.getInt64Ty()); 1058 llvmModule->getOrInsertFunction("free", builder.getVoidTy(), 1059 builder.getInt8PtrTy()); 1060 1061 return llvmModule; 1062 } 1063