1 //===- llvm/CodeGen/GlobalISel/IRTranslator.cpp - IRTranslator ---*- C++ -*-==// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// \file 9 /// This file implements the IRTranslator class. 10 //===----------------------------------------------------------------------===// 11 12 #include "llvm/CodeGen/GlobalISel/IRTranslator.h" 13 #include "llvm/ADT/PostOrderIterator.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/BranchProbabilityInfo.h" 19 #include "llvm/Analysis/Loads.h" 20 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 21 #include "llvm/Analysis/ValueTracking.h" 22 #include "llvm/CodeGen/Analysis.h" 23 #include "llvm/CodeGen/GlobalISel/CallLowering.h" 24 #include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h" 25 #include "llvm/CodeGen/GlobalISel/InlineAsmLowering.h" 26 #include "llvm/CodeGen/LowLevelType.h" 27 #include "llvm/CodeGen/MachineBasicBlock.h" 28 #include "llvm/CodeGen/MachineFrameInfo.h" 29 #include "llvm/CodeGen/MachineFunction.h" 30 #include "llvm/CodeGen/MachineInstrBuilder.h" 31 #include "llvm/CodeGen/MachineMemOperand.h" 32 #include "llvm/CodeGen/MachineOperand.h" 33 #include "llvm/CodeGen/MachineRegisterInfo.h" 34 #include "llvm/CodeGen/StackProtector.h" 35 #include "llvm/CodeGen/TargetFrameLowering.h" 36 #include "llvm/CodeGen/TargetInstrInfo.h" 37 #include "llvm/CodeGen/TargetLowering.h" 38 #include "llvm/CodeGen/TargetPassConfig.h" 39 #include "llvm/CodeGen/TargetRegisterInfo.h" 40 #include "llvm/CodeGen/TargetSubtargetInfo.h" 41 #include "llvm/IR/BasicBlock.h" 42 #include "llvm/IR/CFG.h" 43 #include "llvm/IR/Constant.h" 44 #include "llvm/IR/Constants.h" 45 #include "llvm/IR/DataLayout.h" 46 #include "llvm/IR/DebugInfo.h" 47 #include "llvm/IR/DerivedTypes.h" 48 #include "llvm/IR/Function.h" 49 #include "llvm/IR/GetElementPtrTypeIterator.h" 50 #include "llvm/IR/InlineAsm.h" 51 #include "llvm/IR/Instructions.h" 52 #include "llvm/IR/IntrinsicInst.h" 53 #include "llvm/IR/Intrinsics.h" 54 #include "llvm/IR/LLVMContext.h" 55 #include "llvm/IR/Metadata.h" 56 #include "llvm/IR/Type.h" 57 #include "llvm/IR/User.h" 58 #include "llvm/IR/Value.h" 59 #include "llvm/InitializePasses.h" 60 #include "llvm/MC/MCContext.h" 61 #include "llvm/Pass.h" 62 #include "llvm/Support/Casting.h" 63 #include "llvm/Support/CodeGen.h" 64 #include "llvm/Support/Debug.h" 65 #include "llvm/Support/ErrorHandling.h" 66 #include "llvm/Support/LowLevelTypeImpl.h" 67 #include "llvm/Support/MathExtras.h" 68 #include "llvm/Support/raw_ostream.h" 69 #include "llvm/Target/TargetIntrinsicInfo.h" 70 #include "llvm/Target/TargetMachine.h" 71 #include <algorithm> 72 #include <cassert> 73 #include <cstdint> 74 #include <iterator> 75 #include <string> 76 #include <utility> 77 #include <vector> 78 79 #define DEBUG_TYPE "irtranslator" 80 81 using namespace llvm; 82 83 static cl::opt<bool> 84 EnableCSEInIRTranslator("enable-cse-in-irtranslator", 85 cl::desc("Should enable CSE in irtranslator"), 86 cl::Optional, cl::init(false)); 87 char IRTranslator::ID = 0; 88 89 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI", 90 false, false) 91 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) 92 INITIALIZE_PASS_DEPENDENCY(GISelCSEAnalysisWrapperPass) 93 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI", 94 false, false) 95 96 static void reportTranslationError(MachineFunction &MF, 97 const TargetPassConfig &TPC, 98 OptimizationRemarkEmitter &ORE, 99 OptimizationRemarkMissed &R) { 100 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel); 101 102 // Print the function name explicitly if we don't have a debug location (which 103 // makes the diagnostic less useful) or if we're going to emit a raw error. 104 if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled()) 105 R << (" (in function: " + MF.getName() + ")").str(); 106 107 if (TPC.isGlobalISelAbortEnabled()) 108 report_fatal_error(R.getMsg()); 109 else 110 ORE.emit(R); 111 } 112 113 IRTranslator::IRTranslator() : MachineFunctionPass(ID) { } 114 115 #ifndef NDEBUG 116 namespace { 117 /// Verify that every instruction created has the same DILocation as the 118 /// instruction being translated. 119 class DILocationVerifier : public GISelChangeObserver { 120 const Instruction *CurrInst = nullptr; 121 122 public: 123 DILocationVerifier() = default; 124 ~DILocationVerifier() = default; 125 126 const Instruction *getCurrentInst() const { return CurrInst; } 127 void setCurrentInst(const Instruction *Inst) { CurrInst = Inst; } 128 129 void erasingInstr(MachineInstr &MI) override {} 130 void changingInstr(MachineInstr &MI) override {} 131 void changedInstr(MachineInstr &MI) override {} 132 133 void createdInstr(MachineInstr &MI) override { 134 assert(getCurrentInst() && "Inserted instruction without a current MI"); 135 136 // Only print the check message if we're actually checking it. 137 #ifndef NDEBUG 138 LLVM_DEBUG(dbgs() << "Checking DILocation from " << *CurrInst 139 << " was copied to " << MI); 140 #endif 141 // We allow insts in the entry block to have a debug loc line of 0 because 142 // they could have originated from constants, and we don't want a jumpy 143 // debug experience. 144 assert((CurrInst->getDebugLoc() == MI.getDebugLoc() || 145 MI.getDebugLoc().getLine() == 0) && 146 "Line info was not transferred to all instructions"); 147 } 148 }; 149 } // namespace 150 #endif // ifndef NDEBUG 151 152 153 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const { 154 AU.addRequired<StackProtector>(); 155 AU.addRequired<TargetPassConfig>(); 156 AU.addRequired<GISelCSEAnalysisWrapperPass>(); 157 getSelectionDAGFallbackAnalysisUsage(AU); 158 MachineFunctionPass::getAnalysisUsage(AU); 159 } 160 161 IRTranslator::ValueToVRegInfo::VRegListT & 162 IRTranslator::allocateVRegs(const Value &Val) { 163 assert(!VMap.contains(Val) && "Value already allocated in VMap"); 164 auto *Regs = VMap.getVRegs(Val); 165 auto *Offsets = VMap.getOffsets(Val); 166 SmallVector<LLT, 4> SplitTys; 167 computeValueLLTs(*DL, *Val.getType(), SplitTys, 168 Offsets->empty() ? Offsets : nullptr); 169 for (unsigned i = 0; i < SplitTys.size(); ++i) 170 Regs->push_back(0); 171 return *Regs; 172 } 173 174 ArrayRef<Register> IRTranslator::getOrCreateVRegs(const Value &Val) { 175 auto VRegsIt = VMap.findVRegs(Val); 176 if (VRegsIt != VMap.vregs_end()) 177 return *VRegsIt->second; 178 179 if (Val.getType()->isVoidTy()) 180 return *VMap.getVRegs(Val); 181 182 // Create entry for this type. 183 auto *VRegs = VMap.getVRegs(Val); 184 auto *Offsets = VMap.getOffsets(Val); 185 186 assert(Val.getType()->isSized() && 187 "Don't know how to create an empty vreg"); 188 189 SmallVector<LLT, 4> SplitTys; 190 computeValueLLTs(*DL, *Val.getType(), SplitTys, 191 Offsets->empty() ? Offsets : nullptr); 192 193 if (!isa<Constant>(Val)) { 194 for (auto Ty : SplitTys) 195 VRegs->push_back(MRI->createGenericVirtualRegister(Ty)); 196 return *VRegs; 197 } 198 199 if (Val.getType()->isAggregateType()) { 200 // UndefValue, ConstantAggregateZero 201 auto &C = cast<Constant>(Val); 202 unsigned Idx = 0; 203 while (auto Elt = C.getAggregateElement(Idx++)) { 204 auto EltRegs = getOrCreateVRegs(*Elt); 205 llvm::copy(EltRegs, std::back_inserter(*VRegs)); 206 } 207 } else { 208 assert(SplitTys.size() == 1 && "unexpectedly split LLT"); 209 VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0])); 210 bool Success = translate(cast<Constant>(Val), VRegs->front()); 211 if (!Success) { 212 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 213 MF->getFunction().getSubprogram(), 214 &MF->getFunction().getEntryBlock()); 215 R << "unable to translate constant: " << ore::NV("Type", Val.getType()); 216 reportTranslationError(*MF, *TPC, *ORE, R); 217 return *VRegs; 218 } 219 } 220 221 return *VRegs; 222 } 223 224 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) { 225 if (FrameIndices.find(&AI) != FrameIndices.end()) 226 return FrameIndices[&AI]; 227 228 uint64_t ElementSize = DL->getTypeAllocSize(AI.getAllocatedType()); 229 uint64_t Size = 230 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue(); 231 232 // Always allocate at least one byte. 233 Size = std::max<uint64_t>(Size, 1u); 234 235 int &FI = FrameIndices[&AI]; 236 FI = MF->getFrameInfo().CreateStackObject(Size, AI.getAlign(), false, &AI); 237 return FI; 238 } 239 240 Align IRTranslator::getMemOpAlign(const Instruction &I) { 241 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) 242 return SI->getAlign(); 243 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) { 244 return LI->getAlign(); 245 } 246 if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) { 247 // TODO(PR27168): This instruction has no alignment attribute, but unlike 248 // the default alignment for load/store, the default here is to assume 249 // it has NATURAL alignment, not DataLayout-specified alignment. 250 const DataLayout &DL = AI->getModule()->getDataLayout(); 251 return Align(DL.getTypeStoreSize(AI->getCompareOperand()->getType())); 252 } 253 if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) { 254 // TODO(PR27168): This instruction has no alignment attribute, but unlike 255 // the default alignment for load/store, the default here is to assume 256 // it has NATURAL alignment, not DataLayout-specified alignment. 257 const DataLayout &DL = AI->getModule()->getDataLayout(); 258 return Align(DL.getTypeStoreSize(AI->getValOperand()->getType())); 259 } 260 OptimizationRemarkMissed R("gisel-irtranslator", "", &I); 261 R << "unable to translate memop: " << ore::NV("Opcode", &I); 262 reportTranslationError(*MF, *TPC, *ORE, R); 263 return Align(1); 264 } 265 266 MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) { 267 MachineBasicBlock *&MBB = BBToMBB[&BB]; 268 assert(MBB && "BasicBlock was not encountered before"); 269 return *MBB; 270 } 271 272 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) { 273 assert(NewPred && "new predecessor must be a real MachineBasicBlock"); 274 MachinePreds[Edge].push_back(NewPred); 275 } 276 277 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U, 278 MachineIRBuilder &MIRBuilder) { 279 // Get or create a virtual register for each value. 280 // Unless the value is a Constant => loadimm cst? 281 // or inline constant each time? 282 // Creation of a virtual register needs to have a size. 283 Register Op0 = getOrCreateVReg(*U.getOperand(0)); 284 Register Op1 = getOrCreateVReg(*U.getOperand(1)); 285 Register Res = getOrCreateVReg(U); 286 uint16_t Flags = 0; 287 if (isa<Instruction>(U)) { 288 const Instruction &I = cast<Instruction>(U); 289 Flags = MachineInstr::copyFlagsFromInstruction(I); 290 } 291 292 MIRBuilder.buildInstr(Opcode, {Res}, {Op0, Op1}, Flags); 293 return true; 294 } 295 296 bool IRTranslator::translateFSub(const User &U, MachineIRBuilder &MIRBuilder) { 297 // -0.0 - X --> G_FNEG 298 if (isa<Constant>(U.getOperand(0)) && 299 U.getOperand(0) == ConstantFP::getZeroValueForNegation(U.getType())) { 300 Register Op1 = getOrCreateVReg(*U.getOperand(1)); 301 Register Res = getOrCreateVReg(U); 302 uint16_t Flags = 0; 303 if (isa<Instruction>(U)) { 304 const Instruction &I = cast<Instruction>(U); 305 Flags = MachineInstr::copyFlagsFromInstruction(I); 306 } 307 // Negate the last operand of the FSUB 308 MIRBuilder.buildFNeg(Res, Op1, Flags); 309 return true; 310 } 311 return translateBinaryOp(TargetOpcode::G_FSUB, U, MIRBuilder); 312 } 313 314 bool IRTranslator::translateFNeg(const User &U, MachineIRBuilder &MIRBuilder) { 315 Register Op0 = getOrCreateVReg(*U.getOperand(0)); 316 Register Res = getOrCreateVReg(U); 317 uint16_t Flags = 0; 318 if (isa<Instruction>(U)) { 319 const Instruction &I = cast<Instruction>(U); 320 Flags = MachineInstr::copyFlagsFromInstruction(I); 321 } 322 MIRBuilder.buildFNeg(Res, Op0, Flags); 323 return true; 324 } 325 326 bool IRTranslator::translateCompare(const User &U, 327 MachineIRBuilder &MIRBuilder) { 328 auto *CI = dyn_cast<CmpInst>(&U); 329 Register Op0 = getOrCreateVReg(*U.getOperand(0)); 330 Register Op1 = getOrCreateVReg(*U.getOperand(1)); 331 Register Res = getOrCreateVReg(U); 332 CmpInst::Predicate Pred = 333 CI ? CI->getPredicate() : static_cast<CmpInst::Predicate>( 334 cast<ConstantExpr>(U).getPredicate()); 335 if (CmpInst::isIntPredicate(Pred)) 336 MIRBuilder.buildICmp(Pred, Res, Op0, Op1); 337 else if (Pred == CmpInst::FCMP_FALSE) 338 MIRBuilder.buildCopy( 339 Res, getOrCreateVReg(*Constant::getNullValue(U.getType()))); 340 else if (Pred == CmpInst::FCMP_TRUE) 341 MIRBuilder.buildCopy( 342 Res, getOrCreateVReg(*Constant::getAllOnesValue(U.getType()))); 343 else { 344 assert(CI && "Instruction should be CmpInst"); 345 MIRBuilder.buildFCmp(Pred, Res, Op0, Op1, 346 MachineInstr::copyFlagsFromInstruction(*CI)); 347 } 348 349 return true; 350 } 351 352 bool IRTranslator::translateRet(const User &U, MachineIRBuilder &MIRBuilder) { 353 const ReturnInst &RI = cast<ReturnInst>(U); 354 const Value *Ret = RI.getReturnValue(); 355 if (Ret && DL->getTypeStoreSize(Ret->getType()) == 0) 356 Ret = nullptr; 357 358 ArrayRef<Register> VRegs; 359 if (Ret) 360 VRegs = getOrCreateVRegs(*Ret); 361 362 Register SwiftErrorVReg = 0; 363 if (CLI->supportSwiftError() && SwiftError.getFunctionArg()) { 364 SwiftErrorVReg = SwiftError.getOrCreateVRegUseAt( 365 &RI, &MIRBuilder.getMBB(), SwiftError.getFunctionArg()); 366 } 367 368 // The target may mess up with the insertion point, but 369 // this is not important as a return is the last instruction 370 // of the block anyway. 371 return CLI->lowerReturn(MIRBuilder, Ret, VRegs, SwiftErrorVReg); 372 } 373 374 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) { 375 const BranchInst &BrInst = cast<BranchInst>(U); 376 unsigned Succ = 0; 377 if (!BrInst.isUnconditional()) { 378 // We want a G_BRCOND to the true BB followed by an unconditional branch. 379 Register Tst = getOrCreateVReg(*BrInst.getCondition()); 380 const BasicBlock &TrueTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ++)); 381 MachineBasicBlock &TrueBB = getMBB(TrueTgt); 382 MIRBuilder.buildBrCond(Tst, TrueBB); 383 } 384 385 const BasicBlock &BrTgt = *cast<BasicBlock>(BrInst.getSuccessor(Succ)); 386 MachineBasicBlock &TgtBB = getMBB(BrTgt); 387 MachineBasicBlock &CurBB = MIRBuilder.getMBB(); 388 389 // If the unconditional target is the layout successor, fallthrough. 390 if (!CurBB.isLayoutSuccessor(&TgtBB)) 391 MIRBuilder.buildBr(TgtBB); 392 393 // Link successors. 394 for (const BasicBlock *Succ : successors(&BrInst)) 395 CurBB.addSuccessor(&getMBB(*Succ)); 396 return true; 397 } 398 399 void IRTranslator::addSuccessorWithProb(MachineBasicBlock *Src, 400 MachineBasicBlock *Dst, 401 BranchProbability Prob) { 402 if (!FuncInfo.BPI) { 403 Src->addSuccessorWithoutProb(Dst); 404 return; 405 } 406 if (Prob.isUnknown()) 407 Prob = getEdgeProbability(Src, Dst); 408 Src->addSuccessor(Dst, Prob); 409 } 410 411 BranchProbability 412 IRTranslator::getEdgeProbability(const MachineBasicBlock *Src, 413 const MachineBasicBlock *Dst) const { 414 const BasicBlock *SrcBB = Src->getBasicBlock(); 415 const BasicBlock *DstBB = Dst->getBasicBlock(); 416 if (!FuncInfo.BPI) { 417 // If BPI is not available, set the default probability as 1 / N, where N is 418 // the number of successors. 419 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 420 return BranchProbability(1, SuccSize); 421 } 422 return FuncInfo.BPI->getEdgeProbability(SrcBB, DstBB); 423 } 424 425 bool IRTranslator::translateSwitch(const User &U, MachineIRBuilder &MIB) { 426 using namespace SwitchCG; 427 // Extract cases from the switch. 428 const SwitchInst &SI = cast<SwitchInst>(U); 429 BranchProbabilityInfo *BPI = FuncInfo.BPI; 430 CaseClusterVector Clusters; 431 Clusters.reserve(SI.getNumCases()); 432 for (auto &I : SI.cases()) { 433 MachineBasicBlock *Succ = &getMBB(*I.getCaseSuccessor()); 434 assert(Succ && "Could not find successor mbb in mapping"); 435 const ConstantInt *CaseVal = I.getCaseValue(); 436 BranchProbability Prob = 437 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 438 : BranchProbability(1, SI.getNumCases() + 1); 439 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 440 } 441 442 MachineBasicBlock *DefaultMBB = &getMBB(*SI.getDefaultDest()); 443 444 // Cluster adjacent cases with the same destination. We do this at all 445 // optimization levels because it's cheap to do and will make codegen faster 446 // if there are many clusters. 447 sortAndRangeify(Clusters); 448 449 MachineBasicBlock *SwitchMBB = &getMBB(*SI.getParent()); 450 451 // If there is only the default destination, jump there directly. 452 if (Clusters.empty()) { 453 SwitchMBB->addSuccessor(DefaultMBB); 454 if (DefaultMBB != SwitchMBB->getNextNode()) 455 MIB.buildBr(*DefaultMBB); 456 return true; 457 } 458 459 SL->findJumpTables(Clusters, &SI, DefaultMBB, nullptr, nullptr); 460 461 LLVM_DEBUG({ 462 dbgs() << "Case clusters: "; 463 for (const CaseCluster &C : Clusters) { 464 if (C.Kind == CC_JumpTable) 465 dbgs() << "JT:"; 466 if (C.Kind == CC_BitTests) 467 dbgs() << "BT:"; 468 469 C.Low->getValue().print(dbgs(), true); 470 if (C.Low != C.High) { 471 dbgs() << '-'; 472 C.High->getValue().print(dbgs(), true); 473 } 474 dbgs() << ' '; 475 } 476 dbgs() << '\n'; 477 }); 478 479 assert(!Clusters.empty()); 480 SwitchWorkList WorkList; 481 CaseClusterIt First = Clusters.begin(); 482 CaseClusterIt Last = Clusters.end() - 1; 483 auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB); 484 WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 485 486 // FIXME: At the moment we don't do any splitting optimizations here like 487 // SelectionDAG does, so this worklist only has one entry. 488 while (!WorkList.empty()) { 489 SwitchWorkListItem W = WorkList.back(); 490 WorkList.pop_back(); 491 if (!lowerSwitchWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB, MIB)) 492 return false; 493 } 494 return true; 495 } 496 497 void IRTranslator::emitJumpTable(SwitchCG::JumpTable &JT, 498 MachineBasicBlock *MBB) { 499 // Emit the code for the jump table 500 assert(JT.Reg != -1U && "Should lower JT Header first!"); 501 MachineIRBuilder MIB(*MBB->getParent()); 502 MIB.setMBB(*MBB); 503 MIB.setDebugLoc(CurBuilder->getDebugLoc()); 504 505 Type *PtrIRTy = Type::getInt8PtrTy(MF->getFunction().getContext()); 506 const LLT PtrTy = getLLTForType(*PtrIRTy, *DL); 507 508 auto Table = MIB.buildJumpTable(PtrTy, JT.JTI); 509 MIB.buildBrJT(Table.getReg(0), JT.JTI, JT.Reg); 510 } 511 512 bool IRTranslator::emitJumpTableHeader(SwitchCG::JumpTable &JT, 513 SwitchCG::JumpTableHeader &JTH, 514 MachineBasicBlock *HeaderBB) { 515 MachineIRBuilder MIB(*HeaderBB->getParent()); 516 MIB.setMBB(*HeaderBB); 517 MIB.setDebugLoc(CurBuilder->getDebugLoc()); 518 519 const Value &SValue = *JTH.SValue; 520 // Subtract the lowest switch case value from the value being switched on. 521 const LLT SwitchTy = getLLTForType(*SValue.getType(), *DL); 522 Register SwitchOpReg = getOrCreateVReg(SValue); 523 auto FirstCst = MIB.buildConstant(SwitchTy, JTH.First); 524 auto Sub = MIB.buildSub({SwitchTy}, SwitchOpReg, FirstCst); 525 526 // This value may be smaller or larger than the target's pointer type, and 527 // therefore require extension or truncating. 528 Type *PtrIRTy = SValue.getType()->getPointerTo(); 529 const LLT PtrScalarTy = LLT::scalar(DL->getTypeSizeInBits(PtrIRTy)); 530 Sub = MIB.buildZExtOrTrunc(PtrScalarTy, Sub); 531 532 JT.Reg = Sub.getReg(0); 533 534 if (JTH.OmitRangeCheck) { 535 if (JT.MBB != HeaderBB->getNextNode()) 536 MIB.buildBr(*JT.MBB); 537 return true; 538 } 539 540 // Emit the range check for the jump table, and branch to the default block 541 // for the switch statement if the value being switched on exceeds the 542 // largest case in the switch. 543 auto Cst = getOrCreateVReg( 544 *ConstantInt::get(SValue.getType(), JTH.Last - JTH.First)); 545 Cst = MIB.buildZExtOrTrunc(PtrScalarTy, Cst).getReg(0); 546 auto Cmp = MIB.buildICmp(CmpInst::ICMP_UGT, LLT::scalar(1), Sub, Cst); 547 548 auto BrCond = MIB.buildBrCond(Cmp.getReg(0), *JT.Default); 549 550 // Avoid emitting unnecessary branches to the next block. 551 if (JT.MBB != HeaderBB->getNextNode()) 552 BrCond = MIB.buildBr(*JT.MBB); 553 return true; 554 } 555 556 void IRTranslator::emitSwitchCase(SwitchCG::CaseBlock &CB, 557 MachineBasicBlock *SwitchBB, 558 MachineIRBuilder &MIB) { 559 Register CondLHS = getOrCreateVReg(*CB.CmpLHS); 560 Register Cond; 561 DebugLoc OldDbgLoc = MIB.getDebugLoc(); 562 MIB.setDebugLoc(CB.DbgLoc); 563 MIB.setMBB(*CB.ThisBB); 564 565 if (CB.PredInfo.NoCmp) { 566 // Branch or fall through to TrueBB. 567 addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb); 568 addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()}, 569 CB.ThisBB); 570 CB.ThisBB->normalizeSuccProbs(); 571 if (CB.TrueBB != CB.ThisBB->getNextNode()) 572 MIB.buildBr(*CB.TrueBB); 573 MIB.setDebugLoc(OldDbgLoc); 574 return; 575 } 576 577 const LLT i1Ty = LLT::scalar(1); 578 // Build the compare. 579 if (!CB.CmpMHS) { 580 Register CondRHS = getOrCreateVReg(*CB.CmpRHS); 581 Cond = MIB.buildICmp(CB.PredInfo.Pred, i1Ty, CondLHS, CondRHS).getReg(0); 582 } else { 583 assert(CB.PredInfo.Pred == CmpInst::ICMP_SLE && 584 "Can only handle SLE ranges"); 585 586 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 587 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 588 589 Register CmpOpReg = getOrCreateVReg(*CB.CmpMHS); 590 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 591 Register CondRHS = getOrCreateVReg(*CB.CmpRHS); 592 Cond = 593 MIB.buildICmp(CmpInst::ICMP_SLE, i1Ty, CmpOpReg, CondRHS).getReg(0); 594 } else { 595 const LLT CmpTy = MRI->getType(CmpOpReg); 596 auto Sub = MIB.buildSub({CmpTy}, CmpOpReg, CondLHS); 597 auto Diff = MIB.buildConstant(CmpTy, High - Low); 598 Cond = MIB.buildICmp(CmpInst::ICMP_ULE, i1Ty, Sub, Diff).getReg(0); 599 } 600 } 601 602 // Update successor info 603 addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb); 604 605 addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()}, 606 CB.ThisBB); 607 608 // TrueBB and FalseBB are always different unless the incoming IR is 609 // degenerate. This only happens when running llc on weird IR. 610 if (CB.TrueBB != CB.FalseBB) 611 addSuccessorWithProb(CB.ThisBB, CB.FalseBB, CB.FalseProb); 612 CB.ThisBB->normalizeSuccProbs(); 613 614 // if (SwitchBB->getBasicBlock() != CB.FalseBB->getBasicBlock()) 615 addMachineCFGPred({SwitchBB->getBasicBlock(), CB.FalseBB->getBasicBlock()}, 616 CB.ThisBB); 617 618 // If the lhs block is the next block, invert the condition so that we can 619 // fall through to the lhs instead of the rhs block. 620 if (CB.TrueBB == CB.ThisBB->getNextNode()) { 621 std::swap(CB.TrueBB, CB.FalseBB); 622 auto True = MIB.buildConstant(i1Ty, 1); 623 Cond = MIB.buildXor(i1Ty, Cond, True).getReg(0); 624 } 625 626 MIB.buildBrCond(Cond, *CB.TrueBB); 627 MIB.buildBr(*CB.FalseBB); 628 MIB.setDebugLoc(OldDbgLoc); 629 } 630 631 bool IRTranslator::lowerJumpTableWorkItem(SwitchCG::SwitchWorkListItem W, 632 MachineBasicBlock *SwitchMBB, 633 MachineBasicBlock *CurMBB, 634 MachineBasicBlock *DefaultMBB, 635 MachineIRBuilder &MIB, 636 MachineFunction::iterator BBI, 637 BranchProbability UnhandledProbs, 638 SwitchCG::CaseClusterIt I, 639 MachineBasicBlock *Fallthrough, 640 bool FallthroughUnreachable) { 641 using namespace SwitchCG; 642 MachineFunction *CurMF = SwitchMBB->getParent(); 643 // FIXME: Optimize away range check based on pivot comparisons. 644 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 645 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 646 BranchProbability DefaultProb = W.DefaultProb; 647 648 // The jump block hasn't been inserted yet; insert it here. 649 MachineBasicBlock *JumpMBB = JT->MBB; 650 CurMF->insert(BBI, JumpMBB); 651 652 // Since the jump table block is separate from the switch block, we need 653 // to keep track of it as a machine predecessor to the default block, 654 // otherwise we lose the phi edges. 655 addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()}, 656 CurMBB); 657 addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()}, 658 JumpMBB); 659 660 auto JumpProb = I->Prob; 661 auto FallthroughProb = UnhandledProbs; 662 663 // If the default statement is a target of the jump table, we evenly 664 // distribute the default probability to successors of CurMBB. Also 665 // update the probability on the edge from JumpMBB to Fallthrough. 666 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 667 SE = JumpMBB->succ_end(); 668 SI != SE; ++SI) { 669 if (*SI == DefaultMBB) { 670 JumpProb += DefaultProb / 2; 671 FallthroughProb -= DefaultProb / 2; 672 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 673 JumpMBB->normalizeSuccProbs(); 674 } else { 675 // Also record edges from the jump table block to it's successors. 676 addMachineCFGPred({SwitchMBB->getBasicBlock(), (*SI)->getBasicBlock()}, 677 JumpMBB); 678 } 679 } 680 681 // Skip the range check if the fallthrough block is unreachable. 682 if (FallthroughUnreachable) 683 JTH->OmitRangeCheck = true; 684 685 if (!JTH->OmitRangeCheck) 686 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 687 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 688 CurMBB->normalizeSuccProbs(); 689 690 // The jump table header will be inserted in our current block, do the 691 // range check, and fall through to our fallthrough block. 692 JTH->HeaderBB = CurMBB; 693 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 694 695 // If we're in the right place, emit the jump table header right now. 696 if (CurMBB == SwitchMBB) { 697 if (!emitJumpTableHeader(*JT, *JTH, CurMBB)) 698 return false; 699 JTH->Emitted = true; 700 } 701 return true; 702 } 703 bool IRTranslator::lowerSwitchRangeWorkItem(SwitchCG::CaseClusterIt I, 704 Value *Cond, 705 MachineBasicBlock *Fallthrough, 706 bool FallthroughUnreachable, 707 BranchProbability UnhandledProbs, 708 MachineBasicBlock *CurMBB, 709 MachineIRBuilder &MIB, 710 MachineBasicBlock *SwitchMBB) { 711 using namespace SwitchCG; 712 const Value *RHS, *LHS, *MHS; 713 CmpInst::Predicate Pred; 714 if (I->Low == I->High) { 715 // Check Cond == I->Low. 716 Pred = CmpInst::ICMP_EQ; 717 LHS = Cond; 718 RHS = I->Low; 719 MHS = nullptr; 720 } else { 721 // Check I->Low <= Cond <= I->High. 722 Pred = CmpInst::ICMP_SLE; 723 LHS = I->Low; 724 MHS = Cond; 725 RHS = I->High; 726 } 727 728 // If Fallthrough is unreachable, fold away the comparison. 729 // The false probability is the sum of all unhandled cases. 730 CaseBlock CB(Pred, FallthroughUnreachable, LHS, RHS, MHS, I->MBB, Fallthrough, 731 CurMBB, MIB.getDebugLoc(), I->Prob, UnhandledProbs); 732 733 emitSwitchCase(CB, SwitchMBB, MIB); 734 return true; 735 } 736 737 bool IRTranslator::lowerSwitchWorkItem(SwitchCG::SwitchWorkListItem W, 738 Value *Cond, 739 MachineBasicBlock *SwitchMBB, 740 MachineBasicBlock *DefaultMBB, 741 MachineIRBuilder &MIB) { 742 using namespace SwitchCG; 743 MachineFunction *CurMF = FuncInfo.MF; 744 MachineBasicBlock *NextMBB = nullptr; 745 MachineFunction::iterator BBI(W.MBB); 746 if (++BBI != FuncInfo.MF->end()) 747 NextMBB = &*BBI; 748 749 if (EnableOpts) { 750 // Here, we order cases by probability so the most likely case will be 751 // checked first. However, two clusters can have the same probability in 752 // which case their relative ordering is non-deterministic. So we use Low 753 // as a tie-breaker as clusters are guaranteed to never overlap. 754 llvm::sort(W.FirstCluster, W.LastCluster + 1, 755 [](const CaseCluster &a, const CaseCluster &b) { 756 return a.Prob != b.Prob 757 ? a.Prob > b.Prob 758 : a.Low->getValue().slt(b.Low->getValue()); 759 }); 760 761 // Rearrange the case blocks so that the last one falls through if possible 762 // without changing the order of probabilities. 763 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster;) { 764 --I; 765 if (I->Prob > W.LastCluster->Prob) 766 break; 767 if (I->Kind == CC_Range && I->MBB == NextMBB) { 768 std::swap(*I, *W.LastCluster); 769 break; 770 } 771 } 772 } 773 774 // Compute total probability. 775 BranchProbability DefaultProb = W.DefaultProb; 776 BranchProbability UnhandledProbs = DefaultProb; 777 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 778 UnhandledProbs += I->Prob; 779 780 MachineBasicBlock *CurMBB = W.MBB; 781 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 782 bool FallthroughUnreachable = false; 783 MachineBasicBlock *Fallthrough; 784 if (I == W.LastCluster) { 785 // For the last cluster, fall through to the default destination. 786 Fallthrough = DefaultMBB; 787 FallthroughUnreachable = isa<UnreachableInst>( 788 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 789 } else { 790 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 791 CurMF->insert(BBI, Fallthrough); 792 } 793 UnhandledProbs -= I->Prob; 794 795 switch (I->Kind) { 796 case CC_BitTests: { 797 LLVM_DEBUG(dbgs() << "Switch to bit test optimization unimplemented"); 798 return false; // Bit tests currently unimplemented. 799 } 800 case CC_JumpTable: { 801 if (!lowerJumpTableWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI, 802 UnhandledProbs, I, Fallthrough, 803 FallthroughUnreachable)) { 804 LLVM_DEBUG(dbgs() << "Failed to lower jump table"); 805 return false; 806 } 807 break; 808 } 809 case CC_Range: { 810 if (!lowerSwitchRangeWorkItem(I, Cond, Fallthrough, 811 FallthroughUnreachable, UnhandledProbs, 812 CurMBB, MIB, SwitchMBB)) { 813 LLVM_DEBUG(dbgs() << "Failed to lower switch range"); 814 return false; 815 } 816 break; 817 } 818 } 819 CurMBB = Fallthrough; 820 } 821 822 return true; 823 } 824 825 bool IRTranslator::translateIndirectBr(const User &U, 826 MachineIRBuilder &MIRBuilder) { 827 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U); 828 829 const Register Tgt = getOrCreateVReg(*BrInst.getAddress()); 830 MIRBuilder.buildBrIndirect(Tgt); 831 832 // Link successors. 833 SmallPtrSet<const BasicBlock *, 32> AddedSuccessors; 834 MachineBasicBlock &CurBB = MIRBuilder.getMBB(); 835 for (const BasicBlock *Succ : successors(&BrInst)) { 836 // It's legal for indirectbr instructions to have duplicate blocks in the 837 // destination list. We don't allow this in MIR. Skip anything that's 838 // already a successor. 839 if (!AddedSuccessors.insert(Succ).second) 840 continue; 841 CurBB.addSuccessor(&getMBB(*Succ)); 842 } 843 844 return true; 845 } 846 847 static bool isSwiftError(const Value *V) { 848 if (auto Arg = dyn_cast<Argument>(V)) 849 return Arg->hasSwiftErrorAttr(); 850 if (auto AI = dyn_cast<AllocaInst>(V)) 851 return AI->isSwiftError(); 852 return false; 853 } 854 855 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) { 856 const LoadInst &LI = cast<LoadInst>(U); 857 if (DL->getTypeStoreSize(LI.getType()) == 0) 858 return true; 859 860 ArrayRef<Register> Regs = getOrCreateVRegs(LI); 861 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI); 862 Register Base = getOrCreateVReg(*LI.getPointerOperand()); 863 864 Type *OffsetIRTy = DL->getIntPtrType(LI.getPointerOperandType()); 865 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL); 866 867 if (CLI->supportSwiftError() && isSwiftError(LI.getPointerOperand())) { 868 assert(Regs.size() == 1 && "swifterror should be single pointer"); 869 Register VReg = SwiftError.getOrCreateVRegUseAt(&LI, &MIRBuilder.getMBB(), 870 LI.getPointerOperand()); 871 MIRBuilder.buildCopy(Regs[0], VReg); 872 return true; 873 } 874 875 auto &TLI = *MF->getSubtarget().getTargetLowering(); 876 MachineMemOperand::Flags Flags = TLI.getLoadMemOperandFlags(LI, *DL); 877 878 const MDNode *Ranges = 879 Regs.size() == 1 ? LI.getMetadata(LLVMContext::MD_range) : nullptr; 880 for (unsigned i = 0; i < Regs.size(); ++i) { 881 Register Addr; 882 MIRBuilder.materializePtrAdd(Addr, Base, OffsetTy, Offsets[i] / 8); 883 884 MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8); 885 Align BaseAlign = getMemOpAlign(LI); 886 AAMDNodes AAMetadata; 887 LI.getAAMetadata(AAMetadata); 888 auto MMO = MF->getMachineMemOperand( 889 Ptr, Flags, MRI->getType(Regs[i]).getSizeInBytes(), 890 commonAlignment(BaseAlign, Offsets[i] / 8), AAMetadata, Ranges, 891 LI.getSyncScopeID(), LI.getOrdering()); 892 MIRBuilder.buildLoad(Regs[i], Addr, *MMO); 893 } 894 895 return true; 896 } 897 898 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) { 899 const StoreInst &SI = cast<StoreInst>(U); 900 if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0) 901 return true; 902 903 ArrayRef<Register> Vals = getOrCreateVRegs(*SI.getValueOperand()); 904 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand()); 905 Register Base = getOrCreateVReg(*SI.getPointerOperand()); 906 907 Type *OffsetIRTy = DL->getIntPtrType(SI.getPointerOperandType()); 908 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL); 909 910 if (CLI->supportSwiftError() && isSwiftError(SI.getPointerOperand())) { 911 assert(Vals.size() == 1 && "swifterror should be single pointer"); 912 913 Register VReg = SwiftError.getOrCreateVRegDefAt(&SI, &MIRBuilder.getMBB(), 914 SI.getPointerOperand()); 915 MIRBuilder.buildCopy(VReg, Vals[0]); 916 return true; 917 } 918 919 auto &TLI = *MF->getSubtarget().getTargetLowering(); 920 MachineMemOperand::Flags Flags = TLI.getStoreMemOperandFlags(SI, *DL); 921 922 for (unsigned i = 0; i < Vals.size(); ++i) { 923 Register Addr; 924 MIRBuilder.materializePtrAdd(Addr, Base, OffsetTy, Offsets[i] / 8); 925 926 MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8); 927 Align BaseAlign = getMemOpAlign(SI); 928 AAMDNodes AAMetadata; 929 SI.getAAMetadata(AAMetadata); 930 auto MMO = MF->getMachineMemOperand( 931 Ptr, Flags, MRI->getType(Vals[i]).getSizeInBytes(), 932 commonAlignment(BaseAlign, Offsets[i] / 8), AAMetadata, nullptr, 933 SI.getSyncScopeID(), SI.getOrdering()); 934 MIRBuilder.buildStore(Vals[i], Addr, *MMO); 935 } 936 return true; 937 } 938 939 static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) { 940 const Value *Src = U.getOperand(0); 941 Type *Int32Ty = Type::getInt32Ty(U.getContext()); 942 943 // getIndexedOffsetInType is designed for GEPs, so the first index is the 944 // usual array element rather than looking into the actual aggregate. 945 SmallVector<Value *, 1> Indices; 946 Indices.push_back(ConstantInt::get(Int32Ty, 0)); 947 948 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) { 949 for (auto Idx : EVI->indices()) 950 Indices.push_back(ConstantInt::get(Int32Ty, Idx)); 951 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) { 952 for (auto Idx : IVI->indices()) 953 Indices.push_back(ConstantInt::get(Int32Ty, Idx)); 954 } else { 955 for (unsigned i = 1; i < U.getNumOperands(); ++i) 956 Indices.push_back(U.getOperand(i)); 957 } 958 959 return 8 * static_cast<uint64_t>( 960 DL.getIndexedOffsetInType(Src->getType(), Indices)); 961 } 962 963 bool IRTranslator::translateExtractValue(const User &U, 964 MachineIRBuilder &MIRBuilder) { 965 const Value *Src = U.getOperand(0); 966 uint64_t Offset = getOffsetFromIndices(U, *DL); 967 ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src); 968 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src); 969 unsigned Idx = llvm::lower_bound(Offsets, Offset) - Offsets.begin(); 970 auto &DstRegs = allocateVRegs(U); 971 972 for (unsigned i = 0; i < DstRegs.size(); ++i) 973 DstRegs[i] = SrcRegs[Idx++]; 974 975 return true; 976 } 977 978 bool IRTranslator::translateInsertValue(const User &U, 979 MachineIRBuilder &MIRBuilder) { 980 const Value *Src = U.getOperand(0); 981 uint64_t Offset = getOffsetFromIndices(U, *DL); 982 auto &DstRegs = allocateVRegs(U); 983 ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U); 984 ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src); 985 ArrayRef<Register> InsertedRegs = getOrCreateVRegs(*U.getOperand(1)); 986 auto InsertedIt = InsertedRegs.begin(); 987 988 for (unsigned i = 0; i < DstRegs.size(); ++i) { 989 if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end()) 990 DstRegs[i] = *InsertedIt++; 991 else 992 DstRegs[i] = SrcRegs[i]; 993 } 994 995 return true; 996 } 997 998 bool IRTranslator::translateSelect(const User &U, 999 MachineIRBuilder &MIRBuilder) { 1000 Register Tst = getOrCreateVReg(*U.getOperand(0)); 1001 ArrayRef<Register> ResRegs = getOrCreateVRegs(U); 1002 ArrayRef<Register> Op0Regs = getOrCreateVRegs(*U.getOperand(1)); 1003 ArrayRef<Register> Op1Regs = getOrCreateVRegs(*U.getOperand(2)); 1004 1005 uint16_t Flags = 0; 1006 if (const SelectInst *SI = dyn_cast<SelectInst>(&U)) 1007 Flags = MachineInstr::copyFlagsFromInstruction(*SI); 1008 1009 for (unsigned i = 0; i < ResRegs.size(); ++i) { 1010 MIRBuilder.buildSelect(ResRegs[i], Tst, Op0Regs[i], Op1Regs[i], Flags); 1011 } 1012 1013 return true; 1014 } 1015 1016 bool IRTranslator::translateCopy(const User &U, const Value &V, 1017 MachineIRBuilder &MIRBuilder) { 1018 Register Src = getOrCreateVReg(V); 1019 auto &Regs = *VMap.getVRegs(U); 1020 if (Regs.empty()) { 1021 Regs.push_back(Src); 1022 VMap.getOffsets(U)->push_back(0); 1023 } else { 1024 // If we already assigned a vreg for this instruction, we can't change that. 1025 // Emit a copy to satisfy the users we already emitted. 1026 MIRBuilder.buildCopy(Regs[0], Src); 1027 } 1028 return true; 1029 } 1030 1031 bool IRTranslator::translateBitCast(const User &U, 1032 MachineIRBuilder &MIRBuilder) { 1033 // If we're bitcasting to the source type, we can reuse the source vreg. 1034 if (getLLTForType(*U.getOperand(0)->getType(), *DL) == 1035 getLLTForType(*U.getType(), *DL)) 1036 return translateCopy(U, *U.getOperand(0), MIRBuilder); 1037 1038 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder); 1039 } 1040 1041 bool IRTranslator::translateCast(unsigned Opcode, const User &U, 1042 MachineIRBuilder &MIRBuilder) { 1043 Register Op = getOrCreateVReg(*U.getOperand(0)); 1044 Register Res = getOrCreateVReg(U); 1045 MIRBuilder.buildInstr(Opcode, {Res}, {Op}); 1046 return true; 1047 } 1048 1049 bool IRTranslator::translateGetElementPtr(const User &U, 1050 MachineIRBuilder &MIRBuilder) { 1051 Value &Op0 = *U.getOperand(0); 1052 Register BaseReg = getOrCreateVReg(Op0); 1053 Type *PtrIRTy = Op0.getType(); 1054 LLT PtrTy = getLLTForType(*PtrIRTy, *DL); 1055 Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy); 1056 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL); 1057 1058 // Normalize Vector GEP - all scalar operands should be converted to the 1059 // splat vector. 1060 unsigned VectorWidth = 0; 1061 if (auto *VT = dyn_cast<VectorType>(U.getType())) 1062 VectorWidth = cast<FixedVectorType>(VT)->getNumElements(); 1063 1064 // We might need to splat the base pointer into a vector if the offsets 1065 // are vectors. 1066 if (VectorWidth && !PtrTy.isVector()) { 1067 BaseReg = 1068 MIRBuilder.buildSplatVector(LLT::vector(VectorWidth, PtrTy), BaseReg) 1069 .getReg(0); 1070 PtrIRTy = FixedVectorType::get(PtrIRTy, VectorWidth); 1071 PtrTy = getLLTForType(*PtrIRTy, *DL); 1072 OffsetIRTy = DL->getIntPtrType(PtrIRTy); 1073 OffsetTy = getLLTForType(*OffsetIRTy, *DL); 1074 } 1075 1076 int64_t Offset = 0; 1077 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U); 1078 GTI != E; ++GTI) { 1079 const Value *Idx = GTI.getOperand(); 1080 if (StructType *StTy = GTI.getStructTypeOrNull()) { 1081 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 1082 Offset += DL->getStructLayout(StTy)->getElementOffset(Field); 1083 continue; 1084 } else { 1085 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 1086 1087 // If this is a scalar constant or a splat vector of constants, 1088 // handle it quickly. 1089 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) { 1090 Offset += ElementSize * CI->getSExtValue(); 1091 continue; 1092 } 1093 1094 if (Offset != 0) { 1095 auto OffsetMIB = MIRBuilder.buildConstant({OffsetTy}, Offset); 1096 BaseReg = MIRBuilder.buildPtrAdd(PtrTy, BaseReg, OffsetMIB.getReg(0)) 1097 .getReg(0); 1098 Offset = 0; 1099 } 1100 1101 Register IdxReg = getOrCreateVReg(*Idx); 1102 LLT IdxTy = MRI->getType(IdxReg); 1103 if (IdxTy != OffsetTy) { 1104 if (!IdxTy.isVector() && VectorWidth) { 1105 IdxReg = MIRBuilder.buildSplatVector( 1106 OffsetTy.changeElementType(IdxTy), IdxReg).getReg(0); 1107 } 1108 1109 IdxReg = MIRBuilder.buildSExtOrTrunc(OffsetTy, IdxReg).getReg(0); 1110 } 1111 1112 // N = N + Idx * ElementSize; 1113 // Avoid doing it for ElementSize of 1. 1114 Register GepOffsetReg; 1115 if (ElementSize != 1) { 1116 auto ElementSizeMIB = MIRBuilder.buildConstant( 1117 getLLTForType(*OffsetIRTy, *DL), ElementSize); 1118 GepOffsetReg = 1119 MIRBuilder.buildMul(OffsetTy, IdxReg, ElementSizeMIB).getReg(0); 1120 } else 1121 GepOffsetReg = IdxReg; 1122 1123 BaseReg = MIRBuilder.buildPtrAdd(PtrTy, BaseReg, GepOffsetReg).getReg(0); 1124 } 1125 } 1126 1127 if (Offset != 0) { 1128 auto OffsetMIB = 1129 MIRBuilder.buildConstant(OffsetTy, Offset); 1130 MIRBuilder.buildPtrAdd(getOrCreateVReg(U), BaseReg, OffsetMIB.getReg(0)); 1131 return true; 1132 } 1133 1134 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg); 1135 return true; 1136 } 1137 1138 bool IRTranslator::translateMemFunc(const CallInst &CI, 1139 MachineIRBuilder &MIRBuilder, 1140 Intrinsic::ID ID) { 1141 1142 // If the source is undef, then just emit a nop. 1143 if (isa<UndefValue>(CI.getArgOperand(1))) 1144 return true; 1145 1146 ArrayRef<Register> Res; 1147 auto ICall = MIRBuilder.buildIntrinsic(ID, Res, true); 1148 for (auto AI = CI.arg_begin(), AE = CI.arg_end(); std::next(AI) != AE; ++AI) 1149 ICall.addUse(getOrCreateVReg(**AI)); 1150 1151 Align DstAlign; 1152 Align SrcAlign; 1153 unsigned IsVol = 1154 cast<ConstantInt>(CI.getArgOperand(CI.getNumArgOperands() - 1)) 1155 ->getZExtValue(); 1156 1157 if (auto *MCI = dyn_cast<MemCpyInst>(&CI)) { 1158 DstAlign = MCI->getDestAlign().valueOrOne(); 1159 SrcAlign = MCI->getSourceAlign().valueOrOne(); 1160 } else if (auto *MMI = dyn_cast<MemMoveInst>(&CI)) { 1161 DstAlign = MMI->getDestAlign().valueOrOne(); 1162 SrcAlign = MMI->getSourceAlign().valueOrOne(); 1163 } else { 1164 auto *MSI = cast<MemSetInst>(&CI); 1165 DstAlign = MSI->getDestAlign().valueOrOne(); 1166 } 1167 1168 // We need to propagate the tail call flag from the IR inst as an argument. 1169 // Otherwise, we have to pessimize and assume later that we cannot tail call 1170 // any memory intrinsics. 1171 ICall.addImm(CI.isTailCall() ? 1 : 0); 1172 1173 // Create mem operands to store the alignment and volatile info. 1174 auto VolFlag = IsVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 1175 ICall.addMemOperand(MF->getMachineMemOperand( 1176 MachinePointerInfo(CI.getArgOperand(0)), 1177 MachineMemOperand::MOStore | VolFlag, 1, DstAlign)); 1178 if (ID != Intrinsic::memset) 1179 ICall.addMemOperand(MF->getMachineMemOperand( 1180 MachinePointerInfo(CI.getArgOperand(1)), 1181 MachineMemOperand::MOLoad | VolFlag, 1, SrcAlign)); 1182 1183 return true; 1184 } 1185 1186 void IRTranslator::getStackGuard(Register DstReg, 1187 MachineIRBuilder &MIRBuilder) { 1188 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 1189 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF)); 1190 auto MIB = 1191 MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD, {DstReg}, {}); 1192 1193 auto &TLI = *MF->getSubtarget().getTargetLowering(); 1194 Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent()); 1195 if (!Global) 1196 return; 1197 1198 MachinePointerInfo MPInfo(Global); 1199 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 1200 MachineMemOperand::MODereferenceable; 1201 MachineMemOperand *MemRef = 1202 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8, 1203 DL->getPointerABIAlignment(0)); 1204 MIB.setMemRefs({MemRef}); 1205 } 1206 1207 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op, 1208 MachineIRBuilder &MIRBuilder) { 1209 ArrayRef<Register> ResRegs = getOrCreateVRegs(CI); 1210 MIRBuilder.buildInstr( 1211 Op, {ResRegs[0], ResRegs[1]}, 1212 {getOrCreateVReg(*CI.getOperand(0)), getOrCreateVReg(*CI.getOperand(1))}); 1213 1214 return true; 1215 } 1216 1217 bool IRTranslator::translateFixedPointIntrinsic(unsigned Op, const CallInst &CI, 1218 MachineIRBuilder &MIRBuilder) { 1219 Register Dst = getOrCreateVReg(CI); 1220 Register Src0 = getOrCreateVReg(*CI.getOperand(0)); 1221 Register Src1 = getOrCreateVReg(*CI.getOperand(1)); 1222 uint64_t Scale = cast<ConstantInt>(CI.getOperand(2))->getZExtValue(); 1223 MIRBuilder.buildInstr(Op, {Dst}, { Src0, Src1, Scale }); 1224 return true; 1225 } 1226 1227 unsigned IRTranslator::getSimpleIntrinsicOpcode(Intrinsic::ID ID) { 1228 switch (ID) { 1229 default: 1230 break; 1231 case Intrinsic::bswap: 1232 return TargetOpcode::G_BSWAP; 1233 case Intrinsic::bitreverse: 1234 return TargetOpcode::G_BITREVERSE; 1235 case Intrinsic::fshl: 1236 return TargetOpcode::G_FSHL; 1237 case Intrinsic::fshr: 1238 return TargetOpcode::G_FSHR; 1239 case Intrinsic::ceil: 1240 return TargetOpcode::G_FCEIL; 1241 case Intrinsic::cos: 1242 return TargetOpcode::G_FCOS; 1243 case Intrinsic::ctpop: 1244 return TargetOpcode::G_CTPOP; 1245 case Intrinsic::exp: 1246 return TargetOpcode::G_FEXP; 1247 case Intrinsic::exp2: 1248 return TargetOpcode::G_FEXP2; 1249 case Intrinsic::fabs: 1250 return TargetOpcode::G_FABS; 1251 case Intrinsic::copysign: 1252 return TargetOpcode::G_FCOPYSIGN; 1253 case Intrinsic::minnum: 1254 return TargetOpcode::G_FMINNUM; 1255 case Intrinsic::maxnum: 1256 return TargetOpcode::G_FMAXNUM; 1257 case Intrinsic::minimum: 1258 return TargetOpcode::G_FMINIMUM; 1259 case Intrinsic::maximum: 1260 return TargetOpcode::G_FMAXIMUM; 1261 case Intrinsic::canonicalize: 1262 return TargetOpcode::G_FCANONICALIZE; 1263 case Intrinsic::floor: 1264 return TargetOpcode::G_FFLOOR; 1265 case Intrinsic::fma: 1266 return TargetOpcode::G_FMA; 1267 case Intrinsic::log: 1268 return TargetOpcode::G_FLOG; 1269 case Intrinsic::log2: 1270 return TargetOpcode::G_FLOG2; 1271 case Intrinsic::log10: 1272 return TargetOpcode::G_FLOG10; 1273 case Intrinsic::nearbyint: 1274 return TargetOpcode::G_FNEARBYINT; 1275 case Intrinsic::pow: 1276 return TargetOpcode::G_FPOW; 1277 case Intrinsic::powi: 1278 return TargetOpcode::G_FPOWI; 1279 case Intrinsic::rint: 1280 return TargetOpcode::G_FRINT; 1281 case Intrinsic::round: 1282 return TargetOpcode::G_INTRINSIC_ROUND; 1283 case Intrinsic::sin: 1284 return TargetOpcode::G_FSIN; 1285 case Intrinsic::sqrt: 1286 return TargetOpcode::G_FSQRT; 1287 case Intrinsic::trunc: 1288 return TargetOpcode::G_INTRINSIC_TRUNC; 1289 case Intrinsic::readcyclecounter: 1290 return TargetOpcode::G_READCYCLECOUNTER; 1291 case Intrinsic::ptrmask: 1292 return TargetOpcode::G_PTRMASK; 1293 case Intrinsic::lrint: 1294 return TargetOpcode::G_INTRINSIC_LRINT; 1295 } 1296 return Intrinsic::not_intrinsic; 1297 } 1298 1299 bool IRTranslator::translateSimpleIntrinsic(const CallInst &CI, 1300 Intrinsic::ID ID, 1301 MachineIRBuilder &MIRBuilder) { 1302 1303 unsigned Op = getSimpleIntrinsicOpcode(ID); 1304 1305 // Is this a simple intrinsic? 1306 if (Op == Intrinsic::not_intrinsic) 1307 return false; 1308 1309 // Yes. Let's translate it. 1310 SmallVector<llvm::SrcOp, 4> VRegs; 1311 for (auto &Arg : CI.arg_operands()) 1312 VRegs.push_back(getOrCreateVReg(*Arg)); 1313 1314 MIRBuilder.buildInstr(Op, {getOrCreateVReg(CI)}, VRegs, 1315 MachineInstr::copyFlagsFromInstruction(CI)); 1316 return true; 1317 } 1318 1319 // TODO: Include ConstainedOps.def when all strict instructions are defined. 1320 static unsigned getConstrainedOpcode(Intrinsic::ID ID) { 1321 switch (ID) { 1322 case Intrinsic::experimental_constrained_fadd: 1323 return TargetOpcode::G_STRICT_FADD; 1324 case Intrinsic::experimental_constrained_fsub: 1325 return TargetOpcode::G_STRICT_FSUB; 1326 case Intrinsic::experimental_constrained_fmul: 1327 return TargetOpcode::G_STRICT_FMUL; 1328 case Intrinsic::experimental_constrained_fdiv: 1329 return TargetOpcode::G_STRICT_FDIV; 1330 case Intrinsic::experimental_constrained_frem: 1331 return TargetOpcode::G_STRICT_FREM; 1332 case Intrinsic::experimental_constrained_fma: 1333 return TargetOpcode::G_STRICT_FMA; 1334 case Intrinsic::experimental_constrained_sqrt: 1335 return TargetOpcode::G_STRICT_FSQRT; 1336 default: 1337 return 0; 1338 } 1339 } 1340 1341 bool IRTranslator::translateConstrainedFPIntrinsic( 1342 const ConstrainedFPIntrinsic &FPI, MachineIRBuilder &MIRBuilder) { 1343 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 1344 1345 unsigned Opcode = getConstrainedOpcode(FPI.getIntrinsicID()); 1346 if (!Opcode) 1347 return false; 1348 1349 unsigned Flags = MachineInstr::copyFlagsFromInstruction(FPI); 1350 if (EB == fp::ExceptionBehavior::ebIgnore) 1351 Flags |= MachineInstr::NoFPExcept; 1352 1353 SmallVector<llvm::SrcOp, 4> VRegs; 1354 VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(0))); 1355 if (!FPI.isUnaryOp()) 1356 VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(1))); 1357 if (FPI.isTernaryOp()) 1358 VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(2))); 1359 1360 MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(FPI)}, VRegs, Flags); 1361 return true; 1362 } 1363 1364 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID, 1365 MachineIRBuilder &MIRBuilder) { 1366 1367 // If this is a simple intrinsic (that is, we just need to add a def of 1368 // a vreg, and uses for each arg operand, then translate it. 1369 if (translateSimpleIntrinsic(CI, ID, MIRBuilder)) 1370 return true; 1371 1372 switch (ID) { 1373 default: 1374 break; 1375 case Intrinsic::lifetime_start: 1376 case Intrinsic::lifetime_end: { 1377 // No stack colouring in O0, discard region information. 1378 if (MF->getTarget().getOptLevel() == CodeGenOpt::None) 1379 return true; 1380 1381 unsigned Op = ID == Intrinsic::lifetime_start ? TargetOpcode::LIFETIME_START 1382 : TargetOpcode::LIFETIME_END; 1383 1384 // Get the underlying objects for the location passed on the lifetime 1385 // marker. 1386 SmallVector<const Value *, 4> Allocas; 1387 GetUnderlyingObjects(CI.getArgOperand(1), Allocas, *DL); 1388 1389 // Iterate over each underlying object, creating lifetime markers for each 1390 // static alloca. Quit if we find a non-static alloca. 1391 for (const Value *V : Allocas) { 1392 const AllocaInst *AI = dyn_cast<AllocaInst>(V); 1393 if (!AI) 1394 continue; 1395 1396 if (!AI->isStaticAlloca()) 1397 return true; 1398 1399 MIRBuilder.buildInstr(Op).addFrameIndex(getOrCreateFrameIndex(*AI)); 1400 } 1401 return true; 1402 } 1403 case Intrinsic::dbg_declare: { 1404 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI); 1405 assert(DI.getVariable() && "Missing variable"); 1406 1407 const Value *Address = DI.getAddress(); 1408 if (!Address || isa<UndefValue>(Address)) { 1409 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 1410 return true; 1411 } 1412 1413 assert(DI.getVariable()->isValidLocationForIntrinsic( 1414 MIRBuilder.getDebugLoc()) && 1415 "Expected inlined-at fields to agree"); 1416 auto AI = dyn_cast<AllocaInst>(Address); 1417 if (AI && AI->isStaticAlloca()) { 1418 // Static allocas are tracked at the MF level, no need for DBG_VALUE 1419 // instructions (in fact, they get ignored if they *do* exist). 1420 MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(), 1421 getOrCreateFrameIndex(*AI), DI.getDebugLoc()); 1422 } else { 1423 // A dbg.declare describes the address of a source variable, so lower it 1424 // into an indirect DBG_VALUE. 1425 MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address), 1426 DI.getVariable(), DI.getExpression()); 1427 } 1428 return true; 1429 } 1430 case Intrinsic::dbg_label: { 1431 const DbgLabelInst &DI = cast<DbgLabelInst>(CI); 1432 assert(DI.getLabel() && "Missing label"); 1433 1434 assert(DI.getLabel()->isValidLocationForIntrinsic( 1435 MIRBuilder.getDebugLoc()) && 1436 "Expected inlined-at fields to agree"); 1437 1438 MIRBuilder.buildDbgLabel(DI.getLabel()); 1439 return true; 1440 } 1441 case Intrinsic::vaend: 1442 // No target I know of cares about va_end. Certainly no in-tree target 1443 // does. Simplest intrinsic ever! 1444 return true; 1445 case Intrinsic::vastart: { 1446 auto &TLI = *MF->getSubtarget().getTargetLowering(); 1447 Value *Ptr = CI.getArgOperand(0); 1448 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8; 1449 1450 // FIXME: Get alignment 1451 MIRBuilder.buildInstr(TargetOpcode::G_VASTART, {}, {getOrCreateVReg(*Ptr)}) 1452 .addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Ptr), 1453 MachineMemOperand::MOStore, 1454 ListSize, Align(1))); 1455 return true; 1456 } 1457 case Intrinsic::dbg_value: { 1458 // This form of DBG_VALUE is target-independent. 1459 const DbgValueInst &DI = cast<DbgValueInst>(CI); 1460 const Value *V = DI.getValue(); 1461 assert(DI.getVariable()->isValidLocationForIntrinsic( 1462 MIRBuilder.getDebugLoc()) && 1463 "Expected inlined-at fields to agree"); 1464 if (!V) { 1465 // Currently the optimizer can produce this; insert an undef to 1466 // help debugging. Probably the optimizer should not do this. 1467 MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression()); 1468 } else if (const auto *CI = dyn_cast<Constant>(V)) { 1469 MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression()); 1470 } else { 1471 for (Register Reg : getOrCreateVRegs(*V)) { 1472 // FIXME: This does not handle register-indirect values at offset 0. The 1473 // direct/indirect thing shouldn't really be handled by something as 1474 // implicit as reg+noreg vs reg+imm in the first place, but it seems 1475 // pretty baked in right now. 1476 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression()); 1477 } 1478 } 1479 return true; 1480 } 1481 case Intrinsic::uadd_with_overflow: 1482 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder); 1483 case Intrinsic::sadd_with_overflow: 1484 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder); 1485 case Intrinsic::usub_with_overflow: 1486 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder); 1487 case Intrinsic::ssub_with_overflow: 1488 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder); 1489 case Intrinsic::umul_with_overflow: 1490 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder); 1491 case Intrinsic::smul_with_overflow: 1492 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder); 1493 case Intrinsic::uadd_sat: 1494 return translateBinaryOp(TargetOpcode::G_UADDSAT, CI, MIRBuilder); 1495 case Intrinsic::sadd_sat: 1496 return translateBinaryOp(TargetOpcode::G_SADDSAT, CI, MIRBuilder); 1497 case Intrinsic::usub_sat: 1498 return translateBinaryOp(TargetOpcode::G_USUBSAT, CI, MIRBuilder); 1499 case Intrinsic::ssub_sat: 1500 return translateBinaryOp(TargetOpcode::G_SSUBSAT, CI, MIRBuilder); 1501 case Intrinsic::umin: 1502 return translateBinaryOp(TargetOpcode::G_UMIN, CI, MIRBuilder); 1503 case Intrinsic::umax: 1504 return translateBinaryOp(TargetOpcode::G_UMAX, CI, MIRBuilder); 1505 case Intrinsic::smin: 1506 return translateBinaryOp(TargetOpcode::G_SMIN, CI, MIRBuilder); 1507 case Intrinsic::smax: 1508 return translateBinaryOp(TargetOpcode::G_SMAX, CI, MIRBuilder); 1509 case Intrinsic::smul_fix: 1510 return translateFixedPointIntrinsic(TargetOpcode::G_SMULFIX, CI, MIRBuilder); 1511 case Intrinsic::umul_fix: 1512 return translateFixedPointIntrinsic(TargetOpcode::G_UMULFIX, CI, MIRBuilder); 1513 case Intrinsic::smul_fix_sat: 1514 return translateFixedPointIntrinsic(TargetOpcode::G_SMULFIXSAT, CI, MIRBuilder); 1515 case Intrinsic::umul_fix_sat: 1516 return translateFixedPointIntrinsic(TargetOpcode::G_UMULFIXSAT, CI, MIRBuilder); 1517 case Intrinsic::sdiv_fix: 1518 return translateFixedPointIntrinsic(TargetOpcode::G_SDIVFIX, CI, MIRBuilder); 1519 case Intrinsic::udiv_fix: 1520 return translateFixedPointIntrinsic(TargetOpcode::G_UDIVFIX, CI, MIRBuilder); 1521 case Intrinsic::sdiv_fix_sat: 1522 return translateFixedPointIntrinsic(TargetOpcode::G_SDIVFIXSAT, CI, MIRBuilder); 1523 case Intrinsic::udiv_fix_sat: 1524 return translateFixedPointIntrinsic(TargetOpcode::G_UDIVFIXSAT, CI, MIRBuilder); 1525 case Intrinsic::fmuladd: { 1526 const TargetMachine &TM = MF->getTarget(); 1527 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering(); 1528 Register Dst = getOrCreateVReg(CI); 1529 Register Op0 = getOrCreateVReg(*CI.getArgOperand(0)); 1530 Register Op1 = getOrCreateVReg(*CI.getArgOperand(1)); 1531 Register Op2 = getOrCreateVReg(*CI.getArgOperand(2)); 1532 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 1533 TLI.isFMAFasterThanFMulAndFAdd(*MF, 1534 TLI.getValueType(*DL, CI.getType()))) { 1535 // TODO: Revisit this to see if we should move this part of the 1536 // lowering to the combiner. 1537 MIRBuilder.buildFMA(Dst, Op0, Op1, Op2, 1538 MachineInstr::copyFlagsFromInstruction(CI)); 1539 } else { 1540 LLT Ty = getLLTForType(*CI.getType(), *DL); 1541 auto FMul = MIRBuilder.buildFMul( 1542 Ty, Op0, Op1, MachineInstr::copyFlagsFromInstruction(CI)); 1543 MIRBuilder.buildFAdd(Dst, FMul, Op2, 1544 MachineInstr::copyFlagsFromInstruction(CI)); 1545 } 1546 return true; 1547 } 1548 case Intrinsic::convert_from_fp16: 1549 // FIXME: This intrinsic should probably be removed from the IR. 1550 MIRBuilder.buildFPExt(getOrCreateVReg(CI), 1551 getOrCreateVReg(*CI.getArgOperand(0)), 1552 MachineInstr::copyFlagsFromInstruction(CI)); 1553 return true; 1554 case Intrinsic::convert_to_fp16: 1555 // FIXME: This intrinsic should probably be removed from the IR. 1556 MIRBuilder.buildFPTrunc(getOrCreateVReg(CI), 1557 getOrCreateVReg(*CI.getArgOperand(0)), 1558 MachineInstr::copyFlagsFromInstruction(CI)); 1559 return true; 1560 case Intrinsic::memcpy: 1561 case Intrinsic::memmove: 1562 case Intrinsic::memset: 1563 return translateMemFunc(CI, MIRBuilder, ID); 1564 case Intrinsic::eh_typeid_for: { 1565 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0)); 1566 Register Reg = getOrCreateVReg(CI); 1567 unsigned TypeID = MF->getTypeIDFor(GV); 1568 MIRBuilder.buildConstant(Reg, TypeID); 1569 return true; 1570 } 1571 case Intrinsic::objectsize: 1572 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 1573 1574 case Intrinsic::is_constant: 1575 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 1576 1577 case Intrinsic::stackguard: 1578 getStackGuard(getOrCreateVReg(CI), MIRBuilder); 1579 return true; 1580 case Intrinsic::stackprotector: { 1581 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL); 1582 Register GuardVal = MRI->createGenericVirtualRegister(PtrTy); 1583 getStackGuard(GuardVal, MIRBuilder); 1584 1585 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1)); 1586 int FI = getOrCreateFrameIndex(*Slot); 1587 MF->getFrameInfo().setStackProtectorIndex(FI); 1588 1589 MIRBuilder.buildStore( 1590 GuardVal, getOrCreateVReg(*Slot), 1591 *MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 1592 MachineMemOperand::MOStore | 1593 MachineMemOperand::MOVolatile, 1594 PtrTy.getSizeInBits() / 8, Align(8))); 1595 return true; 1596 } 1597 case Intrinsic::stacksave: { 1598 // Save the stack pointer to the location provided by the intrinsic. 1599 Register Reg = getOrCreateVReg(CI); 1600 Register StackPtr = MF->getSubtarget() 1601 .getTargetLowering() 1602 ->getStackPointerRegisterToSaveRestore(); 1603 1604 // If the target doesn't specify a stack pointer, then fall back. 1605 if (!StackPtr) 1606 return false; 1607 1608 MIRBuilder.buildCopy(Reg, StackPtr); 1609 return true; 1610 } 1611 case Intrinsic::stackrestore: { 1612 // Restore the stack pointer from the location provided by the intrinsic. 1613 Register Reg = getOrCreateVReg(*CI.getArgOperand(0)); 1614 Register StackPtr = MF->getSubtarget() 1615 .getTargetLowering() 1616 ->getStackPointerRegisterToSaveRestore(); 1617 1618 // If the target doesn't specify a stack pointer, then fall back. 1619 if (!StackPtr) 1620 return false; 1621 1622 MIRBuilder.buildCopy(StackPtr, Reg); 1623 return true; 1624 } 1625 case Intrinsic::cttz: 1626 case Intrinsic::ctlz: { 1627 ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1)); 1628 bool isTrailing = ID == Intrinsic::cttz; 1629 unsigned Opcode = isTrailing 1630 ? Cst->isZero() ? TargetOpcode::G_CTTZ 1631 : TargetOpcode::G_CTTZ_ZERO_UNDEF 1632 : Cst->isZero() ? TargetOpcode::G_CTLZ 1633 : TargetOpcode::G_CTLZ_ZERO_UNDEF; 1634 MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(CI)}, 1635 {getOrCreateVReg(*CI.getArgOperand(0))}); 1636 return true; 1637 } 1638 case Intrinsic::invariant_start: { 1639 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL); 1640 Register Undef = MRI->createGenericVirtualRegister(PtrTy); 1641 MIRBuilder.buildUndef(Undef); 1642 return true; 1643 } 1644 case Intrinsic::invariant_end: 1645 return true; 1646 case Intrinsic::assume: 1647 case Intrinsic::var_annotation: 1648 case Intrinsic::sideeffect: 1649 // Discard annotate attributes, assumptions, and artificial side-effects. 1650 return true; 1651 case Intrinsic::read_volatile_register: 1652 case Intrinsic::read_register: { 1653 Value *Arg = CI.getArgOperand(0); 1654 MIRBuilder 1655 .buildInstr(TargetOpcode::G_READ_REGISTER, {getOrCreateVReg(CI)}, {}) 1656 .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata())); 1657 return true; 1658 } 1659 case Intrinsic::write_register: { 1660 Value *Arg = CI.getArgOperand(0); 1661 MIRBuilder.buildInstr(TargetOpcode::G_WRITE_REGISTER) 1662 .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata())) 1663 .addUse(getOrCreateVReg(*CI.getArgOperand(1))); 1664 return true; 1665 } 1666 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 1667 case Intrinsic::INTRINSIC: 1668 #include "llvm/IR/ConstrainedOps.def" 1669 return translateConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(CI), 1670 MIRBuilder); 1671 1672 } 1673 return false; 1674 } 1675 1676 bool IRTranslator::translateInlineAsm(const CallBase &CB, 1677 MachineIRBuilder &MIRBuilder) { 1678 1679 const InlineAsmLowering *ALI = MF->getSubtarget().getInlineAsmLowering(); 1680 1681 if (!ALI) { 1682 LLVM_DEBUG( 1683 dbgs() << "Inline asm lowering is not supported for this target yet\n"); 1684 return false; 1685 } 1686 1687 return ALI->lowerInlineAsm( 1688 MIRBuilder, CB, [&](const Value &Val) { return getOrCreateVRegs(Val); }); 1689 } 1690 1691 bool IRTranslator::translateCallBase(const CallBase &CB, 1692 MachineIRBuilder &MIRBuilder) { 1693 ArrayRef<Register> Res = getOrCreateVRegs(CB); 1694 1695 SmallVector<ArrayRef<Register>, 8> Args; 1696 Register SwiftInVReg = 0; 1697 Register SwiftErrorVReg = 0; 1698 for (auto &Arg : CB.args()) { 1699 if (CLI->supportSwiftError() && isSwiftError(Arg)) { 1700 assert(SwiftInVReg == 0 && "Expected only one swift error argument"); 1701 LLT Ty = getLLTForType(*Arg->getType(), *DL); 1702 SwiftInVReg = MRI->createGenericVirtualRegister(Ty); 1703 MIRBuilder.buildCopy(SwiftInVReg, SwiftError.getOrCreateVRegUseAt( 1704 &CB, &MIRBuilder.getMBB(), Arg)); 1705 Args.emplace_back(makeArrayRef(SwiftInVReg)); 1706 SwiftErrorVReg = 1707 SwiftError.getOrCreateVRegDefAt(&CB, &MIRBuilder.getMBB(), Arg); 1708 continue; 1709 } 1710 Args.push_back(getOrCreateVRegs(*Arg)); 1711 } 1712 1713 // We don't set HasCalls on MFI here yet because call lowering may decide to 1714 // optimize into tail calls. Instead, we defer that to selection where a final 1715 // scan is done to check if any instructions are calls. 1716 bool Success = 1717 CLI->lowerCall(MIRBuilder, CB, Res, Args, SwiftErrorVReg, 1718 [&]() { return getOrCreateVReg(*CB.getCalledOperand()); }); 1719 1720 // Check if we just inserted a tail call. 1721 if (Success) { 1722 assert(!HasTailCall && "Can't tail call return twice from block?"); 1723 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 1724 HasTailCall = TII->isTailCall(*std::prev(MIRBuilder.getInsertPt())); 1725 } 1726 1727 return Success; 1728 } 1729 1730 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) { 1731 const CallInst &CI = cast<CallInst>(U); 1732 auto TII = MF->getTarget().getIntrinsicInfo(); 1733 const Function *F = CI.getCalledFunction(); 1734 1735 // FIXME: support Windows dllimport function calls. 1736 if (F && (F->hasDLLImportStorageClass() || 1737 (MF->getTarget().getTargetTriple().isOSWindows() && 1738 F->hasExternalWeakLinkage()))) 1739 return false; 1740 1741 // FIXME: support control flow guard targets. 1742 if (CI.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget)) 1743 return false; 1744 1745 if (CI.isInlineAsm()) 1746 return translateInlineAsm(CI, MIRBuilder); 1747 1748 Intrinsic::ID ID = Intrinsic::not_intrinsic; 1749 if (F && F->isIntrinsic()) { 1750 ID = F->getIntrinsicID(); 1751 if (TII && ID == Intrinsic::not_intrinsic) 1752 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F)); 1753 } 1754 1755 if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic) 1756 return translateCallBase(CI, MIRBuilder); 1757 1758 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic"); 1759 1760 if (translateKnownIntrinsic(CI, ID, MIRBuilder)) 1761 return true; 1762 1763 ArrayRef<Register> ResultRegs; 1764 if (!CI.getType()->isVoidTy()) 1765 ResultRegs = getOrCreateVRegs(CI); 1766 1767 // Ignore the callsite attributes. Backend code is most likely not expecting 1768 // an intrinsic to sometimes have side effects and sometimes not. 1769 MachineInstrBuilder MIB = 1770 MIRBuilder.buildIntrinsic(ID, ResultRegs, !F->doesNotAccessMemory()); 1771 if (isa<FPMathOperator>(CI)) 1772 MIB->copyIRFlags(CI); 1773 1774 for (auto &Arg : enumerate(CI.arg_operands())) { 1775 // If this is required to be an immediate, don't materialize it in a 1776 // register. 1777 if (CI.paramHasAttr(Arg.index(), Attribute::ImmArg)) { 1778 if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg.value())) { 1779 // imm arguments are more convenient than cimm (and realistically 1780 // probably sufficient), so use them. 1781 assert(CI->getBitWidth() <= 64 && 1782 "large intrinsic immediates not handled"); 1783 MIB.addImm(CI->getSExtValue()); 1784 } else { 1785 MIB.addFPImm(cast<ConstantFP>(Arg.value())); 1786 } 1787 } else if (auto MD = dyn_cast<MetadataAsValue>(Arg.value())) { 1788 auto *MDN = dyn_cast<MDNode>(MD->getMetadata()); 1789 if (!MDN) // This was probably an MDString. 1790 return false; 1791 MIB.addMetadata(MDN); 1792 } else { 1793 ArrayRef<Register> VRegs = getOrCreateVRegs(*Arg.value()); 1794 if (VRegs.size() > 1) 1795 return false; 1796 MIB.addUse(VRegs[0]); 1797 } 1798 } 1799 1800 // Add a MachineMemOperand if it is a target mem intrinsic. 1801 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering(); 1802 TargetLowering::IntrinsicInfo Info; 1803 // TODO: Add a GlobalISel version of getTgtMemIntrinsic. 1804 if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) { 1805 Align Alignment = Info.align.getValueOr( 1806 DL->getABITypeAlign(Info.memVT.getTypeForEVT(F->getContext()))); 1807 1808 uint64_t Size = Info.memVT.getStoreSize(); 1809 MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal), 1810 Info.flags, Size, Alignment)); 1811 } 1812 1813 return true; 1814 } 1815 1816 bool IRTranslator::translateInvoke(const User &U, 1817 MachineIRBuilder &MIRBuilder) { 1818 const InvokeInst &I = cast<InvokeInst>(U); 1819 MCContext &Context = MF->getContext(); 1820 1821 const BasicBlock *ReturnBB = I.getSuccessor(0); 1822 const BasicBlock *EHPadBB = I.getSuccessor(1); 1823 1824 const Function *Fn = I.getCalledFunction(); 1825 if (I.isInlineAsm()) 1826 return false; 1827 1828 // FIXME: support invoking patchpoint and statepoint intrinsics. 1829 if (Fn && Fn->isIntrinsic()) 1830 return false; 1831 1832 // FIXME: support whatever these are. 1833 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 1834 return false; 1835 1836 // FIXME: support control flow guard targets. 1837 if (I.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget)) 1838 return false; 1839 1840 // FIXME: support Windows exception handling. 1841 if (!isa<LandingPadInst>(EHPadBB->front())) 1842 return false; 1843 1844 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about 1845 // the region covered by the try. 1846 MCSymbol *BeginSymbol = Context.createTempSymbol(); 1847 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol); 1848 1849 if (!translateCallBase(I, MIRBuilder)) 1850 return false; 1851 1852 MCSymbol *EndSymbol = Context.createTempSymbol(); 1853 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol); 1854 1855 // FIXME: track probabilities. 1856 MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB), 1857 &ReturnMBB = getMBB(*ReturnBB); 1858 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol); 1859 MIRBuilder.getMBB().addSuccessor(&ReturnMBB); 1860 MIRBuilder.getMBB().addSuccessor(&EHPadMBB); 1861 MIRBuilder.buildBr(ReturnMBB); 1862 1863 return true; 1864 } 1865 1866 bool IRTranslator::translateCallBr(const User &U, 1867 MachineIRBuilder &MIRBuilder) { 1868 // FIXME: Implement this. 1869 return false; 1870 } 1871 1872 bool IRTranslator::translateLandingPad(const User &U, 1873 MachineIRBuilder &MIRBuilder) { 1874 const LandingPadInst &LP = cast<LandingPadInst>(U); 1875 1876 MachineBasicBlock &MBB = MIRBuilder.getMBB(); 1877 1878 MBB.setIsEHPad(); 1879 1880 // If there aren't registers to copy the values into (e.g., during SjLj 1881 // exceptions), then don't bother. 1882 auto &TLI = *MF->getSubtarget().getTargetLowering(); 1883 const Constant *PersonalityFn = MF->getFunction().getPersonalityFn(); 1884 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 1885 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 1886 return true; 1887 1888 // If landingpad's return type is token type, we don't create DAG nodes 1889 // for its exception pointer and selector value. The extraction of exception 1890 // pointer or selector value from token type landingpads is not currently 1891 // supported. 1892 if (LP.getType()->isTokenTy()) 1893 return true; 1894 1895 // Add a label to mark the beginning of the landing pad. Deletion of the 1896 // landing pad can thus be detected via the MachineModuleInfo. 1897 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL) 1898 .addSym(MF->addLandingPad(&MBB)); 1899 1900 LLT Ty = getLLTForType(*LP.getType(), *DL); 1901 Register Undef = MRI->createGenericVirtualRegister(Ty); 1902 MIRBuilder.buildUndef(Undef); 1903 1904 SmallVector<LLT, 2> Tys; 1905 for (Type *Ty : cast<StructType>(LP.getType())->elements()) 1906 Tys.push_back(getLLTForType(*Ty, *DL)); 1907 assert(Tys.size() == 2 && "Only two-valued landingpads are supported"); 1908 1909 // Mark exception register as live in. 1910 Register ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn); 1911 if (!ExceptionReg) 1912 return false; 1913 1914 MBB.addLiveIn(ExceptionReg); 1915 ArrayRef<Register> ResRegs = getOrCreateVRegs(LP); 1916 MIRBuilder.buildCopy(ResRegs[0], ExceptionReg); 1917 1918 Register SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn); 1919 if (!SelectorReg) 1920 return false; 1921 1922 MBB.addLiveIn(SelectorReg); 1923 Register PtrVReg = MRI->createGenericVirtualRegister(Tys[0]); 1924 MIRBuilder.buildCopy(PtrVReg, SelectorReg); 1925 MIRBuilder.buildCast(ResRegs[1], PtrVReg); 1926 1927 return true; 1928 } 1929 1930 bool IRTranslator::translateAlloca(const User &U, 1931 MachineIRBuilder &MIRBuilder) { 1932 auto &AI = cast<AllocaInst>(U); 1933 1934 if (AI.isSwiftError()) 1935 return true; 1936 1937 if (AI.isStaticAlloca()) { 1938 Register Res = getOrCreateVReg(AI); 1939 int FI = getOrCreateFrameIndex(AI); 1940 MIRBuilder.buildFrameIndex(Res, FI); 1941 return true; 1942 } 1943 1944 // FIXME: support stack probing for Windows. 1945 if (MF->getTarget().getTargetTriple().isOSWindows()) 1946 return false; 1947 1948 // Now we're in the harder dynamic case. 1949 Register NumElts = getOrCreateVReg(*AI.getArraySize()); 1950 Type *IntPtrIRTy = DL->getIntPtrType(AI.getType()); 1951 LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL); 1952 if (MRI->getType(NumElts) != IntPtrTy) { 1953 Register ExtElts = MRI->createGenericVirtualRegister(IntPtrTy); 1954 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts); 1955 NumElts = ExtElts; 1956 } 1957 1958 Type *Ty = AI.getAllocatedType(); 1959 1960 Register AllocSize = MRI->createGenericVirtualRegister(IntPtrTy); 1961 Register TySize = 1962 getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, DL->getTypeAllocSize(Ty))); 1963 MIRBuilder.buildMul(AllocSize, NumElts, TySize); 1964 1965 // Round the size of the allocation up to the stack alignment size 1966 // by add SA-1 to the size. This doesn't overflow because we're computing 1967 // an address inside an alloca. 1968 Align StackAlign = MF->getSubtarget().getFrameLowering()->getStackAlign(); 1969 auto SAMinusOne = MIRBuilder.buildConstant(IntPtrTy, StackAlign.value() - 1); 1970 auto AllocAdd = MIRBuilder.buildAdd(IntPtrTy, AllocSize, SAMinusOne, 1971 MachineInstr::NoUWrap); 1972 auto AlignCst = 1973 MIRBuilder.buildConstant(IntPtrTy, ~(uint64_t)(StackAlign.value() - 1)); 1974 auto AlignedAlloc = MIRBuilder.buildAnd(IntPtrTy, AllocAdd, AlignCst); 1975 1976 Align Alignment = std::max(AI.getAlign(), DL->getPrefTypeAlign(Ty)); 1977 if (Alignment <= StackAlign) 1978 Alignment = Align(1); 1979 MIRBuilder.buildDynStackAlloc(getOrCreateVReg(AI), AlignedAlloc, Alignment); 1980 1981 MF->getFrameInfo().CreateVariableSizedObject(Alignment, &AI); 1982 assert(MF->getFrameInfo().hasVarSizedObjects()); 1983 return true; 1984 } 1985 1986 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) { 1987 // FIXME: We may need more info about the type. Because of how LLT works, 1988 // we're completely discarding the i64/double distinction here (amongst 1989 // others). Fortunately the ABIs I know of where that matters don't use va_arg 1990 // anyway but that's not guaranteed. 1991 MIRBuilder.buildInstr(TargetOpcode::G_VAARG, {getOrCreateVReg(U)}, 1992 {getOrCreateVReg(*U.getOperand(0)), 1993 DL->getABITypeAlign(U.getType()).value()}); 1994 return true; 1995 } 1996 1997 bool IRTranslator::translateInsertElement(const User &U, 1998 MachineIRBuilder &MIRBuilder) { 1999 // If it is a <1 x Ty> vector, use the scalar as it is 2000 // not a legal vector type in LLT. 2001 if (cast<FixedVectorType>(U.getType())->getNumElements() == 1) 2002 return translateCopy(U, *U.getOperand(1), MIRBuilder); 2003 2004 Register Res = getOrCreateVReg(U); 2005 Register Val = getOrCreateVReg(*U.getOperand(0)); 2006 Register Elt = getOrCreateVReg(*U.getOperand(1)); 2007 Register Idx = getOrCreateVReg(*U.getOperand(2)); 2008 MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx); 2009 return true; 2010 } 2011 2012 bool IRTranslator::translateExtractElement(const User &U, 2013 MachineIRBuilder &MIRBuilder) { 2014 // If it is a <1 x Ty> vector, use the scalar as it is 2015 // not a legal vector type in LLT. 2016 if (cast<FixedVectorType>(U.getOperand(0)->getType())->getNumElements() == 1) 2017 return translateCopy(U, *U.getOperand(0), MIRBuilder); 2018 2019 Register Res = getOrCreateVReg(U); 2020 Register Val = getOrCreateVReg(*U.getOperand(0)); 2021 const auto &TLI = *MF->getSubtarget().getTargetLowering(); 2022 unsigned PreferredVecIdxWidth = TLI.getVectorIdxTy(*DL).getSizeInBits(); 2023 Register Idx; 2024 if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(1))) { 2025 if (CI->getBitWidth() != PreferredVecIdxWidth) { 2026 APInt NewIdx = CI->getValue().sextOrTrunc(PreferredVecIdxWidth); 2027 auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx); 2028 Idx = getOrCreateVReg(*NewIdxCI); 2029 } 2030 } 2031 if (!Idx) 2032 Idx = getOrCreateVReg(*U.getOperand(1)); 2033 if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) { 2034 const LLT VecIdxTy = LLT::scalar(PreferredVecIdxWidth); 2035 Idx = MIRBuilder.buildSExtOrTrunc(VecIdxTy, Idx).getReg(0); 2036 } 2037 MIRBuilder.buildExtractVectorElement(Res, Val, Idx); 2038 return true; 2039 } 2040 2041 bool IRTranslator::translateShuffleVector(const User &U, 2042 MachineIRBuilder &MIRBuilder) { 2043 ArrayRef<int> Mask; 2044 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&U)) 2045 Mask = SVI->getShuffleMask(); 2046 else 2047 Mask = cast<ConstantExpr>(U).getShuffleMask(); 2048 ArrayRef<int> MaskAlloc = MF->allocateShuffleMask(Mask); 2049 MIRBuilder 2050 .buildInstr(TargetOpcode::G_SHUFFLE_VECTOR, {getOrCreateVReg(U)}, 2051 {getOrCreateVReg(*U.getOperand(0)), 2052 getOrCreateVReg(*U.getOperand(1))}) 2053 .addShuffleMask(MaskAlloc); 2054 return true; 2055 } 2056 2057 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) { 2058 const PHINode &PI = cast<PHINode>(U); 2059 2060 SmallVector<MachineInstr *, 4> Insts; 2061 for (auto Reg : getOrCreateVRegs(PI)) { 2062 auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, {Reg}, {}); 2063 Insts.push_back(MIB.getInstr()); 2064 } 2065 2066 PendingPHIs.emplace_back(&PI, std::move(Insts)); 2067 return true; 2068 } 2069 2070 bool IRTranslator::translateAtomicCmpXchg(const User &U, 2071 MachineIRBuilder &MIRBuilder) { 2072 const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U); 2073 2074 auto &TLI = *MF->getSubtarget().getTargetLowering(); 2075 auto Flags = TLI.getAtomicMemOperandFlags(I, *DL); 2076 2077 Type *ResType = I.getType(); 2078 Type *ValType = ResType->Type::getStructElementType(0); 2079 2080 auto Res = getOrCreateVRegs(I); 2081 Register OldValRes = Res[0]; 2082 Register SuccessRes = Res[1]; 2083 Register Addr = getOrCreateVReg(*I.getPointerOperand()); 2084 Register Cmp = getOrCreateVReg(*I.getCompareOperand()); 2085 Register NewVal = getOrCreateVReg(*I.getNewValOperand()); 2086 2087 AAMDNodes AAMetadata; 2088 I.getAAMetadata(AAMetadata); 2089 2090 MIRBuilder.buildAtomicCmpXchgWithSuccess( 2091 OldValRes, SuccessRes, Addr, Cmp, NewVal, 2092 *MF->getMachineMemOperand( 2093 MachinePointerInfo(I.getPointerOperand()), Flags, 2094 DL->getTypeStoreSize(ValType), getMemOpAlign(I), AAMetadata, nullptr, 2095 I.getSyncScopeID(), I.getSuccessOrdering(), I.getFailureOrdering())); 2096 return true; 2097 } 2098 2099 bool IRTranslator::translateAtomicRMW(const User &U, 2100 MachineIRBuilder &MIRBuilder) { 2101 const AtomicRMWInst &I = cast<AtomicRMWInst>(U); 2102 auto &TLI = *MF->getSubtarget().getTargetLowering(); 2103 auto Flags = TLI.getAtomicMemOperandFlags(I, *DL); 2104 2105 Type *ResType = I.getType(); 2106 2107 Register Res = getOrCreateVReg(I); 2108 Register Addr = getOrCreateVReg(*I.getPointerOperand()); 2109 Register Val = getOrCreateVReg(*I.getValOperand()); 2110 2111 unsigned Opcode = 0; 2112 switch (I.getOperation()) { 2113 default: 2114 return false; 2115 case AtomicRMWInst::Xchg: 2116 Opcode = TargetOpcode::G_ATOMICRMW_XCHG; 2117 break; 2118 case AtomicRMWInst::Add: 2119 Opcode = TargetOpcode::G_ATOMICRMW_ADD; 2120 break; 2121 case AtomicRMWInst::Sub: 2122 Opcode = TargetOpcode::G_ATOMICRMW_SUB; 2123 break; 2124 case AtomicRMWInst::And: 2125 Opcode = TargetOpcode::G_ATOMICRMW_AND; 2126 break; 2127 case AtomicRMWInst::Nand: 2128 Opcode = TargetOpcode::G_ATOMICRMW_NAND; 2129 break; 2130 case AtomicRMWInst::Or: 2131 Opcode = TargetOpcode::G_ATOMICRMW_OR; 2132 break; 2133 case AtomicRMWInst::Xor: 2134 Opcode = TargetOpcode::G_ATOMICRMW_XOR; 2135 break; 2136 case AtomicRMWInst::Max: 2137 Opcode = TargetOpcode::G_ATOMICRMW_MAX; 2138 break; 2139 case AtomicRMWInst::Min: 2140 Opcode = TargetOpcode::G_ATOMICRMW_MIN; 2141 break; 2142 case AtomicRMWInst::UMax: 2143 Opcode = TargetOpcode::G_ATOMICRMW_UMAX; 2144 break; 2145 case AtomicRMWInst::UMin: 2146 Opcode = TargetOpcode::G_ATOMICRMW_UMIN; 2147 break; 2148 case AtomicRMWInst::FAdd: 2149 Opcode = TargetOpcode::G_ATOMICRMW_FADD; 2150 break; 2151 case AtomicRMWInst::FSub: 2152 Opcode = TargetOpcode::G_ATOMICRMW_FSUB; 2153 break; 2154 } 2155 2156 AAMDNodes AAMetadata; 2157 I.getAAMetadata(AAMetadata); 2158 2159 MIRBuilder.buildAtomicRMW( 2160 Opcode, Res, Addr, Val, 2161 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 2162 Flags, DL->getTypeStoreSize(ResType), 2163 getMemOpAlign(I), AAMetadata, nullptr, 2164 I.getSyncScopeID(), I.getOrdering())); 2165 return true; 2166 } 2167 2168 bool IRTranslator::translateFence(const User &U, 2169 MachineIRBuilder &MIRBuilder) { 2170 const FenceInst &Fence = cast<FenceInst>(U); 2171 MIRBuilder.buildFence(static_cast<unsigned>(Fence.getOrdering()), 2172 Fence.getSyncScopeID()); 2173 return true; 2174 } 2175 2176 bool IRTranslator::translateFreeze(const User &U, 2177 MachineIRBuilder &MIRBuilder) { 2178 const ArrayRef<Register> DstRegs = getOrCreateVRegs(U); 2179 const ArrayRef<Register> SrcRegs = getOrCreateVRegs(*U.getOperand(0)); 2180 2181 assert(DstRegs.size() == SrcRegs.size() && 2182 "Freeze with different source and destination type?"); 2183 2184 for (unsigned I = 0; I < DstRegs.size(); ++I) { 2185 MIRBuilder.buildFreeze(DstRegs[I], SrcRegs[I]); 2186 } 2187 2188 return true; 2189 } 2190 2191 void IRTranslator::finishPendingPhis() { 2192 #ifndef NDEBUG 2193 DILocationVerifier Verifier; 2194 GISelObserverWrapper WrapperObserver(&Verifier); 2195 RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver); 2196 #endif // ifndef NDEBUG 2197 for (auto &Phi : PendingPHIs) { 2198 const PHINode *PI = Phi.first; 2199 ArrayRef<MachineInstr *> ComponentPHIs = Phi.second; 2200 MachineBasicBlock *PhiMBB = ComponentPHIs[0]->getParent(); 2201 EntryBuilder->setDebugLoc(PI->getDebugLoc()); 2202 #ifndef NDEBUG 2203 Verifier.setCurrentInst(PI); 2204 #endif // ifndef NDEBUG 2205 2206 SmallSet<const MachineBasicBlock *, 16> SeenPreds; 2207 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) { 2208 auto IRPred = PI->getIncomingBlock(i); 2209 ArrayRef<Register> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i)); 2210 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) { 2211 if (SeenPreds.count(Pred) || !PhiMBB->isPredecessor(Pred)) 2212 continue; 2213 SeenPreds.insert(Pred); 2214 for (unsigned j = 0; j < ValRegs.size(); ++j) { 2215 MachineInstrBuilder MIB(*MF, ComponentPHIs[j]); 2216 MIB.addUse(ValRegs[j]); 2217 MIB.addMBB(Pred); 2218 } 2219 } 2220 } 2221 } 2222 } 2223 2224 bool IRTranslator::valueIsSplit(const Value &V, 2225 SmallVectorImpl<uint64_t> *Offsets) { 2226 SmallVector<LLT, 4> SplitTys; 2227 if (Offsets && !Offsets->empty()) 2228 Offsets->clear(); 2229 computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets); 2230 return SplitTys.size() > 1; 2231 } 2232 2233 bool IRTranslator::translate(const Instruction &Inst) { 2234 CurBuilder->setDebugLoc(Inst.getDebugLoc()); 2235 // We only emit constants into the entry block from here. To prevent jumpy 2236 // debug behaviour set the line to 0. 2237 if (const DebugLoc &DL = Inst.getDebugLoc()) 2238 EntryBuilder->setDebugLoc( 2239 DebugLoc::get(0, 0, DL.getScope(), DL.getInlinedAt())); 2240 else 2241 EntryBuilder->setDebugLoc(DebugLoc()); 2242 2243 auto &TLI = *MF->getSubtarget().getTargetLowering(); 2244 if (TLI.fallBackToDAGISel(Inst)) 2245 return false; 2246 2247 switch (Inst.getOpcode()) { 2248 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 2249 case Instruction::OPCODE: \ 2250 return translate##OPCODE(Inst, *CurBuilder.get()); 2251 #include "llvm/IR/Instruction.def" 2252 default: 2253 return false; 2254 } 2255 } 2256 2257 bool IRTranslator::translate(const Constant &C, Register Reg) { 2258 if (auto CI = dyn_cast<ConstantInt>(&C)) 2259 EntryBuilder->buildConstant(Reg, *CI); 2260 else if (auto CF = dyn_cast<ConstantFP>(&C)) 2261 EntryBuilder->buildFConstant(Reg, *CF); 2262 else if (isa<UndefValue>(C)) 2263 EntryBuilder->buildUndef(Reg); 2264 else if (isa<ConstantPointerNull>(C)) 2265 EntryBuilder->buildConstant(Reg, 0); 2266 else if (auto GV = dyn_cast<GlobalValue>(&C)) 2267 EntryBuilder->buildGlobalValue(Reg, GV); 2268 else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) { 2269 if (!CAZ->getType()->isVectorTy()) 2270 return false; 2271 // Return the scalar if it is a <1 x Ty> vector. 2272 if (CAZ->getNumElements() == 1) 2273 return translateCopy(C, *CAZ->getElementValue(0u), *EntryBuilder.get()); 2274 SmallVector<Register, 4> Ops; 2275 for (unsigned i = 0; i < CAZ->getNumElements(); ++i) { 2276 Constant &Elt = *CAZ->getElementValue(i); 2277 Ops.push_back(getOrCreateVReg(Elt)); 2278 } 2279 EntryBuilder->buildBuildVector(Reg, Ops); 2280 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) { 2281 // Return the scalar if it is a <1 x Ty> vector. 2282 if (CV->getNumElements() == 1) 2283 return translateCopy(C, *CV->getElementAsConstant(0), 2284 *EntryBuilder.get()); 2285 SmallVector<Register, 4> Ops; 2286 for (unsigned i = 0; i < CV->getNumElements(); ++i) { 2287 Constant &Elt = *CV->getElementAsConstant(i); 2288 Ops.push_back(getOrCreateVReg(Elt)); 2289 } 2290 EntryBuilder->buildBuildVector(Reg, Ops); 2291 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) { 2292 switch(CE->getOpcode()) { 2293 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 2294 case Instruction::OPCODE: \ 2295 return translate##OPCODE(*CE, *EntryBuilder.get()); 2296 #include "llvm/IR/Instruction.def" 2297 default: 2298 return false; 2299 } 2300 } else if (auto CV = dyn_cast<ConstantVector>(&C)) { 2301 if (CV->getNumOperands() == 1) 2302 return translateCopy(C, *CV->getOperand(0), *EntryBuilder.get()); 2303 SmallVector<Register, 4> Ops; 2304 for (unsigned i = 0; i < CV->getNumOperands(); ++i) { 2305 Ops.push_back(getOrCreateVReg(*CV->getOperand(i))); 2306 } 2307 EntryBuilder->buildBuildVector(Reg, Ops); 2308 } else if (auto *BA = dyn_cast<BlockAddress>(&C)) { 2309 EntryBuilder->buildBlockAddress(Reg, BA); 2310 } else 2311 return false; 2312 2313 return true; 2314 } 2315 2316 void IRTranslator::finalizeBasicBlock() { 2317 for (auto &JTCase : SL->JTCases) { 2318 // Emit header first, if it wasn't already emitted. 2319 if (!JTCase.first.Emitted) 2320 emitJumpTableHeader(JTCase.second, JTCase.first, JTCase.first.HeaderBB); 2321 2322 emitJumpTable(JTCase.second, JTCase.second.MBB); 2323 } 2324 SL->JTCases.clear(); 2325 } 2326 2327 void IRTranslator::finalizeFunction() { 2328 // Release the memory used by the different maps we 2329 // needed during the translation. 2330 PendingPHIs.clear(); 2331 VMap.reset(); 2332 FrameIndices.clear(); 2333 MachinePreds.clear(); 2334 // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it 2335 // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid 2336 // destroying it twice (in ~IRTranslator() and ~LLVMContext()) 2337 EntryBuilder.reset(); 2338 CurBuilder.reset(); 2339 FuncInfo.clear(); 2340 } 2341 2342 /// Returns true if a BasicBlock \p BB within a variadic function contains a 2343 /// variadic musttail call. 2344 static bool checkForMustTailInVarArgFn(bool IsVarArg, const BasicBlock &BB) { 2345 if (!IsVarArg) 2346 return false; 2347 2348 // Walk the block backwards, because tail calls usually only appear at the end 2349 // of a block. 2350 return std::any_of(BB.rbegin(), BB.rend(), [](const Instruction &I) { 2351 const auto *CI = dyn_cast<CallInst>(&I); 2352 return CI && CI->isMustTailCall(); 2353 }); 2354 } 2355 2356 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) { 2357 MF = &CurMF; 2358 const Function &F = MF->getFunction(); 2359 if (F.empty()) 2360 return false; 2361 GISelCSEAnalysisWrapper &Wrapper = 2362 getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper(); 2363 // Set the CSEConfig and run the analysis. 2364 GISelCSEInfo *CSEInfo = nullptr; 2365 TPC = &getAnalysis<TargetPassConfig>(); 2366 bool EnableCSE = EnableCSEInIRTranslator.getNumOccurrences() 2367 ? EnableCSEInIRTranslator 2368 : TPC->isGISelCSEEnabled(); 2369 2370 if (EnableCSE) { 2371 EntryBuilder = std::make_unique<CSEMIRBuilder>(CurMF); 2372 CSEInfo = &Wrapper.get(TPC->getCSEConfig()); 2373 EntryBuilder->setCSEInfo(CSEInfo); 2374 CurBuilder = std::make_unique<CSEMIRBuilder>(CurMF); 2375 CurBuilder->setCSEInfo(CSEInfo); 2376 } else { 2377 EntryBuilder = std::make_unique<MachineIRBuilder>(); 2378 CurBuilder = std::make_unique<MachineIRBuilder>(); 2379 } 2380 CLI = MF->getSubtarget().getCallLowering(); 2381 CurBuilder->setMF(*MF); 2382 EntryBuilder->setMF(*MF); 2383 MRI = &MF->getRegInfo(); 2384 DL = &F.getParent()->getDataLayout(); 2385 ORE = std::make_unique<OptimizationRemarkEmitter>(&F); 2386 FuncInfo.MF = MF; 2387 FuncInfo.BPI = nullptr; 2388 const auto &TLI = *MF->getSubtarget().getTargetLowering(); 2389 const TargetMachine &TM = MF->getTarget(); 2390 SL = std::make_unique<GISelSwitchLowering>(this, FuncInfo); 2391 SL->init(TLI, TM, *DL); 2392 2393 EnableOpts = TM.getOptLevel() != CodeGenOpt::None && !skipFunction(F); 2394 2395 assert(PendingPHIs.empty() && "stale PHIs"); 2396 2397 if (!DL->isLittleEndian()) { 2398 // Currently we don't properly handle big endian code. 2399 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 2400 F.getSubprogram(), &F.getEntryBlock()); 2401 R << "unable to translate in big endian mode"; 2402 reportTranslationError(*MF, *TPC, *ORE, R); 2403 } 2404 2405 // Release the per-function state when we return, whether we succeeded or not. 2406 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); }); 2407 2408 // Setup a separate basic-block for the arguments and constants 2409 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock(); 2410 MF->push_back(EntryBB); 2411 EntryBuilder->setMBB(*EntryBB); 2412 2413 DebugLoc DbgLoc = F.getEntryBlock().getFirstNonPHI()->getDebugLoc(); 2414 SwiftError.setFunction(CurMF); 2415 SwiftError.createEntriesInEntryBlock(DbgLoc); 2416 2417 bool IsVarArg = F.isVarArg(); 2418 bool HasMustTailInVarArgFn = false; 2419 2420 // Create all blocks, in IR order, to preserve the layout. 2421 for (const BasicBlock &BB: F) { 2422 auto *&MBB = BBToMBB[&BB]; 2423 2424 MBB = MF->CreateMachineBasicBlock(&BB); 2425 MF->push_back(MBB); 2426 2427 if (BB.hasAddressTaken()) 2428 MBB->setHasAddressTaken(); 2429 2430 if (!HasMustTailInVarArgFn) 2431 HasMustTailInVarArgFn = checkForMustTailInVarArgFn(IsVarArg, BB); 2432 } 2433 2434 MF->getFrameInfo().setHasMustTailInVarArgFunc(HasMustTailInVarArgFn); 2435 2436 // Make our arguments/constants entry block fallthrough to the IR entry block. 2437 EntryBB->addSuccessor(&getMBB(F.front())); 2438 2439 if (CLI->fallBackToDAGISel(F)) { 2440 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 2441 F.getSubprogram(), &F.getEntryBlock()); 2442 R << "unable to lower function: " << ore::NV("Prototype", F.getType()); 2443 reportTranslationError(*MF, *TPC, *ORE, R); 2444 return false; 2445 } 2446 2447 // Lower the actual args into this basic block. 2448 SmallVector<ArrayRef<Register>, 8> VRegArgs; 2449 for (const Argument &Arg: F.args()) { 2450 if (DL->getTypeStoreSize(Arg.getType()).isZero()) 2451 continue; // Don't handle zero sized types. 2452 ArrayRef<Register> VRegs = getOrCreateVRegs(Arg); 2453 VRegArgs.push_back(VRegs); 2454 2455 if (Arg.hasSwiftErrorAttr()) { 2456 assert(VRegs.size() == 1 && "Too many vregs for Swift error"); 2457 SwiftError.setCurrentVReg(EntryBB, SwiftError.getFunctionArg(), VRegs[0]); 2458 } 2459 } 2460 2461 if (!CLI->lowerFormalArguments(*EntryBuilder.get(), F, VRegArgs)) { 2462 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 2463 F.getSubprogram(), &F.getEntryBlock()); 2464 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType()); 2465 reportTranslationError(*MF, *TPC, *ORE, R); 2466 return false; 2467 } 2468 2469 // Need to visit defs before uses when translating instructions. 2470 GISelObserverWrapper WrapperObserver; 2471 if (EnableCSE && CSEInfo) 2472 WrapperObserver.addObserver(CSEInfo); 2473 { 2474 ReversePostOrderTraversal<const Function *> RPOT(&F); 2475 #ifndef NDEBUG 2476 DILocationVerifier Verifier; 2477 WrapperObserver.addObserver(&Verifier); 2478 #endif // ifndef NDEBUG 2479 RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver); 2480 RAIIMFObserverInstaller ObsInstall(*MF, WrapperObserver); 2481 for (const BasicBlock *BB : RPOT) { 2482 MachineBasicBlock &MBB = getMBB(*BB); 2483 // Set the insertion point of all the following translations to 2484 // the end of this basic block. 2485 CurBuilder->setMBB(MBB); 2486 HasTailCall = false; 2487 for (const Instruction &Inst : *BB) { 2488 // If we translated a tail call in the last step, then we know 2489 // everything after the call is either a return, or something that is 2490 // handled by the call itself. (E.g. a lifetime marker or assume 2491 // intrinsic.) In this case, we should stop translating the block and 2492 // move on. 2493 if (HasTailCall) 2494 break; 2495 #ifndef NDEBUG 2496 Verifier.setCurrentInst(&Inst); 2497 #endif // ifndef NDEBUG 2498 if (translate(Inst)) 2499 continue; 2500 2501 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 2502 Inst.getDebugLoc(), BB); 2503 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst); 2504 2505 if (ORE->allowExtraAnalysis("gisel-irtranslator")) { 2506 std::string InstStrStorage; 2507 raw_string_ostream InstStr(InstStrStorage); 2508 InstStr << Inst; 2509 2510 R << ": '" << InstStr.str() << "'"; 2511 } 2512 2513 reportTranslationError(*MF, *TPC, *ORE, R); 2514 return false; 2515 } 2516 2517 finalizeBasicBlock(); 2518 } 2519 #ifndef NDEBUG 2520 WrapperObserver.removeObserver(&Verifier); 2521 #endif 2522 } 2523 2524 finishPendingPhis(); 2525 2526 SwiftError.propagateVRegs(); 2527 2528 // Merge the argument lowering and constants block with its single 2529 // successor, the LLVM-IR entry block. We want the basic block to 2530 // be maximal. 2531 assert(EntryBB->succ_size() == 1 && 2532 "Custom BB used for lowering should have only one successor"); 2533 // Get the successor of the current entry block. 2534 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin(); 2535 assert(NewEntryBB.pred_size() == 1 && 2536 "LLVM-IR entry block has a predecessor!?"); 2537 // Move all the instruction from the current entry block to the 2538 // new entry block. 2539 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(), 2540 EntryBB->end()); 2541 2542 // Update the live-in information for the new entry block. 2543 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins()) 2544 NewEntryBB.addLiveIn(LiveIn); 2545 NewEntryBB.sortUniqueLiveIns(); 2546 2547 // Get rid of the now empty basic block. 2548 EntryBB->removeSuccessor(&NewEntryBB); 2549 MF->remove(EntryBB); 2550 MF->DeleteMachineBasicBlock(EntryBB); 2551 2552 assert(&MF->front() == &NewEntryBB && 2553 "New entry wasn't next in the list of basic block!"); 2554 2555 // Initialize stack protector information. 2556 StackProtector &SP = getAnalysis<StackProtector>(); 2557 SP.copyToMachineFrameInfo(MF->getFrameInfo()); 2558 2559 return false; 2560 } 2561