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