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