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