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