1 //===- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator ---*- C++ -*-==// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// \file 10 /// This file implements the IRTranslator class. 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/CodeGen/GlobalISel/IRTranslator.h" 14 #include "llvm/ADT/STLExtras.h" 15 #include "llvm/ADT/ScopeExit.h" 16 #include "llvm/ADT/SmallSet.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 19 #include "llvm/CodeGen/Analysis.h" 20 #include "llvm/CodeGen/GlobalISel/CallLowering.h" 21 #include "llvm/CodeGen/LowLevelType.h" 22 #include "llvm/CodeGen/MachineBasicBlock.h" 23 #include "llvm/CodeGen/MachineFrameInfo.h" 24 #include "llvm/CodeGen/MachineFunction.h" 25 #include "llvm/CodeGen/MachineInstrBuilder.h" 26 #include "llvm/CodeGen/MachineMemOperand.h" 27 #include "llvm/CodeGen/MachineOperand.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/TargetFrameLowering.h" 30 #include "llvm/CodeGen/TargetLowering.h" 31 #include "llvm/CodeGen/TargetPassConfig.h" 32 #include "llvm/CodeGen/TargetRegisterInfo.h" 33 #include "llvm/CodeGen/TargetSubtargetInfo.h" 34 #include "llvm/IR/BasicBlock.h" 35 #include "llvm/IR/Constant.h" 36 #include "llvm/IR/Constants.h" 37 #include "llvm/IR/DataLayout.h" 38 #include "llvm/IR/DebugInfo.h" 39 #include "llvm/IR/DerivedTypes.h" 40 #include "llvm/IR/Function.h" 41 #include "llvm/IR/GetElementPtrTypeIterator.h" 42 #include "llvm/IR/InlineAsm.h" 43 #include "llvm/IR/InstrTypes.h" 44 #include "llvm/IR/Instructions.h" 45 #include "llvm/IR/IntrinsicInst.h" 46 #include "llvm/IR/Intrinsics.h" 47 #include "llvm/IR/LLVMContext.h" 48 #include "llvm/IR/Metadata.h" 49 #include "llvm/IR/Type.h" 50 #include "llvm/IR/User.h" 51 #include "llvm/IR/Value.h" 52 #include "llvm/MC/MCContext.h" 53 #include "llvm/Pass.h" 54 #include "llvm/Support/Casting.h" 55 #include "llvm/Support/CodeGen.h" 56 #include "llvm/Support/Debug.h" 57 #include "llvm/Support/ErrorHandling.h" 58 #include "llvm/Support/LowLevelTypeImpl.h" 59 #include "llvm/Support/MathExtras.h" 60 #include "llvm/Support/raw_ostream.h" 61 #include "llvm/Target/TargetIntrinsicInfo.h" 62 #include "llvm/Target/TargetMachine.h" 63 #include <algorithm> 64 #include <cassert> 65 #include <cstdint> 66 #include <iterator> 67 #include <string> 68 #include <utility> 69 #include <vector> 70 71 #define DEBUG_TYPE "irtranslator" 72 73 using namespace llvm; 74 75 char IRTranslator::ID = 0; 76 77 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI", 78 false, false) 79 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) 80 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI", 81 false, false) 82 83 static void reportTranslationError(MachineFunction &MF, 84 const TargetPassConfig &TPC, 85 OptimizationRemarkEmitter &ORE, 86 OptimizationRemarkMissed &R) { 87 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel); 88 89 // Print the function name explicitly if we don't have a debug location (which 90 // makes the diagnostic less useful) or if we're going to emit a raw error. 91 if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled()) 92 R << (" (in function: " + MF.getName() + ")").str(); 93 94 if (TPC.isGlobalISelAbortEnabled()) 95 report_fatal_error(R.getMsg()); 96 else 97 ORE.emit(R); 98 } 99 100 IRTranslator::IRTranslator() : MachineFunctionPass(ID) { 101 initializeIRTranslatorPass(*PassRegistry::getPassRegistry()); 102 } 103 104 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const { 105 AU.addRequired<TargetPassConfig>(); 106 MachineFunctionPass::getAnalysisUsage(AU); 107 } 108 109 unsigned IRTranslator::getOrCreateVReg(const Value &Val) { 110 unsigned &ValReg = ValToVReg[&Val]; 111 112 if (ValReg) 113 return ValReg; 114 115 // Fill ValRegsSequence with the sequence of registers 116 // we need to concat together to produce the value. 117 assert(Val.getType()->isSized() && 118 "Don't know how to create an empty vreg"); 119 unsigned VReg = 120 MRI->createGenericVirtualRegister(getLLTForType(*Val.getType(), *DL)); 121 ValReg = VReg; 122 123 if (auto CV = dyn_cast<Constant>(&Val)) { 124 bool Success = translate(*CV, VReg); 125 if (!Success) { 126 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 127 MF->getFunction().getSubprogram(), 128 &MF->getFunction().getEntryBlock()); 129 R << "unable to translate constant: " << ore::NV("Type", Val.getType()); 130 reportTranslationError(*MF, *TPC, *ORE, R); 131 return VReg; 132 } 133 } 134 135 return VReg; 136 } 137 138 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) { 139 if (FrameIndices.find(&AI) != FrameIndices.end()) 140 return FrameIndices[&AI]; 141 142 unsigned ElementSize = DL->getTypeStoreSize(AI.getAllocatedType()); 143 unsigned Size = 144 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue(); 145 146 // Always allocate at least one byte. 147 Size = std::max(Size, 1u); 148 149 unsigned Alignment = AI.getAlignment(); 150 if (!Alignment) 151 Alignment = DL->getABITypeAlignment(AI.getAllocatedType()); 152 153 int &FI = FrameIndices[&AI]; 154 FI = MF->getFrameInfo().CreateStackObject(Size, Alignment, false, &AI); 155 return FI; 156 } 157 158 unsigned IRTranslator::getMemOpAlignment(const Instruction &I) { 159 unsigned Alignment = 0; 160 Type *ValTy = nullptr; 161 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) { 162 Alignment = SI->getAlignment(); 163 ValTy = SI->getValueOperand()->getType(); 164 } else if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) { 165 Alignment = LI->getAlignment(); 166 ValTy = LI->getType(); 167 } else { 168 OptimizationRemarkMissed R("gisel-irtranslator", "", &I); 169 R << "unable to translate memop: " << ore::NV("Opcode", &I); 170 reportTranslationError(*MF, *TPC, *ORE, R); 171 return 1; 172 } 173 174 return Alignment ? Alignment : DL->getABITypeAlignment(ValTy); 175 } 176 177 MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) { 178 MachineBasicBlock *&MBB = BBToMBB[&BB]; 179 assert(MBB && "BasicBlock was not encountered before"); 180 return *MBB; 181 } 182 183 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) { 184 assert(NewPred && "new predecessor must be a real MachineBasicBlock"); 185 MachinePreds[Edge].push_back(NewPred); 186 } 187 188 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U, 189 MachineIRBuilder &MIRBuilder) { 190 // FIXME: handle signed/unsigned wrapping flags. 191 192 // Get or create a virtual register for each value. 193 // Unless the value is a Constant => loadimm cst? 194 // or inline constant each time? 195 // Creation of a virtual register needs to have a size. 196 unsigned Op0 = getOrCreateVReg(*U.getOperand(0)); 197 unsigned Op1 = getOrCreateVReg(*U.getOperand(1)); 198 unsigned Res = getOrCreateVReg(U); 199 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op0).addUse(Op1); 200 return true; 201 } 202 203 bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) { 204 // -0.0 - X --> G_FNEG 205 if (isa<Constant>(U.getOperand(0)) && 206 U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) { 207 MIRBuilder.buildInstr(TargetOpcode::G_FNEG) 208 .addDef(getOrCreateVReg(U)) 209 .addUse(getOrCreateVReg(*U.getOperand(1))); 210 return true; 211 } 212 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder); 213 } 214 215 bool IRTranslator::translateCompare(const User &U, 216 MachineIRBuilder &MIRBuilder) { 217 const CmpInst *CI = dyn_cast<CmpInst>(&U); 218 unsigned Op0 = getOrCreateVReg(*U.getOperand(0)); 219 unsigned Op1 = getOrCreateVReg(*U.getOperand(1)); 220 unsigned Res = getOrCreateVReg(U); 221 CmpInst::Predicate Pred = 222 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>( 223 cast<ConstantExpr>(U).getPredicate()); 224 if (CmpInst::isIntPredicate(Pred)) 225 MIRBuilder.buildICmp(Pred, Res, Op0, Op1); 226 else if (Pred == CmpInst::FCMP_FALSE) 227 MIRBuilder.buildCopy( 228 Res, getOrCreateVReg(*Constant::getNullValue(CI->getType()))); 229 else if (Pred == CmpInst::FCMP_TRUE) 230 MIRBuilder.buildCopy( 231 Res, getOrCreateVReg(*Constant::getAllOnesValue(CI->getType()))); 232 else 233 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1); 234 235 return true; 236 } 237 238 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) { 239 const ReturnInst &RI = cast<ReturnInst>(U); 240 const Value *Ret = RI.getReturnValue(); 241 if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0) 242 Ret = nullptr; 243 // The target may mess up with the insertion point, but 244 // this is not important as a return is the last instruction 245 // of the block anyway. 246 return CLI->lowerReturn(MIRBuilder, Ret, !Ret ? 0 : getOrCreateVReg(*Ret)); 247 } 248 249 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) { 250 const BranchInst &BrInst = cast<BranchInst>(U); 251 unsigned Succ = 0; 252 if (!BrInst.isUnconditional()) { 253 // We want a G_BRCOND to the true BB followed by an unconditional branch. 254 unsigned Tst = getOrCreateVReg(*BrInst.getCondition()); 255 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++)); 256 MachineBasicBlock &TrueBB = getMBB(TrueTgt); 257 MIRBuilder.buildBrCond(Tst, TrueBB); 258 } 259 260 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ)); 261 MachineBasicBlock &TgtBB = getMBB(BrTgt); 262 MachineBasicBlock &CurBB = MIRBuilder.getMBB(); 263 264 // If the unconditional target is the layout successor, fallthrough. 265 if (!CurBB.isLayoutSuccessor(&TgtBB)) 266 MIRBuilder.buildBr(TgtBB); 267 268 // Link successors. 269 for (const BasicBlock *Succ : BrInst.successors()) 270 CurBB.addSuccessor(&getMBB(*Succ)); 271 return true; 272 } 273 274 bool IRTranslator::translateSwitch(const User &U, 275 MachineIRBuilder &MIRBuilder) { 276 // For now, just translate as a chain of conditional branches. 277 // FIXME: could we share most of the logic/code in 278 // SelectionDAGBuilder::visitSwitch between SelectionDAG and GlobalISel? 279 // At first sight, it seems most of the logic in there is independent of 280 // SelectionDAG-specifics and a lot of work went in to optimize switch 281 // lowering in there. 282 283 const SwitchInst &SwInst = cast<SwitchInst>(U); 284 const unsigned SwCondValue = getOrCreateVReg(*SwInst.getCondition()); 285 const BasicBlock *OrigBB = SwInst.getParent(); 286 287 LLT LLTi1 = getLLTForType(*Type::getInt1Ty(U.getContext()), *DL); 288 for (auto &CaseIt : SwInst.cases()) { 289 const unsigned CaseValueReg = getOrCreateVReg(*CaseIt.getCaseValue()); 290 const unsigned Tst = MRI->createGenericVirtualRegister(LLTi1); 291 MIRBuilder.buildICmp(CmpInst::ICMP_EQ, Tst, CaseValueReg, SwCondValue); 292 MachineBasicBlock &CurMBB = MIRBuilder.getMBB(); 293 const BasicBlock *TrueBB = CaseIt.getCaseSuccessor(); 294 MachineBasicBlock &TrueMBB = getMBB(*TrueBB); 295 296 MIRBuilder.buildBrCond(Tst, TrueMBB); 297 CurMBB.addSuccessor(&TrueMBB); 298 addMachineCFGPred({OrigBB, TrueBB}, &CurMBB); 299 300 MachineBasicBlock *FalseMBB = 301 MF->CreateMachineBasicBlock(SwInst.getParent()); 302 // Insert the comparison blocks one after the other. 303 MF->insert(std::next(CurMBB.getIterator()), FalseMBB); 304 MIRBuilder.buildBr(*FalseMBB); 305 CurMBB.addSuccessor(FalseMBB); 306 307 MIRBuilder.setMBB(*FalseMBB); 308 } 309 // handle default case 310 const BasicBlock *DefaultBB = SwInst.getDefaultDest(); 311 MachineBasicBlock &DefaultMBB = getMBB(*DefaultBB); 312 MIRBuilder.buildBr(DefaultMBB); 313 MachineBasicBlock &CurMBB = MIRBuilder.getMBB(); 314 CurMBB.addSuccessor(&DefaultMBB); 315 addMachineCFGPred({OrigBB, DefaultBB}, &CurMBB); 316 317 return true; 318 } 319 320 bool IRTranslator::translateIndirectBr(const User &U, 321 MachineIRBuilder &MIRBuilder) { 322 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U); 323 324 const unsigned Tgt = getOrCreateVReg(*BrInst.getAddress()); 325 MIRBuilder.buildBrIndirect(Tgt); 326 327 // Link successors. 328 MachineBasicBlock &CurBB = MIRBuilder.getMBB(); 329 for (const BasicBlock *Succ : BrInst.successors()) 330 CurBB.addSuccessor(&getMBB(*Succ)); 331 332 return true; 333 } 334 335 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) { 336 const LoadInst &LI = cast<LoadInst>(U); 337 338 auto Flags = LI.isVolatile() ? MachineMemOperand::MOVolatile 339 : MachineMemOperand::MONone; 340 Flags |= MachineMemOperand::MOLoad; 341 342 if (DL->getTypeStoreSize(LI.getType()) == 0) 343 return true; 344 345 unsigned Res = getOrCreateVReg(LI); 346 unsigned Addr = getOrCreateVReg(*LI.getPointerOperand()); 347 348 MIRBuilder.buildLoad( 349 Res, Addr, 350 *MF->getMachineMemOperand(MachinePointerInfo(LI.getPointerOperand()), 351 Flags, DL->getTypeStoreSize(LI.getType()), 352 getMemOpAlignment(LI), AAMDNodes(), nullptr, 353 LI.getSyncScopeID(), LI.getOrdering())); 354 return true; 355 } 356 357 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) { 358 const StoreInst &SI = cast<StoreInst>(U); 359 auto Flags = SI.isVolatile() ? MachineMemOperand::MOVolatile 360 : MachineMemOperand::MONone; 361 Flags |= MachineMemOperand::MOStore; 362 363 if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0) 364 return true; 365 366 unsigned Val = getOrCreateVReg(*SI.getValueOperand()); 367 unsigned Addr = getOrCreateVReg(*SI.getPointerOperand()); 368 369 MIRBuilder.buildStore( 370 Val, Addr, 371 *MF->getMachineMemOperand( 372 MachinePointerInfo(SI.getPointerOperand()), Flags, 373 DL->getTypeStoreSize(SI.getValueOperand()->getType()), 374 getMemOpAlignment(SI), AAMDNodes(), nullptr, SI.getSyncScopeID(), 375 SI.getOrdering())); 376 return true; 377 } 378 379 bool IRTranslator::translateExtractValue(const User &U, 380 MachineIRBuilder &MIRBuilder) { 381 const Value *Src = U.getOperand(0); 382 Type *Int32Ty = Type::getInt32Ty(U.getContext()); 383 SmallVector<Value *, 1> Indices; 384 385 // If Src is a single element ConstantStruct, translate extractvalue 386 // to that element to avoid inserting a cast instruction. 387 if (auto CS = dyn_cast<ConstantStruct>(Src)) 388 if (CS->getNumOperands() == 1) { 389 unsigned Res = getOrCreateVReg(*CS->getOperand(0)); 390 ValToVReg[&U] = Res; 391 return true; 392 } 393 394 // getIndexedOffsetInType is designed for GEPs, so the first index is the 395 // usual array element rather than looking into the actual aggregate. 396 Indices.push_back(ConstantInt::get(Int32Ty, 0)); 397 398 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) { 399 for (auto Idx : EVI->indices()) 400 Indices.push_back(ConstantInt::get(Int32Ty, Idx)); 401 } else { 402 for (unsigned i = 1; i < U.getNumOperands(); ++i) 403 Indices.push_back(U.getOperand(i)); 404 } 405 406 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices); 407 408 unsigned Res = getOrCreateVReg(U); 409 MIRBuilder.buildExtract(Res, getOrCreateVReg(*Src), Offset); 410 411 return true; 412 } 413 414 bool IRTranslator::translateInsertValue(const User &U, 415 MachineIRBuilder &MIRBuilder) { 416 const Value *Src = U.getOperand(0); 417 Type *Int32Ty = Type::getInt32Ty(U.getContext()); 418 SmallVector<Value *, 1> Indices; 419 420 // getIndexedOffsetInType is designed for GEPs, so the first index is the 421 // usual array element rather than looking into the actual aggregate. 422 Indices.push_back(ConstantInt::get(Int32Ty, 0)); 423 424 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) { 425 for (auto Idx : IVI->indices()) 426 Indices.push_back(ConstantInt::get(Int32Ty, Idx)); 427 } else { 428 for (unsigned i = 2; i < U.getNumOperands(); ++i) 429 Indices.push_back(U.getOperand(i)); 430 } 431 432 uint64_t Offset = 8 * DL->getIndexedOffsetInType(Src->getType(), Indices); 433 434 unsigned Res = getOrCreateVReg(U); 435 unsigned Inserted = getOrCreateVReg(*U.getOperand(1)); 436 MIRBuilder.buildInsert(Res, getOrCreateVReg(*Src), Inserted, Offset); 437 438 return true; 439 } 440 441 bool IRTranslator::translateSelect(const User &U, 442 MachineIRBuilder &MIRBuilder) { 443 unsigned Res = getOrCreateVReg(U); 444 unsigned Tst = getOrCreateVReg(*U.getOperand(0)); 445 unsigned Op0 = getOrCreateVReg(*U.getOperand(1)); 446 unsigned Op1 = getOrCreateVReg(*U.getOperand(2)); 447 MIRBuilder.buildSelect(Res, Tst, Op0, Op1); 448 return true; 449 } 450 451 bool IRTranslator::translateBitCast(const User &U, 452 MachineIRBuilder &MIRBuilder) { 453 // If we're bitcasting to the source type, we can reuse the source vreg. 454 if (getLLTForType(*U.getOperand(0)->getType(), *DL) == 455 getLLTForType(*U.getType(), *DL)) { 456 // Get the source vreg now, to avoid invalidating ValToVReg. 457 unsigned SrcReg = getOrCreateVReg(*U.getOperand(0)); 458 unsigned &Reg = ValToVReg[&U]; 459 // If we already assigned a vreg for this bitcast, we can't change that. 460 // Emit a copy to satisfy the users we already emitted. 461 if (Reg) 462 MIRBuilder.buildCopy(Reg, SrcReg); 463 else 464 Reg = SrcReg; 465 return true; 466 } 467 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder); 468 } 469 470 bool IRTranslator::translateCast(unsigned Opcode, const User &U, 471 MachineIRBuilder &MIRBuilder) { 472 unsigned Op = getOrCreateVReg(*U.getOperand(0)); 473 unsigned Res = getOrCreateVReg(U); 474 MIRBuilder.buildInstr(Opcode).addDef(Res).addUse(Op); 475 return true; 476 } 477 478 bool IRTranslator::translateGetElementPtr(const User &U, 479 MachineIRBuilder &MIRBuilder) { 480 // FIXME: support vector GEPs. 481 if (U.getType()->isVectorTy()) 482 return false; 483 484 Value &Op0 = *U.getOperand(0); 485 unsigned BaseReg = getOrCreateVReg(Op0); 486 Type *PtrIRTy = Op0.getType(); 487 LLT PtrTy = getLLTForType(*PtrIRTy, *DL); 488 Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy); 489 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL); 490 491 int64_t Offset = 0; 492 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U); 493 GTI != E; ++GTI) { 494 const Value *Idx = GTI.getOperand(); 495 if (StructType *StTy = GTI.getStructTypeOrNull()) { 496 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 497 Offset += DL->getStructLayout(StTy)->getElementOffset(Field); 498 continue; 499 } else { 500 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 501 502 // If this is a scalar constant or a splat vector of constants, 503 // handle it quickly. 504 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) { 505 Offset += ElementSize * CI->getSExtValue(); 506 continue; 507 } 508 509 if (Offset != 0) { 510 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy); 511 unsigned OffsetReg = 512 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset)); 513 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg); 514 515 BaseReg = NewBaseReg; 516 Offset = 0; 517 } 518 519 // N = N + Idx * ElementSize; 520 unsigned ElementSizeReg = 521 getOrCreateVReg(*ConstantInt::get(OffsetIRTy, ElementSize)); 522 523 unsigned IdxReg = getOrCreateVReg(*Idx); 524 if (MRI->getType(IdxReg) != OffsetTy) { 525 unsigned NewIdxReg = MRI->createGenericVirtualRegister(OffsetTy); 526 MIRBuilder.buildSExtOrTrunc(NewIdxReg, IdxReg); 527 IdxReg = NewIdxReg; 528 } 529 530 unsigned OffsetReg = MRI->createGenericVirtualRegister(OffsetTy); 531 MIRBuilder.buildMul(OffsetReg, ElementSizeReg, IdxReg); 532 533 unsigned NewBaseReg = MRI->createGenericVirtualRegister(PtrTy); 534 MIRBuilder.buildGEP(NewBaseReg, BaseReg, OffsetReg); 535 BaseReg = NewBaseReg; 536 } 537 } 538 539 if (Offset != 0) { 540 unsigned OffsetReg = getOrCreateVReg(*ConstantInt::get(OffsetIRTy, Offset)); 541 MIRBuilder.buildGEP(getOrCreateVReg(U), BaseReg, OffsetReg); 542 return true; 543 } 544 545 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg); 546 return true; 547 } 548 549 bool IRTranslator::translateMemfunc(const CallInst &CI, 550 MachineIRBuilder &MIRBuilder, 551 unsigned ID) { 552 LLT SizeTy = getLLTForType(*CI.getArgOperand(2)->getType(), *DL); 553 Type *DstTy = CI.getArgOperand(0)->getType(); 554 if (cast<PointerType>(DstTy)->getAddressSpace() != 0 || 555 SizeTy.getSizeInBits() != DL->getPointerSizeInBits(0)) 556 return false; 557 558 SmallVector<CallLowering::ArgInfo, 8> Args; 559 for (int i = 0; i < 3; ++i) { 560 const auto &Arg = CI.getArgOperand(i); 561 Args.emplace_back(getOrCreateVReg(*Arg), Arg->getType()); 562 } 563 564 const char *Callee; 565 switch (ID) { 566 case Intrinsic::memmove: 567 case Intrinsic::memcpy: { 568 Type *SrcTy = CI.getArgOperand(1)->getType(); 569 if(cast<PointerType>(SrcTy)->getAddressSpace() != 0) 570 return false; 571 Callee = ID == Intrinsic::memcpy ? "memcpy" : "memmove"; 572 break; 573 } 574 case Intrinsic::memset: 575 Callee = "memset"; 576 break; 577 default: 578 return false; 579 } 580 581 return CLI->lowerCall(MIRBuilder, CI.getCallingConv(), 582 MachineOperand::CreateES(Callee), 583 CallLowering::ArgInfo(0, CI.getType()), Args); 584 } 585 586 void IRTranslator::getStackGuard(unsigned DstReg, 587 MachineIRBuilder &MIRBuilder) { 588 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 589 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF)); 590 auto MIB = MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD); 591 MIB.addDef(DstReg); 592 593 auto &TLI = *MF->getSubtarget().getTargetLowering(); 594 Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent()); 595 if (!Global) 596 return; 597 598 MachinePointerInfo MPInfo(Global); 599 MachineInstr::mmo_iterator MemRefs = MF->allocateMemRefsArray(1); 600 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 601 MachineMemOperand::MODereferenceable; 602 *MemRefs = 603 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8, 604 DL->getPointerABIAlignment(0)); 605 MIB.setMemRefs(MemRefs, MemRefs + 1); 606 } 607 608 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op, 609 MachineIRBuilder &MIRBuilder) { 610 LLT Ty = getLLTForType(*CI.getOperand(0)->getType(), *DL); 611 LLT s1 = LLT::scalar(1); 612 unsigned Width = Ty.getSizeInBits(); 613 unsigned Res = MRI->createGenericVirtualRegister(Ty); 614 unsigned Overflow = MRI->createGenericVirtualRegister(s1); 615 auto MIB = MIRBuilder.buildInstr(Op) 616 .addDef(Res) 617 .addDef(Overflow) 618 .addUse(getOrCreateVReg(*CI.getOperand(0))) 619 .addUse(getOrCreateVReg(*CI.getOperand(1))); 620 621 if (Op == TargetOpcode::G_UADDE || Op == TargetOpcode::G_USUBE) { 622 unsigned Zero = getOrCreateVReg( 623 *Constant::getNullValue(Type::getInt1Ty(CI.getContext()))); 624 MIB.addUse(Zero); 625 } 626 627 MIRBuilder.buildSequence(getOrCreateVReg(CI), {Res, Overflow}, {0, Width}); 628 return true; 629 } 630 631 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID, 632 MachineIRBuilder &MIRBuilder) { 633 switch (ID) { 634 default: 635 break; 636 case Intrinsic::lifetime_start: 637 case Intrinsic::lifetime_end: 638 // Stack coloring is not enabled in O0 (which we care about now) so we can 639 // drop these. Make sure someone notices when we start compiling at higher 640 // opts though. 641 if (MF->getTarget().getOptLevel() != CodeGenOpt::None) 642 return false; 643 return true; 644 case Intrinsic::dbg_declare: { 645 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI); 646 assert(DI.getVariable() && "Missing variable"); 647 648 const Value *Address = DI.getAddress(); 649 if (!Address || isa<UndefValue>(Address)) { 650 DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 651 return true; 652 } 653 654 assert(DI.getVariable()->isValidLocationForIntrinsic( 655 MIRBuilder.getDebugLoc()) && 656 "Expected inlined-at fields to agree"); 657 auto AI = dyn_cast<AllocaInst>(Address); 658 if (AI && AI->isStaticAlloca()) { 659 // Static allocas are tracked at the MF level, no need for DBG_VALUE 660 // instructions (in fact, they get ignored if they *do* exist). 661 MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(), 662 getOrCreateFrameIndex(*AI), DI.getDebugLoc()); 663 } else 664 MIRBuilder.buildDirectDbgValue(getOrCreateVReg(*Address), 665 DI.getVariable(), DI.getExpression()); 666 return true; 667 } 668 case Intrinsic::vaend: 669 // No target I know of cares about va_end. Certainly no in-tree target 670 // does. Simplest intrinsic ever! 671 return true; 672 case Intrinsic::vastart: { 673 auto &TLI = *MF->getSubtarget().getTargetLowering(); 674 Value *Ptr = CI.getArgOperand(0); 675 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8; 676 677 MIRBuilder.buildInstr(TargetOpcode::G_VASTART) 678 .addUse(getOrCreateVReg(*Ptr)) 679 .addMemOperand(MF->getMachineMemOperand( 680 MachinePointerInfo(Ptr), MachineMemOperand::MOStore, ListSize, 0)); 681 return true; 682 } 683 case Intrinsic::dbg_value: { 684 // This form of DBG_VALUE is target-independent. 685 const DbgValueInst &DI = cast<DbgValueInst>(CI); 686 const Value *V = DI.getValue(); 687 assert(DI.getVariable()->isValidLocationForIntrinsic( 688 MIRBuilder.getDebugLoc()) && 689 "Expected inlined-at fields to agree"); 690 if (!V) { 691 // Currently the optimizer can produce this; insert an undef to 692 // help debugging. Probably the optimizer should not do this. 693 MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression()); 694 } else if (const auto *CI = dyn_cast<Constant>(V)) { 695 MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression()); 696 } else { 697 unsigned Reg = getOrCreateVReg(*V); 698 // FIXME: This does not handle register-indirect values at offset 0. The 699 // direct/indirect thing shouldn't really be handled by something as 700 // implicit as reg+noreg vs reg+imm in the first palce, but it seems 701 // pretty baked in right now. 702 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression()); 703 } 704 return true; 705 } 706 case Intrinsic::uadd_with_overflow: 707 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDE, MIRBuilder); 708 case Intrinsic::sadd_with_overflow: 709 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder); 710 case Intrinsic::usub_with_overflow: 711 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBE, MIRBuilder); 712 case Intrinsic::ssub_with_overflow: 713 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder); 714 case Intrinsic::umul_with_overflow: 715 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder); 716 case Intrinsic::smul_with_overflow: 717 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder); 718 case Intrinsic::pow: 719 MIRBuilder.buildInstr(TargetOpcode::G_FPOW) 720 .addDef(getOrCreateVReg(CI)) 721 .addUse(getOrCreateVReg(*CI.getArgOperand(0))) 722 .addUse(getOrCreateVReg(*CI.getArgOperand(1))); 723 return true; 724 case Intrinsic::exp: 725 MIRBuilder.buildInstr(TargetOpcode::G_FEXP) 726 .addDef(getOrCreateVReg(CI)) 727 .addUse(getOrCreateVReg(*CI.getArgOperand(0))); 728 return true; 729 case Intrinsic::exp2: 730 MIRBuilder.buildInstr(TargetOpcode::G_FEXP2) 731 .addDef(getOrCreateVReg(CI)) 732 .addUse(getOrCreateVReg(*CI.getArgOperand(0))); 733 return true; 734 case Intrinsic::log: 735 MIRBuilder.buildInstr(TargetOpcode::G_FLOG) 736 .addDef(getOrCreateVReg(CI)) 737 .addUse(getOrCreateVReg(*CI.getArgOperand(0))); 738 return true; 739 case Intrinsic::log2: 740 MIRBuilder.buildInstr(TargetOpcode::G_FLOG2) 741 .addDef(getOrCreateVReg(CI)) 742 .addUse(getOrCreateVReg(*CI.getArgOperand(0))); 743 return true; 744 case Intrinsic::fma: 745 MIRBuilder.buildInstr(TargetOpcode::G_FMA) 746 .addDef(getOrCreateVReg(CI)) 747 .addUse(getOrCreateVReg(*CI.getArgOperand(0))) 748 .addUse(getOrCreateVReg(*CI.getArgOperand(1))) 749 .addUse(getOrCreateVReg(*CI.getArgOperand(2))); 750 return true; 751 case Intrinsic::memcpy: 752 case Intrinsic::memmove: 753 case Intrinsic::memset: 754 return translateMemfunc(CI, MIRBuilder, ID); 755 case Intrinsic::eh_typeid_for: { 756 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0)); 757 unsigned Reg = getOrCreateVReg(CI); 758 unsigned TypeID = MF->getTypeIDFor(GV); 759 MIRBuilder.buildConstant(Reg, TypeID); 760 return true; 761 } 762 case Intrinsic::objectsize: { 763 // If we don't know by now, we're never going to know. 764 const ConstantInt *Min = cast<ConstantInt>(CI.getArgOperand(1)); 765 766 MIRBuilder.buildConstant(getOrCreateVReg(CI), Min->isZero() ? -1ULL : 0); 767 return true; 768 } 769 case Intrinsic::stackguard: 770 getStackGuard(getOrCreateVReg(CI), MIRBuilder); 771 return true; 772 case Intrinsic::stackprotector: { 773 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL); 774 unsigned GuardVal = MRI->createGenericVirtualRegister(PtrTy); 775 getStackGuard(GuardVal, MIRBuilder); 776 777 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1)); 778 MIRBuilder.buildStore( 779 GuardVal, getOrCreateVReg(*Slot), 780 *MF->getMachineMemOperand( 781 MachinePointerInfo::getFixedStack(*MF, 782 getOrCreateFrameIndex(*Slot)), 783 MachineMemOperand::MOStore | MachineMemOperand::MOVolatile, 784 PtrTy.getSizeInBits() / 8, 8)); 785 return true; 786 } 787 } 788 return false; 789 } 790 791 bool IRTranslator::translateInlineAsm(const CallInst &CI, 792 MachineIRBuilder &MIRBuilder) { 793 const InlineAsm &IA = cast<InlineAsm>(*CI.getCalledValue()); 794 if (!IA.getConstraintString().empty()) 795 return false; 796 797 unsigned ExtraInfo = 0; 798 if (IA.hasSideEffects()) 799 ExtraInfo |= InlineAsm::Extra_HasSideEffects; 800 if (IA.getDialect() == InlineAsm::AD_Intel) 801 ExtraInfo |= InlineAsm::Extra_AsmDialect; 802 803 MIRBuilder.buildInstr(TargetOpcode::INLINEASM) 804 .addExternalSymbol(IA.getAsmString().c_str()) 805 .addImm(ExtraInfo); 806 807 return true; 808 } 809 810 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) { 811 const CallInst &CI = cast<CallInst>(U); 812 auto TII = MF->getTarget().getIntrinsicInfo(); 813 const Function *F = CI.getCalledFunction(); 814 815 // FIXME: support Windows dllimport function calls. 816 if (F && F->hasDLLImportStorageClass()) 817 return false; 818 819 if (CI.isInlineAsm()) 820 return translateInlineAsm(CI, MIRBuilder); 821 822 Intrinsic::ID ID = Intrinsic::not_intrinsic; 823 if (F && F->isIntrinsic()) { 824 ID = F->getIntrinsicID(); 825 if (TII && ID == Intrinsic::not_intrinsic) 826 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F)); 827 } 828 829 if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic) { 830 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI); 831 SmallVector<unsigned, 8> Args; 832 for (auto &Arg: CI.arg_operands()) 833 Args.push_back(getOrCreateVReg(*Arg)); 834 835 MF->getFrameInfo().setHasCalls(true); 836 return CLI->lowerCall(MIRBuilder, &CI, Res, Args, [&]() { 837 return getOrCreateVReg(*CI.getCalledValue()); 838 }); 839 } 840 841 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic"); 842 843 if (translateKnownIntrinsic(CI, ID, MIRBuilder)) 844 return true; 845 846 unsigned Res = CI.getType()->isVoidTy() ? 0 : getOrCreateVReg(CI); 847 MachineInstrBuilder MIB = 848 MIRBuilder.buildIntrinsic(ID, Res, !CI.doesNotAccessMemory()); 849 850 for (auto &Arg : CI.arg_operands()) { 851 // Some intrinsics take metadata parameters. Reject them. 852 if (isa<MetadataAsValue>(Arg)) 853 return false; 854 MIB.addUse(getOrCreateVReg(*Arg)); 855 } 856 857 // Add a MachineMemOperand if it is a target mem intrinsic. 858 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering(); 859 TargetLowering::IntrinsicInfo Info; 860 // TODO: Add a GlobalISel version of getTgtMemIntrinsic. 861 if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) { 862 uint64_t Size = Info.memVT.getStoreSize(); 863 MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal), 864 Info.flags, Size, Info.align)); 865 } 866 867 return true; 868 } 869 870 bool IRTranslator::translateInvoke(const User &U, 871 MachineIRBuilder &MIRBuilder) { 872 const InvokeInst &I = cast<InvokeInst>(U); 873 MCContext &Context = MF->getContext(); 874 875 const BasicBlock *ReturnBB = I.getSuccessor(0); 876 const BasicBlock *EHPadBB = I.getSuccessor(1); 877 878 const Value *Callee = I.getCalledValue(); 879 const Function *Fn = dyn_cast<Function>(Callee); 880 if (isa<InlineAsm>(Callee)) 881 return false; 882 883 // FIXME: support invoking patchpoint and statepoint intrinsics. 884 if (Fn && Fn->isIntrinsic()) 885 return false; 886 887 // FIXME: support whatever these are. 888 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 889 return false; 890 891 // FIXME: support Windows exception handling. 892 if (!isa<LandingPadInst>(EHPadBB->front())) 893 return false; 894 895 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about 896 // the region covered by the try. 897 MCSymbol *BeginSymbol = Context.createTempSymbol(); 898 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol); 899 900 unsigned Res = I.getType()->isVoidTy() ? 0 : getOrCreateVReg(I); 901 SmallVector<unsigned, 8> Args; 902 for (auto &Arg: I.arg_operands()) 903 Args.push_back(getOrCreateVReg(*Arg)); 904 905 if (!CLI->lowerCall(MIRBuilder, &I, Res, Args, 906 [&]() { return getOrCreateVReg(*I.getCalledValue()); })) 907 return false; 908 909 MCSymbol *EndSymbol = Context.createTempSymbol(); 910 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol); 911 912 // FIXME: track probabilities. 913 MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB), 914 &ReturnMBB = getMBB(*ReturnBB); 915 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol); 916 MIRBuilder.getMBB().addSuccessor(&ReturnMBB); 917 MIRBuilder.getMBB().addSuccessor(&EHPadMBB); 918 MIRBuilder.buildBr(ReturnMBB); 919 920 return true; 921 } 922 923 bool IRTranslator::translateLandingPad(const User &U, 924 MachineIRBuilder &MIRBuilder) { 925 const LandingPadInst &LP = cast<LandingPadInst>(U); 926 927 MachineBasicBlock &MBB = MIRBuilder.getMBB(); 928 addLandingPadInfo(LP, MBB); 929 930 MBB.setIsEHPad(); 931 932 // If there aren't registers to copy the values into (e.g., during SjLj 933 // exceptions), then don't bother. 934 auto &TLI = *MF->getSubtarget().getTargetLowering(); 935 const Constant *PersonalityFn = MF->getFunction().getPersonalityFn(); 936 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 937 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 938 return true; 939 940 // If landingpad's return type is token type, we don't create DAG nodes 941 // for its exception pointer and selector value. The extraction of exception 942 // pointer or selector value from token type landingpads is not currently 943 // supported. 944 if (LP.getType()->isTokenTy()) 945 return true; 946 947 // Add a label to mark the beginning of the landing pad. Deletion of the 948 // landing pad can thus be detected via the MachineModuleInfo. 949 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL) 950 .addSym(MF->addLandingPad(&MBB)); 951 952 LLT Ty = getLLTForType(*LP.getType(), *DL); 953 unsigned Undef = MRI->createGenericVirtualRegister(Ty); 954 MIRBuilder.buildUndef(Undef); 955 956 SmallVector<LLT, 2> Tys; 957 for (Type *Ty : cast<StructType>(LP.getType())->elements()) 958 Tys.push_back(getLLTForType(*Ty, *DL)); 959 assert(Tys.size() == 2 && "Only two-valued landingpads are supported"); 960 961 // Mark exception register as live in. 962 unsigned ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn); 963 if (!ExceptionReg) 964 return false; 965 966 MBB.addLiveIn(ExceptionReg); 967 unsigned VReg = MRI->createGenericVirtualRegister(Tys[0]), 968 Tmp = MRI->createGenericVirtualRegister(Ty); 969 MIRBuilder.buildCopy(VReg, ExceptionReg); 970 MIRBuilder.buildInsert(Tmp, Undef, VReg, 0); 971 972 unsigned SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn); 973 if (!SelectorReg) 974 return false; 975 976 MBB.addLiveIn(SelectorReg); 977 978 // N.b. the exception selector register always has pointer type and may not 979 // match the actual IR-level type in the landingpad so an extra cast is 980 // needed. 981 unsigned PtrVReg = MRI->createGenericVirtualRegister(Tys[0]); 982 MIRBuilder.buildCopy(PtrVReg, SelectorReg); 983 984 VReg = MRI->createGenericVirtualRegister(Tys[1]); 985 MIRBuilder.buildInstr(TargetOpcode::G_PTRTOINT).addDef(VReg).addUse(PtrVReg); 986 MIRBuilder.buildInsert(getOrCreateVReg(LP), Tmp, VReg, 987 Tys[0].getSizeInBits()); 988 return true; 989 } 990 991 bool IRTranslator::translateAlloca(const User &U, 992 MachineIRBuilder &MIRBuilder) { 993 auto &AI = cast<AllocaInst>(U); 994 995 if (AI.isStaticAlloca()) { 996 unsigned Res = getOrCreateVReg(AI); 997 int FI = getOrCreateFrameIndex(AI); 998 MIRBuilder.buildFrameIndex(Res, FI); 999 return true; 1000 } 1001 1002 // Now we're in the harder dynamic case. 1003 Type *Ty = AI.getAllocatedType(); 1004 unsigned Align = 1005 std::max((unsigned)DL->getPrefTypeAlignment(Ty), AI.getAlignment()); 1006 1007 unsigned NumElts = getOrCreateVReg(*AI.getArraySize()); 1008 1009 Type *IntPtrIRTy = DL->getIntPtrType(AI.getType()); 1010 LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL); 1011 if (MRI->getType(NumElts) != IntPtrTy) { 1012 unsigned ExtElts = MRI->createGenericVirtualRegister(IntPtrTy); 1013 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts); 1014 NumElts = ExtElts; 1015 } 1016 1017 unsigned AllocSize = MRI->createGenericVirtualRegister(IntPtrTy); 1018 unsigned TySize = 1019 getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, -DL->getTypeAllocSize(Ty))); 1020 MIRBuilder.buildMul(AllocSize, NumElts, TySize); 1021 1022 LLT PtrTy = getLLTForType(*AI.getType(), *DL); 1023 auto &TLI = *MF->getSubtarget().getTargetLowering(); 1024 unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore(); 1025 1026 unsigned SPTmp = MRI->createGenericVirtualRegister(PtrTy); 1027 MIRBuilder.buildCopy(SPTmp, SPReg); 1028 1029 unsigned AllocTmp = MRI->createGenericVirtualRegister(PtrTy); 1030 MIRBuilder.buildGEP(AllocTmp, SPTmp, AllocSize); 1031 1032 // Handle alignment. We have to realign if the allocation granule was smaller 1033 // than stack alignment, or the specific alloca requires more than stack 1034 // alignment. 1035 unsigned StackAlign = 1036 MF->getSubtarget().getFrameLowering()->getStackAlignment(); 1037 Align = std::max(Align, StackAlign); 1038 if (Align > StackAlign || DL->getTypeAllocSize(Ty) % StackAlign != 0) { 1039 // Round the size of the allocation up to the stack alignment size 1040 // by add SA-1 to the size. This doesn't overflow because we're computing 1041 // an address inside an alloca. 1042 unsigned AlignedAlloc = MRI->createGenericVirtualRegister(PtrTy); 1043 MIRBuilder.buildPtrMask(AlignedAlloc, AllocTmp, Log2_32(Align)); 1044 AllocTmp = AlignedAlloc; 1045 } 1046 1047 MIRBuilder.buildCopy(SPReg, AllocTmp); 1048 MIRBuilder.buildCopy(getOrCreateVReg(AI), AllocTmp); 1049 1050 MF->getFrameInfo().CreateVariableSizedObject(Align ? Align : 1, &AI); 1051 assert(MF->getFrameInfo().hasVarSizedObjects()); 1052 return true; 1053 } 1054 1055 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) { 1056 // FIXME: We may need more info about the type. Because of how LLT works, 1057 // we're completely discarding the i64/double distinction here (amongst 1058 // others). Fortunately the ABIs I know of where that matters don't use va_arg 1059 // anyway but that's not guaranteed. 1060 MIRBuilder.buildInstr(TargetOpcode::G_VAARG) 1061 .addDef(getOrCreateVReg(U)) 1062 .addUse(getOrCreateVReg(*U.getOperand(0))) 1063 .addImm(DL->getABITypeAlignment(U.getType())); 1064 return true; 1065 } 1066 1067 bool IRTranslator::translateInsertElement(const User &U, 1068 MachineIRBuilder &MIRBuilder) { 1069 // If it is a <1 x Ty> vector, use the scalar as it is 1070 // not a legal vector type in LLT. 1071 if (U.getType()->getVectorNumElements() == 1) { 1072 unsigned Elt = getOrCreateVReg(*U.getOperand(1)); 1073 ValToVReg[&U] = Elt; 1074 return true; 1075 } 1076 unsigned Res = getOrCreateVReg(U); 1077 unsigned Val = getOrCreateVReg(*U.getOperand(0)); 1078 unsigned Elt = getOrCreateVReg(*U.getOperand(1)); 1079 unsigned Idx = getOrCreateVReg(*U.getOperand(2)); 1080 MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx); 1081 return true; 1082 } 1083 1084 bool IRTranslator::translateExtractElement(const User &U, 1085 MachineIRBuilder &MIRBuilder) { 1086 // If it is a <1 x Ty> vector, use the scalar as it is 1087 // not a legal vector type in LLT. 1088 if (U.getOperand(0)->getType()->getVectorNumElements() == 1) { 1089 unsigned Elt = getOrCreateVReg(*U.getOperand(0)); 1090 ValToVReg[&U] = Elt; 1091 return true; 1092 } 1093 unsigned Res = getOrCreateVReg(U); 1094 unsigned Val = getOrCreateVReg(*U.getOperand(0)); 1095 unsigned Idx = getOrCreateVReg(*U.getOperand(1)); 1096 MIRBuilder.buildExtractVectorElement(Res, Val, Idx); 1097 return true; 1098 } 1099 1100 bool IRTranslator::translateShuffleVector(const User &U, 1101 MachineIRBuilder &MIRBuilder) { 1102 MIRBuilder.buildInstr(TargetOpcode::G_SHUFFLE_VECTOR) 1103 .addDef(getOrCreateVReg(U)) 1104 .addUse(getOrCreateVReg(*U.getOperand(0))) 1105 .addUse(getOrCreateVReg(*U.getOperand(1))) 1106 .addUse(getOrCreateVReg(*U.getOperand(2))); 1107 return true; 1108 } 1109 1110 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) { 1111 const PHINode &PI = cast<PHINode>(U); 1112 auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI); 1113 MIB.addDef(getOrCreateVReg(PI)); 1114 1115 PendingPHIs.emplace_back(&PI, MIB.getInstr()); 1116 return true; 1117 } 1118 1119 void IRTranslator::finishPendingPhis() { 1120 for (std::pair<const PHINode *, MachineInstr *> &Phi : PendingPHIs) { 1121 const PHINode *PI = Phi.first; 1122 MachineInstrBuilder MIB(*MF, Phi.second); 1123 1124 // All MachineBasicBlocks exist, add them to the PHI. We assume IRTranslator 1125 // won't create extra control flow here, otherwise we need to find the 1126 // dominating predecessor here (or perhaps force the weirder IRTranslators 1127 // to provide a simple boundary). 1128 SmallSet<const BasicBlock *, 4> HandledPreds; 1129 1130 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) { 1131 auto IRPred = PI->getIncomingBlock(i); 1132 if (HandledPreds.count(IRPred)) 1133 continue; 1134 1135 HandledPreds.insert(IRPred); 1136 unsigned ValReg = getOrCreateVReg(*PI->getIncomingValue(i)); 1137 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) { 1138 assert(Pred->isSuccessor(MIB->getParent()) && 1139 "incorrect CFG at MachineBasicBlock level"); 1140 MIB.addUse(ValReg); 1141 MIB.addMBB(Pred); 1142 } 1143 } 1144 } 1145 } 1146 1147 bool IRTranslator::translate(const Instruction &Inst) { 1148 CurBuilder.setDebugLoc(Inst.getDebugLoc()); 1149 switch(Inst.getOpcode()) { 1150 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1151 case Instruction::OPCODE: return translate##OPCODE(Inst, CurBuilder); 1152 #include "llvm/IR/Instruction.def" 1153 default: 1154 return false; 1155 } 1156 } 1157 1158 bool IRTranslator::translate(const Constant &C, unsigned Reg) { 1159 if (auto CI = dyn_cast<ConstantInt>(&C)) 1160 EntryBuilder.buildConstant(Reg, *CI); 1161 else if (auto CF = dyn_cast<ConstantFP>(&C)) 1162 EntryBuilder.buildFConstant(Reg, *CF); 1163 else if (isa<UndefValue>(C)) 1164 EntryBuilder.buildUndef(Reg); 1165 else if (isa<ConstantPointerNull>(C)) 1166 EntryBuilder.buildConstant(Reg, 0); 1167 else if (auto GV = dyn_cast<GlobalValue>(&C)) 1168 EntryBuilder.buildGlobalValue(Reg, GV); 1169 else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) { 1170 if (!CAZ->getType()->isVectorTy()) 1171 return false; 1172 // Return the scalar if it is a <1 x Ty> vector. 1173 if (CAZ->getNumElements() == 1) 1174 return translate(*CAZ->getElementValue(0u), Reg); 1175 std::vector<unsigned> Ops; 1176 for (unsigned i = 0; i < CAZ->getNumElements(); ++i) { 1177 Constant &Elt = *CAZ->getElementValue(i); 1178 Ops.push_back(getOrCreateVReg(Elt)); 1179 } 1180 EntryBuilder.buildMerge(Reg, Ops); 1181 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) { 1182 // Return the scalar if it is a <1 x Ty> vector. 1183 if (CV->getNumElements() == 1) 1184 return translate(*CV->getElementAsConstant(0), Reg); 1185 std::vector<unsigned> Ops; 1186 for (unsigned i = 0; i < CV->getNumElements(); ++i) { 1187 Constant &Elt = *CV->getElementAsConstant(i); 1188 Ops.push_back(getOrCreateVReg(Elt)); 1189 } 1190 EntryBuilder.buildMerge(Reg, Ops); 1191 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) { 1192 switch(CE->getOpcode()) { 1193 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 1194 case Instruction::OPCODE: return translate##OPCODE(*CE, EntryBuilder); 1195 #include "llvm/IR/Instruction.def" 1196 default: 1197 return false; 1198 } 1199 } else if (auto CS = dyn_cast<ConstantStruct>(&C)) { 1200 // Return the element if it is a single element ConstantStruct. 1201 if (CS->getNumOperands() == 1) { 1202 unsigned EltReg = getOrCreateVReg(*CS->getOperand(0)); 1203 EntryBuilder.buildCast(Reg, EltReg); 1204 return true; 1205 } 1206 SmallVector<unsigned, 4> Ops; 1207 SmallVector<uint64_t, 4> Indices; 1208 uint64_t Offset = 0; 1209 for (unsigned i = 0; i < CS->getNumOperands(); ++i) { 1210 unsigned OpReg = getOrCreateVReg(*CS->getOperand(i)); 1211 Ops.push_back(OpReg); 1212 Indices.push_back(Offset); 1213 Offset += MRI->getType(OpReg).getSizeInBits(); 1214 } 1215 EntryBuilder.buildSequence(Reg, Ops, Indices); 1216 } else if (auto CV = dyn_cast<ConstantVector>(&C)) { 1217 if (CV->getNumOperands() == 1) 1218 return translate(*CV->getOperand(0), Reg); 1219 SmallVector<unsigned, 4> Ops; 1220 for (unsigned i = 0; i < CV->getNumOperands(); ++i) { 1221 Ops.push_back(getOrCreateVReg(*CV->getOperand(i))); 1222 } 1223 EntryBuilder.buildMerge(Reg, Ops); 1224 } else 1225 return false; 1226 1227 return true; 1228 } 1229 1230 void IRTranslator::finalizeFunction() { 1231 // Release the memory used by the different maps we 1232 // needed during the translation. 1233 PendingPHIs.clear(); 1234 ValToVReg.clear(); 1235 FrameIndices.clear(); 1236 MachinePreds.clear(); 1237 // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it 1238 // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid 1239 // destroying it twice (in ~IRTranslator() and ~LLVMContext()) 1240 EntryBuilder = MachineIRBuilder(); 1241 CurBuilder = MachineIRBuilder(); 1242 } 1243 1244 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) { 1245 MF = &CurMF; 1246 const Function &F = MF->getFunction(); 1247 if (F.empty()) 1248 return false; 1249 CLI = MF->getSubtarget().getCallLowering(); 1250 CurBuilder.setMF(*MF); 1251 EntryBuilder.setMF(*MF); 1252 MRI = &MF->getRegInfo(); 1253 DL = &F.getParent()->getDataLayout(); 1254 TPC = &getAnalysis<TargetPassConfig>(); 1255 ORE = llvm::make_unique<OptimizationRemarkEmitter>(&F); 1256 1257 assert(PendingPHIs.empty() && "stale PHIs"); 1258 1259 if (!DL->isLittleEndian()) { 1260 // Currently we don't properly handle big endian code. 1261 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 1262 F.getSubprogram(), &F.getEntryBlock()); 1263 R << "unable to translate in big endian mode"; 1264 reportTranslationError(*MF, *TPC, *ORE, R); 1265 } 1266 1267 // Release the per-function state when we return, whether we succeeded or not. 1268 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); }); 1269 1270 // Setup a separate basic-block for the arguments and constants 1271 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock(); 1272 MF->push_back(EntryBB); 1273 EntryBuilder.setMBB(*EntryBB); 1274 1275 // Create all blocks, in IR order, to preserve the layout. 1276 for (const BasicBlock &BB: F) { 1277 auto *&MBB = BBToMBB[&BB]; 1278 1279 MBB = MF->CreateMachineBasicBlock(&BB); 1280 MF->push_back(MBB); 1281 1282 if (BB.hasAddressTaken()) 1283 MBB->setHasAddressTaken(); 1284 } 1285 1286 // Make our arguments/constants entry block fallthrough to the IR entry block. 1287 EntryBB->addSuccessor(&getMBB(F.front())); 1288 1289 // Lower the actual args into this basic block. 1290 SmallVector<unsigned, 8> VRegArgs; 1291 for (const Argument &Arg: F.args()) { 1292 if (DL->getTypeStoreSize(Arg.getType()) == 0) 1293 continue; // Don't handle zero sized types. 1294 VRegArgs.push_back(getOrCreateVReg(Arg)); 1295 } 1296 if (!CLI->lowerFormalArguments(EntryBuilder, F, VRegArgs)) { 1297 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 1298 F.getSubprogram(), &F.getEntryBlock()); 1299 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType()); 1300 reportTranslationError(*MF, *TPC, *ORE, R); 1301 return false; 1302 } 1303 1304 // And translate the function! 1305 for (const BasicBlock &BB: F) { 1306 MachineBasicBlock &MBB = getMBB(BB); 1307 // Set the insertion point of all the following translations to 1308 // the end of this basic block. 1309 CurBuilder.setMBB(MBB); 1310 1311 for (const Instruction &Inst: BB) { 1312 if (translate(Inst)) 1313 continue; 1314 1315 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 1316 Inst.getDebugLoc(), &BB); 1317 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst); 1318 1319 if (ORE->allowExtraAnalysis("gisel-irtranslator")) { 1320 std::string InstStrStorage; 1321 raw_string_ostream InstStr(InstStrStorage); 1322 InstStr << Inst; 1323 1324 R << ": '" << InstStr.str() << "'"; 1325 } 1326 1327 reportTranslationError(*MF, *TPC, *ORE, R); 1328 return false; 1329 } 1330 } 1331 1332 finishPendingPhis(); 1333 1334 // Merge the argument lowering and constants block with its single 1335 // successor, the LLVM-IR entry block. We want the basic block to 1336 // be maximal. 1337 assert(EntryBB->succ_size() == 1 && 1338 "Custom BB used for lowering should have only one successor"); 1339 // Get the successor of the current entry block. 1340 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin(); 1341 assert(NewEntryBB.pred_size() == 1 && 1342 "LLVM-IR entry block has a predecessor!?"); 1343 // Move all the instruction from the current entry block to the 1344 // new entry block. 1345 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(), 1346 EntryBB->end()); 1347 1348 // Update the live-in information for the new entry block. 1349 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins()) 1350 NewEntryBB.addLiveIn(LiveIn); 1351 NewEntryBB.sortUniqueLiveIns(); 1352 1353 // Get rid of the now empty basic block. 1354 EntryBB->removeSuccessor(&NewEntryBB); 1355 MF->remove(EntryBB); 1356 MF->DeleteMachineBasicBlock(EntryBB); 1357 1358 assert(&MF->front() == &NewEntryBB && 1359 "New entry wasn't next in the list of basic block!"); 1360 1361 return false; 1362 } 1363