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