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