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