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