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