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