1 //===- SelectionDAGISel.cpp - Implement the SelectionDAGISel class --------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This implements the SelectionDAGISel class. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/CodeGen/SelectionDAGISel.h" 15 #include "ScheduleDAGSDNodes.h" 16 #include "SelectionDAGBuilder.h" 17 #include "llvm/ADT/APInt.h" 18 #include "llvm/ADT/DenseMap.h" 19 #include "llvm/ADT/None.h" 20 #include "llvm/ADT/PostOrderIterator.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/SmallPtrSet.h" 23 #include "llvm/ADT/SmallSet.h" 24 #include "llvm/ADT/SmallVector.h" 25 #include "llvm/ADT/Statistic.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/Analysis/AliasAnalysis.h" 28 #include "llvm/Analysis/BranchProbabilityInfo.h" 29 #include "llvm/Analysis/CFG.h" 30 #include "llvm/Analysis/EHPersonalities.h" 31 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 32 #include "llvm/Analysis/TargetLibraryInfo.h" 33 #include "llvm/Analysis/TargetTransformInfo.h" 34 #include "llvm/CodeGen/FastISel.h" 35 #include "llvm/CodeGen/FunctionLoweringInfo.h" 36 #include "llvm/CodeGen/GCMetadata.h" 37 #include "llvm/CodeGen/ISDOpcodes.h" 38 #include "llvm/CodeGen/MachineBasicBlock.h" 39 #include "llvm/CodeGen/MachineFrameInfo.h" 40 #include "llvm/CodeGen/MachineFunction.h" 41 #include "llvm/CodeGen/MachineFunctionPass.h" 42 #include "llvm/CodeGen/MachineInstr.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachineMemOperand.h" 45 #include "llvm/CodeGen/MachineOperand.h" 46 #include "llvm/CodeGen/MachinePassRegistry.h" 47 #include "llvm/CodeGen/MachineRegisterInfo.h" 48 #include "llvm/CodeGen/SchedulerRegistry.h" 49 #include "llvm/CodeGen/SelectionDAG.h" 50 #include "llvm/CodeGen/SelectionDAGNodes.h" 51 #include "llvm/CodeGen/StackProtector.h" 52 #include "llvm/CodeGen/TargetInstrInfo.h" 53 #include "llvm/CodeGen/TargetLowering.h" 54 #include "llvm/CodeGen/TargetRegisterInfo.h" 55 #include "llvm/CodeGen/TargetSubtargetInfo.h" 56 #include "llvm/CodeGen/ValueTypes.h" 57 #include "llvm/IR/BasicBlock.h" 58 #include "llvm/IR/Constants.h" 59 #include "llvm/IR/DataLayout.h" 60 #include "llvm/IR/DebugInfoMetadata.h" 61 #include "llvm/IR/DebugLoc.h" 62 #include "llvm/IR/DiagnosticInfo.h" 63 #include "llvm/IR/Dominators.h" 64 #include "llvm/IR/Function.h" 65 #include "llvm/IR/InlineAsm.h" 66 #include "llvm/IR/InstrTypes.h" 67 #include "llvm/IR/Instruction.h" 68 #include "llvm/IR/Instructions.h" 69 #include "llvm/IR/IntrinsicInst.h" 70 #include "llvm/IR/Intrinsics.h" 71 #include "llvm/IR/Metadata.h" 72 #include "llvm/IR/Type.h" 73 #include "llvm/IR/User.h" 74 #include "llvm/IR/Value.h" 75 #include "llvm/MC/MCInstrDesc.h" 76 #include "llvm/MC/MCRegisterInfo.h" 77 #include "llvm/Pass.h" 78 #include "llvm/Support/BranchProbability.h" 79 #include "llvm/Support/Casting.h" 80 #include "llvm/Support/CodeGen.h" 81 #include "llvm/Support/CommandLine.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/Debug.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/KnownBits.h" 86 #include "llvm/Support/MachineValueType.h" 87 #include "llvm/Support/Timer.h" 88 #include "llvm/Support/raw_ostream.h" 89 #include "llvm/Target/TargetIntrinsicInfo.h" 90 #include "llvm/Target/TargetMachine.h" 91 #include "llvm/Target/TargetOptions.h" 92 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 93 #include <algorithm> 94 #include <cassert> 95 #include <cstdint> 96 #include <iterator> 97 #include <limits> 98 #include <memory> 99 #include <string> 100 #include <utility> 101 #include <vector> 102 103 using namespace llvm; 104 105 #define DEBUG_TYPE "isel" 106 107 STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on"); 108 STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected"); 109 STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel"); 110 STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG"); 111 STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path"); 112 STATISTIC(NumEntryBlocks, "Number of entry blocks encountered"); 113 STATISTIC(NumFastIselFailLowerArguments, 114 "Number of entry blocks where fast isel failed to lower arguments"); 115 116 static cl::opt<int> EnableFastISelAbort( 117 "fast-isel-abort", cl::Hidden, 118 cl::desc("Enable abort calls when \"fast\" instruction selection " 119 "fails to lower an instruction: 0 disable the abort, 1 will " 120 "abort but for args, calls and terminators, 2 will also " 121 "abort for argument lowering, and 3 will never fallback " 122 "to SelectionDAG.")); 123 124 static cl::opt<bool> EnableFastISelFallbackReport( 125 "fast-isel-report-on-fallback", cl::Hidden, 126 cl::desc("Emit a diagnostic when \"fast\" instruction selection " 127 "falls back to SelectionDAG.")); 128 129 static cl::opt<bool> 130 UseMBPI("use-mbpi", 131 cl::desc("use Machine Branch Probability Info"), 132 cl::init(true), cl::Hidden); 133 134 #ifndef NDEBUG 135 static cl::opt<std::string> 136 FilterDAGBasicBlockName("filter-view-dags", cl::Hidden, 137 cl::desc("Only display the basic block whose name " 138 "matches this for all view-*-dags options")); 139 static cl::opt<bool> 140 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden, 141 cl::desc("Pop up a window to show dags before the first " 142 "dag combine pass")); 143 static cl::opt<bool> 144 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden, 145 cl::desc("Pop up a window to show dags before legalize types")); 146 static cl::opt<bool> 147 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden, 148 cl::desc("Pop up a window to show dags before legalize")); 149 static cl::opt<bool> 150 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden, 151 cl::desc("Pop up a window to show dags before the second " 152 "dag combine pass")); 153 static cl::opt<bool> 154 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden, 155 cl::desc("Pop up a window to show dags before the post legalize types" 156 " dag combine pass")); 157 static cl::opt<bool> 158 ViewISelDAGs("view-isel-dags", cl::Hidden, 159 cl::desc("Pop up a window to show isel dags as they are selected")); 160 static cl::opt<bool> 161 ViewSchedDAGs("view-sched-dags", cl::Hidden, 162 cl::desc("Pop up a window to show sched dags as they are processed")); 163 static cl::opt<bool> 164 ViewSUnitDAGs("view-sunit-dags", cl::Hidden, 165 cl::desc("Pop up a window to show SUnit dags after they are processed")); 166 #else 167 static const bool ViewDAGCombine1 = false, 168 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false, 169 ViewDAGCombine2 = false, 170 ViewDAGCombineLT = false, 171 ViewISelDAGs = false, ViewSchedDAGs = false, 172 ViewSUnitDAGs = false; 173 #endif 174 175 //===---------------------------------------------------------------------===// 176 /// 177 /// RegisterScheduler class - Track the registration of instruction schedulers. 178 /// 179 //===---------------------------------------------------------------------===// 180 MachinePassRegistry RegisterScheduler::Registry; 181 182 //===---------------------------------------------------------------------===// 183 /// 184 /// ISHeuristic command line option for instruction schedulers. 185 /// 186 //===---------------------------------------------------------------------===// 187 static cl::opt<RegisterScheduler::FunctionPassCtor, false, 188 RegisterPassParser<RegisterScheduler>> 189 ISHeuristic("pre-RA-sched", 190 cl::init(&createDefaultScheduler), cl::Hidden, 191 cl::desc("Instruction schedulers available (before register" 192 " allocation):")); 193 194 static RegisterScheduler 195 defaultListDAGScheduler("default", "Best scheduler for the target", 196 createDefaultScheduler); 197 198 namespace llvm { 199 200 //===--------------------------------------------------------------------===// 201 /// This class is used by SelectionDAGISel to temporarily override 202 /// the optimization level on a per-function basis. 203 class OptLevelChanger { 204 SelectionDAGISel &IS; 205 CodeGenOpt::Level SavedOptLevel; 206 bool SavedFastISel; 207 208 public: 209 OptLevelChanger(SelectionDAGISel &ISel, 210 CodeGenOpt::Level NewOptLevel) : IS(ISel) { 211 SavedOptLevel = IS.OptLevel; 212 if (NewOptLevel == SavedOptLevel) 213 return; 214 IS.OptLevel = NewOptLevel; 215 IS.TM.setOptLevel(NewOptLevel); 216 LLVM_DEBUG(dbgs() << "\nChanging optimization level for Function " 217 << IS.MF->getFunction().getName() << "\n"); 218 LLVM_DEBUG(dbgs() << "\tBefore: -O" << SavedOptLevel << " ; After: -O" 219 << NewOptLevel << "\n"); 220 SavedFastISel = IS.TM.Options.EnableFastISel; 221 if (NewOptLevel == CodeGenOpt::None) { 222 IS.TM.setFastISel(IS.TM.getO0WantsFastISel()); 223 LLVM_DEBUG( 224 dbgs() << "\tFastISel is " 225 << (IS.TM.Options.EnableFastISel ? "enabled" : "disabled") 226 << "\n"); 227 } 228 } 229 230 ~OptLevelChanger() { 231 if (IS.OptLevel == SavedOptLevel) 232 return; 233 LLVM_DEBUG(dbgs() << "\nRestoring optimization level for Function " 234 << IS.MF->getFunction().getName() << "\n"); 235 LLVM_DEBUG(dbgs() << "\tBefore: -O" << IS.OptLevel << " ; After: -O" 236 << SavedOptLevel << "\n"); 237 IS.OptLevel = SavedOptLevel; 238 IS.TM.setOptLevel(SavedOptLevel); 239 IS.TM.setFastISel(SavedFastISel); 240 } 241 }; 242 243 //===--------------------------------------------------------------------===// 244 /// createDefaultScheduler - This creates an instruction scheduler appropriate 245 /// for the target. 246 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS, 247 CodeGenOpt::Level OptLevel) { 248 const TargetLowering *TLI = IS->TLI; 249 const TargetSubtargetInfo &ST = IS->MF->getSubtarget(); 250 251 // Try first to see if the Target has its own way of selecting a scheduler 252 if (auto *SchedulerCtor = ST.getDAGScheduler(OptLevel)) { 253 return SchedulerCtor(IS, OptLevel); 254 } 255 256 if (OptLevel == CodeGenOpt::None || 257 (ST.enableMachineScheduler() && ST.enableMachineSchedDefaultSched()) || 258 TLI->getSchedulingPreference() == Sched::Source) 259 return createSourceListDAGScheduler(IS, OptLevel); 260 if (TLI->getSchedulingPreference() == Sched::RegPressure) 261 return createBURRListDAGScheduler(IS, OptLevel); 262 if (TLI->getSchedulingPreference() == Sched::Hybrid) 263 return createHybridListDAGScheduler(IS, OptLevel); 264 if (TLI->getSchedulingPreference() == Sched::VLIW) 265 return createVLIWDAGScheduler(IS, OptLevel); 266 assert(TLI->getSchedulingPreference() == Sched::ILP && 267 "Unknown sched type!"); 268 return createILPListDAGScheduler(IS, OptLevel); 269 } 270 271 } // end namespace llvm 272 273 // EmitInstrWithCustomInserter - This method should be implemented by targets 274 // that mark instructions with the 'usesCustomInserter' flag. These 275 // instructions are special in various ways, which require special support to 276 // insert. The specified MachineInstr is created but not inserted into any 277 // basic blocks, and this method is called to expand it into a sequence of 278 // instructions, potentially also creating new basic blocks and control flow. 279 // When new basic blocks are inserted and the edges from MBB to its successors 280 // are modified, the method should insert pairs of <OldSucc, NewSucc> into the 281 // DenseMap. 282 MachineBasicBlock * 283 TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI, 284 MachineBasicBlock *MBB) const { 285 #ifndef NDEBUG 286 dbgs() << "If a target marks an instruction with " 287 "'usesCustomInserter', it must implement " 288 "TargetLowering::EmitInstrWithCustomInserter!"; 289 #endif 290 llvm_unreachable(nullptr); 291 } 292 293 void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI, 294 SDNode *Node) const { 295 assert(!MI.hasPostISelHook() && 296 "If a target marks an instruction with 'hasPostISelHook', " 297 "it must implement TargetLowering::AdjustInstrPostInstrSelection!"); 298 } 299 300 //===----------------------------------------------------------------------===// 301 // SelectionDAGISel code 302 //===----------------------------------------------------------------------===// 303 304 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, 305 CodeGenOpt::Level OL) : 306 MachineFunctionPass(ID), TM(tm), 307 FuncInfo(new FunctionLoweringInfo()), 308 CurDAG(new SelectionDAG(tm, OL)), 309 SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)), 310 AA(), GFI(), 311 OptLevel(OL), 312 DAGSize(0) { 313 initializeGCModuleInfoPass(*PassRegistry::getPassRegistry()); 314 initializeBranchProbabilityInfoWrapperPassPass( 315 *PassRegistry::getPassRegistry()); 316 initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry()); 317 initializeTargetLibraryInfoWrapperPassPass( 318 *PassRegistry::getPassRegistry()); 319 } 320 321 SelectionDAGISel::~SelectionDAGISel() { 322 delete SDB; 323 delete CurDAG; 324 delete FuncInfo; 325 } 326 327 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const { 328 if (OptLevel != CodeGenOpt::None) 329 AU.addRequired<AAResultsWrapperPass>(); 330 AU.addRequired<GCModuleInfo>(); 331 AU.addRequired<StackProtector>(); 332 AU.addPreserved<GCModuleInfo>(); 333 AU.addRequired<TargetLibraryInfoWrapperPass>(); 334 AU.addRequired<TargetTransformInfoWrapperPass>(); 335 if (UseMBPI && OptLevel != CodeGenOpt::None) 336 AU.addRequired<BranchProbabilityInfoWrapperPass>(); 337 MachineFunctionPass::getAnalysisUsage(AU); 338 } 339 340 /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that 341 /// may trap on it. In this case we have to split the edge so that the path 342 /// through the predecessor block that doesn't go to the phi block doesn't 343 /// execute the possibly trapping instruction. If available, we pass domtree 344 /// and loop info to be updated when we split critical edges. This is because 345 /// SelectionDAGISel preserves these analyses. 346 /// This is required for correctness, so it must be done at -O0. 347 /// 348 static void SplitCriticalSideEffectEdges(Function &Fn, DominatorTree *DT, 349 LoopInfo *LI) { 350 // Loop for blocks with phi nodes. 351 for (BasicBlock &BB : Fn) { 352 PHINode *PN = dyn_cast<PHINode>(BB.begin()); 353 if (!PN) continue; 354 355 ReprocessBlock: 356 // For each block with a PHI node, check to see if any of the input values 357 // are potentially trapping constant expressions. Constant expressions are 358 // the only potentially trapping value that can occur as the argument to a 359 // PHI. 360 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I)); ++I) 361 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 362 ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i)); 363 if (!CE || !CE->canTrap()) continue; 364 365 // The only case we have to worry about is when the edge is critical. 366 // Since this block has a PHI Node, we assume it has multiple input 367 // edges: check to see if the pred has multiple successors. 368 BasicBlock *Pred = PN->getIncomingBlock(i); 369 if (Pred->getTerminator()->getNumSuccessors() == 1) 370 continue; 371 372 // Okay, we have to split this edge. 373 SplitCriticalEdge( 374 Pred->getTerminator(), GetSuccessorNumber(Pred, &BB), 375 CriticalEdgeSplittingOptions(DT, LI).setMergeIdenticalEdges()); 376 goto ReprocessBlock; 377 } 378 } 379 } 380 381 bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) { 382 // If we already selected that function, we do not need to run SDISel. 383 if (mf.getProperties().hasProperty( 384 MachineFunctionProperties::Property::Selected)) 385 return false; 386 // Do some sanity-checking on the command-line options. 387 assert((!EnableFastISelAbort || TM.Options.EnableFastISel) && 388 "-fast-isel-abort > 0 requires -fast-isel"); 389 390 const Function &Fn = mf.getFunction(); 391 MF = &mf; 392 393 // Reset the target options before resetting the optimization 394 // level below. 395 // FIXME: This is a horrible hack and should be processed via 396 // codegen looking at the optimization level explicitly when 397 // it wants to look at it. 398 TM.resetTargetOptions(Fn); 399 // Reset OptLevel to None for optnone functions. 400 CodeGenOpt::Level NewOptLevel = OptLevel; 401 if (OptLevel != CodeGenOpt::None && skipFunction(Fn)) 402 NewOptLevel = CodeGenOpt::None; 403 OptLevelChanger OLC(*this, NewOptLevel); 404 405 TII = MF->getSubtarget().getInstrInfo(); 406 TLI = MF->getSubtarget().getTargetLowering(); 407 RegInfo = &MF->getRegInfo(); 408 LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 409 GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : nullptr; 410 ORE = make_unique<OptimizationRemarkEmitter>(&Fn); 411 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 412 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr; 413 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>(); 414 LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr; 415 416 LLVM_DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n"); 417 418 SplitCriticalSideEffectEdges(const_cast<Function &>(Fn), DT, LI); 419 420 CurDAG->init(*MF, *ORE, this, LibInfo, 421 getAnalysisIfAvailable<LegacyDivergenceAnalysis>()); 422 FuncInfo->set(Fn, *MF, CurDAG); 423 424 // Now get the optional analyzes if we want to. 425 // This is based on the possibly changed OptLevel (after optnone is taken 426 // into account). That's unfortunate but OK because it just means we won't 427 // ask for passes that have been required anyway. 428 429 if (UseMBPI && OptLevel != CodeGenOpt::None) 430 FuncInfo->BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI(); 431 else 432 FuncInfo->BPI = nullptr; 433 434 if (OptLevel != CodeGenOpt::None) 435 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 436 else 437 AA = nullptr; 438 439 SDB->init(GFI, AA, LibInfo); 440 441 MF->setHasInlineAsm(false); 442 443 FuncInfo->SplitCSR = false; 444 445 // We split CSR if the target supports it for the given function 446 // and the function has only return exits. 447 if (OptLevel != CodeGenOpt::None && TLI->supportSplitCSR(MF)) { 448 FuncInfo->SplitCSR = true; 449 450 // Collect all the return blocks. 451 for (const BasicBlock &BB : Fn) { 452 if (!succ_empty(&BB)) 453 continue; 454 455 const Instruction *Term = BB.getTerminator(); 456 if (isa<UnreachableInst>(Term) || isa<ReturnInst>(Term)) 457 continue; 458 459 // Bail out if the exit block is not Return nor Unreachable. 460 FuncInfo->SplitCSR = false; 461 break; 462 } 463 } 464 465 MachineBasicBlock *EntryMBB = &MF->front(); 466 if (FuncInfo->SplitCSR) 467 // This performs initialization so lowering for SplitCSR will be correct. 468 TLI->initializeSplitCSR(EntryMBB); 469 470 SelectAllBasicBlocks(Fn); 471 if (FastISelFailed && EnableFastISelFallbackReport) { 472 DiagnosticInfoISelFallback DiagFallback(Fn); 473 Fn.getContext().diagnose(DiagFallback); 474 } 475 476 // If the first basic block in the function has live ins that need to be 477 // copied into vregs, emit the copies into the top of the block before 478 // emitting the code for the block. 479 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo(); 480 RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII); 481 482 // Insert copies in the entry block and the return blocks. 483 if (FuncInfo->SplitCSR) { 484 SmallVector<MachineBasicBlock*, 4> Returns; 485 // Collect all the return blocks. 486 for (MachineBasicBlock &MBB : mf) { 487 if (!MBB.succ_empty()) 488 continue; 489 490 MachineBasicBlock::iterator Term = MBB.getFirstTerminator(); 491 if (Term != MBB.end() && Term->isReturn()) { 492 Returns.push_back(&MBB); 493 continue; 494 } 495 } 496 TLI->insertCopiesSplitCSR(EntryMBB, Returns); 497 } 498 499 DenseMap<unsigned, unsigned> LiveInMap; 500 if (!FuncInfo->ArgDbgValues.empty()) 501 for (std::pair<unsigned, unsigned> LI : RegInfo->liveins()) 502 if (LI.second) 503 LiveInMap.insert(LI); 504 505 // Insert DBG_VALUE instructions for function arguments to the entry block. 506 for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) { 507 MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1]; 508 bool hasFI = MI->getOperand(0).isFI(); 509 unsigned Reg = 510 hasFI ? TRI.getFrameRegister(*MF) : MI->getOperand(0).getReg(); 511 if (TargetRegisterInfo::isPhysicalRegister(Reg)) 512 EntryMBB->insert(EntryMBB->begin(), MI); 513 else { 514 MachineInstr *Def = RegInfo->getVRegDef(Reg); 515 if (Def) { 516 MachineBasicBlock::iterator InsertPos = Def; 517 // FIXME: VR def may not be in entry block. 518 Def->getParent()->insert(std::next(InsertPos), MI); 519 } else 520 LLVM_DEBUG(dbgs() << "Dropping debug info for dead vreg" 521 << TargetRegisterInfo::virtReg2Index(Reg) << "\n"); 522 } 523 524 // If Reg is live-in then update debug info to track its copy in a vreg. 525 DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg); 526 if (LDI != LiveInMap.end()) { 527 assert(!hasFI && "There's no handling of frame pointer updating here yet " 528 "- add if needed"); 529 MachineInstr *Def = RegInfo->getVRegDef(LDI->second); 530 MachineBasicBlock::iterator InsertPos = Def; 531 const MDNode *Variable = MI->getDebugVariable(); 532 const MDNode *Expr = MI->getDebugExpression(); 533 DebugLoc DL = MI->getDebugLoc(); 534 bool IsIndirect = MI->isIndirectDebugValue(); 535 if (IsIndirect) 536 assert(MI->getOperand(1).getImm() == 0 && 537 "DBG_VALUE with nonzero offset"); 538 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) && 539 "Expected inlined-at fields to agree"); 540 // Def is never a terminator here, so it is ok to increment InsertPos. 541 BuildMI(*EntryMBB, ++InsertPos, DL, TII->get(TargetOpcode::DBG_VALUE), 542 IsIndirect, LDI->second, Variable, Expr); 543 544 // If this vreg is directly copied into an exported register then 545 // that COPY instructions also need DBG_VALUE, if it is the only 546 // user of LDI->second. 547 MachineInstr *CopyUseMI = nullptr; 548 for (MachineRegisterInfo::use_instr_iterator 549 UI = RegInfo->use_instr_begin(LDI->second), 550 E = RegInfo->use_instr_end(); UI != E; ) { 551 MachineInstr *UseMI = &*(UI++); 552 if (UseMI->isDebugValue()) continue; 553 if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) { 554 CopyUseMI = UseMI; continue; 555 } 556 // Otherwise this is another use or second copy use. 557 CopyUseMI = nullptr; break; 558 } 559 if (CopyUseMI) { 560 // Use MI's debug location, which describes where Variable was 561 // declared, rather than whatever is attached to CopyUseMI. 562 MachineInstr *NewMI = 563 BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect, 564 CopyUseMI->getOperand(0).getReg(), Variable, Expr); 565 MachineBasicBlock::iterator Pos = CopyUseMI; 566 EntryMBB->insertAfter(Pos, NewMI); 567 } 568 } 569 } 570 571 // Determine if there are any calls in this machine function. 572 MachineFrameInfo &MFI = MF->getFrameInfo(); 573 for (const auto &MBB : *MF) { 574 if (MFI.hasCalls() && MF->hasInlineAsm()) 575 break; 576 577 for (const auto &MI : MBB) { 578 const MCInstrDesc &MCID = TII->get(MI.getOpcode()); 579 if ((MCID.isCall() && !MCID.isReturn()) || 580 MI.isStackAligningInlineAsm()) { 581 MFI.setHasCalls(true); 582 } 583 if (MI.isInlineAsm()) { 584 MF->setHasInlineAsm(true); 585 } 586 } 587 } 588 589 // Determine if there is a call to setjmp in the machine function. 590 MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice()); 591 592 // Replace forward-declared registers with the registers containing 593 // the desired value. 594 MachineRegisterInfo &MRI = MF->getRegInfo(); 595 for (DenseMap<unsigned, unsigned>::iterator 596 I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end(); 597 I != E; ++I) { 598 unsigned From = I->first; 599 unsigned To = I->second; 600 // If To is also scheduled to be replaced, find what its ultimate 601 // replacement is. 602 while (true) { 603 DenseMap<unsigned, unsigned>::iterator J = FuncInfo->RegFixups.find(To); 604 if (J == E) break; 605 To = J->second; 606 } 607 // Make sure the new register has a sufficiently constrained register class. 608 if (TargetRegisterInfo::isVirtualRegister(From) && 609 TargetRegisterInfo::isVirtualRegister(To)) 610 MRI.constrainRegClass(To, MRI.getRegClass(From)); 611 // Replace it. 612 613 614 // Replacing one register with another won't touch the kill flags. 615 // We need to conservatively clear the kill flags as a kill on the old 616 // register might dominate existing uses of the new register. 617 if (!MRI.use_empty(To)) 618 MRI.clearKillFlags(From); 619 MRI.replaceRegWith(From, To); 620 } 621 622 TLI->finalizeLowering(*MF); 623 624 // Release function-specific state. SDB and CurDAG are already cleared 625 // at this point. 626 FuncInfo->clear(); 627 628 LLVM_DEBUG(dbgs() << "*** MachineFunction at end of ISel ***\n"); 629 LLVM_DEBUG(MF->print(dbgs())); 630 631 return true; 632 } 633 634 static void reportFastISelFailure(MachineFunction &MF, 635 OptimizationRemarkEmitter &ORE, 636 OptimizationRemarkMissed &R, 637 bool ShouldAbort) { 638 // Print the function name explicitly if we don't have a debug location (which 639 // makes the diagnostic less useful) or if we're going to emit a raw error. 640 if (!R.getLocation().isValid() || ShouldAbort) 641 R << (" (in function: " + MF.getName() + ")").str(); 642 643 if (ShouldAbort) 644 report_fatal_error(R.getMsg()); 645 646 ORE.emit(R); 647 } 648 649 void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin, 650 BasicBlock::const_iterator End, 651 bool &HadTailCall) { 652 // Allow creating illegal types during DAG building for the basic block. 653 CurDAG->NewNodesMustHaveLegalTypes = false; 654 655 // Lower the instructions. If a call is emitted as a tail call, cease emitting 656 // nodes for this block. 657 for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I) { 658 if (!ElidedArgCopyInstrs.count(&*I)) 659 SDB->visit(*I); 660 } 661 662 // Make sure the root of the DAG is up-to-date. 663 CurDAG->setRoot(SDB->getControlRoot()); 664 HadTailCall = SDB->HasTailCall; 665 SDB->clear(); 666 667 // Final step, emit the lowered DAG as machine code. 668 CodeGenAndEmitDAG(); 669 } 670 671 void SelectionDAGISel::ComputeLiveOutVRegInfo() { 672 SmallPtrSet<SDNode*, 16> VisitedNodes; 673 SmallVector<SDNode*, 128> Worklist; 674 675 Worklist.push_back(CurDAG->getRoot().getNode()); 676 677 KnownBits Known; 678 679 do { 680 SDNode *N = Worklist.pop_back_val(); 681 682 // If we've already seen this node, ignore it. 683 if (!VisitedNodes.insert(N).second) 684 continue; 685 686 // Otherwise, add all chain operands to the worklist. 687 for (const SDValue &Op : N->op_values()) 688 if (Op.getValueType() == MVT::Other) 689 Worklist.push_back(Op.getNode()); 690 691 // If this is a CopyToReg with a vreg dest, process it. 692 if (N->getOpcode() != ISD::CopyToReg) 693 continue; 694 695 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg(); 696 if (!TargetRegisterInfo::isVirtualRegister(DestReg)) 697 continue; 698 699 // Ignore non-scalar or non-integer values. 700 SDValue Src = N->getOperand(2); 701 EVT SrcVT = Src.getValueType(); 702 if (!SrcVT.isInteger() || SrcVT.isVector()) 703 continue; 704 705 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src); 706 CurDAG->computeKnownBits(Src, Known); 707 FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, Known); 708 } while (!Worklist.empty()); 709 } 710 711 void SelectionDAGISel::CodeGenAndEmitDAG() { 712 StringRef GroupName = "sdag"; 713 StringRef GroupDescription = "Instruction Selection and Scheduling"; 714 std::string BlockName; 715 int BlockNumber = -1; 716 (void)BlockNumber; 717 bool MatchFilterBB = false; (void)MatchFilterBB; 718 #ifndef NDEBUG 719 TargetTransformInfo &TTI = 720 getAnalysis<TargetTransformInfoWrapperPass>().getTTI(*FuncInfo->Fn); 721 #endif 722 723 // Pre-type legalization allow creation of any node types. 724 CurDAG->NewNodesMustHaveLegalTypes = false; 725 726 #ifndef NDEBUG 727 MatchFilterBB = (FilterDAGBasicBlockName.empty() || 728 FilterDAGBasicBlockName == 729 FuncInfo->MBB->getBasicBlock()->getName()); 730 #endif 731 #ifdef NDEBUG 732 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs || 733 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs || 734 ViewSUnitDAGs) 735 #endif 736 { 737 BlockNumber = FuncInfo->MBB->getNumber(); 738 BlockName = 739 (MF->getName() + ":" + FuncInfo->MBB->getBasicBlock()->getName()).str(); 740 } 741 LLVM_DEBUG(dbgs() << "Initial selection DAG: " 742 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName 743 << "'\n"; 744 CurDAG->dump()); 745 746 if (ViewDAGCombine1 && MatchFilterBB) 747 CurDAG->viewGraph("dag-combine1 input for " + BlockName); 748 749 // Run the DAG combiner in pre-legalize mode. 750 { 751 NamedRegionTimer T("combine1", "DAG Combining 1", GroupName, 752 GroupDescription, TimePassesIsEnabled); 753 CurDAG->Combine(BeforeLegalizeTypes, AA, OptLevel); 754 } 755 756 #ifndef NDEBUG 757 if (TTI.hasBranchDivergence()) 758 CurDAG->VerifyDAGDiverence(); 759 #endif 760 761 LLVM_DEBUG(dbgs() << "Optimized lowered selection DAG: " 762 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName 763 << "'\n"; 764 CurDAG->dump()); 765 766 // Second step, hack on the DAG until it only uses operations and types that 767 // the target supports. 768 if (ViewLegalizeTypesDAGs && MatchFilterBB) 769 CurDAG->viewGraph("legalize-types input for " + BlockName); 770 771 bool Changed; 772 { 773 NamedRegionTimer T("legalize_types", "Type Legalization", GroupName, 774 GroupDescription, TimePassesIsEnabled); 775 Changed = CurDAG->LegalizeTypes(); 776 } 777 778 #ifndef NDEBUG 779 if (TTI.hasBranchDivergence()) 780 CurDAG->VerifyDAGDiverence(); 781 #endif 782 783 LLVM_DEBUG(dbgs() << "Type-legalized selection DAG: " 784 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName 785 << "'\n"; 786 CurDAG->dump()); 787 788 // Only allow creation of legal node types. 789 CurDAG->NewNodesMustHaveLegalTypes = true; 790 791 if (Changed) { 792 if (ViewDAGCombineLT && MatchFilterBB) 793 CurDAG->viewGraph("dag-combine-lt input for " + BlockName); 794 795 // Run the DAG combiner in post-type-legalize mode. 796 { 797 NamedRegionTimer T("combine_lt", "DAG Combining after legalize types", 798 GroupName, GroupDescription, TimePassesIsEnabled); 799 CurDAG->Combine(AfterLegalizeTypes, AA, OptLevel); 800 } 801 802 #ifndef NDEBUG 803 if (TTI.hasBranchDivergence()) 804 CurDAG->VerifyDAGDiverence(); 805 #endif 806 807 LLVM_DEBUG(dbgs() << "Optimized type-legalized selection DAG: " 808 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName 809 << "'\n"; 810 CurDAG->dump()); 811 } 812 813 { 814 NamedRegionTimer T("legalize_vec", "Vector Legalization", GroupName, 815 GroupDescription, TimePassesIsEnabled); 816 Changed = CurDAG->LegalizeVectors(); 817 } 818 819 if (Changed) { 820 LLVM_DEBUG(dbgs() << "Vector-legalized selection DAG: " 821 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName 822 << "'\n"; 823 CurDAG->dump()); 824 825 { 826 NamedRegionTimer T("legalize_types2", "Type Legalization 2", GroupName, 827 GroupDescription, TimePassesIsEnabled); 828 CurDAG->LegalizeTypes(); 829 } 830 831 LLVM_DEBUG(dbgs() << "Vector/type-legalized selection DAG: " 832 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName 833 << "'\n"; 834 CurDAG->dump()); 835 836 if (ViewDAGCombineLT && MatchFilterBB) 837 CurDAG->viewGraph("dag-combine-lv input for " + BlockName); 838 839 // Run the DAG combiner in post-type-legalize mode. 840 { 841 NamedRegionTimer T("combine_lv", "DAG Combining after legalize vectors", 842 GroupName, GroupDescription, TimePassesIsEnabled); 843 CurDAG->Combine(AfterLegalizeVectorOps, AA, OptLevel); 844 } 845 846 LLVM_DEBUG(dbgs() << "Optimized vector-legalized selection DAG: " 847 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName 848 << "'\n"; 849 CurDAG->dump()); 850 851 #ifndef NDEBUG 852 if (TTI.hasBranchDivergence()) 853 CurDAG->VerifyDAGDiverence(); 854 #endif 855 } 856 857 if (ViewLegalizeDAGs && MatchFilterBB) 858 CurDAG->viewGraph("legalize input for " + BlockName); 859 860 { 861 NamedRegionTimer T("legalize", "DAG Legalization", GroupName, 862 GroupDescription, TimePassesIsEnabled); 863 CurDAG->Legalize(); 864 } 865 866 #ifndef NDEBUG 867 if (TTI.hasBranchDivergence()) 868 CurDAG->VerifyDAGDiverence(); 869 #endif 870 871 LLVM_DEBUG(dbgs() << "Legalized selection DAG: " 872 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName 873 << "'\n"; 874 CurDAG->dump()); 875 876 if (ViewDAGCombine2 && MatchFilterBB) 877 CurDAG->viewGraph("dag-combine2 input for " + BlockName); 878 879 // Run the DAG combiner in post-legalize mode. 880 { 881 NamedRegionTimer T("combine2", "DAG Combining 2", GroupName, 882 GroupDescription, TimePassesIsEnabled); 883 CurDAG->Combine(AfterLegalizeDAG, AA, OptLevel); 884 } 885 886 #ifndef NDEBUG 887 if (TTI.hasBranchDivergence()) 888 CurDAG->VerifyDAGDiverence(); 889 #endif 890 891 LLVM_DEBUG(dbgs() << "Optimized legalized selection DAG: " 892 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName 893 << "'\n"; 894 CurDAG->dump()); 895 896 if (OptLevel != CodeGenOpt::None) 897 ComputeLiveOutVRegInfo(); 898 899 if (ViewISelDAGs && MatchFilterBB) 900 CurDAG->viewGraph("isel input for " + BlockName); 901 902 // Third, instruction select all of the operations to machine code, adding the 903 // code to the MachineBasicBlock. 904 { 905 NamedRegionTimer T("isel", "Instruction Selection", GroupName, 906 GroupDescription, TimePassesIsEnabled); 907 DoInstructionSelection(); 908 } 909 910 LLVM_DEBUG(dbgs() << "Selected selection DAG: " 911 << printMBBReference(*FuncInfo->MBB) << " '" << BlockName 912 << "'\n"; 913 CurDAG->dump()); 914 915 if (ViewSchedDAGs && MatchFilterBB) 916 CurDAG->viewGraph("scheduler input for " + BlockName); 917 918 // Schedule machine code. 919 ScheduleDAGSDNodes *Scheduler = CreateScheduler(); 920 { 921 NamedRegionTimer T("sched", "Instruction Scheduling", GroupName, 922 GroupDescription, TimePassesIsEnabled); 923 Scheduler->Run(CurDAG, FuncInfo->MBB); 924 } 925 926 if (ViewSUnitDAGs && MatchFilterBB) 927 Scheduler->viewGraph(); 928 929 // Emit machine code to BB. This can change 'BB' to the last block being 930 // inserted into. 931 MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB; 932 { 933 NamedRegionTimer T("emit", "Instruction Creation", GroupName, 934 GroupDescription, TimePassesIsEnabled); 935 936 // FuncInfo->InsertPt is passed by reference and set to the end of the 937 // scheduled instructions. 938 LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt); 939 } 940 941 // If the block was split, make sure we update any references that are used to 942 // update PHI nodes later on. 943 if (FirstMBB != LastMBB) 944 SDB->UpdateSplitBlock(FirstMBB, LastMBB); 945 946 // Free the scheduler state. 947 { 948 NamedRegionTimer T("cleanup", "Instruction Scheduling Cleanup", GroupName, 949 GroupDescription, TimePassesIsEnabled); 950 delete Scheduler; 951 } 952 953 // Free the SelectionDAG state, now that we're finished with it. 954 CurDAG->clear(); 955 } 956 957 namespace { 958 959 /// ISelUpdater - helper class to handle updates of the instruction selection 960 /// graph. 961 class ISelUpdater : public SelectionDAG::DAGUpdateListener { 962 SelectionDAG::allnodes_iterator &ISelPosition; 963 964 public: 965 ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp) 966 : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {} 967 968 /// NodeDeleted - Handle nodes deleted from the graph. If the node being 969 /// deleted is the current ISelPosition node, update ISelPosition. 970 /// 971 void NodeDeleted(SDNode *N, SDNode *E) override { 972 if (ISelPosition == SelectionDAG::allnodes_iterator(N)) 973 ++ISelPosition; 974 } 975 }; 976 977 } // end anonymous namespace 978 979 // This function is used to enforce the topological node id property 980 // property leveraged during Instruction selection. Before selection all 981 // nodes are given a non-negative id such that all nodes have a larger id than 982 // their operands. As this holds transitively we can prune checks that a node N 983 // is a predecessor of M another by not recursively checking through M's 984 // operands if N's ID is larger than M's ID. This is significantly improves 985 // performance of for various legality checks (e.g. IsLegalToFold / 986 // UpdateChains). 987 988 // However, when we fuse multiple nodes into a single node 989 // during selection we may induce a predecessor relationship between inputs and 990 // outputs of distinct nodes being merged violating the topological property. 991 // Should a fused node have a successor which has yet to be selected, our 992 // legality checks would be incorrect. To avoid this we mark all unselected 993 // sucessor nodes, i.e. id != -1 as invalid for pruning by bit-negating (x => 994 // (-(x+1))) the ids and modify our pruning check to ignore negative Ids of M. 995 // We use bit-negation to more clearly enforce that node id -1 can only be 996 // achieved by selected nodes). As the conversion is reversable the original Id, 997 // topological pruning can still be leveraged when looking for unselected nodes. 998 // This method is call internally in all ISel replacement calls. 999 void SelectionDAGISel::EnforceNodeIdInvariant(SDNode *Node) { 1000 SmallVector<SDNode *, 4> Nodes; 1001 Nodes.push_back(Node); 1002 1003 while (!Nodes.empty()) { 1004 SDNode *N = Nodes.pop_back_val(); 1005 for (auto *U : N->uses()) { 1006 auto UId = U->getNodeId(); 1007 if (UId > 0) { 1008 InvalidateNodeId(U); 1009 Nodes.push_back(U); 1010 } 1011 } 1012 } 1013 } 1014 1015 // InvalidateNodeId - As discusses in EnforceNodeIdInvariant, mark a 1016 // NodeId with the equivalent node id which is invalid for topological 1017 // pruning. 1018 void SelectionDAGISel::InvalidateNodeId(SDNode *N) { 1019 int InvalidId = -(N->getNodeId() + 1); 1020 N->setNodeId(InvalidId); 1021 } 1022 1023 // getUninvalidatedNodeId - get original uninvalidated node id. 1024 int SelectionDAGISel::getUninvalidatedNodeId(SDNode *N) { 1025 int Id = N->getNodeId(); 1026 if (Id < -1) 1027 return -(Id + 1); 1028 return Id; 1029 } 1030 1031 void SelectionDAGISel::DoInstructionSelection() { 1032 LLVM_DEBUG(dbgs() << "===== Instruction selection begins: " 1033 << printMBBReference(*FuncInfo->MBB) << " '" 1034 << FuncInfo->MBB->getName() << "'\n"); 1035 1036 PreprocessISelDAG(); 1037 1038 // Select target instructions for the DAG. 1039 { 1040 // Number all nodes with a topological order and set DAGSize. 1041 DAGSize = CurDAG->AssignTopologicalOrder(); 1042 1043 // Create a dummy node (which is not added to allnodes), that adds 1044 // a reference to the root node, preventing it from being deleted, 1045 // and tracking any changes of the root. 1046 HandleSDNode Dummy(CurDAG->getRoot()); 1047 SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode()); 1048 ++ISelPosition; 1049 1050 // Make sure that ISelPosition gets properly updated when nodes are deleted 1051 // in calls made from this function. 1052 ISelUpdater ISU(*CurDAG, ISelPosition); 1053 1054 // The AllNodes list is now topological-sorted. Visit the 1055 // nodes by starting at the end of the list (the root of the 1056 // graph) and preceding back toward the beginning (the entry 1057 // node). 1058 while (ISelPosition != CurDAG->allnodes_begin()) { 1059 SDNode *Node = &*--ISelPosition; 1060 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes, 1061 // but there are currently some corner cases that it misses. Also, this 1062 // makes it theoretically possible to disable the DAGCombiner. 1063 if (Node->use_empty()) 1064 continue; 1065 1066 #ifndef NDEBUG 1067 SmallVector<SDNode *, 4> Nodes; 1068 Nodes.push_back(Node); 1069 1070 while (!Nodes.empty()) { 1071 auto N = Nodes.pop_back_val(); 1072 if (N->getOpcode() == ISD::TokenFactor || N->getNodeId() < 0) 1073 continue; 1074 for (const SDValue &Op : N->op_values()) { 1075 if (Op->getOpcode() == ISD::TokenFactor) 1076 Nodes.push_back(Op.getNode()); 1077 else { 1078 // We rely on topological ordering of node ids for checking for 1079 // cycles when fusing nodes during selection. All unselected nodes 1080 // successors of an already selected node should have a negative id. 1081 // This assertion will catch such cases. If this assertion triggers 1082 // it is likely you using DAG-level Value/Node replacement functions 1083 // (versus equivalent ISEL replacement) in backend-specific 1084 // selections. See comment in EnforceNodeIdInvariant for more 1085 // details. 1086 assert(Op->getNodeId() != -1 && 1087 "Node has already selected predecessor node"); 1088 } 1089 } 1090 } 1091 #endif 1092 1093 // When we are using non-default rounding modes or FP exception behavior 1094 // FP operations are represented by StrictFP pseudo-operations. They 1095 // need to be simplified here so that the target-specific instruction 1096 // selectors know how to handle them. 1097 // 1098 // If the current node is a strict FP pseudo-op, the isStrictFPOp() 1099 // function will provide the corresponding normal FP opcode to which the 1100 // node should be mutated. 1101 // 1102 // FIXME: The backends need a way to handle FP constraints. 1103 if (Node->isStrictFPOpcode()) 1104 Node = CurDAG->mutateStrictFPToFP(Node); 1105 1106 LLVM_DEBUG(dbgs() << "\nISEL: Starting selection on root node: "; 1107 Node->dump(CurDAG)); 1108 1109 Select(Node); 1110 } 1111 1112 CurDAG->setRoot(Dummy.getValue()); 1113 } 1114 1115 LLVM_DEBUG(dbgs() << "\n===== Instruction selection ends:\n"); 1116 1117 PostprocessISelDAG(); 1118 } 1119 1120 static bool hasExceptionPointerOrCodeUser(const CatchPadInst *CPI) { 1121 for (const User *U : CPI->users()) { 1122 if (const IntrinsicInst *EHPtrCall = dyn_cast<IntrinsicInst>(U)) { 1123 Intrinsic::ID IID = EHPtrCall->getIntrinsicID(); 1124 if (IID == Intrinsic::eh_exceptionpointer || 1125 IID == Intrinsic::eh_exceptioncode) 1126 return true; 1127 } 1128 } 1129 return false; 1130 } 1131 1132 // wasm.landingpad.index intrinsic is for associating a landing pad index number 1133 // with a catchpad instruction. Retrieve the landing pad index in the intrinsic 1134 // and store the mapping in the function. 1135 static void mapWasmLandingPadIndex(MachineBasicBlock *MBB, 1136 const CatchPadInst *CPI) { 1137 MachineFunction *MF = MBB->getParent(); 1138 // In case of single catch (...), we don't emit LSDA, so we don't need 1139 // this information. 1140 bool IsSingleCatchAllClause = 1141 CPI->getNumArgOperands() == 1 && 1142 cast<Constant>(CPI->getArgOperand(0))->isNullValue(); 1143 if (!IsSingleCatchAllClause) { 1144 // Create a mapping from landing pad label to landing pad index. 1145 bool IntrFound = false; 1146 for (const User *U : CPI->users()) { 1147 if (const auto *Call = dyn_cast<IntrinsicInst>(U)) { 1148 Intrinsic::ID IID = Call->getIntrinsicID(); 1149 if (IID == Intrinsic::wasm_landingpad_index) { 1150 Value *IndexArg = Call->getArgOperand(1); 1151 int Index = cast<ConstantInt>(IndexArg)->getZExtValue(); 1152 MF->setWasmLandingPadIndex(MBB, Index); 1153 IntrFound = true; 1154 break; 1155 } 1156 } 1157 } 1158 assert(IntrFound && "wasm.landingpad.index intrinsic not found!"); 1159 (void)IntrFound; 1160 } 1161 } 1162 1163 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and 1164 /// do other setup for EH landing-pad blocks. 1165 bool SelectionDAGISel::PrepareEHLandingPad() { 1166 MachineBasicBlock *MBB = FuncInfo->MBB; 1167 const Constant *PersonalityFn = FuncInfo->Fn->getPersonalityFn(); 1168 const BasicBlock *LLVMBB = MBB->getBasicBlock(); 1169 const TargetRegisterClass *PtrRC = 1170 TLI->getRegClassFor(TLI->getPointerTy(CurDAG->getDataLayout())); 1171 1172 auto Pers = classifyEHPersonality(PersonalityFn); 1173 1174 // Catchpads have one live-in register, which typically holds the exception 1175 // pointer or code. 1176 if (isFuncletEHPersonality(Pers)) { 1177 if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) { 1178 if (hasExceptionPointerOrCodeUser(CPI)) { 1179 // Get or create the virtual register to hold the pointer or code. Mark 1180 // the live in physreg and copy into the vreg. 1181 MCPhysReg EHPhysReg = TLI->getExceptionPointerRegister(PersonalityFn); 1182 assert(EHPhysReg && "target lacks exception pointer register"); 1183 MBB->addLiveIn(EHPhysReg); 1184 unsigned VReg = FuncInfo->getCatchPadExceptionPointerVReg(CPI, PtrRC); 1185 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), 1186 TII->get(TargetOpcode::COPY), VReg) 1187 .addReg(EHPhysReg, RegState::Kill); 1188 } 1189 } 1190 return true; 1191 } 1192 1193 // Add a label to mark the beginning of the landing pad. Deletion of the 1194 // landing pad can thus be detected via the MachineModuleInfo. 1195 MCSymbol *Label = MF->addLandingPad(MBB); 1196 1197 const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL); 1198 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II) 1199 .addSym(Label); 1200 1201 if (Pers == EHPersonality::Wasm_CXX) { 1202 if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) 1203 mapWasmLandingPadIndex(MBB, CPI); 1204 } else { 1205 // Assign the call site to the landing pad's begin label. 1206 MF->setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]); 1207 // Mark exception register as live in. 1208 if (unsigned Reg = TLI->getExceptionPointerRegister(PersonalityFn)) 1209 FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC); 1210 // Mark exception selector register as live in. 1211 if (unsigned Reg = TLI->getExceptionSelectorRegister(PersonalityFn)) 1212 FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC); 1213 } 1214 1215 return true; 1216 } 1217 1218 /// isFoldedOrDeadInstruction - Return true if the specified instruction is 1219 /// side-effect free and is either dead or folded into a generated instruction. 1220 /// Return false if it needs to be emitted. 1221 static bool isFoldedOrDeadInstruction(const Instruction *I, 1222 FunctionLoweringInfo *FuncInfo) { 1223 return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded. 1224 !I->isTerminator() && // Terminators aren't folded. 1225 !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded. 1226 !I->isEHPad() && // EH pad instructions aren't folded. 1227 !FuncInfo->isExportedInst(I); // Exported instrs must be computed. 1228 } 1229 1230 /// Set up SwiftErrorVals by going through the function. If the function has 1231 /// swifterror argument, it will be the first entry. 1232 static void setupSwiftErrorVals(const Function &Fn, const TargetLowering *TLI, 1233 FunctionLoweringInfo *FuncInfo) { 1234 if (!TLI->supportSwiftError()) 1235 return; 1236 1237 FuncInfo->SwiftErrorVals.clear(); 1238 FuncInfo->SwiftErrorVRegDefMap.clear(); 1239 FuncInfo->SwiftErrorVRegUpwardsUse.clear(); 1240 FuncInfo->SwiftErrorVRegDefUses.clear(); 1241 FuncInfo->SwiftErrorArg = nullptr; 1242 1243 // Check if function has a swifterror argument. 1244 bool HaveSeenSwiftErrorArg = false; 1245 for (Function::const_arg_iterator AI = Fn.arg_begin(), AE = Fn.arg_end(); 1246 AI != AE; ++AI) 1247 if (AI->hasSwiftErrorAttr()) { 1248 assert(!HaveSeenSwiftErrorArg && 1249 "Must have only one swifterror parameter"); 1250 (void)HaveSeenSwiftErrorArg; // silence warning. 1251 HaveSeenSwiftErrorArg = true; 1252 FuncInfo->SwiftErrorArg = &*AI; 1253 FuncInfo->SwiftErrorVals.push_back(&*AI); 1254 } 1255 1256 for (const auto &LLVMBB : Fn) 1257 for (const auto &Inst : LLVMBB) { 1258 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(&Inst)) 1259 if (Alloca->isSwiftError()) 1260 FuncInfo->SwiftErrorVals.push_back(Alloca); 1261 } 1262 } 1263 1264 static void createSwiftErrorEntriesInEntryBlock(FunctionLoweringInfo *FuncInfo, 1265 FastISel *FastIS, 1266 const TargetLowering *TLI, 1267 const TargetInstrInfo *TII, 1268 SelectionDAGBuilder *SDB) { 1269 if (!TLI->supportSwiftError()) 1270 return; 1271 1272 // We only need to do this when we have swifterror parameter or swifterror 1273 // alloc. 1274 if (FuncInfo->SwiftErrorVals.empty()) 1275 return; 1276 1277 assert(FuncInfo->MBB == &*FuncInfo->MF->begin() && 1278 "expected to insert into entry block"); 1279 auto &DL = FuncInfo->MF->getDataLayout(); 1280 auto const *RC = TLI->getRegClassFor(TLI->getPointerTy(DL)); 1281 for (const auto *SwiftErrorVal : FuncInfo->SwiftErrorVals) { 1282 // We will always generate a copy from the argument. It is always used at 1283 // least by the 'return' of the swifterror. 1284 if (FuncInfo->SwiftErrorArg && FuncInfo->SwiftErrorArg == SwiftErrorVal) 1285 continue; 1286 unsigned VReg = FuncInfo->MF->getRegInfo().createVirtualRegister(RC); 1287 // Assign Undef to Vreg. We construct MI directly to make sure it works 1288 // with FastISel. 1289 BuildMI(*FuncInfo->MBB, FuncInfo->MBB->getFirstNonPHI(), 1290 SDB->getCurDebugLoc(), TII->get(TargetOpcode::IMPLICIT_DEF), 1291 VReg); 1292 1293 // Keep FastIS informed about the value we just inserted. 1294 if (FastIS) 1295 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt)); 1296 1297 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, SwiftErrorVal, VReg); 1298 } 1299 } 1300 1301 /// Collect llvm.dbg.declare information. This is done after argument lowering 1302 /// in case the declarations refer to arguments. 1303 static void processDbgDeclares(FunctionLoweringInfo *FuncInfo) { 1304 MachineFunction *MF = FuncInfo->MF; 1305 const DataLayout &DL = MF->getDataLayout(); 1306 for (const BasicBlock &BB : *FuncInfo->Fn) { 1307 for (const Instruction &I : BB) { 1308 const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(&I); 1309 if (!DI) 1310 continue; 1311 1312 assert(DI->getVariable() && "Missing variable"); 1313 assert(DI->getDebugLoc() && "Missing location"); 1314 const Value *Address = DI->getAddress(); 1315 if (!Address) 1316 continue; 1317 1318 // Look through casts and constant offset GEPs. These mostly come from 1319 // inalloca. 1320 APInt Offset(DL.getTypeSizeInBits(Address->getType()), 0); 1321 Address = Address->stripAndAccumulateInBoundsConstantOffsets(DL, Offset); 1322 1323 // Check if the variable is a static alloca or a byval or inalloca 1324 // argument passed in memory. If it is not, then we will ignore this 1325 // intrinsic and handle this during isel like dbg.value. 1326 int FI = std::numeric_limits<int>::max(); 1327 if (const auto *AI = dyn_cast<AllocaInst>(Address)) { 1328 auto SI = FuncInfo->StaticAllocaMap.find(AI); 1329 if (SI != FuncInfo->StaticAllocaMap.end()) 1330 FI = SI->second; 1331 } else if (const auto *Arg = dyn_cast<Argument>(Address)) 1332 FI = FuncInfo->getArgumentFrameIndex(Arg); 1333 1334 if (FI == std::numeric_limits<int>::max()) 1335 continue; 1336 1337 DIExpression *Expr = DI->getExpression(); 1338 if (Offset.getBoolValue()) 1339 Expr = DIExpression::prepend(Expr, DIExpression::NoDeref, 1340 Offset.getZExtValue()); 1341 MF->setVariableDbgInfo(DI->getVariable(), Expr, FI, DI->getDebugLoc()); 1342 } 1343 } 1344 } 1345 1346 /// Propagate swifterror values through the machine function CFG. 1347 static void propagateSwiftErrorVRegs(FunctionLoweringInfo *FuncInfo) { 1348 auto *TLI = FuncInfo->TLI; 1349 if (!TLI->supportSwiftError()) 1350 return; 1351 1352 // We only need to do this when we have swifterror parameter or swifterror 1353 // alloc. 1354 if (FuncInfo->SwiftErrorVals.empty()) 1355 return; 1356 1357 // For each machine basic block in reverse post order. 1358 ReversePostOrderTraversal<MachineFunction *> RPOT(FuncInfo->MF); 1359 for (MachineBasicBlock *MBB : RPOT) { 1360 // For each swifterror value in the function. 1361 for(const auto *SwiftErrorVal : FuncInfo->SwiftErrorVals) { 1362 auto Key = std::make_pair(MBB, SwiftErrorVal); 1363 auto UUseIt = FuncInfo->SwiftErrorVRegUpwardsUse.find(Key); 1364 auto VRegDefIt = FuncInfo->SwiftErrorVRegDefMap.find(Key); 1365 bool UpwardsUse = UUseIt != FuncInfo->SwiftErrorVRegUpwardsUse.end(); 1366 unsigned UUseVReg = UpwardsUse ? UUseIt->second : 0; 1367 bool DownwardDef = VRegDefIt != FuncInfo->SwiftErrorVRegDefMap.end(); 1368 assert(!(UpwardsUse && !DownwardDef) && 1369 "We can't have an upwards use but no downwards def"); 1370 1371 // If there is no upwards exposed use and an entry for the swifterror in 1372 // the def map for this value we don't need to do anything: We already 1373 // have a downward def for this basic block. 1374 if (!UpwardsUse && DownwardDef) 1375 continue; 1376 1377 // Otherwise we either have an upwards exposed use vreg that we need to 1378 // materialize or need to forward the downward def from predecessors. 1379 1380 // Check whether we have a single vreg def from all predecessors. 1381 // Otherwise we need a phi. 1382 SmallVector<std::pair<MachineBasicBlock *, unsigned>, 4> VRegs; 1383 SmallSet<const MachineBasicBlock*, 8> Visited; 1384 for (auto *Pred : MBB->predecessors()) { 1385 if (!Visited.insert(Pred).second) 1386 continue; 1387 VRegs.push_back(std::make_pair( 1388 Pred, FuncInfo->getOrCreateSwiftErrorVReg(Pred, SwiftErrorVal))); 1389 if (Pred != MBB) 1390 continue; 1391 // We have a self-edge. 1392 // If there was no upwards use in this basic block there is now one: the 1393 // phi needs to use it self. 1394 if (!UpwardsUse) { 1395 UpwardsUse = true; 1396 UUseIt = FuncInfo->SwiftErrorVRegUpwardsUse.find(Key); 1397 assert(UUseIt != FuncInfo->SwiftErrorVRegUpwardsUse.end()); 1398 UUseVReg = UUseIt->second; 1399 } 1400 } 1401 1402 // We need a phi node if we have more than one predecessor with different 1403 // downward defs. 1404 bool needPHI = 1405 VRegs.size() >= 1 && 1406 std::find_if( 1407 VRegs.begin(), VRegs.end(), 1408 [&](const std::pair<const MachineBasicBlock *, unsigned> &V) 1409 -> bool { return V.second != VRegs[0].second; }) != 1410 VRegs.end(); 1411 1412 // If there is no upwards exposed used and we don't need a phi just 1413 // forward the swifterror vreg from the predecessor(s). 1414 if (!UpwardsUse && !needPHI) { 1415 assert(!VRegs.empty() && 1416 "No predecessors? The entry block should bail out earlier"); 1417 // Just forward the swifterror vreg from the predecessor(s). 1418 FuncInfo->setCurrentSwiftErrorVReg(MBB, SwiftErrorVal, VRegs[0].second); 1419 continue; 1420 } 1421 1422 auto DLoc = isa<Instruction>(SwiftErrorVal) 1423 ? cast<Instruction>(SwiftErrorVal)->getDebugLoc() 1424 : DebugLoc(); 1425 const auto *TII = FuncInfo->MF->getSubtarget().getInstrInfo(); 1426 1427 // If we don't need a phi create a copy to the upward exposed vreg. 1428 if (!needPHI) { 1429 assert(UpwardsUse); 1430 assert(!VRegs.empty() && 1431 "No predecessors? Is the Calling Convention correct?"); 1432 unsigned DestReg = UUseVReg; 1433 BuildMI(*MBB, MBB->getFirstNonPHI(), DLoc, TII->get(TargetOpcode::COPY), 1434 DestReg) 1435 .addReg(VRegs[0].second); 1436 continue; 1437 } 1438 1439 // We need a phi: if there is an upwards exposed use we already have a 1440 // destination virtual register number otherwise we generate a new one. 1441 auto &DL = FuncInfo->MF->getDataLayout(); 1442 auto const *RC = TLI->getRegClassFor(TLI->getPointerTy(DL)); 1443 unsigned PHIVReg = 1444 UpwardsUse ? UUseVReg 1445 : FuncInfo->MF->getRegInfo().createVirtualRegister(RC); 1446 MachineInstrBuilder SwiftErrorPHI = 1447 BuildMI(*MBB, MBB->getFirstNonPHI(), DLoc, 1448 TII->get(TargetOpcode::PHI), PHIVReg); 1449 for (auto BBRegPair : VRegs) { 1450 SwiftErrorPHI.addReg(BBRegPair.second).addMBB(BBRegPair.first); 1451 } 1452 1453 // We did not have a definition in this block before: store the phi's vreg 1454 // as this block downward exposed def. 1455 if (!UpwardsUse) 1456 FuncInfo->setCurrentSwiftErrorVReg(MBB, SwiftErrorVal, PHIVReg); 1457 } 1458 } 1459 } 1460 1461 static void preassignSwiftErrorRegs(const TargetLowering *TLI, 1462 FunctionLoweringInfo *FuncInfo, 1463 BasicBlock::const_iterator Begin, 1464 BasicBlock::const_iterator End) { 1465 if (!TLI->supportSwiftError() || FuncInfo->SwiftErrorVals.empty()) 1466 return; 1467 1468 // Iterator over instructions and assign vregs to swifterror defs and uses. 1469 for (auto It = Begin; It != End; ++It) { 1470 ImmutableCallSite CS(&*It); 1471 if (CS) { 1472 // A call-site with a swifterror argument is both use and def. 1473 const Value *SwiftErrorAddr = nullptr; 1474 for (auto &Arg : CS.args()) { 1475 if (!Arg->isSwiftError()) 1476 continue; 1477 // Use of swifterror. 1478 assert(!SwiftErrorAddr && "Cannot have multiple swifterror arguments"); 1479 SwiftErrorAddr = &*Arg; 1480 assert(SwiftErrorAddr->isSwiftError() && 1481 "Must have a swifterror value argument"); 1482 unsigned VReg; bool CreatedReg; 1483 std::tie(VReg, CreatedReg) = FuncInfo->getOrCreateSwiftErrorVRegUseAt( 1484 &*It, FuncInfo->MBB, SwiftErrorAddr); 1485 assert(CreatedReg); 1486 } 1487 if (!SwiftErrorAddr) 1488 continue; 1489 1490 // Def of swifterror. 1491 unsigned VReg; bool CreatedReg; 1492 std::tie(VReg, CreatedReg) = 1493 FuncInfo->getOrCreateSwiftErrorVRegDefAt(&*It); 1494 assert(CreatedReg); 1495 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, SwiftErrorAddr, VReg); 1496 1497 // A load is a use. 1498 } else if (const LoadInst *LI = dyn_cast<const LoadInst>(&*It)) { 1499 const Value *V = LI->getOperand(0); 1500 if (!V->isSwiftError()) 1501 continue; 1502 1503 unsigned VReg; bool CreatedReg; 1504 std::tie(VReg, CreatedReg) = 1505 FuncInfo->getOrCreateSwiftErrorVRegUseAt(LI, FuncInfo->MBB, V); 1506 assert(CreatedReg); 1507 1508 // A store is a def. 1509 } else if (const StoreInst *SI = dyn_cast<const StoreInst>(&*It)) { 1510 const Value *SwiftErrorAddr = SI->getOperand(1); 1511 if (!SwiftErrorAddr->isSwiftError()) 1512 continue; 1513 1514 // Def of swifterror. 1515 unsigned VReg; bool CreatedReg; 1516 std::tie(VReg, CreatedReg) = 1517 FuncInfo->getOrCreateSwiftErrorVRegDefAt(&*It); 1518 assert(CreatedReg); 1519 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, SwiftErrorAddr, VReg); 1520 1521 // A return in a swiferror returning function is a use. 1522 } else if (const ReturnInst *R = dyn_cast<const ReturnInst>(&*It)) { 1523 const Function *F = R->getParent()->getParent(); 1524 if(!F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 1525 continue; 1526 1527 unsigned VReg; bool CreatedReg; 1528 std::tie(VReg, CreatedReg) = FuncInfo->getOrCreateSwiftErrorVRegUseAt( 1529 R, FuncInfo->MBB, FuncInfo->SwiftErrorArg); 1530 assert(CreatedReg); 1531 } 1532 } 1533 } 1534 1535 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) { 1536 FastISelFailed = false; 1537 // Initialize the Fast-ISel state, if needed. 1538 FastISel *FastIS = nullptr; 1539 if (TM.Options.EnableFastISel) { 1540 LLVM_DEBUG(dbgs() << "Enabling fast-isel\n"); 1541 FastIS = TLI->createFastISel(*FuncInfo, LibInfo); 1542 } 1543 1544 setupSwiftErrorVals(Fn, TLI, FuncInfo); 1545 1546 ReversePostOrderTraversal<const Function*> RPOT(&Fn); 1547 1548 // Lower arguments up front. An RPO iteration always visits the entry block 1549 // first. 1550 assert(*RPOT.begin() == &Fn.getEntryBlock()); 1551 ++NumEntryBlocks; 1552 1553 // Set up FuncInfo for ISel. Entry blocks never have PHIs. 1554 FuncInfo->MBB = FuncInfo->MBBMap[&Fn.getEntryBlock()]; 1555 FuncInfo->InsertPt = FuncInfo->MBB->begin(); 1556 1557 CurDAG->setFunctionLoweringInfo(FuncInfo); 1558 1559 if (!FastIS) { 1560 LowerArguments(Fn); 1561 } else { 1562 // See if fast isel can lower the arguments. 1563 FastIS->startNewBlock(); 1564 if (!FastIS->lowerArguments()) { 1565 FastISelFailed = true; 1566 // Fast isel failed to lower these arguments 1567 ++NumFastIselFailLowerArguments; 1568 1569 OptimizationRemarkMissed R("sdagisel", "FastISelFailure", 1570 Fn.getSubprogram(), 1571 &Fn.getEntryBlock()); 1572 R << "FastISel didn't lower all arguments: " 1573 << ore::NV("Prototype", Fn.getType()); 1574 reportFastISelFailure(*MF, *ORE, R, EnableFastISelAbort > 1); 1575 1576 // Use SelectionDAG argument lowering 1577 LowerArguments(Fn); 1578 CurDAG->setRoot(SDB->getControlRoot()); 1579 SDB->clear(); 1580 CodeGenAndEmitDAG(); 1581 } 1582 1583 // If we inserted any instructions at the beginning, make a note of 1584 // where they are, so we can be sure to emit subsequent instructions 1585 // after them. 1586 if (FuncInfo->InsertPt != FuncInfo->MBB->begin()) 1587 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt)); 1588 else 1589 FastIS->setLastLocalValue(nullptr); 1590 } 1591 createSwiftErrorEntriesInEntryBlock(FuncInfo, FastIS, TLI, TII, SDB); 1592 1593 processDbgDeclares(FuncInfo); 1594 1595 // Iterate over all basic blocks in the function. 1596 StackProtector &SP = getAnalysis<StackProtector>(); 1597 for (const BasicBlock *LLVMBB : RPOT) { 1598 if (OptLevel != CodeGenOpt::None) { 1599 bool AllPredsVisited = true; 1600 for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB); 1601 PI != PE; ++PI) { 1602 if (!FuncInfo->VisitedBBs.count(*PI)) { 1603 AllPredsVisited = false; 1604 break; 1605 } 1606 } 1607 1608 if (AllPredsVisited) { 1609 for (const PHINode &PN : LLVMBB->phis()) 1610 FuncInfo->ComputePHILiveOutRegInfo(&PN); 1611 } else { 1612 for (const PHINode &PN : LLVMBB->phis()) 1613 FuncInfo->InvalidatePHILiveOutRegInfo(&PN); 1614 } 1615 1616 FuncInfo->VisitedBBs.insert(LLVMBB); 1617 } 1618 1619 BasicBlock::const_iterator const Begin = 1620 LLVMBB->getFirstNonPHI()->getIterator(); 1621 BasicBlock::const_iterator const End = LLVMBB->end(); 1622 BasicBlock::const_iterator BI = End; 1623 1624 FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB]; 1625 if (!FuncInfo->MBB) 1626 continue; // Some blocks like catchpads have no code or MBB. 1627 1628 // Insert new instructions after any phi or argument setup code. 1629 FuncInfo->InsertPt = FuncInfo->MBB->end(); 1630 1631 // Setup an EH landing-pad block. 1632 FuncInfo->ExceptionPointerVirtReg = 0; 1633 FuncInfo->ExceptionSelectorVirtReg = 0; 1634 if (LLVMBB->isEHPad()) 1635 if (!PrepareEHLandingPad()) 1636 continue; 1637 1638 // Before doing SelectionDAG ISel, see if FastISel has been requested. 1639 if (FastIS) { 1640 if (LLVMBB != &Fn.getEntryBlock()) 1641 FastIS->startNewBlock(); 1642 1643 unsigned NumFastIselRemaining = std::distance(Begin, End); 1644 1645 // Pre-assign swifterror vregs. 1646 preassignSwiftErrorRegs(TLI, FuncInfo, Begin, End); 1647 1648 // Do FastISel on as many instructions as possible. 1649 for (; BI != Begin; --BI) { 1650 const Instruction *Inst = &*std::prev(BI); 1651 1652 // If we no longer require this instruction, skip it. 1653 if (isFoldedOrDeadInstruction(Inst, FuncInfo) || 1654 ElidedArgCopyInstrs.count(Inst)) { 1655 --NumFastIselRemaining; 1656 continue; 1657 } 1658 1659 // Bottom-up: reset the insert pos at the top, after any local-value 1660 // instructions. 1661 FastIS->recomputeInsertPt(); 1662 1663 // Try to select the instruction with FastISel. 1664 if (FastIS->selectInstruction(Inst)) { 1665 --NumFastIselRemaining; 1666 ++NumFastIselSuccess; 1667 // If fast isel succeeded, skip over all the folded instructions, and 1668 // then see if there is a load right before the selected instructions. 1669 // Try to fold the load if so. 1670 const Instruction *BeforeInst = Inst; 1671 while (BeforeInst != &*Begin) { 1672 BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst)); 1673 if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo)) 1674 break; 1675 } 1676 if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) && 1677 BeforeInst->hasOneUse() && 1678 FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) { 1679 // If we succeeded, don't re-select the load. 1680 BI = std::next(BasicBlock::const_iterator(BeforeInst)); 1681 --NumFastIselRemaining; 1682 ++NumFastIselSuccess; 1683 } 1684 continue; 1685 } 1686 1687 FastISelFailed = true; 1688 1689 // Then handle certain instructions as single-LLVM-Instruction blocks. 1690 // We cannot separate out GCrelocates to their own blocks since we need 1691 // to keep track of gc-relocates for a particular gc-statepoint. This is 1692 // done by SelectionDAGBuilder::LowerAsSTATEPOINT, called before 1693 // visitGCRelocate. 1694 if (isa<CallInst>(Inst) && !isStatepoint(Inst) && !isGCRelocate(Inst)) { 1695 OptimizationRemarkMissed R("sdagisel", "FastISelFailure", 1696 Inst->getDebugLoc(), LLVMBB); 1697 1698 R << "FastISel missed call"; 1699 1700 if (R.isEnabled() || EnableFastISelAbort) { 1701 std::string InstStrStorage; 1702 raw_string_ostream InstStr(InstStrStorage); 1703 InstStr << *Inst; 1704 1705 R << ": " << InstStr.str(); 1706 } 1707 1708 reportFastISelFailure(*MF, *ORE, R, EnableFastISelAbort > 2); 1709 1710 if (!Inst->getType()->isVoidTy() && !Inst->getType()->isTokenTy() && 1711 !Inst->use_empty()) { 1712 unsigned &R = FuncInfo->ValueMap[Inst]; 1713 if (!R) 1714 R = FuncInfo->CreateRegs(Inst->getType()); 1715 } 1716 1717 bool HadTailCall = false; 1718 MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt; 1719 SelectBasicBlock(Inst->getIterator(), BI, HadTailCall); 1720 1721 // If the call was emitted as a tail call, we're done with the block. 1722 // We also need to delete any previously emitted instructions. 1723 if (HadTailCall) { 1724 FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end()); 1725 --BI; 1726 break; 1727 } 1728 1729 // Recompute NumFastIselRemaining as Selection DAG instruction 1730 // selection may have handled the call, input args, etc. 1731 unsigned RemainingNow = std::distance(Begin, BI); 1732 NumFastIselFailures += NumFastIselRemaining - RemainingNow; 1733 NumFastIselRemaining = RemainingNow; 1734 continue; 1735 } 1736 1737 OptimizationRemarkMissed R("sdagisel", "FastISelFailure", 1738 Inst->getDebugLoc(), LLVMBB); 1739 1740 bool ShouldAbort = EnableFastISelAbort; 1741 if (Inst->isTerminator()) { 1742 // Use a different message for terminator misses. 1743 R << "FastISel missed terminator"; 1744 // Don't abort for terminator unless the level is really high 1745 ShouldAbort = (EnableFastISelAbort > 2); 1746 } else { 1747 R << "FastISel missed"; 1748 } 1749 1750 if (R.isEnabled() || EnableFastISelAbort) { 1751 std::string InstStrStorage; 1752 raw_string_ostream InstStr(InstStrStorage); 1753 InstStr << *Inst; 1754 R << ": " << InstStr.str(); 1755 } 1756 1757 reportFastISelFailure(*MF, *ORE, R, ShouldAbort); 1758 1759 NumFastIselFailures += NumFastIselRemaining; 1760 break; 1761 } 1762 1763 FastIS->recomputeInsertPt(); 1764 } 1765 1766 if (SP.shouldEmitSDCheck(*LLVMBB)) { 1767 bool FunctionBasedInstrumentation = 1768 TLI->getSSPStackGuardCheck(*Fn.getParent()); 1769 SDB->SPDescriptor.initialize(LLVMBB, FuncInfo->MBBMap[LLVMBB], 1770 FunctionBasedInstrumentation); 1771 } 1772 1773 if (Begin != BI) 1774 ++NumDAGBlocks; 1775 else 1776 ++NumFastIselBlocks; 1777 1778 if (Begin != BI) { 1779 // Run SelectionDAG instruction selection on the remainder of the block 1780 // not handled by FastISel. If FastISel is not run, this is the entire 1781 // block. 1782 bool HadTailCall; 1783 SelectBasicBlock(Begin, BI, HadTailCall); 1784 1785 // But if FastISel was run, we already selected some of the block. 1786 // If we emitted a tail-call, we need to delete any previously emitted 1787 // instruction that follows it. 1788 if (HadTailCall && FuncInfo->InsertPt != FuncInfo->MBB->end()) 1789 FastIS->removeDeadCode(FuncInfo->InsertPt, FuncInfo->MBB->end()); 1790 } 1791 1792 if (FastIS) 1793 FastIS->finishBasicBlock(); 1794 FinishBasicBlock(); 1795 FuncInfo->PHINodesToUpdate.clear(); 1796 ElidedArgCopyInstrs.clear(); 1797 } 1798 1799 SP.copyToMachineFrameInfo(MF->getFrameInfo()); 1800 1801 propagateSwiftErrorVRegs(FuncInfo); 1802 1803 delete FastIS; 1804 SDB->clearDanglingDebugInfo(); 1805 SDB->SPDescriptor.resetPerFunctionState(); 1806 } 1807 1808 /// Given that the input MI is before a partial terminator sequence TSeq, return 1809 /// true if M + TSeq also a partial terminator sequence. 1810 /// 1811 /// A Terminator sequence is a sequence of MachineInstrs which at this point in 1812 /// lowering copy vregs into physical registers, which are then passed into 1813 /// terminator instructors so we can satisfy ABI constraints. A partial 1814 /// terminator sequence is an improper subset of a terminator sequence (i.e. it 1815 /// may be the whole terminator sequence). 1816 static bool MIIsInTerminatorSequence(const MachineInstr &MI) { 1817 // If we do not have a copy or an implicit def, we return true if and only if 1818 // MI is a debug value. 1819 if (!MI.isCopy() && !MI.isImplicitDef()) 1820 // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the 1821 // physical registers if there is debug info associated with the terminator 1822 // of our mbb. We want to include said debug info in our terminator 1823 // sequence, so we return true in that case. 1824 return MI.isDebugValue(); 1825 1826 // We have left the terminator sequence if we are not doing one of the 1827 // following: 1828 // 1829 // 1. Copying a vreg into a physical register. 1830 // 2. Copying a vreg into a vreg. 1831 // 3. Defining a register via an implicit def. 1832 1833 // OPI should always be a register definition... 1834 MachineInstr::const_mop_iterator OPI = MI.operands_begin(); 1835 if (!OPI->isReg() || !OPI->isDef()) 1836 return false; 1837 1838 // Defining any register via an implicit def is always ok. 1839 if (MI.isImplicitDef()) 1840 return true; 1841 1842 // Grab the copy source... 1843 MachineInstr::const_mop_iterator OPI2 = OPI; 1844 ++OPI2; 1845 assert(OPI2 != MI.operands_end() 1846 && "Should have a copy implying we should have 2 arguments."); 1847 1848 // Make sure that the copy dest is not a vreg when the copy source is a 1849 // physical register. 1850 if (!OPI2->isReg() || 1851 (!TargetRegisterInfo::isPhysicalRegister(OPI->getReg()) && 1852 TargetRegisterInfo::isPhysicalRegister(OPI2->getReg()))) 1853 return false; 1854 1855 return true; 1856 } 1857 1858 /// Find the split point at which to splice the end of BB into its success stack 1859 /// protector check machine basic block. 1860 /// 1861 /// On many platforms, due to ABI constraints, terminators, even before register 1862 /// allocation, use physical registers. This creates an issue for us since 1863 /// physical registers at this point can not travel across basic 1864 /// blocks. Luckily, selectiondag always moves physical registers into vregs 1865 /// when they enter functions and moves them through a sequence of copies back 1866 /// into the physical registers right before the terminator creating a 1867 /// ``Terminator Sequence''. This function is searching for the beginning of the 1868 /// terminator sequence so that we can ensure that we splice off not just the 1869 /// terminator, but additionally the copies that move the vregs into the 1870 /// physical registers. 1871 static MachineBasicBlock::iterator 1872 FindSplitPointForStackProtector(MachineBasicBlock *BB) { 1873 MachineBasicBlock::iterator SplitPoint = BB->getFirstTerminator(); 1874 // 1875 if (SplitPoint == BB->begin()) 1876 return SplitPoint; 1877 1878 MachineBasicBlock::iterator Start = BB->begin(); 1879 MachineBasicBlock::iterator Previous = SplitPoint; 1880 --Previous; 1881 1882 while (MIIsInTerminatorSequence(*Previous)) { 1883 SplitPoint = Previous; 1884 if (Previous == Start) 1885 break; 1886 --Previous; 1887 } 1888 1889 return SplitPoint; 1890 } 1891 1892 void 1893 SelectionDAGISel::FinishBasicBlock() { 1894 LLVM_DEBUG(dbgs() << "Total amount of phi nodes to update: " 1895 << FuncInfo->PHINodesToUpdate.size() << "\n"; 1896 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; 1897 ++i) dbgs() 1898 << "Node " << i << " : (" << FuncInfo->PHINodesToUpdate[i].first 1899 << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n"); 1900 1901 // Next, now that we know what the last MBB the LLVM BB expanded is, update 1902 // PHI nodes in successors. 1903 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) { 1904 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first); 1905 assert(PHI->isPHI() && 1906 "This is not a machine PHI node that we are updating!"); 1907 if (!FuncInfo->MBB->isSuccessor(PHI->getParent())) 1908 continue; 1909 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB); 1910 } 1911 1912 // Handle stack protector. 1913 if (SDB->SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) { 1914 // The target provides a guard check function. There is no need to 1915 // generate error handling code or to split current basic block. 1916 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB(); 1917 1918 // Add load and check to the basicblock. 1919 FuncInfo->MBB = ParentMBB; 1920 FuncInfo->InsertPt = 1921 FindSplitPointForStackProtector(ParentMBB); 1922 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB); 1923 CurDAG->setRoot(SDB->getRoot()); 1924 SDB->clear(); 1925 CodeGenAndEmitDAG(); 1926 1927 // Clear the Per-BB State. 1928 SDB->SPDescriptor.resetPerBBState(); 1929 } else if (SDB->SPDescriptor.shouldEmitStackProtector()) { 1930 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB(); 1931 MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB(); 1932 1933 // Find the split point to split the parent mbb. At the same time copy all 1934 // physical registers used in the tail of parent mbb into virtual registers 1935 // before the split point and back into physical registers after the split 1936 // point. This prevents us needing to deal with Live-ins and many other 1937 // register allocation issues caused by us splitting the parent mbb. The 1938 // register allocator will clean up said virtual copies later on. 1939 MachineBasicBlock::iterator SplitPoint = 1940 FindSplitPointForStackProtector(ParentMBB); 1941 1942 // Splice the terminator of ParentMBB into SuccessMBB. 1943 SuccessMBB->splice(SuccessMBB->end(), ParentMBB, 1944 SplitPoint, 1945 ParentMBB->end()); 1946 1947 // Add compare/jump on neq/jump to the parent BB. 1948 FuncInfo->MBB = ParentMBB; 1949 FuncInfo->InsertPt = ParentMBB->end(); 1950 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB); 1951 CurDAG->setRoot(SDB->getRoot()); 1952 SDB->clear(); 1953 CodeGenAndEmitDAG(); 1954 1955 // CodeGen Failure MBB if we have not codegened it yet. 1956 MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB(); 1957 if (FailureMBB->empty()) { 1958 FuncInfo->MBB = FailureMBB; 1959 FuncInfo->InsertPt = FailureMBB->end(); 1960 SDB->visitSPDescriptorFailure(SDB->SPDescriptor); 1961 CurDAG->setRoot(SDB->getRoot()); 1962 SDB->clear(); 1963 CodeGenAndEmitDAG(); 1964 } 1965 1966 // Clear the Per-BB State. 1967 SDB->SPDescriptor.resetPerBBState(); 1968 } 1969 1970 // Lower each BitTestBlock. 1971 for (auto &BTB : SDB->BitTestCases) { 1972 // Lower header first, if it wasn't already lowered 1973 if (!BTB.Emitted) { 1974 // Set the current basic block to the mbb we wish to insert the code into 1975 FuncInfo->MBB = BTB.Parent; 1976 FuncInfo->InsertPt = FuncInfo->MBB->end(); 1977 // Emit the code 1978 SDB->visitBitTestHeader(BTB, FuncInfo->MBB); 1979 CurDAG->setRoot(SDB->getRoot()); 1980 SDB->clear(); 1981 CodeGenAndEmitDAG(); 1982 } 1983 1984 BranchProbability UnhandledProb = BTB.Prob; 1985 for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) { 1986 UnhandledProb -= BTB.Cases[j].ExtraProb; 1987 // Set the current basic block to the mbb we wish to insert the code into 1988 FuncInfo->MBB = BTB.Cases[j].ThisBB; 1989 FuncInfo->InsertPt = FuncInfo->MBB->end(); 1990 // Emit the code 1991 1992 // If all cases cover a contiguous range, it is not necessary to jump to 1993 // the default block after the last bit test fails. This is because the 1994 // range check during bit test header creation has guaranteed that every 1995 // case here doesn't go outside the range. In this case, there is no need 1996 // to perform the last bit test, as it will always be true. Instead, make 1997 // the second-to-last bit-test fall through to the target of the last bit 1998 // test, and delete the last bit test. 1999 2000 MachineBasicBlock *NextMBB; 2001 if (BTB.ContiguousRange && j + 2 == ej) { 2002 // Second-to-last bit-test with contiguous range: fall through to the 2003 // target of the final bit test. 2004 NextMBB = BTB.Cases[j + 1].TargetBB; 2005 } else if (j + 1 == ej) { 2006 // For the last bit test, fall through to Default. 2007 NextMBB = BTB.Default; 2008 } else { 2009 // Otherwise, fall through to the next bit test. 2010 NextMBB = BTB.Cases[j + 1].ThisBB; 2011 } 2012 2013 SDB->visitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j], 2014 FuncInfo->MBB); 2015 2016 CurDAG->setRoot(SDB->getRoot()); 2017 SDB->clear(); 2018 CodeGenAndEmitDAG(); 2019 2020 if (BTB.ContiguousRange && j + 2 == ej) { 2021 // Since we're not going to use the final bit test, remove it. 2022 BTB.Cases.pop_back(); 2023 break; 2024 } 2025 } 2026 2027 // Update PHI Nodes 2028 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size(); 2029 pi != pe; ++pi) { 2030 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first); 2031 MachineBasicBlock *PHIBB = PHI->getParent(); 2032 assert(PHI->isPHI() && 2033 "This is not a machine PHI node that we are updating!"); 2034 // This is "default" BB. We have two jumps to it. From "header" BB and 2035 // from last "case" BB, unless the latter was skipped. 2036 if (PHIBB == BTB.Default) { 2037 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(BTB.Parent); 2038 if (!BTB.ContiguousRange) { 2039 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second) 2040 .addMBB(BTB.Cases.back().ThisBB); 2041 } 2042 } 2043 // One of "cases" BB. 2044 for (unsigned j = 0, ej = BTB.Cases.size(); 2045 j != ej; ++j) { 2046 MachineBasicBlock* cBB = BTB.Cases[j].ThisBB; 2047 if (cBB->isSuccessor(PHIBB)) 2048 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB); 2049 } 2050 } 2051 } 2052 SDB->BitTestCases.clear(); 2053 2054 // If the JumpTable record is filled in, then we need to emit a jump table. 2055 // Updating the PHI nodes is tricky in this case, since we need to determine 2056 // whether the PHI is a successor of the range check MBB or the jump table MBB 2057 for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) { 2058 // Lower header first, if it wasn't already lowered 2059 if (!SDB->JTCases[i].first.Emitted) { 2060 // Set the current basic block to the mbb we wish to insert the code into 2061 FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB; 2062 FuncInfo->InsertPt = FuncInfo->MBB->end(); 2063 // Emit the code 2064 SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first, 2065 FuncInfo->MBB); 2066 CurDAG->setRoot(SDB->getRoot()); 2067 SDB->clear(); 2068 CodeGenAndEmitDAG(); 2069 } 2070 2071 // Set the current basic block to the mbb we wish to insert the code into 2072 FuncInfo->MBB = SDB->JTCases[i].second.MBB; 2073 FuncInfo->InsertPt = FuncInfo->MBB->end(); 2074 // Emit the code 2075 SDB->visitJumpTable(SDB->JTCases[i].second); 2076 CurDAG->setRoot(SDB->getRoot()); 2077 SDB->clear(); 2078 CodeGenAndEmitDAG(); 2079 2080 // Update PHI Nodes 2081 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size(); 2082 pi != pe; ++pi) { 2083 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first); 2084 MachineBasicBlock *PHIBB = PHI->getParent(); 2085 assert(PHI->isPHI() && 2086 "This is not a machine PHI node that we are updating!"); 2087 // "default" BB. We can go there only from header BB. 2088 if (PHIBB == SDB->JTCases[i].second.Default) 2089 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second) 2090 .addMBB(SDB->JTCases[i].first.HeaderBB); 2091 // JT BB. Just iterate over successors here 2092 if (FuncInfo->MBB->isSuccessor(PHIBB)) 2093 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB); 2094 } 2095 } 2096 SDB->JTCases.clear(); 2097 2098 // If we generated any switch lowering information, build and codegen any 2099 // additional DAGs necessary. 2100 for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) { 2101 // Set the current basic block to the mbb we wish to insert the code into 2102 FuncInfo->MBB = SDB->SwitchCases[i].ThisBB; 2103 FuncInfo->InsertPt = FuncInfo->MBB->end(); 2104 2105 // Determine the unique successors. 2106 SmallVector<MachineBasicBlock *, 2> Succs; 2107 Succs.push_back(SDB->SwitchCases[i].TrueBB); 2108 if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB) 2109 Succs.push_back(SDB->SwitchCases[i].FalseBB); 2110 2111 // Emit the code. Note that this could result in FuncInfo->MBB being split. 2112 SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB); 2113 CurDAG->setRoot(SDB->getRoot()); 2114 SDB->clear(); 2115 CodeGenAndEmitDAG(); 2116 2117 // Remember the last block, now that any splitting is done, for use in 2118 // populating PHI nodes in successors. 2119 MachineBasicBlock *ThisBB = FuncInfo->MBB; 2120 2121 // Handle any PHI nodes in successors of this chunk, as if we were coming 2122 // from the original BB before switch expansion. Note that PHI nodes can 2123 // occur multiple times in PHINodesToUpdate. We have to be very careful to 2124 // handle them the right number of times. 2125 for (unsigned i = 0, e = Succs.size(); i != e; ++i) { 2126 FuncInfo->MBB = Succs[i]; 2127 FuncInfo->InsertPt = FuncInfo->MBB->end(); 2128 // FuncInfo->MBB may have been removed from the CFG if a branch was 2129 // constant folded. 2130 if (ThisBB->isSuccessor(FuncInfo->MBB)) { 2131 for (MachineBasicBlock::iterator 2132 MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end(); 2133 MBBI != MBBE && MBBI->isPHI(); ++MBBI) { 2134 MachineInstrBuilder PHI(*MF, MBBI); 2135 // This value for this PHI node is recorded in PHINodesToUpdate. 2136 for (unsigned pn = 0; ; ++pn) { 2137 assert(pn != FuncInfo->PHINodesToUpdate.size() && 2138 "Didn't find PHI entry!"); 2139 if (FuncInfo->PHINodesToUpdate[pn].first == PHI) { 2140 PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB); 2141 break; 2142 } 2143 } 2144 } 2145 } 2146 } 2147 } 2148 SDB->SwitchCases.clear(); 2149 } 2150 2151 /// Create the scheduler. If a specific scheduler was specified 2152 /// via the SchedulerRegistry, use it, otherwise select the 2153 /// one preferred by the target. 2154 /// 2155 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() { 2156 return ISHeuristic(this, OptLevel); 2157 } 2158 2159 //===----------------------------------------------------------------------===// 2160 // Helper functions used by the generated instruction selector. 2161 //===----------------------------------------------------------------------===// 2162 // Calls to these methods are generated by tblgen. 2163 2164 /// CheckAndMask - The isel is trying to match something like (and X, 255). If 2165 /// the dag combiner simplified the 255, we still want to match. RHS is the 2166 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value 2167 /// specified in the .td file (e.g. 255). 2168 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS, 2169 int64_t DesiredMaskS) const { 2170 const APInt &ActualMask = RHS->getAPIntValue(); 2171 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS); 2172 2173 // If the actual mask exactly matches, success! 2174 if (ActualMask == DesiredMask) 2175 return true; 2176 2177 // If the actual AND mask is allowing unallowed bits, this doesn't match. 2178 if (!ActualMask.isSubsetOf(DesiredMask)) 2179 return false; 2180 2181 // Otherwise, the DAG Combiner may have proven that the value coming in is 2182 // either already zero or is not demanded. Check for known zero input bits. 2183 APInt NeededMask = DesiredMask & ~ActualMask; 2184 if (CurDAG->MaskedValueIsZero(LHS, NeededMask)) 2185 return true; 2186 2187 // TODO: check to see if missing bits are just not demanded. 2188 2189 // Otherwise, this pattern doesn't match. 2190 return false; 2191 } 2192 2193 /// CheckOrMask - The isel is trying to match something like (or X, 255). If 2194 /// the dag combiner simplified the 255, we still want to match. RHS is the 2195 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value 2196 /// specified in the .td file (e.g. 255). 2197 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS, 2198 int64_t DesiredMaskS) const { 2199 const APInt &ActualMask = RHS->getAPIntValue(); 2200 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS); 2201 2202 // If the actual mask exactly matches, success! 2203 if (ActualMask == DesiredMask) 2204 return true; 2205 2206 // If the actual AND mask is allowing unallowed bits, this doesn't match. 2207 if (!ActualMask.isSubsetOf(DesiredMask)) 2208 return false; 2209 2210 // Otherwise, the DAG Combiner may have proven that the value coming in is 2211 // either already zero or is not demanded. Check for known zero input bits. 2212 APInt NeededMask = DesiredMask & ~ActualMask; 2213 2214 KnownBits Known; 2215 CurDAG->computeKnownBits(LHS, Known); 2216 2217 // If all the missing bits in the or are already known to be set, match! 2218 if (NeededMask.isSubsetOf(Known.One)) 2219 return true; 2220 2221 // TODO: check to see if missing bits are just not demanded. 2222 2223 // Otherwise, this pattern doesn't match. 2224 return false; 2225 } 2226 2227 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated 2228 /// by tblgen. Others should not call it. 2229 void SelectionDAGISel::SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops, 2230 const SDLoc &DL) { 2231 std::vector<SDValue> InOps; 2232 std::swap(InOps, Ops); 2233 2234 Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0 2235 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1 2236 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc 2237 Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack) 2238 2239 unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size(); 2240 if (InOps[e-1].getValueType() == MVT::Glue) 2241 --e; // Don't process a glue operand if it is here. 2242 2243 while (i != e) { 2244 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue(); 2245 if (!InlineAsm::isMemKind(Flags)) { 2246 // Just skip over this operand, copying the operands verbatim. 2247 Ops.insert(Ops.end(), InOps.begin()+i, 2248 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1); 2249 i += InlineAsm::getNumOperandRegisters(Flags) + 1; 2250 } else { 2251 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 && 2252 "Memory operand with multiple values?"); 2253 2254 unsigned TiedToOperand; 2255 if (InlineAsm::isUseOperandTiedToDef(Flags, TiedToOperand)) { 2256 // We need the constraint ID from the operand this is tied to. 2257 unsigned CurOp = InlineAsm::Op_FirstOperand; 2258 Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue(); 2259 for (; TiedToOperand; --TiedToOperand) { 2260 CurOp += InlineAsm::getNumOperandRegisters(Flags)+1; 2261 Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue(); 2262 } 2263 } 2264 2265 // Otherwise, this is a memory operand. Ask the target to select it. 2266 std::vector<SDValue> SelOps; 2267 unsigned ConstraintID = InlineAsm::getMemoryConstraintID(Flags); 2268 if (SelectInlineAsmMemoryOperand(InOps[i+1], ConstraintID, SelOps)) 2269 report_fatal_error("Could not match memory address. Inline asm" 2270 " failure!"); 2271 2272 // Add this to the output node. 2273 unsigned NewFlags = 2274 InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size()); 2275 NewFlags = InlineAsm::getFlagWordForMem(NewFlags, ConstraintID); 2276 Ops.push_back(CurDAG->getTargetConstant(NewFlags, DL, MVT::i32)); 2277 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end()); 2278 i += 2; 2279 } 2280 } 2281 2282 // Add the glue input back if present. 2283 if (e != InOps.size()) 2284 Ops.push_back(InOps.back()); 2285 } 2286 2287 /// findGlueUse - Return use of MVT::Glue value produced by the specified 2288 /// SDNode. 2289 /// 2290 static SDNode *findGlueUse(SDNode *N) { 2291 unsigned FlagResNo = N->getNumValues()-1; 2292 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 2293 SDUse &Use = I.getUse(); 2294 if (Use.getResNo() == FlagResNo) 2295 return Use.getUser(); 2296 } 2297 return nullptr; 2298 } 2299 2300 /// findNonImmUse - Return true if "Def" is a predecessor of "Root" via a path 2301 /// beyond "ImmedUse". We may ignore chains as they are checked separately. 2302 static bool findNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse, 2303 bool IgnoreChains) { 2304 SmallPtrSet<const SDNode *, 16> Visited; 2305 SmallVector<const SDNode *, 16> WorkList; 2306 // Only check if we have non-immediate uses of Def. 2307 if (ImmedUse->isOnlyUserOf(Def)) 2308 return false; 2309 2310 // We don't care about paths to Def that go through ImmedUse so mark it 2311 // visited and mark non-def operands as used. 2312 Visited.insert(ImmedUse); 2313 for (const SDValue &Op : ImmedUse->op_values()) { 2314 SDNode *N = Op.getNode(); 2315 // Ignore chain deps (they are validated by 2316 // HandleMergeInputChains) and immediate uses 2317 if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def) 2318 continue; 2319 if (!Visited.insert(N).second) 2320 continue; 2321 WorkList.push_back(N); 2322 } 2323 2324 // Initialize worklist to operands of Root. 2325 if (Root != ImmedUse) { 2326 for (const SDValue &Op : Root->op_values()) { 2327 SDNode *N = Op.getNode(); 2328 // Ignore chains (they are validated by HandleMergeInputChains) 2329 if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def) 2330 continue; 2331 if (!Visited.insert(N).second) 2332 continue; 2333 WorkList.push_back(N); 2334 } 2335 } 2336 2337 return SDNode::hasPredecessorHelper(Def, Visited, WorkList, 0, true); 2338 } 2339 2340 /// IsProfitableToFold - Returns true if it's profitable to fold the specific 2341 /// operand node N of U during instruction selection that starts at Root. 2342 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U, 2343 SDNode *Root) const { 2344 if (OptLevel == CodeGenOpt::None) return false; 2345 return N.hasOneUse(); 2346 } 2347 2348 /// IsLegalToFold - Returns true if the specific operand node N of 2349 /// U can be folded during instruction selection that starts at Root. 2350 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root, 2351 CodeGenOpt::Level OptLevel, 2352 bool IgnoreChains) { 2353 if (OptLevel == CodeGenOpt::None) return false; 2354 2355 // If Root use can somehow reach N through a path that that doesn't contain 2356 // U then folding N would create a cycle. e.g. In the following 2357 // diagram, Root can reach N through X. If N is folded into Root, then 2358 // X is both a predecessor and a successor of U. 2359 // 2360 // [N*] // 2361 // ^ ^ // 2362 // / \ // 2363 // [U*] [X]? // 2364 // ^ ^ // 2365 // \ / // 2366 // \ / // 2367 // [Root*] // 2368 // 2369 // * indicates nodes to be folded together. 2370 // 2371 // If Root produces glue, then it gets (even more) interesting. Since it 2372 // will be "glued" together with its glue use in the scheduler, we need to 2373 // check if it might reach N. 2374 // 2375 // [N*] // 2376 // ^ ^ // 2377 // / \ // 2378 // [U*] [X]? // 2379 // ^ ^ // 2380 // \ \ // 2381 // \ | // 2382 // [Root*] | // 2383 // ^ | // 2384 // f | // 2385 // | / // 2386 // [Y] / // 2387 // ^ / // 2388 // f / // 2389 // | / // 2390 // [GU] // 2391 // 2392 // If GU (glue use) indirectly reaches N (the load), and Root folds N 2393 // (call it Fold), then X is a predecessor of GU and a successor of 2394 // Fold. But since Fold and GU are glued together, this will create 2395 // a cycle in the scheduling graph. 2396 2397 // If the node has glue, walk down the graph to the "lowest" node in the 2398 // glueged set. 2399 EVT VT = Root->getValueType(Root->getNumValues()-1); 2400 while (VT == MVT::Glue) { 2401 SDNode *GU = findGlueUse(Root); 2402 if (!GU) 2403 break; 2404 Root = GU; 2405 VT = Root->getValueType(Root->getNumValues()-1); 2406 2407 // If our query node has a glue result with a use, we've walked up it. If 2408 // the user (which has already been selected) has a chain or indirectly uses 2409 // the chain, HandleMergeInputChains will not consider it. Because of 2410 // this, we cannot ignore chains in this predicate. 2411 IgnoreChains = false; 2412 } 2413 2414 return !findNonImmUse(Root, N.getNode(), U, IgnoreChains); 2415 } 2416 2417 void SelectionDAGISel::Select_INLINEASM(SDNode *N) { 2418 SDLoc DL(N); 2419 2420 std::vector<SDValue> Ops(N->op_begin(), N->op_end()); 2421 SelectInlineAsmMemoryOperands(Ops, DL); 2422 2423 const EVT VTs[] = {MVT::Other, MVT::Glue}; 2424 SDValue New = CurDAG->getNode(ISD::INLINEASM, DL, VTs, Ops); 2425 New->setNodeId(-1); 2426 ReplaceUses(N, New.getNode()); 2427 CurDAG->RemoveDeadNode(N); 2428 } 2429 2430 void SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) { 2431 SDLoc dl(Op); 2432 MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1)); 2433 const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0)); 2434 unsigned Reg = 2435 TLI->getRegisterByName(RegStr->getString().data(), Op->getValueType(0), 2436 *CurDAG); 2437 SDValue New = CurDAG->getCopyFromReg( 2438 Op->getOperand(0), dl, Reg, Op->getValueType(0)); 2439 New->setNodeId(-1); 2440 ReplaceUses(Op, New.getNode()); 2441 CurDAG->RemoveDeadNode(Op); 2442 } 2443 2444 void SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) { 2445 SDLoc dl(Op); 2446 MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1)); 2447 const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0)); 2448 unsigned Reg = TLI->getRegisterByName(RegStr->getString().data(), 2449 Op->getOperand(2).getValueType(), 2450 *CurDAG); 2451 SDValue New = CurDAG->getCopyToReg( 2452 Op->getOperand(0), dl, Reg, Op->getOperand(2)); 2453 New->setNodeId(-1); 2454 ReplaceUses(Op, New.getNode()); 2455 CurDAG->RemoveDeadNode(Op); 2456 } 2457 2458 void SelectionDAGISel::Select_UNDEF(SDNode *N) { 2459 CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0)); 2460 } 2461 2462 /// GetVBR - decode a vbr encoding whose top bit is set. 2463 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline uint64_t 2464 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) { 2465 assert(Val >= 128 && "Not a VBR"); 2466 Val &= 127; // Remove first vbr bit. 2467 2468 unsigned Shift = 7; 2469 uint64_t NextBits; 2470 do { 2471 NextBits = MatcherTable[Idx++]; 2472 Val |= (NextBits&127) << Shift; 2473 Shift += 7; 2474 } while (NextBits & 128); 2475 2476 return Val; 2477 } 2478 2479 /// When a match is complete, this method updates uses of interior chain results 2480 /// to use the new results. 2481 void SelectionDAGISel::UpdateChains( 2482 SDNode *NodeToMatch, SDValue InputChain, 2483 SmallVectorImpl<SDNode *> &ChainNodesMatched, bool isMorphNodeTo) { 2484 SmallVector<SDNode*, 4> NowDeadNodes; 2485 2486 // Now that all the normal results are replaced, we replace the chain and 2487 // glue results if present. 2488 if (!ChainNodesMatched.empty()) { 2489 assert(InputChain.getNode() && 2490 "Matched input chains but didn't produce a chain"); 2491 // Loop over all of the nodes we matched that produced a chain result. 2492 // Replace all the chain results with the final chain we ended up with. 2493 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) { 2494 SDNode *ChainNode = ChainNodesMatched[i]; 2495 // If ChainNode is null, it's because we replaced it on a previous 2496 // iteration and we cleared it out of the map. Just skip it. 2497 if (!ChainNode) 2498 continue; 2499 2500 assert(ChainNode->getOpcode() != ISD::DELETED_NODE && 2501 "Deleted node left in chain"); 2502 2503 // Don't replace the results of the root node if we're doing a 2504 // MorphNodeTo. 2505 if (ChainNode == NodeToMatch && isMorphNodeTo) 2506 continue; 2507 2508 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1); 2509 if (ChainVal.getValueType() == MVT::Glue) 2510 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2); 2511 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?"); 2512 SelectionDAG::DAGNodeDeletedListener NDL( 2513 *CurDAG, [&](SDNode *N, SDNode *E) { 2514 std::replace(ChainNodesMatched.begin(), ChainNodesMatched.end(), N, 2515 static_cast<SDNode *>(nullptr)); 2516 }); 2517 if (ChainNode->getOpcode() != ISD::TokenFactor) 2518 ReplaceUses(ChainVal, InputChain); 2519 2520 // If the node became dead and we haven't already seen it, delete it. 2521 if (ChainNode != NodeToMatch && ChainNode->use_empty() && 2522 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode)) 2523 NowDeadNodes.push_back(ChainNode); 2524 } 2525 } 2526 2527 if (!NowDeadNodes.empty()) 2528 CurDAG->RemoveDeadNodes(NowDeadNodes); 2529 2530 LLVM_DEBUG(dbgs() << "ISEL: Match complete!\n"); 2531 } 2532 2533 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains 2534 /// operation for when the pattern matched at least one node with a chains. The 2535 /// input vector contains a list of all of the chained nodes that we match. We 2536 /// must determine if this is a valid thing to cover (i.e. matching it won't 2537 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will 2538 /// be used as the input node chain for the generated nodes. 2539 static SDValue 2540 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched, 2541 SelectionDAG *CurDAG) { 2542 2543 SmallPtrSet<const SDNode *, 16> Visited; 2544 SmallVector<const SDNode *, 8> Worklist; 2545 SmallVector<SDValue, 3> InputChains; 2546 unsigned int Max = 8192; 2547 2548 // Quick exit on trivial merge. 2549 if (ChainNodesMatched.size() == 1) 2550 return ChainNodesMatched[0]->getOperand(0); 2551 2552 // Add chains that aren't already added (internal). Peek through 2553 // token factors. 2554 std::function<void(const SDValue)> AddChains = [&](const SDValue V) { 2555 if (V.getValueType() != MVT::Other) 2556 return; 2557 if (V->getOpcode() == ISD::EntryToken) 2558 return; 2559 if (!Visited.insert(V.getNode()).second) 2560 return; 2561 if (V->getOpcode() == ISD::TokenFactor) { 2562 for (const SDValue &Op : V->op_values()) 2563 AddChains(Op); 2564 } else 2565 InputChains.push_back(V); 2566 }; 2567 2568 for (auto *N : ChainNodesMatched) { 2569 Worklist.push_back(N); 2570 Visited.insert(N); 2571 } 2572 2573 while (!Worklist.empty()) 2574 AddChains(Worklist.pop_back_val()->getOperand(0)); 2575 2576 // Skip the search if there are no chain dependencies. 2577 if (InputChains.size() == 0) 2578 return CurDAG->getEntryNode(); 2579 2580 // If one of these chains is a successor of input, we must have a 2581 // node that is both the predecessor and successor of the 2582 // to-be-merged nodes. Fail. 2583 Visited.clear(); 2584 for (SDValue V : InputChains) 2585 Worklist.push_back(V.getNode()); 2586 2587 for (auto *N : ChainNodesMatched) 2588 if (SDNode::hasPredecessorHelper(N, Visited, Worklist, Max, true)) 2589 return SDValue(); 2590 2591 // Return merged chain. 2592 if (InputChains.size() == 1) 2593 return InputChains[0]; 2594 return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]), 2595 MVT::Other, InputChains); 2596 } 2597 2598 /// MorphNode - Handle morphing a node in place for the selector. 2599 SDNode *SelectionDAGISel:: 2600 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList, 2601 ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) { 2602 // It is possible we're using MorphNodeTo to replace a node with no 2603 // normal results with one that has a normal result (or we could be 2604 // adding a chain) and the input could have glue and chains as well. 2605 // In this case we need to shift the operands down. 2606 // FIXME: This is a horrible hack and broken in obscure cases, no worse 2607 // than the old isel though. 2608 int OldGlueResultNo = -1, OldChainResultNo = -1; 2609 2610 unsigned NTMNumResults = Node->getNumValues(); 2611 if (Node->getValueType(NTMNumResults-1) == MVT::Glue) { 2612 OldGlueResultNo = NTMNumResults-1; 2613 if (NTMNumResults != 1 && 2614 Node->getValueType(NTMNumResults-2) == MVT::Other) 2615 OldChainResultNo = NTMNumResults-2; 2616 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other) 2617 OldChainResultNo = NTMNumResults-1; 2618 2619 // Call the underlying SelectionDAG routine to do the transmogrification. Note 2620 // that this deletes operands of the old node that become dead. 2621 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops); 2622 2623 // MorphNodeTo can operate in two ways: if an existing node with the 2624 // specified operands exists, it can just return it. Otherwise, it 2625 // updates the node in place to have the requested operands. 2626 if (Res == Node) { 2627 // If we updated the node in place, reset the node ID. To the isel, 2628 // this should be just like a newly allocated machine node. 2629 Res->setNodeId(-1); 2630 } 2631 2632 unsigned ResNumResults = Res->getNumValues(); 2633 // Move the glue if needed. 2634 if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 && 2635 (unsigned)OldGlueResultNo != ResNumResults-1) 2636 ReplaceUses(SDValue(Node, OldGlueResultNo), 2637 SDValue(Res, ResNumResults - 1)); 2638 2639 if ((EmitNodeInfo & OPFL_GlueOutput) != 0) 2640 --ResNumResults; 2641 2642 // Move the chain reference if needed. 2643 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 && 2644 (unsigned)OldChainResultNo != ResNumResults-1) 2645 ReplaceUses(SDValue(Node, OldChainResultNo), 2646 SDValue(Res, ResNumResults - 1)); 2647 2648 // Otherwise, no replacement happened because the node already exists. Replace 2649 // Uses of the old node with the new one. 2650 if (Res != Node) { 2651 ReplaceNode(Node, Res); 2652 } else { 2653 EnforceNodeIdInvariant(Res); 2654 } 2655 2656 return Res; 2657 } 2658 2659 /// CheckSame - Implements OP_CheckSame. 2660 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2661 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2662 SDValue N, 2663 const SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) { 2664 // Accept if it is exactly the same as a previously recorded node. 2665 unsigned RecNo = MatcherTable[MatcherIndex++]; 2666 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame"); 2667 return N == RecordedNodes[RecNo].first; 2668 } 2669 2670 /// CheckChildSame - Implements OP_CheckChildXSame. 2671 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2672 CheckChildSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2673 SDValue N, 2674 const SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes, 2675 unsigned ChildNo) { 2676 if (ChildNo >= N.getNumOperands()) 2677 return false; // Match fails if out of range child #. 2678 return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo), 2679 RecordedNodes); 2680 } 2681 2682 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate. 2683 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2684 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2685 const SelectionDAGISel &SDISel) { 2686 return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]); 2687 } 2688 2689 /// CheckNodePredicate - Implements OP_CheckNodePredicate. 2690 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2691 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2692 const SelectionDAGISel &SDISel, SDNode *N) { 2693 return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]); 2694 } 2695 2696 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2697 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2698 SDNode *N) { 2699 uint16_t Opc = MatcherTable[MatcherIndex++]; 2700 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8; 2701 return N->getOpcode() == Opc; 2702 } 2703 2704 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2705 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, 2706 const TargetLowering *TLI, const DataLayout &DL) { 2707 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 2708 if (N.getValueType() == VT) return true; 2709 2710 // Handle the case when VT is iPTR. 2711 return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL); 2712 } 2713 2714 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2715 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2716 SDValue N, const TargetLowering *TLI, const DataLayout &DL, 2717 unsigned ChildNo) { 2718 if (ChildNo >= N.getNumOperands()) 2719 return false; // Match fails if out of range child #. 2720 return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI, 2721 DL); 2722 } 2723 2724 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2725 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2726 SDValue N) { 2727 return cast<CondCodeSDNode>(N)->get() == 2728 (ISD::CondCode)MatcherTable[MatcherIndex++]; 2729 } 2730 2731 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2732 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2733 SDValue N, const TargetLowering *TLI, const DataLayout &DL) { 2734 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 2735 if (cast<VTSDNode>(N)->getVT() == VT) 2736 return true; 2737 2738 // Handle the case when VT is iPTR. 2739 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL); 2740 } 2741 2742 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2743 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2744 SDValue N) { 2745 int64_t Val = MatcherTable[MatcherIndex++]; 2746 if (Val & 128) 2747 Val = GetVBR(Val, MatcherTable, MatcherIndex); 2748 2749 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N); 2750 return C && C->getSExtValue() == Val; 2751 } 2752 2753 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2754 CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2755 SDValue N, unsigned ChildNo) { 2756 if (ChildNo >= N.getNumOperands()) 2757 return false; // Match fails if out of range child #. 2758 return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo)); 2759 } 2760 2761 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2762 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2763 SDValue N, const SelectionDAGISel &SDISel) { 2764 int64_t Val = MatcherTable[MatcherIndex++]; 2765 if (Val & 128) 2766 Val = GetVBR(Val, MatcherTable, MatcherIndex); 2767 2768 if (N->getOpcode() != ISD::AND) return false; 2769 2770 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 2771 return C && SDISel.CheckAndMask(N.getOperand(0), C, Val); 2772 } 2773 2774 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2775 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2776 SDValue N, const SelectionDAGISel &SDISel) { 2777 int64_t Val = MatcherTable[MatcherIndex++]; 2778 if (Val & 128) 2779 Val = GetVBR(Val, MatcherTable, MatcherIndex); 2780 2781 if (N->getOpcode() != ISD::OR) return false; 2782 2783 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 2784 return C && SDISel.CheckOrMask(N.getOperand(0), C, Val); 2785 } 2786 2787 /// IsPredicateKnownToFail - If we know how and can do so without pushing a 2788 /// scope, evaluate the current node. If the current predicate is known to 2789 /// fail, set Result=true and return anything. If the current predicate is 2790 /// known to pass, set Result=false and return the MatcherIndex to continue 2791 /// with. If the current predicate is unknown, set Result=false and return the 2792 /// MatcherIndex to continue with. 2793 static unsigned IsPredicateKnownToFail(const unsigned char *Table, 2794 unsigned Index, SDValue N, 2795 bool &Result, 2796 const SelectionDAGISel &SDISel, 2797 SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) { 2798 switch (Table[Index++]) { 2799 default: 2800 Result = false; 2801 return Index-1; // Could not evaluate this predicate. 2802 case SelectionDAGISel::OPC_CheckSame: 2803 Result = !::CheckSame(Table, Index, N, RecordedNodes); 2804 return Index; 2805 case SelectionDAGISel::OPC_CheckChild0Same: 2806 case SelectionDAGISel::OPC_CheckChild1Same: 2807 case SelectionDAGISel::OPC_CheckChild2Same: 2808 case SelectionDAGISel::OPC_CheckChild3Same: 2809 Result = !::CheckChildSame(Table, Index, N, RecordedNodes, 2810 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Same); 2811 return Index; 2812 case SelectionDAGISel::OPC_CheckPatternPredicate: 2813 Result = !::CheckPatternPredicate(Table, Index, SDISel); 2814 return Index; 2815 case SelectionDAGISel::OPC_CheckPredicate: 2816 Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode()); 2817 return Index; 2818 case SelectionDAGISel::OPC_CheckOpcode: 2819 Result = !::CheckOpcode(Table, Index, N.getNode()); 2820 return Index; 2821 case SelectionDAGISel::OPC_CheckType: 2822 Result = !::CheckType(Table, Index, N, SDISel.TLI, 2823 SDISel.CurDAG->getDataLayout()); 2824 return Index; 2825 case SelectionDAGISel::OPC_CheckTypeRes: { 2826 unsigned Res = Table[Index++]; 2827 Result = !::CheckType(Table, Index, N.getValue(Res), SDISel.TLI, 2828 SDISel.CurDAG->getDataLayout()); 2829 return Index; 2830 } 2831 case SelectionDAGISel::OPC_CheckChild0Type: 2832 case SelectionDAGISel::OPC_CheckChild1Type: 2833 case SelectionDAGISel::OPC_CheckChild2Type: 2834 case SelectionDAGISel::OPC_CheckChild3Type: 2835 case SelectionDAGISel::OPC_CheckChild4Type: 2836 case SelectionDAGISel::OPC_CheckChild5Type: 2837 case SelectionDAGISel::OPC_CheckChild6Type: 2838 case SelectionDAGISel::OPC_CheckChild7Type: 2839 Result = !::CheckChildType( 2840 Table, Index, N, SDISel.TLI, SDISel.CurDAG->getDataLayout(), 2841 Table[Index - 1] - SelectionDAGISel::OPC_CheckChild0Type); 2842 return Index; 2843 case SelectionDAGISel::OPC_CheckCondCode: 2844 Result = !::CheckCondCode(Table, Index, N); 2845 return Index; 2846 case SelectionDAGISel::OPC_CheckValueType: 2847 Result = !::CheckValueType(Table, Index, N, SDISel.TLI, 2848 SDISel.CurDAG->getDataLayout()); 2849 return Index; 2850 case SelectionDAGISel::OPC_CheckInteger: 2851 Result = !::CheckInteger(Table, Index, N); 2852 return Index; 2853 case SelectionDAGISel::OPC_CheckChild0Integer: 2854 case SelectionDAGISel::OPC_CheckChild1Integer: 2855 case SelectionDAGISel::OPC_CheckChild2Integer: 2856 case SelectionDAGISel::OPC_CheckChild3Integer: 2857 case SelectionDAGISel::OPC_CheckChild4Integer: 2858 Result = !::CheckChildInteger(Table, Index, N, 2859 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Integer); 2860 return Index; 2861 case SelectionDAGISel::OPC_CheckAndImm: 2862 Result = !::CheckAndImm(Table, Index, N, SDISel); 2863 return Index; 2864 case SelectionDAGISel::OPC_CheckOrImm: 2865 Result = !::CheckOrImm(Table, Index, N, SDISel); 2866 return Index; 2867 } 2868 } 2869 2870 namespace { 2871 2872 struct MatchScope { 2873 /// FailIndex - If this match fails, this is the index to continue with. 2874 unsigned FailIndex; 2875 2876 /// NodeStack - The node stack when the scope was formed. 2877 SmallVector<SDValue, 4> NodeStack; 2878 2879 /// NumRecordedNodes - The number of recorded nodes when the scope was formed. 2880 unsigned NumRecordedNodes; 2881 2882 /// NumMatchedMemRefs - The number of matched memref entries. 2883 unsigned NumMatchedMemRefs; 2884 2885 /// InputChain/InputGlue - The current chain/glue 2886 SDValue InputChain, InputGlue; 2887 2888 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty. 2889 bool HasChainNodesMatched; 2890 }; 2891 2892 /// \A DAG update listener to keep the matching state 2893 /// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to 2894 /// change the DAG while matching. X86 addressing mode matcher is an example 2895 /// for this. 2896 class MatchStateUpdater : public SelectionDAG::DAGUpdateListener 2897 { 2898 SDNode **NodeToMatch; 2899 SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes; 2900 SmallVectorImpl<MatchScope> &MatchScopes; 2901 2902 public: 2903 MatchStateUpdater(SelectionDAG &DAG, SDNode **NodeToMatch, 2904 SmallVectorImpl<std::pair<SDValue, SDNode *>> &RN, 2905 SmallVectorImpl<MatchScope> &MS) 2906 : SelectionDAG::DAGUpdateListener(DAG), NodeToMatch(NodeToMatch), 2907 RecordedNodes(RN), MatchScopes(MS) {} 2908 2909 void NodeDeleted(SDNode *N, SDNode *E) override { 2910 // Some early-returns here to avoid the search if we deleted the node or 2911 // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we 2912 // do, so it's unnecessary to update matching state at that point). 2913 // Neither of these can occur currently because we only install this 2914 // update listener during matching a complex patterns. 2915 if (!E || E->isMachineOpcode()) 2916 return; 2917 // Check if NodeToMatch was updated. 2918 if (N == *NodeToMatch) 2919 *NodeToMatch = E; 2920 // Performing linear search here does not matter because we almost never 2921 // run this code. You'd have to have a CSE during complex pattern 2922 // matching. 2923 for (auto &I : RecordedNodes) 2924 if (I.first.getNode() == N) 2925 I.first.setNode(E); 2926 2927 for (auto &I : MatchScopes) 2928 for (auto &J : I.NodeStack) 2929 if (J.getNode() == N) 2930 J.setNode(E); 2931 } 2932 }; 2933 2934 } // end anonymous namespace 2935 2936 void SelectionDAGISel::SelectCodeCommon(SDNode *NodeToMatch, 2937 const unsigned char *MatcherTable, 2938 unsigned TableSize) { 2939 // FIXME: Should these even be selected? Handle these cases in the caller? 2940 switch (NodeToMatch->getOpcode()) { 2941 default: 2942 break; 2943 case ISD::EntryToken: // These nodes remain the same. 2944 case ISD::BasicBlock: 2945 case ISD::Register: 2946 case ISD::RegisterMask: 2947 case ISD::HANDLENODE: 2948 case ISD::MDNODE_SDNODE: 2949 case ISD::TargetConstant: 2950 case ISD::TargetConstantFP: 2951 case ISD::TargetConstantPool: 2952 case ISD::TargetFrameIndex: 2953 case ISD::TargetExternalSymbol: 2954 case ISD::MCSymbol: 2955 case ISD::TargetBlockAddress: 2956 case ISD::TargetJumpTable: 2957 case ISD::TargetGlobalTLSAddress: 2958 case ISD::TargetGlobalAddress: 2959 case ISD::TokenFactor: 2960 case ISD::CopyFromReg: 2961 case ISD::CopyToReg: 2962 case ISD::EH_LABEL: 2963 case ISD::ANNOTATION_LABEL: 2964 case ISD::LIFETIME_START: 2965 case ISD::LIFETIME_END: 2966 NodeToMatch->setNodeId(-1); // Mark selected. 2967 return; 2968 case ISD::AssertSext: 2969 case ISD::AssertZext: 2970 ReplaceUses(SDValue(NodeToMatch, 0), NodeToMatch->getOperand(0)); 2971 CurDAG->RemoveDeadNode(NodeToMatch); 2972 return; 2973 case ISD::INLINEASM: 2974 Select_INLINEASM(NodeToMatch); 2975 return; 2976 case ISD::READ_REGISTER: 2977 Select_READ_REGISTER(NodeToMatch); 2978 return; 2979 case ISD::WRITE_REGISTER: 2980 Select_WRITE_REGISTER(NodeToMatch); 2981 return; 2982 case ISD::UNDEF: 2983 Select_UNDEF(NodeToMatch); 2984 return; 2985 } 2986 2987 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!"); 2988 2989 // Set up the node stack with NodeToMatch as the only node on the stack. 2990 SmallVector<SDValue, 8> NodeStack; 2991 SDValue N = SDValue(NodeToMatch, 0); 2992 NodeStack.push_back(N); 2993 2994 // MatchScopes - Scopes used when matching, if a match failure happens, this 2995 // indicates where to continue checking. 2996 SmallVector<MatchScope, 8> MatchScopes; 2997 2998 // RecordedNodes - This is the set of nodes that have been recorded by the 2999 // state machine. The second value is the parent of the node, or null if the 3000 // root is recorded. 3001 SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes; 3002 3003 // MatchedMemRefs - This is the set of MemRef's we've seen in the input 3004 // pattern. 3005 SmallVector<MachineMemOperand*, 2> MatchedMemRefs; 3006 3007 // These are the current input chain and glue for use when generating nodes. 3008 // Various Emit operations change these. For example, emitting a copytoreg 3009 // uses and updates these. 3010 SDValue InputChain, InputGlue; 3011 3012 // ChainNodesMatched - If a pattern matches nodes that have input/output 3013 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates 3014 // which ones they are. The result is captured into this list so that we can 3015 // update the chain results when the pattern is complete. 3016 SmallVector<SDNode*, 3> ChainNodesMatched; 3017 3018 LLVM_DEBUG(dbgs() << "ISEL: Starting pattern match\n"); 3019 3020 // Determine where to start the interpreter. Normally we start at opcode #0, 3021 // but if the state machine starts with an OPC_SwitchOpcode, then we 3022 // accelerate the first lookup (which is guaranteed to be hot) with the 3023 // OpcodeOffset table. 3024 unsigned MatcherIndex = 0; 3025 3026 if (!OpcodeOffset.empty()) { 3027 // Already computed the OpcodeOffset table, just index into it. 3028 if (N.getOpcode() < OpcodeOffset.size()) 3029 MatcherIndex = OpcodeOffset[N.getOpcode()]; 3030 LLVM_DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n"); 3031 3032 } else if (MatcherTable[0] == OPC_SwitchOpcode) { 3033 // Otherwise, the table isn't computed, but the state machine does start 3034 // with an OPC_SwitchOpcode instruction. Populate the table now, since this 3035 // is the first time we're selecting an instruction. 3036 unsigned Idx = 1; 3037 while (true) { 3038 // Get the size of this case. 3039 unsigned CaseSize = MatcherTable[Idx++]; 3040 if (CaseSize & 128) 3041 CaseSize = GetVBR(CaseSize, MatcherTable, Idx); 3042 if (CaseSize == 0) break; 3043 3044 // Get the opcode, add the index to the table. 3045 uint16_t Opc = MatcherTable[Idx++]; 3046 Opc |= (unsigned short)MatcherTable[Idx++] << 8; 3047 if (Opc >= OpcodeOffset.size()) 3048 OpcodeOffset.resize((Opc+1)*2); 3049 OpcodeOffset[Opc] = Idx; 3050 Idx += CaseSize; 3051 } 3052 3053 // Okay, do the lookup for the first opcode. 3054 if (N.getOpcode() < OpcodeOffset.size()) 3055 MatcherIndex = OpcodeOffset[N.getOpcode()]; 3056 } 3057 3058 while (true) { 3059 assert(MatcherIndex < TableSize && "Invalid index"); 3060 #ifndef NDEBUG 3061 unsigned CurrentOpcodeIndex = MatcherIndex; 3062 #endif 3063 BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++]; 3064 switch (Opcode) { 3065 case OPC_Scope: { 3066 // Okay, the semantics of this operation are that we should push a scope 3067 // then evaluate the first child. However, pushing a scope only to have 3068 // the first check fail (which then pops it) is inefficient. If we can 3069 // determine immediately that the first check (or first several) will 3070 // immediately fail, don't even bother pushing a scope for them. 3071 unsigned FailIndex; 3072 3073 while (true) { 3074 unsigned NumToSkip = MatcherTable[MatcherIndex++]; 3075 if (NumToSkip & 128) 3076 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex); 3077 // Found the end of the scope with no match. 3078 if (NumToSkip == 0) { 3079 FailIndex = 0; 3080 break; 3081 } 3082 3083 FailIndex = MatcherIndex+NumToSkip; 3084 3085 unsigned MatcherIndexOfPredicate = MatcherIndex; 3086 (void)MatcherIndexOfPredicate; // silence warning. 3087 3088 // If we can't evaluate this predicate without pushing a scope (e.g. if 3089 // it is a 'MoveParent') or if the predicate succeeds on this node, we 3090 // push the scope and evaluate the full predicate chain. 3091 bool Result; 3092 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N, 3093 Result, *this, RecordedNodes); 3094 if (!Result) 3095 break; 3096 3097 LLVM_DEBUG( 3098 dbgs() << " Skipped scope entry (due to false predicate) at " 3099 << "index " << MatcherIndexOfPredicate << ", continuing at " 3100 << FailIndex << "\n"); 3101 ++NumDAGIselRetries; 3102 3103 // Otherwise, we know that this case of the Scope is guaranteed to fail, 3104 // move to the next case. 3105 MatcherIndex = FailIndex; 3106 } 3107 3108 // If the whole scope failed to match, bail. 3109 if (FailIndex == 0) break; 3110 3111 // Push a MatchScope which indicates where to go if the first child fails 3112 // to match. 3113 MatchScope NewEntry; 3114 NewEntry.FailIndex = FailIndex; 3115 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end()); 3116 NewEntry.NumRecordedNodes = RecordedNodes.size(); 3117 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size(); 3118 NewEntry.InputChain = InputChain; 3119 NewEntry.InputGlue = InputGlue; 3120 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty(); 3121 MatchScopes.push_back(NewEntry); 3122 continue; 3123 } 3124 case OPC_RecordNode: { 3125 // Remember this node, it may end up being an operand in the pattern. 3126 SDNode *Parent = nullptr; 3127 if (NodeStack.size() > 1) 3128 Parent = NodeStack[NodeStack.size()-2].getNode(); 3129 RecordedNodes.push_back(std::make_pair(N, Parent)); 3130 continue; 3131 } 3132 3133 case OPC_RecordChild0: case OPC_RecordChild1: 3134 case OPC_RecordChild2: case OPC_RecordChild3: 3135 case OPC_RecordChild4: case OPC_RecordChild5: 3136 case OPC_RecordChild6: case OPC_RecordChild7: { 3137 unsigned ChildNo = Opcode-OPC_RecordChild0; 3138 if (ChildNo >= N.getNumOperands()) 3139 break; // Match fails if out of range child #. 3140 3141 RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo), 3142 N.getNode())); 3143 continue; 3144 } 3145 case OPC_RecordMemRef: 3146 if (auto *MN = dyn_cast<MemSDNode>(N)) 3147 MatchedMemRefs.push_back(MN->getMemOperand()); 3148 else { 3149 LLVM_DEBUG(dbgs() << "Expected MemSDNode "; N->dump(CurDAG); 3150 dbgs() << '\n'); 3151 } 3152 3153 continue; 3154 3155 case OPC_CaptureGlueInput: 3156 // If the current node has an input glue, capture it in InputGlue. 3157 if (N->getNumOperands() != 0 && 3158 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) 3159 InputGlue = N->getOperand(N->getNumOperands()-1); 3160 continue; 3161 3162 case OPC_MoveChild: { 3163 unsigned ChildNo = MatcherTable[MatcherIndex++]; 3164 if (ChildNo >= N.getNumOperands()) 3165 break; // Match fails if out of range child #. 3166 N = N.getOperand(ChildNo); 3167 NodeStack.push_back(N); 3168 continue; 3169 } 3170 3171 case OPC_MoveChild0: case OPC_MoveChild1: 3172 case OPC_MoveChild2: case OPC_MoveChild3: 3173 case OPC_MoveChild4: case OPC_MoveChild5: 3174 case OPC_MoveChild6: case OPC_MoveChild7: { 3175 unsigned ChildNo = Opcode-OPC_MoveChild0; 3176 if (ChildNo >= N.getNumOperands()) 3177 break; // Match fails if out of range child #. 3178 N = N.getOperand(ChildNo); 3179 NodeStack.push_back(N); 3180 continue; 3181 } 3182 3183 case OPC_MoveParent: 3184 // Pop the current node off the NodeStack. 3185 NodeStack.pop_back(); 3186 assert(!NodeStack.empty() && "Node stack imbalance!"); 3187 N = NodeStack.back(); 3188 continue; 3189 3190 case OPC_CheckSame: 3191 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break; 3192 continue; 3193 3194 case OPC_CheckChild0Same: case OPC_CheckChild1Same: 3195 case OPC_CheckChild2Same: case OPC_CheckChild3Same: 3196 if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes, 3197 Opcode-OPC_CheckChild0Same)) 3198 break; 3199 continue; 3200 3201 case OPC_CheckPatternPredicate: 3202 if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break; 3203 continue; 3204 case OPC_CheckPredicate: 3205 if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this, 3206 N.getNode())) 3207 break; 3208 continue; 3209 case OPC_CheckComplexPat: { 3210 unsigned CPNum = MatcherTable[MatcherIndex++]; 3211 unsigned RecNo = MatcherTable[MatcherIndex++]; 3212 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat"); 3213 3214 // If target can modify DAG during matching, keep the matching state 3215 // consistent. 3216 std::unique_ptr<MatchStateUpdater> MSU; 3217 if (ComplexPatternFuncMutatesDAG()) 3218 MSU.reset(new MatchStateUpdater(*CurDAG, &NodeToMatch, RecordedNodes, 3219 MatchScopes)); 3220 3221 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second, 3222 RecordedNodes[RecNo].first, CPNum, 3223 RecordedNodes)) 3224 break; 3225 continue; 3226 } 3227 case OPC_CheckOpcode: 3228 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break; 3229 continue; 3230 3231 case OPC_CheckType: 3232 if (!::CheckType(MatcherTable, MatcherIndex, N, TLI, 3233 CurDAG->getDataLayout())) 3234 break; 3235 continue; 3236 3237 case OPC_CheckTypeRes: { 3238 unsigned Res = MatcherTable[MatcherIndex++]; 3239 if (!::CheckType(MatcherTable, MatcherIndex, N.getValue(Res), TLI, 3240 CurDAG->getDataLayout())) 3241 break; 3242 continue; 3243 } 3244 3245 case OPC_SwitchOpcode: { 3246 unsigned CurNodeOpcode = N.getOpcode(); 3247 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart; 3248 unsigned CaseSize; 3249 while (true) { 3250 // Get the size of this case. 3251 CaseSize = MatcherTable[MatcherIndex++]; 3252 if (CaseSize & 128) 3253 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex); 3254 if (CaseSize == 0) break; 3255 3256 uint16_t Opc = MatcherTable[MatcherIndex++]; 3257 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8; 3258 3259 // If the opcode matches, then we will execute this case. 3260 if (CurNodeOpcode == Opc) 3261 break; 3262 3263 // Otherwise, skip over this case. 3264 MatcherIndex += CaseSize; 3265 } 3266 3267 // If no cases matched, bail out. 3268 if (CaseSize == 0) break; 3269 3270 // Otherwise, execute the case we found. 3271 LLVM_DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart << " to " 3272 << MatcherIndex << "\n"); 3273 continue; 3274 } 3275 3276 case OPC_SwitchType: { 3277 MVT CurNodeVT = N.getSimpleValueType(); 3278 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart; 3279 unsigned CaseSize; 3280 while (true) { 3281 // Get the size of this case. 3282 CaseSize = MatcherTable[MatcherIndex++]; 3283 if (CaseSize & 128) 3284 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex); 3285 if (CaseSize == 0) break; 3286 3287 MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 3288 if (CaseVT == MVT::iPTR) 3289 CaseVT = TLI->getPointerTy(CurDAG->getDataLayout()); 3290 3291 // If the VT matches, then we will execute this case. 3292 if (CurNodeVT == CaseVT) 3293 break; 3294 3295 // Otherwise, skip over this case. 3296 MatcherIndex += CaseSize; 3297 } 3298 3299 // If no cases matched, bail out. 3300 if (CaseSize == 0) break; 3301 3302 // Otherwise, execute the case we found. 3303 LLVM_DEBUG(dbgs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString() 3304 << "] from " << SwitchStart << " to " << MatcherIndex 3305 << '\n'); 3306 continue; 3307 } 3308 case OPC_CheckChild0Type: case OPC_CheckChild1Type: 3309 case OPC_CheckChild2Type: case OPC_CheckChild3Type: 3310 case OPC_CheckChild4Type: case OPC_CheckChild5Type: 3311 case OPC_CheckChild6Type: case OPC_CheckChild7Type: 3312 if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI, 3313 CurDAG->getDataLayout(), 3314 Opcode - OPC_CheckChild0Type)) 3315 break; 3316 continue; 3317 case OPC_CheckCondCode: 3318 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break; 3319 continue; 3320 case OPC_CheckValueType: 3321 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI, 3322 CurDAG->getDataLayout())) 3323 break; 3324 continue; 3325 case OPC_CheckInteger: 3326 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break; 3327 continue; 3328 case OPC_CheckChild0Integer: case OPC_CheckChild1Integer: 3329 case OPC_CheckChild2Integer: case OPC_CheckChild3Integer: 3330 case OPC_CheckChild4Integer: 3331 if (!::CheckChildInteger(MatcherTable, MatcherIndex, N, 3332 Opcode-OPC_CheckChild0Integer)) break; 3333 continue; 3334 case OPC_CheckAndImm: 3335 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break; 3336 continue; 3337 case OPC_CheckOrImm: 3338 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break; 3339 continue; 3340 3341 case OPC_CheckFoldableChainNode: { 3342 assert(NodeStack.size() != 1 && "No parent node"); 3343 // Verify that all intermediate nodes between the root and this one have 3344 // a single use. 3345 bool HasMultipleUses = false; 3346 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i) 3347 if (!NodeStack[i].getNode()->hasOneUse()) { 3348 HasMultipleUses = true; 3349 break; 3350 } 3351 if (HasMultipleUses) break; 3352 3353 // Check to see that the target thinks this is profitable to fold and that 3354 // we can fold it without inducing cycles in the graph. 3355 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(), 3356 NodeToMatch) || 3357 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(), 3358 NodeToMatch, OptLevel, 3359 true/*We validate our own chains*/)) 3360 break; 3361 3362 continue; 3363 } 3364 case OPC_EmitInteger: { 3365 MVT::SimpleValueType VT = 3366 (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 3367 int64_t Val = MatcherTable[MatcherIndex++]; 3368 if (Val & 128) 3369 Val = GetVBR(Val, MatcherTable, MatcherIndex); 3370 RecordedNodes.push_back(std::pair<SDValue, SDNode*>( 3371 CurDAG->getTargetConstant(Val, SDLoc(NodeToMatch), 3372 VT), nullptr)); 3373 continue; 3374 } 3375 case OPC_EmitRegister: { 3376 MVT::SimpleValueType VT = 3377 (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 3378 unsigned RegNo = MatcherTable[MatcherIndex++]; 3379 RecordedNodes.push_back(std::pair<SDValue, SDNode*>( 3380 CurDAG->getRegister(RegNo, VT), nullptr)); 3381 continue; 3382 } 3383 case OPC_EmitRegister2: { 3384 // For targets w/ more than 256 register names, the register enum 3385 // values are stored in two bytes in the matcher table (just like 3386 // opcodes). 3387 MVT::SimpleValueType VT = 3388 (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 3389 unsigned RegNo = MatcherTable[MatcherIndex++]; 3390 RegNo |= MatcherTable[MatcherIndex++] << 8; 3391 RecordedNodes.push_back(std::pair<SDValue, SDNode*>( 3392 CurDAG->getRegister(RegNo, VT), nullptr)); 3393 continue; 3394 } 3395 3396 case OPC_EmitConvertToTarget: { 3397 // Convert from IMM/FPIMM to target version. 3398 unsigned RecNo = MatcherTable[MatcherIndex++]; 3399 assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget"); 3400 SDValue Imm = RecordedNodes[RecNo].first; 3401 3402 if (Imm->getOpcode() == ISD::Constant) { 3403 const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue(); 3404 Imm = CurDAG->getTargetConstant(*Val, SDLoc(NodeToMatch), 3405 Imm.getValueType()); 3406 } else if (Imm->getOpcode() == ISD::ConstantFP) { 3407 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue(); 3408 Imm = CurDAG->getTargetConstantFP(*Val, SDLoc(NodeToMatch), 3409 Imm.getValueType()); 3410 } 3411 3412 RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second)); 3413 continue; 3414 } 3415 3416 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0 3417 case OPC_EmitMergeInputChains1_1: // OPC_EmitMergeInputChains, 1, 1 3418 case OPC_EmitMergeInputChains1_2: { // OPC_EmitMergeInputChains, 1, 2 3419 // These are space-optimized forms of OPC_EmitMergeInputChains. 3420 assert(!InputChain.getNode() && 3421 "EmitMergeInputChains should be the first chain producing node"); 3422 assert(ChainNodesMatched.empty() && 3423 "Should only have one EmitMergeInputChains per match"); 3424 3425 // Read all of the chained nodes. 3426 unsigned RecNo = Opcode - OPC_EmitMergeInputChains1_0; 3427 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains"); 3428 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode()); 3429 3430 // FIXME: What if other value results of the node have uses not matched 3431 // by this pattern? 3432 if (ChainNodesMatched.back() != NodeToMatch && 3433 !RecordedNodes[RecNo].first.hasOneUse()) { 3434 ChainNodesMatched.clear(); 3435 break; 3436 } 3437 3438 // Merge the input chains if they are not intra-pattern references. 3439 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG); 3440 3441 if (!InputChain.getNode()) 3442 break; // Failed to merge. 3443 continue; 3444 } 3445 3446 case OPC_EmitMergeInputChains: { 3447 assert(!InputChain.getNode() && 3448 "EmitMergeInputChains should be the first chain producing node"); 3449 // This node gets a list of nodes we matched in the input that have 3450 // chains. We want to token factor all of the input chains to these nodes 3451 // together. However, if any of the input chains is actually one of the 3452 // nodes matched in this pattern, then we have an intra-match reference. 3453 // Ignore these because the newly token factored chain should not refer to 3454 // the old nodes. 3455 unsigned NumChains = MatcherTable[MatcherIndex++]; 3456 assert(NumChains != 0 && "Can't TF zero chains"); 3457 3458 assert(ChainNodesMatched.empty() && 3459 "Should only have one EmitMergeInputChains per match"); 3460 3461 // Read all of the chained nodes. 3462 for (unsigned i = 0; i != NumChains; ++i) { 3463 unsigned RecNo = MatcherTable[MatcherIndex++]; 3464 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains"); 3465 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode()); 3466 3467 // FIXME: What if other value results of the node have uses not matched 3468 // by this pattern? 3469 if (ChainNodesMatched.back() != NodeToMatch && 3470 !RecordedNodes[RecNo].first.hasOneUse()) { 3471 ChainNodesMatched.clear(); 3472 break; 3473 } 3474 } 3475 3476 // If the inner loop broke out, the match fails. 3477 if (ChainNodesMatched.empty()) 3478 break; 3479 3480 // Merge the input chains if they are not intra-pattern references. 3481 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG); 3482 3483 if (!InputChain.getNode()) 3484 break; // Failed to merge. 3485 3486 continue; 3487 } 3488 3489 case OPC_EmitCopyToReg: { 3490 unsigned RecNo = MatcherTable[MatcherIndex++]; 3491 assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg"); 3492 unsigned DestPhysReg = MatcherTable[MatcherIndex++]; 3493 3494 if (!InputChain.getNode()) 3495 InputChain = CurDAG->getEntryNode(); 3496 3497 InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch), 3498 DestPhysReg, RecordedNodes[RecNo].first, 3499 InputGlue); 3500 3501 InputGlue = InputChain.getValue(1); 3502 continue; 3503 } 3504 3505 case OPC_EmitNodeXForm: { 3506 unsigned XFormNo = MatcherTable[MatcherIndex++]; 3507 unsigned RecNo = MatcherTable[MatcherIndex++]; 3508 assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm"); 3509 SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo); 3510 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr)); 3511 continue; 3512 } 3513 case OPC_Coverage: { 3514 // This is emitted right before MorphNode/EmitNode. 3515 // So it should be safe to assume that this node has been selected 3516 unsigned index = MatcherTable[MatcherIndex++]; 3517 index |= (MatcherTable[MatcherIndex++] << 8); 3518 dbgs() << "COVERED: " << getPatternForIndex(index) << "\n"; 3519 dbgs() << "INCLUDED: " << getIncludePathForIndex(index) << "\n"; 3520 continue; 3521 } 3522 3523 case OPC_EmitNode: case OPC_MorphNodeTo: 3524 case OPC_EmitNode0: case OPC_EmitNode1: case OPC_EmitNode2: 3525 case OPC_MorphNodeTo0: case OPC_MorphNodeTo1: case OPC_MorphNodeTo2: { 3526 uint16_t TargetOpc = MatcherTable[MatcherIndex++]; 3527 TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8; 3528 unsigned EmitNodeInfo = MatcherTable[MatcherIndex++]; 3529 // Get the result VT list. 3530 unsigned NumVTs; 3531 // If this is one of the compressed forms, get the number of VTs based 3532 // on the Opcode. Otherwise read the next byte from the table. 3533 if (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2) 3534 NumVTs = Opcode - OPC_MorphNodeTo0; 3535 else if (Opcode >= OPC_EmitNode0 && Opcode <= OPC_EmitNode2) 3536 NumVTs = Opcode - OPC_EmitNode0; 3537 else 3538 NumVTs = MatcherTable[MatcherIndex++]; 3539 SmallVector<EVT, 4> VTs; 3540 for (unsigned i = 0; i != NumVTs; ++i) { 3541 MVT::SimpleValueType VT = 3542 (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 3543 if (VT == MVT::iPTR) 3544 VT = TLI->getPointerTy(CurDAG->getDataLayout()).SimpleTy; 3545 VTs.push_back(VT); 3546 } 3547 3548 if (EmitNodeInfo & OPFL_Chain) 3549 VTs.push_back(MVT::Other); 3550 if (EmitNodeInfo & OPFL_GlueOutput) 3551 VTs.push_back(MVT::Glue); 3552 3553 // This is hot code, so optimize the two most common cases of 1 and 2 3554 // results. 3555 SDVTList VTList; 3556 if (VTs.size() == 1) 3557 VTList = CurDAG->getVTList(VTs[0]); 3558 else if (VTs.size() == 2) 3559 VTList = CurDAG->getVTList(VTs[0], VTs[1]); 3560 else 3561 VTList = CurDAG->getVTList(VTs); 3562 3563 // Get the operand list. 3564 unsigned NumOps = MatcherTable[MatcherIndex++]; 3565 SmallVector<SDValue, 8> Ops; 3566 for (unsigned i = 0; i != NumOps; ++i) { 3567 unsigned RecNo = MatcherTable[MatcherIndex++]; 3568 if (RecNo & 128) 3569 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex); 3570 3571 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode"); 3572 Ops.push_back(RecordedNodes[RecNo].first); 3573 } 3574 3575 // If there are variadic operands to add, handle them now. 3576 if (EmitNodeInfo & OPFL_VariadicInfo) { 3577 // Determine the start index to copy from. 3578 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo); 3579 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0; 3580 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy && 3581 "Invalid variadic node"); 3582 // Copy all of the variadic operands, not including a potential glue 3583 // input. 3584 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands(); 3585 i != e; ++i) { 3586 SDValue V = NodeToMatch->getOperand(i); 3587 if (V.getValueType() == MVT::Glue) break; 3588 Ops.push_back(V); 3589 } 3590 } 3591 3592 // If this has chain/glue inputs, add them. 3593 if (EmitNodeInfo & OPFL_Chain) 3594 Ops.push_back(InputChain); 3595 if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr) 3596 Ops.push_back(InputGlue); 3597 3598 // Create the node. 3599 MachineSDNode *Res = nullptr; 3600 bool IsMorphNodeTo = Opcode == OPC_MorphNodeTo || 3601 (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2); 3602 if (!IsMorphNodeTo) { 3603 // If this is a normal EmitNode command, just create the new node and 3604 // add the results to the RecordedNodes list. 3605 Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch), 3606 VTList, Ops); 3607 3608 // Add all the non-glue/non-chain results to the RecordedNodes list. 3609 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 3610 if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break; 3611 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i), 3612 nullptr)); 3613 } 3614 } else { 3615 assert(NodeToMatch->getOpcode() != ISD::DELETED_NODE && 3616 "NodeToMatch was removed partway through selection"); 3617 SelectionDAG::DAGNodeDeletedListener NDL(*CurDAG, [&](SDNode *N, 3618 SDNode *E) { 3619 CurDAG->salvageDebugInfo(*N); 3620 auto &Chain = ChainNodesMatched; 3621 assert((!E || !is_contained(Chain, N)) && 3622 "Chain node replaced during MorphNode"); 3623 Chain.erase(std::remove(Chain.begin(), Chain.end(), N), Chain.end()); 3624 }); 3625 Res = cast<MachineSDNode>(MorphNode(NodeToMatch, TargetOpc, VTList, 3626 Ops, EmitNodeInfo)); 3627 } 3628 3629 // If the node had chain/glue results, update our notion of the current 3630 // chain and glue. 3631 if (EmitNodeInfo & OPFL_GlueOutput) { 3632 InputGlue = SDValue(Res, VTs.size()-1); 3633 if (EmitNodeInfo & OPFL_Chain) 3634 InputChain = SDValue(Res, VTs.size()-2); 3635 } else if (EmitNodeInfo & OPFL_Chain) 3636 InputChain = SDValue(Res, VTs.size()-1); 3637 3638 // If the OPFL_MemRefs glue is set on this node, slap all of the 3639 // accumulated memrefs onto it. 3640 // 3641 // FIXME: This is vastly incorrect for patterns with multiple outputs 3642 // instructions that access memory and for ComplexPatterns that match 3643 // loads. 3644 if (EmitNodeInfo & OPFL_MemRefs) { 3645 // Only attach load or store memory operands if the generated 3646 // instruction may load or store. 3647 const MCInstrDesc &MCID = TII->get(TargetOpc); 3648 bool mayLoad = MCID.mayLoad(); 3649 bool mayStore = MCID.mayStore(); 3650 3651 // We expect to have relatively few of these so just filter them into a 3652 // temporary buffer so that we can easily add them to the instruction. 3653 SmallVector<MachineMemOperand *, 4> FilteredMemRefs; 3654 for (MachineMemOperand *MMO : MatchedMemRefs) { 3655 if (MMO->isLoad()) { 3656 if (mayLoad) 3657 FilteredMemRefs.push_back(MMO); 3658 } else if (MMO->isStore()) { 3659 if (mayStore) 3660 FilteredMemRefs.push_back(MMO); 3661 } else { 3662 FilteredMemRefs.push_back(MMO); 3663 } 3664 } 3665 3666 CurDAG->setNodeMemRefs(Res, FilteredMemRefs); 3667 } 3668 3669 LLVM_DEBUG(if (!MatchedMemRefs.empty() && Res->memoperands_empty()) dbgs() 3670 << " Dropping mem operands\n"; 3671 dbgs() << " " << (IsMorphNodeTo ? "Morphed" : "Created") 3672 << " node: "; 3673 Res->dump(CurDAG);); 3674 3675 // If this was a MorphNodeTo then we're completely done! 3676 if (IsMorphNodeTo) { 3677 // Update chain uses. 3678 UpdateChains(Res, InputChain, ChainNodesMatched, true); 3679 return; 3680 } 3681 continue; 3682 } 3683 3684 case OPC_CompleteMatch: { 3685 // The match has been completed, and any new nodes (if any) have been 3686 // created. Patch up references to the matched dag to use the newly 3687 // created nodes. 3688 unsigned NumResults = MatcherTable[MatcherIndex++]; 3689 3690 for (unsigned i = 0; i != NumResults; ++i) { 3691 unsigned ResSlot = MatcherTable[MatcherIndex++]; 3692 if (ResSlot & 128) 3693 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex); 3694 3695 assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch"); 3696 SDValue Res = RecordedNodes[ResSlot].first; 3697 3698 assert(i < NodeToMatch->getNumValues() && 3699 NodeToMatch->getValueType(i) != MVT::Other && 3700 NodeToMatch->getValueType(i) != MVT::Glue && 3701 "Invalid number of results to complete!"); 3702 assert((NodeToMatch->getValueType(i) == Res.getValueType() || 3703 NodeToMatch->getValueType(i) == MVT::iPTR || 3704 Res.getValueType() == MVT::iPTR || 3705 NodeToMatch->getValueType(i).getSizeInBits() == 3706 Res.getValueSizeInBits()) && 3707 "invalid replacement"); 3708 ReplaceUses(SDValue(NodeToMatch, i), Res); 3709 } 3710 3711 // Update chain uses. 3712 UpdateChains(NodeToMatch, InputChain, ChainNodesMatched, false); 3713 3714 // If the root node defines glue, we need to update it to the glue result. 3715 // TODO: This never happens in our tests and I think it can be removed / 3716 // replaced with an assert, but if we do it this the way the change is 3717 // NFC. 3718 if (NodeToMatch->getValueType(NodeToMatch->getNumValues() - 1) == 3719 MVT::Glue && 3720 InputGlue.getNode()) 3721 ReplaceUses(SDValue(NodeToMatch, NodeToMatch->getNumValues() - 1), 3722 InputGlue); 3723 3724 assert(NodeToMatch->use_empty() && 3725 "Didn't replace all uses of the node?"); 3726 CurDAG->RemoveDeadNode(NodeToMatch); 3727 3728 return; 3729 } 3730 } 3731 3732 // If the code reached this point, then the match failed. See if there is 3733 // another child to try in the current 'Scope', otherwise pop it until we 3734 // find a case to check. 3735 LLVM_DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex 3736 << "\n"); 3737 ++NumDAGIselRetries; 3738 while (true) { 3739 if (MatchScopes.empty()) { 3740 CannotYetSelect(NodeToMatch); 3741 return; 3742 } 3743 3744 // Restore the interpreter state back to the point where the scope was 3745 // formed. 3746 MatchScope &LastScope = MatchScopes.back(); 3747 RecordedNodes.resize(LastScope.NumRecordedNodes); 3748 NodeStack.clear(); 3749 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end()); 3750 N = NodeStack.back(); 3751 3752 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size()) 3753 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs); 3754 MatcherIndex = LastScope.FailIndex; 3755 3756 LLVM_DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n"); 3757 3758 InputChain = LastScope.InputChain; 3759 InputGlue = LastScope.InputGlue; 3760 if (!LastScope.HasChainNodesMatched) 3761 ChainNodesMatched.clear(); 3762 3763 // Check to see what the offset is at the new MatcherIndex. If it is zero 3764 // we have reached the end of this scope, otherwise we have another child 3765 // in the current scope to try. 3766 unsigned NumToSkip = MatcherTable[MatcherIndex++]; 3767 if (NumToSkip & 128) 3768 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex); 3769 3770 // If we have another child in this scope to match, update FailIndex and 3771 // try it. 3772 if (NumToSkip != 0) { 3773 LastScope.FailIndex = MatcherIndex+NumToSkip; 3774 break; 3775 } 3776 3777 // End of this scope, pop it and try the next child in the containing 3778 // scope. 3779 MatchScopes.pop_back(); 3780 } 3781 } 3782 } 3783 3784 bool SelectionDAGISel::isOrEquivalentToAdd(const SDNode *N) const { 3785 assert(N->getOpcode() == ISD::OR && "Unexpected opcode"); 3786 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 3787 if (!C) 3788 return false; 3789 3790 // Detect when "or" is used to add an offset to a stack object. 3791 if (auto *FN = dyn_cast<FrameIndexSDNode>(N->getOperand(0))) { 3792 MachineFrameInfo &MFI = MF->getFrameInfo(); 3793 unsigned A = MFI.getObjectAlignment(FN->getIndex()); 3794 assert(isPowerOf2_32(A) && "Unexpected alignment"); 3795 int32_t Off = C->getSExtValue(); 3796 // If the alleged offset fits in the zero bits guaranteed by 3797 // the alignment, then this or is really an add. 3798 return (Off >= 0) && (((A - 1) & Off) == unsigned(Off)); 3799 } 3800 return false; 3801 } 3802 3803 void SelectionDAGISel::CannotYetSelect(SDNode *N) { 3804 std::string msg; 3805 raw_string_ostream Msg(msg); 3806 Msg << "Cannot select: "; 3807 3808 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN && 3809 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN && 3810 N->getOpcode() != ISD::INTRINSIC_VOID) { 3811 N->printrFull(Msg, CurDAG); 3812 Msg << "\nIn function: " << MF->getName(); 3813 } else { 3814 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other; 3815 unsigned iid = 3816 cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue(); 3817 if (iid < Intrinsic::num_intrinsics) 3818 Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid, None); 3819 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo()) 3820 Msg << "target intrinsic %" << TII->getName(iid); 3821 else 3822 Msg << "unknown intrinsic #" << iid; 3823 } 3824 report_fatal_error(Msg.str()); 3825 } 3826 3827 char SelectionDAGISel::ID = 0; 3828