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 } 1160 } 1161 1162 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and 1163 /// do other setup for EH landing-pad blocks. 1164 bool SelectionDAGISel::PrepareEHLandingPad() { 1165 MachineBasicBlock *MBB = FuncInfo->MBB; 1166 const Constant *PersonalityFn = FuncInfo->Fn->getPersonalityFn(); 1167 const BasicBlock *LLVMBB = MBB->getBasicBlock(); 1168 const TargetRegisterClass *PtrRC = 1169 TLI->getRegClassFor(TLI->getPointerTy(CurDAG->getDataLayout())); 1170 1171 auto Pers = classifyEHPersonality(PersonalityFn); 1172 1173 // Catchpads have one live-in register, which typically holds the exception 1174 // pointer or code. 1175 if (isFuncletEHPersonality(Pers)) { 1176 if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) { 1177 if (hasExceptionPointerOrCodeUser(CPI)) { 1178 // Get or create the virtual register to hold the pointer or code. Mark 1179 // the live in physreg and copy into the vreg. 1180 MCPhysReg EHPhysReg = TLI->getExceptionPointerRegister(PersonalityFn); 1181 assert(EHPhysReg && "target lacks exception pointer register"); 1182 MBB->addLiveIn(EHPhysReg); 1183 unsigned VReg = FuncInfo->getCatchPadExceptionPointerVReg(CPI, PtrRC); 1184 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), 1185 TII->get(TargetOpcode::COPY), VReg) 1186 .addReg(EHPhysReg, RegState::Kill); 1187 } 1188 } 1189 return true; 1190 } 1191 1192 // Add a label to mark the beginning of the landing pad. Deletion of the 1193 // landing pad can thus be detected via the MachineModuleInfo. 1194 MCSymbol *Label = MF->addLandingPad(MBB); 1195 1196 const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL); 1197 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II) 1198 .addSym(Label); 1199 1200 if (Pers == EHPersonality::Wasm_CXX) { 1201 if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) 1202 mapWasmLandingPadIndex(MBB, CPI); 1203 } else { 1204 // Assign the call site to the landing pad's begin label. 1205 MF->setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]); 1206 // Mark exception register as live in. 1207 if (unsigned Reg = TLI->getExceptionPointerRegister(PersonalityFn)) 1208 FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC); 1209 // Mark exception selector register as live in. 1210 if (unsigned Reg = TLI->getExceptionSelectorRegister(PersonalityFn)) 1211 FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC); 1212 } 1213 1214 return true; 1215 } 1216 1217 /// isFoldedOrDeadInstruction - Return true if the specified instruction is 1218 /// side-effect free and is either dead or folded into a generated instruction. 1219 /// Return false if it needs to be emitted. 1220 static bool isFoldedOrDeadInstruction(const Instruction *I, 1221 FunctionLoweringInfo *FuncInfo) { 1222 return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded. 1223 !I->isTerminator() && // Terminators aren't folded. 1224 !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded. 1225 !I->isEHPad() && // EH pad instructions aren't folded. 1226 !FuncInfo->isExportedInst(I); // Exported instrs must be computed. 1227 } 1228 1229 /// Set up SwiftErrorVals by going through the function. If the function has 1230 /// swifterror argument, it will be the first entry. 1231 static void setupSwiftErrorVals(const Function &Fn, const TargetLowering *TLI, 1232 FunctionLoweringInfo *FuncInfo) { 1233 if (!TLI->supportSwiftError()) 1234 return; 1235 1236 FuncInfo->SwiftErrorVals.clear(); 1237 FuncInfo->SwiftErrorVRegDefMap.clear(); 1238 FuncInfo->SwiftErrorVRegUpwardsUse.clear(); 1239 FuncInfo->SwiftErrorVRegDefUses.clear(); 1240 FuncInfo->SwiftErrorArg = nullptr; 1241 1242 // Check if function has a swifterror argument. 1243 bool HaveSeenSwiftErrorArg = false; 1244 for (Function::const_arg_iterator AI = Fn.arg_begin(), AE = Fn.arg_end(); 1245 AI != AE; ++AI) 1246 if (AI->hasSwiftErrorAttr()) { 1247 assert(!HaveSeenSwiftErrorArg && 1248 "Must have only one swifterror parameter"); 1249 (void)HaveSeenSwiftErrorArg; // silence warning. 1250 HaveSeenSwiftErrorArg = true; 1251 FuncInfo->SwiftErrorArg = &*AI; 1252 FuncInfo->SwiftErrorVals.push_back(&*AI); 1253 } 1254 1255 for (const auto &LLVMBB : Fn) 1256 for (const auto &Inst : LLVMBB) { 1257 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(&Inst)) 1258 if (Alloca->isSwiftError()) 1259 FuncInfo->SwiftErrorVals.push_back(Alloca); 1260 } 1261 } 1262 1263 static void createSwiftErrorEntriesInEntryBlock(FunctionLoweringInfo *FuncInfo, 1264 FastISel *FastIS, 1265 const TargetLowering *TLI, 1266 const TargetInstrInfo *TII, 1267 SelectionDAGBuilder *SDB) { 1268 if (!TLI->supportSwiftError()) 1269 return; 1270 1271 // We only need to do this when we have swifterror parameter or swifterror 1272 // alloc. 1273 if (FuncInfo->SwiftErrorVals.empty()) 1274 return; 1275 1276 assert(FuncInfo->MBB == &*FuncInfo->MF->begin() && 1277 "expected to insert into entry block"); 1278 auto &DL = FuncInfo->MF->getDataLayout(); 1279 auto const *RC = TLI->getRegClassFor(TLI->getPointerTy(DL)); 1280 for (const auto *SwiftErrorVal : FuncInfo->SwiftErrorVals) { 1281 // We will always generate a copy from the argument. It is always used at 1282 // least by the 'return' of the swifterror. 1283 if (FuncInfo->SwiftErrorArg && FuncInfo->SwiftErrorArg == SwiftErrorVal) 1284 continue; 1285 unsigned VReg = FuncInfo->MF->getRegInfo().createVirtualRegister(RC); 1286 // Assign Undef to Vreg. We construct MI directly to make sure it works 1287 // with FastISel. 1288 BuildMI(*FuncInfo->MBB, FuncInfo->MBB->getFirstNonPHI(), 1289 SDB->getCurDebugLoc(), TII->get(TargetOpcode::IMPLICIT_DEF), 1290 VReg); 1291 1292 // Keep FastIS informed about the value we just inserted. 1293 if (FastIS) 1294 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt)); 1295 1296 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, SwiftErrorVal, VReg); 1297 } 1298 } 1299 1300 /// Collect llvm.dbg.declare information. This is done after argument lowering 1301 /// in case the declarations refer to arguments. 1302 static void processDbgDeclares(FunctionLoweringInfo *FuncInfo) { 1303 MachineFunction *MF = FuncInfo->MF; 1304 const DataLayout &DL = MF->getDataLayout(); 1305 for (const BasicBlock &BB : *FuncInfo->Fn) { 1306 for (const Instruction &I : BB) { 1307 const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(&I); 1308 if (!DI) 1309 continue; 1310 1311 assert(DI->getVariable() && "Missing variable"); 1312 assert(DI->getDebugLoc() && "Missing location"); 1313 const Value *Address = DI->getAddress(); 1314 if (!Address) 1315 continue; 1316 1317 // Look through casts and constant offset GEPs. These mostly come from 1318 // inalloca. 1319 APInt Offset(DL.getTypeSizeInBits(Address->getType()), 0); 1320 Address = Address->stripAndAccumulateInBoundsConstantOffsets(DL, Offset); 1321 1322 // Check if the variable is a static alloca or a byval or inalloca 1323 // argument passed in memory. If it is not, then we will ignore this 1324 // intrinsic and handle this during isel like dbg.value. 1325 int FI = std::numeric_limits<int>::max(); 1326 if (const auto *AI = dyn_cast<AllocaInst>(Address)) { 1327 auto SI = FuncInfo->StaticAllocaMap.find(AI); 1328 if (SI != FuncInfo->StaticAllocaMap.end()) 1329 FI = SI->second; 1330 } else if (const auto *Arg = dyn_cast<Argument>(Address)) 1331 FI = FuncInfo->getArgumentFrameIndex(Arg); 1332 1333 if (FI == std::numeric_limits<int>::max()) 1334 continue; 1335 1336 DIExpression *Expr = DI->getExpression(); 1337 if (Offset.getBoolValue()) 1338 Expr = DIExpression::prepend(Expr, DIExpression::NoDeref, 1339 Offset.getZExtValue()); 1340 MF->setVariableDbgInfo(DI->getVariable(), Expr, FI, DI->getDebugLoc()); 1341 } 1342 } 1343 } 1344 1345 /// Propagate swifterror values through the machine function CFG. 1346 static void propagateSwiftErrorVRegs(FunctionLoweringInfo *FuncInfo) { 1347 auto *TLI = FuncInfo->TLI; 1348 if (!TLI->supportSwiftError()) 1349 return; 1350 1351 // We only need to do this when we have swifterror parameter or swifterror 1352 // alloc. 1353 if (FuncInfo->SwiftErrorVals.empty()) 1354 return; 1355 1356 // For each machine basic block in reverse post order. 1357 ReversePostOrderTraversal<MachineFunction *> RPOT(FuncInfo->MF); 1358 for (MachineBasicBlock *MBB : RPOT) { 1359 // For each swifterror value in the function. 1360 for(const auto *SwiftErrorVal : FuncInfo->SwiftErrorVals) { 1361 auto Key = std::make_pair(MBB, SwiftErrorVal); 1362 auto UUseIt = FuncInfo->SwiftErrorVRegUpwardsUse.find(Key); 1363 auto VRegDefIt = FuncInfo->SwiftErrorVRegDefMap.find(Key); 1364 bool UpwardsUse = UUseIt != FuncInfo->SwiftErrorVRegUpwardsUse.end(); 1365 unsigned UUseVReg = UpwardsUse ? UUseIt->second : 0; 1366 bool DownwardDef = VRegDefIt != FuncInfo->SwiftErrorVRegDefMap.end(); 1367 assert(!(UpwardsUse && !DownwardDef) && 1368 "We can't have an upwards use but no downwards def"); 1369 1370 // If there is no upwards exposed use and an entry for the swifterror in 1371 // the def map for this value we don't need to do anything: We already 1372 // have a downward def for this basic block. 1373 if (!UpwardsUse && DownwardDef) 1374 continue; 1375 1376 // Otherwise we either have an upwards exposed use vreg that we need to 1377 // materialize or need to forward the downward def from predecessors. 1378 1379 // Check whether we have a single vreg def from all predecessors. 1380 // Otherwise we need a phi. 1381 SmallVector<std::pair<MachineBasicBlock *, unsigned>, 4> VRegs; 1382 SmallSet<const MachineBasicBlock*, 8> Visited; 1383 for (auto *Pred : MBB->predecessors()) { 1384 if (!Visited.insert(Pred).second) 1385 continue; 1386 VRegs.push_back(std::make_pair( 1387 Pred, FuncInfo->getOrCreateSwiftErrorVReg(Pred, SwiftErrorVal))); 1388 if (Pred != MBB) 1389 continue; 1390 // We have a self-edge. 1391 // If there was no upwards use in this basic block there is now one: the 1392 // phi needs to use it self. 1393 if (!UpwardsUse) { 1394 UpwardsUse = true; 1395 UUseIt = FuncInfo->SwiftErrorVRegUpwardsUse.find(Key); 1396 assert(UUseIt != FuncInfo->SwiftErrorVRegUpwardsUse.end()); 1397 UUseVReg = UUseIt->second; 1398 } 1399 } 1400 1401 // We need a phi node if we have more than one predecessor with different 1402 // downward defs. 1403 bool needPHI = 1404 VRegs.size() >= 1 && 1405 std::find_if( 1406 VRegs.begin(), VRegs.end(), 1407 [&](const std::pair<const MachineBasicBlock *, unsigned> &V) 1408 -> bool { return V.second != VRegs[0].second; }) != 1409 VRegs.end(); 1410 1411 // If there is no upwards exposed used and we don't need a phi just 1412 // forward the swifterror vreg from the predecessor(s). 1413 if (!UpwardsUse && !needPHI) { 1414 assert(!VRegs.empty() && 1415 "No predecessors? The entry block should bail out earlier"); 1416 // Just forward the swifterror vreg from the predecessor(s). 1417 FuncInfo->setCurrentSwiftErrorVReg(MBB, SwiftErrorVal, VRegs[0].second); 1418 continue; 1419 } 1420 1421 auto DLoc = isa<Instruction>(SwiftErrorVal) 1422 ? cast<Instruction>(SwiftErrorVal)->getDebugLoc() 1423 : DebugLoc(); 1424 const auto *TII = FuncInfo->MF->getSubtarget().getInstrInfo(); 1425 1426 // If we don't need a phi create a copy to the upward exposed vreg. 1427 if (!needPHI) { 1428 assert(UpwardsUse); 1429 assert(!VRegs.empty() && 1430 "No predecessors? Is the Calling Convention correct?"); 1431 unsigned DestReg = UUseVReg; 1432 BuildMI(*MBB, MBB->getFirstNonPHI(), DLoc, TII->get(TargetOpcode::COPY), 1433 DestReg) 1434 .addReg(VRegs[0].second); 1435 continue; 1436 } 1437 1438 // We need a phi: if there is an upwards exposed use we already have a 1439 // destination virtual register number otherwise we generate a new one. 1440 auto &DL = FuncInfo->MF->getDataLayout(); 1441 auto const *RC = TLI->getRegClassFor(TLI->getPointerTy(DL)); 1442 unsigned PHIVReg = 1443 UpwardsUse ? UUseVReg 1444 : FuncInfo->MF->getRegInfo().createVirtualRegister(RC); 1445 MachineInstrBuilder SwiftErrorPHI = 1446 BuildMI(*MBB, MBB->getFirstNonPHI(), DLoc, 1447 TII->get(TargetOpcode::PHI), PHIVReg); 1448 for (auto BBRegPair : VRegs) { 1449 SwiftErrorPHI.addReg(BBRegPair.second).addMBB(BBRegPair.first); 1450 } 1451 1452 // We did not have a definition in this block before: store the phi's vreg 1453 // as this block downward exposed def. 1454 if (!UpwardsUse) 1455 FuncInfo->setCurrentSwiftErrorVReg(MBB, SwiftErrorVal, PHIVReg); 1456 } 1457 } 1458 } 1459 1460 static void preassignSwiftErrorRegs(const TargetLowering *TLI, 1461 FunctionLoweringInfo *FuncInfo, 1462 BasicBlock::const_iterator Begin, 1463 BasicBlock::const_iterator End) { 1464 if (!TLI->supportSwiftError() || FuncInfo->SwiftErrorVals.empty()) 1465 return; 1466 1467 // Iterator over instructions and assign vregs to swifterror defs and uses. 1468 for (auto It = Begin; It != End; ++It) { 1469 ImmutableCallSite CS(&*It); 1470 if (CS) { 1471 // A call-site with a swifterror argument is both use and def. 1472 const Value *SwiftErrorAddr = nullptr; 1473 for (auto &Arg : CS.args()) { 1474 if (!Arg->isSwiftError()) 1475 continue; 1476 // Use of swifterror. 1477 assert(!SwiftErrorAddr && "Cannot have multiple swifterror arguments"); 1478 SwiftErrorAddr = &*Arg; 1479 assert(SwiftErrorAddr->isSwiftError() && 1480 "Must have a swifterror value argument"); 1481 unsigned VReg; bool CreatedReg; 1482 std::tie(VReg, CreatedReg) = FuncInfo->getOrCreateSwiftErrorVRegUseAt( 1483 &*It, FuncInfo->MBB, SwiftErrorAddr); 1484 assert(CreatedReg); 1485 } 1486 if (!SwiftErrorAddr) 1487 continue; 1488 1489 // Def of swifterror. 1490 unsigned VReg; bool CreatedReg; 1491 std::tie(VReg, CreatedReg) = 1492 FuncInfo->getOrCreateSwiftErrorVRegDefAt(&*It); 1493 assert(CreatedReg); 1494 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, SwiftErrorAddr, VReg); 1495 1496 // A load is a use. 1497 } else if (const LoadInst *LI = dyn_cast<const LoadInst>(&*It)) { 1498 const Value *V = LI->getOperand(0); 1499 if (!V->isSwiftError()) 1500 continue; 1501 1502 unsigned VReg; bool CreatedReg; 1503 std::tie(VReg, CreatedReg) = 1504 FuncInfo->getOrCreateSwiftErrorVRegUseAt(LI, FuncInfo->MBB, V); 1505 assert(CreatedReg); 1506 1507 // A store is a def. 1508 } else if (const StoreInst *SI = dyn_cast<const StoreInst>(&*It)) { 1509 const Value *SwiftErrorAddr = SI->getOperand(1); 1510 if (!SwiftErrorAddr->isSwiftError()) 1511 continue; 1512 1513 // Def of swifterror. 1514 unsigned VReg; bool CreatedReg; 1515 std::tie(VReg, CreatedReg) = 1516 FuncInfo->getOrCreateSwiftErrorVRegDefAt(&*It); 1517 assert(CreatedReg); 1518 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, SwiftErrorAddr, VReg); 1519 1520 // A return in a swiferror returning function is a use. 1521 } else if (const ReturnInst *R = dyn_cast<const ReturnInst>(&*It)) { 1522 const Function *F = R->getParent()->getParent(); 1523 if(!F->getAttributes().hasAttrSomewhere(Attribute::SwiftError)) 1524 continue; 1525 1526 unsigned VReg; bool CreatedReg; 1527 std::tie(VReg, CreatedReg) = FuncInfo->getOrCreateSwiftErrorVRegUseAt( 1528 R, FuncInfo->MBB, FuncInfo->SwiftErrorArg); 1529 assert(CreatedReg); 1530 } 1531 } 1532 } 1533 1534 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) { 1535 FastISelFailed = false; 1536 // Initialize the Fast-ISel state, if needed. 1537 FastISel *FastIS = nullptr; 1538 if (TM.Options.EnableFastISel) { 1539 LLVM_DEBUG(dbgs() << "Enabling fast-isel\n"); 1540 FastIS = TLI->createFastISel(*FuncInfo, LibInfo); 1541 } 1542 1543 setupSwiftErrorVals(Fn, TLI, FuncInfo); 1544 1545 ReversePostOrderTraversal<const Function*> RPOT(&Fn); 1546 1547 // Lower arguments up front. An RPO iteration always visits the entry block 1548 // first. 1549 assert(*RPOT.begin() == &Fn.getEntryBlock()); 1550 ++NumEntryBlocks; 1551 1552 // Set up FuncInfo for ISel. Entry blocks never have PHIs. 1553 FuncInfo->MBB = FuncInfo->MBBMap[&Fn.getEntryBlock()]; 1554 FuncInfo->InsertPt = FuncInfo->MBB->begin(); 1555 1556 CurDAG->setFunctionLoweringInfo(FuncInfo); 1557 1558 if (!FastIS) { 1559 LowerArguments(Fn); 1560 } else { 1561 // See if fast isel can lower the arguments. 1562 FastIS->startNewBlock(); 1563 if (!FastIS->lowerArguments()) { 1564 FastISelFailed = true; 1565 // Fast isel failed to lower these arguments 1566 ++NumFastIselFailLowerArguments; 1567 1568 OptimizationRemarkMissed R("sdagisel", "FastISelFailure", 1569 Fn.getSubprogram(), 1570 &Fn.getEntryBlock()); 1571 R << "FastISel didn't lower all arguments: " 1572 << ore::NV("Prototype", Fn.getType()); 1573 reportFastISelFailure(*MF, *ORE, R, EnableFastISelAbort > 1); 1574 1575 // Use SelectionDAG argument lowering 1576 LowerArguments(Fn); 1577 CurDAG->setRoot(SDB->getControlRoot()); 1578 SDB->clear(); 1579 CodeGenAndEmitDAG(); 1580 } 1581 1582 // If we inserted any instructions at the beginning, make a note of 1583 // where they are, so we can be sure to emit subsequent instructions 1584 // after them. 1585 if (FuncInfo->InsertPt != FuncInfo->MBB->begin()) 1586 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt)); 1587 else 1588 FastIS->setLastLocalValue(nullptr); 1589 } 1590 createSwiftErrorEntriesInEntryBlock(FuncInfo, FastIS, TLI, TII, SDB); 1591 1592 processDbgDeclares(FuncInfo); 1593 1594 // Iterate over all basic blocks in the function. 1595 StackProtector &SP = getAnalysis<StackProtector>(); 1596 for (const BasicBlock *LLVMBB : RPOT) { 1597 if (OptLevel != CodeGenOpt::None) { 1598 bool AllPredsVisited = true; 1599 for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB); 1600 PI != PE; ++PI) { 1601 if (!FuncInfo->VisitedBBs.count(*PI)) { 1602 AllPredsVisited = false; 1603 break; 1604 } 1605 } 1606 1607 if (AllPredsVisited) { 1608 for (const PHINode &PN : LLVMBB->phis()) 1609 FuncInfo->ComputePHILiveOutRegInfo(&PN); 1610 } else { 1611 for (const PHINode &PN : LLVMBB->phis()) 1612 FuncInfo->InvalidatePHILiveOutRegInfo(&PN); 1613 } 1614 1615 FuncInfo->VisitedBBs.insert(LLVMBB); 1616 } 1617 1618 BasicBlock::const_iterator const Begin = 1619 LLVMBB->getFirstNonPHI()->getIterator(); 1620 BasicBlock::const_iterator const End = LLVMBB->end(); 1621 BasicBlock::const_iterator BI = End; 1622 1623 FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB]; 1624 if (!FuncInfo->MBB) 1625 continue; // Some blocks like catchpads have no code or MBB. 1626 1627 // Insert new instructions after any phi or argument setup code. 1628 FuncInfo->InsertPt = FuncInfo->MBB->end(); 1629 1630 // Setup an EH landing-pad block. 1631 FuncInfo->ExceptionPointerVirtReg = 0; 1632 FuncInfo->ExceptionSelectorVirtReg = 0; 1633 if (LLVMBB->isEHPad()) 1634 if (!PrepareEHLandingPad()) 1635 continue; 1636 1637 // Before doing SelectionDAG ISel, see if FastISel has been requested. 1638 if (FastIS) { 1639 if (LLVMBB != &Fn.getEntryBlock()) 1640 FastIS->startNewBlock(); 1641 1642 unsigned NumFastIselRemaining = std::distance(Begin, End); 1643 1644 // Pre-assign swifterror vregs. 1645 preassignSwiftErrorRegs(TLI, FuncInfo, Begin, End); 1646 1647 // Do FastISel on as many instructions as possible. 1648 for (; BI != Begin; --BI) { 1649 const Instruction *Inst = &*std::prev(BI); 1650 1651 // If we no longer require this instruction, skip it. 1652 if (isFoldedOrDeadInstruction(Inst, FuncInfo) || 1653 ElidedArgCopyInstrs.count(Inst)) { 1654 --NumFastIselRemaining; 1655 continue; 1656 } 1657 1658 // Bottom-up: reset the insert pos at the top, after any local-value 1659 // instructions. 1660 FastIS->recomputeInsertPt(); 1661 1662 // Try to select the instruction with FastISel. 1663 if (FastIS->selectInstruction(Inst)) { 1664 --NumFastIselRemaining; 1665 ++NumFastIselSuccess; 1666 // If fast isel succeeded, skip over all the folded instructions, and 1667 // then see if there is a load right before the selected instructions. 1668 // Try to fold the load if so. 1669 const Instruction *BeforeInst = Inst; 1670 while (BeforeInst != &*Begin) { 1671 BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst)); 1672 if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo)) 1673 break; 1674 } 1675 if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) && 1676 BeforeInst->hasOneUse() && 1677 FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) { 1678 // If we succeeded, don't re-select the load. 1679 BI = std::next(BasicBlock::const_iterator(BeforeInst)); 1680 --NumFastIselRemaining; 1681 ++NumFastIselSuccess; 1682 } 1683 continue; 1684 } 1685 1686 FastISelFailed = true; 1687 1688 // Then handle certain instructions as single-LLVM-Instruction blocks. 1689 // We cannot separate out GCrelocates to their own blocks since we need 1690 // to keep track of gc-relocates for a particular gc-statepoint. This is 1691 // done by SelectionDAGBuilder::LowerAsSTATEPOINT, called before 1692 // visitGCRelocate. 1693 if (isa<CallInst>(Inst) && !isStatepoint(Inst) && !isGCRelocate(Inst)) { 1694 OptimizationRemarkMissed R("sdagisel", "FastISelFailure", 1695 Inst->getDebugLoc(), LLVMBB); 1696 1697 R << "FastISel missed call"; 1698 1699 if (R.isEnabled() || EnableFastISelAbort) { 1700 std::string InstStrStorage; 1701 raw_string_ostream InstStr(InstStrStorage); 1702 InstStr << *Inst; 1703 1704 R << ": " << InstStr.str(); 1705 } 1706 1707 reportFastISelFailure(*MF, *ORE, R, EnableFastISelAbort > 2); 1708 1709 if (!Inst->getType()->isVoidTy() && !Inst->getType()->isTokenTy() && 1710 !Inst->use_empty()) { 1711 unsigned &R = FuncInfo->ValueMap[Inst]; 1712 if (!R) 1713 R = FuncInfo->CreateRegs(Inst->getType()); 1714 } 1715 1716 bool HadTailCall = false; 1717 MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt; 1718 SelectBasicBlock(Inst->getIterator(), BI, HadTailCall); 1719 1720 // If the call was emitted as a tail call, we're done with the block. 1721 // We also need to delete any previously emitted instructions. 1722 if (HadTailCall) { 1723 FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end()); 1724 --BI; 1725 break; 1726 } 1727 1728 // Recompute NumFastIselRemaining as Selection DAG instruction 1729 // selection may have handled the call, input args, etc. 1730 unsigned RemainingNow = std::distance(Begin, BI); 1731 NumFastIselFailures += NumFastIselRemaining - RemainingNow; 1732 NumFastIselRemaining = RemainingNow; 1733 continue; 1734 } 1735 1736 OptimizationRemarkMissed R("sdagisel", "FastISelFailure", 1737 Inst->getDebugLoc(), LLVMBB); 1738 1739 bool ShouldAbort = EnableFastISelAbort; 1740 if (Inst->isTerminator()) { 1741 // Use a different message for terminator misses. 1742 R << "FastISel missed terminator"; 1743 // Don't abort for terminator unless the level is really high 1744 ShouldAbort = (EnableFastISelAbort > 2); 1745 } else { 1746 R << "FastISel missed"; 1747 } 1748 1749 if (R.isEnabled() || EnableFastISelAbort) { 1750 std::string InstStrStorage; 1751 raw_string_ostream InstStr(InstStrStorage); 1752 InstStr << *Inst; 1753 R << ": " << InstStr.str(); 1754 } 1755 1756 reportFastISelFailure(*MF, *ORE, R, ShouldAbort); 1757 1758 NumFastIselFailures += NumFastIselRemaining; 1759 break; 1760 } 1761 1762 FastIS->recomputeInsertPt(); 1763 } 1764 1765 if (SP.shouldEmitSDCheck(*LLVMBB)) { 1766 bool FunctionBasedInstrumentation = 1767 TLI->getSSPStackGuardCheck(*Fn.getParent()); 1768 SDB->SPDescriptor.initialize(LLVMBB, FuncInfo->MBBMap[LLVMBB], 1769 FunctionBasedInstrumentation); 1770 } 1771 1772 if (Begin != BI) 1773 ++NumDAGBlocks; 1774 else 1775 ++NumFastIselBlocks; 1776 1777 if (Begin != BI) { 1778 // Run SelectionDAG instruction selection on the remainder of the block 1779 // not handled by FastISel. If FastISel is not run, this is the entire 1780 // block. 1781 bool HadTailCall; 1782 SelectBasicBlock(Begin, BI, HadTailCall); 1783 1784 // But if FastISel was run, we already selected some of the block. 1785 // If we emitted a tail-call, we need to delete any previously emitted 1786 // instruction that follows it. 1787 if (HadTailCall && FuncInfo->InsertPt != FuncInfo->MBB->end()) 1788 FastIS->removeDeadCode(FuncInfo->InsertPt, FuncInfo->MBB->end()); 1789 } 1790 1791 if (FastIS) 1792 FastIS->finishBasicBlock(); 1793 FinishBasicBlock(); 1794 FuncInfo->PHINodesToUpdate.clear(); 1795 ElidedArgCopyInstrs.clear(); 1796 } 1797 1798 SP.copyToMachineFrameInfo(MF->getFrameInfo()); 1799 1800 propagateSwiftErrorVRegs(FuncInfo); 1801 1802 delete FastIS; 1803 SDB->clearDanglingDebugInfo(); 1804 SDB->SPDescriptor.resetPerFunctionState(); 1805 } 1806 1807 /// Given that the input MI is before a partial terminator sequence TSeq, return 1808 /// true if M + TSeq also a partial terminator sequence. 1809 /// 1810 /// A Terminator sequence is a sequence of MachineInstrs which at this point in 1811 /// lowering copy vregs into physical registers, which are then passed into 1812 /// terminator instructors so we can satisfy ABI constraints. A partial 1813 /// terminator sequence is an improper subset of a terminator sequence (i.e. it 1814 /// may be the whole terminator sequence). 1815 static bool MIIsInTerminatorSequence(const MachineInstr &MI) { 1816 // If we do not have a copy or an implicit def, we return true if and only if 1817 // MI is a debug value. 1818 if (!MI.isCopy() && !MI.isImplicitDef()) 1819 // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the 1820 // physical registers if there is debug info associated with the terminator 1821 // of our mbb. We want to include said debug info in our terminator 1822 // sequence, so we return true in that case. 1823 return MI.isDebugValue(); 1824 1825 // We have left the terminator sequence if we are not doing one of the 1826 // following: 1827 // 1828 // 1. Copying a vreg into a physical register. 1829 // 2. Copying a vreg into a vreg. 1830 // 3. Defining a register via an implicit def. 1831 1832 // OPI should always be a register definition... 1833 MachineInstr::const_mop_iterator OPI = MI.operands_begin(); 1834 if (!OPI->isReg() || !OPI->isDef()) 1835 return false; 1836 1837 // Defining any register via an implicit def is always ok. 1838 if (MI.isImplicitDef()) 1839 return true; 1840 1841 // Grab the copy source... 1842 MachineInstr::const_mop_iterator OPI2 = OPI; 1843 ++OPI2; 1844 assert(OPI2 != MI.operands_end() 1845 && "Should have a copy implying we should have 2 arguments."); 1846 1847 // Make sure that the copy dest is not a vreg when the copy source is a 1848 // physical register. 1849 if (!OPI2->isReg() || 1850 (!TargetRegisterInfo::isPhysicalRegister(OPI->getReg()) && 1851 TargetRegisterInfo::isPhysicalRegister(OPI2->getReg()))) 1852 return false; 1853 1854 return true; 1855 } 1856 1857 /// Find the split point at which to splice the end of BB into its success stack 1858 /// protector check machine basic block. 1859 /// 1860 /// On many platforms, due to ABI constraints, terminators, even before register 1861 /// allocation, use physical registers. This creates an issue for us since 1862 /// physical registers at this point can not travel across basic 1863 /// blocks. Luckily, selectiondag always moves physical registers into vregs 1864 /// when they enter functions and moves them through a sequence of copies back 1865 /// into the physical registers right before the terminator creating a 1866 /// ``Terminator Sequence''. This function is searching for the beginning of the 1867 /// terminator sequence so that we can ensure that we splice off not just the 1868 /// terminator, but additionally the copies that move the vregs into the 1869 /// physical registers. 1870 static MachineBasicBlock::iterator 1871 FindSplitPointForStackProtector(MachineBasicBlock *BB) { 1872 MachineBasicBlock::iterator SplitPoint = BB->getFirstTerminator(); 1873 // 1874 if (SplitPoint == BB->begin()) 1875 return SplitPoint; 1876 1877 MachineBasicBlock::iterator Start = BB->begin(); 1878 MachineBasicBlock::iterator Previous = SplitPoint; 1879 --Previous; 1880 1881 while (MIIsInTerminatorSequence(*Previous)) { 1882 SplitPoint = Previous; 1883 if (Previous == Start) 1884 break; 1885 --Previous; 1886 } 1887 1888 return SplitPoint; 1889 } 1890 1891 void 1892 SelectionDAGISel::FinishBasicBlock() { 1893 LLVM_DEBUG(dbgs() << "Total amount of phi nodes to update: " 1894 << FuncInfo->PHINodesToUpdate.size() << "\n"; 1895 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; 1896 ++i) dbgs() 1897 << "Node " << i << " : (" << FuncInfo->PHINodesToUpdate[i].first 1898 << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n"); 1899 1900 // Next, now that we know what the last MBB the LLVM BB expanded is, update 1901 // PHI nodes in successors. 1902 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) { 1903 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first); 1904 assert(PHI->isPHI() && 1905 "This is not a machine PHI node that we are updating!"); 1906 if (!FuncInfo->MBB->isSuccessor(PHI->getParent())) 1907 continue; 1908 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB); 1909 } 1910 1911 // Handle stack protector. 1912 if (SDB->SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) { 1913 // The target provides a guard check function. There is no need to 1914 // generate error handling code or to split current basic block. 1915 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB(); 1916 1917 // Add load and check to the basicblock. 1918 FuncInfo->MBB = ParentMBB; 1919 FuncInfo->InsertPt = 1920 FindSplitPointForStackProtector(ParentMBB); 1921 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB); 1922 CurDAG->setRoot(SDB->getRoot()); 1923 SDB->clear(); 1924 CodeGenAndEmitDAG(); 1925 1926 // Clear the Per-BB State. 1927 SDB->SPDescriptor.resetPerBBState(); 1928 } else if (SDB->SPDescriptor.shouldEmitStackProtector()) { 1929 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB(); 1930 MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB(); 1931 1932 // Find the split point to split the parent mbb. At the same time copy all 1933 // physical registers used in the tail of parent mbb into virtual registers 1934 // before the split point and back into physical registers after the split 1935 // point. This prevents us needing to deal with Live-ins and many other 1936 // register allocation issues caused by us splitting the parent mbb. The 1937 // register allocator will clean up said virtual copies later on. 1938 MachineBasicBlock::iterator SplitPoint = 1939 FindSplitPointForStackProtector(ParentMBB); 1940 1941 // Splice the terminator of ParentMBB into SuccessMBB. 1942 SuccessMBB->splice(SuccessMBB->end(), ParentMBB, 1943 SplitPoint, 1944 ParentMBB->end()); 1945 1946 // Add compare/jump on neq/jump to the parent BB. 1947 FuncInfo->MBB = ParentMBB; 1948 FuncInfo->InsertPt = ParentMBB->end(); 1949 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB); 1950 CurDAG->setRoot(SDB->getRoot()); 1951 SDB->clear(); 1952 CodeGenAndEmitDAG(); 1953 1954 // CodeGen Failure MBB if we have not codegened it yet. 1955 MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB(); 1956 if (FailureMBB->empty()) { 1957 FuncInfo->MBB = FailureMBB; 1958 FuncInfo->InsertPt = FailureMBB->end(); 1959 SDB->visitSPDescriptorFailure(SDB->SPDescriptor); 1960 CurDAG->setRoot(SDB->getRoot()); 1961 SDB->clear(); 1962 CodeGenAndEmitDAG(); 1963 } 1964 1965 // Clear the Per-BB State. 1966 SDB->SPDescriptor.resetPerBBState(); 1967 } 1968 1969 // Lower each BitTestBlock. 1970 for (auto &BTB : SDB->BitTestCases) { 1971 // Lower header first, if it wasn't already lowered 1972 if (!BTB.Emitted) { 1973 // Set the current basic block to the mbb we wish to insert the code into 1974 FuncInfo->MBB = BTB.Parent; 1975 FuncInfo->InsertPt = FuncInfo->MBB->end(); 1976 // Emit the code 1977 SDB->visitBitTestHeader(BTB, FuncInfo->MBB); 1978 CurDAG->setRoot(SDB->getRoot()); 1979 SDB->clear(); 1980 CodeGenAndEmitDAG(); 1981 } 1982 1983 BranchProbability UnhandledProb = BTB.Prob; 1984 for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) { 1985 UnhandledProb -= BTB.Cases[j].ExtraProb; 1986 // Set the current basic block to the mbb we wish to insert the code into 1987 FuncInfo->MBB = BTB.Cases[j].ThisBB; 1988 FuncInfo->InsertPt = FuncInfo->MBB->end(); 1989 // Emit the code 1990 1991 // If all cases cover a contiguous range, it is not necessary to jump to 1992 // the default block after the last bit test fails. This is because the 1993 // range check during bit test header creation has guaranteed that every 1994 // case here doesn't go outside the range. In this case, there is no need 1995 // to perform the last bit test, as it will always be true. Instead, make 1996 // the second-to-last bit-test fall through to the target of the last bit 1997 // test, and delete the last bit test. 1998 1999 MachineBasicBlock *NextMBB; 2000 if (BTB.ContiguousRange && j + 2 == ej) { 2001 // Second-to-last bit-test with contiguous range: fall through to the 2002 // target of the final bit test. 2003 NextMBB = BTB.Cases[j + 1].TargetBB; 2004 } else if (j + 1 == ej) { 2005 // For the last bit test, fall through to Default. 2006 NextMBB = BTB.Default; 2007 } else { 2008 // Otherwise, fall through to the next bit test. 2009 NextMBB = BTB.Cases[j + 1].ThisBB; 2010 } 2011 2012 SDB->visitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j], 2013 FuncInfo->MBB); 2014 2015 CurDAG->setRoot(SDB->getRoot()); 2016 SDB->clear(); 2017 CodeGenAndEmitDAG(); 2018 2019 if (BTB.ContiguousRange && j + 2 == ej) { 2020 // Since we're not going to use the final bit test, remove it. 2021 BTB.Cases.pop_back(); 2022 break; 2023 } 2024 } 2025 2026 // Update PHI Nodes 2027 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size(); 2028 pi != pe; ++pi) { 2029 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first); 2030 MachineBasicBlock *PHIBB = PHI->getParent(); 2031 assert(PHI->isPHI() && 2032 "This is not a machine PHI node that we are updating!"); 2033 // This is "default" BB. We have two jumps to it. From "header" BB and 2034 // from last "case" BB, unless the latter was skipped. 2035 if (PHIBB == BTB.Default) { 2036 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(BTB.Parent); 2037 if (!BTB.ContiguousRange) { 2038 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second) 2039 .addMBB(BTB.Cases.back().ThisBB); 2040 } 2041 } 2042 // One of "cases" BB. 2043 for (unsigned j = 0, ej = BTB.Cases.size(); 2044 j != ej; ++j) { 2045 MachineBasicBlock* cBB = BTB.Cases[j].ThisBB; 2046 if (cBB->isSuccessor(PHIBB)) 2047 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB); 2048 } 2049 } 2050 } 2051 SDB->BitTestCases.clear(); 2052 2053 // If the JumpTable record is filled in, then we need to emit a jump table. 2054 // Updating the PHI nodes is tricky in this case, since we need to determine 2055 // whether the PHI is a successor of the range check MBB or the jump table MBB 2056 for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) { 2057 // Lower header first, if it wasn't already lowered 2058 if (!SDB->JTCases[i].first.Emitted) { 2059 // Set the current basic block to the mbb we wish to insert the code into 2060 FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB; 2061 FuncInfo->InsertPt = FuncInfo->MBB->end(); 2062 // Emit the code 2063 SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first, 2064 FuncInfo->MBB); 2065 CurDAG->setRoot(SDB->getRoot()); 2066 SDB->clear(); 2067 CodeGenAndEmitDAG(); 2068 } 2069 2070 // Set the current basic block to the mbb we wish to insert the code into 2071 FuncInfo->MBB = SDB->JTCases[i].second.MBB; 2072 FuncInfo->InsertPt = FuncInfo->MBB->end(); 2073 // Emit the code 2074 SDB->visitJumpTable(SDB->JTCases[i].second); 2075 CurDAG->setRoot(SDB->getRoot()); 2076 SDB->clear(); 2077 CodeGenAndEmitDAG(); 2078 2079 // Update PHI Nodes 2080 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size(); 2081 pi != pe; ++pi) { 2082 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first); 2083 MachineBasicBlock *PHIBB = PHI->getParent(); 2084 assert(PHI->isPHI() && 2085 "This is not a machine PHI node that we are updating!"); 2086 // "default" BB. We can go there only from header BB. 2087 if (PHIBB == SDB->JTCases[i].second.Default) 2088 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second) 2089 .addMBB(SDB->JTCases[i].first.HeaderBB); 2090 // JT BB. Just iterate over successors here 2091 if (FuncInfo->MBB->isSuccessor(PHIBB)) 2092 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB); 2093 } 2094 } 2095 SDB->JTCases.clear(); 2096 2097 // If we generated any switch lowering information, build and codegen any 2098 // additional DAGs necessary. 2099 for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) { 2100 // Set the current basic block to the mbb we wish to insert the code into 2101 FuncInfo->MBB = SDB->SwitchCases[i].ThisBB; 2102 FuncInfo->InsertPt = FuncInfo->MBB->end(); 2103 2104 // Determine the unique successors. 2105 SmallVector<MachineBasicBlock *, 2> Succs; 2106 Succs.push_back(SDB->SwitchCases[i].TrueBB); 2107 if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB) 2108 Succs.push_back(SDB->SwitchCases[i].FalseBB); 2109 2110 // Emit the code. Note that this could result in FuncInfo->MBB being split. 2111 SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB); 2112 CurDAG->setRoot(SDB->getRoot()); 2113 SDB->clear(); 2114 CodeGenAndEmitDAG(); 2115 2116 // Remember the last block, now that any splitting is done, for use in 2117 // populating PHI nodes in successors. 2118 MachineBasicBlock *ThisBB = FuncInfo->MBB; 2119 2120 // Handle any PHI nodes in successors of this chunk, as if we were coming 2121 // from the original BB before switch expansion. Note that PHI nodes can 2122 // occur multiple times in PHINodesToUpdate. We have to be very careful to 2123 // handle them the right number of times. 2124 for (unsigned i = 0, e = Succs.size(); i != e; ++i) { 2125 FuncInfo->MBB = Succs[i]; 2126 FuncInfo->InsertPt = FuncInfo->MBB->end(); 2127 // FuncInfo->MBB may have been removed from the CFG if a branch was 2128 // constant folded. 2129 if (ThisBB->isSuccessor(FuncInfo->MBB)) { 2130 for (MachineBasicBlock::iterator 2131 MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end(); 2132 MBBI != MBBE && MBBI->isPHI(); ++MBBI) { 2133 MachineInstrBuilder PHI(*MF, MBBI); 2134 // This value for this PHI node is recorded in PHINodesToUpdate. 2135 for (unsigned pn = 0; ; ++pn) { 2136 assert(pn != FuncInfo->PHINodesToUpdate.size() && 2137 "Didn't find PHI entry!"); 2138 if (FuncInfo->PHINodesToUpdate[pn].first == PHI) { 2139 PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB); 2140 break; 2141 } 2142 } 2143 } 2144 } 2145 } 2146 } 2147 SDB->SwitchCases.clear(); 2148 } 2149 2150 /// Create the scheduler. If a specific scheduler was specified 2151 /// via the SchedulerRegistry, use it, otherwise select the 2152 /// one preferred by the target. 2153 /// 2154 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() { 2155 return ISHeuristic(this, OptLevel); 2156 } 2157 2158 //===----------------------------------------------------------------------===// 2159 // Helper functions used by the generated instruction selector. 2160 //===----------------------------------------------------------------------===// 2161 // Calls to these methods are generated by tblgen. 2162 2163 /// CheckAndMask - The isel is trying to match something like (and X, 255). If 2164 /// the dag combiner simplified the 255, we still want to match. RHS is the 2165 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value 2166 /// specified in the .td file (e.g. 255). 2167 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS, 2168 int64_t DesiredMaskS) const { 2169 const APInt &ActualMask = RHS->getAPIntValue(); 2170 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS); 2171 2172 // If the actual mask exactly matches, success! 2173 if (ActualMask == DesiredMask) 2174 return true; 2175 2176 // If the actual AND mask is allowing unallowed bits, this doesn't match. 2177 if (!ActualMask.isSubsetOf(DesiredMask)) 2178 return false; 2179 2180 // Otherwise, the DAG Combiner may have proven that the value coming in is 2181 // either already zero or is not demanded. Check for known zero input bits. 2182 APInt NeededMask = DesiredMask & ~ActualMask; 2183 if (CurDAG->MaskedValueIsZero(LHS, NeededMask)) 2184 return true; 2185 2186 // TODO: check to see if missing bits are just not demanded. 2187 2188 // Otherwise, this pattern doesn't match. 2189 return false; 2190 } 2191 2192 /// CheckOrMask - The isel is trying to match something like (or X, 255). If 2193 /// the dag combiner simplified the 255, we still want to match. RHS is the 2194 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value 2195 /// specified in the .td file (e.g. 255). 2196 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS, 2197 int64_t DesiredMaskS) const { 2198 const APInt &ActualMask = RHS->getAPIntValue(); 2199 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS); 2200 2201 // If the actual mask exactly matches, success! 2202 if (ActualMask == DesiredMask) 2203 return true; 2204 2205 // If the actual AND mask is allowing unallowed bits, this doesn't match. 2206 if (!ActualMask.isSubsetOf(DesiredMask)) 2207 return false; 2208 2209 // Otherwise, the DAG Combiner may have proven that the value coming in is 2210 // either already zero or is not demanded. Check for known zero input bits. 2211 APInt NeededMask = DesiredMask & ~ActualMask; 2212 2213 KnownBits Known; 2214 CurDAG->computeKnownBits(LHS, Known); 2215 2216 // If all the missing bits in the or are already known to be set, match! 2217 if (NeededMask.isSubsetOf(Known.One)) 2218 return true; 2219 2220 // TODO: check to see if missing bits are just not demanded. 2221 2222 // Otherwise, this pattern doesn't match. 2223 return false; 2224 } 2225 2226 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated 2227 /// by tblgen. Others should not call it. 2228 void SelectionDAGISel::SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops, 2229 const SDLoc &DL) { 2230 std::vector<SDValue> InOps; 2231 std::swap(InOps, Ops); 2232 2233 Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0 2234 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1 2235 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc 2236 Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack) 2237 2238 unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size(); 2239 if (InOps[e-1].getValueType() == MVT::Glue) 2240 --e; // Don't process a glue operand if it is here. 2241 2242 while (i != e) { 2243 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue(); 2244 if (!InlineAsm::isMemKind(Flags)) { 2245 // Just skip over this operand, copying the operands verbatim. 2246 Ops.insert(Ops.end(), InOps.begin()+i, 2247 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1); 2248 i += InlineAsm::getNumOperandRegisters(Flags) + 1; 2249 } else { 2250 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 && 2251 "Memory operand with multiple values?"); 2252 2253 unsigned TiedToOperand; 2254 if (InlineAsm::isUseOperandTiedToDef(Flags, TiedToOperand)) { 2255 // We need the constraint ID from the operand this is tied to. 2256 unsigned CurOp = InlineAsm::Op_FirstOperand; 2257 Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue(); 2258 for (; TiedToOperand; --TiedToOperand) { 2259 CurOp += InlineAsm::getNumOperandRegisters(Flags)+1; 2260 Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue(); 2261 } 2262 } 2263 2264 // Otherwise, this is a memory operand. Ask the target to select it. 2265 std::vector<SDValue> SelOps; 2266 unsigned ConstraintID = InlineAsm::getMemoryConstraintID(Flags); 2267 if (SelectInlineAsmMemoryOperand(InOps[i+1], ConstraintID, SelOps)) 2268 report_fatal_error("Could not match memory address. Inline asm" 2269 " failure!"); 2270 2271 // Add this to the output node. 2272 unsigned NewFlags = 2273 InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size()); 2274 NewFlags = InlineAsm::getFlagWordForMem(NewFlags, ConstraintID); 2275 Ops.push_back(CurDAG->getTargetConstant(NewFlags, DL, MVT::i32)); 2276 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end()); 2277 i += 2; 2278 } 2279 } 2280 2281 // Add the glue input back if present. 2282 if (e != InOps.size()) 2283 Ops.push_back(InOps.back()); 2284 } 2285 2286 /// findGlueUse - Return use of MVT::Glue value produced by the specified 2287 /// SDNode. 2288 /// 2289 static SDNode *findGlueUse(SDNode *N) { 2290 unsigned FlagResNo = N->getNumValues()-1; 2291 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) { 2292 SDUse &Use = I.getUse(); 2293 if (Use.getResNo() == FlagResNo) 2294 return Use.getUser(); 2295 } 2296 return nullptr; 2297 } 2298 2299 /// findNonImmUse - Return true if "Def" is a predecessor of "Root" via a path 2300 /// beyond "ImmedUse". We may ignore chains as they are checked separately. 2301 static bool findNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse, 2302 bool IgnoreChains) { 2303 SmallPtrSet<const SDNode *, 16> Visited; 2304 SmallVector<const SDNode *, 16> WorkList; 2305 // Only check if we have non-immediate uses of Def. 2306 if (ImmedUse->isOnlyUserOf(Def)) 2307 return false; 2308 2309 // We don't care about paths to Def that go through ImmedUse so mark it 2310 // visited and mark non-def operands as used. 2311 Visited.insert(ImmedUse); 2312 for (const SDValue &Op : ImmedUse->op_values()) { 2313 SDNode *N = Op.getNode(); 2314 // Ignore chain deps (they are validated by 2315 // HandleMergeInputChains) and immediate uses 2316 if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def) 2317 continue; 2318 if (!Visited.insert(N).second) 2319 continue; 2320 WorkList.push_back(N); 2321 } 2322 2323 // Initialize worklist to operands of Root. 2324 if (Root != ImmedUse) { 2325 for (const SDValue &Op : Root->op_values()) { 2326 SDNode *N = Op.getNode(); 2327 // Ignore chains (they are validated by HandleMergeInputChains) 2328 if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def) 2329 continue; 2330 if (!Visited.insert(N).second) 2331 continue; 2332 WorkList.push_back(N); 2333 } 2334 } 2335 2336 return SDNode::hasPredecessorHelper(Def, Visited, WorkList, 0, true); 2337 } 2338 2339 /// IsProfitableToFold - Returns true if it's profitable to fold the specific 2340 /// operand node N of U during instruction selection that starts at Root. 2341 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U, 2342 SDNode *Root) const { 2343 if (OptLevel == CodeGenOpt::None) return false; 2344 return N.hasOneUse(); 2345 } 2346 2347 /// IsLegalToFold - Returns true if the specific operand node N of 2348 /// U can be folded during instruction selection that starts at Root. 2349 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root, 2350 CodeGenOpt::Level OptLevel, 2351 bool IgnoreChains) { 2352 if (OptLevel == CodeGenOpt::None) return false; 2353 2354 // If Root use can somehow reach N through a path that that doesn't contain 2355 // U then folding N would create a cycle. e.g. In the following 2356 // diagram, Root can reach N through X. If N is folded into Root, then 2357 // X is both a predecessor and a successor of U. 2358 // 2359 // [N*] // 2360 // ^ ^ // 2361 // / \ // 2362 // [U*] [X]? // 2363 // ^ ^ // 2364 // \ / // 2365 // \ / // 2366 // [Root*] // 2367 // 2368 // * indicates nodes to be folded together. 2369 // 2370 // If Root produces glue, then it gets (even more) interesting. Since it 2371 // will be "glued" together with its glue use in the scheduler, we need to 2372 // check if it might reach N. 2373 // 2374 // [N*] // 2375 // ^ ^ // 2376 // / \ // 2377 // [U*] [X]? // 2378 // ^ ^ // 2379 // \ \ // 2380 // \ | // 2381 // [Root*] | // 2382 // ^ | // 2383 // f | // 2384 // | / // 2385 // [Y] / // 2386 // ^ / // 2387 // f / // 2388 // | / // 2389 // [GU] // 2390 // 2391 // If GU (glue use) indirectly reaches N (the load), and Root folds N 2392 // (call it Fold), then X is a predecessor of GU and a successor of 2393 // Fold. But since Fold and GU are glued together, this will create 2394 // a cycle in the scheduling graph. 2395 2396 // If the node has glue, walk down the graph to the "lowest" node in the 2397 // glueged set. 2398 EVT VT = Root->getValueType(Root->getNumValues()-1); 2399 while (VT == MVT::Glue) { 2400 SDNode *GU = findGlueUse(Root); 2401 if (!GU) 2402 break; 2403 Root = GU; 2404 VT = Root->getValueType(Root->getNumValues()-1); 2405 2406 // If our query node has a glue result with a use, we've walked up it. If 2407 // the user (which has already been selected) has a chain or indirectly uses 2408 // the chain, HandleMergeInputChains will not consider it. Because of 2409 // this, we cannot ignore chains in this predicate. 2410 IgnoreChains = false; 2411 } 2412 2413 return !findNonImmUse(Root, N.getNode(), U, IgnoreChains); 2414 } 2415 2416 void SelectionDAGISel::Select_INLINEASM(SDNode *N) { 2417 SDLoc DL(N); 2418 2419 std::vector<SDValue> Ops(N->op_begin(), N->op_end()); 2420 SelectInlineAsmMemoryOperands(Ops, DL); 2421 2422 const EVT VTs[] = {MVT::Other, MVT::Glue}; 2423 SDValue New = CurDAG->getNode(ISD::INLINEASM, DL, VTs, Ops); 2424 New->setNodeId(-1); 2425 ReplaceUses(N, New.getNode()); 2426 CurDAG->RemoveDeadNode(N); 2427 } 2428 2429 void SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) { 2430 SDLoc dl(Op); 2431 MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1)); 2432 const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0)); 2433 unsigned Reg = 2434 TLI->getRegisterByName(RegStr->getString().data(), Op->getValueType(0), 2435 *CurDAG); 2436 SDValue New = CurDAG->getCopyFromReg( 2437 Op->getOperand(0), dl, Reg, Op->getValueType(0)); 2438 New->setNodeId(-1); 2439 ReplaceUses(Op, New.getNode()); 2440 CurDAG->RemoveDeadNode(Op); 2441 } 2442 2443 void SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) { 2444 SDLoc dl(Op); 2445 MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1)); 2446 const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0)); 2447 unsigned Reg = TLI->getRegisterByName(RegStr->getString().data(), 2448 Op->getOperand(2).getValueType(), 2449 *CurDAG); 2450 SDValue New = CurDAG->getCopyToReg( 2451 Op->getOperand(0), dl, Reg, Op->getOperand(2)); 2452 New->setNodeId(-1); 2453 ReplaceUses(Op, New.getNode()); 2454 CurDAG->RemoveDeadNode(Op); 2455 } 2456 2457 void SelectionDAGISel::Select_UNDEF(SDNode *N) { 2458 CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0)); 2459 } 2460 2461 /// GetVBR - decode a vbr encoding whose top bit is set. 2462 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline uint64_t 2463 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) { 2464 assert(Val >= 128 && "Not a VBR"); 2465 Val &= 127; // Remove first vbr bit. 2466 2467 unsigned Shift = 7; 2468 uint64_t NextBits; 2469 do { 2470 NextBits = MatcherTable[Idx++]; 2471 Val |= (NextBits&127) << Shift; 2472 Shift += 7; 2473 } while (NextBits & 128); 2474 2475 return Val; 2476 } 2477 2478 /// When a match is complete, this method updates uses of interior chain results 2479 /// to use the new results. 2480 void SelectionDAGISel::UpdateChains( 2481 SDNode *NodeToMatch, SDValue InputChain, 2482 SmallVectorImpl<SDNode *> &ChainNodesMatched, bool isMorphNodeTo) { 2483 SmallVector<SDNode*, 4> NowDeadNodes; 2484 2485 // Now that all the normal results are replaced, we replace the chain and 2486 // glue results if present. 2487 if (!ChainNodesMatched.empty()) { 2488 assert(InputChain.getNode() && 2489 "Matched input chains but didn't produce a chain"); 2490 // Loop over all of the nodes we matched that produced a chain result. 2491 // Replace all the chain results with the final chain we ended up with. 2492 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) { 2493 SDNode *ChainNode = ChainNodesMatched[i]; 2494 // If ChainNode is null, it's because we replaced it on a previous 2495 // iteration and we cleared it out of the map. Just skip it. 2496 if (!ChainNode) 2497 continue; 2498 2499 assert(ChainNode->getOpcode() != ISD::DELETED_NODE && 2500 "Deleted node left in chain"); 2501 2502 // Don't replace the results of the root node if we're doing a 2503 // MorphNodeTo. 2504 if (ChainNode == NodeToMatch && isMorphNodeTo) 2505 continue; 2506 2507 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1); 2508 if (ChainVal.getValueType() == MVT::Glue) 2509 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2); 2510 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?"); 2511 SelectionDAG::DAGNodeDeletedListener NDL( 2512 *CurDAG, [&](SDNode *N, SDNode *E) { 2513 std::replace(ChainNodesMatched.begin(), ChainNodesMatched.end(), N, 2514 static_cast<SDNode *>(nullptr)); 2515 }); 2516 if (ChainNode->getOpcode() != ISD::TokenFactor) 2517 ReplaceUses(ChainVal, InputChain); 2518 2519 // If the node became dead and we haven't already seen it, delete it. 2520 if (ChainNode != NodeToMatch && ChainNode->use_empty() && 2521 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode)) 2522 NowDeadNodes.push_back(ChainNode); 2523 } 2524 } 2525 2526 if (!NowDeadNodes.empty()) 2527 CurDAG->RemoveDeadNodes(NowDeadNodes); 2528 2529 LLVM_DEBUG(dbgs() << "ISEL: Match complete!\n"); 2530 } 2531 2532 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains 2533 /// operation for when the pattern matched at least one node with a chains. The 2534 /// input vector contains a list of all of the chained nodes that we match. We 2535 /// must determine if this is a valid thing to cover (i.e. matching it won't 2536 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will 2537 /// be used as the input node chain for the generated nodes. 2538 static SDValue 2539 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched, 2540 SelectionDAG *CurDAG) { 2541 2542 SmallPtrSet<const SDNode *, 16> Visited; 2543 SmallVector<const SDNode *, 8> Worklist; 2544 SmallVector<SDValue, 3> InputChains; 2545 unsigned int Max = 8192; 2546 2547 // Quick exit on trivial merge. 2548 if (ChainNodesMatched.size() == 1) 2549 return ChainNodesMatched[0]->getOperand(0); 2550 2551 // Add chains that aren't already added (internal). Peek through 2552 // token factors. 2553 std::function<void(const SDValue)> AddChains = [&](const SDValue V) { 2554 if (V.getValueType() != MVT::Other) 2555 return; 2556 if (V->getOpcode() == ISD::EntryToken) 2557 return; 2558 if (!Visited.insert(V.getNode()).second) 2559 return; 2560 if (V->getOpcode() == ISD::TokenFactor) { 2561 for (const SDValue &Op : V->op_values()) 2562 AddChains(Op); 2563 } else 2564 InputChains.push_back(V); 2565 }; 2566 2567 for (auto *N : ChainNodesMatched) { 2568 Worklist.push_back(N); 2569 Visited.insert(N); 2570 } 2571 2572 while (!Worklist.empty()) 2573 AddChains(Worklist.pop_back_val()->getOperand(0)); 2574 2575 // Skip the search if there are no chain dependencies. 2576 if (InputChains.size() == 0) 2577 return CurDAG->getEntryNode(); 2578 2579 // If one of these chains is a successor of input, we must have a 2580 // node that is both the predecessor and successor of the 2581 // to-be-merged nodes. Fail. 2582 Visited.clear(); 2583 for (SDValue V : InputChains) 2584 Worklist.push_back(V.getNode()); 2585 2586 for (auto *N : ChainNodesMatched) 2587 if (SDNode::hasPredecessorHelper(N, Visited, Worklist, Max, true)) 2588 return SDValue(); 2589 2590 // Return merged chain. 2591 if (InputChains.size() == 1) 2592 return InputChains[0]; 2593 return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]), 2594 MVT::Other, InputChains); 2595 } 2596 2597 /// MorphNode - Handle morphing a node in place for the selector. 2598 SDNode *SelectionDAGISel:: 2599 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList, 2600 ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) { 2601 // It is possible we're using MorphNodeTo to replace a node with no 2602 // normal results with one that has a normal result (or we could be 2603 // adding a chain) and the input could have glue and chains as well. 2604 // In this case we need to shift the operands down. 2605 // FIXME: This is a horrible hack and broken in obscure cases, no worse 2606 // than the old isel though. 2607 int OldGlueResultNo = -1, OldChainResultNo = -1; 2608 2609 unsigned NTMNumResults = Node->getNumValues(); 2610 if (Node->getValueType(NTMNumResults-1) == MVT::Glue) { 2611 OldGlueResultNo = NTMNumResults-1; 2612 if (NTMNumResults != 1 && 2613 Node->getValueType(NTMNumResults-2) == MVT::Other) 2614 OldChainResultNo = NTMNumResults-2; 2615 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other) 2616 OldChainResultNo = NTMNumResults-1; 2617 2618 // Call the underlying SelectionDAG routine to do the transmogrification. Note 2619 // that this deletes operands of the old node that become dead. 2620 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops); 2621 2622 // MorphNodeTo can operate in two ways: if an existing node with the 2623 // specified operands exists, it can just return it. Otherwise, it 2624 // updates the node in place to have the requested operands. 2625 if (Res == Node) { 2626 // If we updated the node in place, reset the node ID. To the isel, 2627 // this should be just like a newly allocated machine node. 2628 Res->setNodeId(-1); 2629 } 2630 2631 unsigned ResNumResults = Res->getNumValues(); 2632 // Move the glue if needed. 2633 if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 && 2634 (unsigned)OldGlueResultNo != ResNumResults-1) 2635 ReplaceUses(SDValue(Node, OldGlueResultNo), 2636 SDValue(Res, ResNumResults - 1)); 2637 2638 if ((EmitNodeInfo & OPFL_GlueOutput) != 0) 2639 --ResNumResults; 2640 2641 // Move the chain reference if needed. 2642 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 && 2643 (unsigned)OldChainResultNo != ResNumResults-1) 2644 ReplaceUses(SDValue(Node, OldChainResultNo), 2645 SDValue(Res, ResNumResults - 1)); 2646 2647 // Otherwise, no replacement happened because the node already exists. Replace 2648 // Uses of the old node with the new one. 2649 if (Res != Node) { 2650 ReplaceNode(Node, Res); 2651 } else { 2652 EnforceNodeIdInvariant(Res); 2653 } 2654 2655 return Res; 2656 } 2657 2658 /// CheckSame - Implements OP_CheckSame. 2659 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2660 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2661 SDValue N, 2662 const SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) { 2663 // Accept if it is exactly the same as a previously recorded node. 2664 unsigned RecNo = MatcherTable[MatcherIndex++]; 2665 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame"); 2666 return N == RecordedNodes[RecNo].first; 2667 } 2668 2669 /// CheckChildSame - Implements OP_CheckChildXSame. 2670 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2671 CheckChildSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2672 SDValue N, 2673 const SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes, 2674 unsigned ChildNo) { 2675 if (ChildNo >= N.getNumOperands()) 2676 return false; // Match fails if out of range child #. 2677 return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo), 2678 RecordedNodes); 2679 } 2680 2681 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate. 2682 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2683 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2684 const SelectionDAGISel &SDISel) { 2685 return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]); 2686 } 2687 2688 /// CheckNodePredicate - Implements OP_CheckNodePredicate. 2689 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2690 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2691 const SelectionDAGISel &SDISel, SDNode *N) { 2692 return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]); 2693 } 2694 2695 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2696 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2697 SDNode *N) { 2698 uint16_t Opc = MatcherTable[MatcherIndex++]; 2699 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8; 2700 return N->getOpcode() == Opc; 2701 } 2702 2703 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2704 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, 2705 const TargetLowering *TLI, const DataLayout &DL) { 2706 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 2707 if (N.getValueType() == VT) return true; 2708 2709 // Handle the case when VT is iPTR. 2710 return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL); 2711 } 2712 2713 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2714 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2715 SDValue N, const TargetLowering *TLI, const DataLayout &DL, 2716 unsigned ChildNo) { 2717 if (ChildNo >= N.getNumOperands()) 2718 return false; // Match fails if out of range child #. 2719 return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI, 2720 DL); 2721 } 2722 2723 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2724 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2725 SDValue N) { 2726 return cast<CondCodeSDNode>(N)->get() == 2727 (ISD::CondCode)MatcherTable[MatcherIndex++]; 2728 } 2729 2730 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2731 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2732 SDValue N, const TargetLowering *TLI, const DataLayout &DL) { 2733 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 2734 if (cast<VTSDNode>(N)->getVT() == VT) 2735 return true; 2736 2737 // Handle the case when VT is iPTR. 2738 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL); 2739 } 2740 2741 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2742 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2743 SDValue N) { 2744 int64_t Val = MatcherTable[MatcherIndex++]; 2745 if (Val & 128) 2746 Val = GetVBR(Val, MatcherTable, MatcherIndex); 2747 2748 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N); 2749 return C && C->getSExtValue() == Val; 2750 } 2751 2752 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2753 CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2754 SDValue N, unsigned ChildNo) { 2755 if (ChildNo >= N.getNumOperands()) 2756 return false; // Match fails if out of range child #. 2757 return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo)); 2758 } 2759 2760 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2761 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2762 SDValue N, const SelectionDAGISel &SDISel) { 2763 int64_t Val = MatcherTable[MatcherIndex++]; 2764 if (Val & 128) 2765 Val = GetVBR(Val, MatcherTable, MatcherIndex); 2766 2767 if (N->getOpcode() != ISD::AND) return false; 2768 2769 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 2770 return C && SDISel.CheckAndMask(N.getOperand(0), C, Val); 2771 } 2772 2773 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool 2774 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, 2775 SDValue N, const SelectionDAGISel &SDISel) { 2776 int64_t Val = MatcherTable[MatcherIndex++]; 2777 if (Val & 128) 2778 Val = GetVBR(Val, MatcherTable, MatcherIndex); 2779 2780 if (N->getOpcode() != ISD::OR) return false; 2781 2782 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 2783 return C && SDISel.CheckOrMask(N.getOperand(0), C, Val); 2784 } 2785 2786 /// IsPredicateKnownToFail - If we know how and can do so without pushing a 2787 /// scope, evaluate the current node. If the current predicate is known to 2788 /// fail, set Result=true and return anything. If the current predicate is 2789 /// known to pass, set Result=false and return the MatcherIndex to continue 2790 /// with. If the current predicate is unknown, set Result=false and return the 2791 /// MatcherIndex to continue with. 2792 static unsigned IsPredicateKnownToFail(const unsigned char *Table, 2793 unsigned Index, SDValue N, 2794 bool &Result, 2795 const SelectionDAGISel &SDISel, 2796 SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) { 2797 switch (Table[Index++]) { 2798 default: 2799 Result = false; 2800 return Index-1; // Could not evaluate this predicate. 2801 case SelectionDAGISel::OPC_CheckSame: 2802 Result = !::CheckSame(Table, Index, N, RecordedNodes); 2803 return Index; 2804 case SelectionDAGISel::OPC_CheckChild0Same: 2805 case SelectionDAGISel::OPC_CheckChild1Same: 2806 case SelectionDAGISel::OPC_CheckChild2Same: 2807 case SelectionDAGISel::OPC_CheckChild3Same: 2808 Result = !::CheckChildSame(Table, Index, N, RecordedNodes, 2809 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Same); 2810 return Index; 2811 case SelectionDAGISel::OPC_CheckPatternPredicate: 2812 Result = !::CheckPatternPredicate(Table, Index, SDISel); 2813 return Index; 2814 case SelectionDAGISel::OPC_CheckPredicate: 2815 Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode()); 2816 return Index; 2817 case SelectionDAGISel::OPC_CheckOpcode: 2818 Result = !::CheckOpcode(Table, Index, N.getNode()); 2819 return Index; 2820 case SelectionDAGISel::OPC_CheckType: 2821 Result = !::CheckType(Table, Index, N, SDISel.TLI, 2822 SDISel.CurDAG->getDataLayout()); 2823 return Index; 2824 case SelectionDAGISel::OPC_CheckTypeRes: { 2825 unsigned Res = Table[Index++]; 2826 Result = !::CheckType(Table, Index, N.getValue(Res), SDISel.TLI, 2827 SDISel.CurDAG->getDataLayout()); 2828 return Index; 2829 } 2830 case SelectionDAGISel::OPC_CheckChild0Type: 2831 case SelectionDAGISel::OPC_CheckChild1Type: 2832 case SelectionDAGISel::OPC_CheckChild2Type: 2833 case SelectionDAGISel::OPC_CheckChild3Type: 2834 case SelectionDAGISel::OPC_CheckChild4Type: 2835 case SelectionDAGISel::OPC_CheckChild5Type: 2836 case SelectionDAGISel::OPC_CheckChild6Type: 2837 case SelectionDAGISel::OPC_CheckChild7Type: 2838 Result = !::CheckChildType( 2839 Table, Index, N, SDISel.TLI, SDISel.CurDAG->getDataLayout(), 2840 Table[Index - 1] - SelectionDAGISel::OPC_CheckChild0Type); 2841 return Index; 2842 case SelectionDAGISel::OPC_CheckCondCode: 2843 Result = !::CheckCondCode(Table, Index, N); 2844 return Index; 2845 case SelectionDAGISel::OPC_CheckValueType: 2846 Result = !::CheckValueType(Table, Index, N, SDISel.TLI, 2847 SDISel.CurDAG->getDataLayout()); 2848 return Index; 2849 case SelectionDAGISel::OPC_CheckInteger: 2850 Result = !::CheckInteger(Table, Index, N); 2851 return Index; 2852 case SelectionDAGISel::OPC_CheckChild0Integer: 2853 case SelectionDAGISel::OPC_CheckChild1Integer: 2854 case SelectionDAGISel::OPC_CheckChild2Integer: 2855 case SelectionDAGISel::OPC_CheckChild3Integer: 2856 case SelectionDAGISel::OPC_CheckChild4Integer: 2857 Result = !::CheckChildInteger(Table, Index, N, 2858 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Integer); 2859 return Index; 2860 case SelectionDAGISel::OPC_CheckAndImm: 2861 Result = !::CheckAndImm(Table, Index, N, SDISel); 2862 return Index; 2863 case SelectionDAGISel::OPC_CheckOrImm: 2864 Result = !::CheckOrImm(Table, Index, N, SDISel); 2865 return Index; 2866 } 2867 } 2868 2869 namespace { 2870 2871 struct MatchScope { 2872 /// FailIndex - If this match fails, this is the index to continue with. 2873 unsigned FailIndex; 2874 2875 /// NodeStack - The node stack when the scope was formed. 2876 SmallVector<SDValue, 4> NodeStack; 2877 2878 /// NumRecordedNodes - The number of recorded nodes when the scope was formed. 2879 unsigned NumRecordedNodes; 2880 2881 /// NumMatchedMemRefs - The number of matched memref entries. 2882 unsigned NumMatchedMemRefs; 2883 2884 /// InputChain/InputGlue - The current chain/glue 2885 SDValue InputChain, InputGlue; 2886 2887 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty. 2888 bool HasChainNodesMatched; 2889 }; 2890 2891 /// \A DAG update listener to keep the matching state 2892 /// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to 2893 /// change the DAG while matching. X86 addressing mode matcher is an example 2894 /// for this. 2895 class MatchStateUpdater : public SelectionDAG::DAGUpdateListener 2896 { 2897 SDNode **NodeToMatch; 2898 SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes; 2899 SmallVectorImpl<MatchScope> &MatchScopes; 2900 2901 public: 2902 MatchStateUpdater(SelectionDAG &DAG, SDNode **NodeToMatch, 2903 SmallVectorImpl<std::pair<SDValue, SDNode *>> &RN, 2904 SmallVectorImpl<MatchScope> &MS) 2905 : SelectionDAG::DAGUpdateListener(DAG), NodeToMatch(NodeToMatch), 2906 RecordedNodes(RN), MatchScopes(MS) {} 2907 2908 void NodeDeleted(SDNode *N, SDNode *E) override { 2909 // Some early-returns here to avoid the search if we deleted the node or 2910 // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we 2911 // do, so it's unnecessary to update matching state at that point). 2912 // Neither of these can occur currently because we only install this 2913 // update listener during matching a complex patterns. 2914 if (!E || E->isMachineOpcode()) 2915 return; 2916 // Check if NodeToMatch was updated. 2917 if (N == *NodeToMatch) 2918 *NodeToMatch = E; 2919 // Performing linear search here does not matter because we almost never 2920 // run this code. You'd have to have a CSE during complex pattern 2921 // matching. 2922 for (auto &I : RecordedNodes) 2923 if (I.first.getNode() == N) 2924 I.first.setNode(E); 2925 2926 for (auto &I : MatchScopes) 2927 for (auto &J : I.NodeStack) 2928 if (J.getNode() == N) 2929 J.setNode(E); 2930 } 2931 }; 2932 2933 } // end anonymous namespace 2934 2935 void SelectionDAGISel::SelectCodeCommon(SDNode *NodeToMatch, 2936 const unsigned char *MatcherTable, 2937 unsigned TableSize) { 2938 // FIXME: Should these even be selected? Handle these cases in the caller? 2939 switch (NodeToMatch->getOpcode()) { 2940 default: 2941 break; 2942 case ISD::EntryToken: // These nodes remain the same. 2943 case ISD::BasicBlock: 2944 case ISD::Register: 2945 case ISD::RegisterMask: 2946 case ISD::HANDLENODE: 2947 case ISD::MDNODE_SDNODE: 2948 case ISD::TargetConstant: 2949 case ISD::TargetConstantFP: 2950 case ISD::TargetConstantPool: 2951 case ISD::TargetFrameIndex: 2952 case ISD::TargetExternalSymbol: 2953 case ISD::MCSymbol: 2954 case ISD::TargetBlockAddress: 2955 case ISD::TargetJumpTable: 2956 case ISD::TargetGlobalTLSAddress: 2957 case ISD::TargetGlobalAddress: 2958 case ISD::TokenFactor: 2959 case ISD::CopyFromReg: 2960 case ISD::CopyToReg: 2961 case ISD::EH_LABEL: 2962 case ISD::ANNOTATION_LABEL: 2963 case ISD::LIFETIME_START: 2964 case ISD::LIFETIME_END: 2965 NodeToMatch->setNodeId(-1); // Mark selected. 2966 return; 2967 case ISD::AssertSext: 2968 case ISD::AssertZext: 2969 ReplaceUses(SDValue(NodeToMatch, 0), NodeToMatch->getOperand(0)); 2970 CurDAG->RemoveDeadNode(NodeToMatch); 2971 return; 2972 case ISD::INLINEASM: 2973 Select_INLINEASM(NodeToMatch); 2974 return; 2975 case ISD::READ_REGISTER: 2976 Select_READ_REGISTER(NodeToMatch); 2977 return; 2978 case ISD::WRITE_REGISTER: 2979 Select_WRITE_REGISTER(NodeToMatch); 2980 return; 2981 case ISD::UNDEF: 2982 Select_UNDEF(NodeToMatch); 2983 return; 2984 } 2985 2986 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!"); 2987 2988 // Set up the node stack with NodeToMatch as the only node on the stack. 2989 SmallVector<SDValue, 8> NodeStack; 2990 SDValue N = SDValue(NodeToMatch, 0); 2991 NodeStack.push_back(N); 2992 2993 // MatchScopes - Scopes used when matching, if a match failure happens, this 2994 // indicates where to continue checking. 2995 SmallVector<MatchScope, 8> MatchScopes; 2996 2997 // RecordedNodes - This is the set of nodes that have been recorded by the 2998 // state machine. The second value is the parent of the node, or null if the 2999 // root is recorded. 3000 SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes; 3001 3002 // MatchedMemRefs - This is the set of MemRef's we've seen in the input 3003 // pattern. 3004 SmallVector<MachineMemOperand*, 2> MatchedMemRefs; 3005 3006 // These are the current input chain and glue for use when generating nodes. 3007 // Various Emit operations change these. For example, emitting a copytoreg 3008 // uses and updates these. 3009 SDValue InputChain, InputGlue; 3010 3011 // ChainNodesMatched - If a pattern matches nodes that have input/output 3012 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates 3013 // which ones they are. The result is captured into this list so that we can 3014 // update the chain results when the pattern is complete. 3015 SmallVector<SDNode*, 3> ChainNodesMatched; 3016 3017 LLVM_DEBUG(dbgs() << "ISEL: Starting pattern match\n"); 3018 3019 // Determine where to start the interpreter. Normally we start at opcode #0, 3020 // but if the state machine starts with an OPC_SwitchOpcode, then we 3021 // accelerate the first lookup (which is guaranteed to be hot) with the 3022 // OpcodeOffset table. 3023 unsigned MatcherIndex = 0; 3024 3025 if (!OpcodeOffset.empty()) { 3026 // Already computed the OpcodeOffset table, just index into it. 3027 if (N.getOpcode() < OpcodeOffset.size()) 3028 MatcherIndex = OpcodeOffset[N.getOpcode()]; 3029 LLVM_DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n"); 3030 3031 } else if (MatcherTable[0] == OPC_SwitchOpcode) { 3032 // Otherwise, the table isn't computed, but the state machine does start 3033 // with an OPC_SwitchOpcode instruction. Populate the table now, since this 3034 // is the first time we're selecting an instruction. 3035 unsigned Idx = 1; 3036 while (true) { 3037 // Get the size of this case. 3038 unsigned CaseSize = MatcherTable[Idx++]; 3039 if (CaseSize & 128) 3040 CaseSize = GetVBR(CaseSize, MatcherTable, Idx); 3041 if (CaseSize == 0) break; 3042 3043 // Get the opcode, add the index to the table. 3044 uint16_t Opc = MatcherTable[Idx++]; 3045 Opc |= (unsigned short)MatcherTable[Idx++] << 8; 3046 if (Opc >= OpcodeOffset.size()) 3047 OpcodeOffset.resize((Opc+1)*2); 3048 OpcodeOffset[Opc] = Idx; 3049 Idx += CaseSize; 3050 } 3051 3052 // Okay, do the lookup for the first opcode. 3053 if (N.getOpcode() < OpcodeOffset.size()) 3054 MatcherIndex = OpcodeOffset[N.getOpcode()]; 3055 } 3056 3057 while (true) { 3058 assert(MatcherIndex < TableSize && "Invalid index"); 3059 #ifndef NDEBUG 3060 unsigned CurrentOpcodeIndex = MatcherIndex; 3061 #endif 3062 BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++]; 3063 switch (Opcode) { 3064 case OPC_Scope: { 3065 // Okay, the semantics of this operation are that we should push a scope 3066 // then evaluate the first child. However, pushing a scope only to have 3067 // the first check fail (which then pops it) is inefficient. If we can 3068 // determine immediately that the first check (or first several) will 3069 // immediately fail, don't even bother pushing a scope for them. 3070 unsigned FailIndex; 3071 3072 while (true) { 3073 unsigned NumToSkip = MatcherTable[MatcherIndex++]; 3074 if (NumToSkip & 128) 3075 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex); 3076 // Found the end of the scope with no match. 3077 if (NumToSkip == 0) { 3078 FailIndex = 0; 3079 break; 3080 } 3081 3082 FailIndex = MatcherIndex+NumToSkip; 3083 3084 unsigned MatcherIndexOfPredicate = MatcherIndex; 3085 (void)MatcherIndexOfPredicate; // silence warning. 3086 3087 // If we can't evaluate this predicate without pushing a scope (e.g. if 3088 // it is a 'MoveParent') or if the predicate succeeds on this node, we 3089 // push the scope and evaluate the full predicate chain. 3090 bool Result; 3091 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N, 3092 Result, *this, RecordedNodes); 3093 if (!Result) 3094 break; 3095 3096 LLVM_DEBUG( 3097 dbgs() << " Skipped scope entry (due to false predicate) at " 3098 << "index " << MatcherIndexOfPredicate << ", continuing at " 3099 << FailIndex << "\n"); 3100 ++NumDAGIselRetries; 3101 3102 // Otherwise, we know that this case of the Scope is guaranteed to fail, 3103 // move to the next case. 3104 MatcherIndex = FailIndex; 3105 } 3106 3107 // If the whole scope failed to match, bail. 3108 if (FailIndex == 0) break; 3109 3110 // Push a MatchScope which indicates where to go if the first child fails 3111 // to match. 3112 MatchScope NewEntry; 3113 NewEntry.FailIndex = FailIndex; 3114 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end()); 3115 NewEntry.NumRecordedNodes = RecordedNodes.size(); 3116 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size(); 3117 NewEntry.InputChain = InputChain; 3118 NewEntry.InputGlue = InputGlue; 3119 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty(); 3120 MatchScopes.push_back(NewEntry); 3121 continue; 3122 } 3123 case OPC_RecordNode: { 3124 // Remember this node, it may end up being an operand in the pattern. 3125 SDNode *Parent = nullptr; 3126 if (NodeStack.size() > 1) 3127 Parent = NodeStack[NodeStack.size()-2].getNode(); 3128 RecordedNodes.push_back(std::make_pair(N, Parent)); 3129 continue; 3130 } 3131 3132 case OPC_RecordChild0: case OPC_RecordChild1: 3133 case OPC_RecordChild2: case OPC_RecordChild3: 3134 case OPC_RecordChild4: case OPC_RecordChild5: 3135 case OPC_RecordChild6: case OPC_RecordChild7: { 3136 unsigned ChildNo = Opcode-OPC_RecordChild0; 3137 if (ChildNo >= N.getNumOperands()) 3138 break; // Match fails if out of range child #. 3139 3140 RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo), 3141 N.getNode())); 3142 continue; 3143 } 3144 case OPC_RecordMemRef: 3145 if (auto *MN = dyn_cast<MemSDNode>(N)) 3146 MatchedMemRefs.push_back(MN->getMemOperand()); 3147 else { 3148 LLVM_DEBUG(dbgs() << "Expected MemSDNode "; N->dump(CurDAG); 3149 dbgs() << '\n'); 3150 } 3151 3152 continue; 3153 3154 case OPC_CaptureGlueInput: 3155 // If the current node has an input glue, capture it in InputGlue. 3156 if (N->getNumOperands() != 0 && 3157 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) 3158 InputGlue = N->getOperand(N->getNumOperands()-1); 3159 continue; 3160 3161 case OPC_MoveChild: { 3162 unsigned ChildNo = MatcherTable[MatcherIndex++]; 3163 if (ChildNo >= N.getNumOperands()) 3164 break; // Match fails if out of range child #. 3165 N = N.getOperand(ChildNo); 3166 NodeStack.push_back(N); 3167 continue; 3168 } 3169 3170 case OPC_MoveChild0: case OPC_MoveChild1: 3171 case OPC_MoveChild2: case OPC_MoveChild3: 3172 case OPC_MoveChild4: case OPC_MoveChild5: 3173 case OPC_MoveChild6: case OPC_MoveChild7: { 3174 unsigned ChildNo = Opcode-OPC_MoveChild0; 3175 if (ChildNo >= N.getNumOperands()) 3176 break; // Match fails if out of range child #. 3177 N = N.getOperand(ChildNo); 3178 NodeStack.push_back(N); 3179 continue; 3180 } 3181 3182 case OPC_MoveParent: 3183 // Pop the current node off the NodeStack. 3184 NodeStack.pop_back(); 3185 assert(!NodeStack.empty() && "Node stack imbalance!"); 3186 N = NodeStack.back(); 3187 continue; 3188 3189 case OPC_CheckSame: 3190 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break; 3191 continue; 3192 3193 case OPC_CheckChild0Same: case OPC_CheckChild1Same: 3194 case OPC_CheckChild2Same: case OPC_CheckChild3Same: 3195 if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes, 3196 Opcode-OPC_CheckChild0Same)) 3197 break; 3198 continue; 3199 3200 case OPC_CheckPatternPredicate: 3201 if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break; 3202 continue; 3203 case OPC_CheckPredicate: 3204 if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this, 3205 N.getNode())) 3206 break; 3207 continue; 3208 case OPC_CheckComplexPat: { 3209 unsigned CPNum = MatcherTable[MatcherIndex++]; 3210 unsigned RecNo = MatcherTable[MatcherIndex++]; 3211 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat"); 3212 3213 // If target can modify DAG during matching, keep the matching state 3214 // consistent. 3215 std::unique_ptr<MatchStateUpdater> MSU; 3216 if (ComplexPatternFuncMutatesDAG()) 3217 MSU.reset(new MatchStateUpdater(*CurDAG, &NodeToMatch, RecordedNodes, 3218 MatchScopes)); 3219 3220 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second, 3221 RecordedNodes[RecNo].first, CPNum, 3222 RecordedNodes)) 3223 break; 3224 continue; 3225 } 3226 case OPC_CheckOpcode: 3227 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break; 3228 continue; 3229 3230 case OPC_CheckType: 3231 if (!::CheckType(MatcherTable, MatcherIndex, N, TLI, 3232 CurDAG->getDataLayout())) 3233 break; 3234 continue; 3235 3236 case OPC_CheckTypeRes: { 3237 unsigned Res = MatcherTable[MatcherIndex++]; 3238 if (!::CheckType(MatcherTable, MatcherIndex, N.getValue(Res), TLI, 3239 CurDAG->getDataLayout())) 3240 break; 3241 continue; 3242 } 3243 3244 case OPC_SwitchOpcode: { 3245 unsigned CurNodeOpcode = N.getOpcode(); 3246 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart; 3247 unsigned CaseSize; 3248 while (true) { 3249 // Get the size of this case. 3250 CaseSize = MatcherTable[MatcherIndex++]; 3251 if (CaseSize & 128) 3252 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex); 3253 if (CaseSize == 0) break; 3254 3255 uint16_t Opc = MatcherTable[MatcherIndex++]; 3256 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8; 3257 3258 // If the opcode matches, then we will execute this case. 3259 if (CurNodeOpcode == Opc) 3260 break; 3261 3262 // Otherwise, skip over this case. 3263 MatcherIndex += CaseSize; 3264 } 3265 3266 // If no cases matched, bail out. 3267 if (CaseSize == 0) break; 3268 3269 // Otherwise, execute the case we found. 3270 LLVM_DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart << " to " 3271 << MatcherIndex << "\n"); 3272 continue; 3273 } 3274 3275 case OPC_SwitchType: { 3276 MVT CurNodeVT = N.getSimpleValueType(); 3277 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart; 3278 unsigned CaseSize; 3279 while (true) { 3280 // Get the size of this case. 3281 CaseSize = MatcherTable[MatcherIndex++]; 3282 if (CaseSize & 128) 3283 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex); 3284 if (CaseSize == 0) break; 3285 3286 MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 3287 if (CaseVT == MVT::iPTR) 3288 CaseVT = TLI->getPointerTy(CurDAG->getDataLayout()); 3289 3290 // If the VT matches, then we will execute this case. 3291 if (CurNodeVT == CaseVT) 3292 break; 3293 3294 // Otherwise, skip over this case. 3295 MatcherIndex += CaseSize; 3296 } 3297 3298 // If no cases matched, bail out. 3299 if (CaseSize == 0) break; 3300 3301 // Otherwise, execute the case we found. 3302 LLVM_DEBUG(dbgs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString() 3303 << "] from " << SwitchStart << " to " << MatcherIndex 3304 << '\n'); 3305 continue; 3306 } 3307 case OPC_CheckChild0Type: case OPC_CheckChild1Type: 3308 case OPC_CheckChild2Type: case OPC_CheckChild3Type: 3309 case OPC_CheckChild4Type: case OPC_CheckChild5Type: 3310 case OPC_CheckChild6Type: case OPC_CheckChild7Type: 3311 if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI, 3312 CurDAG->getDataLayout(), 3313 Opcode - OPC_CheckChild0Type)) 3314 break; 3315 continue; 3316 case OPC_CheckCondCode: 3317 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break; 3318 continue; 3319 case OPC_CheckValueType: 3320 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI, 3321 CurDAG->getDataLayout())) 3322 break; 3323 continue; 3324 case OPC_CheckInteger: 3325 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break; 3326 continue; 3327 case OPC_CheckChild0Integer: case OPC_CheckChild1Integer: 3328 case OPC_CheckChild2Integer: case OPC_CheckChild3Integer: 3329 case OPC_CheckChild4Integer: 3330 if (!::CheckChildInteger(MatcherTable, MatcherIndex, N, 3331 Opcode-OPC_CheckChild0Integer)) break; 3332 continue; 3333 case OPC_CheckAndImm: 3334 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break; 3335 continue; 3336 case OPC_CheckOrImm: 3337 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break; 3338 continue; 3339 3340 case OPC_CheckFoldableChainNode: { 3341 assert(NodeStack.size() != 1 && "No parent node"); 3342 // Verify that all intermediate nodes between the root and this one have 3343 // a single use. 3344 bool HasMultipleUses = false; 3345 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i) 3346 if (!NodeStack[i].getNode()->hasOneUse()) { 3347 HasMultipleUses = true; 3348 break; 3349 } 3350 if (HasMultipleUses) break; 3351 3352 // Check to see that the target thinks this is profitable to fold and that 3353 // we can fold it without inducing cycles in the graph. 3354 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(), 3355 NodeToMatch) || 3356 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(), 3357 NodeToMatch, OptLevel, 3358 true/*We validate our own chains*/)) 3359 break; 3360 3361 continue; 3362 } 3363 case OPC_EmitInteger: { 3364 MVT::SimpleValueType VT = 3365 (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 3366 int64_t Val = MatcherTable[MatcherIndex++]; 3367 if (Val & 128) 3368 Val = GetVBR(Val, MatcherTable, MatcherIndex); 3369 RecordedNodes.push_back(std::pair<SDValue, SDNode*>( 3370 CurDAG->getTargetConstant(Val, SDLoc(NodeToMatch), 3371 VT), nullptr)); 3372 continue; 3373 } 3374 case OPC_EmitRegister: { 3375 MVT::SimpleValueType VT = 3376 (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 3377 unsigned RegNo = MatcherTable[MatcherIndex++]; 3378 RecordedNodes.push_back(std::pair<SDValue, SDNode*>( 3379 CurDAG->getRegister(RegNo, VT), nullptr)); 3380 continue; 3381 } 3382 case OPC_EmitRegister2: { 3383 // For targets w/ more than 256 register names, the register enum 3384 // values are stored in two bytes in the matcher table (just like 3385 // opcodes). 3386 MVT::SimpleValueType VT = 3387 (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 3388 unsigned RegNo = MatcherTable[MatcherIndex++]; 3389 RegNo |= MatcherTable[MatcherIndex++] << 8; 3390 RecordedNodes.push_back(std::pair<SDValue, SDNode*>( 3391 CurDAG->getRegister(RegNo, VT), nullptr)); 3392 continue; 3393 } 3394 3395 case OPC_EmitConvertToTarget: { 3396 // Convert from IMM/FPIMM to target version. 3397 unsigned RecNo = MatcherTable[MatcherIndex++]; 3398 assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget"); 3399 SDValue Imm = RecordedNodes[RecNo].first; 3400 3401 if (Imm->getOpcode() == ISD::Constant) { 3402 const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue(); 3403 Imm = CurDAG->getTargetConstant(*Val, SDLoc(NodeToMatch), 3404 Imm.getValueType()); 3405 } else if (Imm->getOpcode() == ISD::ConstantFP) { 3406 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue(); 3407 Imm = CurDAG->getTargetConstantFP(*Val, SDLoc(NodeToMatch), 3408 Imm.getValueType()); 3409 } 3410 3411 RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second)); 3412 continue; 3413 } 3414 3415 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0 3416 case OPC_EmitMergeInputChains1_1: // OPC_EmitMergeInputChains, 1, 1 3417 case OPC_EmitMergeInputChains1_2: { // OPC_EmitMergeInputChains, 1, 2 3418 // These are space-optimized forms of OPC_EmitMergeInputChains. 3419 assert(!InputChain.getNode() && 3420 "EmitMergeInputChains should be the first chain producing node"); 3421 assert(ChainNodesMatched.empty() && 3422 "Should only have one EmitMergeInputChains per match"); 3423 3424 // Read all of the chained nodes. 3425 unsigned RecNo = Opcode - OPC_EmitMergeInputChains1_0; 3426 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains"); 3427 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode()); 3428 3429 // FIXME: What if other value results of the node have uses not matched 3430 // by this pattern? 3431 if (ChainNodesMatched.back() != NodeToMatch && 3432 !RecordedNodes[RecNo].first.hasOneUse()) { 3433 ChainNodesMatched.clear(); 3434 break; 3435 } 3436 3437 // Merge the input chains if they are not intra-pattern references. 3438 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG); 3439 3440 if (!InputChain.getNode()) 3441 break; // Failed to merge. 3442 continue; 3443 } 3444 3445 case OPC_EmitMergeInputChains: { 3446 assert(!InputChain.getNode() && 3447 "EmitMergeInputChains should be the first chain producing node"); 3448 // This node gets a list of nodes we matched in the input that have 3449 // chains. We want to token factor all of the input chains to these nodes 3450 // together. However, if any of the input chains is actually one of the 3451 // nodes matched in this pattern, then we have an intra-match reference. 3452 // Ignore these because the newly token factored chain should not refer to 3453 // the old nodes. 3454 unsigned NumChains = MatcherTable[MatcherIndex++]; 3455 assert(NumChains != 0 && "Can't TF zero chains"); 3456 3457 assert(ChainNodesMatched.empty() && 3458 "Should only have one EmitMergeInputChains per match"); 3459 3460 // Read all of the chained nodes. 3461 for (unsigned i = 0; i != NumChains; ++i) { 3462 unsigned RecNo = MatcherTable[MatcherIndex++]; 3463 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains"); 3464 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode()); 3465 3466 // FIXME: What if other value results of the node have uses not matched 3467 // by this pattern? 3468 if (ChainNodesMatched.back() != NodeToMatch && 3469 !RecordedNodes[RecNo].first.hasOneUse()) { 3470 ChainNodesMatched.clear(); 3471 break; 3472 } 3473 } 3474 3475 // If the inner loop broke out, the match fails. 3476 if (ChainNodesMatched.empty()) 3477 break; 3478 3479 // Merge the input chains if they are not intra-pattern references. 3480 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG); 3481 3482 if (!InputChain.getNode()) 3483 break; // Failed to merge. 3484 3485 continue; 3486 } 3487 3488 case OPC_EmitCopyToReg: { 3489 unsigned RecNo = MatcherTable[MatcherIndex++]; 3490 assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg"); 3491 unsigned DestPhysReg = MatcherTable[MatcherIndex++]; 3492 3493 if (!InputChain.getNode()) 3494 InputChain = CurDAG->getEntryNode(); 3495 3496 InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch), 3497 DestPhysReg, RecordedNodes[RecNo].first, 3498 InputGlue); 3499 3500 InputGlue = InputChain.getValue(1); 3501 continue; 3502 } 3503 3504 case OPC_EmitNodeXForm: { 3505 unsigned XFormNo = MatcherTable[MatcherIndex++]; 3506 unsigned RecNo = MatcherTable[MatcherIndex++]; 3507 assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm"); 3508 SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo); 3509 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr)); 3510 continue; 3511 } 3512 case OPC_Coverage: { 3513 // This is emitted right before MorphNode/EmitNode. 3514 // So it should be safe to assume that this node has been selected 3515 unsigned index = MatcherTable[MatcherIndex++]; 3516 index |= (MatcherTable[MatcherIndex++] << 8); 3517 dbgs() << "COVERED: " << getPatternForIndex(index) << "\n"; 3518 dbgs() << "INCLUDED: " << getIncludePathForIndex(index) << "\n"; 3519 continue; 3520 } 3521 3522 case OPC_EmitNode: case OPC_MorphNodeTo: 3523 case OPC_EmitNode0: case OPC_EmitNode1: case OPC_EmitNode2: 3524 case OPC_MorphNodeTo0: case OPC_MorphNodeTo1: case OPC_MorphNodeTo2: { 3525 uint16_t TargetOpc = MatcherTable[MatcherIndex++]; 3526 TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8; 3527 unsigned EmitNodeInfo = MatcherTable[MatcherIndex++]; 3528 // Get the result VT list. 3529 unsigned NumVTs; 3530 // If this is one of the compressed forms, get the number of VTs based 3531 // on the Opcode. Otherwise read the next byte from the table. 3532 if (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2) 3533 NumVTs = Opcode - OPC_MorphNodeTo0; 3534 else if (Opcode >= OPC_EmitNode0 && Opcode <= OPC_EmitNode2) 3535 NumVTs = Opcode - OPC_EmitNode0; 3536 else 3537 NumVTs = MatcherTable[MatcherIndex++]; 3538 SmallVector<EVT, 4> VTs; 3539 for (unsigned i = 0; i != NumVTs; ++i) { 3540 MVT::SimpleValueType VT = 3541 (MVT::SimpleValueType)MatcherTable[MatcherIndex++]; 3542 if (VT == MVT::iPTR) 3543 VT = TLI->getPointerTy(CurDAG->getDataLayout()).SimpleTy; 3544 VTs.push_back(VT); 3545 } 3546 3547 if (EmitNodeInfo & OPFL_Chain) 3548 VTs.push_back(MVT::Other); 3549 if (EmitNodeInfo & OPFL_GlueOutput) 3550 VTs.push_back(MVT::Glue); 3551 3552 // This is hot code, so optimize the two most common cases of 1 and 2 3553 // results. 3554 SDVTList VTList; 3555 if (VTs.size() == 1) 3556 VTList = CurDAG->getVTList(VTs[0]); 3557 else if (VTs.size() == 2) 3558 VTList = CurDAG->getVTList(VTs[0], VTs[1]); 3559 else 3560 VTList = CurDAG->getVTList(VTs); 3561 3562 // Get the operand list. 3563 unsigned NumOps = MatcherTable[MatcherIndex++]; 3564 SmallVector<SDValue, 8> Ops; 3565 for (unsigned i = 0; i != NumOps; ++i) { 3566 unsigned RecNo = MatcherTable[MatcherIndex++]; 3567 if (RecNo & 128) 3568 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex); 3569 3570 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode"); 3571 Ops.push_back(RecordedNodes[RecNo].first); 3572 } 3573 3574 // If there are variadic operands to add, handle them now. 3575 if (EmitNodeInfo & OPFL_VariadicInfo) { 3576 // Determine the start index to copy from. 3577 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo); 3578 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0; 3579 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy && 3580 "Invalid variadic node"); 3581 // Copy all of the variadic operands, not including a potential glue 3582 // input. 3583 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands(); 3584 i != e; ++i) { 3585 SDValue V = NodeToMatch->getOperand(i); 3586 if (V.getValueType() == MVT::Glue) break; 3587 Ops.push_back(V); 3588 } 3589 } 3590 3591 // If this has chain/glue inputs, add them. 3592 if (EmitNodeInfo & OPFL_Chain) 3593 Ops.push_back(InputChain); 3594 if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr) 3595 Ops.push_back(InputGlue); 3596 3597 // Create the node. 3598 MachineSDNode *Res = nullptr; 3599 bool IsMorphNodeTo = Opcode == OPC_MorphNodeTo || 3600 (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2); 3601 if (!IsMorphNodeTo) { 3602 // If this is a normal EmitNode command, just create the new node and 3603 // add the results to the RecordedNodes list. 3604 Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch), 3605 VTList, Ops); 3606 3607 // Add all the non-glue/non-chain results to the RecordedNodes list. 3608 for (unsigned i = 0, e = VTs.size(); i != e; ++i) { 3609 if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break; 3610 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i), 3611 nullptr)); 3612 } 3613 } else { 3614 assert(NodeToMatch->getOpcode() != ISD::DELETED_NODE && 3615 "NodeToMatch was removed partway through selection"); 3616 SelectionDAG::DAGNodeDeletedListener NDL(*CurDAG, [&](SDNode *N, 3617 SDNode *E) { 3618 CurDAG->salvageDebugInfo(*N); 3619 auto &Chain = ChainNodesMatched; 3620 assert((!E || !is_contained(Chain, N)) && 3621 "Chain node replaced during MorphNode"); 3622 Chain.erase(std::remove(Chain.begin(), Chain.end(), N), Chain.end()); 3623 }); 3624 Res = cast<MachineSDNode>(MorphNode(NodeToMatch, TargetOpc, VTList, 3625 Ops, EmitNodeInfo)); 3626 } 3627 3628 // If the node had chain/glue results, update our notion of the current 3629 // chain and glue. 3630 if (EmitNodeInfo & OPFL_GlueOutput) { 3631 InputGlue = SDValue(Res, VTs.size()-1); 3632 if (EmitNodeInfo & OPFL_Chain) 3633 InputChain = SDValue(Res, VTs.size()-2); 3634 } else if (EmitNodeInfo & OPFL_Chain) 3635 InputChain = SDValue(Res, VTs.size()-1); 3636 3637 // If the OPFL_MemRefs glue is set on this node, slap all of the 3638 // accumulated memrefs onto it. 3639 // 3640 // FIXME: This is vastly incorrect for patterns with multiple outputs 3641 // instructions that access memory and for ComplexPatterns that match 3642 // loads. 3643 if (EmitNodeInfo & OPFL_MemRefs) { 3644 // Only attach load or store memory operands if the generated 3645 // instruction may load or store. 3646 const MCInstrDesc &MCID = TII->get(TargetOpc); 3647 bool mayLoad = MCID.mayLoad(); 3648 bool mayStore = MCID.mayStore(); 3649 3650 // We expect to have relatively few of these so just filter them into a 3651 // temporary buffer so that we can easily add them to the instruction. 3652 SmallVector<MachineMemOperand *, 4> FilteredMemRefs; 3653 for (MachineMemOperand *MMO : MatchedMemRefs) { 3654 if (MMO->isLoad()) { 3655 if (mayLoad) 3656 FilteredMemRefs.push_back(MMO); 3657 } else if (MMO->isStore()) { 3658 if (mayStore) 3659 FilteredMemRefs.push_back(MMO); 3660 } else { 3661 FilteredMemRefs.push_back(MMO); 3662 } 3663 } 3664 3665 CurDAG->setNodeMemRefs(Res, FilteredMemRefs); 3666 } 3667 3668 LLVM_DEBUG(if (!MatchedMemRefs.empty() && Res->memoperands_empty()) dbgs() 3669 << " Dropping mem operands\n"; 3670 dbgs() << " " << (IsMorphNodeTo ? "Morphed" : "Created") 3671 << " node: "; 3672 Res->dump(CurDAG);); 3673 3674 // If this was a MorphNodeTo then we're completely done! 3675 if (IsMorphNodeTo) { 3676 // Update chain uses. 3677 UpdateChains(Res, InputChain, ChainNodesMatched, true); 3678 return; 3679 } 3680 continue; 3681 } 3682 3683 case OPC_CompleteMatch: { 3684 // The match has been completed, and any new nodes (if any) have been 3685 // created. Patch up references to the matched dag to use the newly 3686 // created nodes. 3687 unsigned NumResults = MatcherTable[MatcherIndex++]; 3688 3689 for (unsigned i = 0; i != NumResults; ++i) { 3690 unsigned ResSlot = MatcherTable[MatcherIndex++]; 3691 if (ResSlot & 128) 3692 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex); 3693 3694 assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch"); 3695 SDValue Res = RecordedNodes[ResSlot].first; 3696 3697 assert(i < NodeToMatch->getNumValues() && 3698 NodeToMatch->getValueType(i) != MVT::Other && 3699 NodeToMatch->getValueType(i) != MVT::Glue && 3700 "Invalid number of results to complete!"); 3701 assert((NodeToMatch->getValueType(i) == Res.getValueType() || 3702 NodeToMatch->getValueType(i) == MVT::iPTR || 3703 Res.getValueType() == MVT::iPTR || 3704 NodeToMatch->getValueType(i).getSizeInBits() == 3705 Res.getValueSizeInBits()) && 3706 "invalid replacement"); 3707 ReplaceUses(SDValue(NodeToMatch, i), Res); 3708 } 3709 3710 // Update chain uses. 3711 UpdateChains(NodeToMatch, InputChain, ChainNodesMatched, false); 3712 3713 // If the root node defines glue, we need to update it to the glue result. 3714 // TODO: This never happens in our tests and I think it can be removed / 3715 // replaced with an assert, but if we do it this the way the change is 3716 // NFC. 3717 if (NodeToMatch->getValueType(NodeToMatch->getNumValues() - 1) == 3718 MVT::Glue && 3719 InputGlue.getNode()) 3720 ReplaceUses(SDValue(NodeToMatch, NodeToMatch->getNumValues() - 1), 3721 InputGlue); 3722 3723 assert(NodeToMatch->use_empty() && 3724 "Didn't replace all uses of the node?"); 3725 CurDAG->RemoveDeadNode(NodeToMatch); 3726 3727 return; 3728 } 3729 } 3730 3731 // If the code reached this point, then the match failed. See if there is 3732 // another child to try in the current 'Scope', otherwise pop it until we 3733 // find a case to check. 3734 LLVM_DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex 3735 << "\n"); 3736 ++NumDAGIselRetries; 3737 while (true) { 3738 if (MatchScopes.empty()) { 3739 CannotYetSelect(NodeToMatch); 3740 return; 3741 } 3742 3743 // Restore the interpreter state back to the point where the scope was 3744 // formed. 3745 MatchScope &LastScope = MatchScopes.back(); 3746 RecordedNodes.resize(LastScope.NumRecordedNodes); 3747 NodeStack.clear(); 3748 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end()); 3749 N = NodeStack.back(); 3750 3751 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size()) 3752 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs); 3753 MatcherIndex = LastScope.FailIndex; 3754 3755 LLVM_DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n"); 3756 3757 InputChain = LastScope.InputChain; 3758 InputGlue = LastScope.InputGlue; 3759 if (!LastScope.HasChainNodesMatched) 3760 ChainNodesMatched.clear(); 3761 3762 // Check to see what the offset is at the new MatcherIndex. If it is zero 3763 // we have reached the end of this scope, otherwise we have another child 3764 // in the current scope to try. 3765 unsigned NumToSkip = MatcherTable[MatcherIndex++]; 3766 if (NumToSkip & 128) 3767 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex); 3768 3769 // If we have another child in this scope to match, update FailIndex and 3770 // try it. 3771 if (NumToSkip != 0) { 3772 LastScope.FailIndex = MatcherIndex+NumToSkip; 3773 break; 3774 } 3775 3776 // End of this scope, pop it and try the next child in the containing 3777 // scope. 3778 MatchScopes.pop_back(); 3779 } 3780 } 3781 } 3782 3783 bool SelectionDAGISel::isOrEquivalentToAdd(const SDNode *N) const { 3784 assert(N->getOpcode() == ISD::OR && "Unexpected opcode"); 3785 auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1)); 3786 if (!C) 3787 return false; 3788 3789 // Detect when "or" is used to add an offset to a stack object. 3790 if (auto *FN = dyn_cast<FrameIndexSDNode>(N->getOperand(0))) { 3791 MachineFrameInfo &MFI = MF->getFrameInfo(); 3792 unsigned A = MFI.getObjectAlignment(FN->getIndex()); 3793 assert(isPowerOf2_32(A) && "Unexpected alignment"); 3794 int32_t Off = C->getSExtValue(); 3795 // If the alleged offset fits in the zero bits guaranteed by 3796 // the alignment, then this or is really an add. 3797 return (Off >= 0) && (((A - 1) & Off) == unsigned(Off)); 3798 } 3799 return false; 3800 } 3801 3802 void SelectionDAGISel::CannotYetSelect(SDNode *N) { 3803 std::string msg; 3804 raw_string_ostream Msg(msg); 3805 Msg << "Cannot select: "; 3806 3807 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN && 3808 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN && 3809 N->getOpcode() != ISD::INTRINSIC_VOID) { 3810 N->printrFull(Msg, CurDAG); 3811 Msg << "\nIn function: " << MF->getName(); 3812 } else { 3813 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other; 3814 unsigned iid = 3815 cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue(); 3816 if (iid < Intrinsic::num_intrinsics) 3817 Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid, None); 3818 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo()) 3819 Msg << "target intrinsic %" << TII->getName(iid); 3820 else 3821 Msg << "unknown intrinsic #" << iid; 3822 } 3823 report_fatal_error(Msg.str()); 3824 } 3825 3826 char SelectionDAGISel::ID = 0; 3827