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