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