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