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