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