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