xref: /freebsd/contrib/llvm-project/llvm/lib/CodeGen/SelectionDAG/SelectionDAGISel.cpp (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
10b57cec5SDimitry Andric //===- SelectionDAGISel.cpp - Implement the SelectionDAGISel class --------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This implements the SelectionDAGISel class.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "llvm/CodeGen/SelectionDAGISel.h"
140b57cec5SDimitry Andric #include "ScheduleDAGSDNodes.h"
150b57cec5SDimitry Andric #include "SelectionDAGBuilder.h"
160b57cec5SDimitry Andric #include "llvm/ADT/APInt.h"
170b57cec5SDimitry Andric #include "llvm/ADT/DenseMap.h"
180b57cec5SDimitry Andric #include "llvm/ADT/None.h"
190b57cec5SDimitry Andric #include "llvm/ADT/PostOrderIterator.h"
200b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
210b57cec5SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
220b57cec5SDimitry Andric #include "llvm/ADT/SmallSet.h"
230b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
240b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
250b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
260b57cec5SDimitry Andric #include "llvm/Analysis/AliasAnalysis.h"
270b57cec5SDimitry Andric #include "llvm/Analysis/BranchProbabilityInfo.h"
280b57cec5SDimitry Andric #include "llvm/Analysis/CFG.h"
290b57cec5SDimitry Andric #include "llvm/Analysis/EHPersonalities.h"
30480093f4SDimitry Andric #include "llvm/Analysis/LazyBlockFrequencyInfo.h"
318bcb0991SDimitry Andric #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
320b57cec5SDimitry Andric #include "llvm/Analysis/OptimizationRemarkEmitter.h"
33480093f4SDimitry Andric #include "llvm/Analysis/ProfileSummaryInfo.h"
340b57cec5SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
350b57cec5SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
360b57cec5SDimitry Andric #include "llvm/CodeGen/FastISel.h"
370b57cec5SDimitry Andric #include "llvm/CodeGen/FunctionLoweringInfo.h"
380b57cec5SDimitry Andric #include "llvm/CodeGen/GCMetadata.h"
390b57cec5SDimitry Andric #include "llvm/CodeGen/ISDOpcodes.h"
400b57cec5SDimitry Andric #include "llvm/CodeGen/MachineBasicBlock.h"
410b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFrameInfo.h"
420b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunction.h"
430b57cec5SDimitry Andric #include "llvm/CodeGen/MachineFunctionPass.h"
440b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstr.h"
450b57cec5SDimitry Andric #include "llvm/CodeGen/MachineInstrBuilder.h"
460b57cec5SDimitry Andric #include "llvm/CodeGen/MachineMemOperand.h"
470b57cec5SDimitry Andric #include "llvm/CodeGen/MachineModuleInfo.h"
480b57cec5SDimitry Andric #include "llvm/CodeGen/MachineOperand.h"
490b57cec5SDimitry Andric #include "llvm/CodeGen/MachinePassRegistry.h"
500b57cec5SDimitry Andric #include "llvm/CodeGen/MachineRegisterInfo.h"
510b57cec5SDimitry Andric #include "llvm/CodeGen/SchedulerRegistry.h"
520b57cec5SDimitry Andric #include "llvm/CodeGen/SelectionDAG.h"
530b57cec5SDimitry Andric #include "llvm/CodeGen/SelectionDAGNodes.h"
540b57cec5SDimitry Andric #include "llvm/CodeGen/StackProtector.h"
550b57cec5SDimitry Andric #include "llvm/CodeGen/SwiftErrorValueTracking.h"
560b57cec5SDimitry Andric #include "llvm/CodeGen/TargetInstrInfo.h"
570b57cec5SDimitry Andric #include "llvm/CodeGen/TargetLowering.h"
580b57cec5SDimitry Andric #include "llvm/CodeGen/TargetRegisterInfo.h"
590b57cec5SDimitry Andric #include "llvm/CodeGen/TargetSubtargetInfo.h"
600b57cec5SDimitry Andric #include "llvm/CodeGen/ValueTypes.h"
610b57cec5SDimitry Andric #include "llvm/IR/BasicBlock.h"
620b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
630b57cec5SDimitry Andric #include "llvm/IR/DataLayout.h"
640b57cec5SDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
650b57cec5SDimitry Andric #include "llvm/IR/DebugLoc.h"
660b57cec5SDimitry Andric #include "llvm/IR/DiagnosticInfo.h"
670b57cec5SDimitry Andric #include "llvm/IR/Dominators.h"
680b57cec5SDimitry Andric #include "llvm/IR/Function.h"
690b57cec5SDimitry Andric #include "llvm/IR/InlineAsm.h"
700b57cec5SDimitry Andric #include "llvm/IR/InstIterator.h"
710b57cec5SDimitry Andric #include "llvm/IR/InstrTypes.h"
720b57cec5SDimitry Andric #include "llvm/IR/Instruction.h"
730b57cec5SDimitry Andric #include "llvm/IR/Instructions.h"
740b57cec5SDimitry Andric #include "llvm/IR/IntrinsicInst.h"
750b57cec5SDimitry Andric #include "llvm/IR/Intrinsics.h"
76480093f4SDimitry Andric #include "llvm/IR/IntrinsicsWebAssembly.h"
770b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
78*e8d8bef9SDimitry Andric #include "llvm/IR/Statepoint.h"
790b57cec5SDimitry Andric #include "llvm/IR/Type.h"
800b57cec5SDimitry Andric #include "llvm/IR/User.h"
810b57cec5SDimitry Andric #include "llvm/IR/Value.h"
82480093f4SDimitry Andric #include "llvm/InitializePasses.h"
830b57cec5SDimitry Andric #include "llvm/MC/MCInstrDesc.h"
840b57cec5SDimitry Andric #include "llvm/MC/MCRegisterInfo.h"
850b57cec5SDimitry Andric #include "llvm/Pass.h"
860b57cec5SDimitry Andric #include "llvm/Support/BranchProbability.h"
870b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
880b57cec5SDimitry Andric #include "llvm/Support/CodeGen.h"
890b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
900b57cec5SDimitry Andric #include "llvm/Support/Compiler.h"
910b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
920b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
930b57cec5SDimitry Andric #include "llvm/Support/KnownBits.h"
940b57cec5SDimitry Andric #include "llvm/Support/MachineValueType.h"
950b57cec5SDimitry Andric #include "llvm/Support/Timer.h"
960b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
970b57cec5SDimitry Andric #include "llvm/Target/TargetIntrinsicInfo.h"
980b57cec5SDimitry Andric #include "llvm/Target/TargetMachine.h"
990b57cec5SDimitry Andric #include "llvm/Target/TargetOptions.h"
1000b57cec5SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
1010b57cec5SDimitry Andric #include <algorithm>
1020b57cec5SDimitry Andric #include <cassert>
1030b57cec5SDimitry Andric #include <cstdint>
1040b57cec5SDimitry Andric #include <iterator>
1050b57cec5SDimitry Andric #include <limits>
1060b57cec5SDimitry Andric #include <memory>
1070b57cec5SDimitry Andric #include <string>
1080b57cec5SDimitry Andric #include <utility>
1090b57cec5SDimitry Andric #include <vector>
1100b57cec5SDimitry Andric 
1110b57cec5SDimitry Andric using namespace llvm;
1120b57cec5SDimitry Andric 
1130b57cec5SDimitry Andric #define DEBUG_TYPE "isel"
1140b57cec5SDimitry Andric 
1150b57cec5SDimitry Andric STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
1160b57cec5SDimitry Andric STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
1170b57cec5SDimitry Andric STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
1180b57cec5SDimitry Andric STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
1190b57cec5SDimitry Andric STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
1200b57cec5SDimitry Andric STATISTIC(NumEntryBlocks, "Number of entry blocks encountered");
1210b57cec5SDimitry Andric STATISTIC(NumFastIselFailLowerArguments,
1220b57cec5SDimitry Andric           "Number of entry blocks where fast isel failed to lower arguments");
1230b57cec5SDimitry Andric 
1240b57cec5SDimitry Andric static cl::opt<int> EnableFastISelAbort(
1250b57cec5SDimitry Andric     "fast-isel-abort", cl::Hidden,
1260b57cec5SDimitry Andric     cl::desc("Enable abort calls when \"fast\" instruction selection "
1270b57cec5SDimitry Andric              "fails to lower an instruction: 0 disable the abort, 1 will "
1280b57cec5SDimitry Andric              "abort but for args, calls and terminators, 2 will also "
1290b57cec5SDimitry Andric              "abort for argument lowering, and 3 will never fallback "
1300b57cec5SDimitry Andric              "to SelectionDAG."));
1310b57cec5SDimitry Andric 
1320b57cec5SDimitry Andric static cl::opt<bool> EnableFastISelFallbackReport(
1330b57cec5SDimitry Andric     "fast-isel-report-on-fallback", cl::Hidden,
1340b57cec5SDimitry Andric     cl::desc("Emit a diagnostic when \"fast\" instruction selection "
1350b57cec5SDimitry Andric              "falls back to SelectionDAG."));
1360b57cec5SDimitry Andric 
1370b57cec5SDimitry Andric static cl::opt<bool>
1380b57cec5SDimitry Andric UseMBPI("use-mbpi",
1390b57cec5SDimitry Andric         cl::desc("use Machine Branch Probability Info"),
1400b57cec5SDimitry Andric         cl::init(true), cl::Hidden);
1410b57cec5SDimitry Andric 
1420b57cec5SDimitry Andric #ifndef NDEBUG
1430b57cec5SDimitry Andric static cl::opt<std::string>
1440b57cec5SDimitry Andric FilterDAGBasicBlockName("filter-view-dags", cl::Hidden,
1450b57cec5SDimitry Andric                         cl::desc("Only display the basic block whose name "
1460b57cec5SDimitry Andric                                  "matches this for all view-*-dags options"));
1470b57cec5SDimitry Andric static cl::opt<bool>
1480b57cec5SDimitry Andric ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
1490b57cec5SDimitry Andric           cl::desc("Pop up a window to show dags before the first "
1500b57cec5SDimitry Andric                    "dag combine pass"));
1510b57cec5SDimitry Andric static cl::opt<bool>
1520b57cec5SDimitry Andric ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
1530b57cec5SDimitry Andric           cl::desc("Pop up a window to show dags before legalize types"));
1540b57cec5SDimitry Andric static cl::opt<bool>
155480093f4SDimitry Andric     ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
156480093f4SDimitry Andric                      cl::desc("Pop up a window to show dags before the post "
157480093f4SDimitry Andric                               "legalize types dag combine pass"));
158480093f4SDimitry Andric static cl::opt<bool>
1590b57cec5SDimitry Andric     ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
1600b57cec5SDimitry Andric                      cl::desc("Pop up a window to show dags before legalize"));
1610b57cec5SDimitry Andric static cl::opt<bool>
1620b57cec5SDimitry Andric ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
1630b57cec5SDimitry Andric           cl::desc("Pop up a window to show dags before the second "
1640b57cec5SDimitry Andric                    "dag combine pass"));
1650b57cec5SDimitry Andric static cl::opt<bool>
1660b57cec5SDimitry Andric ViewISelDAGs("view-isel-dags", cl::Hidden,
1670b57cec5SDimitry Andric           cl::desc("Pop up a window to show isel dags as they are selected"));
1680b57cec5SDimitry Andric static cl::opt<bool>
1690b57cec5SDimitry Andric ViewSchedDAGs("view-sched-dags", cl::Hidden,
1700b57cec5SDimitry Andric           cl::desc("Pop up a window to show sched dags as they are processed"));
1710b57cec5SDimitry Andric static cl::opt<bool>
1720b57cec5SDimitry Andric ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
1730b57cec5SDimitry Andric       cl::desc("Pop up a window to show SUnit dags after they are processed"));
1740b57cec5SDimitry Andric #else
175480093f4SDimitry Andric static const bool ViewDAGCombine1 = false, ViewLegalizeTypesDAGs = false,
176480093f4SDimitry Andric                   ViewDAGCombineLT = false, ViewLegalizeDAGs = false,
177480093f4SDimitry Andric                   ViewDAGCombine2 = false, ViewISelDAGs = false,
178480093f4SDimitry Andric                   ViewSchedDAGs = false, ViewSUnitDAGs = false;
1790b57cec5SDimitry Andric #endif
1800b57cec5SDimitry Andric 
1810b57cec5SDimitry Andric //===---------------------------------------------------------------------===//
1820b57cec5SDimitry Andric ///
1830b57cec5SDimitry Andric /// RegisterScheduler class - Track the registration of instruction schedulers.
1840b57cec5SDimitry Andric ///
1850b57cec5SDimitry Andric //===---------------------------------------------------------------------===//
1860b57cec5SDimitry Andric MachinePassRegistry<RegisterScheduler::FunctionPassCtor>
1870b57cec5SDimitry Andric     RegisterScheduler::Registry;
1880b57cec5SDimitry Andric 
1890b57cec5SDimitry Andric //===---------------------------------------------------------------------===//
1900b57cec5SDimitry Andric ///
1910b57cec5SDimitry Andric /// ISHeuristic command line option for instruction schedulers.
1920b57cec5SDimitry Andric ///
1930b57cec5SDimitry Andric //===---------------------------------------------------------------------===//
1940b57cec5SDimitry Andric static cl::opt<RegisterScheduler::FunctionPassCtor, false,
1950b57cec5SDimitry Andric                RegisterPassParser<RegisterScheduler>>
1960b57cec5SDimitry Andric ISHeuristic("pre-RA-sched",
1970b57cec5SDimitry Andric             cl::init(&createDefaultScheduler), cl::Hidden,
1980b57cec5SDimitry Andric             cl::desc("Instruction schedulers available (before register"
1990b57cec5SDimitry Andric                      " allocation):"));
2000b57cec5SDimitry Andric 
2010b57cec5SDimitry Andric static RegisterScheduler
2020b57cec5SDimitry Andric defaultListDAGScheduler("default", "Best scheduler for the target",
2030b57cec5SDimitry Andric                         createDefaultScheduler);
2040b57cec5SDimitry Andric 
2050b57cec5SDimitry Andric namespace llvm {
2060b57cec5SDimitry Andric 
2070b57cec5SDimitry Andric   //===--------------------------------------------------------------------===//
2080b57cec5SDimitry Andric   /// This class is used by SelectionDAGISel to temporarily override
2090b57cec5SDimitry Andric   /// the optimization level on a per-function basis.
2100b57cec5SDimitry Andric   class OptLevelChanger {
2110b57cec5SDimitry Andric     SelectionDAGISel &IS;
2120b57cec5SDimitry Andric     CodeGenOpt::Level SavedOptLevel;
2130b57cec5SDimitry Andric     bool SavedFastISel;
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric   public:
2160b57cec5SDimitry Andric     OptLevelChanger(SelectionDAGISel &ISel,
2170b57cec5SDimitry Andric                     CodeGenOpt::Level NewOptLevel) : IS(ISel) {
2180b57cec5SDimitry Andric       SavedOptLevel = IS.OptLevel;
2195ffd83dbSDimitry Andric       SavedFastISel = IS.TM.Options.EnableFastISel;
2200b57cec5SDimitry Andric       if (NewOptLevel == SavedOptLevel)
2210b57cec5SDimitry Andric         return;
2220b57cec5SDimitry Andric       IS.OptLevel = NewOptLevel;
2230b57cec5SDimitry Andric       IS.TM.setOptLevel(NewOptLevel);
2240b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\nChanging optimization level for Function "
2250b57cec5SDimitry Andric                         << IS.MF->getFunction().getName() << "\n");
2260b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\tBefore: -O" << SavedOptLevel << " ; After: -O"
2270b57cec5SDimitry Andric                         << NewOptLevel << "\n");
2280b57cec5SDimitry Andric       if (NewOptLevel == CodeGenOpt::None) {
2290b57cec5SDimitry Andric         IS.TM.setFastISel(IS.TM.getO0WantsFastISel());
2300b57cec5SDimitry Andric         LLVM_DEBUG(
2310b57cec5SDimitry Andric             dbgs() << "\tFastISel is "
2320b57cec5SDimitry Andric                    << (IS.TM.Options.EnableFastISel ? "enabled" : "disabled")
2330b57cec5SDimitry Andric                    << "\n");
2340b57cec5SDimitry Andric       }
2350b57cec5SDimitry Andric     }
2360b57cec5SDimitry Andric 
2370b57cec5SDimitry Andric     ~OptLevelChanger() {
2380b57cec5SDimitry Andric       if (IS.OptLevel == SavedOptLevel)
2390b57cec5SDimitry Andric         return;
2400b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\nRestoring optimization level for Function "
2410b57cec5SDimitry Andric                         << IS.MF->getFunction().getName() << "\n");
2420b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\tBefore: -O" << IS.OptLevel << " ; After: -O"
2430b57cec5SDimitry Andric                         << SavedOptLevel << "\n");
2440b57cec5SDimitry Andric       IS.OptLevel = SavedOptLevel;
2450b57cec5SDimitry Andric       IS.TM.setOptLevel(SavedOptLevel);
2460b57cec5SDimitry Andric       IS.TM.setFastISel(SavedFastISel);
2470b57cec5SDimitry Andric     }
2480b57cec5SDimitry Andric   };
2490b57cec5SDimitry Andric 
2500b57cec5SDimitry Andric   //===--------------------------------------------------------------------===//
2510b57cec5SDimitry Andric   /// createDefaultScheduler - This creates an instruction scheduler appropriate
2520b57cec5SDimitry Andric   /// for the target.
2530b57cec5SDimitry Andric   ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
2540b57cec5SDimitry Andric                                              CodeGenOpt::Level OptLevel) {
2550b57cec5SDimitry Andric     const TargetLowering *TLI = IS->TLI;
2560b57cec5SDimitry Andric     const TargetSubtargetInfo &ST = IS->MF->getSubtarget();
2570b57cec5SDimitry Andric 
2580b57cec5SDimitry Andric     // Try first to see if the Target has its own way of selecting a scheduler
2590b57cec5SDimitry Andric     if (auto *SchedulerCtor = ST.getDAGScheduler(OptLevel)) {
2600b57cec5SDimitry Andric       return SchedulerCtor(IS, OptLevel);
2610b57cec5SDimitry Andric     }
2620b57cec5SDimitry Andric 
2630b57cec5SDimitry Andric     if (OptLevel == CodeGenOpt::None ||
2640b57cec5SDimitry Andric         (ST.enableMachineScheduler() && ST.enableMachineSchedDefaultSched()) ||
2650b57cec5SDimitry Andric         TLI->getSchedulingPreference() == Sched::Source)
2660b57cec5SDimitry Andric       return createSourceListDAGScheduler(IS, OptLevel);
2670b57cec5SDimitry Andric     if (TLI->getSchedulingPreference() == Sched::RegPressure)
2680b57cec5SDimitry Andric       return createBURRListDAGScheduler(IS, OptLevel);
2690b57cec5SDimitry Andric     if (TLI->getSchedulingPreference() == Sched::Hybrid)
2700b57cec5SDimitry Andric       return createHybridListDAGScheduler(IS, OptLevel);
2710b57cec5SDimitry Andric     if (TLI->getSchedulingPreference() == Sched::VLIW)
2720b57cec5SDimitry Andric       return createVLIWDAGScheduler(IS, OptLevel);
2730b57cec5SDimitry Andric     assert(TLI->getSchedulingPreference() == Sched::ILP &&
2740b57cec5SDimitry Andric            "Unknown sched type!");
2750b57cec5SDimitry Andric     return createILPListDAGScheduler(IS, OptLevel);
2760b57cec5SDimitry Andric   }
2770b57cec5SDimitry Andric 
2780b57cec5SDimitry Andric } // end namespace llvm
2790b57cec5SDimitry Andric 
2800b57cec5SDimitry Andric // EmitInstrWithCustomInserter - This method should be implemented by targets
2810b57cec5SDimitry Andric // that mark instructions with the 'usesCustomInserter' flag.  These
2820b57cec5SDimitry Andric // instructions are special in various ways, which require special support to
2830b57cec5SDimitry Andric // insert.  The specified MachineInstr is created but not inserted into any
2840b57cec5SDimitry Andric // basic blocks, and this method is called to expand it into a sequence of
2850b57cec5SDimitry Andric // instructions, potentially also creating new basic blocks and control flow.
2860b57cec5SDimitry Andric // When new basic blocks are inserted and the edges from MBB to its successors
2870b57cec5SDimitry Andric // are modified, the method should insert pairs of <OldSucc, NewSucc> into the
2880b57cec5SDimitry Andric // DenseMap.
2890b57cec5SDimitry Andric MachineBasicBlock *
2900b57cec5SDimitry Andric TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
2910b57cec5SDimitry Andric                                             MachineBasicBlock *MBB) const {
2920b57cec5SDimitry Andric #ifndef NDEBUG
2930b57cec5SDimitry Andric   dbgs() << "If a target marks an instruction with "
2940b57cec5SDimitry Andric           "'usesCustomInserter', it must implement "
2950b57cec5SDimitry Andric           "TargetLowering::EmitInstrWithCustomInserter!";
2960b57cec5SDimitry Andric #endif
2970b57cec5SDimitry Andric   llvm_unreachable(nullptr);
2980b57cec5SDimitry Andric }
2990b57cec5SDimitry Andric 
3000b57cec5SDimitry Andric void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
3010b57cec5SDimitry Andric                                                    SDNode *Node) const {
3020b57cec5SDimitry Andric   assert(!MI.hasPostISelHook() &&
3030b57cec5SDimitry Andric          "If a target marks an instruction with 'hasPostISelHook', "
3040b57cec5SDimitry Andric          "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
3050b57cec5SDimitry Andric }
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
3080b57cec5SDimitry Andric // SelectionDAGISel code
3090b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
3100b57cec5SDimitry Andric 
311480093f4SDimitry Andric SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, CodeGenOpt::Level OL)
312480093f4SDimitry Andric     : MachineFunctionPass(ID), TM(tm), FuncInfo(new FunctionLoweringInfo()),
3130b57cec5SDimitry Andric       SwiftError(new SwiftErrorValueTracking()),
3140b57cec5SDimitry Andric       CurDAG(new SelectionDAG(tm, OL)),
315480093f4SDimitry Andric       SDB(std::make_unique<SelectionDAGBuilder>(*CurDAG, *FuncInfo, *SwiftError,
316480093f4SDimitry Andric                                                 OL)),
317480093f4SDimitry Andric       AA(), GFI(), OptLevel(OL), DAGSize(0) {
3180b57cec5SDimitry Andric   initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
3190b57cec5SDimitry Andric   initializeBranchProbabilityInfoWrapperPassPass(
3200b57cec5SDimitry Andric       *PassRegistry::getPassRegistry());
3210b57cec5SDimitry Andric   initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
322480093f4SDimitry Andric   initializeTargetLibraryInfoWrapperPassPass(*PassRegistry::getPassRegistry());
3230b57cec5SDimitry Andric }
3240b57cec5SDimitry Andric 
3250b57cec5SDimitry Andric SelectionDAGISel::~SelectionDAGISel() {
3260b57cec5SDimitry Andric   delete CurDAG;
3270b57cec5SDimitry Andric   delete SwiftError;
3280b57cec5SDimitry Andric }
3290b57cec5SDimitry Andric 
3300b57cec5SDimitry Andric void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
3310b57cec5SDimitry Andric   if (OptLevel != CodeGenOpt::None)
3320b57cec5SDimitry Andric     AU.addRequired<AAResultsWrapperPass>();
3330b57cec5SDimitry Andric   AU.addRequired<GCModuleInfo>();
3340b57cec5SDimitry Andric   AU.addRequired<StackProtector>();
3350b57cec5SDimitry Andric   AU.addPreserved<GCModuleInfo>();
3360b57cec5SDimitry Andric   AU.addRequired<TargetLibraryInfoWrapperPass>();
3370b57cec5SDimitry Andric   AU.addRequired<TargetTransformInfoWrapperPass>();
3380b57cec5SDimitry Andric   if (UseMBPI && OptLevel != CodeGenOpt::None)
3390b57cec5SDimitry Andric     AU.addRequired<BranchProbabilityInfoWrapperPass>();
340480093f4SDimitry Andric   AU.addRequired<ProfileSummaryInfoWrapperPass>();
3415ffd83dbSDimitry Andric   if (OptLevel != CodeGenOpt::None)
342480093f4SDimitry Andric     LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage(AU);
3430b57cec5SDimitry Andric   MachineFunctionPass::getAnalysisUsage(AU);
3440b57cec5SDimitry Andric }
3450b57cec5SDimitry Andric 
3460b57cec5SDimitry Andric /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that
3470b57cec5SDimitry Andric /// may trap on it.  In this case we have to split the edge so that the path
3480b57cec5SDimitry Andric /// through the predecessor block that doesn't go to the phi block doesn't
3490b57cec5SDimitry Andric /// execute the possibly trapping instruction. If available, we pass domtree
3500b57cec5SDimitry Andric /// and loop info to be updated when we split critical edges. This is because
3510b57cec5SDimitry Andric /// SelectionDAGISel preserves these analyses.
3520b57cec5SDimitry Andric /// This is required for correctness, so it must be done at -O0.
3530b57cec5SDimitry Andric ///
3540b57cec5SDimitry Andric static void SplitCriticalSideEffectEdges(Function &Fn, DominatorTree *DT,
3550b57cec5SDimitry Andric                                          LoopInfo *LI) {
3560b57cec5SDimitry Andric   // Loop for blocks with phi nodes.
3570b57cec5SDimitry Andric   for (BasicBlock &BB : Fn) {
3580b57cec5SDimitry Andric     PHINode *PN = dyn_cast<PHINode>(BB.begin());
3590b57cec5SDimitry Andric     if (!PN) continue;
3600b57cec5SDimitry Andric 
3610b57cec5SDimitry Andric   ReprocessBlock:
3620b57cec5SDimitry Andric     // For each block with a PHI node, check to see if any of the input values
3630b57cec5SDimitry Andric     // are potentially trapping constant expressions.  Constant expressions are
3640b57cec5SDimitry Andric     // the only potentially trapping value that can occur as the argument to a
3650b57cec5SDimitry Andric     // PHI.
3660b57cec5SDimitry Andric     for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I)); ++I)
3670b57cec5SDimitry Andric       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3680b57cec5SDimitry Andric         ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i));
3690b57cec5SDimitry Andric         if (!CE || !CE->canTrap()) continue;
3700b57cec5SDimitry Andric 
3710b57cec5SDimitry Andric         // The only case we have to worry about is when the edge is critical.
3720b57cec5SDimitry Andric         // Since this block has a PHI Node, we assume it has multiple input
3730b57cec5SDimitry Andric         // edges: check to see if the pred has multiple successors.
3740b57cec5SDimitry Andric         BasicBlock *Pred = PN->getIncomingBlock(i);
3750b57cec5SDimitry Andric         if (Pred->getTerminator()->getNumSuccessors() == 1)
3760b57cec5SDimitry Andric           continue;
3770b57cec5SDimitry Andric 
3780b57cec5SDimitry Andric         // Okay, we have to split this edge.
3790b57cec5SDimitry Andric         SplitCriticalEdge(
3800b57cec5SDimitry Andric             Pred->getTerminator(), GetSuccessorNumber(Pred, &BB),
3810b57cec5SDimitry Andric             CriticalEdgeSplittingOptions(DT, LI).setMergeIdenticalEdges());
3820b57cec5SDimitry Andric         goto ReprocessBlock;
3830b57cec5SDimitry Andric       }
3840b57cec5SDimitry Andric   }
3850b57cec5SDimitry Andric }
3860b57cec5SDimitry Andric 
3870b57cec5SDimitry Andric static void computeUsesMSVCFloatingPoint(const Triple &TT, const Function &F,
3880b57cec5SDimitry Andric                                          MachineModuleInfo &MMI) {
3890b57cec5SDimitry Andric   // Only needed for MSVC
3900b57cec5SDimitry Andric   if (!TT.isWindowsMSVCEnvironment())
3910b57cec5SDimitry Andric     return;
3920b57cec5SDimitry Andric 
3930b57cec5SDimitry Andric   // If it's already set, nothing to do.
3940b57cec5SDimitry Andric   if (MMI.usesMSVCFloatingPoint())
3950b57cec5SDimitry Andric     return;
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric   for (const Instruction &I : instructions(F)) {
3980b57cec5SDimitry Andric     if (I.getType()->isFPOrFPVectorTy()) {
3990b57cec5SDimitry Andric       MMI.setUsesMSVCFloatingPoint(true);
4000b57cec5SDimitry Andric       return;
4010b57cec5SDimitry Andric     }
4020b57cec5SDimitry Andric     for (const auto &Op : I.operands()) {
4030b57cec5SDimitry Andric       if (Op->getType()->isFPOrFPVectorTy()) {
4040b57cec5SDimitry Andric         MMI.setUsesMSVCFloatingPoint(true);
4050b57cec5SDimitry Andric         return;
4060b57cec5SDimitry Andric       }
4070b57cec5SDimitry Andric     }
4080b57cec5SDimitry Andric   }
4090b57cec5SDimitry Andric }
4100b57cec5SDimitry Andric 
4110b57cec5SDimitry Andric bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
4120b57cec5SDimitry Andric   // If we already selected that function, we do not need to run SDISel.
4130b57cec5SDimitry Andric   if (mf.getProperties().hasProperty(
4140b57cec5SDimitry Andric           MachineFunctionProperties::Property::Selected))
4150b57cec5SDimitry Andric     return false;
4160b57cec5SDimitry Andric   // Do some sanity-checking on the command-line options.
4170b57cec5SDimitry Andric   assert((!EnableFastISelAbort || TM.Options.EnableFastISel) &&
4180b57cec5SDimitry Andric          "-fast-isel-abort > 0 requires -fast-isel");
4190b57cec5SDimitry Andric 
4200b57cec5SDimitry Andric   const Function &Fn = mf.getFunction();
4210b57cec5SDimitry Andric   MF = &mf;
4220b57cec5SDimitry Andric 
4230b57cec5SDimitry Andric   // Reset the target options before resetting the optimization
4240b57cec5SDimitry Andric   // level below.
4250b57cec5SDimitry Andric   // FIXME: This is a horrible hack and should be processed via
4260b57cec5SDimitry Andric   // codegen looking at the optimization level explicitly when
4270b57cec5SDimitry Andric   // it wants to look at it.
4280b57cec5SDimitry Andric   TM.resetTargetOptions(Fn);
4290b57cec5SDimitry Andric   // Reset OptLevel to None for optnone functions.
4300b57cec5SDimitry Andric   CodeGenOpt::Level NewOptLevel = OptLevel;
4310b57cec5SDimitry Andric   if (OptLevel != CodeGenOpt::None && skipFunction(Fn))
4320b57cec5SDimitry Andric     NewOptLevel = CodeGenOpt::None;
4330b57cec5SDimitry Andric   OptLevelChanger OLC(*this, NewOptLevel);
4340b57cec5SDimitry Andric 
4350b57cec5SDimitry Andric   TII = MF->getSubtarget().getInstrInfo();
4360b57cec5SDimitry Andric   TLI = MF->getSubtarget().getTargetLowering();
4370b57cec5SDimitry Andric   RegInfo = &MF->getRegInfo();
4388bcb0991SDimitry Andric   LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(Fn);
4390b57cec5SDimitry Andric   GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : nullptr;
4408bcb0991SDimitry Andric   ORE = std::make_unique<OptimizationRemarkEmitter>(&Fn);
4410b57cec5SDimitry Andric   auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
4420b57cec5SDimitry Andric   DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
4430b57cec5SDimitry Andric   auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
4440b57cec5SDimitry Andric   LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
445480093f4SDimitry Andric   auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
4465ffd83dbSDimitry Andric   BlockFrequencyInfo *BFI = nullptr;
4475ffd83dbSDimitry Andric   if (PSI && PSI->hasProfileSummary() && OptLevel != CodeGenOpt::None)
4485ffd83dbSDimitry Andric     BFI = &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI();
4490b57cec5SDimitry Andric 
4500b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
4510b57cec5SDimitry Andric 
4520b57cec5SDimitry Andric   SplitCriticalSideEffectEdges(const_cast<Function &>(Fn), DT, LI);
4530b57cec5SDimitry Andric 
4540b57cec5SDimitry Andric   CurDAG->init(*MF, *ORE, this, LibInfo,
455480093f4SDimitry Andric                getAnalysisIfAvailable<LegacyDivergenceAnalysis>(), PSI, BFI);
4560b57cec5SDimitry Andric   FuncInfo->set(Fn, *MF, CurDAG);
4570b57cec5SDimitry Andric   SwiftError->setFunction(*MF);
4580b57cec5SDimitry Andric 
4590b57cec5SDimitry Andric   // Now get the optional analyzes if we want to.
4600b57cec5SDimitry Andric   // This is based on the possibly changed OptLevel (after optnone is taken
4610b57cec5SDimitry Andric   // into account).  That's unfortunate but OK because it just means we won't
4620b57cec5SDimitry Andric   // ask for passes that have been required anyway.
4630b57cec5SDimitry Andric 
4640b57cec5SDimitry Andric   if (UseMBPI && OptLevel != CodeGenOpt::None)
4650b57cec5SDimitry Andric     FuncInfo->BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
4660b57cec5SDimitry Andric   else
4670b57cec5SDimitry Andric     FuncInfo->BPI = nullptr;
4680b57cec5SDimitry Andric 
4690b57cec5SDimitry Andric   if (OptLevel != CodeGenOpt::None)
4700b57cec5SDimitry Andric     AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4710b57cec5SDimitry Andric   else
4720b57cec5SDimitry Andric     AA = nullptr;
4730b57cec5SDimitry Andric 
4740b57cec5SDimitry Andric   SDB->init(GFI, AA, LibInfo);
4750b57cec5SDimitry Andric 
4760b57cec5SDimitry Andric   MF->setHasInlineAsm(false);
4770b57cec5SDimitry Andric 
4780b57cec5SDimitry Andric   FuncInfo->SplitCSR = false;
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric   // We split CSR if the target supports it for the given function
4810b57cec5SDimitry Andric   // and the function has only return exits.
4820b57cec5SDimitry Andric   if (OptLevel != CodeGenOpt::None && TLI->supportSplitCSR(MF)) {
4830b57cec5SDimitry Andric     FuncInfo->SplitCSR = true;
4840b57cec5SDimitry Andric 
4850b57cec5SDimitry Andric     // Collect all the return blocks.
4860b57cec5SDimitry Andric     for (const BasicBlock &BB : Fn) {
4870b57cec5SDimitry Andric       if (!succ_empty(&BB))
4880b57cec5SDimitry Andric         continue;
4890b57cec5SDimitry Andric 
4900b57cec5SDimitry Andric       const Instruction *Term = BB.getTerminator();
4910b57cec5SDimitry Andric       if (isa<UnreachableInst>(Term) || isa<ReturnInst>(Term))
4920b57cec5SDimitry Andric         continue;
4930b57cec5SDimitry Andric 
4940b57cec5SDimitry Andric       // Bail out if the exit block is not Return nor Unreachable.
4950b57cec5SDimitry Andric       FuncInfo->SplitCSR = false;
4960b57cec5SDimitry Andric       break;
4970b57cec5SDimitry Andric     }
4980b57cec5SDimitry Andric   }
4990b57cec5SDimitry Andric 
5000b57cec5SDimitry Andric   MachineBasicBlock *EntryMBB = &MF->front();
5010b57cec5SDimitry Andric   if (FuncInfo->SplitCSR)
5020b57cec5SDimitry Andric     // This performs initialization so lowering for SplitCSR will be correct.
5030b57cec5SDimitry Andric     TLI->initializeSplitCSR(EntryMBB);
5040b57cec5SDimitry Andric 
5050b57cec5SDimitry Andric   SelectAllBasicBlocks(Fn);
5060b57cec5SDimitry Andric   if (FastISelFailed && EnableFastISelFallbackReport) {
5070b57cec5SDimitry Andric     DiagnosticInfoISelFallback DiagFallback(Fn);
5080b57cec5SDimitry Andric     Fn.getContext().diagnose(DiagFallback);
5090b57cec5SDimitry Andric   }
5100b57cec5SDimitry Andric 
5110b57cec5SDimitry Andric   // Replace forward-declared registers with the registers containing
5120b57cec5SDimitry Andric   // the desired value.
5130b57cec5SDimitry Andric   // Note: it is important that this happens **before** the call to
5140b57cec5SDimitry Andric   // EmitLiveInCopies, since implementations can skip copies of unused
5150b57cec5SDimitry Andric   // registers. If we don't apply the reg fixups before, some registers may
5160b57cec5SDimitry Andric   // appear as unused and will be skipped, resulting in bad MI.
5170b57cec5SDimitry Andric   MachineRegisterInfo &MRI = MF->getRegInfo();
5185ffd83dbSDimitry Andric   for (DenseMap<Register, Register>::iterator I = FuncInfo->RegFixups.begin(),
5190b57cec5SDimitry Andric                                               E = FuncInfo->RegFixups.end();
5200b57cec5SDimitry Andric        I != E; ++I) {
5215ffd83dbSDimitry Andric     Register From = I->first;
5225ffd83dbSDimitry Andric     Register To = I->second;
5230b57cec5SDimitry Andric     // If To is also scheduled to be replaced, find what its ultimate
5240b57cec5SDimitry Andric     // replacement is.
5250b57cec5SDimitry Andric     while (true) {
5265ffd83dbSDimitry Andric       DenseMap<Register, Register>::iterator J = FuncInfo->RegFixups.find(To);
5270b57cec5SDimitry Andric       if (J == E)
5280b57cec5SDimitry Andric         break;
5290b57cec5SDimitry Andric       To = J->second;
5300b57cec5SDimitry Andric     }
5310b57cec5SDimitry Andric     // Make sure the new register has a sufficiently constrained register class.
5328bcb0991SDimitry Andric     if (Register::isVirtualRegister(From) && Register::isVirtualRegister(To))
5330b57cec5SDimitry Andric       MRI.constrainRegClass(To, MRI.getRegClass(From));
5340b57cec5SDimitry Andric     // Replace it.
5350b57cec5SDimitry Andric 
5360b57cec5SDimitry Andric     // Replacing one register with another won't touch the kill flags.
5370b57cec5SDimitry Andric     // We need to conservatively clear the kill flags as a kill on the old
5380b57cec5SDimitry Andric     // register might dominate existing uses of the new register.
5390b57cec5SDimitry Andric     if (!MRI.use_empty(To))
5400b57cec5SDimitry Andric       MRI.clearKillFlags(From);
5410b57cec5SDimitry Andric     MRI.replaceRegWith(From, To);
5420b57cec5SDimitry Andric   }
5430b57cec5SDimitry Andric 
5440b57cec5SDimitry Andric   // If the first basic block in the function has live ins that need to be
5450b57cec5SDimitry Andric   // copied into vregs, emit the copies into the top of the block before
5460b57cec5SDimitry Andric   // emitting the code for the block.
5470b57cec5SDimitry Andric   const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
5480b57cec5SDimitry Andric   RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
5490b57cec5SDimitry Andric 
5500b57cec5SDimitry Andric   // Insert copies in the entry block and the return blocks.
5510b57cec5SDimitry Andric   if (FuncInfo->SplitCSR) {
5520b57cec5SDimitry Andric     SmallVector<MachineBasicBlock*, 4> Returns;
5530b57cec5SDimitry Andric     // Collect all the return blocks.
5540b57cec5SDimitry Andric     for (MachineBasicBlock &MBB : mf) {
5550b57cec5SDimitry Andric       if (!MBB.succ_empty())
5560b57cec5SDimitry Andric         continue;
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric       MachineBasicBlock::iterator Term = MBB.getFirstTerminator();
5590b57cec5SDimitry Andric       if (Term != MBB.end() && Term->isReturn()) {
5600b57cec5SDimitry Andric         Returns.push_back(&MBB);
5610b57cec5SDimitry Andric         continue;
5620b57cec5SDimitry Andric       }
5630b57cec5SDimitry Andric     }
5640b57cec5SDimitry Andric     TLI->insertCopiesSplitCSR(EntryMBB, Returns);
5650b57cec5SDimitry Andric   }
5660b57cec5SDimitry Andric 
5670b57cec5SDimitry Andric   DenseMap<unsigned, unsigned> LiveInMap;
5680b57cec5SDimitry Andric   if (!FuncInfo->ArgDbgValues.empty())
5690b57cec5SDimitry Andric     for (std::pair<unsigned, unsigned> LI : RegInfo->liveins())
5700b57cec5SDimitry Andric       if (LI.second)
5710b57cec5SDimitry Andric         LiveInMap.insert(LI);
5720b57cec5SDimitry Andric 
5730b57cec5SDimitry Andric   // Insert DBG_VALUE instructions for function arguments to the entry block.
5740b57cec5SDimitry Andric   for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
5750b57cec5SDimitry Andric     MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1];
5760b57cec5SDimitry Andric     bool hasFI = MI->getOperand(0).isFI();
5770b57cec5SDimitry Andric     Register Reg =
5780b57cec5SDimitry Andric         hasFI ? TRI.getFrameRegister(*MF) : MI->getOperand(0).getReg();
5798bcb0991SDimitry Andric     if (Register::isPhysicalRegister(Reg))
5800b57cec5SDimitry Andric       EntryMBB->insert(EntryMBB->begin(), MI);
5810b57cec5SDimitry Andric     else {
5820b57cec5SDimitry Andric       MachineInstr *Def = RegInfo->getVRegDef(Reg);
5830b57cec5SDimitry Andric       if (Def) {
5840b57cec5SDimitry Andric         MachineBasicBlock::iterator InsertPos = Def;
5850b57cec5SDimitry Andric         // FIXME: VR def may not be in entry block.
5860b57cec5SDimitry Andric         Def->getParent()->insert(std::next(InsertPos), MI);
5870b57cec5SDimitry Andric       } else
5880b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Dropping debug info for dead vreg"
5898bcb0991SDimitry Andric                           << Register::virtReg2Index(Reg) << "\n");
5900b57cec5SDimitry Andric     }
5910b57cec5SDimitry Andric 
5920b57cec5SDimitry Andric     // If Reg is live-in then update debug info to track its copy in a vreg.
5930b57cec5SDimitry Andric     DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
5940b57cec5SDimitry Andric     if (LDI != LiveInMap.end()) {
5950b57cec5SDimitry Andric       assert(!hasFI && "There's no handling of frame pointer updating here yet "
5960b57cec5SDimitry Andric                        "- add if needed");
5970b57cec5SDimitry Andric       MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
5980b57cec5SDimitry Andric       MachineBasicBlock::iterator InsertPos = Def;
5990b57cec5SDimitry Andric       const MDNode *Variable = MI->getDebugVariable();
6000b57cec5SDimitry Andric       const MDNode *Expr = MI->getDebugExpression();
6010b57cec5SDimitry Andric       DebugLoc DL = MI->getDebugLoc();
6020b57cec5SDimitry Andric       bool IsIndirect = MI->isIndirectDebugValue();
6030b57cec5SDimitry Andric       if (IsIndirect)
6040b57cec5SDimitry Andric         assert(MI->getOperand(1).getImm() == 0 &&
6050b57cec5SDimitry Andric                "DBG_VALUE with nonzero offset");
6060b57cec5SDimitry Andric       assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
6070b57cec5SDimitry Andric              "Expected inlined-at fields to agree");
6080b57cec5SDimitry Andric       // Def is never a terminator here, so it is ok to increment InsertPos.
6090b57cec5SDimitry Andric       BuildMI(*EntryMBB, ++InsertPos, DL, TII->get(TargetOpcode::DBG_VALUE),
6100b57cec5SDimitry Andric               IsIndirect, LDI->second, Variable, Expr);
6110b57cec5SDimitry Andric 
6120b57cec5SDimitry Andric       // If this vreg is directly copied into an exported register then
6130b57cec5SDimitry Andric       // that COPY instructions also need DBG_VALUE, if it is the only
6140b57cec5SDimitry Andric       // user of LDI->second.
6150b57cec5SDimitry Andric       MachineInstr *CopyUseMI = nullptr;
6160b57cec5SDimitry Andric       for (MachineRegisterInfo::use_instr_iterator
6170b57cec5SDimitry Andric            UI = RegInfo->use_instr_begin(LDI->second),
6180b57cec5SDimitry Andric            E = RegInfo->use_instr_end(); UI != E; ) {
6190b57cec5SDimitry Andric         MachineInstr *UseMI = &*(UI++);
6200b57cec5SDimitry Andric         if (UseMI->isDebugValue()) continue;
6210b57cec5SDimitry Andric         if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
6220b57cec5SDimitry Andric           CopyUseMI = UseMI; continue;
6230b57cec5SDimitry Andric         }
6240b57cec5SDimitry Andric         // Otherwise this is another use or second copy use.
6250b57cec5SDimitry Andric         CopyUseMI = nullptr; break;
6260b57cec5SDimitry Andric       }
6275ffd83dbSDimitry Andric       if (CopyUseMI &&
6285ffd83dbSDimitry Andric           TRI.getRegSizeInBits(LDI->second, MRI) ==
6295ffd83dbSDimitry Andric               TRI.getRegSizeInBits(CopyUseMI->getOperand(0).getReg(), MRI)) {
6300b57cec5SDimitry Andric         // Use MI's debug location, which describes where Variable was
6310b57cec5SDimitry Andric         // declared, rather than whatever is attached to CopyUseMI.
6320b57cec5SDimitry Andric         MachineInstr *NewMI =
6330b57cec5SDimitry Andric             BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
6340b57cec5SDimitry Andric                     CopyUseMI->getOperand(0).getReg(), Variable, Expr);
6350b57cec5SDimitry Andric         MachineBasicBlock::iterator Pos = CopyUseMI;
6360b57cec5SDimitry Andric         EntryMBB->insertAfter(Pos, NewMI);
6370b57cec5SDimitry Andric       }
6380b57cec5SDimitry Andric     }
6390b57cec5SDimitry Andric   }
6400b57cec5SDimitry Andric 
6410b57cec5SDimitry Andric   // Determine if there are any calls in this machine function.
6420b57cec5SDimitry Andric   MachineFrameInfo &MFI = MF->getFrameInfo();
6430b57cec5SDimitry Andric   for (const auto &MBB : *MF) {
6440b57cec5SDimitry Andric     if (MFI.hasCalls() && MF->hasInlineAsm())
6450b57cec5SDimitry Andric       break;
6460b57cec5SDimitry Andric 
6470b57cec5SDimitry Andric     for (const auto &MI : MBB) {
6480b57cec5SDimitry Andric       const MCInstrDesc &MCID = TII->get(MI.getOpcode());
6490b57cec5SDimitry Andric       if ((MCID.isCall() && !MCID.isReturn()) ||
6500b57cec5SDimitry Andric           MI.isStackAligningInlineAsm()) {
6510b57cec5SDimitry Andric         MFI.setHasCalls(true);
6520b57cec5SDimitry Andric       }
6530b57cec5SDimitry Andric       if (MI.isInlineAsm()) {
6540b57cec5SDimitry Andric         MF->setHasInlineAsm(true);
6550b57cec5SDimitry Andric       }
6560b57cec5SDimitry Andric     }
6570b57cec5SDimitry Andric   }
6580b57cec5SDimitry Andric 
6590b57cec5SDimitry Andric   // Determine if there is a call to setjmp in the machine function.
6600b57cec5SDimitry Andric   MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice());
6610b57cec5SDimitry Andric 
6620b57cec5SDimitry Andric   // Determine if floating point is used for msvc
6630b57cec5SDimitry Andric   computeUsesMSVCFloatingPoint(TM.getTargetTriple(), Fn, MF->getMMI());
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric   // Release function-specific state. SDB and CurDAG are already cleared
6660b57cec5SDimitry Andric   // at this point.
6670b57cec5SDimitry Andric   FuncInfo->clear();
6680b57cec5SDimitry Andric 
6690b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "*** MachineFunction at end of ISel ***\n");
6700b57cec5SDimitry Andric   LLVM_DEBUG(MF->print(dbgs()));
6710b57cec5SDimitry Andric 
6720b57cec5SDimitry Andric   return true;
6730b57cec5SDimitry Andric }
6740b57cec5SDimitry Andric 
6750b57cec5SDimitry Andric static void reportFastISelFailure(MachineFunction &MF,
6760b57cec5SDimitry Andric                                   OptimizationRemarkEmitter &ORE,
6770b57cec5SDimitry Andric                                   OptimizationRemarkMissed &R,
6780b57cec5SDimitry Andric                                   bool ShouldAbort) {
6790b57cec5SDimitry Andric   // Print the function name explicitly if we don't have a debug location (which
6800b57cec5SDimitry Andric   // makes the diagnostic less useful) or if we're going to emit a raw error.
6810b57cec5SDimitry Andric   if (!R.getLocation().isValid() || ShouldAbort)
6820b57cec5SDimitry Andric     R << (" (in function: " + MF.getName() + ")").str();
6830b57cec5SDimitry Andric 
6840b57cec5SDimitry Andric   if (ShouldAbort)
6850b57cec5SDimitry Andric     report_fatal_error(R.getMsg());
6860b57cec5SDimitry Andric 
6870b57cec5SDimitry Andric   ORE.emit(R);
6880b57cec5SDimitry Andric }
6890b57cec5SDimitry Andric 
6900b57cec5SDimitry Andric void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
6910b57cec5SDimitry Andric                                         BasicBlock::const_iterator End,
6920b57cec5SDimitry Andric                                         bool &HadTailCall) {
6930b57cec5SDimitry Andric   // Allow creating illegal types during DAG building for the basic block.
6940b57cec5SDimitry Andric   CurDAG->NewNodesMustHaveLegalTypes = false;
6950b57cec5SDimitry Andric 
6960b57cec5SDimitry Andric   // Lower the instructions. If a call is emitted as a tail call, cease emitting
6970b57cec5SDimitry Andric   // nodes for this block.
6980b57cec5SDimitry Andric   for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I) {
6990b57cec5SDimitry Andric     if (!ElidedArgCopyInstrs.count(&*I))
7000b57cec5SDimitry Andric       SDB->visit(*I);
7010b57cec5SDimitry Andric   }
7020b57cec5SDimitry Andric 
7030b57cec5SDimitry Andric   // Make sure the root of the DAG is up-to-date.
7040b57cec5SDimitry Andric   CurDAG->setRoot(SDB->getControlRoot());
7050b57cec5SDimitry Andric   HadTailCall = SDB->HasTailCall;
7060b57cec5SDimitry Andric   SDB->resolveOrClearDbgInfo();
7070b57cec5SDimitry Andric   SDB->clear();
7080b57cec5SDimitry Andric 
7090b57cec5SDimitry Andric   // Final step, emit the lowered DAG as machine code.
7100b57cec5SDimitry Andric   CodeGenAndEmitDAG();
7110b57cec5SDimitry Andric }
7120b57cec5SDimitry Andric 
7130b57cec5SDimitry Andric void SelectionDAGISel::ComputeLiveOutVRegInfo() {
714480093f4SDimitry Andric   SmallPtrSet<SDNode *, 16> Added;
7150b57cec5SDimitry Andric   SmallVector<SDNode*, 128> Worklist;
7160b57cec5SDimitry Andric 
7170b57cec5SDimitry Andric   Worklist.push_back(CurDAG->getRoot().getNode());
718480093f4SDimitry Andric   Added.insert(CurDAG->getRoot().getNode());
7190b57cec5SDimitry Andric 
7200b57cec5SDimitry Andric   KnownBits Known;
7210b57cec5SDimitry Andric 
7220b57cec5SDimitry Andric   do {
7230b57cec5SDimitry Andric     SDNode *N = Worklist.pop_back_val();
7240b57cec5SDimitry Andric 
7250b57cec5SDimitry Andric     // Otherwise, add all chain operands to the worklist.
7260b57cec5SDimitry Andric     for (const SDValue &Op : N->op_values())
727480093f4SDimitry Andric       if (Op.getValueType() == MVT::Other && Added.insert(Op.getNode()).second)
7280b57cec5SDimitry Andric         Worklist.push_back(Op.getNode());
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric     // If this is a CopyToReg with a vreg dest, process it.
7310b57cec5SDimitry Andric     if (N->getOpcode() != ISD::CopyToReg)
7320b57cec5SDimitry Andric       continue;
7330b57cec5SDimitry Andric 
7340b57cec5SDimitry Andric     unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
7358bcb0991SDimitry Andric     if (!Register::isVirtualRegister(DestReg))
7360b57cec5SDimitry Andric       continue;
7370b57cec5SDimitry Andric 
7380b57cec5SDimitry Andric     // Ignore non-integer values.
7390b57cec5SDimitry Andric     SDValue Src = N->getOperand(2);
7400b57cec5SDimitry Andric     EVT SrcVT = Src.getValueType();
7410b57cec5SDimitry Andric     if (!SrcVT.isInteger())
7420b57cec5SDimitry Andric       continue;
7430b57cec5SDimitry Andric 
7440b57cec5SDimitry Andric     unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
7450b57cec5SDimitry Andric     Known = CurDAG->computeKnownBits(Src);
7460b57cec5SDimitry Andric     FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, Known);
7470b57cec5SDimitry Andric   } while (!Worklist.empty());
7480b57cec5SDimitry Andric }
7490b57cec5SDimitry Andric 
7500b57cec5SDimitry Andric void SelectionDAGISel::CodeGenAndEmitDAG() {
7510b57cec5SDimitry Andric   StringRef GroupName = "sdag";
7520b57cec5SDimitry Andric   StringRef GroupDescription = "Instruction Selection and Scheduling";
7530b57cec5SDimitry Andric   std::string BlockName;
7540b57cec5SDimitry Andric   bool MatchFilterBB = false; (void)MatchFilterBB;
7550b57cec5SDimitry Andric #ifndef NDEBUG
7560b57cec5SDimitry Andric   TargetTransformInfo &TTI =
7570b57cec5SDimitry Andric       getAnalysis<TargetTransformInfoWrapperPass>().getTTI(*FuncInfo->Fn);
7580b57cec5SDimitry Andric #endif
7590b57cec5SDimitry Andric 
7600b57cec5SDimitry Andric   // Pre-type legalization allow creation of any node types.
7610b57cec5SDimitry Andric   CurDAG->NewNodesMustHaveLegalTypes = false;
7620b57cec5SDimitry Andric 
7630b57cec5SDimitry Andric #ifndef NDEBUG
7640b57cec5SDimitry Andric   MatchFilterBB = (FilterDAGBasicBlockName.empty() ||
7650b57cec5SDimitry Andric                    FilterDAGBasicBlockName ==
7660b57cec5SDimitry Andric                        FuncInfo->MBB->getBasicBlock()->getName());
7670b57cec5SDimitry Andric #endif
7680b57cec5SDimitry Andric #ifdef NDEBUG
769480093f4SDimitry Andric   if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewDAGCombineLT ||
770480093f4SDimitry Andric       ViewLegalizeDAGs || ViewDAGCombine2 || ViewISelDAGs || ViewSchedDAGs ||
7710b57cec5SDimitry Andric       ViewSUnitDAGs)
7720b57cec5SDimitry Andric #endif
7730b57cec5SDimitry Andric   {
7740b57cec5SDimitry Andric     BlockName =
7750b57cec5SDimitry Andric         (MF->getName() + ":" + FuncInfo->MBB->getBasicBlock()->getName()).str();
7760b57cec5SDimitry Andric   }
7770b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Initial selection DAG: "
7780b57cec5SDimitry Andric                     << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
7790b57cec5SDimitry Andric                     << "'\n";
7800b57cec5SDimitry Andric              CurDAG->dump());
7810b57cec5SDimitry Andric 
782*e8d8bef9SDimitry Andric #ifndef NDEBUG
783*e8d8bef9SDimitry Andric   if (TTI.hasBranchDivergence())
784*e8d8bef9SDimitry Andric     CurDAG->VerifyDAGDiverence();
785*e8d8bef9SDimitry Andric #endif
786*e8d8bef9SDimitry Andric 
7870b57cec5SDimitry Andric   if (ViewDAGCombine1 && MatchFilterBB)
7880b57cec5SDimitry Andric     CurDAG->viewGraph("dag-combine1 input for " + BlockName);
7890b57cec5SDimitry Andric 
7900b57cec5SDimitry Andric   // Run the DAG combiner in pre-legalize mode.
7910b57cec5SDimitry Andric   {
7920b57cec5SDimitry Andric     NamedRegionTimer T("combine1", "DAG Combining 1", GroupName,
7930b57cec5SDimitry Andric                        GroupDescription, TimePassesIsEnabled);
7940b57cec5SDimitry Andric     CurDAG->Combine(BeforeLegalizeTypes, AA, OptLevel);
7950b57cec5SDimitry Andric   }
7960b57cec5SDimitry Andric 
7970b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Optimized lowered selection DAG: "
7980b57cec5SDimitry Andric                     << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
7990b57cec5SDimitry Andric                     << "'\n";
8000b57cec5SDimitry Andric              CurDAG->dump());
8010b57cec5SDimitry Andric 
802*e8d8bef9SDimitry Andric #ifndef NDEBUG
803*e8d8bef9SDimitry Andric   if (TTI.hasBranchDivergence())
804*e8d8bef9SDimitry Andric     CurDAG->VerifyDAGDiverence();
805*e8d8bef9SDimitry Andric #endif
806*e8d8bef9SDimitry Andric 
8070b57cec5SDimitry Andric   // Second step, hack on the DAG until it only uses operations and types that
8080b57cec5SDimitry Andric   // the target supports.
8090b57cec5SDimitry Andric   if (ViewLegalizeTypesDAGs && MatchFilterBB)
8100b57cec5SDimitry Andric     CurDAG->viewGraph("legalize-types input for " + BlockName);
8110b57cec5SDimitry Andric 
8120b57cec5SDimitry Andric   bool Changed;
8130b57cec5SDimitry Andric   {
8140b57cec5SDimitry Andric     NamedRegionTimer T("legalize_types", "Type Legalization", GroupName,
8150b57cec5SDimitry Andric                        GroupDescription, TimePassesIsEnabled);
8160b57cec5SDimitry Andric     Changed = CurDAG->LegalizeTypes();
8170b57cec5SDimitry Andric   }
8180b57cec5SDimitry Andric 
8190b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Type-legalized selection DAG: "
8200b57cec5SDimitry Andric                     << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
8210b57cec5SDimitry Andric                     << "'\n";
8220b57cec5SDimitry Andric              CurDAG->dump());
8230b57cec5SDimitry Andric 
824*e8d8bef9SDimitry Andric #ifndef NDEBUG
825*e8d8bef9SDimitry Andric   if (TTI.hasBranchDivergence())
826*e8d8bef9SDimitry Andric     CurDAG->VerifyDAGDiverence();
827*e8d8bef9SDimitry Andric #endif
828*e8d8bef9SDimitry Andric 
8290b57cec5SDimitry Andric   // Only allow creation of legal node types.
8300b57cec5SDimitry Andric   CurDAG->NewNodesMustHaveLegalTypes = true;
8310b57cec5SDimitry Andric 
8320b57cec5SDimitry Andric   if (Changed) {
8330b57cec5SDimitry Andric     if (ViewDAGCombineLT && MatchFilterBB)
8340b57cec5SDimitry Andric       CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
8350b57cec5SDimitry Andric 
8360b57cec5SDimitry Andric     // Run the DAG combiner in post-type-legalize mode.
8370b57cec5SDimitry Andric     {
8380b57cec5SDimitry Andric       NamedRegionTimer T("combine_lt", "DAG Combining after legalize types",
8390b57cec5SDimitry Andric                          GroupName, GroupDescription, TimePassesIsEnabled);
8400b57cec5SDimitry Andric       CurDAG->Combine(AfterLegalizeTypes, AA, OptLevel);
8410b57cec5SDimitry Andric     }
8420b57cec5SDimitry Andric 
8430b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Optimized type-legalized selection DAG: "
8440b57cec5SDimitry Andric                       << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
8450b57cec5SDimitry Andric                       << "'\n";
8460b57cec5SDimitry Andric                CurDAG->dump());
847*e8d8bef9SDimitry Andric 
848*e8d8bef9SDimitry Andric #ifndef NDEBUG
849*e8d8bef9SDimitry Andric     if (TTI.hasBranchDivergence())
850*e8d8bef9SDimitry Andric       CurDAG->VerifyDAGDiverence();
851*e8d8bef9SDimitry Andric #endif
8520b57cec5SDimitry Andric   }
8530b57cec5SDimitry Andric 
8540b57cec5SDimitry Andric   {
8550b57cec5SDimitry Andric     NamedRegionTimer T("legalize_vec", "Vector Legalization", GroupName,
8560b57cec5SDimitry Andric                        GroupDescription, TimePassesIsEnabled);
8570b57cec5SDimitry Andric     Changed = CurDAG->LegalizeVectors();
8580b57cec5SDimitry Andric   }
8590b57cec5SDimitry Andric 
8600b57cec5SDimitry Andric   if (Changed) {
8610b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Vector-legalized selection DAG: "
8620b57cec5SDimitry Andric                       << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
8630b57cec5SDimitry Andric                       << "'\n";
8640b57cec5SDimitry Andric                CurDAG->dump());
8650b57cec5SDimitry Andric 
866*e8d8bef9SDimitry Andric #ifndef NDEBUG
867*e8d8bef9SDimitry Andric     if (TTI.hasBranchDivergence())
868*e8d8bef9SDimitry Andric       CurDAG->VerifyDAGDiverence();
869*e8d8bef9SDimitry Andric #endif
870*e8d8bef9SDimitry Andric 
8710b57cec5SDimitry Andric     {
8720b57cec5SDimitry Andric       NamedRegionTimer T("legalize_types2", "Type Legalization 2", GroupName,
8730b57cec5SDimitry Andric                          GroupDescription, TimePassesIsEnabled);
8740b57cec5SDimitry Andric       CurDAG->LegalizeTypes();
8750b57cec5SDimitry Andric     }
8760b57cec5SDimitry Andric 
8770b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Vector/type-legalized selection DAG: "
8780b57cec5SDimitry Andric                       << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
8790b57cec5SDimitry Andric                       << "'\n";
8800b57cec5SDimitry Andric                CurDAG->dump());
8810b57cec5SDimitry Andric 
882*e8d8bef9SDimitry Andric #ifndef NDEBUG
883*e8d8bef9SDimitry Andric     if (TTI.hasBranchDivergence())
884*e8d8bef9SDimitry Andric       CurDAG->VerifyDAGDiverence();
885*e8d8bef9SDimitry Andric #endif
886*e8d8bef9SDimitry Andric 
8870b57cec5SDimitry Andric     if (ViewDAGCombineLT && MatchFilterBB)
8880b57cec5SDimitry Andric       CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
8890b57cec5SDimitry Andric 
8900b57cec5SDimitry Andric     // Run the DAG combiner in post-type-legalize mode.
8910b57cec5SDimitry Andric     {
8920b57cec5SDimitry Andric       NamedRegionTimer T("combine_lv", "DAG Combining after legalize vectors",
8930b57cec5SDimitry Andric                          GroupName, GroupDescription, TimePassesIsEnabled);
8940b57cec5SDimitry Andric       CurDAG->Combine(AfterLegalizeVectorOps, AA, OptLevel);
8950b57cec5SDimitry Andric     }
8960b57cec5SDimitry Andric 
8970b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Optimized vector-legalized selection DAG: "
8980b57cec5SDimitry Andric                       << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
8990b57cec5SDimitry Andric                       << "'\n";
9000b57cec5SDimitry Andric                CurDAG->dump());
9010b57cec5SDimitry Andric 
9020b57cec5SDimitry Andric #ifndef NDEBUG
9030b57cec5SDimitry Andric     if (TTI.hasBranchDivergence())
9040b57cec5SDimitry Andric       CurDAG->VerifyDAGDiverence();
9050b57cec5SDimitry Andric #endif
9060b57cec5SDimitry Andric   }
9070b57cec5SDimitry Andric 
9080b57cec5SDimitry Andric   if (ViewLegalizeDAGs && MatchFilterBB)
9090b57cec5SDimitry Andric     CurDAG->viewGraph("legalize input for " + BlockName);
9100b57cec5SDimitry Andric 
9110b57cec5SDimitry Andric   {
9120b57cec5SDimitry Andric     NamedRegionTimer T("legalize", "DAG Legalization", GroupName,
9130b57cec5SDimitry Andric                        GroupDescription, TimePassesIsEnabled);
9140b57cec5SDimitry Andric     CurDAG->Legalize();
9150b57cec5SDimitry Andric   }
9160b57cec5SDimitry Andric 
9170b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Legalized selection DAG: "
9180b57cec5SDimitry Andric                     << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
9190b57cec5SDimitry Andric                     << "'\n";
9200b57cec5SDimitry Andric              CurDAG->dump());
9210b57cec5SDimitry Andric 
922*e8d8bef9SDimitry Andric #ifndef NDEBUG
923*e8d8bef9SDimitry Andric   if (TTI.hasBranchDivergence())
924*e8d8bef9SDimitry Andric     CurDAG->VerifyDAGDiverence();
925*e8d8bef9SDimitry Andric #endif
926*e8d8bef9SDimitry Andric 
9270b57cec5SDimitry Andric   if (ViewDAGCombine2 && MatchFilterBB)
9280b57cec5SDimitry Andric     CurDAG->viewGraph("dag-combine2 input for " + BlockName);
9290b57cec5SDimitry Andric 
9300b57cec5SDimitry Andric   // Run the DAG combiner in post-legalize mode.
9310b57cec5SDimitry Andric   {
9320b57cec5SDimitry Andric     NamedRegionTimer T("combine2", "DAG Combining 2", GroupName,
9330b57cec5SDimitry Andric                        GroupDescription, TimePassesIsEnabled);
9340b57cec5SDimitry Andric     CurDAG->Combine(AfterLegalizeDAG, AA, OptLevel);
9350b57cec5SDimitry Andric   }
9360b57cec5SDimitry Andric 
9370b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Optimized legalized selection DAG: "
9380b57cec5SDimitry Andric                     << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
9390b57cec5SDimitry Andric                     << "'\n";
9400b57cec5SDimitry Andric              CurDAG->dump());
9410b57cec5SDimitry Andric 
942*e8d8bef9SDimitry Andric #ifndef NDEBUG
943*e8d8bef9SDimitry Andric   if (TTI.hasBranchDivergence())
944*e8d8bef9SDimitry Andric     CurDAG->VerifyDAGDiverence();
945*e8d8bef9SDimitry Andric #endif
946*e8d8bef9SDimitry Andric 
9470b57cec5SDimitry Andric   if (OptLevel != CodeGenOpt::None)
9480b57cec5SDimitry Andric     ComputeLiveOutVRegInfo();
9490b57cec5SDimitry Andric 
9500b57cec5SDimitry Andric   if (ViewISelDAGs && MatchFilterBB)
9510b57cec5SDimitry Andric     CurDAG->viewGraph("isel input for " + BlockName);
9520b57cec5SDimitry Andric 
9530b57cec5SDimitry Andric   // Third, instruction select all of the operations to machine code, adding the
9540b57cec5SDimitry Andric   // code to the MachineBasicBlock.
9550b57cec5SDimitry Andric   {
9560b57cec5SDimitry Andric     NamedRegionTimer T("isel", "Instruction Selection", GroupName,
9570b57cec5SDimitry Andric                        GroupDescription, TimePassesIsEnabled);
9580b57cec5SDimitry Andric     DoInstructionSelection();
9590b57cec5SDimitry Andric   }
9600b57cec5SDimitry Andric 
9610b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Selected selection DAG: "
9620b57cec5SDimitry Andric                     << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
9630b57cec5SDimitry Andric                     << "'\n";
9640b57cec5SDimitry Andric              CurDAG->dump());
9650b57cec5SDimitry Andric 
9660b57cec5SDimitry Andric   if (ViewSchedDAGs && MatchFilterBB)
9670b57cec5SDimitry Andric     CurDAG->viewGraph("scheduler input for " + BlockName);
9680b57cec5SDimitry Andric 
9690b57cec5SDimitry Andric   // Schedule machine code.
9700b57cec5SDimitry Andric   ScheduleDAGSDNodes *Scheduler = CreateScheduler();
9710b57cec5SDimitry Andric   {
9720b57cec5SDimitry Andric     NamedRegionTimer T("sched", "Instruction Scheduling", GroupName,
9730b57cec5SDimitry Andric                        GroupDescription, TimePassesIsEnabled);
9740b57cec5SDimitry Andric     Scheduler->Run(CurDAG, FuncInfo->MBB);
9750b57cec5SDimitry Andric   }
9760b57cec5SDimitry Andric 
9770b57cec5SDimitry Andric   if (ViewSUnitDAGs && MatchFilterBB)
9780b57cec5SDimitry Andric     Scheduler->viewGraph();
9790b57cec5SDimitry Andric 
9800b57cec5SDimitry Andric   // Emit machine code to BB.  This can change 'BB' to the last block being
9810b57cec5SDimitry Andric   // inserted into.
9820b57cec5SDimitry Andric   MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
9830b57cec5SDimitry Andric   {
9840b57cec5SDimitry Andric     NamedRegionTimer T("emit", "Instruction Creation", GroupName,
9850b57cec5SDimitry Andric                        GroupDescription, TimePassesIsEnabled);
9860b57cec5SDimitry Andric 
9870b57cec5SDimitry Andric     // FuncInfo->InsertPt is passed by reference and set to the end of the
9880b57cec5SDimitry Andric     // scheduled instructions.
9890b57cec5SDimitry Andric     LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
9900b57cec5SDimitry Andric   }
9910b57cec5SDimitry Andric 
9920b57cec5SDimitry Andric   // If the block was split, make sure we update any references that are used to
9930b57cec5SDimitry Andric   // update PHI nodes later on.
9940b57cec5SDimitry Andric   if (FirstMBB != LastMBB)
9950b57cec5SDimitry Andric     SDB->UpdateSplitBlock(FirstMBB, LastMBB);
9960b57cec5SDimitry Andric 
9970b57cec5SDimitry Andric   // Free the scheduler state.
9980b57cec5SDimitry Andric   {
9990b57cec5SDimitry Andric     NamedRegionTimer T("cleanup", "Instruction Scheduling Cleanup", GroupName,
10000b57cec5SDimitry Andric                        GroupDescription, TimePassesIsEnabled);
10010b57cec5SDimitry Andric     delete Scheduler;
10020b57cec5SDimitry Andric   }
10030b57cec5SDimitry Andric 
10040b57cec5SDimitry Andric   // Free the SelectionDAG state, now that we're finished with it.
10050b57cec5SDimitry Andric   CurDAG->clear();
10060b57cec5SDimitry Andric }
10070b57cec5SDimitry Andric 
10080b57cec5SDimitry Andric namespace {
10090b57cec5SDimitry Andric 
10100b57cec5SDimitry Andric /// ISelUpdater - helper class to handle updates of the instruction selection
10110b57cec5SDimitry Andric /// graph.
10120b57cec5SDimitry Andric class ISelUpdater : public SelectionDAG::DAGUpdateListener {
10130b57cec5SDimitry Andric   SelectionDAG::allnodes_iterator &ISelPosition;
10140b57cec5SDimitry Andric 
10150b57cec5SDimitry Andric public:
10160b57cec5SDimitry Andric   ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
10170b57cec5SDimitry Andric     : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
10180b57cec5SDimitry Andric 
10190b57cec5SDimitry Andric   /// NodeDeleted - Handle nodes deleted from the graph. If the node being
10200b57cec5SDimitry Andric   /// deleted is the current ISelPosition node, update ISelPosition.
10210b57cec5SDimitry Andric   ///
10220b57cec5SDimitry Andric   void NodeDeleted(SDNode *N, SDNode *E) override {
10230b57cec5SDimitry Andric     if (ISelPosition == SelectionDAG::allnodes_iterator(N))
10240b57cec5SDimitry Andric       ++ISelPosition;
10250b57cec5SDimitry Andric   }
10260b57cec5SDimitry Andric };
10270b57cec5SDimitry Andric 
10280b57cec5SDimitry Andric } // end anonymous namespace
10290b57cec5SDimitry Andric 
10300b57cec5SDimitry Andric // This function is used to enforce the topological node id property
10310b57cec5SDimitry Andric // property leveraged during Instruction selection. Before selection all
10320b57cec5SDimitry Andric // nodes are given a non-negative id such that all nodes have a larger id than
10330b57cec5SDimitry Andric // their operands. As this holds transitively we can prune checks that a node N
10340b57cec5SDimitry Andric // is a predecessor of M another by not recursively checking through M's
10350b57cec5SDimitry Andric // operands if N's ID is larger than M's ID. This is significantly improves
10360b57cec5SDimitry Andric // performance of for various legality checks (e.g. IsLegalToFold /
10370b57cec5SDimitry Andric // UpdateChains).
10380b57cec5SDimitry Andric 
10390b57cec5SDimitry Andric // However, when we fuse multiple nodes into a single node
10400b57cec5SDimitry Andric // during selection we may induce a predecessor relationship between inputs and
10410b57cec5SDimitry Andric // outputs of distinct nodes being merged violating the topological property.
10420b57cec5SDimitry Andric // Should a fused node have a successor which has yet to be selected, our
10430b57cec5SDimitry Andric // legality checks would be incorrect. To avoid this we mark all unselected
10440b57cec5SDimitry Andric // sucessor nodes, i.e. id != -1 as invalid for pruning by bit-negating (x =>
10450b57cec5SDimitry Andric // (-(x+1))) the ids and modify our pruning check to ignore negative Ids of M.
10460b57cec5SDimitry Andric // We use bit-negation to more clearly enforce that node id -1 can only be
10470b57cec5SDimitry Andric // achieved by selected nodes). As the conversion is reversable the original Id,
10480b57cec5SDimitry Andric // topological pruning can still be leveraged when looking for unselected nodes.
10490b57cec5SDimitry Andric // This method is call internally in all ISel replacement calls.
10500b57cec5SDimitry Andric void SelectionDAGISel::EnforceNodeIdInvariant(SDNode *Node) {
10510b57cec5SDimitry Andric   SmallVector<SDNode *, 4> Nodes;
10520b57cec5SDimitry Andric   Nodes.push_back(Node);
10530b57cec5SDimitry Andric 
10540b57cec5SDimitry Andric   while (!Nodes.empty()) {
10550b57cec5SDimitry Andric     SDNode *N = Nodes.pop_back_val();
10560b57cec5SDimitry Andric     for (auto *U : N->uses()) {
10570b57cec5SDimitry Andric       auto UId = U->getNodeId();
10580b57cec5SDimitry Andric       if (UId > 0) {
10590b57cec5SDimitry Andric         InvalidateNodeId(U);
10600b57cec5SDimitry Andric         Nodes.push_back(U);
10610b57cec5SDimitry Andric       }
10620b57cec5SDimitry Andric     }
10630b57cec5SDimitry Andric   }
10640b57cec5SDimitry Andric }
10650b57cec5SDimitry Andric 
10660b57cec5SDimitry Andric // InvalidateNodeId - As discusses in EnforceNodeIdInvariant, mark a
10670b57cec5SDimitry Andric // NodeId with the equivalent node id which is invalid for topological
10680b57cec5SDimitry Andric // pruning.
10690b57cec5SDimitry Andric void SelectionDAGISel::InvalidateNodeId(SDNode *N) {
10700b57cec5SDimitry Andric   int InvalidId = -(N->getNodeId() + 1);
10710b57cec5SDimitry Andric   N->setNodeId(InvalidId);
10720b57cec5SDimitry Andric }
10730b57cec5SDimitry Andric 
10740b57cec5SDimitry Andric // getUninvalidatedNodeId - get original uninvalidated node id.
10750b57cec5SDimitry Andric int SelectionDAGISel::getUninvalidatedNodeId(SDNode *N) {
10760b57cec5SDimitry Andric   int Id = N->getNodeId();
10770b57cec5SDimitry Andric   if (Id < -1)
10780b57cec5SDimitry Andric     return -(Id + 1);
10790b57cec5SDimitry Andric   return Id;
10800b57cec5SDimitry Andric }
10810b57cec5SDimitry Andric 
10820b57cec5SDimitry Andric void SelectionDAGISel::DoInstructionSelection() {
10830b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "===== Instruction selection begins: "
10840b57cec5SDimitry Andric                     << printMBBReference(*FuncInfo->MBB) << " '"
10850b57cec5SDimitry Andric                     << FuncInfo->MBB->getName() << "'\n");
10860b57cec5SDimitry Andric 
10870b57cec5SDimitry Andric   PreprocessISelDAG();
10880b57cec5SDimitry Andric 
10890b57cec5SDimitry Andric   // Select target instructions for the DAG.
10900b57cec5SDimitry Andric   {
10910b57cec5SDimitry Andric     // Number all nodes with a topological order and set DAGSize.
10920b57cec5SDimitry Andric     DAGSize = CurDAG->AssignTopologicalOrder();
10930b57cec5SDimitry Andric 
10940b57cec5SDimitry Andric     // Create a dummy node (which is not added to allnodes), that adds
10950b57cec5SDimitry Andric     // a reference to the root node, preventing it from being deleted,
10960b57cec5SDimitry Andric     // and tracking any changes of the root.
10970b57cec5SDimitry Andric     HandleSDNode Dummy(CurDAG->getRoot());
10980b57cec5SDimitry Andric     SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode());
10990b57cec5SDimitry Andric     ++ISelPosition;
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric     // Make sure that ISelPosition gets properly updated when nodes are deleted
11020b57cec5SDimitry Andric     // in calls made from this function.
11030b57cec5SDimitry Andric     ISelUpdater ISU(*CurDAG, ISelPosition);
11040b57cec5SDimitry Andric 
11050b57cec5SDimitry Andric     // The AllNodes list is now topological-sorted. Visit the
11060b57cec5SDimitry Andric     // nodes by starting at the end of the list (the root of the
11070b57cec5SDimitry Andric     // graph) and preceding back toward the beginning (the entry
11080b57cec5SDimitry Andric     // node).
11090b57cec5SDimitry Andric     while (ISelPosition != CurDAG->allnodes_begin()) {
11100b57cec5SDimitry Andric       SDNode *Node = &*--ISelPosition;
11110b57cec5SDimitry Andric       // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
11120b57cec5SDimitry Andric       // but there are currently some corner cases that it misses. Also, this
11130b57cec5SDimitry Andric       // makes it theoretically possible to disable the DAGCombiner.
11140b57cec5SDimitry Andric       if (Node->use_empty())
11150b57cec5SDimitry Andric         continue;
11160b57cec5SDimitry Andric 
11170b57cec5SDimitry Andric #ifndef NDEBUG
11180b57cec5SDimitry Andric       SmallVector<SDNode *, 4> Nodes;
11190b57cec5SDimitry Andric       Nodes.push_back(Node);
11200b57cec5SDimitry Andric 
11210b57cec5SDimitry Andric       while (!Nodes.empty()) {
11220b57cec5SDimitry Andric         auto N = Nodes.pop_back_val();
11230b57cec5SDimitry Andric         if (N->getOpcode() == ISD::TokenFactor || N->getNodeId() < 0)
11240b57cec5SDimitry Andric           continue;
11250b57cec5SDimitry Andric         for (const SDValue &Op : N->op_values()) {
11260b57cec5SDimitry Andric           if (Op->getOpcode() == ISD::TokenFactor)
11270b57cec5SDimitry Andric             Nodes.push_back(Op.getNode());
11280b57cec5SDimitry Andric           else {
11290b57cec5SDimitry Andric             // We rely on topological ordering of node ids for checking for
11300b57cec5SDimitry Andric             // cycles when fusing nodes during selection. All unselected nodes
11310b57cec5SDimitry Andric             // successors of an already selected node should have a negative id.
11320b57cec5SDimitry Andric             // This assertion will catch such cases. If this assertion triggers
11330b57cec5SDimitry Andric             // it is likely you using DAG-level Value/Node replacement functions
11340b57cec5SDimitry Andric             // (versus equivalent ISEL replacement) in backend-specific
11350b57cec5SDimitry Andric             // selections. See comment in EnforceNodeIdInvariant for more
11360b57cec5SDimitry Andric             // details.
11370b57cec5SDimitry Andric             assert(Op->getNodeId() != -1 &&
11380b57cec5SDimitry Andric                    "Node has already selected predecessor node");
11390b57cec5SDimitry Andric           }
11400b57cec5SDimitry Andric         }
11410b57cec5SDimitry Andric       }
11420b57cec5SDimitry Andric #endif
11430b57cec5SDimitry Andric 
11440b57cec5SDimitry Andric       // When we are using non-default rounding modes or FP exception behavior
11450b57cec5SDimitry Andric       // FP operations are represented by StrictFP pseudo-operations.  For
11460b57cec5SDimitry Andric       // targets that do not (yet) understand strict FP operations directly,
11470b57cec5SDimitry Andric       // we convert them to normal FP opcodes instead at this point.  This
11480b57cec5SDimitry Andric       // will allow them to be handled by existing target-specific instruction
11490b57cec5SDimitry Andric       // selectors.
1150480093f4SDimitry Andric       if (!TLI->isStrictFPEnabled() && Node->isStrictFPOpcode()) {
1151480093f4SDimitry Andric         // For some opcodes, we need to call TLI->getOperationAction using
1152480093f4SDimitry Andric         // the first operand type instead of the result type.  Note that this
1153480093f4SDimitry Andric         // must match what SelectionDAGLegalize::LegalizeOp is doing.
1154480093f4SDimitry Andric         EVT ActionVT;
1155480093f4SDimitry Andric         switch (Node->getOpcode()) {
1156480093f4SDimitry Andric         case ISD::STRICT_SINT_TO_FP:
1157480093f4SDimitry Andric         case ISD::STRICT_UINT_TO_FP:
1158480093f4SDimitry Andric         case ISD::STRICT_LRINT:
1159480093f4SDimitry Andric         case ISD::STRICT_LLRINT:
1160480093f4SDimitry Andric         case ISD::STRICT_LROUND:
1161480093f4SDimitry Andric         case ISD::STRICT_LLROUND:
1162480093f4SDimitry Andric         case ISD::STRICT_FSETCC:
1163480093f4SDimitry Andric         case ISD::STRICT_FSETCCS:
1164480093f4SDimitry Andric           ActionVT = Node->getOperand(1).getValueType();
1165480093f4SDimitry Andric           break;
1166480093f4SDimitry Andric         default:
1167480093f4SDimitry Andric           ActionVT = Node->getValueType(0);
1168480093f4SDimitry Andric           break;
1169480093f4SDimitry Andric         }
1170480093f4SDimitry Andric         if (TLI->getOperationAction(Node->getOpcode(), ActionVT)
1171480093f4SDimitry Andric             == TargetLowering::Expand)
11720b57cec5SDimitry Andric           Node = CurDAG->mutateStrictFPToFP(Node);
1173480093f4SDimitry Andric       }
11740b57cec5SDimitry Andric 
11750b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "\nISEL: Starting selection on root node: ";
11760b57cec5SDimitry Andric                  Node->dump(CurDAG));
11770b57cec5SDimitry Andric 
11780b57cec5SDimitry Andric       Select(Node);
11790b57cec5SDimitry Andric     }
11800b57cec5SDimitry Andric 
11810b57cec5SDimitry Andric     CurDAG->setRoot(Dummy.getValue());
11820b57cec5SDimitry Andric   }
11830b57cec5SDimitry Andric 
11840b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "\n===== Instruction selection ends:\n");
11850b57cec5SDimitry Andric 
11860b57cec5SDimitry Andric   PostprocessISelDAG();
11870b57cec5SDimitry Andric }
11880b57cec5SDimitry Andric 
11890b57cec5SDimitry Andric static bool hasExceptionPointerOrCodeUser(const CatchPadInst *CPI) {
11900b57cec5SDimitry Andric   for (const User *U : CPI->users()) {
11910b57cec5SDimitry Andric     if (const IntrinsicInst *EHPtrCall = dyn_cast<IntrinsicInst>(U)) {
11920b57cec5SDimitry Andric       Intrinsic::ID IID = EHPtrCall->getIntrinsicID();
11930b57cec5SDimitry Andric       if (IID == Intrinsic::eh_exceptionpointer ||
11940b57cec5SDimitry Andric           IID == Intrinsic::eh_exceptioncode)
11950b57cec5SDimitry Andric         return true;
11960b57cec5SDimitry Andric     }
11970b57cec5SDimitry Andric   }
11980b57cec5SDimitry Andric   return false;
11990b57cec5SDimitry Andric }
12000b57cec5SDimitry Andric 
12010b57cec5SDimitry Andric // wasm.landingpad.index intrinsic is for associating a landing pad index number
12020b57cec5SDimitry Andric // with a catchpad instruction. Retrieve the landing pad index in the intrinsic
12030b57cec5SDimitry Andric // and store the mapping in the function.
12040b57cec5SDimitry Andric static void mapWasmLandingPadIndex(MachineBasicBlock *MBB,
12050b57cec5SDimitry Andric                                    const CatchPadInst *CPI) {
12060b57cec5SDimitry Andric   MachineFunction *MF = MBB->getParent();
12070b57cec5SDimitry Andric   // In case of single catch (...), we don't emit LSDA, so we don't need
12080b57cec5SDimitry Andric   // this information.
12090b57cec5SDimitry Andric   bool IsSingleCatchAllClause =
12100b57cec5SDimitry Andric       CPI->getNumArgOperands() == 1 &&
12110b57cec5SDimitry Andric       cast<Constant>(CPI->getArgOperand(0))->isNullValue();
12120b57cec5SDimitry Andric   if (!IsSingleCatchAllClause) {
12130b57cec5SDimitry Andric     // Create a mapping from landing pad label to landing pad index.
12140b57cec5SDimitry Andric     bool IntrFound = false;
12150b57cec5SDimitry Andric     for (const User *U : CPI->users()) {
12160b57cec5SDimitry Andric       if (const auto *Call = dyn_cast<IntrinsicInst>(U)) {
12170b57cec5SDimitry Andric         Intrinsic::ID IID = Call->getIntrinsicID();
12180b57cec5SDimitry Andric         if (IID == Intrinsic::wasm_landingpad_index) {
12190b57cec5SDimitry Andric           Value *IndexArg = Call->getArgOperand(1);
12200b57cec5SDimitry Andric           int Index = cast<ConstantInt>(IndexArg)->getZExtValue();
12210b57cec5SDimitry Andric           MF->setWasmLandingPadIndex(MBB, Index);
12220b57cec5SDimitry Andric           IntrFound = true;
12230b57cec5SDimitry Andric           break;
12240b57cec5SDimitry Andric         }
12250b57cec5SDimitry Andric       }
12260b57cec5SDimitry Andric     }
12270b57cec5SDimitry Andric     assert(IntrFound && "wasm.landingpad.index intrinsic not found!");
12280b57cec5SDimitry Andric     (void)IntrFound;
12290b57cec5SDimitry Andric   }
12300b57cec5SDimitry Andric }
12310b57cec5SDimitry Andric 
12320b57cec5SDimitry Andric /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
12330b57cec5SDimitry Andric /// do other setup for EH landing-pad blocks.
12340b57cec5SDimitry Andric bool SelectionDAGISel::PrepareEHLandingPad() {
12350b57cec5SDimitry Andric   MachineBasicBlock *MBB = FuncInfo->MBB;
12360b57cec5SDimitry Andric   const Constant *PersonalityFn = FuncInfo->Fn->getPersonalityFn();
12370b57cec5SDimitry Andric   const BasicBlock *LLVMBB = MBB->getBasicBlock();
12380b57cec5SDimitry Andric   const TargetRegisterClass *PtrRC =
12390b57cec5SDimitry Andric       TLI->getRegClassFor(TLI->getPointerTy(CurDAG->getDataLayout()));
12400b57cec5SDimitry Andric 
12410b57cec5SDimitry Andric   auto Pers = classifyEHPersonality(PersonalityFn);
12420b57cec5SDimitry Andric 
12430b57cec5SDimitry Andric   // Catchpads have one live-in register, which typically holds the exception
12440b57cec5SDimitry Andric   // pointer or code.
12450b57cec5SDimitry Andric   if (isFuncletEHPersonality(Pers)) {
12460b57cec5SDimitry Andric     if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) {
12470b57cec5SDimitry Andric       if (hasExceptionPointerOrCodeUser(CPI)) {
12480b57cec5SDimitry Andric         // Get or create the virtual register to hold the pointer or code.  Mark
12490b57cec5SDimitry Andric         // the live in physreg and copy into the vreg.
12500b57cec5SDimitry Andric         MCPhysReg EHPhysReg = TLI->getExceptionPointerRegister(PersonalityFn);
12510b57cec5SDimitry Andric         assert(EHPhysReg && "target lacks exception pointer register");
12520b57cec5SDimitry Andric         MBB->addLiveIn(EHPhysReg);
12530b57cec5SDimitry Andric         unsigned VReg = FuncInfo->getCatchPadExceptionPointerVReg(CPI, PtrRC);
12540b57cec5SDimitry Andric         BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(),
12550b57cec5SDimitry Andric                 TII->get(TargetOpcode::COPY), VReg)
12560b57cec5SDimitry Andric             .addReg(EHPhysReg, RegState::Kill);
12570b57cec5SDimitry Andric       }
12580b57cec5SDimitry Andric     }
12590b57cec5SDimitry Andric     return true;
12600b57cec5SDimitry Andric   }
12610b57cec5SDimitry Andric 
12620b57cec5SDimitry Andric   // Add a label to mark the beginning of the landing pad.  Deletion of the
12630b57cec5SDimitry Andric   // landing pad can thus be detected via the MachineModuleInfo.
12640b57cec5SDimitry Andric   MCSymbol *Label = MF->addLandingPad(MBB);
12650b57cec5SDimitry Andric 
12660b57cec5SDimitry Andric   const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL);
12670b57cec5SDimitry Andric   BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
12680b57cec5SDimitry Andric     .addSym(Label);
12690b57cec5SDimitry Andric 
1270*e8d8bef9SDimitry Andric   // If the unwinder does not preserve all registers, ensure that the
1271*e8d8bef9SDimitry Andric   // function marks the clobbered registers as used.
1272*e8d8bef9SDimitry Andric   const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
1273*e8d8bef9SDimitry Andric   if (auto *RegMask = TRI.getCustomEHPadPreservedMask(*MF))
1274*e8d8bef9SDimitry Andric     MF->getRegInfo().addPhysRegsUsedFromRegMask(RegMask);
1275*e8d8bef9SDimitry Andric 
12760b57cec5SDimitry Andric   if (Pers == EHPersonality::Wasm_CXX) {
12770b57cec5SDimitry Andric     if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI()))
12780b57cec5SDimitry Andric       mapWasmLandingPadIndex(MBB, CPI);
12790b57cec5SDimitry Andric   } else {
12800b57cec5SDimitry Andric     // Assign the call site to the landing pad's begin label.
12810b57cec5SDimitry Andric     MF->setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
12820b57cec5SDimitry Andric     // Mark exception register as live in.
12830b57cec5SDimitry Andric     if (unsigned Reg = TLI->getExceptionPointerRegister(PersonalityFn))
12840b57cec5SDimitry Andric       FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
12850b57cec5SDimitry Andric     // Mark exception selector register as live in.
12860b57cec5SDimitry Andric     if (unsigned Reg = TLI->getExceptionSelectorRegister(PersonalityFn))
12870b57cec5SDimitry Andric       FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
12880b57cec5SDimitry Andric   }
12890b57cec5SDimitry Andric 
12900b57cec5SDimitry Andric   return true;
12910b57cec5SDimitry Andric }
12920b57cec5SDimitry Andric 
12930b57cec5SDimitry Andric /// isFoldedOrDeadInstruction - Return true if the specified instruction is
12940b57cec5SDimitry Andric /// side-effect free and is either dead or folded into a generated instruction.
12950b57cec5SDimitry Andric /// Return false if it needs to be emitted.
12960b57cec5SDimitry Andric static bool isFoldedOrDeadInstruction(const Instruction *I,
1297480093f4SDimitry Andric                                       const FunctionLoweringInfo &FuncInfo) {
12980b57cec5SDimitry Andric   return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
12990b57cec5SDimitry Andric          !I->isTerminator() &&     // Terminators aren't folded.
13000b57cec5SDimitry Andric          !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded.
13010b57cec5SDimitry Andric          !I->isEHPad() &&             // EH pad instructions aren't folded.
1302480093f4SDimitry Andric          !FuncInfo.isExportedInst(I); // Exported instrs must be computed.
13030b57cec5SDimitry Andric }
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric /// Collect llvm.dbg.declare information. This is done after argument lowering
13060b57cec5SDimitry Andric /// in case the declarations refer to arguments.
1307480093f4SDimitry Andric static void processDbgDeclares(FunctionLoweringInfo &FuncInfo) {
1308480093f4SDimitry Andric   MachineFunction *MF = FuncInfo.MF;
13090b57cec5SDimitry Andric   const DataLayout &DL = MF->getDataLayout();
1310480093f4SDimitry Andric   for (const BasicBlock &BB : *FuncInfo.Fn) {
13110b57cec5SDimitry Andric     for (const Instruction &I : BB) {
13120b57cec5SDimitry Andric       const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(&I);
13130b57cec5SDimitry Andric       if (!DI)
13140b57cec5SDimitry Andric         continue;
13150b57cec5SDimitry Andric 
13160b57cec5SDimitry Andric       assert(DI->getVariable() && "Missing variable");
13170b57cec5SDimitry Andric       assert(DI->getDebugLoc() && "Missing location");
13180b57cec5SDimitry Andric       const Value *Address = DI->getAddress();
13195ffd83dbSDimitry Andric       if (!Address) {
13205ffd83dbSDimitry Andric         LLVM_DEBUG(dbgs() << "processDbgDeclares skipping " << *DI
13215ffd83dbSDimitry Andric                           << " (bad address)\n");
13220b57cec5SDimitry Andric         continue;
13235ffd83dbSDimitry Andric       }
13240b57cec5SDimitry Andric 
13250b57cec5SDimitry Andric       // Look through casts and constant offset GEPs. These mostly come from
13260b57cec5SDimitry Andric       // inalloca.
13270b57cec5SDimitry Andric       APInt Offset(DL.getTypeSizeInBits(Address->getType()), 0);
13280b57cec5SDimitry Andric       Address = Address->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
13290b57cec5SDimitry Andric 
13300b57cec5SDimitry Andric       // Check if the variable is a static alloca or a byval or inalloca
13310b57cec5SDimitry Andric       // argument passed in memory. If it is not, then we will ignore this
13320b57cec5SDimitry Andric       // intrinsic and handle this during isel like dbg.value.
13330b57cec5SDimitry Andric       int FI = std::numeric_limits<int>::max();
13340b57cec5SDimitry Andric       if (const auto *AI = dyn_cast<AllocaInst>(Address)) {
1335480093f4SDimitry Andric         auto SI = FuncInfo.StaticAllocaMap.find(AI);
1336480093f4SDimitry Andric         if (SI != FuncInfo.StaticAllocaMap.end())
13370b57cec5SDimitry Andric           FI = SI->second;
13380b57cec5SDimitry Andric       } else if (const auto *Arg = dyn_cast<Argument>(Address))
1339480093f4SDimitry Andric         FI = FuncInfo.getArgumentFrameIndex(Arg);
13400b57cec5SDimitry Andric 
13410b57cec5SDimitry Andric       if (FI == std::numeric_limits<int>::max())
13420b57cec5SDimitry Andric         continue;
13430b57cec5SDimitry Andric 
13440b57cec5SDimitry Andric       DIExpression *Expr = DI->getExpression();
13450b57cec5SDimitry Andric       if (Offset.getBoolValue())
13460b57cec5SDimitry Andric         Expr = DIExpression::prepend(Expr, DIExpression::ApplyOffset,
13470b57cec5SDimitry Andric                                      Offset.getZExtValue());
13485ffd83dbSDimitry Andric       LLVM_DEBUG(dbgs() << "processDbgDeclares: setVariableDbgInfo FI=" << FI
13495ffd83dbSDimitry Andric                         << ", " << *DI << "\n");
13500b57cec5SDimitry Andric       MF->setVariableDbgInfo(DI->getVariable(), Expr, FI, DI->getDebugLoc());
13510b57cec5SDimitry Andric     }
13520b57cec5SDimitry Andric   }
13530b57cec5SDimitry Andric }
13540b57cec5SDimitry Andric 
13550b57cec5SDimitry Andric void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
13560b57cec5SDimitry Andric   FastISelFailed = false;
13570b57cec5SDimitry Andric   // Initialize the Fast-ISel state, if needed.
13580b57cec5SDimitry Andric   FastISel *FastIS = nullptr;
13590b57cec5SDimitry Andric   if (TM.Options.EnableFastISel) {
13600b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Enabling fast-isel\n");
13610b57cec5SDimitry Andric     FastIS = TLI->createFastISel(*FuncInfo, LibInfo);
13620b57cec5SDimitry Andric   }
13630b57cec5SDimitry Andric 
13640b57cec5SDimitry Andric   ReversePostOrderTraversal<const Function*> RPOT(&Fn);
13650b57cec5SDimitry Andric 
13660b57cec5SDimitry Andric   // Lower arguments up front. An RPO iteration always visits the entry block
13670b57cec5SDimitry Andric   // first.
13680b57cec5SDimitry Andric   assert(*RPOT.begin() == &Fn.getEntryBlock());
13690b57cec5SDimitry Andric   ++NumEntryBlocks;
13700b57cec5SDimitry Andric 
13710b57cec5SDimitry Andric   // Set up FuncInfo for ISel. Entry blocks never have PHIs.
13720b57cec5SDimitry Andric   FuncInfo->MBB = FuncInfo->MBBMap[&Fn.getEntryBlock()];
13730b57cec5SDimitry Andric   FuncInfo->InsertPt = FuncInfo->MBB->begin();
13740b57cec5SDimitry Andric 
1375480093f4SDimitry Andric   CurDAG->setFunctionLoweringInfo(FuncInfo.get());
13760b57cec5SDimitry Andric 
13770b57cec5SDimitry Andric   if (!FastIS) {
13780b57cec5SDimitry Andric     LowerArguments(Fn);
13790b57cec5SDimitry Andric   } else {
13800b57cec5SDimitry Andric     // See if fast isel can lower the arguments.
13810b57cec5SDimitry Andric     FastIS->startNewBlock();
13820b57cec5SDimitry Andric     if (!FastIS->lowerArguments()) {
13830b57cec5SDimitry Andric       FastISelFailed = true;
13840b57cec5SDimitry Andric       // Fast isel failed to lower these arguments
13850b57cec5SDimitry Andric       ++NumFastIselFailLowerArguments;
13860b57cec5SDimitry Andric 
13870b57cec5SDimitry Andric       OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
13880b57cec5SDimitry Andric                                  Fn.getSubprogram(),
13890b57cec5SDimitry Andric                                  &Fn.getEntryBlock());
13900b57cec5SDimitry Andric       R << "FastISel didn't lower all arguments: "
13910b57cec5SDimitry Andric         << ore::NV("Prototype", Fn.getType());
13920b57cec5SDimitry Andric       reportFastISelFailure(*MF, *ORE, R, EnableFastISelAbort > 1);
13930b57cec5SDimitry Andric 
13940b57cec5SDimitry Andric       // Use SelectionDAG argument lowering
13950b57cec5SDimitry Andric       LowerArguments(Fn);
13960b57cec5SDimitry Andric       CurDAG->setRoot(SDB->getControlRoot());
13970b57cec5SDimitry Andric       SDB->clear();
13980b57cec5SDimitry Andric       CodeGenAndEmitDAG();
13990b57cec5SDimitry Andric     }
14000b57cec5SDimitry Andric 
14010b57cec5SDimitry Andric     // If we inserted any instructions at the beginning, make a note of
14020b57cec5SDimitry Andric     // where they are, so we can be sure to emit subsequent instructions
14030b57cec5SDimitry Andric     // after them.
14040b57cec5SDimitry Andric     if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
14050b57cec5SDimitry Andric       FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
14060b57cec5SDimitry Andric     else
14070b57cec5SDimitry Andric       FastIS->setLastLocalValue(nullptr);
14080b57cec5SDimitry Andric   }
14090b57cec5SDimitry Andric 
14100b57cec5SDimitry Andric   bool Inserted = SwiftError->createEntriesInEntryBlock(SDB->getCurDebugLoc());
14110b57cec5SDimitry Andric 
14120b57cec5SDimitry Andric   if (FastIS && Inserted)
14130b57cec5SDimitry Andric     FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
14140b57cec5SDimitry Andric 
1415480093f4SDimitry Andric   processDbgDeclares(*FuncInfo);
14160b57cec5SDimitry Andric 
14170b57cec5SDimitry Andric   // Iterate over all basic blocks in the function.
14180b57cec5SDimitry Andric   StackProtector &SP = getAnalysis<StackProtector>();
14190b57cec5SDimitry Andric   for (const BasicBlock *LLVMBB : RPOT) {
14200b57cec5SDimitry Andric     if (OptLevel != CodeGenOpt::None) {
14210b57cec5SDimitry Andric       bool AllPredsVisited = true;
14220b57cec5SDimitry Andric       for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB);
14230b57cec5SDimitry Andric            PI != PE; ++PI) {
14240b57cec5SDimitry Andric         if (!FuncInfo->VisitedBBs.count(*PI)) {
14250b57cec5SDimitry Andric           AllPredsVisited = false;
14260b57cec5SDimitry Andric           break;
14270b57cec5SDimitry Andric         }
14280b57cec5SDimitry Andric       }
14290b57cec5SDimitry Andric 
14300b57cec5SDimitry Andric       if (AllPredsVisited) {
14310b57cec5SDimitry Andric         for (const PHINode &PN : LLVMBB->phis())
14320b57cec5SDimitry Andric           FuncInfo->ComputePHILiveOutRegInfo(&PN);
14330b57cec5SDimitry Andric       } else {
14340b57cec5SDimitry Andric         for (const PHINode &PN : LLVMBB->phis())
14350b57cec5SDimitry Andric           FuncInfo->InvalidatePHILiveOutRegInfo(&PN);
14360b57cec5SDimitry Andric       }
14370b57cec5SDimitry Andric 
14380b57cec5SDimitry Andric       FuncInfo->VisitedBBs.insert(LLVMBB);
14390b57cec5SDimitry Andric     }
14400b57cec5SDimitry Andric 
14410b57cec5SDimitry Andric     BasicBlock::const_iterator const Begin =
14420b57cec5SDimitry Andric         LLVMBB->getFirstNonPHI()->getIterator();
14430b57cec5SDimitry Andric     BasicBlock::const_iterator const End = LLVMBB->end();
14440b57cec5SDimitry Andric     BasicBlock::const_iterator BI = End;
14450b57cec5SDimitry Andric 
14460b57cec5SDimitry Andric     FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
14470b57cec5SDimitry Andric     if (!FuncInfo->MBB)
14480b57cec5SDimitry Andric       continue; // Some blocks like catchpads have no code or MBB.
14490b57cec5SDimitry Andric 
14500b57cec5SDimitry Andric     // Insert new instructions after any phi or argument setup code.
14510b57cec5SDimitry Andric     FuncInfo->InsertPt = FuncInfo->MBB->end();
14520b57cec5SDimitry Andric 
14530b57cec5SDimitry Andric     // Setup an EH landing-pad block.
14540b57cec5SDimitry Andric     FuncInfo->ExceptionPointerVirtReg = 0;
14550b57cec5SDimitry Andric     FuncInfo->ExceptionSelectorVirtReg = 0;
14560b57cec5SDimitry Andric     if (LLVMBB->isEHPad())
14570b57cec5SDimitry Andric       if (!PrepareEHLandingPad())
14580b57cec5SDimitry Andric         continue;
14590b57cec5SDimitry Andric 
14600b57cec5SDimitry Andric     // Before doing SelectionDAG ISel, see if FastISel has been requested.
14610b57cec5SDimitry Andric     if (FastIS) {
14620b57cec5SDimitry Andric       if (LLVMBB != &Fn.getEntryBlock())
14630b57cec5SDimitry Andric         FastIS->startNewBlock();
14640b57cec5SDimitry Andric 
14650b57cec5SDimitry Andric       unsigned NumFastIselRemaining = std::distance(Begin, End);
14660b57cec5SDimitry Andric 
14670b57cec5SDimitry Andric       // Pre-assign swifterror vregs.
14680b57cec5SDimitry Andric       SwiftError->preassignVRegs(FuncInfo->MBB, Begin, End);
14690b57cec5SDimitry Andric 
14700b57cec5SDimitry Andric       // Do FastISel on as many instructions as possible.
14710b57cec5SDimitry Andric       for (; BI != Begin; --BI) {
14720b57cec5SDimitry Andric         const Instruction *Inst = &*std::prev(BI);
14730b57cec5SDimitry Andric 
14740b57cec5SDimitry Andric         // If we no longer require this instruction, skip it.
1475480093f4SDimitry Andric         if (isFoldedOrDeadInstruction(Inst, *FuncInfo) ||
14760b57cec5SDimitry Andric             ElidedArgCopyInstrs.count(Inst)) {
14770b57cec5SDimitry Andric           --NumFastIselRemaining;
14780b57cec5SDimitry Andric           continue;
14790b57cec5SDimitry Andric         }
14800b57cec5SDimitry Andric 
14810b57cec5SDimitry Andric         // Bottom-up: reset the insert pos at the top, after any local-value
14820b57cec5SDimitry Andric         // instructions.
14830b57cec5SDimitry Andric         FastIS->recomputeInsertPt();
14840b57cec5SDimitry Andric 
14850b57cec5SDimitry Andric         // Try to select the instruction with FastISel.
14860b57cec5SDimitry Andric         if (FastIS->selectInstruction(Inst)) {
14870b57cec5SDimitry Andric           --NumFastIselRemaining;
14880b57cec5SDimitry Andric           ++NumFastIselSuccess;
14890b57cec5SDimitry Andric           // If fast isel succeeded, skip over all the folded instructions, and
14900b57cec5SDimitry Andric           // then see if there is a load right before the selected instructions.
14910b57cec5SDimitry Andric           // Try to fold the load if so.
14920b57cec5SDimitry Andric           const Instruction *BeforeInst = Inst;
14930b57cec5SDimitry Andric           while (BeforeInst != &*Begin) {
14940b57cec5SDimitry Andric             BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst));
1495480093f4SDimitry Andric             if (!isFoldedOrDeadInstruction(BeforeInst, *FuncInfo))
14960b57cec5SDimitry Andric               break;
14970b57cec5SDimitry Andric           }
14980b57cec5SDimitry Andric           if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
14990b57cec5SDimitry Andric               BeforeInst->hasOneUse() &&
15000b57cec5SDimitry Andric               FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
15010b57cec5SDimitry Andric             // If we succeeded, don't re-select the load.
15020b57cec5SDimitry Andric             BI = std::next(BasicBlock::const_iterator(BeforeInst));
15030b57cec5SDimitry Andric             --NumFastIselRemaining;
15040b57cec5SDimitry Andric             ++NumFastIselSuccess;
15050b57cec5SDimitry Andric           }
15060b57cec5SDimitry Andric           continue;
15070b57cec5SDimitry Andric         }
15080b57cec5SDimitry Andric 
15090b57cec5SDimitry Andric         FastISelFailed = true;
15100b57cec5SDimitry Andric 
15110b57cec5SDimitry Andric         // Then handle certain instructions as single-LLVM-Instruction blocks.
15120b57cec5SDimitry Andric         // We cannot separate out GCrelocates to their own blocks since we need
15130b57cec5SDimitry Andric         // to keep track of gc-relocates for a particular gc-statepoint. This is
15140b57cec5SDimitry Andric         // done by SelectionDAGBuilder::LowerAsSTATEPOINT, called before
15150b57cec5SDimitry Andric         // visitGCRelocate.
15165ffd83dbSDimitry Andric         if (isa<CallInst>(Inst) && !isa<GCStatepointInst>(Inst) &&
15175ffd83dbSDimitry Andric             !isa<GCRelocateInst>(Inst) && !isa<GCResultInst>(Inst)) {
15180b57cec5SDimitry Andric           OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
15190b57cec5SDimitry Andric                                      Inst->getDebugLoc(), LLVMBB);
15200b57cec5SDimitry Andric 
15210b57cec5SDimitry Andric           R << "FastISel missed call";
15220b57cec5SDimitry Andric 
15230b57cec5SDimitry Andric           if (R.isEnabled() || EnableFastISelAbort) {
15240b57cec5SDimitry Andric             std::string InstStrStorage;
15250b57cec5SDimitry Andric             raw_string_ostream InstStr(InstStrStorage);
15260b57cec5SDimitry Andric             InstStr << *Inst;
15270b57cec5SDimitry Andric 
15280b57cec5SDimitry Andric             R << ": " << InstStr.str();
15290b57cec5SDimitry Andric           }
15300b57cec5SDimitry Andric 
15310b57cec5SDimitry Andric           reportFastISelFailure(*MF, *ORE, R, EnableFastISelAbort > 2);
15320b57cec5SDimitry Andric 
15330b57cec5SDimitry Andric           if (!Inst->getType()->isVoidTy() && !Inst->getType()->isTokenTy() &&
15340b57cec5SDimitry Andric               !Inst->use_empty()) {
15355ffd83dbSDimitry Andric             Register &R = FuncInfo->ValueMap[Inst];
15360b57cec5SDimitry Andric             if (!R)
15370b57cec5SDimitry Andric               R = FuncInfo->CreateRegs(Inst);
15380b57cec5SDimitry Andric           }
15390b57cec5SDimitry Andric 
15400b57cec5SDimitry Andric           bool HadTailCall = false;
15410b57cec5SDimitry Andric           MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
15420b57cec5SDimitry Andric           SelectBasicBlock(Inst->getIterator(), BI, HadTailCall);
15430b57cec5SDimitry Andric 
15440b57cec5SDimitry Andric           // If the call was emitted as a tail call, we're done with the block.
15450b57cec5SDimitry Andric           // We also need to delete any previously emitted instructions.
15460b57cec5SDimitry Andric           if (HadTailCall) {
15470b57cec5SDimitry Andric             FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
15480b57cec5SDimitry Andric             --BI;
15490b57cec5SDimitry Andric             break;
15500b57cec5SDimitry Andric           }
15510b57cec5SDimitry Andric 
15520b57cec5SDimitry Andric           // Recompute NumFastIselRemaining as Selection DAG instruction
15530b57cec5SDimitry Andric           // selection may have handled the call, input args, etc.
15540b57cec5SDimitry Andric           unsigned RemainingNow = std::distance(Begin, BI);
15550b57cec5SDimitry Andric           NumFastIselFailures += NumFastIselRemaining - RemainingNow;
15560b57cec5SDimitry Andric           NumFastIselRemaining = RemainingNow;
15570b57cec5SDimitry Andric           continue;
15580b57cec5SDimitry Andric         }
15590b57cec5SDimitry Andric 
15600b57cec5SDimitry Andric         OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
15610b57cec5SDimitry Andric                                    Inst->getDebugLoc(), LLVMBB);
15620b57cec5SDimitry Andric 
15630b57cec5SDimitry Andric         bool ShouldAbort = EnableFastISelAbort;
15640b57cec5SDimitry Andric         if (Inst->isTerminator()) {
15650b57cec5SDimitry Andric           // Use a different message for terminator misses.
15660b57cec5SDimitry Andric           R << "FastISel missed terminator";
15670b57cec5SDimitry Andric           // Don't abort for terminator unless the level is really high
15680b57cec5SDimitry Andric           ShouldAbort = (EnableFastISelAbort > 2);
15690b57cec5SDimitry Andric         } else {
15700b57cec5SDimitry Andric           R << "FastISel missed";
15710b57cec5SDimitry Andric         }
15720b57cec5SDimitry Andric 
15730b57cec5SDimitry Andric         if (R.isEnabled() || EnableFastISelAbort) {
15740b57cec5SDimitry Andric           std::string InstStrStorage;
15750b57cec5SDimitry Andric           raw_string_ostream InstStr(InstStrStorage);
15760b57cec5SDimitry Andric           InstStr << *Inst;
15770b57cec5SDimitry Andric           R << ": " << InstStr.str();
15780b57cec5SDimitry Andric         }
15790b57cec5SDimitry Andric 
15800b57cec5SDimitry Andric         reportFastISelFailure(*MF, *ORE, R, ShouldAbort);
15810b57cec5SDimitry Andric 
15820b57cec5SDimitry Andric         NumFastIselFailures += NumFastIselRemaining;
15830b57cec5SDimitry Andric         break;
15840b57cec5SDimitry Andric       }
15850b57cec5SDimitry Andric 
15860b57cec5SDimitry Andric       FastIS->recomputeInsertPt();
15870b57cec5SDimitry Andric     }
15880b57cec5SDimitry Andric 
15890b57cec5SDimitry Andric     if (SP.shouldEmitSDCheck(*LLVMBB)) {
15900b57cec5SDimitry Andric       bool FunctionBasedInstrumentation =
15910b57cec5SDimitry Andric           TLI->getSSPStackGuardCheck(*Fn.getParent());
15920b57cec5SDimitry Andric       SDB->SPDescriptor.initialize(LLVMBB, FuncInfo->MBBMap[LLVMBB],
15930b57cec5SDimitry Andric                                    FunctionBasedInstrumentation);
15940b57cec5SDimitry Andric     }
15950b57cec5SDimitry Andric 
15960b57cec5SDimitry Andric     if (Begin != BI)
15970b57cec5SDimitry Andric       ++NumDAGBlocks;
15980b57cec5SDimitry Andric     else
15990b57cec5SDimitry Andric       ++NumFastIselBlocks;
16000b57cec5SDimitry Andric 
16010b57cec5SDimitry Andric     if (Begin != BI) {
16020b57cec5SDimitry Andric       // Run SelectionDAG instruction selection on the remainder of the block
16030b57cec5SDimitry Andric       // not handled by FastISel. If FastISel is not run, this is the entire
16040b57cec5SDimitry Andric       // block.
16050b57cec5SDimitry Andric       bool HadTailCall;
16060b57cec5SDimitry Andric       SelectBasicBlock(Begin, BI, HadTailCall);
16070b57cec5SDimitry Andric 
16080b57cec5SDimitry Andric       // But if FastISel was run, we already selected some of the block.
16090b57cec5SDimitry Andric       // If we emitted a tail-call, we need to delete any previously emitted
16100b57cec5SDimitry Andric       // instruction that follows it.
1611480093f4SDimitry Andric       if (FastIS && HadTailCall && FuncInfo->InsertPt != FuncInfo->MBB->end())
16120b57cec5SDimitry Andric         FastIS->removeDeadCode(FuncInfo->InsertPt, FuncInfo->MBB->end());
16130b57cec5SDimitry Andric     }
16140b57cec5SDimitry Andric 
16150b57cec5SDimitry Andric     if (FastIS)
16160b57cec5SDimitry Andric       FastIS->finishBasicBlock();
16170b57cec5SDimitry Andric     FinishBasicBlock();
16180b57cec5SDimitry Andric     FuncInfo->PHINodesToUpdate.clear();
16190b57cec5SDimitry Andric     ElidedArgCopyInstrs.clear();
16200b57cec5SDimitry Andric   }
16210b57cec5SDimitry Andric 
16220b57cec5SDimitry Andric   SP.copyToMachineFrameInfo(MF->getFrameInfo());
16230b57cec5SDimitry Andric 
16240b57cec5SDimitry Andric   SwiftError->propagateVRegs();
16250b57cec5SDimitry Andric 
16260b57cec5SDimitry Andric   delete FastIS;
16270b57cec5SDimitry Andric   SDB->clearDanglingDebugInfo();
16280b57cec5SDimitry Andric   SDB->SPDescriptor.resetPerFunctionState();
16290b57cec5SDimitry Andric }
16300b57cec5SDimitry Andric 
16310b57cec5SDimitry Andric /// Given that the input MI is before a partial terminator sequence TSeq, return
16320b57cec5SDimitry Andric /// true if M + TSeq also a partial terminator sequence.
16330b57cec5SDimitry Andric ///
16340b57cec5SDimitry Andric /// A Terminator sequence is a sequence of MachineInstrs which at this point in
16350b57cec5SDimitry Andric /// lowering copy vregs into physical registers, which are then passed into
16360b57cec5SDimitry Andric /// terminator instructors so we can satisfy ABI constraints. A partial
16370b57cec5SDimitry Andric /// terminator sequence is an improper subset of a terminator sequence (i.e. it
16380b57cec5SDimitry Andric /// may be the whole terminator sequence).
16390b57cec5SDimitry Andric static bool MIIsInTerminatorSequence(const MachineInstr &MI) {
16400b57cec5SDimitry Andric   // If we do not have a copy or an implicit def, we return true if and only if
16410b57cec5SDimitry Andric   // MI is a debug value.
16420b57cec5SDimitry Andric   if (!MI.isCopy() && !MI.isImplicitDef())
16430b57cec5SDimitry Andric     // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the
16440b57cec5SDimitry Andric     // physical registers if there is debug info associated with the terminator
16450b57cec5SDimitry Andric     // of our mbb. We want to include said debug info in our terminator
16460b57cec5SDimitry Andric     // sequence, so we return true in that case.
16470b57cec5SDimitry Andric     return MI.isDebugValue();
16480b57cec5SDimitry Andric 
16490b57cec5SDimitry Andric   // We have left the terminator sequence if we are not doing one of the
16500b57cec5SDimitry Andric   // following:
16510b57cec5SDimitry Andric   //
16520b57cec5SDimitry Andric   // 1. Copying a vreg into a physical register.
16530b57cec5SDimitry Andric   // 2. Copying a vreg into a vreg.
16540b57cec5SDimitry Andric   // 3. Defining a register via an implicit def.
16550b57cec5SDimitry Andric 
16560b57cec5SDimitry Andric   // OPI should always be a register definition...
16570b57cec5SDimitry Andric   MachineInstr::const_mop_iterator OPI = MI.operands_begin();
16580b57cec5SDimitry Andric   if (!OPI->isReg() || !OPI->isDef())
16590b57cec5SDimitry Andric     return false;
16600b57cec5SDimitry Andric 
16610b57cec5SDimitry Andric   // Defining any register via an implicit def is always ok.
16620b57cec5SDimitry Andric   if (MI.isImplicitDef())
16630b57cec5SDimitry Andric     return true;
16640b57cec5SDimitry Andric 
16650b57cec5SDimitry Andric   // Grab the copy source...
16660b57cec5SDimitry Andric   MachineInstr::const_mop_iterator OPI2 = OPI;
16670b57cec5SDimitry Andric   ++OPI2;
16680b57cec5SDimitry Andric   assert(OPI2 != MI.operands_end()
16690b57cec5SDimitry Andric          && "Should have a copy implying we should have 2 arguments.");
16700b57cec5SDimitry Andric 
16710b57cec5SDimitry Andric   // Make sure that the copy dest is not a vreg when the copy source is a
16720b57cec5SDimitry Andric   // physical register.
16738bcb0991SDimitry Andric   if (!OPI2->isReg() || (!Register::isPhysicalRegister(OPI->getReg()) &&
16748bcb0991SDimitry Andric                          Register::isPhysicalRegister(OPI2->getReg())))
16750b57cec5SDimitry Andric     return false;
16760b57cec5SDimitry Andric 
16770b57cec5SDimitry Andric   return true;
16780b57cec5SDimitry Andric }
16790b57cec5SDimitry Andric 
16800b57cec5SDimitry Andric /// Find the split point at which to splice the end of BB into its success stack
16810b57cec5SDimitry Andric /// protector check machine basic block.
16820b57cec5SDimitry Andric ///
16830b57cec5SDimitry Andric /// On many platforms, due to ABI constraints, terminators, even before register
16840b57cec5SDimitry Andric /// allocation, use physical registers. This creates an issue for us since
16850b57cec5SDimitry Andric /// physical registers at this point can not travel across basic
16860b57cec5SDimitry Andric /// blocks. Luckily, selectiondag always moves physical registers into vregs
16870b57cec5SDimitry Andric /// when they enter functions and moves them through a sequence of copies back
16880b57cec5SDimitry Andric /// into the physical registers right before the terminator creating a
16890b57cec5SDimitry Andric /// ``Terminator Sequence''. This function is searching for the beginning of the
16900b57cec5SDimitry Andric /// terminator sequence so that we can ensure that we splice off not just the
16910b57cec5SDimitry Andric /// terminator, but additionally the copies that move the vregs into the
16920b57cec5SDimitry Andric /// physical registers.
16930b57cec5SDimitry Andric static MachineBasicBlock::iterator
16940b57cec5SDimitry Andric FindSplitPointForStackProtector(MachineBasicBlock *BB) {
16950b57cec5SDimitry Andric   MachineBasicBlock::iterator SplitPoint = BB->getFirstTerminator();
16960b57cec5SDimitry Andric   //
16970b57cec5SDimitry Andric   if (SplitPoint == BB->begin())
16980b57cec5SDimitry Andric     return SplitPoint;
16990b57cec5SDimitry Andric 
17000b57cec5SDimitry Andric   MachineBasicBlock::iterator Start = BB->begin();
17010b57cec5SDimitry Andric   MachineBasicBlock::iterator Previous = SplitPoint;
17020b57cec5SDimitry Andric   --Previous;
17030b57cec5SDimitry Andric 
17040b57cec5SDimitry Andric   while (MIIsInTerminatorSequence(*Previous)) {
17050b57cec5SDimitry Andric     SplitPoint = Previous;
17060b57cec5SDimitry Andric     if (Previous == Start)
17070b57cec5SDimitry Andric       break;
17080b57cec5SDimitry Andric     --Previous;
17090b57cec5SDimitry Andric   }
17100b57cec5SDimitry Andric 
17110b57cec5SDimitry Andric   return SplitPoint;
17120b57cec5SDimitry Andric }
17130b57cec5SDimitry Andric 
17140b57cec5SDimitry Andric void
17150b57cec5SDimitry Andric SelectionDAGISel::FinishBasicBlock() {
17160b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Total amount of phi nodes to update: "
17170b57cec5SDimitry Andric                     << FuncInfo->PHINodesToUpdate.size() << "\n";
17180b57cec5SDimitry Andric              for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e;
17190b57cec5SDimitry Andric                   ++i) dbgs()
17200b57cec5SDimitry Andric              << "Node " << i << " : (" << FuncInfo->PHINodesToUpdate[i].first
17210b57cec5SDimitry Andric              << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
17220b57cec5SDimitry Andric 
17230b57cec5SDimitry Andric   // Next, now that we know what the last MBB the LLVM BB expanded is, update
17240b57cec5SDimitry Andric   // PHI nodes in successors.
17250b57cec5SDimitry Andric   for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
17260b57cec5SDimitry Andric     MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
17270b57cec5SDimitry Andric     assert(PHI->isPHI() &&
17280b57cec5SDimitry Andric            "This is not a machine PHI node that we are updating!");
17290b57cec5SDimitry Andric     if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
17300b57cec5SDimitry Andric       continue;
17310b57cec5SDimitry Andric     PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
17320b57cec5SDimitry Andric   }
17330b57cec5SDimitry Andric 
17340b57cec5SDimitry Andric   // Handle stack protector.
17350b57cec5SDimitry Andric   if (SDB->SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) {
17360b57cec5SDimitry Andric     // The target provides a guard check function. There is no need to
17370b57cec5SDimitry Andric     // generate error handling code or to split current basic block.
17380b57cec5SDimitry Andric     MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
17390b57cec5SDimitry Andric 
17400b57cec5SDimitry Andric     // Add load and check to the basicblock.
17410b57cec5SDimitry Andric     FuncInfo->MBB = ParentMBB;
17420b57cec5SDimitry Andric     FuncInfo->InsertPt =
17430b57cec5SDimitry Andric         FindSplitPointForStackProtector(ParentMBB);
17440b57cec5SDimitry Andric     SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
17450b57cec5SDimitry Andric     CurDAG->setRoot(SDB->getRoot());
17460b57cec5SDimitry Andric     SDB->clear();
17470b57cec5SDimitry Andric     CodeGenAndEmitDAG();
17480b57cec5SDimitry Andric 
17490b57cec5SDimitry Andric     // Clear the Per-BB State.
17500b57cec5SDimitry Andric     SDB->SPDescriptor.resetPerBBState();
17510b57cec5SDimitry Andric   } else if (SDB->SPDescriptor.shouldEmitStackProtector()) {
17520b57cec5SDimitry Andric     MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
17530b57cec5SDimitry Andric     MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB();
17540b57cec5SDimitry Andric 
17550b57cec5SDimitry Andric     // Find the split point to split the parent mbb. At the same time copy all
17560b57cec5SDimitry Andric     // physical registers used in the tail of parent mbb into virtual registers
17570b57cec5SDimitry Andric     // before the split point and back into physical registers after the split
17580b57cec5SDimitry Andric     // point. This prevents us needing to deal with Live-ins and many other
17590b57cec5SDimitry Andric     // register allocation issues caused by us splitting the parent mbb. The
17600b57cec5SDimitry Andric     // register allocator will clean up said virtual copies later on.
17610b57cec5SDimitry Andric     MachineBasicBlock::iterator SplitPoint =
17620b57cec5SDimitry Andric         FindSplitPointForStackProtector(ParentMBB);
17630b57cec5SDimitry Andric 
17640b57cec5SDimitry Andric     // Splice the terminator of ParentMBB into SuccessMBB.
17650b57cec5SDimitry Andric     SuccessMBB->splice(SuccessMBB->end(), ParentMBB,
17660b57cec5SDimitry Andric                        SplitPoint,
17670b57cec5SDimitry Andric                        ParentMBB->end());
17680b57cec5SDimitry Andric 
17690b57cec5SDimitry Andric     // Add compare/jump on neq/jump to the parent BB.
17700b57cec5SDimitry Andric     FuncInfo->MBB = ParentMBB;
17710b57cec5SDimitry Andric     FuncInfo->InsertPt = ParentMBB->end();
17720b57cec5SDimitry Andric     SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
17730b57cec5SDimitry Andric     CurDAG->setRoot(SDB->getRoot());
17740b57cec5SDimitry Andric     SDB->clear();
17750b57cec5SDimitry Andric     CodeGenAndEmitDAG();
17760b57cec5SDimitry Andric 
17770b57cec5SDimitry Andric     // CodeGen Failure MBB if we have not codegened it yet.
17780b57cec5SDimitry Andric     MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB();
17790b57cec5SDimitry Andric     if (FailureMBB->empty()) {
17800b57cec5SDimitry Andric       FuncInfo->MBB = FailureMBB;
17810b57cec5SDimitry Andric       FuncInfo->InsertPt = FailureMBB->end();
17820b57cec5SDimitry Andric       SDB->visitSPDescriptorFailure(SDB->SPDescriptor);
17830b57cec5SDimitry Andric       CurDAG->setRoot(SDB->getRoot());
17840b57cec5SDimitry Andric       SDB->clear();
17850b57cec5SDimitry Andric       CodeGenAndEmitDAG();
17860b57cec5SDimitry Andric     }
17870b57cec5SDimitry Andric 
17880b57cec5SDimitry Andric     // Clear the Per-BB State.
17890b57cec5SDimitry Andric     SDB->SPDescriptor.resetPerBBState();
17900b57cec5SDimitry Andric   }
17910b57cec5SDimitry Andric 
17920b57cec5SDimitry Andric   // Lower each BitTestBlock.
17930b57cec5SDimitry Andric   for (auto &BTB : SDB->SL->BitTestCases) {
17940b57cec5SDimitry Andric     // Lower header first, if it wasn't already lowered
17950b57cec5SDimitry Andric     if (!BTB.Emitted) {
17960b57cec5SDimitry Andric       // Set the current basic block to the mbb we wish to insert the code into
17970b57cec5SDimitry Andric       FuncInfo->MBB = BTB.Parent;
17980b57cec5SDimitry Andric       FuncInfo->InsertPt = FuncInfo->MBB->end();
17990b57cec5SDimitry Andric       // Emit the code
18000b57cec5SDimitry Andric       SDB->visitBitTestHeader(BTB, FuncInfo->MBB);
18010b57cec5SDimitry Andric       CurDAG->setRoot(SDB->getRoot());
18020b57cec5SDimitry Andric       SDB->clear();
18030b57cec5SDimitry Andric       CodeGenAndEmitDAG();
18040b57cec5SDimitry Andric     }
18050b57cec5SDimitry Andric 
18060b57cec5SDimitry Andric     BranchProbability UnhandledProb = BTB.Prob;
18070b57cec5SDimitry Andric     for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
18080b57cec5SDimitry Andric       UnhandledProb -= BTB.Cases[j].ExtraProb;
18090b57cec5SDimitry Andric       // Set the current basic block to the mbb we wish to insert the code into
18100b57cec5SDimitry Andric       FuncInfo->MBB = BTB.Cases[j].ThisBB;
18110b57cec5SDimitry Andric       FuncInfo->InsertPt = FuncInfo->MBB->end();
18120b57cec5SDimitry Andric       // Emit the code
18130b57cec5SDimitry Andric 
18140b57cec5SDimitry Andric       // If all cases cover a contiguous range, it is not necessary to jump to
18150b57cec5SDimitry Andric       // the default block after the last bit test fails. This is because the
18160b57cec5SDimitry Andric       // range check during bit test header creation has guaranteed that every
18170b57cec5SDimitry Andric       // case here doesn't go outside the range. In this case, there is no need
18180b57cec5SDimitry Andric       // to perform the last bit test, as it will always be true. Instead, make
18190b57cec5SDimitry Andric       // the second-to-last bit-test fall through to the target of the last bit
18200b57cec5SDimitry Andric       // test, and delete the last bit test.
18210b57cec5SDimitry Andric 
18220b57cec5SDimitry Andric       MachineBasicBlock *NextMBB;
18230b57cec5SDimitry Andric       if (BTB.ContiguousRange && j + 2 == ej) {
18240b57cec5SDimitry Andric         // Second-to-last bit-test with contiguous range: fall through to the
18250b57cec5SDimitry Andric         // target of the final bit test.
18260b57cec5SDimitry Andric         NextMBB = BTB.Cases[j + 1].TargetBB;
18270b57cec5SDimitry Andric       } else if (j + 1 == ej) {
18280b57cec5SDimitry Andric         // For the last bit test, fall through to Default.
18290b57cec5SDimitry Andric         NextMBB = BTB.Default;
18300b57cec5SDimitry Andric       } else {
18310b57cec5SDimitry Andric         // Otherwise, fall through to the next bit test.
18320b57cec5SDimitry Andric         NextMBB = BTB.Cases[j + 1].ThisBB;
18330b57cec5SDimitry Andric       }
18340b57cec5SDimitry Andric 
18350b57cec5SDimitry Andric       SDB->visitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j],
18360b57cec5SDimitry Andric                             FuncInfo->MBB);
18370b57cec5SDimitry Andric 
18380b57cec5SDimitry Andric       CurDAG->setRoot(SDB->getRoot());
18390b57cec5SDimitry Andric       SDB->clear();
18400b57cec5SDimitry Andric       CodeGenAndEmitDAG();
18410b57cec5SDimitry Andric 
18420b57cec5SDimitry Andric       if (BTB.ContiguousRange && j + 2 == ej) {
18430b57cec5SDimitry Andric         // Since we're not going to use the final bit test, remove it.
18440b57cec5SDimitry Andric         BTB.Cases.pop_back();
18450b57cec5SDimitry Andric         break;
18460b57cec5SDimitry Andric       }
18470b57cec5SDimitry Andric     }
18480b57cec5SDimitry Andric 
18490b57cec5SDimitry Andric     // Update PHI Nodes
18500b57cec5SDimitry Andric     for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
18510b57cec5SDimitry Andric          pi != pe; ++pi) {
18520b57cec5SDimitry Andric       MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
18530b57cec5SDimitry Andric       MachineBasicBlock *PHIBB = PHI->getParent();
18540b57cec5SDimitry Andric       assert(PHI->isPHI() &&
18550b57cec5SDimitry Andric              "This is not a machine PHI node that we are updating!");
18560b57cec5SDimitry Andric       // This is "default" BB. We have two jumps to it. From "header" BB and
18570b57cec5SDimitry Andric       // from last "case" BB, unless the latter was skipped.
18580b57cec5SDimitry Andric       if (PHIBB == BTB.Default) {
18590b57cec5SDimitry Andric         PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(BTB.Parent);
18600b57cec5SDimitry Andric         if (!BTB.ContiguousRange) {
18610b57cec5SDimitry Andric           PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
18620b57cec5SDimitry Andric               .addMBB(BTB.Cases.back().ThisBB);
18630b57cec5SDimitry Andric          }
18640b57cec5SDimitry Andric       }
18650b57cec5SDimitry Andric       // One of "cases" BB.
18660b57cec5SDimitry Andric       for (unsigned j = 0, ej = BTB.Cases.size();
18670b57cec5SDimitry Andric            j != ej; ++j) {
18680b57cec5SDimitry Andric         MachineBasicBlock* cBB = BTB.Cases[j].ThisBB;
18690b57cec5SDimitry Andric         if (cBB->isSuccessor(PHIBB))
18700b57cec5SDimitry Andric           PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB);
18710b57cec5SDimitry Andric       }
18720b57cec5SDimitry Andric     }
18730b57cec5SDimitry Andric   }
18740b57cec5SDimitry Andric   SDB->SL->BitTestCases.clear();
18750b57cec5SDimitry Andric 
18760b57cec5SDimitry Andric   // If the JumpTable record is filled in, then we need to emit a jump table.
18770b57cec5SDimitry Andric   // Updating the PHI nodes is tricky in this case, since we need to determine
18780b57cec5SDimitry Andric   // whether the PHI is a successor of the range check MBB or the jump table MBB
18790b57cec5SDimitry Andric   for (unsigned i = 0, e = SDB->SL->JTCases.size(); i != e; ++i) {
18800b57cec5SDimitry Andric     // Lower header first, if it wasn't already lowered
18810b57cec5SDimitry Andric     if (!SDB->SL->JTCases[i].first.Emitted) {
18820b57cec5SDimitry Andric       // Set the current basic block to the mbb we wish to insert the code into
18830b57cec5SDimitry Andric       FuncInfo->MBB = SDB->SL->JTCases[i].first.HeaderBB;
18840b57cec5SDimitry Andric       FuncInfo->InsertPt = FuncInfo->MBB->end();
18850b57cec5SDimitry Andric       // Emit the code
18860b57cec5SDimitry Andric       SDB->visitJumpTableHeader(SDB->SL->JTCases[i].second,
18870b57cec5SDimitry Andric                                 SDB->SL->JTCases[i].first, FuncInfo->MBB);
18880b57cec5SDimitry Andric       CurDAG->setRoot(SDB->getRoot());
18890b57cec5SDimitry Andric       SDB->clear();
18900b57cec5SDimitry Andric       CodeGenAndEmitDAG();
18910b57cec5SDimitry Andric     }
18920b57cec5SDimitry Andric 
18930b57cec5SDimitry Andric     // Set the current basic block to the mbb we wish to insert the code into
18940b57cec5SDimitry Andric     FuncInfo->MBB = SDB->SL->JTCases[i].second.MBB;
18950b57cec5SDimitry Andric     FuncInfo->InsertPt = FuncInfo->MBB->end();
18960b57cec5SDimitry Andric     // Emit the code
18970b57cec5SDimitry Andric     SDB->visitJumpTable(SDB->SL->JTCases[i].second);
18980b57cec5SDimitry Andric     CurDAG->setRoot(SDB->getRoot());
18990b57cec5SDimitry Andric     SDB->clear();
19000b57cec5SDimitry Andric     CodeGenAndEmitDAG();
19010b57cec5SDimitry Andric 
19020b57cec5SDimitry Andric     // Update PHI Nodes
19030b57cec5SDimitry Andric     for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
19040b57cec5SDimitry Andric          pi != pe; ++pi) {
19050b57cec5SDimitry Andric       MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
19060b57cec5SDimitry Andric       MachineBasicBlock *PHIBB = PHI->getParent();
19070b57cec5SDimitry Andric       assert(PHI->isPHI() &&
19080b57cec5SDimitry Andric              "This is not a machine PHI node that we are updating!");
19090b57cec5SDimitry Andric       // "default" BB. We can go there only from header BB.
19100b57cec5SDimitry Andric       if (PHIBB == SDB->SL->JTCases[i].second.Default)
19110b57cec5SDimitry Andric         PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
19120b57cec5SDimitry Andric            .addMBB(SDB->SL->JTCases[i].first.HeaderBB);
19130b57cec5SDimitry Andric       // JT BB. Just iterate over successors here
19140b57cec5SDimitry Andric       if (FuncInfo->MBB->isSuccessor(PHIBB))
19150b57cec5SDimitry Andric         PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
19160b57cec5SDimitry Andric     }
19170b57cec5SDimitry Andric   }
19180b57cec5SDimitry Andric   SDB->SL->JTCases.clear();
19190b57cec5SDimitry Andric 
19200b57cec5SDimitry Andric   // If we generated any switch lowering information, build and codegen any
19210b57cec5SDimitry Andric   // additional DAGs necessary.
19220b57cec5SDimitry Andric   for (unsigned i = 0, e = SDB->SL->SwitchCases.size(); i != e; ++i) {
19230b57cec5SDimitry Andric     // Set the current basic block to the mbb we wish to insert the code into
19240b57cec5SDimitry Andric     FuncInfo->MBB = SDB->SL->SwitchCases[i].ThisBB;
19250b57cec5SDimitry Andric     FuncInfo->InsertPt = FuncInfo->MBB->end();
19260b57cec5SDimitry Andric 
19270b57cec5SDimitry Andric     // Determine the unique successors.
19280b57cec5SDimitry Andric     SmallVector<MachineBasicBlock *, 2> Succs;
19290b57cec5SDimitry Andric     Succs.push_back(SDB->SL->SwitchCases[i].TrueBB);
19300b57cec5SDimitry Andric     if (SDB->SL->SwitchCases[i].TrueBB != SDB->SL->SwitchCases[i].FalseBB)
19310b57cec5SDimitry Andric       Succs.push_back(SDB->SL->SwitchCases[i].FalseBB);
19320b57cec5SDimitry Andric 
19330b57cec5SDimitry Andric     // Emit the code. Note that this could result in FuncInfo->MBB being split.
19340b57cec5SDimitry Andric     SDB->visitSwitchCase(SDB->SL->SwitchCases[i], FuncInfo->MBB);
19350b57cec5SDimitry Andric     CurDAG->setRoot(SDB->getRoot());
19360b57cec5SDimitry Andric     SDB->clear();
19370b57cec5SDimitry Andric     CodeGenAndEmitDAG();
19380b57cec5SDimitry Andric 
19390b57cec5SDimitry Andric     // Remember the last block, now that any splitting is done, for use in
19400b57cec5SDimitry Andric     // populating PHI nodes in successors.
19410b57cec5SDimitry Andric     MachineBasicBlock *ThisBB = FuncInfo->MBB;
19420b57cec5SDimitry Andric 
19430b57cec5SDimitry Andric     // Handle any PHI nodes in successors of this chunk, as if we were coming
19440b57cec5SDimitry Andric     // from the original BB before switch expansion.  Note that PHI nodes can
19450b57cec5SDimitry Andric     // occur multiple times in PHINodesToUpdate.  We have to be very careful to
19460b57cec5SDimitry Andric     // handle them the right number of times.
19470b57cec5SDimitry Andric     for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
19480b57cec5SDimitry Andric       FuncInfo->MBB = Succs[i];
19490b57cec5SDimitry Andric       FuncInfo->InsertPt = FuncInfo->MBB->end();
19500b57cec5SDimitry Andric       // FuncInfo->MBB may have been removed from the CFG if a branch was
19510b57cec5SDimitry Andric       // constant folded.
19520b57cec5SDimitry Andric       if (ThisBB->isSuccessor(FuncInfo->MBB)) {
19530b57cec5SDimitry Andric         for (MachineBasicBlock::iterator
19540b57cec5SDimitry Andric              MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
19550b57cec5SDimitry Andric              MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
19560b57cec5SDimitry Andric           MachineInstrBuilder PHI(*MF, MBBI);
19570b57cec5SDimitry Andric           // This value for this PHI node is recorded in PHINodesToUpdate.
19580b57cec5SDimitry Andric           for (unsigned pn = 0; ; ++pn) {
19590b57cec5SDimitry Andric             assert(pn != FuncInfo->PHINodesToUpdate.size() &&
19600b57cec5SDimitry Andric                    "Didn't find PHI entry!");
19610b57cec5SDimitry Andric             if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
19620b57cec5SDimitry Andric               PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
19630b57cec5SDimitry Andric               break;
19640b57cec5SDimitry Andric             }
19650b57cec5SDimitry Andric           }
19660b57cec5SDimitry Andric         }
19670b57cec5SDimitry Andric       }
19680b57cec5SDimitry Andric     }
19690b57cec5SDimitry Andric   }
19700b57cec5SDimitry Andric   SDB->SL->SwitchCases.clear();
19710b57cec5SDimitry Andric }
19720b57cec5SDimitry Andric 
19730b57cec5SDimitry Andric /// Create the scheduler. If a specific scheduler was specified
19740b57cec5SDimitry Andric /// via the SchedulerRegistry, use it, otherwise select the
19750b57cec5SDimitry Andric /// one preferred by the target.
19760b57cec5SDimitry Andric ///
19770b57cec5SDimitry Andric ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
19780b57cec5SDimitry Andric   return ISHeuristic(this, OptLevel);
19790b57cec5SDimitry Andric }
19800b57cec5SDimitry Andric 
19810b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
19820b57cec5SDimitry Andric // Helper functions used by the generated instruction selector.
19830b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
19840b57cec5SDimitry Andric // Calls to these methods are generated by tblgen.
19850b57cec5SDimitry Andric 
19860b57cec5SDimitry Andric /// CheckAndMask - The isel is trying to match something like (and X, 255).  If
19870b57cec5SDimitry Andric /// the dag combiner simplified the 255, we still want to match.  RHS is the
19880b57cec5SDimitry Andric /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
19890b57cec5SDimitry Andric /// specified in the .td file (e.g. 255).
19900b57cec5SDimitry Andric bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
19910b57cec5SDimitry Andric                                     int64_t DesiredMaskS) const {
19920b57cec5SDimitry Andric   const APInt &ActualMask = RHS->getAPIntValue();
19930b57cec5SDimitry Andric   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
19940b57cec5SDimitry Andric 
19950b57cec5SDimitry Andric   // If the actual mask exactly matches, success!
19960b57cec5SDimitry Andric   if (ActualMask == DesiredMask)
19970b57cec5SDimitry Andric     return true;
19980b57cec5SDimitry Andric 
19990b57cec5SDimitry Andric   // If the actual AND mask is allowing unallowed bits, this doesn't match.
20000b57cec5SDimitry Andric   if (!ActualMask.isSubsetOf(DesiredMask))
20010b57cec5SDimitry Andric     return false;
20020b57cec5SDimitry Andric 
20030b57cec5SDimitry Andric   // Otherwise, the DAG Combiner may have proven that the value coming in is
20040b57cec5SDimitry Andric   // either already zero or is not demanded.  Check for known zero input bits.
20050b57cec5SDimitry Andric   APInt NeededMask = DesiredMask & ~ActualMask;
20060b57cec5SDimitry Andric   if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
20070b57cec5SDimitry Andric     return true;
20080b57cec5SDimitry Andric 
20090b57cec5SDimitry Andric   // TODO: check to see if missing bits are just not demanded.
20100b57cec5SDimitry Andric 
20110b57cec5SDimitry Andric   // Otherwise, this pattern doesn't match.
20120b57cec5SDimitry Andric   return false;
20130b57cec5SDimitry Andric }
20140b57cec5SDimitry Andric 
20150b57cec5SDimitry Andric /// CheckOrMask - The isel is trying to match something like (or X, 255).  If
20160b57cec5SDimitry Andric /// the dag combiner simplified the 255, we still want to match.  RHS is the
20170b57cec5SDimitry Andric /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
20180b57cec5SDimitry Andric /// specified in the .td file (e.g. 255).
20190b57cec5SDimitry Andric bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
20200b57cec5SDimitry Andric                                    int64_t DesiredMaskS) const {
20210b57cec5SDimitry Andric   const APInt &ActualMask = RHS->getAPIntValue();
20220b57cec5SDimitry Andric   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
20230b57cec5SDimitry Andric 
20240b57cec5SDimitry Andric   // If the actual mask exactly matches, success!
20250b57cec5SDimitry Andric   if (ActualMask == DesiredMask)
20260b57cec5SDimitry Andric     return true;
20270b57cec5SDimitry Andric 
20280b57cec5SDimitry Andric   // If the actual AND mask is allowing unallowed bits, this doesn't match.
20290b57cec5SDimitry Andric   if (!ActualMask.isSubsetOf(DesiredMask))
20300b57cec5SDimitry Andric     return false;
20310b57cec5SDimitry Andric 
20320b57cec5SDimitry Andric   // Otherwise, the DAG Combiner may have proven that the value coming in is
20330b57cec5SDimitry Andric   // either already zero or is not demanded.  Check for known zero input bits.
20340b57cec5SDimitry Andric   APInt NeededMask = DesiredMask & ~ActualMask;
20350b57cec5SDimitry Andric   KnownBits Known = CurDAG->computeKnownBits(LHS);
20360b57cec5SDimitry Andric 
20370b57cec5SDimitry Andric   // If all the missing bits in the or are already known to be set, match!
20380b57cec5SDimitry Andric   if (NeededMask.isSubsetOf(Known.One))
20390b57cec5SDimitry Andric     return true;
20400b57cec5SDimitry Andric 
20410b57cec5SDimitry Andric   // TODO: check to see if missing bits are just not demanded.
20420b57cec5SDimitry Andric 
20430b57cec5SDimitry Andric   // Otherwise, this pattern doesn't match.
20440b57cec5SDimitry Andric   return false;
20450b57cec5SDimitry Andric }
20460b57cec5SDimitry Andric 
20470b57cec5SDimitry Andric /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
20480b57cec5SDimitry Andric /// by tblgen.  Others should not call it.
20490b57cec5SDimitry Andric void SelectionDAGISel::SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops,
20500b57cec5SDimitry Andric                                                      const SDLoc &DL) {
20510b57cec5SDimitry Andric   std::vector<SDValue> InOps;
20520b57cec5SDimitry Andric   std::swap(InOps, Ops);
20530b57cec5SDimitry Andric 
20540b57cec5SDimitry Andric   Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
20550b57cec5SDimitry Andric   Ops.push_back(InOps[InlineAsm::Op_AsmString]);  // 1
20560b57cec5SDimitry Andric   Ops.push_back(InOps[InlineAsm::Op_MDNode]);     // 2, !srcloc
20570b57cec5SDimitry Andric   Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]);  // 3 (SideEffect, AlignStack)
20580b57cec5SDimitry Andric 
20590b57cec5SDimitry Andric   unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
20600b57cec5SDimitry Andric   if (InOps[e-1].getValueType() == MVT::Glue)
20610b57cec5SDimitry Andric     --e;  // Don't process a glue operand if it is here.
20620b57cec5SDimitry Andric 
20630b57cec5SDimitry Andric   while (i != e) {
20640b57cec5SDimitry Andric     unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
20650b57cec5SDimitry Andric     if (!InlineAsm::isMemKind(Flags)) {
20660b57cec5SDimitry Andric       // Just skip over this operand, copying the operands verbatim.
20670b57cec5SDimitry Andric       Ops.insert(Ops.end(), InOps.begin()+i,
20680b57cec5SDimitry Andric                  InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
20690b57cec5SDimitry Andric       i += InlineAsm::getNumOperandRegisters(Flags) + 1;
20700b57cec5SDimitry Andric     } else {
20710b57cec5SDimitry Andric       assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
20720b57cec5SDimitry Andric              "Memory operand with multiple values?");
20730b57cec5SDimitry Andric 
20740b57cec5SDimitry Andric       unsigned TiedToOperand;
20750b57cec5SDimitry Andric       if (InlineAsm::isUseOperandTiedToDef(Flags, TiedToOperand)) {
20760b57cec5SDimitry Andric         // We need the constraint ID from the operand this is tied to.
20770b57cec5SDimitry Andric         unsigned CurOp = InlineAsm::Op_FirstOperand;
20780b57cec5SDimitry Andric         Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue();
20790b57cec5SDimitry Andric         for (; TiedToOperand; --TiedToOperand) {
20800b57cec5SDimitry Andric           CurOp += InlineAsm::getNumOperandRegisters(Flags)+1;
20810b57cec5SDimitry Andric           Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue();
20820b57cec5SDimitry Andric         }
20830b57cec5SDimitry Andric       }
20840b57cec5SDimitry Andric 
20850b57cec5SDimitry Andric       // Otherwise, this is a memory operand.  Ask the target to select it.
20860b57cec5SDimitry Andric       std::vector<SDValue> SelOps;
20870b57cec5SDimitry Andric       unsigned ConstraintID = InlineAsm::getMemoryConstraintID(Flags);
20880b57cec5SDimitry Andric       if (SelectInlineAsmMemoryOperand(InOps[i+1], ConstraintID, SelOps))
20890b57cec5SDimitry Andric         report_fatal_error("Could not match memory address.  Inline asm"
20900b57cec5SDimitry Andric                            " failure!");
20910b57cec5SDimitry Andric 
20920b57cec5SDimitry Andric       // Add this to the output node.
20930b57cec5SDimitry Andric       unsigned NewFlags =
20940b57cec5SDimitry Andric         InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
20950b57cec5SDimitry Andric       NewFlags = InlineAsm::getFlagWordForMem(NewFlags, ConstraintID);
20960b57cec5SDimitry Andric       Ops.push_back(CurDAG->getTargetConstant(NewFlags, DL, MVT::i32));
2097*e8d8bef9SDimitry Andric       llvm::append_range(Ops, SelOps);
20980b57cec5SDimitry Andric       i += 2;
20990b57cec5SDimitry Andric     }
21000b57cec5SDimitry Andric   }
21010b57cec5SDimitry Andric 
21020b57cec5SDimitry Andric   // Add the glue input back if present.
21030b57cec5SDimitry Andric   if (e != InOps.size())
21040b57cec5SDimitry Andric     Ops.push_back(InOps.back());
21050b57cec5SDimitry Andric }
21060b57cec5SDimitry Andric 
21070b57cec5SDimitry Andric /// findGlueUse - Return use of MVT::Glue value produced by the specified
21080b57cec5SDimitry Andric /// SDNode.
21090b57cec5SDimitry Andric ///
21100b57cec5SDimitry Andric static SDNode *findGlueUse(SDNode *N) {
21110b57cec5SDimitry Andric   unsigned FlagResNo = N->getNumValues()-1;
21120b57cec5SDimitry Andric   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
21130b57cec5SDimitry Andric     SDUse &Use = I.getUse();
21140b57cec5SDimitry Andric     if (Use.getResNo() == FlagResNo)
21150b57cec5SDimitry Andric       return Use.getUser();
21160b57cec5SDimitry Andric   }
21170b57cec5SDimitry Andric   return nullptr;
21180b57cec5SDimitry Andric }
21190b57cec5SDimitry Andric 
21200b57cec5SDimitry Andric /// findNonImmUse - Return true if "Def" is a predecessor of "Root" via a path
21210b57cec5SDimitry Andric /// beyond "ImmedUse".  We may ignore chains as they are checked separately.
21220b57cec5SDimitry Andric static bool findNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
21230b57cec5SDimitry Andric                           bool IgnoreChains) {
21240b57cec5SDimitry Andric   SmallPtrSet<const SDNode *, 16> Visited;
21250b57cec5SDimitry Andric   SmallVector<const SDNode *, 16> WorkList;
21260b57cec5SDimitry Andric   // Only check if we have non-immediate uses of Def.
21270b57cec5SDimitry Andric   if (ImmedUse->isOnlyUserOf(Def))
21280b57cec5SDimitry Andric     return false;
21290b57cec5SDimitry Andric 
21300b57cec5SDimitry Andric   // We don't care about paths to Def that go through ImmedUse so mark it
21310b57cec5SDimitry Andric   // visited and mark non-def operands as used.
21320b57cec5SDimitry Andric   Visited.insert(ImmedUse);
21330b57cec5SDimitry Andric   for (const SDValue &Op : ImmedUse->op_values()) {
21340b57cec5SDimitry Andric     SDNode *N = Op.getNode();
21350b57cec5SDimitry Andric     // Ignore chain deps (they are validated by
21360b57cec5SDimitry Andric     // HandleMergeInputChains) and immediate uses
21370b57cec5SDimitry Andric     if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def)
21380b57cec5SDimitry Andric       continue;
21390b57cec5SDimitry Andric     if (!Visited.insert(N).second)
21400b57cec5SDimitry Andric       continue;
21410b57cec5SDimitry Andric     WorkList.push_back(N);
21420b57cec5SDimitry Andric   }
21430b57cec5SDimitry Andric 
21440b57cec5SDimitry Andric   // Initialize worklist to operands of Root.
21450b57cec5SDimitry Andric   if (Root != ImmedUse) {
21460b57cec5SDimitry Andric     for (const SDValue &Op : Root->op_values()) {
21470b57cec5SDimitry Andric       SDNode *N = Op.getNode();
21480b57cec5SDimitry Andric       // Ignore chains (they are validated by HandleMergeInputChains)
21490b57cec5SDimitry Andric       if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def)
21500b57cec5SDimitry Andric         continue;
21510b57cec5SDimitry Andric       if (!Visited.insert(N).second)
21520b57cec5SDimitry Andric         continue;
21530b57cec5SDimitry Andric       WorkList.push_back(N);
21540b57cec5SDimitry Andric     }
21550b57cec5SDimitry Andric   }
21560b57cec5SDimitry Andric 
21570b57cec5SDimitry Andric   return SDNode::hasPredecessorHelper(Def, Visited, WorkList, 0, true);
21580b57cec5SDimitry Andric }
21590b57cec5SDimitry Andric 
21600b57cec5SDimitry Andric /// IsProfitableToFold - Returns true if it's profitable to fold the specific
21610b57cec5SDimitry Andric /// operand node N of U during instruction selection that starts at Root.
21620b57cec5SDimitry Andric bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
21630b57cec5SDimitry Andric                                           SDNode *Root) const {
21640b57cec5SDimitry Andric   if (OptLevel == CodeGenOpt::None) return false;
21650b57cec5SDimitry Andric   return N.hasOneUse();
21660b57cec5SDimitry Andric }
21670b57cec5SDimitry Andric 
21680b57cec5SDimitry Andric /// IsLegalToFold - Returns true if the specific operand node N of
21690b57cec5SDimitry Andric /// U can be folded during instruction selection that starts at Root.
21700b57cec5SDimitry Andric bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
21710b57cec5SDimitry Andric                                      CodeGenOpt::Level OptLevel,
21720b57cec5SDimitry Andric                                      bool IgnoreChains) {
21730b57cec5SDimitry Andric   if (OptLevel == CodeGenOpt::None) return false;
21740b57cec5SDimitry Andric 
21750b57cec5SDimitry Andric   // If Root use can somehow reach N through a path that that doesn't contain
21760b57cec5SDimitry Andric   // U then folding N would create a cycle. e.g. In the following
21770b57cec5SDimitry Andric   // diagram, Root can reach N through X. If N is folded into Root, then
21780b57cec5SDimitry Andric   // X is both a predecessor and a successor of U.
21790b57cec5SDimitry Andric   //
21800b57cec5SDimitry Andric   //          [N*]           //
21810b57cec5SDimitry Andric   //         ^   ^           //
21820b57cec5SDimitry Andric   //        /     \          //
21830b57cec5SDimitry Andric   //      [U*]    [X]?       //
21840b57cec5SDimitry Andric   //        ^     ^          //
21850b57cec5SDimitry Andric   //         \   /           //
21860b57cec5SDimitry Andric   //          \ /            //
21870b57cec5SDimitry Andric   //         [Root*]         //
21880b57cec5SDimitry Andric   //
21890b57cec5SDimitry Andric   // * indicates nodes to be folded together.
21900b57cec5SDimitry Andric   //
21910b57cec5SDimitry Andric   // If Root produces glue, then it gets (even more) interesting. Since it
21920b57cec5SDimitry Andric   // will be "glued" together with its glue use in the scheduler, we need to
21930b57cec5SDimitry Andric   // check if it might reach N.
21940b57cec5SDimitry Andric   //
21950b57cec5SDimitry Andric   //          [N*]           //
21960b57cec5SDimitry Andric   //         ^   ^           //
21970b57cec5SDimitry Andric   //        /     \          //
21980b57cec5SDimitry Andric   //      [U*]    [X]?       //
21990b57cec5SDimitry Andric   //        ^       ^        //
22000b57cec5SDimitry Andric   //         \       \       //
22010b57cec5SDimitry Andric   //          \      |       //
22020b57cec5SDimitry Andric   //         [Root*] |       //
22030b57cec5SDimitry Andric   //          ^      |       //
22040b57cec5SDimitry Andric   //          f      |       //
22050b57cec5SDimitry Andric   //          |      /       //
22060b57cec5SDimitry Andric   //         [Y]    /        //
22070b57cec5SDimitry Andric   //           ^   /         //
22080b57cec5SDimitry Andric   //           f  /          //
22090b57cec5SDimitry Andric   //           | /           //
22100b57cec5SDimitry Andric   //          [GU]           //
22110b57cec5SDimitry Andric   //
22120b57cec5SDimitry Andric   // If GU (glue use) indirectly reaches N (the load), and Root folds N
22130b57cec5SDimitry Andric   // (call it Fold), then X is a predecessor of GU and a successor of
22140b57cec5SDimitry Andric   // Fold. But since Fold and GU are glued together, this will create
22150b57cec5SDimitry Andric   // a cycle in the scheduling graph.
22160b57cec5SDimitry Andric 
22170b57cec5SDimitry Andric   // If the node has glue, walk down the graph to the "lowest" node in the
22180b57cec5SDimitry Andric   // glueged set.
22190b57cec5SDimitry Andric   EVT VT = Root->getValueType(Root->getNumValues()-1);
22200b57cec5SDimitry Andric   while (VT == MVT::Glue) {
22210b57cec5SDimitry Andric     SDNode *GU = findGlueUse(Root);
22220b57cec5SDimitry Andric     if (!GU)
22230b57cec5SDimitry Andric       break;
22240b57cec5SDimitry Andric     Root = GU;
22250b57cec5SDimitry Andric     VT = Root->getValueType(Root->getNumValues()-1);
22260b57cec5SDimitry Andric 
22270b57cec5SDimitry Andric     // If our query node has a glue result with a use, we've walked up it.  If
22280b57cec5SDimitry Andric     // the user (which has already been selected) has a chain or indirectly uses
22290b57cec5SDimitry Andric     // the chain, HandleMergeInputChains will not consider it.  Because of
22300b57cec5SDimitry Andric     // this, we cannot ignore chains in this predicate.
22310b57cec5SDimitry Andric     IgnoreChains = false;
22320b57cec5SDimitry Andric   }
22330b57cec5SDimitry Andric 
22340b57cec5SDimitry Andric   return !findNonImmUse(Root, N.getNode(), U, IgnoreChains);
22350b57cec5SDimitry Andric }
22360b57cec5SDimitry Andric 
22375ffd83dbSDimitry Andric void SelectionDAGISel::Select_INLINEASM(SDNode *N) {
22380b57cec5SDimitry Andric   SDLoc DL(N);
22390b57cec5SDimitry Andric 
22400b57cec5SDimitry Andric   std::vector<SDValue> Ops(N->op_begin(), N->op_end());
22410b57cec5SDimitry Andric   SelectInlineAsmMemoryOperands(Ops, DL);
22420b57cec5SDimitry Andric 
22430b57cec5SDimitry Andric   const EVT VTs[] = {MVT::Other, MVT::Glue};
22445ffd83dbSDimitry Andric   SDValue New = CurDAG->getNode(N->getOpcode(), DL, VTs, Ops);
22450b57cec5SDimitry Andric   New->setNodeId(-1);
22460b57cec5SDimitry Andric   ReplaceUses(N, New.getNode());
22470b57cec5SDimitry Andric   CurDAG->RemoveDeadNode(N);
22480b57cec5SDimitry Andric }
22490b57cec5SDimitry Andric 
22500b57cec5SDimitry Andric void SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) {
22510b57cec5SDimitry Andric   SDLoc dl(Op);
2252480093f4SDimitry Andric   MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1));
2253480093f4SDimitry Andric   const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0));
2254480093f4SDimitry Andric 
2255480093f4SDimitry Andric   EVT VT = Op->getValueType(0);
2256480093f4SDimitry Andric   LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
22578bcb0991SDimitry Andric   Register Reg =
2258480093f4SDimitry Andric       TLI->getRegisterByName(RegStr->getString().data(), Ty,
22598bcb0991SDimitry Andric                              CurDAG->getMachineFunction());
22600b57cec5SDimitry Andric   SDValue New = CurDAG->getCopyFromReg(
22610b57cec5SDimitry Andric                         Op->getOperand(0), dl, Reg, Op->getValueType(0));
22620b57cec5SDimitry Andric   New->setNodeId(-1);
22630b57cec5SDimitry Andric   ReplaceUses(Op, New.getNode());
22640b57cec5SDimitry Andric   CurDAG->RemoveDeadNode(Op);
22650b57cec5SDimitry Andric }
22660b57cec5SDimitry Andric 
22670b57cec5SDimitry Andric void SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) {
22680b57cec5SDimitry Andric   SDLoc dl(Op);
2269480093f4SDimitry Andric   MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1));
2270480093f4SDimitry Andric   const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0));
2271480093f4SDimitry Andric 
2272480093f4SDimitry Andric   EVT VT = Op->getOperand(2).getValueType();
2273480093f4SDimitry Andric   LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
2274480093f4SDimitry Andric 
2275480093f4SDimitry Andric   Register Reg = TLI->getRegisterByName(RegStr->getString().data(), Ty,
22768bcb0991SDimitry Andric                                         CurDAG->getMachineFunction());
22770b57cec5SDimitry Andric   SDValue New = CurDAG->getCopyToReg(
22780b57cec5SDimitry Andric                         Op->getOperand(0), dl, Reg, Op->getOperand(2));
22790b57cec5SDimitry Andric   New->setNodeId(-1);
22800b57cec5SDimitry Andric   ReplaceUses(Op, New.getNode());
22810b57cec5SDimitry Andric   CurDAG->RemoveDeadNode(Op);
22820b57cec5SDimitry Andric }
22830b57cec5SDimitry Andric 
22840b57cec5SDimitry Andric void SelectionDAGISel::Select_UNDEF(SDNode *N) {
22850b57cec5SDimitry Andric   CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0));
22860b57cec5SDimitry Andric }
22870b57cec5SDimitry Andric 
22885ffd83dbSDimitry Andric void SelectionDAGISel::Select_FREEZE(SDNode *N) {
22895ffd83dbSDimitry Andric   // TODO: We don't have FREEZE pseudo-instruction in MachineInstr-level now.
22905ffd83dbSDimitry Andric   // If FREEZE instruction is added later, the code below must be changed as
22915ffd83dbSDimitry Andric   // well.
22925ffd83dbSDimitry Andric   CurDAG->SelectNodeTo(N, TargetOpcode::COPY, N->getValueType(0),
22935ffd83dbSDimitry Andric                        N->getOperand(0));
22945ffd83dbSDimitry Andric }
22955ffd83dbSDimitry Andric 
22960b57cec5SDimitry Andric /// GetVBR - decode a vbr encoding whose top bit is set.
2297*e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static uint64_t
22980b57cec5SDimitry Andric GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
22990b57cec5SDimitry Andric   assert(Val >= 128 && "Not a VBR");
23000b57cec5SDimitry Andric   Val &= 127;  // Remove first vbr bit.
23010b57cec5SDimitry Andric 
23020b57cec5SDimitry Andric   unsigned Shift = 7;
23030b57cec5SDimitry Andric   uint64_t NextBits;
23040b57cec5SDimitry Andric   do {
23050b57cec5SDimitry Andric     NextBits = MatcherTable[Idx++];
23060b57cec5SDimitry Andric     Val |= (NextBits&127) << Shift;
23070b57cec5SDimitry Andric     Shift += 7;
23080b57cec5SDimitry Andric   } while (NextBits & 128);
23090b57cec5SDimitry Andric 
23100b57cec5SDimitry Andric   return Val;
23110b57cec5SDimitry Andric }
23120b57cec5SDimitry Andric 
23130b57cec5SDimitry Andric /// When a match is complete, this method updates uses of interior chain results
23140b57cec5SDimitry Andric /// to use the new results.
23150b57cec5SDimitry Andric void SelectionDAGISel::UpdateChains(
23160b57cec5SDimitry Andric     SDNode *NodeToMatch, SDValue InputChain,
23170b57cec5SDimitry Andric     SmallVectorImpl<SDNode *> &ChainNodesMatched, bool isMorphNodeTo) {
23180b57cec5SDimitry Andric   SmallVector<SDNode*, 4> NowDeadNodes;
23190b57cec5SDimitry Andric 
23200b57cec5SDimitry Andric   // Now that all the normal results are replaced, we replace the chain and
23210b57cec5SDimitry Andric   // glue results if present.
23220b57cec5SDimitry Andric   if (!ChainNodesMatched.empty()) {
23230b57cec5SDimitry Andric     assert(InputChain.getNode() &&
23240b57cec5SDimitry Andric            "Matched input chains but didn't produce a chain");
23250b57cec5SDimitry Andric     // Loop over all of the nodes we matched that produced a chain result.
23260b57cec5SDimitry Andric     // Replace all the chain results with the final chain we ended up with.
23270b57cec5SDimitry Andric     for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
23280b57cec5SDimitry Andric       SDNode *ChainNode = ChainNodesMatched[i];
23290b57cec5SDimitry Andric       // If ChainNode is null, it's because we replaced it on a previous
23300b57cec5SDimitry Andric       // iteration and we cleared it out of the map. Just skip it.
23310b57cec5SDimitry Andric       if (!ChainNode)
23320b57cec5SDimitry Andric         continue;
23330b57cec5SDimitry Andric 
23340b57cec5SDimitry Andric       assert(ChainNode->getOpcode() != ISD::DELETED_NODE &&
23350b57cec5SDimitry Andric              "Deleted node left in chain");
23360b57cec5SDimitry Andric 
23370b57cec5SDimitry Andric       // Don't replace the results of the root node if we're doing a
23380b57cec5SDimitry Andric       // MorphNodeTo.
23390b57cec5SDimitry Andric       if (ChainNode == NodeToMatch && isMorphNodeTo)
23400b57cec5SDimitry Andric         continue;
23410b57cec5SDimitry Andric 
23420b57cec5SDimitry Andric       SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
23430b57cec5SDimitry Andric       if (ChainVal.getValueType() == MVT::Glue)
23440b57cec5SDimitry Andric         ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
23450b57cec5SDimitry Andric       assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
23460b57cec5SDimitry Andric       SelectionDAG::DAGNodeDeletedListener NDL(
23470b57cec5SDimitry Andric           *CurDAG, [&](SDNode *N, SDNode *E) {
23480b57cec5SDimitry Andric             std::replace(ChainNodesMatched.begin(), ChainNodesMatched.end(), N,
23490b57cec5SDimitry Andric                          static_cast<SDNode *>(nullptr));
23500b57cec5SDimitry Andric           });
23510b57cec5SDimitry Andric       if (ChainNode->getOpcode() != ISD::TokenFactor)
23520b57cec5SDimitry Andric         ReplaceUses(ChainVal, InputChain);
23530b57cec5SDimitry Andric 
23540b57cec5SDimitry Andric       // If the node became dead and we haven't already seen it, delete it.
23550b57cec5SDimitry Andric       if (ChainNode != NodeToMatch && ChainNode->use_empty() &&
2356*e8d8bef9SDimitry Andric           !llvm::is_contained(NowDeadNodes, ChainNode))
23570b57cec5SDimitry Andric         NowDeadNodes.push_back(ChainNode);
23580b57cec5SDimitry Andric     }
23590b57cec5SDimitry Andric   }
23600b57cec5SDimitry Andric 
23610b57cec5SDimitry Andric   if (!NowDeadNodes.empty())
23620b57cec5SDimitry Andric     CurDAG->RemoveDeadNodes(NowDeadNodes);
23630b57cec5SDimitry Andric 
23640b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "ISEL: Match complete!\n");
23650b57cec5SDimitry Andric }
23660b57cec5SDimitry Andric 
23670b57cec5SDimitry Andric /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
23680b57cec5SDimitry Andric /// operation for when the pattern matched at least one node with a chains.  The
23690b57cec5SDimitry Andric /// input vector contains a list of all of the chained nodes that we match.  We
23700b57cec5SDimitry Andric /// must determine if this is a valid thing to cover (i.e. matching it won't
23710b57cec5SDimitry Andric /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
23720b57cec5SDimitry Andric /// be used as the input node chain for the generated nodes.
23730b57cec5SDimitry Andric static SDValue
23740b57cec5SDimitry Andric HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
23750b57cec5SDimitry Andric                        SelectionDAG *CurDAG) {
23760b57cec5SDimitry Andric 
23770b57cec5SDimitry Andric   SmallPtrSet<const SDNode *, 16> Visited;
23780b57cec5SDimitry Andric   SmallVector<const SDNode *, 8> Worklist;
23790b57cec5SDimitry Andric   SmallVector<SDValue, 3> InputChains;
23800b57cec5SDimitry Andric   unsigned int Max = 8192;
23810b57cec5SDimitry Andric 
23820b57cec5SDimitry Andric   // Quick exit on trivial merge.
23830b57cec5SDimitry Andric   if (ChainNodesMatched.size() == 1)
23840b57cec5SDimitry Andric     return ChainNodesMatched[0]->getOperand(0);
23850b57cec5SDimitry Andric 
23860b57cec5SDimitry Andric   // Add chains that aren't already added (internal). Peek through
23870b57cec5SDimitry Andric   // token factors.
23880b57cec5SDimitry Andric   std::function<void(const SDValue)> AddChains = [&](const SDValue V) {
23890b57cec5SDimitry Andric     if (V.getValueType() != MVT::Other)
23900b57cec5SDimitry Andric       return;
23910b57cec5SDimitry Andric     if (V->getOpcode() == ISD::EntryToken)
23920b57cec5SDimitry Andric       return;
23930b57cec5SDimitry Andric     if (!Visited.insert(V.getNode()).second)
23940b57cec5SDimitry Andric       return;
23950b57cec5SDimitry Andric     if (V->getOpcode() == ISD::TokenFactor) {
23960b57cec5SDimitry Andric       for (const SDValue &Op : V->op_values())
23970b57cec5SDimitry Andric         AddChains(Op);
23980b57cec5SDimitry Andric     } else
23990b57cec5SDimitry Andric       InputChains.push_back(V);
24000b57cec5SDimitry Andric   };
24010b57cec5SDimitry Andric 
24020b57cec5SDimitry Andric   for (auto *N : ChainNodesMatched) {
24030b57cec5SDimitry Andric     Worklist.push_back(N);
24040b57cec5SDimitry Andric     Visited.insert(N);
24050b57cec5SDimitry Andric   }
24060b57cec5SDimitry Andric 
24070b57cec5SDimitry Andric   while (!Worklist.empty())
24080b57cec5SDimitry Andric     AddChains(Worklist.pop_back_val()->getOperand(0));
24090b57cec5SDimitry Andric 
24100b57cec5SDimitry Andric   // Skip the search if there are no chain dependencies.
24110b57cec5SDimitry Andric   if (InputChains.size() == 0)
24120b57cec5SDimitry Andric     return CurDAG->getEntryNode();
24130b57cec5SDimitry Andric 
24140b57cec5SDimitry Andric   // If one of these chains is a successor of input, we must have a
24150b57cec5SDimitry Andric   // node that is both the predecessor and successor of the
24160b57cec5SDimitry Andric   // to-be-merged nodes. Fail.
24170b57cec5SDimitry Andric   Visited.clear();
24180b57cec5SDimitry Andric   for (SDValue V : InputChains)
24190b57cec5SDimitry Andric     Worklist.push_back(V.getNode());
24200b57cec5SDimitry Andric 
24210b57cec5SDimitry Andric   for (auto *N : ChainNodesMatched)
24220b57cec5SDimitry Andric     if (SDNode::hasPredecessorHelper(N, Visited, Worklist, Max, true))
24230b57cec5SDimitry Andric       return SDValue();
24240b57cec5SDimitry Andric 
24250b57cec5SDimitry Andric   // Return merged chain.
24260b57cec5SDimitry Andric   if (InputChains.size() == 1)
24270b57cec5SDimitry Andric     return InputChains[0];
24280b57cec5SDimitry Andric   return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
24290b57cec5SDimitry Andric                          MVT::Other, InputChains);
24300b57cec5SDimitry Andric }
24310b57cec5SDimitry Andric 
24320b57cec5SDimitry Andric /// MorphNode - Handle morphing a node in place for the selector.
24330b57cec5SDimitry Andric SDNode *SelectionDAGISel::
24340b57cec5SDimitry Andric MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
24350b57cec5SDimitry Andric           ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) {
24360b57cec5SDimitry Andric   // It is possible we're using MorphNodeTo to replace a node with no
24370b57cec5SDimitry Andric   // normal results with one that has a normal result (or we could be
24380b57cec5SDimitry Andric   // adding a chain) and the input could have glue and chains as well.
24390b57cec5SDimitry Andric   // In this case we need to shift the operands down.
24400b57cec5SDimitry Andric   // FIXME: This is a horrible hack and broken in obscure cases, no worse
24410b57cec5SDimitry Andric   // than the old isel though.
24420b57cec5SDimitry Andric   int OldGlueResultNo = -1, OldChainResultNo = -1;
24430b57cec5SDimitry Andric 
24440b57cec5SDimitry Andric   unsigned NTMNumResults = Node->getNumValues();
24450b57cec5SDimitry Andric   if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
24460b57cec5SDimitry Andric     OldGlueResultNo = NTMNumResults-1;
24470b57cec5SDimitry Andric     if (NTMNumResults != 1 &&
24480b57cec5SDimitry Andric         Node->getValueType(NTMNumResults-2) == MVT::Other)
24490b57cec5SDimitry Andric       OldChainResultNo = NTMNumResults-2;
24500b57cec5SDimitry Andric   } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
24510b57cec5SDimitry Andric     OldChainResultNo = NTMNumResults-1;
24520b57cec5SDimitry Andric 
24530b57cec5SDimitry Andric   // Call the underlying SelectionDAG routine to do the transmogrification. Note
24540b57cec5SDimitry Andric   // that this deletes operands of the old node that become dead.
24550b57cec5SDimitry Andric   SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops);
24560b57cec5SDimitry Andric 
24570b57cec5SDimitry Andric   // MorphNodeTo can operate in two ways: if an existing node with the
24580b57cec5SDimitry Andric   // specified operands exists, it can just return it.  Otherwise, it
24590b57cec5SDimitry Andric   // updates the node in place to have the requested operands.
24600b57cec5SDimitry Andric   if (Res == Node) {
24610b57cec5SDimitry Andric     // If we updated the node in place, reset the node ID.  To the isel,
24620b57cec5SDimitry Andric     // this should be just like a newly allocated machine node.
24630b57cec5SDimitry Andric     Res->setNodeId(-1);
24640b57cec5SDimitry Andric   }
24650b57cec5SDimitry Andric 
24660b57cec5SDimitry Andric   unsigned ResNumResults = Res->getNumValues();
24670b57cec5SDimitry Andric   // Move the glue if needed.
24680b57cec5SDimitry Andric   if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
24690b57cec5SDimitry Andric       (unsigned)OldGlueResultNo != ResNumResults-1)
24700b57cec5SDimitry Andric     ReplaceUses(SDValue(Node, OldGlueResultNo),
24710b57cec5SDimitry Andric                 SDValue(Res, ResNumResults - 1));
24720b57cec5SDimitry Andric 
24730b57cec5SDimitry Andric   if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
24740b57cec5SDimitry Andric     --ResNumResults;
24750b57cec5SDimitry Andric 
24760b57cec5SDimitry Andric   // Move the chain reference if needed.
24770b57cec5SDimitry Andric   if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
24780b57cec5SDimitry Andric       (unsigned)OldChainResultNo != ResNumResults-1)
24790b57cec5SDimitry Andric     ReplaceUses(SDValue(Node, OldChainResultNo),
24800b57cec5SDimitry Andric                 SDValue(Res, ResNumResults - 1));
24810b57cec5SDimitry Andric 
24820b57cec5SDimitry Andric   // Otherwise, no replacement happened because the node already exists. Replace
24830b57cec5SDimitry Andric   // Uses of the old node with the new one.
24840b57cec5SDimitry Andric   if (Res != Node) {
24850b57cec5SDimitry Andric     ReplaceNode(Node, Res);
24860b57cec5SDimitry Andric   } else {
24870b57cec5SDimitry Andric     EnforceNodeIdInvariant(Res);
24880b57cec5SDimitry Andric   }
24890b57cec5SDimitry Andric 
24900b57cec5SDimitry Andric   return Res;
24910b57cec5SDimitry Andric }
24920b57cec5SDimitry Andric 
24930b57cec5SDimitry Andric /// CheckSame - Implements OP_CheckSame.
2494*e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2495*e8d8bef9SDimitry Andric CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
24960b57cec5SDimitry Andric           const SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes) {
24970b57cec5SDimitry Andric   // Accept if it is exactly the same as a previously recorded node.
24980b57cec5SDimitry Andric   unsigned RecNo = MatcherTable[MatcherIndex++];
24990b57cec5SDimitry Andric   assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
25000b57cec5SDimitry Andric   return N == RecordedNodes[RecNo].first;
25010b57cec5SDimitry Andric }
25020b57cec5SDimitry Andric 
25030b57cec5SDimitry Andric /// CheckChildSame - Implements OP_CheckChildXSame.
2504*e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool CheckChildSame(
2505*e8d8bef9SDimitry Andric     const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
25060b57cec5SDimitry Andric     const SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes,
25070b57cec5SDimitry Andric     unsigned ChildNo) {
25080b57cec5SDimitry Andric   if (ChildNo >= N.getNumOperands())
25090b57cec5SDimitry Andric     return false;  // Match fails if out of range child #.
25100b57cec5SDimitry Andric   return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo),
25110b57cec5SDimitry Andric                      RecordedNodes);
25120b57cec5SDimitry Andric }
25130b57cec5SDimitry Andric 
25140b57cec5SDimitry Andric /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
2515*e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
25160b57cec5SDimitry Andric CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
25170b57cec5SDimitry Andric                       const SelectionDAGISel &SDISel) {
25180b57cec5SDimitry Andric   return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
25190b57cec5SDimitry Andric }
25200b57cec5SDimitry Andric 
25210b57cec5SDimitry Andric /// CheckNodePredicate - Implements OP_CheckNodePredicate.
2522*e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
25230b57cec5SDimitry Andric CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
25240b57cec5SDimitry Andric                    const SelectionDAGISel &SDISel, SDNode *N) {
25250b57cec5SDimitry Andric   return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
25260b57cec5SDimitry Andric }
25270b57cec5SDimitry Andric 
2528*e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
25290b57cec5SDimitry Andric CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
25300b57cec5SDimitry Andric             SDNode *N) {
25310b57cec5SDimitry Andric   uint16_t Opc = MatcherTable[MatcherIndex++];
25320b57cec5SDimitry Andric   Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
25330b57cec5SDimitry Andric   return N->getOpcode() == Opc;
25340b57cec5SDimitry Andric }
25350b57cec5SDimitry Andric 
2536*e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
25370b57cec5SDimitry Andric CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
25380b57cec5SDimitry Andric           const TargetLowering *TLI, const DataLayout &DL) {
25390b57cec5SDimitry Andric   MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
25400b57cec5SDimitry Andric   if (N.getValueType() == VT) return true;
25410b57cec5SDimitry Andric 
25420b57cec5SDimitry Andric   // Handle the case when VT is iPTR.
25430b57cec5SDimitry Andric   return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL);
25440b57cec5SDimitry Andric }
25450b57cec5SDimitry Andric 
2546*e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
25470b57cec5SDimitry Andric CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
25480b57cec5SDimitry Andric                SDValue N, const TargetLowering *TLI, const DataLayout &DL,
25490b57cec5SDimitry Andric                unsigned ChildNo) {
25500b57cec5SDimitry Andric   if (ChildNo >= N.getNumOperands())
25510b57cec5SDimitry Andric     return false;  // Match fails if out of range child #.
25520b57cec5SDimitry Andric   return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI,
25530b57cec5SDimitry Andric                      DL);
25540b57cec5SDimitry Andric }
25550b57cec5SDimitry Andric 
2556*e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
25570b57cec5SDimitry Andric CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
25580b57cec5SDimitry Andric               SDValue N) {
25590b57cec5SDimitry Andric   return cast<CondCodeSDNode>(N)->get() ==
25600b57cec5SDimitry Andric       (ISD::CondCode)MatcherTable[MatcherIndex++];
25610b57cec5SDimitry Andric }
25620b57cec5SDimitry Andric 
2563*e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
25640b57cec5SDimitry Andric CheckChild2CondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
25650b57cec5SDimitry Andric                     SDValue N) {
25660b57cec5SDimitry Andric   if (2 >= N.getNumOperands())
25670b57cec5SDimitry Andric     return false;
25680b57cec5SDimitry Andric   return ::CheckCondCode(MatcherTable, MatcherIndex, N.getOperand(2));
25690b57cec5SDimitry Andric }
25700b57cec5SDimitry Andric 
2571*e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
25720b57cec5SDimitry Andric CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
25730b57cec5SDimitry Andric                SDValue N, const TargetLowering *TLI, const DataLayout &DL) {
25740b57cec5SDimitry Andric   MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
25750b57cec5SDimitry Andric   if (cast<VTSDNode>(N)->getVT() == VT)
25760b57cec5SDimitry Andric     return true;
25770b57cec5SDimitry Andric 
25780b57cec5SDimitry Andric   // Handle the case when VT is iPTR.
25790b57cec5SDimitry Andric   return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL);
25800b57cec5SDimitry Andric }
25810b57cec5SDimitry Andric 
2582*e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
25830b57cec5SDimitry Andric CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
25840b57cec5SDimitry Andric              SDValue N) {
25850b57cec5SDimitry Andric   int64_t Val = MatcherTable[MatcherIndex++];
25860b57cec5SDimitry Andric   if (Val & 128)
25870b57cec5SDimitry Andric     Val = GetVBR(Val, MatcherTable, MatcherIndex);
25880b57cec5SDimitry Andric 
25890b57cec5SDimitry Andric   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
25900b57cec5SDimitry Andric   return C && C->getSExtValue() == Val;
25910b57cec5SDimitry Andric }
25920b57cec5SDimitry Andric 
2593*e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
25940b57cec5SDimitry Andric CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
25950b57cec5SDimitry Andric                   SDValue N, unsigned ChildNo) {
25960b57cec5SDimitry Andric   if (ChildNo >= N.getNumOperands())
25970b57cec5SDimitry Andric     return false;  // Match fails if out of range child #.
25980b57cec5SDimitry Andric   return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo));
25990b57cec5SDimitry Andric }
26000b57cec5SDimitry Andric 
2601*e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
26020b57cec5SDimitry Andric CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
26030b57cec5SDimitry Andric             SDValue N, const SelectionDAGISel &SDISel) {
26040b57cec5SDimitry Andric   int64_t Val = MatcherTable[MatcherIndex++];
26050b57cec5SDimitry Andric   if (Val & 128)
26060b57cec5SDimitry Andric     Val = GetVBR(Val, MatcherTable, MatcherIndex);
26070b57cec5SDimitry Andric 
26080b57cec5SDimitry Andric   if (N->getOpcode() != ISD::AND) return false;
26090b57cec5SDimitry Andric 
26100b57cec5SDimitry Andric   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
26110b57cec5SDimitry Andric   return C && SDISel.CheckAndMask(N.getOperand(0), C, Val);
26120b57cec5SDimitry Andric }
26130b57cec5SDimitry Andric 
2614*e8d8bef9SDimitry Andric LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2615*e8d8bef9SDimitry Andric CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2616*e8d8bef9SDimitry Andric            const SelectionDAGISel &SDISel) {
26170b57cec5SDimitry Andric   int64_t Val = MatcherTable[MatcherIndex++];
26180b57cec5SDimitry Andric   if (Val & 128)
26190b57cec5SDimitry Andric     Val = GetVBR(Val, MatcherTable, MatcherIndex);
26200b57cec5SDimitry Andric 
26210b57cec5SDimitry Andric   if (N->getOpcode() != ISD::OR) return false;
26220b57cec5SDimitry Andric 
26230b57cec5SDimitry Andric   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
26240b57cec5SDimitry Andric   return C && SDISel.CheckOrMask(N.getOperand(0), C, Val);
26250b57cec5SDimitry Andric }
26260b57cec5SDimitry Andric 
26270b57cec5SDimitry Andric /// IsPredicateKnownToFail - If we know how and can do so without pushing a
26280b57cec5SDimitry Andric /// scope, evaluate the current node.  If the current predicate is known to
26290b57cec5SDimitry Andric /// fail, set Result=true and return anything.  If the current predicate is
26300b57cec5SDimitry Andric /// known to pass, set Result=false and return the MatcherIndex to continue
26310b57cec5SDimitry Andric /// with.  If the current predicate is unknown, set Result=false and return the
26320b57cec5SDimitry Andric /// MatcherIndex to continue with.
26330b57cec5SDimitry Andric static unsigned IsPredicateKnownToFail(const unsigned char *Table,
26340b57cec5SDimitry Andric                                        unsigned Index, SDValue N,
26350b57cec5SDimitry Andric                                        bool &Result,
26360b57cec5SDimitry Andric                                        const SelectionDAGISel &SDISel,
26370b57cec5SDimitry Andric                   SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) {
26380b57cec5SDimitry Andric   switch (Table[Index++]) {
26390b57cec5SDimitry Andric   default:
26400b57cec5SDimitry Andric     Result = false;
26410b57cec5SDimitry Andric     return Index-1;  // Could not evaluate this predicate.
26420b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckSame:
26430b57cec5SDimitry Andric     Result = !::CheckSame(Table, Index, N, RecordedNodes);
26440b57cec5SDimitry Andric     return Index;
26450b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckChild0Same:
26460b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckChild1Same:
26470b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckChild2Same:
26480b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckChild3Same:
26490b57cec5SDimitry Andric     Result = !::CheckChildSame(Table, Index, N, RecordedNodes,
26500b57cec5SDimitry Andric                         Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Same);
26510b57cec5SDimitry Andric     return Index;
26520b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckPatternPredicate:
26530b57cec5SDimitry Andric     Result = !::CheckPatternPredicate(Table, Index, SDISel);
26540b57cec5SDimitry Andric     return Index;
26550b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckPredicate:
26560b57cec5SDimitry Andric     Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
26570b57cec5SDimitry Andric     return Index;
26580b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckOpcode:
26590b57cec5SDimitry Andric     Result = !::CheckOpcode(Table, Index, N.getNode());
26600b57cec5SDimitry Andric     return Index;
26610b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckType:
26620b57cec5SDimitry Andric     Result = !::CheckType(Table, Index, N, SDISel.TLI,
26630b57cec5SDimitry Andric                           SDISel.CurDAG->getDataLayout());
26640b57cec5SDimitry Andric     return Index;
26650b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckTypeRes: {
26660b57cec5SDimitry Andric     unsigned Res = Table[Index++];
26670b57cec5SDimitry Andric     Result = !::CheckType(Table, Index, N.getValue(Res), SDISel.TLI,
26680b57cec5SDimitry Andric                           SDISel.CurDAG->getDataLayout());
26690b57cec5SDimitry Andric     return Index;
26700b57cec5SDimitry Andric   }
26710b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckChild0Type:
26720b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckChild1Type:
26730b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckChild2Type:
26740b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckChild3Type:
26750b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckChild4Type:
26760b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckChild5Type:
26770b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckChild6Type:
26780b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckChild7Type:
26790b57cec5SDimitry Andric     Result = !::CheckChildType(
26800b57cec5SDimitry Andric                  Table, Index, N, SDISel.TLI, SDISel.CurDAG->getDataLayout(),
26810b57cec5SDimitry Andric                  Table[Index - 1] - SelectionDAGISel::OPC_CheckChild0Type);
26820b57cec5SDimitry Andric     return Index;
26830b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckCondCode:
26840b57cec5SDimitry Andric     Result = !::CheckCondCode(Table, Index, N);
26850b57cec5SDimitry Andric     return Index;
26860b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckChild2CondCode:
26870b57cec5SDimitry Andric     Result = !::CheckChild2CondCode(Table, Index, N);
26880b57cec5SDimitry Andric     return Index;
26890b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckValueType:
26900b57cec5SDimitry Andric     Result = !::CheckValueType(Table, Index, N, SDISel.TLI,
26910b57cec5SDimitry Andric                                SDISel.CurDAG->getDataLayout());
26920b57cec5SDimitry Andric     return Index;
26930b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckInteger:
26940b57cec5SDimitry Andric     Result = !::CheckInteger(Table, Index, N);
26950b57cec5SDimitry Andric     return Index;
26960b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckChild0Integer:
26970b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckChild1Integer:
26980b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckChild2Integer:
26990b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckChild3Integer:
27000b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckChild4Integer:
27010b57cec5SDimitry Andric     Result = !::CheckChildInteger(Table, Index, N,
27020b57cec5SDimitry Andric                      Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Integer);
27030b57cec5SDimitry Andric     return Index;
27040b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckAndImm:
27050b57cec5SDimitry Andric     Result = !::CheckAndImm(Table, Index, N, SDISel);
27060b57cec5SDimitry Andric     return Index;
27070b57cec5SDimitry Andric   case SelectionDAGISel::OPC_CheckOrImm:
27080b57cec5SDimitry Andric     Result = !::CheckOrImm(Table, Index, N, SDISel);
27090b57cec5SDimitry Andric     return Index;
27100b57cec5SDimitry Andric   }
27110b57cec5SDimitry Andric }
27120b57cec5SDimitry Andric 
27130b57cec5SDimitry Andric namespace {
27140b57cec5SDimitry Andric 
27150b57cec5SDimitry Andric struct MatchScope {
27160b57cec5SDimitry Andric   /// FailIndex - If this match fails, this is the index to continue with.
27170b57cec5SDimitry Andric   unsigned FailIndex;
27180b57cec5SDimitry Andric 
27190b57cec5SDimitry Andric   /// NodeStack - The node stack when the scope was formed.
27200b57cec5SDimitry Andric   SmallVector<SDValue, 4> NodeStack;
27210b57cec5SDimitry Andric 
27220b57cec5SDimitry Andric   /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
27230b57cec5SDimitry Andric   unsigned NumRecordedNodes;
27240b57cec5SDimitry Andric 
27250b57cec5SDimitry Andric   /// NumMatchedMemRefs - The number of matched memref entries.
27260b57cec5SDimitry Andric   unsigned NumMatchedMemRefs;
27270b57cec5SDimitry Andric 
27280b57cec5SDimitry Andric   /// InputChain/InputGlue - The current chain/glue
27290b57cec5SDimitry Andric   SDValue InputChain, InputGlue;
27300b57cec5SDimitry Andric 
27310b57cec5SDimitry Andric   /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
27320b57cec5SDimitry Andric   bool HasChainNodesMatched;
27330b57cec5SDimitry Andric };
27340b57cec5SDimitry Andric 
27350b57cec5SDimitry Andric /// \A DAG update listener to keep the matching state
27360b57cec5SDimitry Andric /// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to
27370b57cec5SDimitry Andric /// change the DAG while matching.  X86 addressing mode matcher is an example
27380b57cec5SDimitry Andric /// for this.
27390b57cec5SDimitry Andric class MatchStateUpdater : public SelectionDAG::DAGUpdateListener
27400b57cec5SDimitry Andric {
27410b57cec5SDimitry Andric   SDNode **NodeToMatch;
27420b57cec5SDimitry Andric   SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes;
27430b57cec5SDimitry Andric   SmallVectorImpl<MatchScope> &MatchScopes;
27440b57cec5SDimitry Andric 
27450b57cec5SDimitry Andric public:
27460b57cec5SDimitry Andric   MatchStateUpdater(SelectionDAG &DAG, SDNode **NodeToMatch,
27470b57cec5SDimitry Andric                     SmallVectorImpl<std::pair<SDValue, SDNode *>> &RN,
27480b57cec5SDimitry Andric                     SmallVectorImpl<MatchScope> &MS)
27490b57cec5SDimitry Andric       : SelectionDAG::DAGUpdateListener(DAG), NodeToMatch(NodeToMatch),
27500b57cec5SDimitry Andric         RecordedNodes(RN), MatchScopes(MS) {}
27510b57cec5SDimitry Andric 
27520b57cec5SDimitry Andric   void NodeDeleted(SDNode *N, SDNode *E) override {
27530b57cec5SDimitry Andric     // Some early-returns here to avoid the search if we deleted the node or
27540b57cec5SDimitry Andric     // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we
27550b57cec5SDimitry Andric     // do, so it's unnecessary to update matching state at that point).
27560b57cec5SDimitry Andric     // Neither of these can occur currently because we only install this
27570b57cec5SDimitry Andric     // update listener during matching a complex patterns.
27580b57cec5SDimitry Andric     if (!E || E->isMachineOpcode())
27590b57cec5SDimitry Andric       return;
27600b57cec5SDimitry Andric     // Check if NodeToMatch was updated.
27610b57cec5SDimitry Andric     if (N == *NodeToMatch)
27620b57cec5SDimitry Andric       *NodeToMatch = E;
27630b57cec5SDimitry Andric     // Performing linear search here does not matter because we almost never
27640b57cec5SDimitry Andric     // run this code.  You'd have to have a CSE during complex pattern
27650b57cec5SDimitry Andric     // matching.
27660b57cec5SDimitry Andric     for (auto &I : RecordedNodes)
27670b57cec5SDimitry Andric       if (I.first.getNode() == N)
27680b57cec5SDimitry Andric         I.first.setNode(E);
27690b57cec5SDimitry Andric 
27700b57cec5SDimitry Andric     for (auto &I : MatchScopes)
27710b57cec5SDimitry Andric       for (auto &J : I.NodeStack)
27720b57cec5SDimitry Andric         if (J.getNode() == N)
27730b57cec5SDimitry Andric           J.setNode(E);
27740b57cec5SDimitry Andric   }
27750b57cec5SDimitry Andric };
27760b57cec5SDimitry Andric 
27770b57cec5SDimitry Andric } // end anonymous namespace
27780b57cec5SDimitry Andric 
27790b57cec5SDimitry Andric void SelectionDAGISel::SelectCodeCommon(SDNode *NodeToMatch,
27800b57cec5SDimitry Andric                                         const unsigned char *MatcherTable,
27810b57cec5SDimitry Andric                                         unsigned TableSize) {
27820b57cec5SDimitry Andric   // FIXME: Should these even be selected?  Handle these cases in the caller?
27830b57cec5SDimitry Andric   switch (NodeToMatch->getOpcode()) {
27840b57cec5SDimitry Andric   default:
27850b57cec5SDimitry Andric     break;
27860b57cec5SDimitry Andric   case ISD::EntryToken:       // These nodes remain the same.
27870b57cec5SDimitry Andric   case ISD::BasicBlock:
27880b57cec5SDimitry Andric   case ISD::Register:
27890b57cec5SDimitry Andric   case ISD::RegisterMask:
27900b57cec5SDimitry Andric   case ISD::HANDLENODE:
27910b57cec5SDimitry Andric   case ISD::MDNODE_SDNODE:
27920b57cec5SDimitry Andric   case ISD::TargetConstant:
27930b57cec5SDimitry Andric   case ISD::TargetConstantFP:
27940b57cec5SDimitry Andric   case ISD::TargetConstantPool:
27950b57cec5SDimitry Andric   case ISD::TargetFrameIndex:
27960b57cec5SDimitry Andric   case ISD::TargetExternalSymbol:
27970b57cec5SDimitry Andric   case ISD::MCSymbol:
27980b57cec5SDimitry Andric   case ISD::TargetBlockAddress:
27990b57cec5SDimitry Andric   case ISD::TargetJumpTable:
28000b57cec5SDimitry Andric   case ISD::TargetGlobalTLSAddress:
28010b57cec5SDimitry Andric   case ISD::TargetGlobalAddress:
28020b57cec5SDimitry Andric   case ISD::TokenFactor:
28030b57cec5SDimitry Andric   case ISD::CopyFromReg:
28040b57cec5SDimitry Andric   case ISD::CopyToReg:
28050b57cec5SDimitry Andric   case ISD::EH_LABEL:
28060b57cec5SDimitry Andric   case ISD::ANNOTATION_LABEL:
28070b57cec5SDimitry Andric   case ISD::LIFETIME_START:
28080b57cec5SDimitry Andric   case ISD::LIFETIME_END:
2809*e8d8bef9SDimitry Andric   case ISD::PSEUDO_PROBE:
28100b57cec5SDimitry Andric     NodeToMatch->setNodeId(-1); // Mark selected.
28110b57cec5SDimitry Andric     return;
28120b57cec5SDimitry Andric   case ISD::AssertSext:
28130b57cec5SDimitry Andric   case ISD::AssertZext:
28145ffd83dbSDimitry Andric   case ISD::AssertAlign:
28150b57cec5SDimitry Andric     ReplaceUses(SDValue(NodeToMatch, 0), NodeToMatch->getOperand(0));
28160b57cec5SDimitry Andric     CurDAG->RemoveDeadNode(NodeToMatch);
28170b57cec5SDimitry Andric     return;
28180b57cec5SDimitry Andric   case ISD::INLINEASM:
28190b57cec5SDimitry Andric   case ISD::INLINEASM_BR:
28205ffd83dbSDimitry Andric     Select_INLINEASM(NodeToMatch);
28210b57cec5SDimitry Andric     return;
28220b57cec5SDimitry Andric   case ISD::READ_REGISTER:
28230b57cec5SDimitry Andric     Select_READ_REGISTER(NodeToMatch);
28240b57cec5SDimitry Andric     return;
28250b57cec5SDimitry Andric   case ISD::WRITE_REGISTER:
28260b57cec5SDimitry Andric     Select_WRITE_REGISTER(NodeToMatch);
28270b57cec5SDimitry Andric     return;
28280b57cec5SDimitry Andric   case ISD::UNDEF:
28290b57cec5SDimitry Andric     Select_UNDEF(NodeToMatch);
28300b57cec5SDimitry Andric     return;
28315ffd83dbSDimitry Andric   case ISD::FREEZE:
28325ffd83dbSDimitry Andric     Select_FREEZE(NodeToMatch);
28335ffd83dbSDimitry Andric     return;
28340b57cec5SDimitry Andric   }
28350b57cec5SDimitry Andric 
28360b57cec5SDimitry Andric   assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
28370b57cec5SDimitry Andric 
28380b57cec5SDimitry Andric   // Set up the node stack with NodeToMatch as the only node on the stack.
28390b57cec5SDimitry Andric   SmallVector<SDValue, 8> NodeStack;
28400b57cec5SDimitry Andric   SDValue N = SDValue(NodeToMatch, 0);
28410b57cec5SDimitry Andric   NodeStack.push_back(N);
28420b57cec5SDimitry Andric 
28430b57cec5SDimitry Andric   // MatchScopes - Scopes used when matching, if a match failure happens, this
28440b57cec5SDimitry Andric   // indicates where to continue checking.
28450b57cec5SDimitry Andric   SmallVector<MatchScope, 8> MatchScopes;
28460b57cec5SDimitry Andric 
28470b57cec5SDimitry Andric   // RecordedNodes - This is the set of nodes that have been recorded by the
28480b57cec5SDimitry Andric   // state machine.  The second value is the parent of the node, or null if the
28490b57cec5SDimitry Andric   // root is recorded.
28500b57cec5SDimitry Andric   SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
28510b57cec5SDimitry Andric 
28520b57cec5SDimitry Andric   // MatchedMemRefs - This is the set of MemRef's we've seen in the input
28530b57cec5SDimitry Andric   // pattern.
28540b57cec5SDimitry Andric   SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
28550b57cec5SDimitry Andric 
28560b57cec5SDimitry Andric   // These are the current input chain and glue for use when generating nodes.
28570b57cec5SDimitry Andric   // Various Emit operations change these.  For example, emitting a copytoreg
28580b57cec5SDimitry Andric   // uses and updates these.
28590b57cec5SDimitry Andric   SDValue InputChain, InputGlue;
28600b57cec5SDimitry Andric 
28610b57cec5SDimitry Andric   // ChainNodesMatched - If a pattern matches nodes that have input/output
28620b57cec5SDimitry Andric   // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
28630b57cec5SDimitry Andric   // which ones they are.  The result is captured into this list so that we can
28640b57cec5SDimitry Andric   // update the chain results when the pattern is complete.
28650b57cec5SDimitry Andric   SmallVector<SDNode*, 3> ChainNodesMatched;
28660b57cec5SDimitry Andric 
28670b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "ISEL: Starting pattern match\n");
28680b57cec5SDimitry Andric 
28690b57cec5SDimitry Andric   // Determine where to start the interpreter.  Normally we start at opcode #0,
28700b57cec5SDimitry Andric   // but if the state machine starts with an OPC_SwitchOpcode, then we
28710b57cec5SDimitry Andric   // accelerate the first lookup (which is guaranteed to be hot) with the
28720b57cec5SDimitry Andric   // OpcodeOffset table.
28730b57cec5SDimitry Andric   unsigned MatcherIndex = 0;
28740b57cec5SDimitry Andric 
28750b57cec5SDimitry Andric   if (!OpcodeOffset.empty()) {
28760b57cec5SDimitry Andric     // Already computed the OpcodeOffset table, just index into it.
28770b57cec5SDimitry Andric     if (N.getOpcode() < OpcodeOffset.size())
28780b57cec5SDimitry Andric       MatcherIndex = OpcodeOffset[N.getOpcode()];
28790b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Initial Opcode index to " << MatcherIndex << "\n");
28800b57cec5SDimitry Andric 
28810b57cec5SDimitry Andric   } else if (MatcherTable[0] == OPC_SwitchOpcode) {
28820b57cec5SDimitry Andric     // Otherwise, the table isn't computed, but the state machine does start
28830b57cec5SDimitry Andric     // with an OPC_SwitchOpcode instruction.  Populate the table now, since this
28840b57cec5SDimitry Andric     // is the first time we're selecting an instruction.
28850b57cec5SDimitry Andric     unsigned Idx = 1;
28860b57cec5SDimitry Andric     while (true) {
28870b57cec5SDimitry Andric       // Get the size of this case.
28880b57cec5SDimitry Andric       unsigned CaseSize = MatcherTable[Idx++];
28890b57cec5SDimitry Andric       if (CaseSize & 128)
28900b57cec5SDimitry Andric         CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
28910b57cec5SDimitry Andric       if (CaseSize == 0) break;
28920b57cec5SDimitry Andric 
28930b57cec5SDimitry Andric       // Get the opcode, add the index to the table.
28940b57cec5SDimitry Andric       uint16_t Opc = MatcherTable[Idx++];
28950b57cec5SDimitry Andric       Opc |= (unsigned short)MatcherTable[Idx++] << 8;
28960b57cec5SDimitry Andric       if (Opc >= OpcodeOffset.size())
28970b57cec5SDimitry Andric         OpcodeOffset.resize((Opc+1)*2);
28980b57cec5SDimitry Andric       OpcodeOffset[Opc] = Idx;
28990b57cec5SDimitry Andric       Idx += CaseSize;
29000b57cec5SDimitry Andric     }
29010b57cec5SDimitry Andric 
29020b57cec5SDimitry Andric     // Okay, do the lookup for the first opcode.
29030b57cec5SDimitry Andric     if (N.getOpcode() < OpcodeOffset.size())
29040b57cec5SDimitry Andric       MatcherIndex = OpcodeOffset[N.getOpcode()];
29050b57cec5SDimitry Andric   }
29060b57cec5SDimitry Andric 
29070b57cec5SDimitry Andric   while (true) {
29080b57cec5SDimitry Andric     assert(MatcherIndex < TableSize && "Invalid index");
29090b57cec5SDimitry Andric #ifndef NDEBUG
29100b57cec5SDimitry Andric     unsigned CurrentOpcodeIndex = MatcherIndex;
29110b57cec5SDimitry Andric #endif
29120b57cec5SDimitry Andric     BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
29130b57cec5SDimitry Andric     switch (Opcode) {
29140b57cec5SDimitry Andric     case OPC_Scope: {
29150b57cec5SDimitry Andric       // Okay, the semantics of this operation are that we should push a scope
29160b57cec5SDimitry Andric       // then evaluate the first child.  However, pushing a scope only to have
29170b57cec5SDimitry Andric       // the first check fail (which then pops it) is inefficient.  If we can
29180b57cec5SDimitry Andric       // determine immediately that the first check (or first several) will
29190b57cec5SDimitry Andric       // immediately fail, don't even bother pushing a scope for them.
29200b57cec5SDimitry Andric       unsigned FailIndex;
29210b57cec5SDimitry Andric 
29220b57cec5SDimitry Andric       while (true) {
29230b57cec5SDimitry Andric         unsigned NumToSkip = MatcherTable[MatcherIndex++];
29240b57cec5SDimitry Andric         if (NumToSkip & 128)
29250b57cec5SDimitry Andric           NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
29260b57cec5SDimitry Andric         // Found the end of the scope with no match.
29270b57cec5SDimitry Andric         if (NumToSkip == 0) {
29280b57cec5SDimitry Andric           FailIndex = 0;
29290b57cec5SDimitry Andric           break;
29300b57cec5SDimitry Andric         }
29310b57cec5SDimitry Andric 
29320b57cec5SDimitry Andric         FailIndex = MatcherIndex+NumToSkip;
29330b57cec5SDimitry Andric 
29340b57cec5SDimitry Andric         unsigned MatcherIndexOfPredicate = MatcherIndex;
29350b57cec5SDimitry Andric         (void)MatcherIndexOfPredicate; // silence warning.
29360b57cec5SDimitry Andric 
29370b57cec5SDimitry Andric         // If we can't evaluate this predicate without pushing a scope (e.g. if
29380b57cec5SDimitry Andric         // it is a 'MoveParent') or if the predicate succeeds on this node, we
29390b57cec5SDimitry Andric         // push the scope and evaluate the full predicate chain.
29400b57cec5SDimitry Andric         bool Result;
29410b57cec5SDimitry Andric         MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
29420b57cec5SDimitry Andric                                               Result, *this, RecordedNodes);
29430b57cec5SDimitry Andric         if (!Result)
29440b57cec5SDimitry Andric           break;
29450b57cec5SDimitry Andric 
29460b57cec5SDimitry Andric         LLVM_DEBUG(
29470b57cec5SDimitry Andric             dbgs() << "  Skipped scope entry (due to false predicate) at "
29480b57cec5SDimitry Andric                    << "index " << MatcherIndexOfPredicate << ", continuing at "
29490b57cec5SDimitry Andric                    << FailIndex << "\n");
29500b57cec5SDimitry Andric         ++NumDAGIselRetries;
29510b57cec5SDimitry Andric 
29520b57cec5SDimitry Andric         // Otherwise, we know that this case of the Scope is guaranteed to fail,
29530b57cec5SDimitry Andric         // move to the next case.
29540b57cec5SDimitry Andric         MatcherIndex = FailIndex;
29550b57cec5SDimitry Andric       }
29560b57cec5SDimitry Andric 
29570b57cec5SDimitry Andric       // If the whole scope failed to match, bail.
29580b57cec5SDimitry Andric       if (FailIndex == 0) break;
29590b57cec5SDimitry Andric 
29600b57cec5SDimitry Andric       // Push a MatchScope which indicates where to go if the first child fails
29610b57cec5SDimitry Andric       // to match.
29620b57cec5SDimitry Andric       MatchScope NewEntry;
29630b57cec5SDimitry Andric       NewEntry.FailIndex = FailIndex;
29640b57cec5SDimitry Andric       NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
29650b57cec5SDimitry Andric       NewEntry.NumRecordedNodes = RecordedNodes.size();
29660b57cec5SDimitry Andric       NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
29670b57cec5SDimitry Andric       NewEntry.InputChain = InputChain;
29680b57cec5SDimitry Andric       NewEntry.InputGlue = InputGlue;
29690b57cec5SDimitry Andric       NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
29700b57cec5SDimitry Andric       MatchScopes.push_back(NewEntry);
29710b57cec5SDimitry Andric       continue;
29720b57cec5SDimitry Andric     }
29730b57cec5SDimitry Andric     case OPC_RecordNode: {
29740b57cec5SDimitry Andric       // Remember this node, it may end up being an operand in the pattern.
29750b57cec5SDimitry Andric       SDNode *Parent = nullptr;
29760b57cec5SDimitry Andric       if (NodeStack.size() > 1)
29770b57cec5SDimitry Andric         Parent = NodeStack[NodeStack.size()-2].getNode();
29780b57cec5SDimitry Andric       RecordedNodes.push_back(std::make_pair(N, Parent));
29790b57cec5SDimitry Andric       continue;
29800b57cec5SDimitry Andric     }
29810b57cec5SDimitry Andric 
29820b57cec5SDimitry Andric     case OPC_RecordChild0: case OPC_RecordChild1:
29830b57cec5SDimitry Andric     case OPC_RecordChild2: case OPC_RecordChild3:
29840b57cec5SDimitry Andric     case OPC_RecordChild4: case OPC_RecordChild5:
29850b57cec5SDimitry Andric     case OPC_RecordChild6: case OPC_RecordChild7: {
29860b57cec5SDimitry Andric       unsigned ChildNo = Opcode-OPC_RecordChild0;
29870b57cec5SDimitry Andric       if (ChildNo >= N.getNumOperands())
29880b57cec5SDimitry Andric         break;  // Match fails if out of range child #.
29890b57cec5SDimitry Andric 
29900b57cec5SDimitry Andric       RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
29910b57cec5SDimitry Andric                                              N.getNode()));
29920b57cec5SDimitry Andric       continue;
29930b57cec5SDimitry Andric     }
29940b57cec5SDimitry Andric     case OPC_RecordMemRef:
29950b57cec5SDimitry Andric       if (auto *MN = dyn_cast<MemSDNode>(N))
29960b57cec5SDimitry Andric         MatchedMemRefs.push_back(MN->getMemOperand());
29970b57cec5SDimitry Andric       else {
29980b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Expected MemSDNode "; N->dump(CurDAG);
29990b57cec5SDimitry Andric                    dbgs() << '\n');
30000b57cec5SDimitry Andric       }
30010b57cec5SDimitry Andric 
30020b57cec5SDimitry Andric       continue;
30030b57cec5SDimitry Andric 
30040b57cec5SDimitry Andric     case OPC_CaptureGlueInput:
30050b57cec5SDimitry Andric       // If the current node has an input glue, capture it in InputGlue.
30060b57cec5SDimitry Andric       if (N->getNumOperands() != 0 &&
30070b57cec5SDimitry Andric           N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
30080b57cec5SDimitry Andric         InputGlue = N->getOperand(N->getNumOperands()-1);
30090b57cec5SDimitry Andric       continue;
30100b57cec5SDimitry Andric 
30110b57cec5SDimitry Andric     case OPC_MoveChild: {
30120b57cec5SDimitry Andric       unsigned ChildNo = MatcherTable[MatcherIndex++];
30130b57cec5SDimitry Andric       if (ChildNo >= N.getNumOperands())
30140b57cec5SDimitry Andric         break;  // Match fails if out of range child #.
30150b57cec5SDimitry Andric       N = N.getOperand(ChildNo);
30160b57cec5SDimitry Andric       NodeStack.push_back(N);
30170b57cec5SDimitry Andric       continue;
30180b57cec5SDimitry Andric     }
30190b57cec5SDimitry Andric 
30200b57cec5SDimitry Andric     case OPC_MoveChild0: case OPC_MoveChild1:
30210b57cec5SDimitry Andric     case OPC_MoveChild2: case OPC_MoveChild3:
30220b57cec5SDimitry Andric     case OPC_MoveChild4: case OPC_MoveChild5:
30230b57cec5SDimitry Andric     case OPC_MoveChild6: case OPC_MoveChild7: {
30240b57cec5SDimitry Andric       unsigned ChildNo = Opcode-OPC_MoveChild0;
30250b57cec5SDimitry Andric       if (ChildNo >= N.getNumOperands())
30260b57cec5SDimitry Andric         break;  // Match fails if out of range child #.
30270b57cec5SDimitry Andric       N = N.getOperand(ChildNo);
30280b57cec5SDimitry Andric       NodeStack.push_back(N);
30290b57cec5SDimitry Andric       continue;
30300b57cec5SDimitry Andric     }
30310b57cec5SDimitry Andric 
30320b57cec5SDimitry Andric     case OPC_MoveParent:
30330b57cec5SDimitry Andric       // Pop the current node off the NodeStack.
30340b57cec5SDimitry Andric       NodeStack.pop_back();
30350b57cec5SDimitry Andric       assert(!NodeStack.empty() && "Node stack imbalance!");
30360b57cec5SDimitry Andric       N = NodeStack.back();
30370b57cec5SDimitry Andric       continue;
30380b57cec5SDimitry Andric 
30390b57cec5SDimitry Andric     case OPC_CheckSame:
30400b57cec5SDimitry Andric       if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
30410b57cec5SDimitry Andric       continue;
30420b57cec5SDimitry Andric 
30430b57cec5SDimitry Andric     case OPC_CheckChild0Same: case OPC_CheckChild1Same:
30440b57cec5SDimitry Andric     case OPC_CheckChild2Same: case OPC_CheckChild3Same:
30450b57cec5SDimitry Andric       if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes,
30460b57cec5SDimitry Andric                             Opcode-OPC_CheckChild0Same))
30470b57cec5SDimitry Andric         break;
30480b57cec5SDimitry Andric       continue;
30490b57cec5SDimitry Andric 
30500b57cec5SDimitry Andric     case OPC_CheckPatternPredicate:
30510b57cec5SDimitry Andric       if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
30520b57cec5SDimitry Andric       continue;
30530b57cec5SDimitry Andric     case OPC_CheckPredicate:
30540b57cec5SDimitry Andric       if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
30550b57cec5SDimitry Andric                                 N.getNode()))
30560b57cec5SDimitry Andric         break;
30570b57cec5SDimitry Andric       continue;
30580b57cec5SDimitry Andric     case OPC_CheckPredicateWithOperands: {
30590b57cec5SDimitry Andric       unsigned OpNum = MatcherTable[MatcherIndex++];
30600b57cec5SDimitry Andric       SmallVector<SDValue, 8> Operands;
30610b57cec5SDimitry Andric 
30620b57cec5SDimitry Andric       for (unsigned i = 0; i < OpNum; ++i)
30630b57cec5SDimitry Andric         Operands.push_back(RecordedNodes[MatcherTable[MatcherIndex++]].first);
30640b57cec5SDimitry Andric 
30650b57cec5SDimitry Andric       unsigned PredNo = MatcherTable[MatcherIndex++];
30660b57cec5SDimitry Andric       if (!CheckNodePredicateWithOperands(N.getNode(), PredNo, Operands))
30670b57cec5SDimitry Andric         break;
30680b57cec5SDimitry Andric       continue;
30690b57cec5SDimitry Andric     }
30700b57cec5SDimitry Andric     case OPC_CheckComplexPat: {
30710b57cec5SDimitry Andric       unsigned CPNum = MatcherTable[MatcherIndex++];
30720b57cec5SDimitry Andric       unsigned RecNo = MatcherTable[MatcherIndex++];
30730b57cec5SDimitry Andric       assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
30740b57cec5SDimitry Andric 
30750b57cec5SDimitry Andric       // If target can modify DAG during matching, keep the matching state
30760b57cec5SDimitry Andric       // consistent.
30770b57cec5SDimitry Andric       std::unique_ptr<MatchStateUpdater> MSU;
30780b57cec5SDimitry Andric       if (ComplexPatternFuncMutatesDAG())
30790b57cec5SDimitry Andric         MSU.reset(new MatchStateUpdater(*CurDAG, &NodeToMatch, RecordedNodes,
30800b57cec5SDimitry Andric                                         MatchScopes));
30810b57cec5SDimitry Andric 
30820b57cec5SDimitry Andric       if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
30830b57cec5SDimitry Andric                                RecordedNodes[RecNo].first, CPNum,
30840b57cec5SDimitry Andric                                RecordedNodes))
30850b57cec5SDimitry Andric         break;
30860b57cec5SDimitry Andric       continue;
30870b57cec5SDimitry Andric     }
30880b57cec5SDimitry Andric     case OPC_CheckOpcode:
30890b57cec5SDimitry Andric       if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
30900b57cec5SDimitry Andric       continue;
30910b57cec5SDimitry Andric 
30920b57cec5SDimitry Andric     case OPC_CheckType:
30930b57cec5SDimitry Andric       if (!::CheckType(MatcherTable, MatcherIndex, N, TLI,
30940b57cec5SDimitry Andric                        CurDAG->getDataLayout()))
30950b57cec5SDimitry Andric         break;
30960b57cec5SDimitry Andric       continue;
30970b57cec5SDimitry Andric 
30980b57cec5SDimitry Andric     case OPC_CheckTypeRes: {
30990b57cec5SDimitry Andric       unsigned Res = MatcherTable[MatcherIndex++];
31000b57cec5SDimitry Andric       if (!::CheckType(MatcherTable, MatcherIndex, N.getValue(Res), TLI,
31010b57cec5SDimitry Andric                        CurDAG->getDataLayout()))
31020b57cec5SDimitry Andric         break;
31030b57cec5SDimitry Andric       continue;
31040b57cec5SDimitry Andric     }
31050b57cec5SDimitry Andric 
31060b57cec5SDimitry Andric     case OPC_SwitchOpcode: {
31070b57cec5SDimitry Andric       unsigned CurNodeOpcode = N.getOpcode();
31080b57cec5SDimitry Andric       unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
31090b57cec5SDimitry Andric       unsigned CaseSize;
31100b57cec5SDimitry Andric       while (true) {
31110b57cec5SDimitry Andric         // Get the size of this case.
31120b57cec5SDimitry Andric         CaseSize = MatcherTable[MatcherIndex++];
31130b57cec5SDimitry Andric         if (CaseSize & 128)
31140b57cec5SDimitry Andric           CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
31150b57cec5SDimitry Andric         if (CaseSize == 0) break;
31160b57cec5SDimitry Andric 
31170b57cec5SDimitry Andric         uint16_t Opc = MatcherTable[MatcherIndex++];
31180b57cec5SDimitry Andric         Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
31190b57cec5SDimitry Andric 
31200b57cec5SDimitry Andric         // If the opcode matches, then we will execute this case.
31210b57cec5SDimitry Andric         if (CurNodeOpcode == Opc)
31220b57cec5SDimitry Andric           break;
31230b57cec5SDimitry Andric 
31240b57cec5SDimitry Andric         // Otherwise, skip over this case.
31250b57cec5SDimitry Andric         MatcherIndex += CaseSize;
31260b57cec5SDimitry Andric       }
31270b57cec5SDimitry Andric 
31280b57cec5SDimitry Andric       // If no cases matched, bail out.
31290b57cec5SDimitry Andric       if (CaseSize == 0) break;
31300b57cec5SDimitry Andric 
31310b57cec5SDimitry Andric       // Otherwise, execute the case we found.
31320b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  OpcodeSwitch from " << SwitchStart << " to "
31330b57cec5SDimitry Andric                         << MatcherIndex << "\n");
31340b57cec5SDimitry Andric       continue;
31350b57cec5SDimitry Andric     }
31360b57cec5SDimitry Andric 
31370b57cec5SDimitry Andric     case OPC_SwitchType: {
31380b57cec5SDimitry Andric       MVT CurNodeVT = N.getSimpleValueType();
31390b57cec5SDimitry Andric       unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
31400b57cec5SDimitry Andric       unsigned CaseSize;
31410b57cec5SDimitry Andric       while (true) {
31420b57cec5SDimitry Andric         // Get the size of this case.
31430b57cec5SDimitry Andric         CaseSize = MatcherTable[MatcherIndex++];
31440b57cec5SDimitry Andric         if (CaseSize & 128)
31450b57cec5SDimitry Andric           CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
31460b57cec5SDimitry Andric         if (CaseSize == 0) break;
31470b57cec5SDimitry Andric 
31480b57cec5SDimitry Andric         MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
31490b57cec5SDimitry Andric         if (CaseVT == MVT::iPTR)
31500b57cec5SDimitry Andric           CaseVT = TLI->getPointerTy(CurDAG->getDataLayout());
31510b57cec5SDimitry Andric 
31520b57cec5SDimitry Andric         // If the VT matches, then we will execute this case.
31530b57cec5SDimitry Andric         if (CurNodeVT == CaseVT)
31540b57cec5SDimitry Andric           break;
31550b57cec5SDimitry Andric 
31560b57cec5SDimitry Andric         // Otherwise, skip over this case.
31570b57cec5SDimitry Andric         MatcherIndex += CaseSize;
31580b57cec5SDimitry Andric       }
31590b57cec5SDimitry Andric 
31600b57cec5SDimitry Andric       // If no cases matched, bail out.
31610b57cec5SDimitry Andric       if (CaseSize == 0) break;
31620b57cec5SDimitry Andric 
31630b57cec5SDimitry Andric       // Otherwise, execute the case we found.
31640b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  TypeSwitch[" << EVT(CurNodeVT).getEVTString()
31650b57cec5SDimitry Andric                         << "] from " << SwitchStart << " to " << MatcherIndex
31660b57cec5SDimitry Andric                         << '\n');
31670b57cec5SDimitry Andric       continue;
31680b57cec5SDimitry Andric     }
31690b57cec5SDimitry Andric     case OPC_CheckChild0Type: case OPC_CheckChild1Type:
31700b57cec5SDimitry Andric     case OPC_CheckChild2Type: case OPC_CheckChild3Type:
31710b57cec5SDimitry Andric     case OPC_CheckChild4Type: case OPC_CheckChild5Type:
31720b57cec5SDimitry Andric     case OPC_CheckChild6Type: case OPC_CheckChild7Type:
31730b57cec5SDimitry Andric       if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
31740b57cec5SDimitry Andric                             CurDAG->getDataLayout(),
31750b57cec5SDimitry Andric                             Opcode - OPC_CheckChild0Type))
31760b57cec5SDimitry Andric         break;
31770b57cec5SDimitry Andric       continue;
31780b57cec5SDimitry Andric     case OPC_CheckCondCode:
31790b57cec5SDimitry Andric       if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
31800b57cec5SDimitry Andric       continue;
31810b57cec5SDimitry Andric     case OPC_CheckChild2CondCode:
31820b57cec5SDimitry Andric       if (!::CheckChild2CondCode(MatcherTable, MatcherIndex, N)) break;
31830b57cec5SDimitry Andric       continue;
31840b57cec5SDimitry Andric     case OPC_CheckValueType:
31850b57cec5SDimitry Andric       if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI,
31860b57cec5SDimitry Andric                             CurDAG->getDataLayout()))
31870b57cec5SDimitry Andric         break;
31880b57cec5SDimitry Andric       continue;
31890b57cec5SDimitry Andric     case OPC_CheckInteger:
31900b57cec5SDimitry Andric       if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
31910b57cec5SDimitry Andric       continue;
31920b57cec5SDimitry Andric     case OPC_CheckChild0Integer: case OPC_CheckChild1Integer:
31930b57cec5SDimitry Andric     case OPC_CheckChild2Integer: case OPC_CheckChild3Integer:
31940b57cec5SDimitry Andric     case OPC_CheckChild4Integer:
31950b57cec5SDimitry Andric       if (!::CheckChildInteger(MatcherTable, MatcherIndex, N,
31960b57cec5SDimitry Andric                                Opcode-OPC_CheckChild0Integer)) break;
31970b57cec5SDimitry Andric       continue;
31980b57cec5SDimitry Andric     case OPC_CheckAndImm:
31990b57cec5SDimitry Andric       if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
32000b57cec5SDimitry Andric       continue;
32010b57cec5SDimitry Andric     case OPC_CheckOrImm:
32020b57cec5SDimitry Andric       if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
32030b57cec5SDimitry Andric       continue;
32040b57cec5SDimitry Andric     case OPC_CheckImmAllOnesV:
3205*e8d8bef9SDimitry Andric       if (!ISD::isConstantSplatVectorAllOnes(N.getNode()))
3206*e8d8bef9SDimitry Andric         break;
32070b57cec5SDimitry Andric       continue;
32080b57cec5SDimitry Andric     case OPC_CheckImmAllZerosV:
3209*e8d8bef9SDimitry Andric       if (!ISD::isConstantSplatVectorAllZeros(N.getNode()))
3210*e8d8bef9SDimitry Andric         break;
32110b57cec5SDimitry Andric       continue;
32120b57cec5SDimitry Andric 
32130b57cec5SDimitry Andric     case OPC_CheckFoldableChainNode: {
32140b57cec5SDimitry Andric       assert(NodeStack.size() != 1 && "No parent node");
32150b57cec5SDimitry Andric       // Verify that all intermediate nodes between the root and this one have
3216480093f4SDimitry Andric       // a single use (ignoring chains, which are handled in UpdateChains).
32170b57cec5SDimitry Andric       bool HasMultipleUses = false;
3218480093f4SDimitry Andric       for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i) {
3219480093f4SDimitry Andric         unsigned NNonChainUses = 0;
3220480093f4SDimitry Andric         SDNode *NS = NodeStack[i].getNode();
3221480093f4SDimitry Andric         for (auto UI = NS->use_begin(), UE = NS->use_end(); UI != UE; ++UI)
3222480093f4SDimitry Andric           if (UI.getUse().getValueType() != MVT::Other)
3223480093f4SDimitry Andric             if (++NNonChainUses > 1) {
32240b57cec5SDimitry Andric               HasMultipleUses = true;
32250b57cec5SDimitry Andric               break;
32260b57cec5SDimitry Andric             }
32270b57cec5SDimitry Andric         if (HasMultipleUses) break;
3228480093f4SDimitry Andric       }
3229480093f4SDimitry Andric       if (HasMultipleUses) break;
32300b57cec5SDimitry Andric 
32310b57cec5SDimitry Andric       // Check to see that the target thinks this is profitable to fold and that
32320b57cec5SDimitry Andric       // we can fold it without inducing cycles in the graph.
32330b57cec5SDimitry Andric       if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
32340b57cec5SDimitry Andric                               NodeToMatch) ||
32350b57cec5SDimitry Andric           !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
32360b57cec5SDimitry Andric                          NodeToMatch, OptLevel,
32370b57cec5SDimitry Andric                          true/*We validate our own chains*/))
32380b57cec5SDimitry Andric         break;
32390b57cec5SDimitry Andric 
32400b57cec5SDimitry Andric       continue;
32410b57cec5SDimitry Andric     }
32420b57cec5SDimitry Andric     case OPC_EmitInteger: {
32430b57cec5SDimitry Andric       MVT::SimpleValueType VT =
32440b57cec5SDimitry Andric         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
32450b57cec5SDimitry Andric       int64_t Val = MatcherTable[MatcherIndex++];
32460b57cec5SDimitry Andric       if (Val & 128)
32470b57cec5SDimitry Andric         Val = GetVBR(Val, MatcherTable, MatcherIndex);
32480b57cec5SDimitry Andric       RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
32490b57cec5SDimitry Andric                               CurDAG->getTargetConstant(Val, SDLoc(NodeToMatch),
32500b57cec5SDimitry Andric                                                         VT), nullptr));
32510b57cec5SDimitry Andric       continue;
32520b57cec5SDimitry Andric     }
32530b57cec5SDimitry Andric     case OPC_EmitRegister: {
32540b57cec5SDimitry Andric       MVT::SimpleValueType VT =
32550b57cec5SDimitry Andric         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
32560b57cec5SDimitry Andric       unsigned RegNo = MatcherTable[MatcherIndex++];
32570b57cec5SDimitry Andric       RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
32580b57cec5SDimitry Andric                               CurDAG->getRegister(RegNo, VT), nullptr));
32590b57cec5SDimitry Andric       continue;
32600b57cec5SDimitry Andric     }
32610b57cec5SDimitry Andric     case OPC_EmitRegister2: {
32620b57cec5SDimitry Andric       // For targets w/ more than 256 register names, the register enum
32630b57cec5SDimitry Andric       // values are stored in two bytes in the matcher table (just like
32640b57cec5SDimitry Andric       // opcodes).
32650b57cec5SDimitry Andric       MVT::SimpleValueType VT =
32660b57cec5SDimitry Andric         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
32670b57cec5SDimitry Andric       unsigned RegNo = MatcherTable[MatcherIndex++];
32680b57cec5SDimitry Andric       RegNo |= MatcherTable[MatcherIndex++] << 8;
32690b57cec5SDimitry Andric       RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
32700b57cec5SDimitry Andric                               CurDAG->getRegister(RegNo, VT), nullptr));
32710b57cec5SDimitry Andric       continue;
32720b57cec5SDimitry Andric     }
32730b57cec5SDimitry Andric 
32740b57cec5SDimitry Andric     case OPC_EmitConvertToTarget:  {
32750b57cec5SDimitry Andric       // Convert from IMM/FPIMM to target version.
32760b57cec5SDimitry Andric       unsigned RecNo = MatcherTable[MatcherIndex++];
32770b57cec5SDimitry Andric       assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget");
32780b57cec5SDimitry Andric       SDValue Imm = RecordedNodes[RecNo].first;
32790b57cec5SDimitry Andric 
32800b57cec5SDimitry Andric       if (Imm->getOpcode() == ISD::Constant) {
32810b57cec5SDimitry Andric         const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
32820b57cec5SDimitry Andric         Imm = CurDAG->getTargetConstant(*Val, SDLoc(NodeToMatch),
32830b57cec5SDimitry Andric                                         Imm.getValueType());
32840b57cec5SDimitry Andric       } else if (Imm->getOpcode() == ISD::ConstantFP) {
32850b57cec5SDimitry Andric         const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
32860b57cec5SDimitry Andric         Imm = CurDAG->getTargetConstantFP(*Val, SDLoc(NodeToMatch),
32870b57cec5SDimitry Andric                                           Imm.getValueType());
32880b57cec5SDimitry Andric       }
32890b57cec5SDimitry Andric 
32900b57cec5SDimitry Andric       RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
32910b57cec5SDimitry Andric       continue;
32920b57cec5SDimitry Andric     }
32930b57cec5SDimitry Andric 
32940b57cec5SDimitry Andric     case OPC_EmitMergeInputChains1_0:    // OPC_EmitMergeInputChains, 1, 0
32950b57cec5SDimitry Andric     case OPC_EmitMergeInputChains1_1:    // OPC_EmitMergeInputChains, 1, 1
32960b57cec5SDimitry Andric     case OPC_EmitMergeInputChains1_2: {  // OPC_EmitMergeInputChains, 1, 2
32970b57cec5SDimitry Andric       // These are space-optimized forms of OPC_EmitMergeInputChains.
32980b57cec5SDimitry Andric       assert(!InputChain.getNode() &&
32990b57cec5SDimitry Andric              "EmitMergeInputChains should be the first chain producing node");
33000b57cec5SDimitry Andric       assert(ChainNodesMatched.empty() &&
33010b57cec5SDimitry Andric              "Should only have one EmitMergeInputChains per match");
33020b57cec5SDimitry Andric 
33030b57cec5SDimitry Andric       // Read all of the chained nodes.
33040b57cec5SDimitry Andric       unsigned RecNo = Opcode - OPC_EmitMergeInputChains1_0;
33050b57cec5SDimitry Andric       assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
33060b57cec5SDimitry Andric       ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
33070b57cec5SDimitry Andric 
33080b57cec5SDimitry Andric       // FIXME: What if other value results of the node have uses not matched
33090b57cec5SDimitry Andric       // by this pattern?
33100b57cec5SDimitry Andric       if (ChainNodesMatched.back() != NodeToMatch &&
33110b57cec5SDimitry Andric           !RecordedNodes[RecNo].first.hasOneUse()) {
33120b57cec5SDimitry Andric         ChainNodesMatched.clear();
33130b57cec5SDimitry Andric         break;
33140b57cec5SDimitry Andric       }
33150b57cec5SDimitry Andric 
33160b57cec5SDimitry Andric       // Merge the input chains if they are not intra-pattern references.
33170b57cec5SDimitry Andric       InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
33180b57cec5SDimitry Andric 
33190b57cec5SDimitry Andric       if (!InputChain.getNode())
33200b57cec5SDimitry Andric         break;  // Failed to merge.
33210b57cec5SDimitry Andric       continue;
33220b57cec5SDimitry Andric     }
33230b57cec5SDimitry Andric 
33240b57cec5SDimitry Andric     case OPC_EmitMergeInputChains: {
33250b57cec5SDimitry Andric       assert(!InputChain.getNode() &&
33260b57cec5SDimitry Andric              "EmitMergeInputChains should be the first chain producing node");
33270b57cec5SDimitry Andric       // This node gets a list of nodes we matched in the input that have
33280b57cec5SDimitry Andric       // chains.  We want to token factor all of the input chains to these nodes
33290b57cec5SDimitry Andric       // together.  However, if any of the input chains is actually one of the
33300b57cec5SDimitry Andric       // nodes matched in this pattern, then we have an intra-match reference.
33310b57cec5SDimitry Andric       // Ignore these because the newly token factored chain should not refer to
33320b57cec5SDimitry Andric       // the old nodes.
33330b57cec5SDimitry Andric       unsigned NumChains = MatcherTable[MatcherIndex++];
33340b57cec5SDimitry Andric       assert(NumChains != 0 && "Can't TF zero chains");
33350b57cec5SDimitry Andric 
33360b57cec5SDimitry Andric       assert(ChainNodesMatched.empty() &&
33370b57cec5SDimitry Andric              "Should only have one EmitMergeInputChains per match");
33380b57cec5SDimitry Andric 
33390b57cec5SDimitry Andric       // Read all of the chained nodes.
33400b57cec5SDimitry Andric       for (unsigned i = 0; i != NumChains; ++i) {
33410b57cec5SDimitry Andric         unsigned RecNo = MatcherTable[MatcherIndex++];
33420b57cec5SDimitry Andric         assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
33430b57cec5SDimitry Andric         ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
33440b57cec5SDimitry Andric 
33450b57cec5SDimitry Andric         // FIXME: What if other value results of the node have uses not matched
33460b57cec5SDimitry Andric         // by this pattern?
33470b57cec5SDimitry Andric         if (ChainNodesMatched.back() != NodeToMatch &&
33480b57cec5SDimitry Andric             !RecordedNodes[RecNo].first.hasOneUse()) {
33490b57cec5SDimitry Andric           ChainNodesMatched.clear();
33500b57cec5SDimitry Andric           break;
33510b57cec5SDimitry Andric         }
33520b57cec5SDimitry Andric       }
33530b57cec5SDimitry Andric 
33540b57cec5SDimitry Andric       // If the inner loop broke out, the match fails.
33550b57cec5SDimitry Andric       if (ChainNodesMatched.empty())
33560b57cec5SDimitry Andric         break;
33570b57cec5SDimitry Andric 
33580b57cec5SDimitry Andric       // Merge the input chains if they are not intra-pattern references.
33590b57cec5SDimitry Andric       InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
33600b57cec5SDimitry Andric 
33610b57cec5SDimitry Andric       if (!InputChain.getNode())
33620b57cec5SDimitry Andric         break;  // Failed to merge.
33630b57cec5SDimitry Andric 
33640b57cec5SDimitry Andric       continue;
33650b57cec5SDimitry Andric     }
33660b57cec5SDimitry Andric 
33678bcb0991SDimitry Andric     case OPC_EmitCopyToReg:
33688bcb0991SDimitry Andric     case OPC_EmitCopyToReg2: {
33690b57cec5SDimitry Andric       unsigned RecNo = MatcherTable[MatcherIndex++];
33700b57cec5SDimitry Andric       assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg");
33710b57cec5SDimitry Andric       unsigned DestPhysReg = MatcherTable[MatcherIndex++];
33728bcb0991SDimitry Andric       if (Opcode == OPC_EmitCopyToReg2)
33738bcb0991SDimitry Andric         DestPhysReg |= MatcherTable[MatcherIndex++] << 8;
33740b57cec5SDimitry Andric 
33750b57cec5SDimitry Andric       if (!InputChain.getNode())
33760b57cec5SDimitry Andric         InputChain = CurDAG->getEntryNode();
33770b57cec5SDimitry Andric 
33780b57cec5SDimitry Andric       InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
33790b57cec5SDimitry Andric                                         DestPhysReg, RecordedNodes[RecNo].first,
33800b57cec5SDimitry Andric                                         InputGlue);
33810b57cec5SDimitry Andric 
33820b57cec5SDimitry Andric       InputGlue = InputChain.getValue(1);
33830b57cec5SDimitry Andric       continue;
33840b57cec5SDimitry Andric     }
33850b57cec5SDimitry Andric 
33860b57cec5SDimitry Andric     case OPC_EmitNodeXForm: {
33870b57cec5SDimitry Andric       unsigned XFormNo = MatcherTable[MatcherIndex++];
33880b57cec5SDimitry Andric       unsigned RecNo = MatcherTable[MatcherIndex++];
33890b57cec5SDimitry Andric       assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm");
33900b57cec5SDimitry Andric       SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
33910b57cec5SDimitry Andric       RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr));
33920b57cec5SDimitry Andric       continue;
33930b57cec5SDimitry Andric     }
33940b57cec5SDimitry Andric     case OPC_Coverage: {
33950b57cec5SDimitry Andric       // This is emitted right before MorphNode/EmitNode.
33960b57cec5SDimitry Andric       // So it should be safe to assume that this node has been selected
33970b57cec5SDimitry Andric       unsigned index = MatcherTable[MatcherIndex++];
33980b57cec5SDimitry Andric       index |= (MatcherTable[MatcherIndex++] << 8);
33990b57cec5SDimitry Andric       dbgs() << "COVERED: " << getPatternForIndex(index) << "\n";
34000b57cec5SDimitry Andric       dbgs() << "INCLUDED: " << getIncludePathForIndex(index) << "\n";
34010b57cec5SDimitry Andric       continue;
34020b57cec5SDimitry Andric     }
34030b57cec5SDimitry Andric 
34040b57cec5SDimitry Andric     case OPC_EmitNode:     case OPC_MorphNodeTo:
34050b57cec5SDimitry Andric     case OPC_EmitNode0:    case OPC_EmitNode1:    case OPC_EmitNode2:
34060b57cec5SDimitry Andric     case OPC_MorphNodeTo0: case OPC_MorphNodeTo1: case OPC_MorphNodeTo2: {
34070b57cec5SDimitry Andric       uint16_t TargetOpc = MatcherTable[MatcherIndex++];
34080b57cec5SDimitry Andric       TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
34090b57cec5SDimitry Andric       unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
34100b57cec5SDimitry Andric       // Get the result VT list.
34110b57cec5SDimitry Andric       unsigned NumVTs;
34120b57cec5SDimitry Andric       // If this is one of the compressed forms, get the number of VTs based
34130b57cec5SDimitry Andric       // on the Opcode. Otherwise read the next byte from the table.
34140b57cec5SDimitry Andric       if (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2)
34150b57cec5SDimitry Andric         NumVTs = Opcode - OPC_MorphNodeTo0;
34160b57cec5SDimitry Andric       else if (Opcode >= OPC_EmitNode0 && Opcode <= OPC_EmitNode2)
34170b57cec5SDimitry Andric         NumVTs = Opcode - OPC_EmitNode0;
34180b57cec5SDimitry Andric       else
34190b57cec5SDimitry Andric         NumVTs = MatcherTable[MatcherIndex++];
34200b57cec5SDimitry Andric       SmallVector<EVT, 4> VTs;
34210b57cec5SDimitry Andric       for (unsigned i = 0; i != NumVTs; ++i) {
34220b57cec5SDimitry Andric         MVT::SimpleValueType VT =
34230b57cec5SDimitry Andric           (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
34240b57cec5SDimitry Andric         if (VT == MVT::iPTR)
34250b57cec5SDimitry Andric           VT = TLI->getPointerTy(CurDAG->getDataLayout()).SimpleTy;
34260b57cec5SDimitry Andric         VTs.push_back(VT);
34270b57cec5SDimitry Andric       }
34280b57cec5SDimitry Andric 
34290b57cec5SDimitry Andric       if (EmitNodeInfo & OPFL_Chain)
34300b57cec5SDimitry Andric         VTs.push_back(MVT::Other);
34310b57cec5SDimitry Andric       if (EmitNodeInfo & OPFL_GlueOutput)
34320b57cec5SDimitry Andric         VTs.push_back(MVT::Glue);
34330b57cec5SDimitry Andric 
34340b57cec5SDimitry Andric       // This is hot code, so optimize the two most common cases of 1 and 2
34350b57cec5SDimitry Andric       // results.
34360b57cec5SDimitry Andric       SDVTList VTList;
34370b57cec5SDimitry Andric       if (VTs.size() == 1)
34380b57cec5SDimitry Andric         VTList = CurDAG->getVTList(VTs[0]);
34390b57cec5SDimitry Andric       else if (VTs.size() == 2)
34400b57cec5SDimitry Andric         VTList = CurDAG->getVTList(VTs[0], VTs[1]);
34410b57cec5SDimitry Andric       else
34420b57cec5SDimitry Andric         VTList = CurDAG->getVTList(VTs);
34430b57cec5SDimitry Andric 
34440b57cec5SDimitry Andric       // Get the operand list.
34450b57cec5SDimitry Andric       unsigned NumOps = MatcherTable[MatcherIndex++];
34460b57cec5SDimitry Andric       SmallVector<SDValue, 8> Ops;
34470b57cec5SDimitry Andric       for (unsigned i = 0; i != NumOps; ++i) {
34480b57cec5SDimitry Andric         unsigned RecNo = MatcherTable[MatcherIndex++];
34490b57cec5SDimitry Andric         if (RecNo & 128)
34500b57cec5SDimitry Andric           RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
34510b57cec5SDimitry Andric 
34520b57cec5SDimitry Andric         assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
34530b57cec5SDimitry Andric         Ops.push_back(RecordedNodes[RecNo].first);
34540b57cec5SDimitry Andric       }
34550b57cec5SDimitry Andric 
34560b57cec5SDimitry Andric       // If there are variadic operands to add, handle them now.
34570b57cec5SDimitry Andric       if (EmitNodeInfo & OPFL_VariadicInfo) {
34580b57cec5SDimitry Andric         // Determine the start index to copy from.
34590b57cec5SDimitry Andric         unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
34600b57cec5SDimitry Andric         FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
34610b57cec5SDimitry Andric         assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
34620b57cec5SDimitry Andric                "Invalid variadic node");
34630b57cec5SDimitry Andric         // Copy all of the variadic operands, not including a potential glue
34640b57cec5SDimitry Andric         // input.
34650b57cec5SDimitry Andric         for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
34660b57cec5SDimitry Andric              i != e; ++i) {
34670b57cec5SDimitry Andric           SDValue V = NodeToMatch->getOperand(i);
34680b57cec5SDimitry Andric           if (V.getValueType() == MVT::Glue) break;
34690b57cec5SDimitry Andric           Ops.push_back(V);
34700b57cec5SDimitry Andric         }
34710b57cec5SDimitry Andric       }
34720b57cec5SDimitry Andric 
34730b57cec5SDimitry Andric       // If this has chain/glue inputs, add them.
34740b57cec5SDimitry Andric       if (EmitNodeInfo & OPFL_Chain)
34750b57cec5SDimitry Andric         Ops.push_back(InputChain);
34760b57cec5SDimitry Andric       if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr)
34770b57cec5SDimitry Andric         Ops.push_back(InputGlue);
34780b57cec5SDimitry Andric 
3479480093f4SDimitry Andric       // Check whether any matched node could raise an FP exception.  Since all
3480480093f4SDimitry Andric       // such nodes must have a chain, it suffices to check ChainNodesMatched.
3481480093f4SDimitry Andric       // We need to perform this check before potentially modifying one of the
3482480093f4SDimitry Andric       // nodes via MorphNode.
3483480093f4SDimitry Andric       bool MayRaiseFPException = false;
3484480093f4SDimitry Andric       for (auto *N : ChainNodesMatched)
3485480093f4SDimitry Andric         if (mayRaiseFPException(N) && !N->getFlags().hasNoFPExcept()) {
3486480093f4SDimitry Andric           MayRaiseFPException = true;
3487480093f4SDimitry Andric           break;
3488480093f4SDimitry Andric         }
3489480093f4SDimitry Andric 
34900b57cec5SDimitry Andric       // Create the node.
34910b57cec5SDimitry Andric       MachineSDNode *Res = nullptr;
34920b57cec5SDimitry Andric       bool IsMorphNodeTo = Opcode == OPC_MorphNodeTo ||
34930b57cec5SDimitry Andric                      (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2);
34940b57cec5SDimitry Andric       if (!IsMorphNodeTo) {
34950b57cec5SDimitry Andric         // If this is a normal EmitNode command, just create the new node and
34960b57cec5SDimitry Andric         // add the results to the RecordedNodes list.
34970b57cec5SDimitry Andric         Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
34980b57cec5SDimitry Andric                                      VTList, Ops);
34990b57cec5SDimitry Andric 
35000b57cec5SDimitry Andric         // Add all the non-glue/non-chain results to the RecordedNodes list.
35010b57cec5SDimitry Andric         for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
35020b57cec5SDimitry Andric           if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
35030b57cec5SDimitry Andric           RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
35040b57cec5SDimitry Andric                                                              nullptr));
35050b57cec5SDimitry Andric         }
35060b57cec5SDimitry Andric       } else {
35070b57cec5SDimitry Andric         assert(NodeToMatch->getOpcode() != ISD::DELETED_NODE &&
35080b57cec5SDimitry Andric                "NodeToMatch was removed partway through selection");
35090b57cec5SDimitry Andric         SelectionDAG::DAGNodeDeletedListener NDL(*CurDAG, [&](SDNode *N,
35100b57cec5SDimitry Andric                                                               SDNode *E) {
35110b57cec5SDimitry Andric           CurDAG->salvageDebugInfo(*N);
35120b57cec5SDimitry Andric           auto &Chain = ChainNodesMatched;
35130b57cec5SDimitry Andric           assert((!E || !is_contained(Chain, N)) &&
35140b57cec5SDimitry Andric                  "Chain node replaced during MorphNode");
3515*e8d8bef9SDimitry Andric           llvm::erase_value(Chain, N);
35160b57cec5SDimitry Andric         });
35170b57cec5SDimitry Andric         Res = cast<MachineSDNode>(MorphNode(NodeToMatch, TargetOpc, VTList,
35180b57cec5SDimitry Andric                                             Ops, EmitNodeInfo));
35190b57cec5SDimitry Andric       }
35200b57cec5SDimitry Andric 
3521480093f4SDimitry Andric       // Set the NoFPExcept flag when no original matched node could
3522480093f4SDimitry Andric       // raise an FP exception, but the new node potentially might.
3523480093f4SDimitry Andric       if (!MayRaiseFPException && mayRaiseFPException(Res)) {
3524480093f4SDimitry Andric         SDNodeFlags Flags = Res->getFlags();
3525480093f4SDimitry Andric         Flags.setNoFPExcept(true);
3526480093f4SDimitry Andric         Res->setFlags(Flags);
3527480093f4SDimitry Andric       }
3528480093f4SDimitry Andric 
35290b57cec5SDimitry Andric       // If the node had chain/glue results, update our notion of the current
35300b57cec5SDimitry Andric       // chain and glue.
35310b57cec5SDimitry Andric       if (EmitNodeInfo & OPFL_GlueOutput) {
35320b57cec5SDimitry Andric         InputGlue = SDValue(Res, VTs.size()-1);
35330b57cec5SDimitry Andric         if (EmitNodeInfo & OPFL_Chain)
35340b57cec5SDimitry Andric           InputChain = SDValue(Res, VTs.size()-2);
35350b57cec5SDimitry Andric       } else if (EmitNodeInfo & OPFL_Chain)
35360b57cec5SDimitry Andric         InputChain = SDValue(Res, VTs.size()-1);
35370b57cec5SDimitry Andric 
35380b57cec5SDimitry Andric       // If the OPFL_MemRefs glue is set on this node, slap all of the
35390b57cec5SDimitry Andric       // accumulated memrefs onto it.
35400b57cec5SDimitry Andric       //
35410b57cec5SDimitry Andric       // FIXME: This is vastly incorrect for patterns with multiple outputs
35420b57cec5SDimitry Andric       // instructions that access memory and for ComplexPatterns that match
35430b57cec5SDimitry Andric       // loads.
35440b57cec5SDimitry Andric       if (EmitNodeInfo & OPFL_MemRefs) {
35450b57cec5SDimitry Andric         // Only attach load or store memory operands if the generated
35460b57cec5SDimitry Andric         // instruction may load or store.
35470b57cec5SDimitry Andric         const MCInstrDesc &MCID = TII->get(TargetOpc);
35480b57cec5SDimitry Andric         bool mayLoad = MCID.mayLoad();
35490b57cec5SDimitry Andric         bool mayStore = MCID.mayStore();
35500b57cec5SDimitry Andric 
35510b57cec5SDimitry Andric         // We expect to have relatively few of these so just filter them into a
35520b57cec5SDimitry Andric         // temporary buffer so that we can easily add them to the instruction.
35530b57cec5SDimitry Andric         SmallVector<MachineMemOperand *, 4> FilteredMemRefs;
35540b57cec5SDimitry Andric         for (MachineMemOperand *MMO : MatchedMemRefs) {
35550b57cec5SDimitry Andric           if (MMO->isLoad()) {
35560b57cec5SDimitry Andric             if (mayLoad)
35570b57cec5SDimitry Andric               FilteredMemRefs.push_back(MMO);
35580b57cec5SDimitry Andric           } else if (MMO->isStore()) {
35590b57cec5SDimitry Andric             if (mayStore)
35600b57cec5SDimitry Andric               FilteredMemRefs.push_back(MMO);
35610b57cec5SDimitry Andric           } else {
35620b57cec5SDimitry Andric             FilteredMemRefs.push_back(MMO);
35630b57cec5SDimitry Andric           }
35640b57cec5SDimitry Andric         }
35650b57cec5SDimitry Andric 
35660b57cec5SDimitry Andric         CurDAG->setNodeMemRefs(Res, FilteredMemRefs);
35670b57cec5SDimitry Andric       }
35680b57cec5SDimitry Andric 
35690b57cec5SDimitry Andric       LLVM_DEBUG(if (!MatchedMemRefs.empty() && Res->memoperands_empty()) dbgs()
35700b57cec5SDimitry Andric                      << "  Dropping mem operands\n";
35710b57cec5SDimitry Andric                  dbgs() << "  " << (IsMorphNodeTo ? "Morphed" : "Created")
35720b57cec5SDimitry Andric                         << " node: ";
35730b57cec5SDimitry Andric                  Res->dump(CurDAG););
35740b57cec5SDimitry Andric 
35750b57cec5SDimitry Andric       // If this was a MorphNodeTo then we're completely done!
35760b57cec5SDimitry Andric       if (IsMorphNodeTo) {
35770b57cec5SDimitry Andric         // Update chain uses.
35780b57cec5SDimitry Andric         UpdateChains(Res, InputChain, ChainNodesMatched, true);
35790b57cec5SDimitry Andric         return;
35800b57cec5SDimitry Andric       }
35810b57cec5SDimitry Andric       continue;
35820b57cec5SDimitry Andric     }
35830b57cec5SDimitry Andric 
35840b57cec5SDimitry Andric     case OPC_CompleteMatch: {
35850b57cec5SDimitry Andric       // The match has been completed, and any new nodes (if any) have been
35860b57cec5SDimitry Andric       // created.  Patch up references to the matched dag to use the newly
35870b57cec5SDimitry Andric       // created nodes.
35880b57cec5SDimitry Andric       unsigned NumResults = MatcherTable[MatcherIndex++];
35890b57cec5SDimitry Andric 
35900b57cec5SDimitry Andric       for (unsigned i = 0; i != NumResults; ++i) {
35910b57cec5SDimitry Andric         unsigned ResSlot = MatcherTable[MatcherIndex++];
35920b57cec5SDimitry Andric         if (ResSlot & 128)
35930b57cec5SDimitry Andric           ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
35940b57cec5SDimitry Andric 
35950b57cec5SDimitry Andric         assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch");
35960b57cec5SDimitry Andric         SDValue Res = RecordedNodes[ResSlot].first;
35970b57cec5SDimitry Andric 
35980b57cec5SDimitry Andric         assert(i < NodeToMatch->getNumValues() &&
35990b57cec5SDimitry Andric                NodeToMatch->getValueType(i) != MVT::Other &&
36000b57cec5SDimitry Andric                NodeToMatch->getValueType(i) != MVT::Glue &&
36010b57cec5SDimitry Andric                "Invalid number of results to complete!");
36020b57cec5SDimitry Andric         assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
36030b57cec5SDimitry Andric                 NodeToMatch->getValueType(i) == MVT::iPTR ||
36040b57cec5SDimitry Andric                 Res.getValueType() == MVT::iPTR ||
36050b57cec5SDimitry Andric                 NodeToMatch->getValueType(i).getSizeInBits() ==
36060b57cec5SDimitry Andric                     Res.getValueSizeInBits()) &&
36070b57cec5SDimitry Andric                "invalid replacement");
36080b57cec5SDimitry Andric         ReplaceUses(SDValue(NodeToMatch, i), Res);
36090b57cec5SDimitry Andric       }
36100b57cec5SDimitry Andric 
36110b57cec5SDimitry Andric       // Update chain uses.
36120b57cec5SDimitry Andric       UpdateChains(NodeToMatch, InputChain, ChainNodesMatched, false);
36130b57cec5SDimitry Andric 
36140b57cec5SDimitry Andric       // If the root node defines glue, we need to update it to the glue result.
36150b57cec5SDimitry Andric       // TODO: This never happens in our tests and I think it can be removed /
36160b57cec5SDimitry Andric       // replaced with an assert, but if we do it this the way the change is
36170b57cec5SDimitry Andric       // NFC.
36180b57cec5SDimitry Andric       if (NodeToMatch->getValueType(NodeToMatch->getNumValues() - 1) ==
36190b57cec5SDimitry Andric               MVT::Glue &&
36200b57cec5SDimitry Andric           InputGlue.getNode())
36210b57cec5SDimitry Andric         ReplaceUses(SDValue(NodeToMatch, NodeToMatch->getNumValues() - 1),
36220b57cec5SDimitry Andric                     InputGlue);
36230b57cec5SDimitry Andric 
36240b57cec5SDimitry Andric       assert(NodeToMatch->use_empty() &&
36250b57cec5SDimitry Andric              "Didn't replace all uses of the node?");
36260b57cec5SDimitry Andric       CurDAG->RemoveDeadNode(NodeToMatch);
36270b57cec5SDimitry Andric 
36280b57cec5SDimitry Andric       return;
36290b57cec5SDimitry Andric     }
36300b57cec5SDimitry Andric     }
36310b57cec5SDimitry Andric 
36320b57cec5SDimitry Andric     // If the code reached this point, then the match failed.  See if there is
36330b57cec5SDimitry Andric     // another child to try in the current 'Scope', otherwise pop it until we
36340b57cec5SDimitry Andric     // find a case to check.
36350b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "  Match failed at index " << CurrentOpcodeIndex
36360b57cec5SDimitry Andric                       << "\n");
36370b57cec5SDimitry Andric     ++NumDAGIselRetries;
36380b57cec5SDimitry Andric     while (true) {
36390b57cec5SDimitry Andric       if (MatchScopes.empty()) {
36400b57cec5SDimitry Andric         CannotYetSelect(NodeToMatch);
36410b57cec5SDimitry Andric         return;
36420b57cec5SDimitry Andric       }
36430b57cec5SDimitry Andric 
36440b57cec5SDimitry Andric       // Restore the interpreter state back to the point where the scope was
36450b57cec5SDimitry Andric       // formed.
36460b57cec5SDimitry Andric       MatchScope &LastScope = MatchScopes.back();
36470b57cec5SDimitry Andric       RecordedNodes.resize(LastScope.NumRecordedNodes);
36480b57cec5SDimitry Andric       NodeStack.clear();
36490b57cec5SDimitry Andric       NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
36500b57cec5SDimitry Andric       N = NodeStack.back();
36510b57cec5SDimitry Andric 
36520b57cec5SDimitry Andric       if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
36530b57cec5SDimitry Andric         MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
36540b57cec5SDimitry Andric       MatcherIndex = LastScope.FailIndex;
36550b57cec5SDimitry Andric 
36560b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "  Continuing at " << MatcherIndex << "\n");
36570b57cec5SDimitry Andric 
36580b57cec5SDimitry Andric       InputChain = LastScope.InputChain;
36590b57cec5SDimitry Andric       InputGlue = LastScope.InputGlue;
36600b57cec5SDimitry Andric       if (!LastScope.HasChainNodesMatched)
36610b57cec5SDimitry Andric         ChainNodesMatched.clear();
36620b57cec5SDimitry Andric 
36630b57cec5SDimitry Andric       // Check to see what the offset is at the new MatcherIndex.  If it is zero
36640b57cec5SDimitry Andric       // we have reached the end of this scope, otherwise we have another child
36650b57cec5SDimitry Andric       // in the current scope to try.
36660b57cec5SDimitry Andric       unsigned NumToSkip = MatcherTable[MatcherIndex++];
36670b57cec5SDimitry Andric       if (NumToSkip & 128)
36680b57cec5SDimitry Andric         NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
36690b57cec5SDimitry Andric 
36700b57cec5SDimitry Andric       // If we have another child in this scope to match, update FailIndex and
36710b57cec5SDimitry Andric       // try it.
36720b57cec5SDimitry Andric       if (NumToSkip != 0) {
36730b57cec5SDimitry Andric         LastScope.FailIndex = MatcherIndex+NumToSkip;
36740b57cec5SDimitry Andric         break;
36750b57cec5SDimitry Andric       }
36760b57cec5SDimitry Andric 
36770b57cec5SDimitry Andric       // End of this scope, pop it and try the next child in the containing
36780b57cec5SDimitry Andric       // scope.
36790b57cec5SDimitry Andric       MatchScopes.pop_back();
36800b57cec5SDimitry Andric     }
36810b57cec5SDimitry Andric   }
36820b57cec5SDimitry Andric }
36830b57cec5SDimitry Andric 
3684480093f4SDimitry Andric /// Return whether the node may raise an FP exception.
3685480093f4SDimitry Andric bool SelectionDAGISel::mayRaiseFPException(SDNode *N) const {
3686480093f4SDimitry Andric   // For machine opcodes, consult the MCID flag.
3687480093f4SDimitry Andric   if (N->isMachineOpcode()) {
3688480093f4SDimitry Andric     const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
3689480093f4SDimitry Andric     return MCID.mayRaiseFPException();
3690480093f4SDimitry Andric   }
3691480093f4SDimitry Andric 
3692480093f4SDimitry Andric   // For ISD opcodes, only StrictFP opcodes may raise an FP
3693480093f4SDimitry Andric   // exception.
3694480093f4SDimitry Andric   if (N->isTargetOpcode())
3695480093f4SDimitry Andric     return N->isTargetStrictFPOpcode();
3696480093f4SDimitry Andric   return N->isStrictFPOpcode();
3697480093f4SDimitry Andric }
3698480093f4SDimitry Andric 
36990b57cec5SDimitry Andric bool SelectionDAGISel::isOrEquivalentToAdd(const SDNode *N) const {
37000b57cec5SDimitry Andric   assert(N->getOpcode() == ISD::OR && "Unexpected opcode");
37010b57cec5SDimitry Andric   auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
37020b57cec5SDimitry Andric   if (!C)
37030b57cec5SDimitry Andric     return false;
37040b57cec5SDimitry Andric 
37050b57cec5SDimitry Andric   // Detect when "or" is used to add an offset to a stack object.
37060b57cec5SDimitry Andric   if (auto *FN = dyn_cast<FrameIndexSDNode>(N->getOperand(0))) {
37070b57cec5SDimitry Andric     MachineFrameInfo &MFI = MF->getFrameInfo();
37085ffd83dbSDimitry Andric     Align A = MFI.getObjectAlign(FN->getIndex());
37090b57cec5SDimitry Andric     int32_t Off = C->getSExtValue();
37100b57cec5SDimitry Andric     // If the alleged offset fits in the zero bits guaranteed by
37110b57cec5SDimitry Andric     // the alignment, then this or is really an add.
37125ffd83dbSDimitry Andric     return (Off >= 0) && (((A.value() - 1) & Off) == unsigned(Off));
37130b57cec5SDimitry Andric   }
37140b57cec5SDimitry Andric   return false;
37150b57cec5SDimitry Andric }
37160b57cec5SDimitry Andric 
37170b57cec5SDimitry Andric void SelectionDAGISel::CannotYetSelect(SDNode *N) {
37180b57cec5SDimitry Andric   std::string msg;
37190b57cec5SDimitry Andric   raw_string_ostream Msg(msg);
37200b57cec5SDimitry Andric   Msg << "Cannot select: ";
37210b57cec5SDimitry Andric 
37220b57cec5SDimitry Andric   if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
37230b57cec5SDimitry Andric       N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
37240b57cec5SDimitry Andric       N->getOpcode() != ISD::INTRINSIC_VOID) {
37250b57cec5SDimitry Andric     N->printrFull(Msg, CurDAG);
37260b57cec5SDimitry Andric     Msg << "\nIn function: " << MF->getName();
37270b57cec5SDimitry Andric   } else {
37280b57cec5SDimitry Andric     bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
37290b57cec5SDimitry Andric     unsigned iid =
37300b57cec5SDimitry Andric       cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
37310b57cec5SDimitry Andric     if (iid < Intrinsic::num_intrinsics)
37320b57cec5SDimitry Andric       Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid, None);
37330b57cec5SDimitry Andric     else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
37340b57cec5SDimitry Andric       Msg << "target intrinsic %" << TII->getName(iid);
37350b57cec5SDimitry Andric     else
37360b57cec5SDimitry Andric       Msg << "unknown intrinsic #" << iid;
37370b57cec5SDimitry Andric   }
37380b57cec5SDimitry Andric   report_fatal_error(Msg.str());
37390b57cec5SDimitry Andric }
37400b57cec5SDimitry Andric 
37410b57cec5SDimitry Andric char SelectionDAGISel::ID = 0;
3742