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