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