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