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