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