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/MachineModuleInfo.h" 33 #include "llvm/CodeGen/MachineOperand.h" 34 #include "llvm/CodeGen/MachineRegisterInfo.h" 35 #include "llvm/CodeGen/StackProtector.h" 36 #include "llvm/CodeGen/SwitchLoweringUtils.h" 37 #include "llvm/CodeGen/TargetFrameLowering.h" 38 #include "llvm/CodeGen/TargetInstrInfo.h" 39 #include "llvm/CodeGen/TargetLowering.h" 40 #include "llvm/CodeGen/TargetPassConfig.h" 41 #include "llvm/CodeGen/TargetRegisterInfo.h" 42 #include "llvm/CodeGen/TargetSubtargetInfo.h" 43 #include "llvm/IR/BasicBlock.h" 44 #include "llvm/IR/CFG.h" 45 #include "llvm/IR/Constant.h" 46 #include "llvm/IR/Constants.h" 47 #include "llvm/IR/DataLayout.h" 48 #include "llvm/IR/DebugInfo.h" 49 #include "llvm/IR/DerivedTypes.h" 50 #include "llvm/IR/Function.h" 51 #include "llvm/IR/GetElementPtrTypeIterator.h" 52 #include "llvm/IR/InlineAsm.h" 53 #include "llvm/IR/InstrTypes.h" 54 #include "llvm/IR/Instructions.h" 55 #include "llvm/IR/IntrinsicInst.h" 56 #include "llvm/IR/Intrinsics.h" 57 #include "llvm/IR/LLVMContext.h" 58 #include "llvm/IR/Metadata.h" 59 #include "llvm/IR/PatternMatch.h" 60 #include "llvm/IR/Type.h" 61 #include "llvm/IR/User.h" 62 #include "llvm/IR/Value.h" 63 #include "llvm/InitializePasses.h" 64 #include "llvm/MC/MCContext.h" 65 #include "llvm/Pass.h" 66 #include "llvm/Support/Casting.h" 67 #include "llvm/Support/CodeGen.h" 68 #include "llvm/Support/Debug.h" 69 #include "llvm/Support/ErrorHandling.h" 70 #include "llvm/Support/LowLevelTypeImpl.h" 71 #include "llvm/Support/MathExtras.h" 72 #include "llvm/Support/raw_ostream.h" 73 #include "llvm/Target/TargetIntrinsicInfo.h" 74 #include "llvm/Target/TargetMachine.h" 75 #include <algorithm> 76 #include <cassert> 77 #include <cstddef> 78 #include <cstdint> 79 #include <iterator> 80 #include <string> 81 #include <utility> 82 #include <vector> 83 84 #define DEBUG_TYPE "irtranslator" 85 86 using namespace llvm; 87 88 static cl::opt<bool> 89 EnableCSEInIRTranslator("enable-cse-in-irtranslator", 90 cl::desc("Should enable CSE in irtranslator"), 91 cl::Optional, cl::init(false)); 92 char IRTranslator::ID = 0; 93 94 INITIALIZE_PASS_BEGIN(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI", 95 false, false) 96 INITIALIZE_PASS_DEPENDENCY(TargetPassConfig) 97 INITIALIZE_PASS_DEPENDENCY(GISelCSEAnalysisWrapperPass) 98 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) 99 INITIALIZE_PASS_DEPENDENCY(StackProtector) 100 INITIALIZE_PASS_END(IRTranslator, DEBUG_TYPE, "IRTranslator LLVM IR -> MI", 101 false, false) 102 103 static void reportTranslationError(MachineFunction &MF, 104 const TargetPassConfig &TPC, 105 OptimizationRemarkEmitter &ORE, 106 OptimizationRemarkMissed &R) { 107 MF.getProperties().set(MachineFunctionProperties::Property::FailedISel); 108 109 // Print the function name explicitly if we don't have a debug location (which 110 // makes the diagnostic less useful) or if we're going to emit a raw error. 111 if (!R.getLocation().isValid() || TPC.isGlobalISelAbortEnabled()) 112 R << (" (in function: " + MF.getName() + ")").str(); 113 114 if (TPC.isGlobalISelAbortEnabled()) 115 report_fatal_error(R.getMsg()); 116 else 117 ORE.emit(R); 118 } 119 120 IRTranslator::IRTranslator(CodeGenOpt::Level optlevel) 121 : MachineFunctionPass(ID), OptLevel(optlevel) {} 122 123 #ifndef NDEBUG 124 namespace { 125 /// Verify that every instruction created has the same DILocation as the 126 /// instruction being translated. 127 class DILocationVerifier : public GISelChangeObserver { 128 const Instruction *CurrInst = nullptr; 129 130 public: 131 DILocationVerifier() = default; 132 ~DILocationVerifier() = default; 133 134 const Instruction *getCurrentInst() const { return CurrInst; } 135 void setCurrentInst(const Instruction *Inst) { CurrInst = Inst; } 136 137 void erasingInstr(MachineInstr &MI) override {} 138 void changingInstr(MachineInstr &MI) override {} 139 void changedInstr(MachineInstr &MI) override {} 140 141 void createdInstr(MachineInstr &MI) override { 142 assert(getCurrentInst() && "Inserted instruction without a current MI"); 143 144 // Only print the check message if we're actually checking it. 145 #ifndef NDEBUG 146 LLVM_DEBUG(dbgs() << "Checking DILocation from " << *CurrInst 147 << " was copied to " << MI); 148 #endif 149 // We allow insts in the entry block to have a debug loc line of 0 because 150 // they could have originated from constants, and we don't want a jumpy 151 // debug experience. 152 assert((CurrInst->getDebugLoc() == MI.getDebugLoc() || 153 MI.getDebugLoc().getLine() == 0) && 154 "Line info was not transferred to all instructions"); 155 } 156 }; 157 } // namespace 158 #endif // ifndef NDEBUG 159 160 161 void IRTranslator::getAnalysisUsage(AnalysisUsage &AU) const { 162 AU.addRequired<StackProtector>(); 163 AU.addRequired<TargetPassConfig>(); 164 AU.addRequired<GISelCSEAnalysisWrapperPass>(); 165 if (OptLevel != CodeGenOpt::None) 166 AU.addRequired<BranchProbabilityInfoWrapperPass>(); 167 getSelectionDAGFallbackAnalysisUsage(AU); 168 MachineFunctionPass::getAnalysisUsage(AU); 169 } 170 171 IRTranslator::ValueToVRegInfo::VRegListT & 172 IRTranslator::allocateVRegs(const Value &Val) { 173 auto VRegsIt = VMap.findVRegs(Val); 174 if (VRegsIt != VMap.vregs_end()) 175 return *VRegsIt->second; 176 auto *Regs = VMap.getVRegs(Val); 177 auto *Offsets = VMap.getOffsets(Val); 178 SmallVector<LLT, 4> SplitTys; 179 computeValueLLTs(*DL, *Val.getType(), SplitTys, 180 Offsets->empty() ? Offsets : nullptr); 181 for (unsigned i = 0; i < SplitTys.size(); ++i) 182 Regs->push_back(0); 183 return *Regs; 184 } 185 186 ArrayRef<Register> IRTranslator::getOrCreateVRegs(const Value &Val) { 187 auto VRegsIt = VMap.findVRegs(Val); 188 if (VRegsIt != VMap.vregs_end()) 189 return *VRegsIt->second; 190 191 if (Val.getType()->isVoidTy()) 192 return *VMap.getVRegs(Val); 193 194 // Create entry for this type. 195 auto *VRegs = VMap.getVRegs(Val); 196 auto *Offsets = VMap.getOffsets(Val); 197 198 assert(Val.getType()->isSized() && 199 "Don't know how to create an empty vreg"); 200 201 SmallVector<LLT, 4> SplitTys; 202 computeValueLLTs(*DL, *Val.getType(), SplitTys, 203 Offsets->empty() ? Offsets : nullptr); 204 205 if (!isa<Constant>(Val)) { 206 for (auto Ty : SplitTys) 207 VRegs->push_back(MRI->createGenericVirtualRegister(Ty)); 208 return *VRegs; 209 } 210 211 if (Val.getType()->isAggregateType()) { 212 // UndefValue, ConstantAggregateZero 213 auto &C = cast<Constant>(Val); 214 unsigned Idx = 0; 215 while (auto Elt = C.getAggregateElement(Idx++)) { 216 auto EltRegs = getOrCreateVRegs(*Elt); 217 llvm::copy(EltRegs, std::back_inserter(*VRegs)); 218 } 219 } else { 220 assert(SplitTys.size() == 1 && "unexpectedly split LLT"); 221 VRegs->push_back(MRI->createGenericVirtualRegister(SplitTys[0])); 222 bool Success = translate(cast<Constant>(Val), VRegs->front()); 223 if (!Success) { 224 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 225 MF->getFunction().getSubprogram(), 226 &MF->getFunction().getEntryBlock()); 227 R << "unable to translate constant: " << ore::NV("Type", Val.getType()); 228 reportTranslationError(*MF, *TPC, *ORE, R); 229 return *VRegs; 230 } 231 } 232 233 return *VRegs; 234 } 235 236 int IRTranslator::getOrCreateFrameIndex(const AllocaInst &AI) { 237 auto MapEntry = FrameIndices.find(&AI); 238 if (MapEntry != FrameIndices.end()) 239 return MapEntry->second; 240 241 uint64_t ElementSize = DL->getTypeAllocSize(AI.getAllocatedType()); 242 uint64_t Size = 243 ElementSize * cast<ConstantInt>(AI.getArraySize())->getZExtValue(); 244 245 // Always allocate at least one byte. 246 Size = std::max<uint64_t>(Size, 1u); 247 248 int &FI = FrameIndices[&AI]; 249 FI = MF->getFrameInfo().CreateStackObject(Size, AI.getAlign(), false, &AI); 250 return FI; 251 } 252 253 Align IRTranslator::getMemOpAlign(const Instruction &I) { 254 if (const StoreInst *SI = dyn_cast<StoreInst>(&I)) 255 return SI->getAlign(); 256 if (const LoadInst *LI = dyn_cast<LoadInst>(&I)) { 257 return LI->getAlign(); 258 } 259 if (const AtomicCmpXchgInst *AI = dyn_cast<AtomicCmpXchgInst>(&I)) { 260 // TODO(PR27168): This instruction has no alignment attribute, but unlike 261 // the default alignment for load/store, the default here is to assume 262 // it has NATURAL alignment, not DataLayout-specified alignment. 263 const DataLayout &DL = AI->getModule()->getDataLayout(); 264 return Align(DL.getTypeStoreSize(AI->getCompareOperand()->getType())); 265 } 266 if (const AtomicRMWInst *AI = dyn_cast<AtomicRMWInst>(&I)) { 267 // TODO(PR27168): This instruction has no alignment attribute, but unlike 268 // the default alignment for load/store, the default here is to assume 269 // it has NATURAL alignment, not DataLayout-specified alignment. 270 const DataLayout &DL = AI->getModule()->getDataLayout(); 271 return Align(DL.getTypeStoreSize(AI->getValOperand()->getType())); 272 } 273 OptimizationRemarkMissed R("gisel-irtranslator", "", &I); 274 R << "unable to translate memop: " << ore::NV("Opcode", &I); 275 reportTranslationError(*MF, *TPC, *ORE, R); 276 return Align(1); 277 } 278 279 MachineBasicBlock &IRTranslator::getMBB(const BasicBlock &BB) { 280 MachineBasicBlock *&MBB = BBToMBB[&BB]; 281 assert(MBB && "BasicBlock was not encountered before"); 282 return *MBB; 283 } 284 285 void IRTranslator::addMachineCFGPred(CFGEdge Edge, MachineBasicBlock *NewPred) { 286 assert(NewPred && "new predecessor must be a real MachineBasicBlock"); 287 MachinePreds[Edge].push_back(NewPred); 288 } 289 290 bool IRTranslator::translateBinaryOp(unsigned Opcode, const User &U, 291 MachineIRBuilder &MIRBuilder) { 292 // Get or create a virtual register for each value. 293 // Unless the value is a Constant => loadimm cst? 294 // or inline constant each time? 295 // Creation of a virtual register needs to have a size. 296 Register Op0 = getOrCreateVReg(*U.getOperand(0)); 297 Register Op1 = getOrCreateVReg(*U.getOperand(1)); 298 Register Res = getOrCreateVReg(U); 299 uint16_t Flags = 0; 300 if (isa<Instruction>(U)) { 301 const Instruction &I = cast<Instruction>(U); 302 Flags = MachineInstr::copyFlagsFromInstruction(I); 303 } 304 305 MIRBuilder.buildInstr(Opcode, {Res}, {Op0, Op1}, Flags); 306 return true; 307 } 308 309 bool IRTranslator::translateUnaryOp(unsigned Opcode, const User &U, 310 MachineIRBuilder &MIRBuilder) { 311 Register Op0 = getOrCreateVReg(*U.getOperand(0)); 312 Register Res = getOrCreateVReg(U); 313 uint16_t Flags = 0; 314 if (isa<Instruction>(U)) { 315 const Instruction &I = cast<Instruction>(U); 316 Flags = MachineInstr::copyFlagsFromInstruction(I); 317 } 318 MIRBuilder.buildInstr(Opcode, {Res}, {Op0}, Flags); 319 return true; 320 } 321 322 bool IRTranslator::translateFNeg(const User &U, MachineIRBuilder &MIRBuilder) { 323 return translateUnaryOp(TargetOpcode::G_FNEG, U, MIRBuilder); 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 void IRTranslator::emitBranchForMergedCondition( 375 const Value *Cond, MachineBasicBlock *TBB, MachineBasicBlock *FBB, 376 MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB, 377 BranchProbability TProb, BranchProbability FProb, bool InvertCond) { 378 // If the leaf of the tree is a comparison, merge the condition into 379 // the caseblock. 380 if (const CmpInst *BOp = dyn_cast<CmpInst>(Cond)) { 381 CmpInst::Predicate Condition; 382 if (const ICmpInst *IC = dyn_cast<ICmpInst>(Cond)) { 383 Condition = InvertCond ? IC->getInversePredicate() : IC->getPredicate(); 384 } else { 385 const FCmpInst *FC = cast<FCmpInst>(Cond); 386 Condition = InvertCond ? FC->getInversePredicate() : FC->getPredicate(); 387 } 388 389 SwitchCG::CaseBlock CB(Condition, false, BOp->getOperand(0), 390 BOp->getOperand(1), nullptr, TBB, FBB, CurBB, 391 CurBuilder->getDebugLoc(), TProb, FProb); 392 SL->SwitchCases.push_back(CB); 393 return; 394 } 395 396 // Create a CaseBlock record representing this branch. 397 CmpInst::Predicate Pred = InvertCond ? CmpInst::ICMP_NE : CmpInst::ICMP_EQ; 398 SwitchCG::CaseBlock CB( 399 Pred, false, Cond, ConstantInt::getTrue(MF->getFunction().getContext()), 400 nullptr, TBB, FBB, CurBB, CurBuilder->getDebugLoc(), TProb, FProb); 401 SL->SwitchCases.push_back(CB); 402 } 403 404 static bool isValInBlock(const Value *V, const BasicBlock *BB) { 405 if (const Instruction *I = dyn_cast<Instruction>(V)) 406 return I->getParent() == BB; 407 return true; 408 } 409 410 void IRTranslator::findMergedConditions( 411 const Value *Cond, MachineBasicBlock *TBB, MachineBasicBlock *FBB, 412 MachineBasicBlock *CurBB, MachineBasicBlock *SwitchBB, 413 Instruction::BinaryOps Opc, BranchProbability TProb, 414 BranchProbability FProb, bool InvertCond) { 415 using namespace PatternMatch; 416 assert((Opc == Instruction::And || Opc == Instruction::Or) && 417 "Expected Opc to be AND/OR"); 418 // Skip over not part of the tree and remember to invert op and operands at 419 // next level. 420 Value *NotCond; 421 if (match(Cond, m_OneUse(m_Not(m_Value(NotCond)))) && 422 isValInBlock(NotCond, CurBB->getBasicBlock())) { 423 findMergedConditions(NotCond, TBB, FBB, CurBB, SwitchBB, Opc, TProb, FProb, 424 !InvertCond); 425 return; 426 } 427 428 const Instruction *BOp = dyn_cast<Instruction>(Cond); 429 // Compute the effective opcode for Cond, taking into account whether it needs 430 // to be inverted, e.g. 431 // and (not (or A, B)), C 432 // gets lowered as 433 // and (and (not A, not B), C) 434 unsigned BOpc = 0; 435 if (BOp) { 436 BOpc = BOp->getOpcode(); 437 if (InvertCond) { 438 if (BOpc == Instruction::And) 439 BOpc = Instruction::Or; 440 else if (BOpc == Instruction::Or) 441 BOpc = Instruction::And; 442 } 443 } 444 445 // If this node is not part of the or/and tree, emit it as a branch. 446 if (!BOp || !(isa<BinaryOperator>(BOp) || isa<CmpInst>(BOp)) || 447 BOpc != static_cast<unsigned>(Opc) || !BOp->hasOneUse() || 448 BOp->getParent() != CurBB->getBasicBlock() || 449 !isValInBlock(BOp->getOperand(0), CurBB->getBasicBlock()) || 450 !isValInBlock(BOp->getOperand(1), CurBB->getBasicBlock())) { 451 emitBranchForMergedCondition(Cond, TBB, FBB, CurBB, SwitchBB, TProb, FProb, 452 InvertCond); 453 return; 454 } 455 456 // Create TmpBB after CurBB. 457 MachineFunction::iterator BBI(CurBB); 458 MachineBasicBlock *TmpBB = 459 MF->CreateMachineBasicBlock(CurBB->getBasicBlock()); 460 CurBB->getParent()->insert(++BBI, TmpBB); 461 462 if (Opc == Instruction::Or) { 463 // Codegen X | Y as: 464 // BB1: 465 // jmp_if_X TBB 466 // jmp TmpBB 467 // TmpBB: 468 // jmp_if_Y TBB 469 // jmp FBB 470 // 471 472 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 473 // The requirement is that 474 // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB) 475 // = TrueProb for original BB. 476 // Assuming the original probabilities are A and B, one choice is to set 477 // BB1's probabilities to A/2 and A/2+B, and set TmpBB's probabilities to 478 // A/(1+B) and 2B/(1+B). This choice assumes that 479 // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB. 480 // Another choice is to assume TrueProb for BB1 equals to TrueProb for 481 // TmpBB, but the math is more complicated. 482 483 auto NewTrueProb = TProb / 2; 484 auto NewFalseProb = TProb / 2 + FProb; 485 // Emit the LHS condition. 486 findMergedConditions(BOp->getOperand(0), TBB, TmpBB, CurBB, SwitchBB, Opc, 487 NewTrueProb, NewFalseProb, InvertCond); 488 489 // Normalize A/2 and B to get A/(1+B) and 2B/(1+B). 490 SmallVector<BranchProbability, 2> Probs{TProb / 2, FProb}; 491 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 492 // Emit the RHS condition into TmpBB. 493 findMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 494 Probs[0], Probs[1], InvertCond); 495 } else { 496 assert(Opc == Instruction::And && "Unknown merge op!"); 497 // Codegen X & Y as: 498 // BB1: 499 // jmp_if_X TmpBB 500 // jmp FBB 501 // TmpBB: 502 // jmp_if_Y TBB 503 // jmp FBB 504 // 505 // This requires creation of TmpBB after CurBB. 506 507 // We have flexibility in setting Prob for BB1 and Prob for TmpBB. 508 // The requirement is that 509 // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB) 510 // = FalseProb for original BB. 511 // Assuming the original probabilities are A and B, one choice is to set 512 // BB1's probabilities to A+B/2 and B/2, and set TmpBB's probabilities to 513 // 2A/(1+A) and B/(1+A). This choice assumes that FalseProb for BB1 == 514 // TrueProb for BB1 * FalseProb for TmpBB. 515 516 auto NewTrueProb = TProb + FProb / 2; 517 auto NewFalseProb = FProb / 2; 518 // Emit the LHS condition. 519 findMergedConditions(BOp->getOperand(0), TmpBB, FBB, CurBB, SwitchBB, Opc, 520 NewTrueProb, NewFalseProb, InvertCond); 521 522 // Normalize A and B/2 to get 2A/(1+A) and B/(1+A). 523 SmallVector<BranchProbability, 2> Probs{TProb, FProb / 2}; 524 BranchProbability::normalizeProbabilities(Probs.begin(), Probs.end()); 525 // Emit the RHS condition into TmpBB. 526 findMergedConditions(BOp->getOperand(1), TBB, FBB, TmpBB, SwitchBB, Opc, 527 Probs[0], Probs[1], InvertCond); 528 } 529 } 530 531 bool IRTranslator::shouldEmitAsBranches( 532 const std::vector<SwitchCG::CaseBlock> &Cases) { 533 // For multiple cases, it's better to emit as branches. 534 if (Cases.size() != 2) 535 return true; 536 537 // If this is two comparisons of the same values or'd or and'd together, they 538 // will get folded into a single comparison, so don't emit two blocks. 539 if ((Cases[0].CmpLHS == Cases[1].CmpLHS && 540 Cases[0].CmpRHS == Cases[1].CmpRHS) || 541 (Cases[0].CmpRHS == Cases[1].CmpLHS && 542 Cases[0].CmpLHS == Cases[1].CmpRHS)) { 543 return false; 544 } 545 546 // Handle: (X != null) | (Y != null) --> (X|Y) != 0 547 // Handle: (X == null) & (Y == null) --> (X|Y) == 0 548 if (Cases[0].CmpRHS == Cases[1].CmpRHS && 549 Cases[0].PredInfo.Pred == Cases[1].PredInfo.Pred && 550 isa<Constant>(Cases[0].CmpRHS) && 551 cast<Constant>(Cases[0].CmpRHS)->isNullValue()) { 552 if (Cases[0].PredInfo.Pred == CmpInst::ICMP_EQ && 553 Cases[0].TrueBB == Cases[1].ThisBB) 554 return false; 555 if (Cases[0].PredInfo.Pred == CmpInst::ICMP_NE && 556 Cases[0].FalseBB == Cases[1].ThisBB) 557 return false; 558 } 559 560 return true; 561 } 562 563 bool IRTranslator::translateBr(const User &U, MachineIRBuilder &MIRBuilder) { 564 const BranchInst &BrInst = cast<BranchInst>(U); 565 auto &CurMBB = MIRBuilder.getMBB(); 566 auto *Succ0MBB = &getMBB(*BrInst.getSuccessor(0)); 567 568 if (BrInst.isUnconditional()) { 569 // If the unconditional target is the layout successor, fallthrough. 570 if (!CurMBB.isLayoutSuccessor(Succ0MBB)) 571 MIRBuilder.buildBr(*Succ0MBB); 572 573 // Link successors. 574 for (const BasicBlock *Succ : successors(&BrInst)) 575 CurMBB.addSuccessor(&getMBB(*Succ)); 576 return true; 577 } 578 579 // If this condition is one of the special cases we handle, do special stuff 580 // now. 581 const Value *CondVal = BrInst.getCondition(); 582 MachineBasicBlock *Succ1MBB = &getMBB(*BrInst.getSuccessor(1)); 583 584 const auto &TLI = *MF->getSubtarget().getTargetLowering(); 585 586 // If this is a series of conditions that are or'd or and'd together, emit 587 // this as a sequence of branches instead of setcc's with and/or operations. 588 // As long as jumps are not expensive (exceptions for multi-use logic ops, 589 // unpredictable branches, and vector extracts because those jumps are likely 590 // expensive for any target), this should improve performance. 591 // For example, instead of something like: 592 // cmp A, B 593 // C = seteq 594 // cmp D, E 595 // F = setle 596 // or C, F 597 // jnz foo 598 // Emit: 599 // cmp A, B 600 // je foo 601 // cmp D, E 602 // jle foo 603 using namespace PatternMatch; 604 if (const BinaryOperator *BOp = dyn_cast<BinaryOperator>(CondVal)) { 605 Instruction::BinaryOps Opcode = BOp->getOpcode(); 606 Value *Vec, *BOp0 = BOp->getOperand(0), *BOp1 = BOp->getOperand(1); 607 if (!TLI.isJumpExpensive() && BOp->hasOneUse() && 608 !BrInst.hasMetadata(LLVMContext::MD_unpredictable) && 609 (Opcode == Instruction::And || Opcode == Instruction::Or) && 610 !(match(BOp0, m_ExtractElt(m_Value(Vec), m_Value())) && 611 match(BOp1, m_ExtractElt(m_Specific(Vec), m_Value())))) { 612 findMergedConditions(BOp, Succ0MBB, Succ1MBB, &CurMBB, &CurMBB, Opcode, 613 getEdgeProbability(&CurMBB, Succ0MBB), 614 getEdgeProbability(&CurMBB, Succ1MBB), 615 /*InvertCond=*/false); 616 assert(SL->SwitchCases[0].ThisBB == &CurMBB && "Unexpected lowering!"); 617 618 // Allow some cases to be rejected. 619 if (shouldEmitAsBranches(SL->SwitchCases)) { 620 // Emit the branch for this block. 621 emitSwitchCase(SL->SwitchCases[0], &CurMBB, *CurBuilder); 622 SL->SwitchCases.erase(SL->SwitchCases.begin()); 623 return true; 624 } 625 626 // Okay, we decided not to do this, remove any inserted MBB's and clear 627 // SwitchCases. 628 for (unsigned I = 1, E = SL->SwitchCases.size(); I != E; ++I) 629 MF->erase(SL->SwitchCases[I].ThisBB); 630 631 SL->SwitchCases.clear(); 632 } 633 } 634 635 // Create a CaseBlock record representing this branch. 636 SwitchCG::CaseBlock CB(CmpInst::ICMP_EQ, false, CondVal, 637 ConstantInt::getTrue(MF->getFunction().getContext()), 638 nullptr, Succ0MBB, Succ1MBB, &CurMBB, 639 CurBuilder->getDebugLoc()); 640 641 // Use emitSwitchCase to actually insert the fast branch sequence for this 642 // cond branch. 643 emitSwitchCase(CB, &CurMBB, *CurBuilder); 644 return true; 645 } 646 647 void IRTranslator::addSuccessorWithProb(MachineBasicBlock *Src, 648 MachineBasicBlock *Dst, 649 BranchProbability Prob) { 650 if (!FuncInfo.BPI) { 651 Src->addSuccessorWithoutProb(Dst); 652 return; 653 } 654 if (Prob.isUnknown()) 655 Prob = getEdgeProbability(Src, Dst); 656 Src->addSuccessor(Dst, Prob); 657 } 658 659 BranchProbability 660 IRTranslator::getEdgeProbability(const MachineBasicBlock *Src, 661 const MachineBasicBlock *Dst) const { 662 const BasicBlock *SrcBB = Src->getBasicBlock(); 663 const BasicBlock *DstBB = Dst->getBasicBlock(); 664 if (!FuncInfo.BPI) { 665 // If BPI is not available, set the default probability as 1 / N, where N is 666 // the number of successors. 667 auto SuccSize = std::max<uint32_t>(succ_size(SrcBB), 1); 668 return BranchProbability(1, SuccSize); 669 } 670 return FuncInfo.BPI->getEdgeProbability(SrcBB, DstBB); 671 } 672 673 bool IRTranslator::translateSwitch(const User &U, MachineIRBuilder &MIB) { 674 using namespace SwitchCG; 675 // Extract cases from the switch. 676 const SwitchInst &SI = cast<SwitchInst>(U); 677 BranchProbabilityInfo *BPI = FuncInfo.BPI; 678 CaseClusterVector Clusters; 679 Clusters.reserve(SI.getNumCases()); 680 for (auto &I : SI.cases()) { 681 MachineBasicBlock *Succ = &getMBB(*I.getCaseSuccessor()); 682 assert(Succ && "Could not find successor mbb in mapping"); 683 const ConstantInt *CaseVal = I.getCaseValue(); 684 BranchProbability Prob = 685 BPI ? BPI->getEdgeProbability(SI.getParent(), I.getSuccessorIndex()) 686 : BranchProbability(1, SI.getNumCases() + 1); 687 Clusters.push_back(CaseCluster::range(CaseVal, CaseVal, Succ, Prob)); 688 } 689 690 MachineBasicBlock *DefaultMBB = &getMBB(*SI.getDefaultDest()); 691 692 // Cluster adjacent cases with the same destination. We do this at all 693 // optimization levels because it's cheap to do and will make codegen faster 694 // if there are many clusters. 695 sortAndRangeify(Clusters); 696 697 MachineBasicBlock *SwitchMBB = &getMBB(*SI.getParent()); 698 699 // If there is only the default destination, jump there directly. 700 if (Clusters.empty()) { 701 SwitchMBB->addSuccessor(DefaultMBB); 702 if (DefaultMBB != SwitchMBB->getNextNode()) 703 MIB.buildBr(*DefaultMBB); 704 return true; 705 } 706 707 SL->findJumpTables(Clusters, &SI, DefaultMBB, nullptr, nullptr); 708 SL->findBitTestClusters(Clusters, &SI); 709 710 LLVM_DEBUG({ 711 dbgs() << "Case clusters: "; 712 for (const CaseCluster &C : Clusters) { 713 if (C.Kind == CC_JumpTable) 714 dbgs() << "JT:"; 715 if (C.Kind == CC_BitTests) 716 dbgs() << "BT:"; 717 718 C.Low->getValue().print(dbgs(), true); 719 if (C.Low != C.High) { 720 dbgs() << '-'; 721 C.High->getValue().print(dbgs(), true); 722 } 723 dbgs() << ' '; 724 } 725 dbgs() << '\n'; 726 }); 727 728 assert(!Clusters.empty()); 729 SwitchWorkList WorkList; 730 CaseClusterIt First = Clusters.begin(); 731 CaseClusterIt Last = Clusters.end() - 1; 732 auto DefaultProb = getEdgeProbability(SwitchMBB, DefaultMBB); 733 WorkList.push_back({SwitchMBB, First, Last, nullptr, nullptr, DefaultProb}); 734 735 // FIXME: At the moment we don't do any splitting optimizations here like 736 // SelectionDAG does, so this worklist only has one entry. 737 while (!WorkList.empty()) { 738 SwitchWorkListItem W = WorkList.back(); 739 WorkList.pop_back(); 740 if (!lowerSwitchWorkItem(W, SI.getCondition(), SwitchMBB, DefaultMBB, MIB)) 741 return false; 742 } 743 return true; 744 } 745 746 void IRTranslator::emitJumpTable(SwitchCG::JumpTable &JT, 747 MachineBasicBlock *MBB) { 748 // Emit the code for the jump table 749 assert(JT.Reg != -1U && "Should lower JT Header first!"); 750 MachineIRBuilder MIB(*MBB->getParent()); 751 MIB.setMBB(*MBB); 752 MIB.setDebugLoc(CurBuilder->getDebugLoc()); 753 754 Type *PtrIRTy = Type::getInt8PtrTy(MF->getFunction().getContext()); 755 const LLT PtrTy = getLLTForType(*PtrIRTy, *DL); 756 757 auto Table = MIB.buildJumpTable(PtrTy, JT.JTI); 758 MIB.buildBrJT(Table.getReg(0), JT.JTI, JT.Reg); 759 } 760 761 bool IRTranslator::emitJumpTableHeader(SwitchCG::JumpTable &JT, 762 SwitchCG::JumpTableHeader &JTH, 763 MachineBasicBlock *HeaderBB) { 764 MachineIRBuilder MIB(*HeaderBB->getParent()); 765 MIB.setMBB(*HeaderBB); 766 MIB.setDebugLoc(CurBuilder->getDebugLoc()); 767 768 const Value &SValue = *JTH.SValue; 769 // Subtract the lowest switch case value from the value being switched on. 770 const LLT SwitchTy = getLLTForType(*SValue.getType(), *DL); 771 Register SwitchOpReg = getOrCreateVReg(SValue); 772 auto FirstCst = MIB.buildConstant(SwitchTy, JTH.First); 773 auto Sub = MIB.buildSub({SwitchTy}, SwitchOpReg, FirstCst); 774 775 // This value may be smaller or larger than the target's pointer type, and 776 // therefore require extension or truncating. 777 Type *PtrIRTy = SValue.getType()->getPointerTo(); 778 const LLT PtrScalarTy = LLT::scalar(DL->getTypeSizeInBits(PtrIRTy)); 779 Sub = MIB.buildZExtOrTrunc(PtrScalarTy, Sub); 780 781 JT.Reg = Sub.getReg(0); 782 783 if (JTH.OmitRangeCheck) { 784 if (JT.MBB != HeaderBB->getNextNode()) 785 MIB.buildBr(*JT.MBB); 786 return true; 787 } 788 789 // Emit the range check for the jump table, and branch to the default block 790 // for the switch statement if the value being switched on exceeds the 791 // largest case in the switch. 792 auto Cst = getOrCreateVReg( 793 *ConstantInt::get(SValue.getType(), JTH.Last - JTH.First)); 794 Cst = MIB.buildZExtOrTrunc(PtrScalarTy, Cst).getReg(0); 795 auto Cmp = MIB.buildICmp(CmpInst::ICMP_UGT, LLT::scalar(1), Sub, Cst); 796 797 auto BrCond = MIB.buildBrCond(Cmp.getReg(0), *JT.Default); 798 799 // Avoid emitting unnecessary branches to the next block. 800 if (JT.MBB != HeaderBB->getNextNode()) 801 BrCond = MIB.buildBr(*JT.MBB); 802 return true; 803 } 804 805 void IRTranslator::emitSwitchCase(SwitchCG::CaseBlock &CB, 806 MachineBasicBlock *SwitchBB, 807 MachineIRBuilder &MIB) { 808 Register CondLHS = getOrCreateVReg(*CB.CmpLHS); 809 Register Cond; 810 DebugLoc OldDbgLoc = MIB.getDebugLoc(); 811 MIB.setDebugLoc(CB.DbgLoc); 812 MIB.setMBB(*CB.ThisBB); 813 814 if (CB.PredInfo.NoCmp) { 815 // Branch or fall through to TrueBB. 816 addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb); 817 addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()}, 818 CB.ThisBB); 819 CB.ThisBB->normalizeSuccProbs(); 820 if (CB.TrueBB != CB.ThisBB->getNextNode()) 821 MIB.buildBr(*CB.TrueBB); 822 MIB.setDebugLoc(OldDbgLoc); 823 return; 824 } 825 826 const LLT i1Ty = LLT::scalar(1); 827 // Build the compare. 828 if (!CB.CmpMHS) { 829 const auto *CI = dyn_cast<ConstantInt>(CB.CmpRHS); 830 // For conditional branch lowering, we might try to do something silly like 831 // emit an G_ICMP to compare an existing G_ICMP i1 result with true. If so, 832 // just re-use the existing condition vreg. 833 if (CI && CI->getZExtValue() == 1 && 834 MRI->getType(CondLHS).getSizeInBits() == 1 && 835 CB.PredInfo.Pred == CmpInst::ICMP_EQ) { 836 Cond = CondLHS; 837 } else { 838 Register CondRHS = getOrCreateVReg(*CB.CmpRHS); 839 if (CmpInst::isFPPredicate(CB.PredInfo.Pred)) 840 Cond = 841 MIB.buildFCmp(CB.PredInfo.Pred, i1Ty, CondLHS, CondRHS).getReg(0); 842 else 843 Cond = 844 MIB.buildICmp(CB.PredInfo.Pred, i1Ty, CondLHS, CondRHS).getReg(0); 845 } 846 } else { 847 assert(CB.PredInfo.Pred == CmpInst::ICMP_SLE && 848 "Can only handle SLE ranges"); 849 850 const APInt& Low = cast<ConstantInt>(CB.CmpLHS)->getValue(); 851 const APInt& High = cast<ConstantInt>(CB.CmpRHS)->getValue(); 852 853 Register CmpOpReg = getOrCreateVReg(*CB.CmpMHS); 854 if (cast<ConstantInt>(CB.CmpLHS)->isMinValue(true)) { 855 Register CondRHS = getOrCreateVReg(*CB.CmpRHS); 856 Cond = 857 MIB.buildICmp(CmpInst::ICMP_SLE, i1Ty, CmpOpReg, CondRHS).getReg(0); 858 } else { 859 const LLT CmpTy = MRI->getType(CmpOpReg); 860 auto Sub = MIB.buildSub({CmpTy}, CmpOpReg, CondLHS); 861 auto Diff = MIB.buildConstant(CmpTy, High - Low); 862 Cond = MIB.buildICmp(CmpInst::ICMP_ULE, i1Ty, Sub, Diff).getReg(0); 863 } 864 } 865 866 // Update successor info 867 addSuccessorWithProb(CB.ThisBB, CB.TrueBB, CB.TrueProb); 868 869 addMachineCFGPred({SwitchBB->getBasicBlock(), CB.TrueBB->getBasicBlock()}, 870 CB.ThisBB); 871 872 // TrueBB and FalseBB are always different unless the incoming IR is 873 // degenerate. This only happens when running llc on weird IR. 874 if (CB.TrueBB != CB.FalseBB) 875 addSuccessorWithProb(CB.ThisBB, CB.FalseBB, CB.FalseProb); 876 CB.ThisBB->normalizeSuccProbs(); 877 878 addMachineCFGPred({SwitchBB->getBasicBlock(), CB.FalseBB->getBasicBlock()}, 879 CB.ThisBB); 880 881 MIB.buildBrCond(Cond, *CB.TrueBB); 882 MIB.buildBr(*CB.FalseBB); 883 MIB.setDebugLoc(OldDbgLoc); 884 } 885 886 bool IRTranslator::lowerJumpTableWorkItem(SwitchCG::SwitchWorkListItem W, 887 MachineBasicBlock *SwitchMBB, 888 MachineBasicBlock *CurMBB, 889 MachineBasicBlock *DefaultMBB, 890 MachineIRBuilder &MIB, 891 MachineFunction::iterator BBI, 892 BranchProbability UnhandledProbs, 893 SwitchCG::CaseClusterIt I, 894 MachineBasicBlock *Fallthrough, 895 bool FallthroughUnreachable) { 896 using namespace SwitchCG; 897 MachineFunction *CurMF = SwitchMBB->getParent(); 898 // FIXME: Optimize away range check based on pivot comparisons. 899 JumpTableHeader *JTH = &SL->JTCases[I->JTCasesIndex].first; 900 SwitchCG::JumpTable *JT = &SL->JTCases[I->JTCasesIndex].second; 901 BranchProbability DefaultProb = W.DefaultProb; 902 903 // The jump block hasn't been inserted yet; insert it here. 904 MachineBasicBlock *JumpMBB = JT->MBB; 905 CurMF->insert(BBI, JumpMBB); 906 907 // Since the jump table block is separate from the switch block, we need 908 // to keep track of it as a machine predecessor to the default block, 909 // otherwise we lose the phi edges. 910 addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()}, 911 CurMBB); 912 addMachineCFGPred({SwitchMBB->getBasicBlock(), DefaultMBB->getBasicBlock()}, 913 JumpMBB); 914 915 auto JumpProb = I->Prob; 916 auto FallthroughProb = UnhandledProbs; 917 918 // If the default statement is a target of the jump table, we evenly 919 // distribute the default probability to successors of CurMBB. Also 920 // update the probability on the edge from JumpMBB to Fallthrough. 921 for (MachineBasicBlock::succ_iterator SI = JumpMBB->succ_begin(), 922 SE = JumpMBB->succ_end(); 923 SI != SE; ++SI) { 924 if (*SI == DefaultMBB) { 925 JumpProb += DefaultProb / 2; 926 FallthroughProb -= DefaultProb / 2; 927 JumpMBB->setSuccProbability(SI, DefaultProb / 2); 928 JumpMBB->normalizeSuccProbs(); 929 } else { 930 // Also record edges from the jump table block to it's successors. 931 addMachineCFGPred({SwitchMBB->getBasicBlock(), (*SI)->getBasicBlock()}, 932 JumpMBB); 933 } 934 } 935 936 // Skip the range check if the fallthrough block is unreachable. 937 if (FallthroughUnreachable) 938 JTH->OmitRangeCheck = true; 939 940 if (!JTH->OmitRangeCheck) 941 addSuccessorWithProb(CurMBB, Fallthrough, FallthroughProb); 942 addSuccessorWithProb(CurMBB, JumpMBB, JumpProb); 943 CurMBB->normalizeSuccProbs(); 944 945 // The jump table header will be inserted in our current block, do the 946 // range check, and fall through to our fallthrough block. 947 JTH->HeaderBB = CurMBB; 948 JT->Default = Fallthrough; // FIXME: Move Default to JumpTableHeader. 949 950 // If we're in the right place, emit the jump table header right now. 951 if (CurMBB == SwitchMBB) { 952 if (!emitJumpTableHeader(*JT, *JTH, CurMBB)) 953 return false; 954 JTH->Emitted = true; 955 } 956 return true; 957 } 958 bool IRTranslator::lowerSwitchRangeWorkItem(SwitchCG::CaseClusterIt I, 959 Value *Cond, 960 MachineBasicBlock *Fallthrough, 961 bool FallthroughUnreachable, 962 BranchProbability UnhandledProbs, 963 MachineBasicBlock *CurMBB, 964 MachineIRBuilder &MIB, 965 MachineBasicBlock *SwitchMBB) { 966 using namespace SwitchCG; 967 const Value *RHS, *LHS, *MHS; 968 CmpInst::Predicate Pred; 969 if (I->Low == I->High) { 970 // Check Cond == I->Low. 971 Pred = CmpInst::ICMP_EQ; 972 LHS = Cond; 973 RHS = I->Low; 974 MHS = nullptr; 975 } else { 976 // Check I->Low <= Cond <= I->High. 977 Pred = CmpInst::ICMP_SLE; 978 LHS = I->Low; 979 MHS = Cond; 980 RHS = I->High; 981 } 982 983 // If Fallthrough is unreachable, fold away the comparison. 984 // The false probability is the sum of all unhandled cases. 985 CaseBlock CB(Pred, FallthroughUnreachable, LHS, RHS, MHS, I->MBB, Fallthrough, 986 CurMBB, MIB.getDebugLoc(), I->Prob, UnhandledProbs); 987 988 emitSwitchCase(CB, SwitchMBB, MIB); 989 return true; 990 } 991 992 void IRTranslator::emitBitTestHeader(SwitchCG::BitTestBlock &B, 993 MachineBasicBlock *SwitchBB) { 994 MachineIRBuilder &MIB = *CurBuilder; 995 MIB.setMBB(*SwitchBB); 996 997 // Subtract the minimum value. 998 Register SwitchOpReg = getOrCreateVReg(*B.SValue); 999 1000 LLT SwitchOpTy = MRI->getType(SwitchOpReg); 1001 Register MinValReg = MIB.buildConstant(SwitchOpTy, B.First).getReg(0); 1002 auto RangeSub = MIB.buildSub(SwitchOpTy, SwitchOpReg, MinValReg); 1003 1004 // Ensure that the type will fit the mask value. 1005 LLT MaskTy = SwitchOpTy; 1006 for (unsigned I = 0, E = B.Cases.size(); I != E; ++I) { 1007 if (!isUIntN(SwitchOpTy.getSizeInBits(), B.Cases[I].Mask)) { 1008 // Switch table case range are encoded into series of masks. 1009 // Just use pointer type, it's guaranteed to fit. 1010 MaskTy = LLT::scalar(64); 1011 break; 1012 } 1013 } 1014 Register SubReg = RangeSub.getReg(0); 1015 if (SwitchOpTy != MaskTy) 1016 SubReg = MIB.buildZExtOrTrunc(MaskTy, SubReg).getReg(0); 1017 1018 B.RegVT = getMVTForLLT(MaskTy); 1019 B.Reg = SubReg; 1020 1021 MachineBasicBlock *MBB = B.Cases[0].ThisBB; 1022 1023 if (!B.OmitRangeCheck) 1024 addSuccessorWithProb(SwitchBB, B.Default, B.DefaultProb); 1025 addSuccessorWithProb(SwitchBB, MBB, B.Prob); 1026 1027 SwitchBB->normalizeSuccProbs(); 1028 1029 if (!B.OmitRangeCheck) { 1030 // Conditional branch to the default block. 1031 auto RangeCst = MIB.buildConstant(SwitchOpTy, B.Range); 1032 auto RangeCmp = MIB.buildICmp(CmpInst::Predicate::ICMP_UGT, LLT::scalar(1), 1033 RangeSub, RangeCst); 1034 MIB.buildBrCond(RangeCmp, *B.Default); 1035 } 1036 1037 // Avoid emitting unnecessary branches to the next block. 1038 if (MBB != SwitchBB->getNextNode()) 1039 MIB.buildBr(*MBB); 1040 } 1041 1042 void IRTranslator::emitBitTestCase(SwitchCG::BitTestBlock &BB, 1043 MachineBasicBlock *NextMBB, 1044 BranchProbability BranchProbToNext, 1045 Register Reg, SwitchCG::BitTestCase &B, 1046 MachineBasicBlock *SwitchBB) { 1047 MachineIRBuilder &MIB = *CurBuilder; 1048 MIB.setMBB(*SwitchBB); 1049 1050 LLT SwitchTy = getLLTForMVT(BB.RegVT); 1051 Register Cmp; 1052 unsigned PopCount = countPopulation(B.Mask); 1053 if (PopCount == 1) { 1054 // Testing for a single bit; just compare the shift count with what it 1055 // would need to be to shift a 1 bit in that position. 1056 auto MaskTrailingZeros = 1057 MIB.buildConstant(SwitchTy, countTrailingZeros(B.Mask)); 1058 Cmp = 1059 MIB.buildICmp(ICmpInst::ICMP_EQ, LLT::scalar(1), Reg, MaskTrailingZeros) 1060 .getReg(0); 1061 } else if (PopCount == BB.Range) { 1062 // There is only one zero bit in the range, test for it directly. 1063 auto MaskTrailingOnes = 1064 MIB.buildConstant(SwitchTy, countTrailingOnes(B.Mask)); 1065 Cmp = MIB.buildICmp(CmpInst::ICMP_NE, LLT::scalar(1), Reg, MaskTrailingOnes) 1066 .getReg(0); 1067 } else { 1068 // Make desired shift. 1069 auto CstOne = MIB.buildConstant(SwitchTy, 1); 1070 auto SwitchVal = MIB.buildShl(SwitchTy, CstOne, Reg); 1071 1072 // Emit bit tests and jumps. 1073 auto CstMask = MIB.buildConstant(SwitchTy, B.Mask); 1074 auto AndOp = MIB.buildAnd(SwitchTy, SwitchVal, CstMask); 1075 auto CstZero = MIB.buildConstant(SwitchTy, 0); 1076 Cmp = MIB.buildICmp(CmpInst::ICMP_NE, LLT::scalar(1), AndOp, CstZero) 1077 .getReg(0); 1078 } 1079 1080 // The branch probability from SwitchBB to B.TargetBB is B.ExtraProb. 1081 addSuccessorWithProb(SwitchBB, B.TargetBB, B.ExtraProb); 1082 // The branch probability from SwitchBB to NextMBB is BranchProbToNext. 1083 addSuccessorWithProb(SwitchBB, NextMBB, BranchProbToNext); 1084 // It is not guaranteed that the sum of B.ExtraProb and BranchProbToNext is 1085 // one as they are relative probabilities (and thus work more like weights), 1086 // and hence we need to normalize them to let the sum of them become one. 1087 SwitchBB->normalizeSuccProbs(); 1088 1089 // Record the fact that the IR edge from the header to the bit test target 1090 // will go through our new block. Neeeded for PHIs to have nodes added. 1091 addMachineCFGPred({BB.Parent->getBasicBlock(), B.TargetBB->getBasicBlock()}, 1092 SwitchBB); 1093 1094 MIB.buildBrCond(Cmp, *B.TargetBB); 1095 1096 // Avoid emitting unnecessary branches to the next block. 1097 if (NextMBB != SwitchBB->getNextNode()) 1098 MIB.buildBr(*NextMBB); 1099 } 1100 1101 bool IRTranslator::lowerBitTestWorkItem( 1102 SwitchCG::SwitchWorkListItem W, MachineBasicBlock *SwitchMBB, 1103 MachineBasicBlock *CurMBB, MachineBasicBlock *DefaultMBB, 1104 MachineIRBuilder &MIB, MachineFunction::iterator BBI, 1105 BranchProbability DefaultProb, BranchProbability UnhandledProbs, 1106 SwitchCG::CaseClusterIt I, MachineBasicBlock *Fallthrough, 1107 bool FallthroughUnreachable) { 1108 using namespace SwitchCG; 1109 MachineFunction *CurMF = SwitchMBB->getParent(); 1110 // FIXME: Optimize away range check based on pivot comparisons. 1111 BitTestBlock *BTB = &SL->BitTestCases[I->BTCasesIndex]; 1112 // The bit test blocks haven't been inserted yet; insert them here. 1113 for (BitTestCase &BTC : BTB->Cases) 1114 CurMF->insert(BBI, BTC.ThisBB); 1115 1116 // Fill in fields of the BitTestBlock. 1117 BTB->Parent = CurMBB; 1118 BTB->Default = Fallthrough; 1119 1120 BTB->DefaultProb = UnhandledProbs; 1121 // If the cases in bit test don't form a contiguous range, we evenly 1122 // distribute the probability on the edge to Fallthrough to two 1123 // successors of CurMBB. 1124 if (!BTB->ContiguousRange) { 1125 BTB->Prob += DefaultProb / 2; 1126 BTB->DefaultProb -= DefaultProb / 2; 1127 } 1128 1129 if (FallthroughUnreachable) { 1130 // Skip the range check if the fallthrough block is unreachable. 1131 BTB->OmitRangeCheck = true; 1132 } 1133 1134 // If we're in the right place, emit the bit test header right now. 1135 if (CurMBB == SwitchMBB) { 1136 emitBitTestHeader(*BTB, SwitchMBB); 1137 BTB->Emitted = true; 1138 } 1139 return true; 1140 } 1141 1142 bool IRTranslator::lowerSwitchWorkItem(SwitchCG::SwitchWorkListItem W, 1143 Value *Cond, 1144 MachineBasicBlock *SwitchMBB, 1145 MachineBasicBlock *DefaultMBB, 1146 MachineIRBuilder &MIB) { 1147 using namespace SwitchCG; 1148 MachineFunction *CurMF = FuncInfo.MF; 1149 MachineBasicBlock *NextMBB = nullptr; 1150 MachineFunction::iterator BBI(W.MBB); 1151 if (++BBI != FuncInfo.MF->end()) 1152 NextMBB = &*BBI; 1153 1154 if (EnableOpts) { 1155 // Here, we order cases by probability so the most likely case will be 1156 // checked first. However, two clusters can have the same probability in 1157 // which case their relative ordering is non-deterministic. So we use Low 1158 // as a tie-breaker as clusters are guaranteed to never overlap. 1159 llvm::sort(W.FirstCluster, W.LastCluster + 1, 1160 [](const CaseCluster &a, const CaseCluster &b) { 1161 return a.Prob != b.Prob 1162 ? a.Prob > b.Prob 1163 : a.Low->getValue().slt(b.Low->getValue()); 1164 }); 1165 1166 // Rearrange the case blocks so that the last one falls through if possible 1167 // without changing the order of probabilities. 1168 for (CaseClusterIt I = W.LastCluster; I > W.FirstCluster;) { 1169 --I; 1170 if (I->Prob > W.LastCluster->Prob) 1171 break; 1172 if (I->Kind == CC_Range && I->MBB == NextMBB) { 1173 std::swap(*I, *W.LastCluster); 1174 break; 1175 } 1176 } 1177 } 1178 1179 // Compute total probability. 1180 BranchProbability DefaultProb = W.DefaultProb; 1181 BranchProbability UnhandledProbs = DefaultProb; 1182 for (CaseClusterIt I = W.FirstCluster; I <= W.LastCluster; ++I) 1183 UnhandledProbs += I->Prob; 1184 1185 MachineBasicBlock *CurMBB = W.MBB; 1186 for (CaseClusterIt I = W.FirstCluster, E = W.LastCluster; I <= E; ++I) { 1187 bool FallthroughUnreachable = false; 1188 MachineBasicBlock *Fallthrough; 1189 if (I == W.LastCluster) { 1190 // For the last cluster, fall through to the default destination. 1191 Fallthrough = DefaultMBB; 1192 FallthroughUnreachable = isa<UnreachableInst>( 1193 DefaultMBB->getBasicBlock()->getFirstNonPHIOrDbg()); 1194 } else { 1195 Fallthrough = CurMF->CreateMachineBasicBlock(CurMBB->getBasicBlock()); 1196 CurMF->insert(BBI, Fallthrough); 1197 } 1198 UnhandledProbs -= I->Prob; 1199 1200 switch (I->Kind) { 1201 case CC_BitTests: { 1202 if (!lowerBitTestWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI, 1203 DefaultProb, UnhandledProbs, I, Fallthrough, 1204 FallthroughUnreachable)) { 1205 LLVM_DEBUG(dbgs() << "Failed to lower bit test for switch"); 1206 return false; 1207 } 1208 break; 1209 } 1210 1211 case CC_JumpTable: { 1212 if (!lowerJumpTableWorkItem(W, SwitchMBB, CurMBB, DefaultMBB, MIB, BBI, 1213 UnhandledProbs, I, Fallthrough, 1214 FallthroughUnreachable)) { 1215 LLVM_DEBUG(dbgs() << "Failed to lower jump table"); 1216 return false; 1217 } 1218 break; 1219 } 1220 case CC_Range: { 1221 if (!lowerSwitchRangeWorkItem(I, Cond, Fallthrough, 1222 FallthroughUnreachable, UnhandledProbs, 1223 CurMBB, MIB, SwitchMBB)) { 1224 LLVM_DEBUG(dbgs() << "Failed to lower switch range"); 1225 return false; 1226 } 1227 break; 1228 } 1229 } 1230 CurMBB = Fallthrough; 1231 } 1232 1233 return true; 1234 } 1235 1236 bool IRTranslator::translateIndirectBr(const User &U, 1237 MachineIRBuilder &MIRBuilder) { 1238 const IndirectBrInst &BrInst = cast<IndirectBrInst>(U); 1239 1240 const Register Tgt = getOrCreateVReg(*BrInst.getAddress()); 1241 MIRBuilder.buildBrIndirect(Tgt); 1242 1243 // Link successors. 1244 SmallPtrSet<const BasicBlock *, 32> AddedSuccessors; 1245 MachineBasicBlock &CurBB = MIRBuilder.getMBB(); 1246 for (const BasicBlock *Succ : successors(&BrInst)) { 1247 // It's legal for indirectbr instructions to have duplicate blocks in the 1248 // destination list. We don't allow this in MIR. Skip anything that's 1249 // already a successor. 1250 if (!AddedSuccessors.insert(Succ).second) 1251 continue; 1252 CurBB.addSuccessor(&getMBB(*Succ)); 1253 } 1254 1255 return true; 1256 } 1257 1258 static bool isSwiftError(const Value *V) { 1259 if (auto Arg = dyn_cast<Argument>(V)) 1260 return Arg->hasSwiftErrorAttr(); 1261 if (auto AI = dyn_cast<AllocaInst>(V)) 1262 return AI->isSwiftError(); 1263 return false; 1264 } 1265 1266 bool IRTranslator::translateLoad(const User &U, MachineIRBuilder &MIRBuilder) { 1267 const LoadInst &LI = cast<LoadInst>(U); 1268 if (DL->getTypeStoreSize(LI.getType()) == 0) 1269 return true; 1270 1271 ArrayRef<Register> Regs = getOrCreateVRegs(LI); 1272 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(LI); 1273 Register Base = getOrCreateVReg(*LI.getPointerOperand()); 1274 1275 Type *OffsetIRTy = DL->getIntPtrType(LI.getPointerOperandType()); 1276 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL); 1277 1278 if (CLI->supportSwiftError() && isSwiftError(LI.getPointerOperand())) { 1279 assert(Regs.size() == 1 && "swifterror should be single pointer"); 1280 Register VReg = SwiftError.getOrCreateVRegUseAt(&LI, &MIRBuilder.getMBB(), 1281 LI.getPointerOperand()); 1282 MIRBuilder.buildCopy(Regs[0], VReg); 1283 return true; 1284 } 1285 1286 auto &TLI = *MF->getSubtarget().getTargetLowering(); 1287 MachineMemOperand::Flags Flags = TLI.getLoadMemOperandFlags(LI, *DL); 1288 1289 const MDNode *Ranges = 1290 Regs.size() == 1 ? LI.getMetadata(LLVMContext::MD_range) : nullptr; 1291 for (unsigned i = 0; i < Regs.size(); ++i) { 1292 Register Addr; 1293 MIRBuilder.materializePtrAdd(Addr, Base, OffsetTy, Offsets[i] / 8); 1294 1295 MachinePointerInfo Ptr(LI.getPointerOperand(), Offsets[i] / 8); 1296 Align BaseAlign = getMemOpAlign(LI); 1297 AAMDNodes AAMetadata; 1298 LI.getAAMetadata(AAMetadata); 1299 auto MMO = MF->getMachineMemOperand( 1300 Ptr, Flags, MRI->getType(Regs[i]).getSizeInBytes(), 1301 commonAlignment(BaseAlign, Offsets[i] / 8), AAMetadata, Ranges, 1302 LI.getSyncScopeID(), LI.getOrdering()); 1303 MIRBuilder.buildLoad(Regs[i], Addr, *MMO); 1304 } 1305 1306 return true; 1307 } 1308 1309 bool IRTranslator::translateStore(const User &U, MachineIRBuilder &MIRBuilder) { 1310 const StoreInst &SI = cast<StoreInst>(U); 1311 if (DL->getTypeStoreSize(SI.getValueOperand()->getType()) == 0) 1312 return true; 1313 1314 ArrayRef<Register> Vals = getOrCreateVRegs(*SI.getValueOperand()); 1315 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*SI.getValueOperand()); 1316 Register Base = getOrCreateVReg(*SI.getPointerOperand()); 1317 1318 Type *OffsetIRTy = DL->getIntPtrType(SI.getPointerOperandType()); 1319 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL); 1320 1321 if (CLI->supportSwiftError() && isSwiftError(SI.getPointerOperand())) { 1322 assert(Vals.size() == 1 && "swifterror should be single pointer"); 1323 1324 Register VReg = SwiftError.getOrCreateVRegDefAt(&SI, &MIRBuilder.getMBB(), 1325 SI.getPointerOperand()); 1326 MIRBuilder.buildCopy(VReg, Vals[0]); 1327 return true; 1328 } 1329 1330 auto &TLI = *MF->getSubtarget().getTargetLowering(); 1331 MachineMemOperand::Flags Flags = TLI.getStoreMemOperandFlags(SI, *DL); 1332 1333 for (unsigned i = 0; i < Vals.size(); ++i) { 1334 Register Addr; 1335 MIRBuilder.materializePtrAdd(Addr, Base, OffsetTy, Offsets[i] / 8); 1336 1337 MachinePointerInfo Ptr(SI.getPointerOperand(), Offsets[i] / 8); 1338 Align BaseAlign = getMemOpAlign(SI); 1339 AAMDNodes AAMetadata; 1340 SI.getAAMetadata(AAMetadata); 1341 auto MMO = MF->getMachineMemOperand( 1342 Ptr, Flags, MRI->getType(Vals[i]).getSizeInBytes(), 1343 commonAlignment(BaseAlign, Offsets[i] / 8), AAMetadata, nullptr, 1344 SI.getSyncScopeID(), SI.getOrdering()); 1345 MIRBuilder.buildStore(Vals[i], Addr, *MMO); 1346 } 1347 return true; 1348 } 1349 1350 static uint64_t getOffsetFromIndices(const User &U, const DataLayout &DL) { 1351 const Value *Src = U.getOperand(0); 1352 Type *Int32Ty = Type::getInt32Ty(U.getContext()); 1353 1354 // getIndexedOffsetInType is designed for GEPs, so the first index is the 1355 // usual array element rather than looking into the actual aggregate. 1356 SmallVector<Value *, 1> Indices; 1357 Indices.push_back(ConstantInt::get(Int32Ty, 0)); 1358 1359 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(&U)) { 1360 for (auto Idx : EVI->indices()) 1361 Indices.push_back(ConstantInt::get(Int32Ty, Idx)); 1362 } else if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(&U)) { 1363 for (auto Idx : IVI->indices()) 1364 Indices.push_back(ConstantInt::get(Int32Ty, Idx)); 1365 } else { 1366 for (unsigned i = 1; i < U.getNumOperands(); ++i) 1367 Indices.push_back(U.getOperand(i)); 1368 } 1369 1370 return 8 * static_cast<uint64_t>( 1371 DL.getIndexedOffsetInType(Src->getType(), Indices)); 1372 } 1373 1374 bool IRTranslator::translateExtractValue(const User &U, 1375 MachineIRBuilder &MIRBuilder) { 1376 const Value *Src = U.getOperand(0); 1377 uint64_t Offset = getOffsetFromIndices(U, *DL); 1378 ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src); 1379 ArrayRef<uint64_t> Offsets = *VMap.getOffsets(*Src); 1380 unsigned Idx = llvm::lower_bound(Offsets, Offset) - Offsets.begin(); 1381 auto &DstRegs = allocateVRegs(U); 1382 1383 for (unsigned i = 0; i < DstRegs.size(); ++i) 1384 DstRegs[i] = SrcRegs[Idx++]; 1385 1386 return true; 1387 } 1388 1389 bool IRTranslator::translateInsertValue(const User &U, 1390 MachineIRBuilder &MIRBuilder) { 1391 const Value *Src = U.getOperand(0); 1392 uint64_t Offset = getOffsetFromIndices(U, *DL); 1393 auto &DstRegs = allocateVRegs(U); 1394 ArrayRef<uint64_t> DstOffsets = *VMap.getOffsets(U); 1395 ArrayRef<Register> SrcRegs = getOrCreateVRegs(*Src); 1396 ArrayRef<Register> InsertedRegs = getOrCreateVRegs(*U.getOperand(1)); 1397 auto InsertedIt = InsertedRegs.begin(); 1398 1399 for (unsigned i = 0; i < DstRegs.size(); ++i) { 1400 if (DstOffsets[i] >= Offset && InsertedIt != InsertedRegs.end()) 1401 DstRegs[i] = *InsertedIt++; 1402 else 1403 DstRegs[i] = SrcRegs[i]; 1404 } 1405 1406 return true; 1407 } 1408 1409 bool IRTranslator::translateSelect(const User &U, 1410 MachineIRBuilder &MIRBuilder) { 1411 Register Tst = getOrCreateVReg(*U.getOperand(0)); 1412 ArrayRef<Register> ResRegs = getOrCreateVRegs(U); 1413 ArrayRef<Register> Op0Regs = getOrCreateVRegs(*U.getOperand(1)); 1414 ArrayRef<Register> Op1Regs = getOrCreateVRegs(*U.getOperand(2)); 1415 1416 uint16_t Flags = 0; 1417 if (const SelectInst *SI = dyn_cast<SelectInst>(&U)) 1418 Flags = MachineInstr::copyFlagsFromInstruction(*SI); 1419 1420 for (unsigned i = 0; i < ResRegs.size(); ++i) { 1421 MIRBuilder.buildSelect(ResRegs[i], Tst, Op0Regs[i], Op1Regs[i], Flags); 1422 } 1423 1424 return true; 1425 } 1426 1427 bool IRTranslator::translateCopy(const User &U, const Value &V, 1428 MachineIRBuilder &MIRBuilder) { 1429 Register Src = getOrCreateVReg(V); 1430 auto &Regs = *VMap.getVRegs(U); 1431 if (Regs.empty()) { 1432 Regs.push_back(Src); 1433 VMap.getOffsets(U)->push_back(0); 1434 } else { 1435 // If we already assigned a vreg for this instruction, we can't change that. 1436 // Emit a copy to satisfy the users we already emitted. 1437 MIRBuilder.buildCopy(Regs[0], Src); 1438 } 1439 return true; 1440 } 1441 1442 bool IRTranslator::translateBitCast(const User &U, 1443 MachineIRBuilder &MIRBuilder) { 1444 // If we're bitcasting to the source type, we can reuse the source vreg. 1445 if (getLLTForType(*U.getOperand(0)->getType(), *DL) == 1446 getLLTForType(*U.getType(), *DL)) 1447 return translateCopy(U, *U.getOperand(0), MIRBuilder); 1448 1449 return translateCast(TargetOpcode::G_BITCAST, U, MIRBuilder); 1450 } 1451 1452 bool IRTranslator::translateCast(unsigned Opcode, const User &U, 1453 MachineIRBuilder &MIRBuilder) { 1454 Register Op = getOrCreateVReg(*U.getOperand(0)); 1455 Register Res = getOrCreateVReg(U); 1456 MIRBuilder.buildInstr(Opcode, {Res}, {Op}); 1457 return true; 1458 } 1459 1460 bool IRTranslator::translateGetElementPtr(const User &U, 1461 MachineIRBuilder &MIRBuilder) { 1462 Value &Op0 = *U.getOperand(0); 1463 Register BaseReg = getOrCreateVReg(Op0); 1464 Type *PtrIRTy = Op0.getType(); 1465 LLT PtrTy = getLLTForType(*PtrIRTy, *DL); 1466 Type *OffsetIRTy = DL->getIntPtrType(PtrIRTy); 1467 LLT OffsetTy = getLLTForType(*OffsetIRTy, *DL); 1468 1469 // Normalize Vector GEP - all scalar operands should be converted to the 1470 // splat vector. 1471 unsigned VectorWidth = 0; 1472 if (auto *VT = dyn_cast<VectorType>(U.getType())) 1473 VectorWidth = cast<FixedVectorType>(VT)->getNumElements(); 1474 1475 // We might need to splat the base pointer into a vector if the offsets 1476 // are vectors. 1477 if (VectorWidth && !PtrTy.isVector()) { 1478 BaseReg = 1479 MIRBuilder.buildSplatVector(LLT::vector(VectorWidth, PtrTy), BaseReg) 1480 .getReg(0); 1481 PtrIRTy = FixedVectorType::get(PtrIRTy, VectorWidth); 1482 PtrTy = getLLTForType(*PtrIRTy, *DL); 1483 OffsetIRTy = DL->getIntPtrType(PtrIRTy); 1484 OffsetTy = getLLTForType(*OffsetIRTy, *DL); 1485 } 1486 1487 int64_t Offset = 0; 1488 for (gep_type_iterator GTI = gep_type_begin(&U), E = gep_type_end(&U); 1489 GTI != E; ++GTI) { 1490 const Value *Idx = GTI.getOperand(); 1491 if (StructType *StTy = GTI.getStructTypeOrNull()) { 1492 unsigned Field = cast<Constant>(Idx)->getUniqueInteger().getZExtValue(); 1493 Offset += DL->getStructLayout(StTy)->getElementOffset(Field); 1494 continue; 1495 } else { 1496 uint64_t ElementSize = DL->getTypeAllocSize(GTI.getIndexedType()); 1497 1498 // If this is a scalar constant or a splat vector of constants, 1499 // handle it quickly. 1500 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) { 1501 Offset += ElementSize * CI->getSExtValue(); 1502 continue; 1503 } 1504 1505 if (Offset != 0) { 1506 auto OffsetMIB = MIRBuilder.buildConstant({OffsetTy}, Offset); 1507 BaseReg = MIRBuilder.buildPtrAdd(PtrTy, BaseReg, OffsetMIB.getReg(0)) 1508 .getReg(0); 1509 Offset = 0; 1510 } 1511 1512 Register IdxReg = getOrCreateVReg(*Idx); 1513 LLT IdxTy = MRI->getType(IdxReg); 1514 if (IdxTy != OffsetTy) { 1515 if (!IdxTy.isVector() && VectorWidth) { 1516 IdxReg = MIRBuilder.buildSplatVector( 1517 OffsetTy.changeElementType(IdxTy), IdxReg).getReg(0); 1518 } 1519 1520 IdxReg = MIRBuilder.buildSExtOrTrunc(OffsetTy, IdxReg).getReg(0); 1521 } 1522 1523 // N = N + Idx * ElementSize; 1524 // Avoid doing it for ElementSize of 1. 1525 Register GepOffsetReg; 1526 if (ElementSize != 1) { 1527 auto ElementSizeMIB = MIRBuilder.buildConstant( 1528 getLLTForType(*OffsetIRTy, *DL), ElementSize); 1529 GepOffsetReg = 1530 MIRBuilder.buildMul(OffsetTy, IdxReg, ElementSizeMIB).getReg(0); 1531 } else 1532 GepOffsetReg = IdxReg; 1533 1534 BaseReg = MIRBuilder.buildPtrAdd(PtrTy, BaseReg, GepOffsetReg).getReg(0); 1535 } 1536 } 1537 1538 if (Offset != 0) { 1539 auto OffsetMIB = 1540 MIRBuilder.buildConstant(OffsetTy, Offset); 1541 MIRBuilder.buildPtrAdd(getOrCreateVReg(U), BaseReg, OffsetMIB.getReg(0)); 1542 return true; 1543 } 1544 1545 MIRBuilder.buildCopy(getOrCreateVReg(U), BaseReg); 1546 return true; 1547 } 1548 1549 bool IRTranslator::translateMemFunc(const CallInst &CI, 1550 MachineIRBuilder &MIRBuilder, 1551 unsigned Opcode) { 1552 1553 // If the source is undef, then just emit a nop. 1554 if (isa<UndefValue>(CI.getArgOperand(1))) 1555 return true; 1556 1557 SmallVector<Register, 3> SrcRegs; 1558 1559 unsigned MinPtrSize = UINT_MAX; 1560 for (auto AI = CI.arg_begin(), AE = CI.arg_end(); std::next(AI) != AE; ++AI) { 1561 Register SrcReg = getOrCreateVReg(**AI); 1562 LLT SrcTy = MRI->getType(SrcReg); 1563 if (SrcTy.isPointer()) 1564 MinPtrSize = std::min(SrcTy.getSizeInBits(), MinPtrSize); 1565 SrcRegs.push_back(SrcReg); 1566 } 1567 1568 LLT SizeTy = LLT::scalar(MinPtrSize); 1569 1570 // The size operand should be the minimum of the pointer sizes. 1571 Register &SizeOpReg = SrcRegs[SrcRegs.size() - 1]; 1572 if (MRI->getType(SizeOpReg) != SizeTy) 1573 SizeOpReg = MIRBuilder.buildZExtOrTrunc(SizeTy, SizeOpReg).getReg(0); 1574 1575 auto ICall = MIRBuilder.buildInstr(Opcode); 1576 for (Register SrcReg : SrcRegs) 1577 ICall.addUse(SrcReg); 1578 1579 Align DstAlign; 1580 Align SrcAlign; 1581 unsigned IsVol = 1582 cast<ConstantInt>(CI.getArgOperand(CI.getNumArgOperands() - 1)) 1583 ->getZExtValue(); 1584 1585 if (auto *MCI = dyn_cast<MemCpyInst>(&CI)) { 1586 DstAlign = MCI->getDestAlign().valueOrOne(); 1587 SrcAlign = MCI->getSourceAlign().valueOrOne(); 1588 } else if (auto *MMI = dyn_cast<MemMoveInst>(&CI)) { 1589 DstAlign = MMI->getDestAlign().valueOrOne(); 1590 SrcAlign = MMI->getSourceAlign().valueOrOne(); 1591 } else { 1592 auto *MSI = cast<MemSetInst>(&CI); 1593 DstAlign = MSI->getDestAlign().valueOrOne(); 1594 } 1595 1596 // We need to propagate the tail call flag from the IR inst as an argument. 1597 // Otherwise, we have to pessimize and assume later that we cannot tail call 1598 // any memory intrinsics. 1599 ICall.addImm(CI.isTailCall() ? 1 : 0); 1600 1601 // Create mem operands to store the alignment and volatile info. 1602 auto VolFlag = IsVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone; 1603 ICall.addMemOperand(MF->getMachineMemOperand( 1604 MachinePointerInfo(CI.getArgOperand(0)), 1605 MachineMemOperand::MOStore | VolFlag, 1, DstAlign)); 1606 if (Opcode != TargetOpcode::G_MEMSET) 1607 ICall.addMemOperand(MF->getMachineMemOperand( 1608 MachinePointerInfo(CI.getArgOperand(1)), 1609 MachineMemOperand::MOLoad | VolFlag, 1, SrcAlign)); 1610 1611 return true; 1612 } 1613 1614 void IRTranslator::getStackGuard(Register DstReg, 1615 MachineIRBuilder &MIRBuilder) { 1616 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo(); 1617 MRI->setRegClass(DstReg, TRI->getPointerRegClass(*MF)); 1618 auto MIB = 1619 MIRBuilder.buildInstr(TargetOpcode::LOAD_STACK_GUARD, {DstReg}, {}); 1620 1621 auto &TLI = *MF->getSubtarget().getTargetLowering(); 1622 Value *Global = TLI.getSDagStackGuard(*MF->getFunction().getParent()); 1623 if (!Global) 1624 return; 1625 1626 MachinePointerInfo MPInfo(Global); 1627 auto Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOInvariant | 1628 MachineMemOperand::MODereferenceable; 1629 MachineMemOperand *MemRef = 1630 MF->getMachineMemOperand(MPInfo, Flags, DL->getPointerSizeInBits() / 8, 1631 DL->getPointerABIAlignment(0)); 1632 MIB.setMemRefs({MemRef}); 1633 } 1634 1635 bool IRTranslator::translateOverflowIntrinsic(const CallInst &CI, unsigned Op, 1636 MachineIRBuilder &MIRBuilder) { 1637 ArrayRef<Register> ResRegs = getOrCreateVRegs(CI); 1638 MIRBuilder.buildInstr( 1639 Op, {ResRegs[0], ResRegs[1]}, 1640 {getOrCreateVReg(*CI.getOperand(0)), getOrCreateVReg(*CI.getOperand(1))}); 1641 1642 return true; 1643 } 1644 1645 bool IRTranslator::translateFixedPointIntrinsic(unsigned Op, const CallInst &CI, 1646 MachineIRBuilder &MIRBuilder) { 1647 Register Dst = getOrCreateVReg(CI); 1648 Register Src0 = getOrCreateVReg(*CI.getOperand(0)); 1649 Register Src1 = getOrCreateVReg(*CI.getOperand(1)); 1650 uint64_t Scale = cast<ConstantInt>(CI.getOperand(2))->getZExtValue(); 1651 MIRBuilder.buildInstr(Op, {Dst}, { Src0, Src1, Scale }); 1652 return true; 1653 } 1654 1655 unsigned IRTranslator::getSimpleIntrinsicOpcode(Intrinsic::ID ID) { 1656 switch (ID) { 1657 default: 1658 break; 1659 case Intrinsic::bswap: 1660 return TargetOpcode::G_BSWAP; 1661 case Intrinsic::bitreverse: 1662 return TargetOpcode::G_BITREVERSE; 1663 case Intrinsic::fshl: 1664 return TargetOpcode::G_FSHL; 1665 case Intrinsic::fshr: 1666 return TargetOpcode::G_FSHR; 1667 case Intrinsic::ceil: 1668 return TargetOpcode::G_FCEIL; 1669 case Intrinsic::cos: 1670 return TargetOpcode::G_FCOS; 1671 case Intrinsic::ctpop: 1672 return TargetOpcode::G_CTPOP; 1673 case Intrinsic::exp: 1674 return TargetOpcode::G_FEXP; 1675 case Intrinsic::exp2: 1676 return TargetOpcode::G_FEXP2; 1677 case Intrinsic::fabs: 1678 return TargetOpcode::G_FABS; 1679 case Intrinsic::copysign: 1680 return TargetOpcode::G_FCOPYSIGN; 1681 case Intrinsic::minnum: 1682 return TargetOpcode::G_FMINNUM; 1683 case Intrinsic::maxnum: 1684 return TargetOpcode::G_FMAXNUM; 1685 case Intrinsic::minimum: 1686 return TargetOpcode::G_FMINIMUM; 1687 case Intrinsic::maximum: 1688 return TargetOpcode::G_FMAXIMUM; 1689 case Intrinsic::canonicalize: 1690 return TargetOpcode::G_FCANONICALIZE; 1691 case Intrinsic::floor: 1692 return TargetOpcode::G_FFLOOR; 1693 case Intrinsic::fma: 1694 return TargetOpcode::G_FMA; 1695 case Intrinsic::log: 1696 return TargetOpcode::G_FLOG; 1697 case Intrinsic::log2: 1698 return TargetOpcode::G_FLOG2; 1699 case Intrinsic::log10: 1700 return TargetOpcode::G_FLOG10; 1701 case Intrinsic::nearbyint: 1702 return TargetOpcode::G_FNEARBYINT; 1703 case Intrinsic::pow: 1704 return TargetOpcode::G_FPOW; 1705 case Intrinsic::powi: 1706 return TargetOpcode::G_FPOWI; 1707 case Intrinsic::rint: 1708 return TargetOpcode::G_FRINT; 1709 case Intrinsic::round: 1710 return TargetOpcode::G_INTRINSIC_ROUND; 1711 case Intrinsic::roundeven: 1712 return TargetOpcode::G_INTRINSIC_ROUNDEVEN; 1713 case Intrinsic::sin: 1714 return TargetOpcode::G_FSIN; 1715 case Intrinsic::sqrt: 1716 return TargetOpcode::G_FSQRT; 1717 case Intrinsic::trunc: 1718 return TargetOpcode::G_INTRINSIC_TRUNC; 1719 case Intrinsic::readcyclecounter: 1720 return TargetOpcode::G_READCYCLECOUNTER; 1721 case Intrinsic::ptrmask: 1722 return TargetOpcode::G_PTRMASK; 1723 case Intrinsic::lrint: 1724 return TargetOpcode::G_INTRINSIC_LRINT; 1725 // FADD/FMUL require checking the FMF, so are handled elsewhere. 1726 case Intrinsic::vector_reduce_fmin: 1727 return TargetOpcode::G_VECREDUCE_FMIN; 1728 case Intrinsic::vector_reduce_fmax: 1729 return TargetOpcode::G_VECREDUCE_FMAX; 1730 case Intrinsic::vector_reduce_add: 1731 return TargetOpcode::G_VECREDUCE_ADD; 1732 case Intrinsic::vector_reduce_mul: 1733 return TargetOpcode::G_VECREDUCE_MUL; 1734 case Intrinsic::vector_reduce_and: 1735 return TargetOpcode::G_VECREDUCE_AND; 1736 case Intrinsic::vector_reduce_or: 1737 return TargetOpcode::G_VECREDUCE_OR; 1738 case Intrinsic::vector_reduce_xor: 1739 return TargetOpcode::G_VECREDUCE_XOR; 1740 case Intrinsic::vector_reduce_smax: 1741 return TargetOpcode::G_VECREDUCE_SMAX; 1742 case Intrinsic::vector_reduce_smin: 1743 return TargetOpcode::G_VECREDUCE_SMIN; 1744 case Intrinsic::vector_reduce_umax: 1745 return TargetOpcode::G_VECREDUCE_UMAX; 1746 case Intrinsic::vector_reduce_umin: 1747 return TargetOpcode::G_VECREDUCE_UMIN; 1748 } 1749 return Intrinsic::not_intrinsic; 1750 } 1751 1752 bool IRTranslator::translateSimpleIntrinsic(const CallInst &CI, 1753 Intrinsic::ID ID, 1754 MachineIRBuilder &MIRBuilder) { 1755 1756 unsigned Op = getSimpleIntrinsicOpcode(ID); 1757 1758 // Is this a simple intrinsic? 1759 if (Op == Intrinsic::not_intrinsic) 1760 return false; 1761 1762 // Yes. Let's translate it. 1763 SmallVector<llvm::SrcOp, 4> VRegs; 1764 for (auto &Arg : CI.arg_operands()) 1765 VRegs.push_back(getOrCreateVReg(*Arg)); 1766 1767 MIRBuilder.buildInstr(Op, {getOrCreateVReg(CI)}, VRegs, 1768 MachineInstr::copyFlagsFromInstruction(CI)); 1769 return true; 1770 } 1771 1772 // TODO: Include ConstainedOps.def when all strict instructions are defined. 1773 static unsigned getConstrainedOpcode(Intrinsic::ID ID) { 1774 switch (ID) { 1775 case Intrinsic::experimental_constrained_fadd: 1776 return TargetOpcode::G_STRICT_FADD; 1777 case Intrinsic::experimental_constrained_fsub: 1778 return TargetOpcode::G_STRICT_FSUB; 1779 case Intrinsic::experimental_constrained_fmul: 1780 return TargetOpcode::G_STRICT_FMUL; 1781 case Intrinsic::experimental_constrained_fdiv: 1782 return TargetOpcode::G_STRICT_FDIV; 1783 case Intrinsic::experimental_constrained_frem: 1784 return TargetOpcode::G_STRICT_FREM; 1785 case Intrinsic::experimental_constrained_fma: 1786 return TargetOpcode::G_STRICT_FMA; 1787 case Intrinsic::experimental_constrained_sqrt: 1788 return TargetOpcode::G_STRICT_FSQRT; 1789 default: 1790 return 0; 1791 } 1792 } 1793 1794 bool IRTranslator::translateConstrainedFPIntrinsic( 1795 const ConstrainedFPIntrinsic &FPI, MachineIRBuilder &MIRBuilder) { 1796 fp::ExceptionBehavior EB = FPI.getExceptionBehavior().getValue(); 1797 1798 unsigned Opcode = getConstrainedOpcode(FPI.getIntrinsicID()); 1799 if (!Opcode) 1800 return false; 1801 1802 unsigned Flags = MachineInstr::copyFlagsFromInstruction(FPI); 1803 if (EB == fp::ExceptionBehavior::ebIgnore) 1804 Flags |= MachineInstr::NoFPExcept; 1805 1806 SmallVector<llvm::SrcOp, 4> VRegs; 1807 VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(0))); 1808 if (!FPI.isUnaryOp()) 1809 VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(1))); 1810 if (FPI.isTernaryOp()) 1811 VRegs.push_back(getOrCreateVReg(*FPI.getArgOperand(2))); 1812 1813 MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(FPI)}, VRegs, Flags); 1814 return true; 1815 } 1816 1817 bool IRTranslator::translateKnownIntrinsic(const CallInst &CI, Intrinsic::ID ID, 1818 MachineIRBuilder &MIRBuilder) { 1819 1820 // If this is a simple intrinsic (that is, we just need to add a def of 1821 // a vreg, and uses for each arg operand, then translate it. 1822 if (translateSimpleIntrinsic(CI, ID, MIRBuilder)) 1823 return true; 1824 1825 switch (ID) { 1826 default: 1827 break; 1828 case Intrinsic::lifetime_start: 1829 case Intrinsic::lifetime_end: { 1830 // No stack colouring in O0, discard region information. 1831 if (MF->getTarget().getOptLevel() == CodeGenOpt::None) 1832 return true; 1833 1834 unsigned Op = ID == Intrinsic::lifetime_start ? TargetOpcode::LIFETIME_START 1835 : TargetOpcode::LIFETIME_END; 1836 1837 // Get the underlying objects for the location passed on the lifetime 1838 // marker. 1839 SmallVector<const Value *, 4> Allocas; 1840 getUnderlyingObjects(CI.getArgOperand(1), Allocas); 1841 1842 // Iterate over each underlying object, creating lifetime markers for each 1843 // static alloca. Quit if we find a non-static alloca. 1844 for (const Value *V : Allocas) { 1845 const AllocaInst *AI = dyn_cast<AllocaInst>(V); 1846 if (!AI) 1847 continue; 1848 1849 if (!AI->isStaticAlloca()) 1850 return true; 1851 1852 MIRBuilder.buildInstr(Op).addFrameIndex(getOrCreateFrameIndex(*AI)); 1853 } 1854 return true; 1855 } 1856 case Intrinsic::dbg_declare: { 1857 const DbgDeclareInst &DI = cast<DbgDeclareInst>(CI); 1858 assert(DI.getVariable() && "Missing variable"); 1859 1860 const Value *Address = DI.getAddress(); 1861 if (!Address || isa<UndefValue>(Address)) { 1862 LLVM_DEBUG(dbgs() << "Dropping debug info for " << DI << "\n"); 1863 return true; 1864 } 1865 1866 assert(DI.getVariable()->isValidLocationForIntrinsic( 1867 MIRBuilder.getDebugLoc()) && 1868 "Expected inlined-at fields to agree"); 1869 auto AI = dyn_cast<AllocaInst>(Address); 1870 if (AI && AI->isStaticAlloca()) { 1871 // Static allocas are tracked at the MF level, no need for DBG_VALUE 1872 // instructions (in fact, they get ignored if they *do* exist). 1873 MF->setVariableDbgInfo(DI.getVariable(), DI.getExpression(), 1874 getOrCreateFrameIndex(*AI), DI.getDebugLoc()); 1875 } else { 1876 // A dbg.declare describes the address of a source variable, so lower it 1877 // into an indirect DBG_VALUE. 1878 MIRBuilder.buildIndirectDbgValue(getOrCreateVReg(*Address), 1879 DI.getVariable(), DI.getExpression()); 1880 } 1881 return true; 1882 } 1883 case Intrinsic::dbg_label: { 1884 const DbgLabelInst &DI = cast<DbgLabelInst>(CI); 1885 assert(DI.getLabel() && "Missing label"); 1886 1887 assert(DI.getLabel()->isValidLocationForIntrinsic( 1888 MIRBuilder.getDebugLoc()) && 1889 "Expected inlined-at fields to agree"); 1890 1891 MIRBuilder.buildDbgLabel(DI.getLabel()); 1892 return true; 1893 } 1894 case Intrinsic::vaend: 1895 // No target I know of cares about va_end. Certainly no in-tree target 1896 // does. Simplest intrinsic ever! 1897 return true; 1898 case Intrinsic::vastart: { 1899 auto &TLI = *MF->getSubtarget().getTargetLowering(); 1900 Value *Ptr = CI.getArgOperand(0); 1901 unsigned ListSize = TLI.getVaListSizeInBits(*DL) / 8; 1902 1903 // FIXME: Get alignment 1904 MIRBuilder.buildInstr(TargetOpcode::G_VASTART, {}, {getOrCreateVReg(*Ptr)}) 1905 .addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Ptr), 1906 MachineMemOperand::MOStore, 1907 ListSize, Align(1))); 1908 return true; 1909 } 1910 case Intrinsic::dbg_value: { 1911 // This form of DBG_VALUE is target-independent. 1912 const DbgValueInst &DI = cast<DbgValueInst>(CI); 1913 const Value *V = DI.getValue(); 1914 assert(DI.getVariable()->isValidLocationForIntrinsic( 1915 MIRBuilder.getDebugLoc()) && 1916 "Expected inlined-at fields to agree"); 1917 if (!V) { 1918 // Currently the optimizer can produce this; insert an undef to 1919 // help debugging. Probably the optimizer should not do this. 1920 MIRBuilder.buildIndirectDbgValue(0, DI.getVariable(), DI.getExpression()); 1921 } else if (const auto *CI = dyn_cast<Constant>(V)) { 1922 MIRBuilder.buildConstDbgValue(*CI, DI.getVariable(), DI.getExpression()); 1923 } else { 1924 for (Register Reg : getOrCreateVRegs(*V)) { 1925 // FIXME: This does not handle register-indirect values at offset 0. The 1926 // direct/indirect thing shouldn't really be handled by something as 1927 // implicit as reg+noreg vs reg+imm in the first place, but it seems 1928 // pretty baked in right now. 1929 MIRBuilder.buildDirectDbgValue(Reg, DI.getVariable(), DI.getExpression()); 1930 } 1931 } 1932 return true; 1933 } 1934 case Intrinsic::uadd_with_overflow: 1935 return translateOverflowIntrinsic(CI, TargetOpcode::G_UADDO, MIRBuilder); 1936 case Intrinsic::sadd_with_overflow: 1937 return translateOverflowIntrinsic(CI, TargetOpcode::G_SADDO, MIRBuilder); 1938 case Intrinsic::usub_with_overflow: 1939 return translateOverflowIntrinsic(CI, TargetOpcode::G_USUBO, MIRBuilder); 1940 case Intrinsic::ssub_with_overflow: 1941 return translateOverflowIntrinsic(CI, TargetOpcode::G_SSUBO, MIRBuilder); 1942 case Intrinsic::umul_with_overflow: 1943 return translateOverflowIntrinsic(CI, TargetOpcode::G_UMULO, MIRBuilder); 1944 case Intrinsic::smul_with_overflow: 1945 return translateOverflowIntrinsic(CI, TargetOpcode::G_SMULO, MIRBuilder); 1946 case Intrinsic::uadd_sat: 1947 return translateBinaryOp(TargetOpcode::G_UADDSAT, CI, MIRBuilder); 1948 case Intrinsic::sadd_sat: 1949 return translateBinaryOp(TargetOpcode::G_SADDSAT, CI, MIRBuilder); 1950 case Intrinsic::usub_sat: 1951 return translateBinaryOp(TargetOpcode::G_USUBSAT, CI, MIRBuilder); 1952 case Intrinsic::ssub_sat: 1953 return translateBinaryOp(TargetOpcode::G_SSUBSAT, CI, MIRBuilder); 1954 case Intrinsic::ushl_sat: 1955 return translateBinaryOp(TargetOpcode::G_USHLSAT, CI, MIRBuilder); 1956 case Intrinsic::sshl_sat: 1957 return translateBinaryOp(TargetOpcode::G_SSHLSAT, CI, MIRBuilder); 1958 case Intrinsic::umin: 1959 return translateBinaryOp(TargetOpcode::G_UMIN, CI, MIRBuilder); 1960 case Intrinsic::umax: 1961 return translateBinaryOp(TargetOpcode::G_UMAX, CI, MIRBuilder); 1962 case Intrinsic::smin: 1963 return translateBinaryOp(TargetOpcode::G_SMIN, CI, MIRBuilder); 1964 case Intrinsic::smax: 1965 return translateBinaryOp(TargetOpcode::G_SMAX, CI, MIRBuilder); 1966 case Intrinsic::abs: 1967 // TODO: Preserve "int min is poison" arg in GMIR? 1968 return translateUnaryOp(TargetOpcode::G_ABS, CI, MIRBuilder); 1969 case Intrinsic::smul_fix: 1970 return translateFixedPointIntrinsic(TargetOpcode::G_SMULFIX, CI, MIRBuilder); 1971 case Intrinsic::umul_fix: 1972 return translateFixedPointIntrinsic(TargetOpcode::G_UMULFIX, CI, MIRBuilder); 1973 case Intrinsic::smul_fix_sat: 1974 return translateFixedPointIntrinsic(TargetOpcode::G_SMULFIXSAT, CI, MIRBuilder); 1975 case Intrinsic::umul_fix_sat: 1976 return translateFixedPointIntrinsic(TargetOpcode::G_UMULFIXSAT, CI, MIRBuilder); 1977 case Intrinsic::sdiv_fix: 1978 return translateFixedPointIntrinsic(TargetOpcode::G_SDIVFIX, CI, MIRBuilder); 1979 case Intrinsic::udiv_fix: 1980 return translateFixedPointIntrinsic(TargetOpcode::G_UDIVFIX, CI, MIRBuilder); 1981 case Intrinsic::sdiv_fix_sat: 1982 return translateFixedPointIntrinsic(TargetOpcode::G_SDIVFIXSAT, CI, MIRBuilder); 1983 case Intrinsic::udiv_fix_sat: 1984 return translateFixedPointIntrinsic(TargetOpcode::G_UDIVFIXSAT, CI, MIRBuilder); 1985 case Intrinsic::fmuladd: { 1986 const TargetMachine &TM = MF->getTarget(); 1987 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering(); 1988 Register Dst = getOrCreateVReg(CI); 1989 Register Op0 = getOrCreateVReg(*CI.getArgOperand(0)); 1990 Register Op1 = getOrCreateVReg(*CI.getArgOperand(1)); 1991 Register Op2 = getOrCreateVReg(*CI.getArgOperand(2)); 1992 if (TM.Options.AllowFPOpFusion != FPOpFusion::Strict && 1993 TLI.isFMAFasterThanFMulAndFAdd(*MF, 1994 TLI.getValueType(*DL, CI.getType()))) { 1995 // TODO: Revisit this to see if we should move this part of the 1996 // lowering to the combiner. 1997 MIRBuilder.buildFMA(Dst, Op0, Op1, Op2, 1998 MachineInstr::copyFlagsFromInstruction(CI)); 1999 } else { 2000 LLT Ty = getLLTForType(*CI.getType(), *DL); 2001 auto FMul = MIRBuilder.buildFMul( 2002 Ty, Op0, Op1, MachineInstr::copyFlagsFromInstruction(CI)); 2003 MIRBuilder.buildFAdd(Dst, FMul, Op2, 2004 MachineInstr::copyFlagsFromInstruction(CI)); 2005 } 2006 return true; 2007 } 2008 case Intrinsic::convert_from_fp16: 2009 // FIXME: This intrinsic should probably be removed from the IR. 2010 MIRBuilder.buildFPExt(getOrCreateVReg(CI), 2011 getOrCreateVReg(*CI.getArgOperand(0)), 2012 MachineInstr::copyFlagsFromInstruction(CI)); 2013 return true; 2014 case Intrinsic::convert_to_fp16: 2015 // FIXME: This intrinsic should probably be removed from the IR. 2016 MIRBuilder.buildFPTrunc(getOrCreateVReg(CI), 2017 getOrCreateVReg(*CI.getArgOperand(0)), 2018 MachineInstr::copyFlagsFromInstruction(CI)); 2019 return true; 2020 case Intrinsic::memcpy: 2021 return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMCPY); 2022 case Intrinsic::memmove: 2023 return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMMOVE); 2024 case Intrinsic::memset: 2025 return translateMemFunc(CI, MIRBuilder, TargetOpcode::G_MEMSET); 2026 case Intrinsic::eh_typeid_for: { 2027 GlobalValue *GV = ExtractTypeInfo(CI.getArgOperand(0)); 2028 Register Reg = getOrCreateVReg(CI); 2029 unsigned TypeID = MF->getTypeIDFor(GV); 2030 MIRBuilder.buildConstant(Reg, TypeID); 2031 return true; 2032 } 2033 case Intrinsic::objectsize: 2034 llvm_unreachable("llvm.objectsize.* should have been lowered already"); 2035 2036 case Intrinsic::is_constant: 2037 llvm_unreachable("llvm.is.constant.* should have been lowered already"); 2038 2039 case Intrinsic::stackguard: 2040 getStackGuard(getOrCreateVReg(CI), MIRBuilder); 2041 return true; 2042 case Intrinsic::stackprotector: { 2043 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL); 2044 Register GuardVal = MRI->createGenericVirtualRegister(PtrTy); 2045 getStackGuard(GuardVal, MIRBuilder); 2046 2047 AllocaInst *Slot = cast<AllocaInst>(CI.getArgOperand(1)); 2048 int FI = getOrCreateFrameIndex(*Slot); 2049 MF->getFrameInfo().setStackProtectorIndex(FI); 2050 2051 MIRBuilder.buildStore( 2052 GuardVal, getOrCreateVReg(*Slot), 2053 *MF->getMachineMemOperand(MachinePointerInfo::getFixedStack(*MF, FI), 2054 MachineMemOperand::MOStore | 2055 MachineMemOperand::MOVolatile, 2056 PtrTy.getSizeInBits() / 8, Align(8))); 2057 return true; 2058 } 2059 case Intrinsic::stacksave: { 2060 // Save the stack pointer to the location provided by the intrinsic. 2061 Register Reg = getOrCreateVReg(CI); 2062 Register StackPtr = MF->getSubtarget() 2063 .getTargetLowering() 2064 ->getStackPointerRegisterToSaveRestore(); 2065 2066 // If the target doesn't specify a stack pointer, then fall back. 2067 if (!StackPtr) 2068 return false; 2069 2070 MIRBuilder.buildCopy(Reg, StackPtr); 2071 return true; 2072 } 2073 case Intrinsic::stackrestore: { 2074 // Restore the stack pointer from the location provided by the intrinsic. 2075 Register Reg = getOrCreateVReg(*CI.getArgOperand(0)); 2076 Register StackPtr = MF->getSubtarget() 2077 .getTargetLowering() 2078 ->getStackPointerRegisterToSaveRestore(); 2079 2080 // If the target doesn't specify a stack pointer, then fall back. 2081 if (!StackPtr) 2082 return false; 2083 2084 MIRBuilder.buildCopy(StackPtr, Reg); 2085 return true; 2086 } 2087 case Intrinsic::cttz: 2088 case Intrinsic::ctlz: { 2089 ConstantInt *Cst = cast<ConstantInt>(CI.getArgOperand(1)); 2090 bool isTrailing = ID == Intrinsic::cttz; 2091 unsigned Opcode = isTrailing 2092 ? Cst->isZero() ? TargetOpcode::G_CTTZ 2093 : TargetOpcode::G_CTTZ_ZERO_UNDEF 2094 : Cst->isZero() ? TargetOpcode::G_CTLZ 2095 : TargetOpcode::G_CTLZ_ZERO_UNDEF; 2096 MIRBuilder.buildInstr(Opcode, {getOrCreateVReg(CI)}, 2097 {getOrCreateVReg(*CI.getArgOperand(0))}); 2098 return true; 2099 } 2100 case Intrinsic::invariant_start: { 2101 LLT PtrTy = getLLTForType(*CI.getArgOperand(0)->getType(), *DL); 2102 Register Undef = MRI->createGenericVirtualRegister(PtrTy); 2103 MIRBuilder.buildUndef(Undef); 2104 return true; 2105 } 2106 case Intrinsic::invariant_end: 2107 return true; 2108 case Intrinsic::expect: 2109 case Intrinsic::annotation: 2110 case Intrinsic::ptr_annotation: 2111 case Intrinsic::launder_invariant_group: 2112 case Intrinsic::strip_invariant_group: { 2113 // Drop the intrinsic, but forward the value. 2114 MIRBuilder.buildCopy(getOrCreateVReg(CI), 2115 getOrCreateVReg(*CI.getArgOperand(0))); 2116 return true; 2117 } 2118 case Intrinsic::assume: 2119 case Intrinsic::var_annotation: 2120 case Intrinsic::sideeffect: 2121 // Discard annotate attributes, assumptions, and artificial side-effects. 2122 return true; 2123 case Intrinsic::read_volatile_register: 2124 case Intrinsic::read_register: { 2125 Value *Arg = CI.getArgOperand(0); 2126 MIRBuilder 2127 .buildInstr(TargetOpcode::G_READ_REGISTER, {getOrCreateVReg(CI)}, {}) 2128 .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata())); 2129 return true; 2130 } 2131 case Intrinsic::write_register: { 2132 Value *Arg = CI.getArgOperand(0); 2133 MIRBuilder.buildInstr(TargetOpcode::G_WRITE_REGISTER) 2134 .addMetadata(cast<MDNode>(cast<MetadataAsValue>(Arg)->getMetadata())) 2135 .addUse(getOrCreateVReg(*CI.getArgOperand(1))); 2136 return true; 2137 } 2138 case Intrinsic::localescape: { 2139 MachineBasicBlock &EntryMBB = MF->front(); 2140 StringRef EscapedName = GlobalValue::dropLLVMManglingEscape(MF->getName()); 2141 2142 // Directly emit some LOCAL_ESCAPE machine instrs. Label assignment emission 2143 // is the same on all targets. 2144 for (unsigned Idx = 0, E = CI.getNumArgOperands(); Idx < E; ++Idx) { 2145 Value *Arg = CI.getArgOperand(Idx)->stripPointerCasts(); 2146 if (isa<ConstantPointerNull>(Arg)) 2147 continue; // Skip null pointers. They represent a hole in index space. 2148 2149 int FI = getOrCreateFrameIndex(*cast<AllocaInst>(Arg)); 2150 MCSymbol *FrameAllocSym = 2151 MF->getMMI().getContext().getOrCreateFrameAllocSymbol(EscapedName, 2152 Idx); 2153 2154 // This should be inserted at the start of the entry block. 2155 auto LocalEscape = 2156 MIRBuilder.buildInstrNoInsert(TargetOpcode::LOCAL_ESCAPE) 2157 .addSym(FrameAllocSym) 2158 .addFrameIndex(FI); 2159 2160 EntryMBB.insert(EntryMBB.begin(), LocalEscape); 2161 } 2162 2163 return true; 2164 } 2165 case Intrinsic::vector_reduce_fadd: 2166 case Intrinsic::vector_reduce_fmul: { 2167 // Need to check for the reassoc flag to decide whether we want a 2168 // sequential reduction opcode or not. 2169 Register Dst = getOrCreateVReg(CI); 2170 Register ScalarSrc = getOrCreateVReg(*CI.getArgOperand(0)); 2171 Register VecSrc = getOrCreateVReg(*CI.getArgOperand(1)); 2172 unsigned Opc = 0; 2173 if (!CI.hasAllowReassoc()) { 2174 // The sequential ordering case. 2175 Opc = ID == Intrinsic::vector_reduce_fadd 2176 ? TargetOpcode::G_VECREDUCE_SEQ_FADD 2177 : TargetOpcode::G_VECREDUCE_SEQ_FMUL; 2178 MIRBuilder.buildInstr(Opc, {Dst}, {ScalarSrc, VecSrc}, 2179 MachineInstr::copyFlagsFromInstruction(CI)); 2180 return true; 2181 } 2182 // We split the operation into a separate G_FADD/G_FMUL + the reduce, 2183 // since the associativity doesn't matter. 2184 unsigned ScalarOpc; 2185 if (ID == Intrinsic::vector_reduce_fadd) { 2186 Opc = TargetOpcode::G_VECREDUCE_FADD; 2187 ScalarOpc = TargetOpcode::G_FADD; 2188 } else { 2189 Opc = TargetOpcode::G_VECREDUCE_FMUL; 2190 ScalarOpc = TargetOpcode::G_FMUL; 2191 } 2192 LLT DstTy = MRI->getType(Dst); 2193 auto Rdx = MIRBuilder.buildInstr( 2194 Opc, {DstTy}, {VecSrc}, MachineInstr::copyFlagsFromInstruction(CI)); 2195 MIRBuilder.buildInstr(ScalarOpc, {Dst}, {ScalarSrc, Rdx}, 2196 MachineInstr::copyFlagsFromInstruction(CI)); 2197 2198 return true; 2199 } 2200 #define INSTRUCTION(NAME, NARG, ROUND_MODE, INTRINSIC) \ 2201 case Intrinsic::INTRINSIC: 2202 #include "llvm/IR/ConstrainedOps.def" 2203 return translateConstrainedFPIntrinsic(cast<ConstrainedFPIntrinsic>(CI), 2204 MIRBuilder); 2205 2206 } 2207 return false; 2208 } 2209 2210 bool IRTranslator::translateInlineAsm(const CallBase &CB, 2211 MachineIRBuilder &MIRBuilder) { 2212 2213 const InlineAsmLowering *ALI = MF->getSubtarget().getInlineAsmLowering(); 2214 2215 if (!ALI) { 2216 LLVM_DEBUG( 2217 dbgs() << "Inline asm lowering is not supported for this target yet\n"); 2218 return false; 2219 } 2220 2221 return ALI->lowerInlineAsm( 2222 MIRBuilder, CB, [&](const Value &Val) { return getOrCreateVRegs(Val); }); 2223 } 2224 2225 bool IRTranslator::translateCallBase(const CallBase &CB, 2226 MachineIRBuilder &MIRBuilder) { 2227 ArrayRef<Register> Res = getOrCreateVRegs(CB); 2228 2229 SmallVector<ArrayRef<Register>, 8> Args; 2230 Register SwiftInVReg = 0; 2231 Register SwiftErrorVReg = 0; 2232 for (auto &Arg : CB.args()) { 2233 if (CLI->supportSwiftError() && isSwiftError(Arg)) { 2234 assert(SwiftInVReg == 0 && "Expected only one swift error argument"); 2235 LLT Ty = getLLTForType(*Arg->getType(), *DL); 2236 SwiftInVReg = MRI->createGenericVirtualRegister(Ty); 2237 MIRBuilder.buildCopy(SwiftInVReg, SwiftError.getOrCreateVRegUseAt( 2238 &CB, &MIRBuilder.getMBB(), Arg)); 2239 Args.emplace_back(makeArrayRef(SwiftInVReg)); 2240 SwiftErrorVReg = 2241 SwiftError.getOrCreateVRegDefAt(&CB, &MIRBuilder.getMBB(), Arg); 2242 continue; 2243 } 2244 Args.push_back(getOrCreateVRegs(*Arg)); 2245 } 2246 2247 // We don't set HasCalls on MFI here yet because call lowering may decide to 2248 // optimize into tail calls. Instead, we defer that to selection where a final 2249 // scan is done to check if any instructions are calls. 2250 bool Success = 2251 CLI->lowerCall(MIRBuilder, CB, Res, Args, SwiftErrorVReg, 2252 [&]() { return getOrCreateVReg(*CB.getCalledOperand()); }); 2253 2254 // Check if we just inserted a tail call. 2255 if (Success) { 2256 assert(!HasTailCall && "Can't tail call return twice from block?"); 2257 const TargetInstrInfo *TII = MF->getSubtarget().getInstrInfo(); 2258 HasTailCall = TII->isTailCall(*std::prev(MIRBuilder.getInsertPt())); 2259 } 2260 2261 return Success; 2262 } 2263 2264 bool IRTranslator::translateCall(const User &U, MachineIRBuilder &MIRBuilder) { 2265 const CallInst &CI = cast<CallInst>(U); 2266 auto TII = MF->getTarget().getIntrinsicInfo(); 2267 const Function *F = CI.getCalledFunction(); 2268 2269 // FIXME: support Windows dllimport function calls. 2270 if (F && (F->hasDLLImportStorageClass() || 2271 (MF->getTarget().getTargetTriple().isOSWindows() && 2272 F->hasExternalWeakLinkage()))) 2273 return false; 2274 2275 // FIXME: support control flow guard targets. 2276 if (CI.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget)) 2277 return false; 2278 2279 if (CI.isInlineAsm()) 2280 return translateInlineAsm(CI, MIRBuilder); 2281 2282 Intrinsic::ID ID = Intrinsic::not_intrinsic; 2283 if (F && F->isIntrinsic()) { 2284 ID = F->getIntrinsicID(); 2285 if (TII && ID == Intrinsic::not_intrinsic) 2286 ID = static_cast<Intrinsic::ID>(TII->getIntrinsicID(F)); 2287 } 2288 2289 if (!F || !F->isIntrinsic() || ID == Intrinsic::not_intrinsic) 2290 return translateCallBase(CI, MIRBuilder); 2291 2292 assert(ID != Intrinsic::not_intrinsic && "unknown intrinsic"); 2293 2294 if (translateKnownIntrinsic(CI, ID, MIRBuilder)) 2295 return true; 2296 2297 ArrayRef<Register> ResultRegs; 2298 if (!CI.getType()->isVoidTy()) 2299 ResultRegs = getOrCreateVRegs(CI); 2300 2301 // Ignore the callsite attributes. Backend code is most likely not expecting 2302 // an intrinsic to sometimes have side effects and sometimes not. 2303 MachineInstrBuilder MIB = 2304 MIRBuilder.buildIntrinsic(ID, ResultRegs, !F->doesNotAccessMemory()); 2305 if (isa<FPMathOperator>(CI)) 2306 MIB->copyIRFlags(CI); 2307 2308 for (auto &Arg : enumerate(CI.arg_operands())) { 2309 // If this is required to be an immediate, don't materialize it in a 2310 // register. 2311 if (CI.paramHasAttr(Arg.index(), Attribute::ImmArg)) { 2312 if (ConstantInt *CI = dyn_cast<ConstantInt>(Arg.value())) { 2313 // imm arguments are more convenient than cimm (and realistically 2314 // probably sufficient), so use them. 2315 assert(CI->getBitWidth() <= 64 && 2316 "large intrinsic immediates not handled"); 2317 MIB.addImm(CI->getSExtValue()); 2318 } else { 2319 MIB.addFPImm(cast<ConstantFP>(Arg.value())); 2320 } 2321 } else if (auto MD = dyn_cast<MetadataAsValue>(Arg.value())) { 2322 auto *MDN = dyn_cast<MDNode>(MD->getMetadata()); 2323 if (!MDN) // This was probably an MDString. 2324 return false; 2325 MIB.addMetadata(MDN); 2326 } else { 2327 ArrayRef<Register> VRegs = getOrCreateVRegs(*Arg.value()); 2328 if (VRegs.size() > 1) 2329 return false; 2330 MIB.addUse(VRegs[0]); 2331 } 2332 } 2333 2334 // Add a MachineMemOperand if it is a target mem intrinsic. 2335 const TargetLowering &TLI = *MF->getSubtarget().getTargetLowering(); 2336 TargetLowering::IntrinsicInfo Info; 2337 // TODO: Add a GlobalISel version of getTgtMemIntrinsic. 2338 if (TLI.getTgtMemIntrinsic(Info, CI, *MF, ID)) { 2339 Align Alignment = Info.align.getValueOr( 2340 DL->getABITypeAlign(Info.memVT.getTypeForEVT(F->getContext()))); 2341 2342 uint64_t Size = Info.memVT.getStoreSize(); 2343 MIB.addMemOperand(MF->getMachineMemOperand(MachinePointerInfo(Info.ptrVal), 2344 Info.flags, Size, Alignment)); 2345 } 2346 2347 return true; 2348 } 2349 2350 bool IRTranslator::findUnwindDestinations( 2351 const BasicBlock *EHPadBB, 2352 BranchProbability Prob, 2353 SmallVectorImpl<std::pair<MachineBasicBlock *, BranchProbability>> 2354 &UnwindDests) { 2355 EHPersonality Personality = classifyEHPersonality( 2356 EHPadBB->getParent()->getFunction().getPersonalityFn()); 2357 bool IsMSVCCXX = Personality == EHPersonality::MSVC_CXX; 2358 bool IsCoreCLR = Personality == EHPersonality::CoreCLR; 2359 bool IsWasmCXX = Personality == EHPersonality::Wasm_CXX; 2360 bool IsSEH = isAsynchronousEHPersonality(Personality); 2361 2362 if (IsWasmCXX) { 2363 // Ignore this for now. 2364 return false; 2365 } 2366 2367 while (EHPadBB) { 2368 const Instruction *Pad = EHPadBB->getFirstNonPHI(); 2369 BasicBlock *NewEHPadBB = nullptr; 2370 if (isa<LandingPadInst>(Pad)) { 2371 // Stop on landingpads. They are not funclets. 2372 UnwindDests.emplace_back(&getMBB(*EHPadBB), Prob); 2373 break; 2374 } 2375 if (isa<CleanupPadInst>(Pad)) { 2376 // Stop on cleanup pads. Cleanups are always funclet entries for all known 2377 // personalities. 2378 UnwindDests.emplace_back(&getMBB(*EHPadBB), Prob); 2379 UnwindDests.back().first->setIsEHScopeEntry(); 2380 UnwindDests.back().first->setIsEHFuncletEntry(); 2381 break; 2382 } 2383 if (auto *CatchSwitch = dyn_cast<CatchSwitchInst>(Pad)) { 2384 // Add the catchpad handlers to the possible destinations. 2385 for (const BasicBlock *CatchPadBB : CatchSwitch->handlers()) { 2386 UnwindDests.emplace_back(&getMBB(*CatchPadBB), Prob); 2387 // For MSVC++ and the CLR, catchblocks are funclets and need prologues. 2388 if (IsMSVCCXX || IsCoreCLR) 2389 UnwindDests.back().first->setIsEHFuncletEntry(); 2390 if (!IsSEH) 2391 UnwindDests.back().first->setIsEHScopeEntry(); 2392 } 2393 NewEHPadBB = CatchSwitch->getUnwindDest(); 2394 } else { 2395 continue; 2396 } 2397 2398 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2399 if (BPI && NewEHPadBB) 2400 Prob *= BPI->getEdgeProbability(EHPadBB, NewEHPadBB); 2401 EHPadBB = NewEHPadBB; 2402 } 2403 return true; 2404 } 2405 2406 bool IRTranslator::translateInvoke(const User &U, 2407 MachineIRBuilder &MIRBuilder) { 2408 const InvokeInst &I = cast<InvokeInst>(U); 2409 MCContext &Context = MF->getContext(); 2410 2411 const BasicBlock *ReturnBB = I.getSuccessor(0); 2412 const BasicBlock *EHPadBB = I.getSuccessor(1); 2413 2414 const Function *Fn = I.getCalledFunction(); 2415 if (I.isInlineAsm()) 2416 return false; 2417 2418 // FIXME: support invoking patchpoint and statepoint intrinsics. 2419 if (Fn && Fn->isIntrinsic()) 2420 return false; 2421 2422 // FIXME: support whatever these are. 2423 if (I.countOperandBundlesOfType(LLVMContext::OB_deopt)) 2424 return false; 2425 2426 // FIXME: support control flow guard targets. 2427 if (I.countOperandBundlesOfType(LLVMContext::OB_cfguardtarget)) 2428 return false; 2429 2430 // FIXME: support Windows exception handling. 2431 if (!isa<LandingPadInst>(EHPadBB->getFirstNonPHI())) 2432 return false; 2433 2434 // Emit the actual call, bracketed by EH_LABELs so that the MF knows about 2435 // the region covered by the try. 2436 MCSymbol *BeginSymbol = Context.createTempSymbol(); 2437 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(BeginSymbol); 2438 2439 if (!translateCallBase(I, MIRBuilder)) 2440 return false; 2441 2442 MCSymbol *EndSymbol = Context.createTempSymbol(); 2443 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL).addSym(EndSymbol); 2444 2445 SmallVector<std::pair<MachineBasicBlock *, BranchProbability>, 1> UnwindDests; 2446 BranchProbabilityInfo *BPI = FuncInfo.BPI; 2447 MachineBasicBlock *InvokeMBB = &MIRBuilder.getMBB(); 2448 BranchProbability EHPadBBProb = 2449 BPI ? BPI->getEdgeProbability(InvokeMBB->getBasicBlock(), EHPadBB) 2450 : BranchProbability::getZero(); 2451 2452 if (!findUnwindDestinations(EHPadBB, EHPadBBProb, UnwindDests)) 2453 return false; 2454 2455 MachineBasicBlock &EHPadMBB = getMBB(*EHPadBB), 2456 &ReturnMBB = getMBB(*ReturnBB); 2457 // Update successor info. 2458 addSuccessorWithProb(InvokeMBB, &ReturnMBB); 2459 for (auto &UnwindDest : UnwindDests) { 2460 UnwindDest.first->setIsEHPad(); 2461 addSuccessorWithProb(InvokeMBB, UnwindDest.first, UnwindDest.second); 2462 } 2463 InvokeMBB->normalizeSuccProbs(); 2464 2465 MF->addInvoke(&EHPadMBB, BeginSymbol, EndSymbol); 2466 MIRBuilder.buildBr(ReturnMBB); 2467 return true; 2468 } 2469 2470 bool IRTranslator::translateCallBr(const User &U, 2471 MachineIRBuilder &MIRBuilder) { 2472 // FIXME: Implement this. 2473 return false; 2474 } 2475 2476 bool IRTranslator::translateLandingPad(const User &U, 2477 MachineIRBuilder &MIRBuilder) { 2478 const LandingPadInst &LP = cast<LandingPadInst>(U); 2479 2480 MachineBasicBlock &MBB = MIRBuilder.getMBB(); 2481 2482 MBB.setIsEHPad(); 2483 2484 // If there aren't registers to copy the values into (e.g., during SjLj 2485 // exceptions), then don't bother. 2486 auto &TLI = *MF->getSubtarget().getTargetLowering(); 2487 const Constant *PersonalityFn = MF->getFunction().getPersonalityFn(); 2488 if (TLI.getExceptionPointerRegister(PersonalityFn) == 0 && 2489 TLI.getExceptionSelectorRegister(PersonalityFn) == 0) 2490 return true; 2491 2492 // If landingpad's return type is token type, we don't create DAG nodes 2493 // for its exception pointer and selector value. The extraction of exception 2494 // pointer or selector value from token type landingpads is not currently 2495 // supported. 2496 if (LP.getType()->isTokenTy()) 2497 return true; 2498 2499 // Add a label to mark the beginning of the landing pad. Deletion of the 2500 // landing pad can thus be detected via the MachineModuleInfo. 2501 MIRBuilder.buildInstr(TargetOpcode::EH_LABEL) 2502 .addSym(MF->addLandingPad(&MBB)); 2503 2504 // If the unwinder does not preserve all registers, ensure that the 2505 // function marks the clobbered registers as used. 2506 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo(); 2507 if (auto *RegMask = TRI.getCustomEHPadPreservedMask(*MF)) 2508 MF->getRegInfo().addPhysRegsUsedFromRegMask(RegMask); 2509 2510 LLT Ty = getLLTForType(*LP.getType(), *DL); 2511 Register Undef = MRI->createGenericVirtualRegister(Ty); 2512 MIRBuilder.buildUndef(Undef); 2513 2514 SmallVector<LLT, 2> Tys; 2515 for (Type *Ty : cast<StructType>(LP.getType())->elements()) 2516 Tys.push_back(getLLTForType(*Ty, *DL)); 2517 assert(Tys.size() == 2 && "Only two-valued landingpads are supported"); 2518 2519 // Mark exception register as live in. 2520 Register ExceptionReg = TLI.getExceptionPointerRegister(PersonalityFn); 2521 if (!ExceptionReg) 2522 return false; 2523 2524 MBB.addLiveIn(ExceptionReg); 2525 ArrayRef<Register> ResRegs = getOrCreateVRegs(LP); 2526 MIRBuilder.buildCopy(ResRegs[0], ExceptionReg); 2527 2528 Register SelectorReg = TLI.getExceptionSelectorRegister(PersonalityFn); 2529 if (!SelectorReg) 2530 return false; 2531 2532 MBB.addLiveIn(SelectorReg); 2533 Register PtrVReg = MRI->createGenericVirtualRegister(Tys[0]); 2534 MIRBuilder.buildCopy(PtrVReg, SelectorReg); 2535 MIRBuilder.buildCast(ResRegs[1], PtrVReg); 2536 2537 return true; 2538 } 2539 2540 bool IRTranslator::translateAlloca(const User &U, 2541 MachineIRBuilder &MIRBuilder) { 2542 auto &AI = cast<AllocaInst>(U); 2543 2544 if (AI.isSwiftError()) 2545 return true; 2546 2547 if (AI.isStaticAlloca()) { 2548 Register Res = getOrCreateVReg(AI); 2549 int FI = getOrCreateFrameIndex(AI); 2550 MIRBuilder.buildFrameIndex(Res, FI); 2551 return true; 2552 } 2553 2554 // FIXME: support stack probing for Windows. 2555 if (MF->getTarget().getTargetTriple().isOSWindows()) 2556 return false; 2557 2558 // Now we're in the harder dynamic case. 2559 Register NumElts = getOrCreateVReg(*AI.getArraySize()); 2560 Type *IntPtrIRTy = DL->getIntPtrType(AI.getType()); 2561 LLT IntPtrTy = getLLTForType(*IntPtrIRTy, *DL); 2562 if (MRI->getType(NumElts) != IntPtrTy) { 2563 Register ExtElts = MRI->createGenericVirtualRegister(IntPtrTy); 2564 MIRBuilder.buildZExtOrTrunc(ExtElts, NumElts); 2565 NumElts = ExtElts; 2566 } 2567 2568 Type *Ty = AI.getAllocatedType(); 2569 2570 Register AllocSize = MRI->createGenericVirtualRegister(IntPtrTy); 2571 Register TySize = 2572 getOrCreateVReg(*ConstantInt::get(IntPtrIRTy, DL->getTypeAllocSize(Ty))); 2573 MIRBuilder.buildMul(AllocSize, NumElts, TySize); 2574 2575 // Round the size of the allocation up to the stack alignment size 2576 // by add SA-1 to the size. This doesn't overflow because we're computing 2577 // an address inside an alloca. 2578 Align StackAlign = MF->getSubtarget().getFrameLowering()->getStackAlign(); 2579 auto SAMinusOne = MIRBuilder.buildConstant(IntPtrTy, StackAlign.value() - 1); 2580 auto AllocAdd = MIRBuilder.buildAdd(IntPtrTy, AllocSize, SAMinusOne, 2581 MachineInstr::NoUWrap); 2582 auto AlignCst = 2583 MIRBuilder.buildConstant(IntPtrTy, ~(uint64_t)(StackAlign.value() - 1)); 2584 auto AlignedAlloc = MIRBuilder.buildAnd(IntPtrTy, AllocAdd, AlignCst); 2585 2586 Align Alignment = std::max(AI.getAlign(), DL->getPrefTypeAlign(Ty)); 2587 if (Alignment <= StackAlign) 2588 Alignment = Align(1); 2589 MIRBuilder.buildDynStackAlloc(getOrCreateVReg(AI), AlignedAlloc, Alignment); 2590 2591 MF->getFrameInfo().CreateVariableSizedObject(Alignment, &AI); 2592 assert(MF->getFrameInfo().hasVarSizedObjects()); 2593 return true; 2594 } 2595 2596 bool IRTranslator::translateVAArg(const User &U, MachineIRBuilder &MIRBuilder) { 2597 // FIXME: We may need more info about the type. Because of how LLT works, 2598 // we're completely discarding the i64/double distinction here (amongst 2599 // others). Fortunately the ABIs I know of where that matters don't use va_arg 2600 // anyway but that's not guaranteed. 2601 MIRBuilder.buildInstr(TargetOpcode::G_VAARG, {getOrCreateVReg(U)}, 2602 {getOrCreateVReg(*U.getOperand(0)), 2603 DL->getABITypeAlign(U.getType()).value()}); 2604 return true; 2605 } 2606 2607 bool IRTranslator::translateInsertElement(const User &U, 2608 MachineIRBuilder &MIRBuilder) { 2609 // If it is a <1 x Ty> vector, use the scalar as it is 2610 // not a legal vector type in LLT. 2611 if (cast<FixedVectorType>(U.getType())->getNumElements() == 1) 2612 return translateCopy(U, *U.getOperand(1), MIRBuilder); 2613 2614 Register Res = getOrCreateVReg(U); 2615 Register Val = getOrCreateVReg(*U.getOperand(0)); 2616 Register Elt = getOrCreateVReg(*U.getOperand(1)); 2617 Register Idx = getOrCreateVReg(*U.getOperand(2)); 2618 MIRBuilder.buildInsertVectorElement(Res, Val, Elt, Idx); 2619 return true; 2620 } 2621 2622 bool IRTranslator::translateExtractElement(const User &U, 2623 MachineIRBuilder &MIRBuilder) { 2624 // If it is a <1 x Ty> vector, use the scalar as it is 2625 // not a legal vector type in LLT. 2626 if (cast<FixedVectorType>(U.getOperand(0)->getType())->getNumElements() == 1) 2627 return translateCopy(U, *U.getOperand(0), MIRBuilder); 2628 2629 Register Res = getOrCreateVReg(U); 2630 Register Val = getOrCreateVReg(*U.getOperand(0)); 2631 const auto &TLI = *MF->getSubtarget().getTargetLowering(); 2632 unsigned PreferredVecIdxWidth = TLI.getVectorIdxTy(*DL).getSizeInBits(); 2633 Register Idx; 2634 if (auto *CI = dyn_cast<ConstantInt>(U.getOperand(1))) { 2635 if (CI->getBitWidth() != PreferredVecIdxWidth) { 2636 APInt NewIdx = CI->getValue().sextOrTrunc(PreferredVecIdxWidth); 2637 auto *NewIdxCI = ConstantInt::get(CI->getContext(), NewIdx); 2638 Idx = getOrCreateVReg(*NewIdxCI); 2639 } 2640 } 2641 if (!Idx) 2642 Idx = getOrCreateVReg(*U.getOperand(1)); 2643 if (MRI->getType(Idx).getSizeInBits() != PreferredVecIdxWidth) { 2644 const LLT VecIdxTy = LLT::scalar(PreferredVecIdxWidth); 2645 Idx = MIRBuilder.buildSExtOrTrunc(VecIdxTy, Idx).getReg(0); 2646 } 2647 MIRBuilder.buildExtractVectorElement(Res, Val, Idx); 2648 return true; 2649 } 2650 2651 bool IRTranslator::translateShuffleVector(const User &U, 2652 MachineIRBuilder &MIRBuilder) { 2653 ArrayRef<int> Mask; 2654 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&U)) 2655 Mask = SVI->getShuffleMask(); 2656 else 2657 Mask = cast<ConstantExpr>(U).getShuffleMask(); 2658 ArrayRef<int> MaskAlloc = MF->allocateShuffleMask(Mask); 2659 MIRBuilder 2660 .buildInstr(TargetOpcode::G_SHUFFLE_VECTOR, {getOrCreateVReg(U)}, 2661 {getOrCreateVReg(*U.getOperand(0)), 2662 getOrCreateVReg(*U.getOperand(1))}) 2663 .addShuffleMask(MaskAlloc); 2664 return true; 2665 } 2666 2667 bool IRTranslator::translatePHI(const User &U, MachineIRBuilder &MIRBuilder) { 2668 const PHINode &PI = cast<PHINode>(U); 2669 2670 SmallVector<MachineInstr *, 4> Insts; 2671 for (auto Reg : getOrCreateVRegs(PI)) { 2672 auto MIB = MIRBuilder.buildInstr(TargetOpcode::G_PHI, {Reg}, {}); 2673 Insts.push_back(MIB.getInstr()); 2674 } 2675 2676 PendingPHIs.emplace_back(&PI, std::move(Insts)); 2677 return true; 2678 } 2679 2680 bool IRTranslator::translateAtomicCmpXchg(const User &U, 2681 MachineIRBuilder &MIRBuilder) { 2682 const AtomicCmpXchgInst &I = cast<AtomicCmpXchgInst>(U); 2683 2684 auto &TLI = *MF->getSubtarget().getTargetLowering(); 2685 auto Flags = TLI.getAtomicMemOperandFlags(I, *DL); 2686 2687 Type *ResType = I.getType(); 2688 Type *ValType = ResType->Type::getStructElementType(0); 2689 2690 auto Res = getOrCreateVRegs(I); 2691 Register OldValRes = Res[0]; 2692 Register SuccessRes = Res[1]; 2693 Register Addr = getOrCreateVReg(*I.getPointerOperand()); 2694 Register Cmp = getOrCreateVReg(*I.getCompareOperand()); 2695 Register NewVal = getOrCreateVReg(*I.getNewValOperand()); 2696 2697 AAMDNodes AAMetadata; 2698 I.getAAMetadata(AAMetadata); 2699 2700 MIRBuilder.buildAtomicCmpXchgWithSuccess( 2701 OldValRes, SuccessRes, Addr, Cmp, NewVal, 2702 *MF->getMachineMemOperand( 2703 MachinePointerInfo(I.getPointerOperand()), Flags, 2704 DL->getTypeStoreSize(ValType), getMemOpAlign(I), AAMetadata, nullptr, 2705 I.getSyncScopeID(), I.getSuccessOrdering(), I.getFailureOrdering())); 2706 return true; 2707 } 2708 2709 bool IRTranslator::translateAtomicRMW(const User &U, 2710 MachineIRBuilder &MIRBuilder) { 2711 const AtomicRMWInst &I = cast<AtomicRMWInst>(U); 2712 auto &TLI = *MF->getSubtarget().getTargetLowering(); 2713 auto Flags = TLI.getAtomicMemOperandFlags(I, *DL); 2714 2715 Type *ResType = I.getType(); 2716 2717 Register Res = getOrCreateVReg(I); 2718 Register Addr = getOrCreateVReg(*I.getPointerOperand()); 2719 Register Val = getOrCreateVReg(*I.getValOperand()); 2720 2721 unsigned Opcode = 0; 2722 switch (I.getOperation()) { 2723 default: 2724 return false; 2725 case AtomicRMWInst::Xchg: 2726 Opcode = TargetOpcode::G_ATOMICRMW_XCHG; 2727 break; 2728 case AtomicRMWInst::Add: 2729 Opcode = TargetOpcode::G_ATOMICRMW_ADD; 2730 break; 2731 case AtomicRMWInst::Sub: 2732 Opcode = TargetOpcode::G_ATOMICRMW_SUB; 2733 break; 2734 case AtomicRMWInst::And: 2735 Opcode = TargetOpcode::G_ATOMICRMW_AND; 2736 break; 2737 case AtomicRMWInst::Nand: 2738 Opcode = TargetOpcode::G_ATOMICRMW_NAND; 2739 break; 2740 case AtomicRMWInst::Or: 2741 Opcode = TargetOpcode::G_ATOMICRMW_OR; 2742 break; 2743 case AtomicRMWInst::Xor: 2744 Opcode = TargetOpcode::G_ATOMICRMW_XOR; 2745 break; 2746 case AtomicRMWInst::Max: 2747 Opcode = TargetOpcode::G_ATOMICRMW_MAX; 2748 break; 2749 case AtomicRMWInst::Min: 2750 Opcode = TargetOpcode::G_ATOMICRMW_MIN; 2751 break; 2752 case AtomicRMWInst::UMax: 2753 Opcode = TargetOpcode::G_ATOMICRMW_UMAX; 2754 break; 2755 case AtomicRMWInst::UMin: 2756 Opcode = TargetOpcode::G_ATOMICRMW_UMIN; 2757 break; 2758 case AtomicRMWInst::FAdd: 2759 Opcode = TargetOpcode::G_ATOMICRMW_FADD; 2760 break; 2761 case AtomicRMWInst::FSub: 2762 Opcode = TargetOpcode::G_ATOMICRMW_FSUB; 2763 break; 2764 } 2765 2766 AAMDNodes AAMetadata; 2767 I.getAAMetadata(AAMetadata); 2768 2769 MIRBuilder.buildAtomicRMW( 2770 Opcode, Res, Addr, Val, 2771 *MF->getMachineMemOperand(MachinePointerInfo(I.getPointerOperand()), 2772 Flags, DL->getTypeStoreSize(ResType), 2773 getMemOpAlign(I), AAMetadata, nullptr, 2774 I.getSyncScopeID(), I.getOrdering())); 2775 return true; 2776 } 2777 2778 bool IRTranslator::translateFence(const User &U, 2779 MachineIRBuilder &MIRBuilder) { 2780 const FenceInst &Fence = cast<FenceInst>(U); 2781 MIRBuilder.buildFence(static_cast<unsigned>(Fence.getOrdering()), 2782 Fence.getSyncScopeID()); 2783 return true; 2784 } 2785 2786 bool IRTranslator::translateFreeze(const User &U, 2787 MachineIRBuilder &MIRBuilder) { 2788 const ArrayRef<Register> DstRegs = getOrCreateVRegs(U); 2789 const ArrayRef<Register> SrcRegs = getOrCreateVRegs(*U.getOperand(0)); 2790 2791 assert(DstRegs.size() == SrcRegs.size() && 2792 "Freeze with different source and destination type?"); 2793 2794 for (unsigned I = 0; I < DstRegs.size(); ++I) { 2795 MIRBuilder.buildFreeze(DstRegs[I], SrcRegs[I]); 2796 } 2797 2798 return true; 2799 } 2800 2801 void IRTranslator::finishPendingPhis() { 2802 #ifndef NDEBUG 2803 DILocationVerifier Verifier; 2804 GISelObserverWrapper WrapperObserver(&Verifier); 2805 RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver); 2806 #endif // ifndef NDEBUG 2807 for (auto &Phi : PendingPHIs) { 2808 const PHINode *PI = Phi.first; 2809 ArrayRef<MachineInstr *> ComponentPHIs = Phi.second; 2810 MachineBasicBlock *PhiMBB = ComponentPHIs[0]->getParent(); 2811 EntryBuilder->setDebugLoc(PI->getDebugLoc()); 2812 #ifndef NDEBUG 2813 Verifier.setCurrentInst(PI); 2814 #endif // ifndef NDEBUG 2815 2816 SmallSet<const MachineBasicBlock *, 16> SeenPreds; 2817 for (unsigned i = 0; i < PI->getNumIncomingValues(); ++i) { 2818 auto IRPred = PI->getIncomingBlock(i); 2819 ArrayRef<Register> ValRegs = getOrCreateVRegs(*PI->getIncomingValue(i)); 2820 for (auto Pred : getMachinePredBBs({IRPred, PI->getParent()})) { 2821 if (SeenPreds.count(Pred) || !PhiMBB->isPredecessor(Pred)) 2822 continue; 2823 SeenPreds.insert(Pred); 2824 for (unsigned j = 0; j < ValRegs.size(); ++j) { 2825 MachineInstrBuilder MIB(*MF, ComponentPHIs[j]); 2826 MIB.addUse(ValRegs[j]); 2827 MIB.addMBB(Pred); 2828 } 2829 } 2830 } 2831 } 2832 } 2833 2834 bool IRTranslator::valueIsSplit(const Value &V, 2835 SmallVectorImpl<uint64_t> *Offsets) { 2836 SmallVector<LLT, 4> SplitTys; 2837 if (Offsets && !Offsets->empty()) 2838 Offsets->clear(); 2839 computeValueLLTs(*DL, *V.getType(), SplitTys, Offsets); 2840 return SplitTys.size() > 1; 2841 } 2842 2843 bool IRTranslator::translate(const Instruction &Inst) { 2844 CurBuilder->setDebugLoc(Inst.getDebugLoc()); 2845 // We only emit constants into the entry block from here. To prevent jumpy 2846 // debug behaviour set the line to 0. 2847 if (const DebugLoc &DL = Inst.getDebugLoc()) 2848 EntryBuilder->setDebugLoc(DILocation::get( 2849 Inst.getContext(), 0, 0, DL.getScope(), DL.getInlinedAt())); 2850 else 2851 EntryBuilder->setDebugLoc(DebugLoc()); 2852 2853 auto &TLI = *MF->getSubtarget().getTargetLowering(); 2854 if (TLI.fallBackToDAGISel(Inst)) 2855 return false; 2856 2857 switch (Inst.getOpcode()) { 2858 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 2859 case Instruction::OPCODE: \ 2860 return translate##OPCODE(Inst, *CurBuilder.get()); 2861 #include "llvm/IR/Instruction.def" 2862 default: 2863 return false; 2864 } 2865 } 2866 2867 bool IRTranslator::translate(const Constant &C, Register Reg) { 2868 if (auto CI = dyn_cast<ConstantInt>(&C)) 2869 EntryBuilder->buildConstant(Reg, *CI); 2870 else if (auto CF = dyn_cast<ConstantFP>(&C)) 2871 EntryBuilder->buildFConstant(Reg, *CF); 2872 else if (isa<UndefValue>(C)) 2873 EntryBuilder->buildUndef(Reg); 2874 else if (isa<ConstantPointerNull>(C)) 2875 EntryBuilder->buildConstant(Reg, 0); 2876 else if (auto GV = dyn_cast<GlobalValue>(&C)) 2877 EntryBuilder->buildGlobalValue(Reg, GV); 2878 else if (auto CAZ = dyn_cast<ConstantAggregateZero>(&C)) { 2879 if (!CAZ->getType()->isVectorTy()) 2880 return false; 2881 // Return the scalar if it is a <1 x Ty> vector. 2882 if (CAZ->getNumElements() == 1) 2883 return translateCopy(C, *CAZ->getElementValue(0u), *EntryBuilder.get()); 2884 SmallVector<Register, 4> Ops; 2885 for (unsigned i = 0; i < CAZ->getNumElements(); ++i) { 2886 Constant &Elt = *CAZ->getElementValue(i); 2887 Ops.push_back(getOrCreateVReg(Elt)); 2888 } 2889 EntryBuilder->buildBuildVector(Reg, Ops); 2890 } else if (auto CV = dyn_cast<ConstantDataVector>(&C)) { 2891 // Return the scalar if it is a <1 x Ty> vector. 2892 if (CV->getNumElements() == 1) 2893 return translateCopy(C, *CV->getElementAsConstant(0), 2894 *EntryBuilder.get()); 2895 SmallVector<Register, 4> Ops; 2896 for (unsigned i = 0; i < CV->getNumElements(); ++i) { 2897 Constant &Elt = *CV->getElementAsConstant(i); 2898 Ops.push_back(getOrCreateVReg(Elt)); 2899 } 2900 EntryBuilder->buildBuildVector(Reg, Ops); 2901 } else if (auto CE = dyn_cast<ConstantExpr>(&C)) { 2902 switch(CE->getOpcode()) { 2903 #define HANDLE_INST(NUM, OPCODE, CLASS) \ 2904 case Instruction::OPCODE: \ 2905 return translate##OPCODE(*CE, *EntryBuilder.get()); 2906 #include "llvm/IR/Instruction.def" 2907 default: 2908 return false; 2909 } 2910 } else if (auto CV = dyn_cast<ConstantVector>(&C)) { 2911 if (CV->getNumOperands() == 1) 2912 return translateCopy(C, *CV->getOperand(0), *EntryBuilder.get()); 2913 SmallVector<Register, 4> Ops; 2914 for (unsigned i = 0; i < CV->getNumOperands(); ++i) { 2915 Ops.push_back(getOrCreateVReg(*CV->getOperand(i))); 2916 } 2917 EntryBuilder->buildBuildVector(Reg, Ops); 2918 } else if (auto *BA = dyn_cast<BlockAddress>(&C)) { 2919 EntryBuilder->buildBlockAddress(Reg, BA); 2920 } else 2921 return false; 2922 2923 return true; 2924 } 2925 2926 void IRTranslator::finalizeBasicBlock() { 2927 for (auto &BTB : SL->BitTestCases) { 2928 // Emit header first, if it wasn't already emitted. 2929 if (!BTB.Emitted) 2930 emitBitTestHeader(BTB, BTB.Parent); 2931 2932 BranchProbability UnhandledProb = BTB.Prob; 2933 for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) { 2934 UnhandledProb -= BTB.Cases[j].ExtraProb; 2935 // Set the current basic block to the mbb we wish to insert the code into 2936 MachineBasicBlock *MBB = BTB.Cases[j].ThisBB; 2937 // If all cases cover a contiguous range, it is not necessary to jump to 2938 // the default block after the last bit test fails. This is because the 2939 // range check during bit test header creation has guaranteed that every 2940 // case here doesn't go outside the range. In this case, there is no need 2941 // to perform the last bit test, as it will always be true. Instead, make 2942 // the second-to-last bit-test fall through to the target of the last bit 2943 // test, and delete the last bit test. 2944 2945 MachineBasicBlock *NextMBB; 2946 if (BTB.ContiguousRange && j + 2 == ej) { 2947 // Second-to-last bit-test with contiguous range: fall through to the 2948 // target of the final bit test. 2949 NextMBB = BTB.Cases[j + 1].TargetBB; 2950 } else if (j + 1 == ej) { 2951 // For the last bit test, fall through to Default. 2952 NextMBB = BTB.Default; 2953 } else { 2954 // Otherwise, fall through to the next bit test. 2955 NextMBB = BTB.Cases[j + 1].ThisBB; 2956 } 2957 2958 emitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j], MBB); 2959 2960 // FIXME delete this block below? 2961 if (BTB.ContiguousRange && j + 2 == ej) { 2962 // Since we're not going to use the final bit test, remove it. 2963 BTB.Cases.pop_back(); 2964 break; 2965 } 2966 } 2967 // This is "default" BB. We have two jumps to it. From "header" BB and from 2968 // last "case" BB, unless the latter was skipped. 2969 CFGEdge HeaderToDefaultEdge = {BTB.Parent->getBasicBlock(), 2970 BTB.Default->getBasicBlock()}; 2971 addMachineCFGPred(HeaderToDefaultEdge, BTB.Parent); 2972 if (!BTB.ContiguousRange) { 2973 addMachineCFGPred(HeaderToDefaultEdge, BTB.Cases.back().ThisBB); 2974 } 2975 } 2976 SL->BitTestCases.clear(); 2977 2978 for (auto &JTCase : SL->JTCases) { 2979 // Emit header first, if it wasn't already emitted. 2980 if (!JTCase.first.Emitted) 2981 emitJumpTableHeader(JTCase.second, JTCase.first, JTCase.first.HeaderBB); 2982 2983 emitJumpTable(JTCase.second, JTCase.second.MBB); 2984 } 2985 SL->JTCases.clear(); 2986 2987 for (auto &SwCase : SL->SwitchCases) 2988 emitSwitchCase(SwCase, &CurBuilder->getMBB(), *CurBuilder); 2989 SL->SwitchCases.clear(); 2990 } 2991 2992 void IRTranslator::finalizeFunction() { 2993 // Release the memory used by the different maps we 2994 // needed during the translation. 2995 PendingPHIs.clear(); 2996 VMap.reset(); 2997 FrameIndices.clear(); 2998 MachinePreds.clear(); 2999 // MachineIRBuilder::DebugLoc can outlive the DILocation it holds. Clear it 3000 // to avoid accessing free’d memory (in runOnMachineFunction) and to avoid 3001 // destroying it twice (in ~IRTranslator() and ~LLVMContext()) 3002 EntryBuilder.reset(); 3003 CurBuilder.reset(); 3004 FuncInfo.clear(); 3005 } 3006 3007 /// Returns true if a BasicBlock \p BB within a variadic function contains a 3008 /// variadic musttail call. 3009 static bool checkForMustTailInVarArgFn(bool IsVarArg, const BasicBlock &BB) { 3010 if (!IsVarArg) 3011 return false; 3012 3013 // Walk the block backwards, because tail calls usually only appear at the end 3014 // of a block. 3015 return std::any_of(BB.rbegin(), BB.rend(), [](const Instruction &I) { 3016 const auto *CI = dyn_cast<CallInst>(&I); 3017 return CI && CI->isMustTailCall(); 3018 }); 3019 } 3020 3021 bool IRTranslator::runOnMachineFunction(MachineFunction &CurMF) { 3022 MF = &CurMF; 3023 const Function &F = MF->getFunction(); 3024 if (F.empty()) 3025 return false; 3026 GISelCSEAnalysisWrapper &Wrapper = 3027 getAnalysis<GISelCSEAnalysisWrapperPass>().getCSEWrapper(); 3028 // Set the CSEConfig and run the analysis. 3029 GISelCSEInfo *CSEInfo = nullptr; 3030 TPC = &getAnalysis<TargetPassConfig>(); 3031 bool EnableCSE = EnableCSEInIRTranslator.getNumOccurrences() 3032 ? EnableCSEInIRTranslator 3033 : TPC->isGISelCSEEnabled(); 3034 3035 if (EnableCSE) { 3036 EntryBuilder = std::make_unique<CSEMIRBuilder>(CurMF); 3037 CSEInfo = &Wrapper.get(TPC->getCSEConfig()); 3038 EntryBuilder->setCSEInfo(CSEInfo); 3039 CurBuilder = std::make_unique<CSEMIRBuilder>(CurMF); 3040 CurBuilder->setCSEInfo(CSEInfo); 3041 } else { 3042 EntryBuilder = std::make_unique<MachineIRBuilder>(); 3043 CurBuilder = std::make_unique<MachineIRBuilder>(); 3044 } 3045 CLI = MF->getSubtarget().getCallLowering(); 3046 CurBuilder->setMF(*MF); 3047 EntryBuilder->setMF(*MF); 3048 MRI = &MF->getRegInfo(); 3049 DL = &F.getParent()->getDataLayout(); 3050 ORE = std::make_unique<OptimizationRemarkEmitter>(&F); 3051 const TargetMachine &TM = MF->getTarget(); 3052 TM.resetTargetOptions(F); 3053 EnableOpts = OptLevel != CodeGenOpt::None && !skipFunction(F); 3054 FuncInfo.MF = MF; 3055 if (EnableOpts) 3056 FuncInfo.BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI(); 3057 else 3058 FuncInfo.BPI = nullptr; 3059 3060 const auto &TLI = *MF->getSubtarget().getTargetLowering(); 3061 3062 SL = std::make_unique<GISelSwitchLowering>(this, FuncInfo); 3063 SL->init(TLI, TM, *DL); 3064 3065 3066 3067 assert(PendingPHIs.empty() && "stale PHIs"); 3068 3069 if (!DL->isLittleEndian()) { 3070 // Currently we don't properly handle big endian code. 3071 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 3072 F.getSubprogram(), &F.getEntryBlock()); 3073 R << "unable to translate in big endian mode"; 3074 reportTranslationError(*MF, *TPC, *ORE, R); 3075 } 3076 3077 // Release the per-function state when we return, whether we succeeded or not. 3078 auto FinalizeOnReturn = make_scope_exit([this]() { finalizeFunction(); }); 3079 3080 // Setup a separate basic-block for the arguments and constants 3081 MachineBasicBlock *EntryBB = MF->CreateMachineBasicBlock(); 3082 MF->push_back(EntryBB); 3083 EntryBuilder->setMBB(*EntryBB); 3084 3085 DebugLoc DbgLoc = F.getEntryBlock().getFirstNonPHI()->getDebugLoc(); 3086 SwiftError.setFunction(CurMF); 3087 SwiftError.createEntriesInEntryBlock(DbgLoc); 3088 3089 bool IsVarArg = F.isVarArg(); 3090 bool HasMustTailInVarArgFn = false; 3091 3092 // Create all blocks, in IR order, to preserve the layout. 3093 for (const BasicBlock &BB: F) { 3094 auto *&MBB = BBToMBB[&BB]; 3095 3096 MBB = MF->CreateMachineBasicBlock(&BB); 3097 MF->push_back(MBB); 3098 3099 if (BB.hasAddressTaken()) 3100 MBB->setHasAddressTaken(); 3101 3102 if (!HasMustTailInVarArgFn) 3103 HasMustTailInVarArgFn = checkForMustTailInVarArgFn(IsVarArg, BB); 3104 } 3105 3106 MF->getFrameInfo().setHasMustTailInVarArgFunc(HasMustTailInVarArgFn); 3107 3108 // Make our arguments/constants entry block fallthrough to the IR entry block. 3109 EntryBB->addSuccessor(&getMBB(F.front())); 3110 3111 if (CLI->fallBackToDAGISel(F)) { 3112 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 3113 F.getSubprogram(), &F.getEntryBlock()); 3114 R << "unable to lower function: " << ore::NV("Prototype", F.getType()); 3115 reportTranslationError(*MF, *TPC, *ORE, R); 3116 return false; 3117 } 3118 3119 // Lower the actual args into this basic block. 3120 SmallVector<ArrayRef<Register>, 8> VRegArgs; 3121 for (const Argument &Arg: F.args()) { 3122 if (DL->getTypeStoreSize(Arg.getType()).isZero()) 3123 continue; // Don't handle zero sized types. 3124 ArrayRef<Register> VRegs = getOrCreateVRegs(Arg); 3125 VRegArgs.push_back(VRegs); 3126 3127 if (Arg.hasSwiftErrorAttr()) { 3128 assert(VRegs.size() == 1 && "Too many vregs for Swift error"); 3129 SwiftError.setCurrentVReg(EntryBB, SwiftError.getFunctionArg(), VRegs[0]); 3130 } 3131 } 3132 3133 if (!CLI->lowerFormalArguments(*EntryBuilder.get(), F, VRegArgs)) { 3134 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 3135 F.getSubprogram(), &F.getEntryBlock()); 3136 R << "unable to lower arguments: " << ore::NV("Prototype", F.getType()); 3137 reportTranslationError(*MF, *TPC, *ORE, R); 3138 return false; 3139 } 3140 3141 // Need to visit defs before uses when translating instructions. 3142 GISelObserverWrapper WrapperObserver; 3143 if (EnableCSE && CSEInfo) 3144 WrapperObserver.addObserver(CSEInfo); 3145 { 3146 ReversePostOrderTraversal<const Function *> RPOT(&F); 3147 #ifndef NDEBUG 3148 DILocationVerifier Verifier; 3149 WrapperObserver.addObserver(&Verifier); 3150 #endif // ifndef NDEBUG 3151 RAIIDelegateInstaller DelInstall(*MF, &WrapperObserver); 3152 RAIIMFObserverInstaller ObsInstall(*MF, WrapperObserver); 3153 for (const BasicBlock *BB : RPOT) { 3154 MachineBasicBlock &MBB = getMBB(*BB); 3155 // Set the insertion point of all the following translations to 3156 // the end of this basic block. 3157 CurBuilder->setMBB(MBB); 3158 HasTailCall = false; 3159 for (const Instruction &Inst : *BB) { 3160 // If we translated a tail call in the last step, then we know 3161 // everything after the call is either a return, or something that is 3162 // handled by the call itself. (E.g. a lifetime marker or assume 3163 // intrinsic.) In this case, we should stop translating the block and 3164 // move on. 3165 if (HasTailCall) 3166 break; 3167 #ifndef NDEBUG 3168 Verifier.setCurrentInst(&Inst); 3169 #endif // ifndef NDEBUG 3170 if (translate(Inst)) 3171 continue; 3172 3173 OptimizationRemarkMissed R("gisel-irtranslator", "GISelFailure", 3174 Inst.getDebugLoc(), BB); 3175 R << "unable to translate instruction: " << ore::NV("Opcode", &Inst); 3176 3177 if (ORE->allowExtraAnalysis("gisel-irtranslator")) { 3178 std::string InstStrStorage; 3179 raw_string_ostream InstStr(InstStrStorage); 3180 InstStr << Inst; 3181 3182 R << ": '" << InstStr.str() << "'"; 3183 } 3184 3185 reportTranslationError(*MF, *TPC, *ORE, R); 3186 return false; 3187 } 3188 3189 finalizeBasicBlock(); 3190 } 3191 #ifndef NDEBUG 3192 WrapperObserver.removeObserver(&Verifier); 3193 #endif 3194 } 3195 3196 finishPendingPhis(); 3197 3198 SwiftError.propagateVRegs(); 3199 3200 // Merge the argument lowering and constants block with its single 3201 // successor, the LLVM-IR entry block. We want the basic block to 3202 // be maximal. 3203 assert(EntryBB->succ_size() == 1 && 3204 "Custom BB used for lowering should have only one successor"); 3205 // Get the successor of the current entry block. 3206 MachineBasicBlock &NewEntryBB = **EntryBB->succ_begin(); 3207 assert(NewEntryBB.pred_size() == 1 && 3208 "LLVM-IR entry block has a predecessor!?"); 3209 // Move all the instruction from the current entry block to the 3210 // new entry block. 3211 NewEntryBB.splice(NewEntryBB.begin(), EntryBB, EntryBB->begin(), 3212 EntryBB->end()); 3213 3214 // Update the live-in information for the new entry block. 3215 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : EntryBB->liveins()) 3216 NewEntryBB.addLiveIn(LiveIn); 3217 NewEntryBB.sortUniqueLiveIns(); 3218 3219 // Get rid of the now empty basic block. 3220 EntryBB->removeSuccessor(&NewEntryBB); 3221 MF->remove(EntryBB); 3222 MF->DeleteMachineBasicBlock(EntryBB); 3223 3224 assert(&MF->front() == &NewEntryBB && 3225 "New entry wasn't next in the list of basic block!"); 3226 3227 // Initialize stack protector information. 3228 StackProtector &SP = getAnalysis<StackProtector>(); 3229 SP.copyToMachineFrameInfo(MF->getFrameInfo()); 3230 3231 return false; 3232 } 3233