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