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