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