LLVM API Documentation

SelectionDAGISel.cpp
Go to the documentation of this file.
00001 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This implements the SelectionDAGISel class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "llvm/CodeGen/SelectionDAGISel.h"
00015 #include "ScheduleDAGSDNodes.h"
00016 #include "SelectionDAGBuilder.h"
00017 #include "llvm/ADT/PostOrderIterator.h"
00018 #include "llvm/ADT/Statistic.h"
00019 #include "llvm/Analysis/AliasAnalysis.h"
00020 #include "llvm/Analysis/BranchProbabilityInfo.h"
00021 #include "llvm/Analysis/CFG.h"
00022 #include "llvm/CodeGen/FastISel.h"
00023 #include "llvm/CodeGen/FunctionLoweringInfo.h"
00024 #include "llvm/CodeGen/GCMetadata.h"
00025 #include "llvm/CodeGen/GCStrategy.h"
00026 #include "llvm/CodeGen/MachineFrameInfo.h"
00027 #include "llvm/CodeGen/MachineFunction.h"
00028 #include "llvm/CodeGen/MachineInstrBuilder.h"
00029 #include "llvm/CodeGen/MachineModuleInfo.h"
00030 #include "llvm/CodeGen/MachineRegisterInfo.h"
00031 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
00032 #include "llvm/CodeGen/SchedulerRegistry.h"
00033 #include "llvm/CodeGen/SelectionDAG.h"
00034 #include "llvm/IR/Constants.h"
00035 #include "llvm/IR/DebugInfo.h"
00036 #include "llvm/IR/Function.h"
00037 #include "llvm/IR/InlineAsm.h"
00038 #include "llvm/IR/Instructions.h"
00039 #include "llvm/IR/IntrinsicInst.h"
00040 #include "llvm/IR/Intrinsics.h"
00041 #include "llvm/IR/LLVMContext.h"
00042 #include "llvm/IR/Module.h"
00043 #include "llvm/Support/Compiler.h"
00044 #include "llvm/Support/Debug.h"
00045 #include "llvm/Support/ErrorHandling.h"
00046 #include "llvm/Support/Timer.h"
00047 #include "llvm/Support/raw_ostream.h"
00048 #include "llvm/Target/TargetInstrInfo.h"
00049 #include "llvm/Target/TargetIntrinsicInfo.h"
00050 #include "llvm/Target/TargetLibraryInfo.h"
00051 #include "llvm/Target/TargetLowering.h"
00052 #include "llvm/Target/TargetMachine.h"
00053 #include "llvm/Target/TargetOptions.h"
00054 #include "llvm/Target/TargetRegisterInfo.h"
00055 #include "llvm/Target/TargetSubtargetInfo.h"
00056 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00057 #include <algorithm>
00058 using namespace llvm;
00059 
00060 #define DEBUG_TYPE "isel"
00061 
00062 STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
00063 STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
00064 STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
00065 STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
00066 STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
00067 STATISTIC(NumEntryBlocks, "Number of entry blocks encountered");
00068 STATISTIC(NumFastIselFailLowerArguments,
00069           "Number of entry blocks where fast isel failed to lower arguments");
00070 
00071 #ifndef NDEBUG
00072 static cl::opt<bool>
00073 EnableFastISelVerbose2("fast-isel-verbose2", cl::Hidden,
00074           cl::desc("Enable extra verbose messages in the \"fast\" "
00075                    "instruction selector"));
00076 
00077   // Terminators
00078 STATISTIC(NumFastIselFailRet,"Fast isel fails on Ret");
00079 STATISTIC(NumFastIselFailBr,"Fast isel fails on Br");
00080 STATISTIC(NumFastIselFailSwitch,"Fast isel fails on Switch");
00081 STATISTIC(NumFastIselFailIndirectBr,"Fast isel fails on IndirectBr");
00082 STATISTIC(NumFastIselFailInvoke,"Fast isel fails on Invoke");
00083 STATISTIC(NumFastIselFailResume,"Fast isel fails on Resume");
00084 STATISTIC(NumFastIselFailUnreachable,"Fast isel fails on Unreachable");
00085 
00086   // Standard binary operators...
00087 STATISTIC(NumFastIselFailAdd,"Fast isel fails on Add");
00088 STATISTIC(NumFastIselFailFAdd,"Fast isel fails on FAdd");
00089 STATISTIC(NumFastIselFailSub,"Fast isel fails on Sub");
00090 STATISTIC(NumFastIselFailFSub,"Fast isel fails on FSub");
00091 STATISTIC(NumFastIselFailMul,"Fast isel fails on Mul");
00092 STATISTIC(NumFastIselFailFMul,"Fast isel fails on FMul");
00093 STATISTIC(NumFastIselFailUDiv,"Fast isel fails on UDiv");
00094 STATISTIC(NumFastIselFailSDiv,"Fast isel fails on SDiv");
00095 STATISTIC(NumFastIselFailFDiv,"Fast isel fails on FDiv");
00096 STATISTIC(NumFastIselFailURem,"Fast isel fails on URem");
00097 STATISTIC(NumFastIselFailSRem,"Fast isel fails on SRem");
00098 STATISTIC(NumFastIselFailFRem,"Fast isel fails on FRem");
00099 
00100   // Logical operators...
00101 STATISTIC(NumFastIselFailAnd,"Fast isel fails on And");
00102 STATISTIC(NumFastIselFailOr,"Fast isel fails on Or");
00103 STATISTIC(NumFastIselFailXor,"Fast isel fails on Xor");
00104 
00105   // Memory instructions...
00106 STATISTIC(NumFastIselFailAlloca,"Fast isel fails on Alloca");
00107 STATISTIC(NumFastIselFailLoad,"Fast isel fails on Load");
00108 STATISTIC(NumFastIselFailStore,"Fast isel fails on Store");
00109 STATISTIC(NumFastIselFailAtomicCmpXchg,"Fast isel fails on AtomicCmpXchg");
00110 STATISTIC(NumFastIselFailAtomicRMW,"Fast isel fails on AtomicRWM");
00111 STATISTIC(NumFastIselFailFence,"Fast isel fails on Frence");
00112 STATISTIC(NumFastIselFailGetElementPtr,"Fast isel fails on GetElementPtr");
00113 
00114   // Convert instructions...
00115 STATISTIC(NumFastIselFailTrunc,"Fast isel fails on Trunc");
00116 STATISTIC(NumFastIselFailZExt,"Fast isel fails on ZExt");
00117 STATISTIC(NumFastIselFailSExt,"Fast isel fails on SExt");
00118 STATISTIC(NumFastIselFailFPTrunc,"Fast isel fails on FPTrunc");
00119 STATISTIC(NumFastIselFailFPExt,"Fast isel fails on FPExt");
00120 STATISTIC(NumFastIselFailFPToUI,"Fast isel fails on FPToUI");
00121 STATISTIC(NumFastIselFailFPToSI,"Fast isel fails on FPToSI");
00122 STATISTIC(NumFastIselFailUIToFP,"Fast isel fails on UIToFP");
00123 STATISTIC(NumFastIselFailSIToFP,"Fast isel fails on SIToFP");
00124 STATISTIC(NumFastIselFailIntToPtr,"Fast isel fails on IntToPtr");
00125 STATISTIC(NumFastIselFailPtrToInt,"Fast isel fails on PtrToInt");
00126 STATISTIC(NumFastIselFailBitCast,"Fast isel fails on BitCast");
00127 
00128   // Other instructions...
00129 STATISTIC(NumFastIselFailICmp,"Fast isel fails on ICmp");
00130 STATISTIC(NumFastIselFailFCmp,"Fast isel fails on FCmp");
00131 STATISTIC(NumFastIselFailPHI,"Fast isel fails on PHI");
00132 STATISTIC(NumFastIselFailSelect,"Fast isel fails on Select");
00133 STATISTIC(NumFastIselFailCall,"Fast isel fails on Call");
00134 STATISTIC(NumFastIselFailShl,"Fast isel fails on Shl");
00135 STATISTIC(NumFastIselFailLShr,"Fast isel fails on LShr");
00136 STATISTIC(NumFastIselFailAShr,"Fast isel fails on AShr");
00137 STATISTIC(NumFastIselFailVAArg,"Fast isel fails on VAArg");
00138 STATISTIC(NumFastIselFailExtractElement,"Fast isel fails on ExtractElement");
00139 STATISTIC(NumFastIselFailInsertElement,"Fast isel fails on InsertElement");
00140 STATISTIC(NumFastIselFailShuffleVector,"Fast isel fails on ShuffleVector");
00141 STATISTIC(NumFastIselFailExtractValue,"Fast isel fails on ExtractValue");
00142 STATISTIC(NumFastIselFailInsertValue,"Fast isel fails on InsertValue");
00143 STATISTIC(NumFastIselFailLandingPad,"Fast isel fails on LandingPad");
00144 
00145 // Intrinsic instructions...
00146 STATISTIC(NumFastIselFailIntrinsicCall, "Fast isel fails on Intrinsic call");
00147 STATISTIC(NumFastIselFailSAddWithOverflow,
00148           "Fast isel fails on sadd.with.overflow");
00149 STATISTIC(NumFastIselFailUAddWithOverflow,
00150           "Fast isel fails on uadd.with.overflow");
00151 STATISTIC(NumFastIselFailSSubWithOverflow,
00152           "Fast isel fails on ssub.with.overflow");
00153 STATISTIC(NumFastIselFailUSubWithOverflow,
00154           "Fast isel fails on usub.with.overflow");
00155 STATISTIC(NumFastIselFailSMulWithOverflow,
00156           "Fast isel fails on smul.with.overflow");
00157 STATISTIC(NumFastIselFailUMulWithOverflow,
00158           "Fast isel fails on umul.with.overflow");
00159 STATISTIC(NumFastIselFailFrameaddress, "Fast isel fails on Frameaddress");
00160 STATISTIC(NumFastIselFailSqrt, "Fast isel fails on sqrt call");
00161 STATISTIC(NumFastIselFailStackMap, "Fast isel fails on StackMap call");
00162 STATISTIC(NumFastIselFailPatchPoint, "Fast isel fails on PatchPoint call");
00163 #endif
00164 
00165 static cl::opt<bool>
00166 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
00167           cl::desc("Enable verbose messages in the \"fast\" "
00168                    "instruction selector"));
00169 static cl::opt<bool>
00170 EnableFastISelAbort("fast-isel-abort", cl::Hidden,
00171           cl::desc("Enable abort calls when \"fast\" instruction selection "
00172                    "fails to lower an instruction"));
00173 static cl::opt<bool>
00174 EnableFastISelAbortArgs("fast-isel-abort-args", cl::Hidden,
00175           cl::desc("Enable abort calls when \"fast\" instruction selection "
00176                    "fails to lower a formal argument"));
00177 
00178 static cl::opt<bool>
00179 UseMBPI("use-mbpi",
00180         cl::desc("use Machine Branch Probability Info"),
00181         cl::init(true), cl::Hidden);
00182 
00183 #ifndef NDEBUG
00184 static cl::opt<bool>
00185 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
00186           cl::desc("Pop up a window to show dags before the first "
00187                    "dag combine pass"));
00188 static cl::opt<bool>
00189 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
00190           cl::desc("Pop up a window to show dags before legalize types"));
00191 static cl::opt<bool>
00192 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
00193           cl::desc("Pop up a window to show dags before legalize"));
00194 static cl::opt<bool>
00195 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
00196           cl::desc("Pop up a window to show dags before the second "
00197                    "dag combine pass"));
00198 static cl::opt<bool>
00199 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
00200           cl::desc("Pop up a window to show dags before the post legalize types"
00201                    " dag combine pass"));
00202 static cl::opt<bool>
00203 ViewISelDAGs("view-isel-dags", cl::Hidden,
00204           cl::desc("Pop up a window to show isel dags as they are selected"));
00205 static cl::opt<bool>
00206 ViewSchedDAGs("view-sched-dags", cl::Hidden,
00207           cl::desc("Pop up a window to show sched dags as they are processed"));
00208 static cl::opt<bool>
00209 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
00210       cl::desc("Pop up a window to show SUnit dags after they are processed"));
00211 #else
00212 static const bool ViewDAGCombine1 = false,
00213                   ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
00214                   ViewDAGCombine2 = false,
00215                   ViewDAGCombineLT = false,
00216                   ViewISelDAGs = false, ViewSchedDAGs = false,
00217                   ViewSUnitDAGs = false;
00218 #endif
00219 
00220 //===---------------------------------------------------------------------===//
00221 ///
00222 /// RegisterScheduler class - Track the registration of instruction schedulers.
00223 ///
00224 //===---------------------------------------------------------------------===//
00225 MachinePassRegistry RegisterScheduler::Registry;
00226 
00227 //===---------------------------------------------------------------------===//
00228 ///
00229 /// ISHeuristic command line option for instruction schedulers.
00230 ///
00231 //===---------------------------------------------------------------------===//
00232 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
00233                RegisterPassParser<RegisterScheduler> >
00234 ISHeuristic("pre-RA-sched",
00235             cl::init(&createDefaultScheduler), cl::Hidden,
00236             cl::desc("Instruction schedulers available (before register"
00237                      " allocation):"));
00238 
00239 static RegisterScheduler
00240 defaultListDAGScheduler("default", "Best scheduler for the target",
00241                         createDefaultScheduler);
00242 
00243 namespace llvm {
00244   //===--------------------------------------------------------------------===//
00245   /// \brief This class is used by SelectionDAGISel to temporarily override
00246   /// the optimization level on a per-function basis.
00247   class OptLevelChanger {
00248     SelectionDAGISel &IS;
00249     CodeGenOpt::Level SavedOptLevel;
00250     bool SavedFastISel;
00251 
00252   public:
00253     OptLevelChanger(SelectionDAGISel &ISel,
00254                     CodeGenOpt::Level NewOptLevel) : IS(ISel) {
00255       SavedOptLevel = IS.OptLevel;
00256       if (NewOptLevel == SavedOptLevel)
00257         return;
00258       IS.OptLevel = NewOptLevel;
00259       IS.TM.setOptLevel(NewOptLevel);
00260       SavedFastISel = IS.TM.Options.EnableFastISel;
00261       if (NewOptLevel == CodeGenOpt::None)
00262         IS.TM.setFastISel(true);
00263       DEBUG(dbgs() << "\nChanging optimization level for Function "
00264             << IS.MF->getFunction()->getName() << "\n");
00265       DEBUG(dbgs() << "\tBefore: -O" << SavedOptLevel
00266             << " ; After: -O" << NewOptLevel << "\n");
00267     }
00268 
00269     ~OptLevelChanger() {
00270       if (IS.OptLevel == SavedOptLevel)
00271         return;
00272       DEBUG(dbgs() << "\nRestoring optimization level for Function "
00273             << IS.MF->getFunction()->getName() << "\n");
00274       DEBUG(dbgs() << "\tBefore: -O" << IS.OptLevel
00275             << " ; After: -O" << SavedOptLevel << "\n");
00276       IS.OptLevel = SavedOptLevel;
00277       IS.TM.setOptLevel(SavedOptLevel);
00278       IS.TM.setFastISel(SavedFastISel);
00279     }
00280   };
00281 
00282   //===--------------------------------------------------------------------===//
00283   /// createDefaultScheduler - This creates an instruction scheduler appropriate
00284   /// for the target.
00285   ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
00286                                              CodeGenOpt::Level OptLevel) {
00287     const TargetLowering *TLI = IS->TLI;
00288     const TargetSubtargetInfo &ST = IS->MF->getSubtarget();
00289 
00290     if (OptLevel == CodeGenOpt::None || ST.useMachineScheduler() ||
00291         TLI->getSchedulingPreference() == Sched::Source)
00292       return createSourceListDAGScheduler(IS, OptLevel);
00293     if (TLI->getSchedulingPreference() == Sched::RegPressure)
00294       return createBURRListDAGScheduler(IS, OptLevel);
00295     if (TLI->getSchedulingPreference() == Sched::Hybrid)
00296       return createHybridListDAGScheduler(IS, OptLevel);
00297     if (TLI->getSchedulingPreference() == Sched::VLIW)
00298       return createVLIWDAGScheduler(IS, OptLevel);
00299     assert(TLI->getSchedulingPreference() == Sched::ILP &&
00300            "Unknown sched type!");
00301     return createILPListDAGScheduler(IS, OptLevel);
00302   }
00303 }
00304 
00305 // EmitInstrWithCustomInserter - This method should be implemented by targets
00306 // that mark instructions with the 'usesCustomInserter' flag.  These
00307 // instructions are special in various ways, which require special support to
00308 // insert.  The specified MachineInstr is created but not inserted into any
00309 // basic blocks, and this method is called to expand it into a sequence of
00310 // instructions, potentially also creating new basic blocks and control flow.
00311 // When new basic blocks are inserted and the edges from MBB to its successors
00312 // are modified, the method should insert pairs of <OldSucc, NewSucc> into the
00313 // DenseMap.
00314 MachineBasicBlock *
00315 TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
00316                                             MachineBasicBlock *MBB) const {
00317 #ifndef NDEBUG
00318   dbgs() << "If a target marks an instruction with "
00319           "'usesCustomInserter', it must implement "
00320           "TargetLowering::EmitInstrWithCustomInserter!";
00321 #endif
00322   llvm_unreachable(nullptr);
00323 }
00324 
00325 void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
00326                                                    SDNode *Node) const {
00327   assert(!MI->hasPostISelHook() &&
00328          "If a target marks an instruction with 'hasPostISelHook', "
00329          "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
00330 }
00331 
00332 //===----------------------------------------------------------------------===//
00333 // SelectionDAGISel code
00334 //===----------------------------------------------------------------------===//
00335 
00336 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm,
00337                                    CodeGenOpt::Level OL) :
00338   MachineFunctionPass(ID), TM(tm),
00339   FuncInfo(new FunctionLoweringInfo()),
00340   CurDAG(new SelectionDAG(tm, OL)),
00341   SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)),
00342   GFI(),
00343   OptLevel(OL),
00344   DAGSize(0) {
00345     initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
00346     initializeAliasAnalysisAnalysisGroup(*PassRegistry::getPassRegistry());
00347     initializeBranchProbabilityInfoPass(*PassRegistry::getPassRegistry());
00348     initializeTargetLibraryInfoPass(*PassRegistry::getPassRegistry());
00349   }
00350 
00351 SelectionDAGISel::~SelectionDAGISel() {
00352   delete SDB;
00353   delete CurDAG;
00354   delete FuncInfo;
00355 }
00356 
00357 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
00358   AU.addRequired<AliasAnalysis>();
00359   AU.addPreserved<AliasAnalysis>();
00360   AU.addRequired<GCModuleInfo>();
00361   AU.addPreserved<GCModuleInfo>();
00362   AU.addRequired<TargetLibraryInfo>();
00363   if (UseMBPI && OptLevel != CodeGenOpt::None)
00364     AU.addRequired<BranchProbabilityInfo>();
00365   MachineFunctionPass::getAnalysisUsage(AU);
00366 }
00367 
00368 /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that
00369 /// may trap on it.  In this case we have to split the edge so that the path
00370 /// through the predecessor block that doesn't go to the phi block doesn't
00371 /// execute the possibly trapping instruction.
00372 ///
00373 /// This is required for correctness, so it must be done at -O0.
00374 ///
00375 static void SplitCriticalSideEffectEdges(Function &Fn, Pass *SDISel) {
00376   // Loop for blocks with phi nodes.
00377   for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
00378     PHINode *PN = dyn_cast<PHINode>(BB->begin());
00379     if (!PN) continue;
00380 
00381   ReprocessBlock:
00382     // For each block with a PHI node, check to see if any of the input values
00383     // are potentially trapping constant expressions.  Constant expressions are
00384     // the only potentially trapping value that can occur as the argument to a
00385     // PHI.
00386     for (BasicBlock::iterator I = BB->begin(); (PN = dyn_cast<PHINode>(I)); ++I)
00387       for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00388         ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i));
00389         if (!CE || !CE->canTrap()) continue;
00390 
00391         // The only case we have to worry about is when the edge is critical.
00392         // Since this block has a PHI Node, we assume it has multiple input
00393         // edges: check to see if the pred has multiple successors.
00394         BasicBlock *Pred = PN->getIncomingBlock(i);
00395         if (Pred->getTerminator()->getNumSuccessors() == 1)
00396           continue;
00397 
00398         // Okay, we have to split this edge.
00399         SplitCriticalEdge(Pred->getTerminator(),
00400                           GetSuccessorNumber(Pred, BB), SDISel, true);
00401         goto ReprocessBlock;
00402       }
00403   }
00404 }
00405 
00406 bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
00407   // Do some sanity-checking on the command-line options.
00408   assert((!EnableFastISelVerbose || TM.Options.EnableFastISel) &&
00409          "-fast-isel-verbose requires -fast-isel");
00410   assert((!EnableFastISelAbort || TM.Options.EnableFastISel) &&
00411          "-fast-isel-abort requires -fast-isel");
00412 
00413   const Function &Fn = *mf.getFunction();
00414   MF = &mf;
00415 
00416   // Reset the target options before resetting the optimization
00417   // level below.
00418   // FIXME: This is a horrible hack and should be processed via
00419   // codegen looking at the optimization level explicitly when
00420   // it wants to look at it.
00421   TM.resetTargetOptions(Fn);
00422   // Reset OptLevel to None for optnone functions.
00423   CodeGenOpt::Level NewOptLevel = OptLevel;
00424   if (Fn.hasFnAttribute(Attribute::OptimizeNone))
00425     NewOptLevel = CodeGenOpt::None;
00426   OptLevelChanger OLC(*this, NewOptLevel);
00427 
00428   TII = MF->getSubtarget().getInstrInfo();
00429   TLI = MF->getSubtarget().getTargetLowering();
00430   RegInfo = &MF->getRegInfo();
00431   AA = &getAnalysis<AliasAnalysis>();
00432   LibInfo = &getAnalysis<TargetLibraryInfo>();
00433   GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : nullptr;
00434 
00435   DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
00436 
00437   SplitCriticalSideEffectEdges(const_cast<Function&>(Fn), this);
00438 
00439   CurDAG->init(*MF);
00440   FuncInfo->set(Fn, *MF, CurDAG);
00441 
00442   if (UseMBPI && OptLevel != CodeGenOpt::None)
00443     FuncInfo->BPI = &getAnalysis<BranchProbabilityInfo>();
00444   else
00445     FuncInfo->BPI = nullptr;
00446 
00447   SDB->init(GFI, *AA, LibInfo);
00448 
00449   MF->setHasInlineAsm(false);
00450 
00451   SelectAllBasicBlocks(Fn);
00452 
00453   // If the first basic block in the function has live ins that need to be
00454   // copied into vregs, emit the copies into the top of the block before
00455   // emitting the code for the block.
00456   MachineBasicBlock *EntryMBB = MF->begin();
00457   const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
00458   RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
00459 
00460   DenseMap<unsigned, unsigned> LiveInMap;
00461   if (!FuncInfo->ArgDbgValues.empty())
00462     for (MachineRegisterInfo::livein_iterator LI = RegInfo->livein_begin(),
00463            E = RegInfo->livein_end(); LI != E; ++LI)
00464       if (LI->second)
00465         LiveInMap.insert(std::make_pair(LI->first, LI->second));
00466 
00467   // Insert DBG_VALUE instructions for function arguments to the entry block.
00468   for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
00469     MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1];
00470     bool hasFI = MI->getOperand(0).isFI();
00471     unsigned Reg =
00472         hasFI ? TRI.getFrameRegister(*MF) : MI->getOperand(0).getReg();
00473     if (TargetRegisterInfo::isPhysicalRegister(Reg))
00474       EntryMBB->insert(EntryMBB->begin(), MI);
00475     else {
00476       MachineInstr *Def = RegInfo->getVRegDef(Reg);
00477       if (Def) {
00478         MachineBasicBlock::iterator InsertPos = Def;
00479         // FIXME: VR def may not be in entry block.
00480         Def->getParent()->insert(std::next(InsertPos), MI);
00481       } else
00482         DEBUG(dbgs() << "Dropping debug info for dead vreg"
00483               << TargetRegisterInfo::virtReg2Index(Reg) << "\n");
00484     }
00485 
00486     // If Reg is live-in then update debug info to track its copy in a vreg.
00487     DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
00488     if (LDI != LiveInMap.end()) {
00489       assert(!hasFI && "There's no handling of frame pointer updating here yet "
00490                        "- add if needed");
00491       MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
00492       MachineBasicBlock::iterator InsertPos = Def;
00493       const MDNode *Variable = MI->getDebugVariable();
00494       const MDNode *Expr = MI->getDebugExpression();
00495       bool IsIndirect = MI->isIndirectDebugValue();
00496       unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
00497       // Def is never a terminator here, so it is ok to increment InsertPos.
00498       BuildMI(*EntryMBB, ++InsertPos, MI->getDebugLoc(),
00499               TII->get(TargetOpcode::DBG_VALUE), IsIndirect, LDI->second, Offset,
00500               Variable, Expr);
00501 
00502       // If this vreg is directly copied into an exported register then
00503       // that COPY instructions also need DBG_VALUE, if it is the only
00504       // user of LDI->second.
00505       MachineInstr *CopyUseMI = nullptr;
00506       for (MachineRegisterInfo::use_instr_iterator
00507            UI = RegInfo->use_instr_begin(LDI->second),
00508            E = RegInfo->use_instr_end(); UI != E; ) {
00509         MachineInstr *UseMI = &*(UI++);
00510         if (UseMI->isDebugValue()) continue;
00511         if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
00512           CopyUseMI = UseMI; continue;
00513         }
00514         // Otherwise this is another use or second copy use.
00515         CopyUseMI = nullptr; break;
00516       }
00517       if (CopyUseMI) {
00518         MachineInstr *NewMI =
00519             BuildMI(*MF, CopyUseMI->getDebugLoc(),
00520                     TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
00521                     CopyUseMI->getOperand(0).getReg(), Offset, Variable, Expr);
00522         MachineBasicBlock::iterator Pos = CopyUseMI;
00523         EntryMBB->insertAfter(Pos, NewMI);
00524       }
00525     }
00526   }
00527 
00528   // Determine if there are any calls in this machine function.
00529   MachineFrameInfo *MFI = MF->getFrameInfo();
00530   for (const auto &MBB : *MF) {
00531     if (MFI->hasCalls() && MF->hasInlineAsm())
00532       break;
00533 
00534     for (const auto &MI : MBB) {
00535       const MCInstrDesc &MCID = TII->get(MI.getOpcode());
00536       if ((MCID.isCall() && !MCID.isReturn()) ||
00537           MI.isStackAligningInlineAsm()) {
00538         MFI->setHasCalls(true);
00539       }
00540       if (MI.isInlineAsm()) {
00541         MF->setHasInlineAsm(true);
00542       }
00543     }
00544   }
00545 
00546   // Determine if there is a call to setjmp in the machine function.
00547   MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice());
00548 
00549   // Replace forward-declared registers with the registers containing
00550   // the desired value.
00551   MachineRegisterInfo &MRI = MF->getRegInfo();
00552   for (DenseMap<unsigned, unsigned>::iterator
00553        I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end();
00554        I != E; ++I) {
00555     unsigned From = I->first;
00556     unsigned To = I->second;
00557     // If To is also scheduled to be replaced, find what its ultimate
00558     // replacement is.
00559     for (;;) {
00560       DenseMap<unsigned, unsigned>::iterator J = FuncInfo->RegFixups.find(To);
00561       if (J == E) break;
00562       To = J->second;
00563     }
00564     // Make sure the new register has a sufficiently constrained register class.
00565     if (TargetRegisterInfo::isVirtualRegister(From) &&
00566         TargetRegisterInfo::isVirtualRegister(To))
00567       MRI.constrainRegClass(To, MRI.getRegClass(From));
00568     // Replace it.
00569     MRI.replaceRegWith(From, To);
00570   }
00571 
00572   // Freeze the set of reserved registers now that MachineFrameInfo has been
00573   // set up. All the information required by getReservedRegs() should be
00574   // available now.
00575   MRI.freezeReservedRegs(*MF);
00576 
00577   // Release function-specific state. SDB and CurDAG are already cleared
00578   // at this point.
00579   FuncInfo->clear();
00580 
00581   DEBUG(dbgs() << "*** MachineFunction at end of ISel ***\n");
00582   DEBUG(MF->print(dbgs()));
00583 
00584   return true;
00585 }
00586 
00587 void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
00588                                         BasicBlock::const_iterator End,
00589                                         bool &HadTailCall) {
00590   // Lower all of the non-terminator instructions. If a call is emitted
00591   // as a tail call, cease emitting nodes for this block. Terminators
00592   // are handled below.
00593   for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I)
00594     SDB->visit(*I);
00595 
00596   // Make sure the root of the DAG is up-to-date.
00597   CurDAG->setRoot(SDB->getControlRoot());
00598   HadTailCall = SDB->HasTailCall;
00599   SDB->clear();
00600 
00601   // Final step, emit the lowered DAG as machine code.
00602   CodeGenAndEmitDAG();
00603 }
00604 
00605 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
00606   SmallPtrSet<SDNode*, 128> VisitedNodes;
00607   SmallVector<SDNode*, 128> Worklist;
00608 
00609   Worklist.push_back(CurDAG->getRoot().getNode());
00610 
00611   APInt KnownZero;
00612   APInt KnownOne;
00613 
00614   do {
00615     SDNode *N = Worklist.pop_back_val();
00616 
00617     // If we've already seen this node, ignore it.
00618     if (!VisitedNodes.insert(N).second)
00619       continue;
00620 
00621     // Otherwise, add all chain operands to the worklist.
00622     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00623       if (N->getOperand(i).getValueType() == MVT::Other)
00624         Worklist.push_back(N->getOperand(i).getNode());
00625 
00626     // If this is a CopyToReg with a vreg dest, process it.
00627     if (N->getOpcode() != ISD::CopyToReg)
00628       continue;
00629 
00630     unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
00631     if (!TargetRegisterInfo::isVirtualRegister(DestReg))
00632       continue;
00633 
00634     // Ignore non-scalar or non-integer values.
00635     SDValue Src = N->getOperand(2);
00636     EVT SrcVT = Src.getValueType();
00637     if (!SrcVT.isInteger() || SrcVT.isVector())
00638       continue;
00639 
00640     unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
00641     CurDAG->computeKnownBits(Src, KnownZero, KnownOne);
00642     FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, KnownZero, KnownOne);
00643   } while (!Worklist.empty());
00644 }
00645 
00646 void SelectionDAGISel::CodeGenAndEmitDAG() {
00647   std::string GroupName;
00648   if (TimePassesIsEnabled)
00649     GroupName = "Instruction Selection and Scheduling";
00650   std::string BlockName;
00651   int BlockNumber = -1;
00652   (void)BlockNumber;
00653 #ifdef NDEBUG
00654   if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
00655       ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
00656       ViewSUnitDAGs)
00657 #endif
00658   {
00659     BlockNumber = FuncInfo->MBB->getNumber();
00660     BlockName = MF->getName().str() + ":" +
00661                 FuncInfo->MBB->getBasicBlock()->getName().str();
00662   }
00663   DEBUG(dbgs() << "Initial selection DAG: BB#" << BlockNumber
00664         << " '" << BlockName << "'\n"; CurDAG->dump());
00665 
00666   if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
00667 
00668   // Run the DAG combiner in pre-legalize mode.
00669   {
00670     NamedRegionTimer T("DAG Combining 1", GroupName, TimePassesIsEnabled);
00671     CurDAG->Combine(BeforeLegalizeTypes, *AA, OptLevel);
00672   }
00673 
00674   DEBUG(dbgs() << "Optimized lowered selection DAG: BB#" << BlockNumber
00675         << " '" << BlockName << "'\n"; CurDAG->dump());
00676 
00677   // Second step, hack on the DAG until it only uses operations and types that
00678   // the target supports.
00679   if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
00680                                                BlockName);
00681 
00682   bool Changed;
00683   {
00684     NamedRegionTimer T("Type Legalization", GroupName, TimePassesIsEnabled);
00685     Changed = CurDAG->LegalizeTypes();
00686   }
00687 
00688   DEBUG(dbgs() << "Type-legalized selection DAG: BB#" << BlockNumber
00689         << " '" << BlockName << "'\n"; CurDAG->dump());
00690 
00691   CurDAG->NewNodesMustHaveLegalTypes = true;
00692 
00693   if (Changed) {
00694     if (ViewDAGCombineLT)
00695       CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
00696 
00697     // Run the DAG combiner in post-type-legalize mode.
00698     {
00699       NamedRegionTimer T("DAG Combining after legalize types", GroupName,
00700                          TimePassesIsEnabled);
00701       CurDAG->Combine(AfterLegalizeTypes, *AA, OptLevel);
00702     }
00703 
00704     DEBUG(dbgs() << "Optimized type-legalized selection DAG: BB#" << BlockNumber
00705           << " '" << BlockName << "'\n"; CurDAG->dump());
00706 
00707   }
00708 
00709   {
00710     NamedRegionTimer T("Vector Legalization", GroupName, TimePassesIsEnabled);
00711     Changed = CurDAG->LegalizeVectors();
00712   }
00713 
00714   if (Changed) {
00715     {
00716       NamedRegionTimer T("Type Legalization 2", GroupName, TimePassesIsEnabled);
00717       CurDAG->LegalizeTypes();
00718     }
00719 
00720     if (ViewDAGCombineLT)
00721       CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
00722 
00723     // Run the DAG combiner in post-type-legalize mode.
00724     {
00725       NamedRegionTimer T("DAG Combining after legalize vectors", GroupName,
00726                          TimePassesIsEnabled);
00727       CurDAG->Combine(AfterLegalizeVectorOps, *AA, OptLevel);
00728     }
00729 
00730     DEBUG(dbgs() << "Optimized vector-legalized selection DAG: BB#"
00731           << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump());
00732   }
00733 
00734   if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
00735 
00736   {
00737     NamedRegionTimer T("DAG Legalization", GroupName, TimePassesIsEnabled);
00738     CurDAG->Legalize();
00739   }
00740 
00741   DEBUG(dbgs() << "Legalized selection DAG: BB#" << BlockNumber
00742         << " '" << BlockName << "'\n"; CurDAG->dump());
00743 
00744   if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
00745 
00746   // Run the DAG combiner in post-legalize mode.
00747   {
00748     NamedRegionTimer T("DAG Combining 2", GroupName, TimePassesIsEnabled);
00749     CurDAG->Combine(AfterLegalizeDAG, *AA, OptLevel);
00750   }
00751 
00752   DEBUG(dbgs() << "Optimized legalized selection DAG: BB#" << BlockNumber
00753         << " '" << BlockName << "'\n"; CurDAG->dump());
00754 
00755   if (OptLevel != CodeGenOpt::None)
00756     ComputeLiveOutVRegInfo();
00757 
00758   if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
00759 
00760   // Third, instruction select all of the operations to machine code, adding the
00761   // code to the MachineBasicBlock.
00762   {
00763     NamedRegionTimer T("Instruction Selection", GroupName, TimePassesIsEnabled);
00764     DoInstructionSelection();
00765   }
00766 
00767   DEBUG(dbgs() << "Selected selection DAG: BB#" << BlockNumber
00768         << " '" << BlockName << "'\n"; CurDAG->dump());
00769 
00770   if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
00771 
00772   // Schedule machine code.
00773   ScheduleDAGSDNodes *Scheduler = CreateScheduler();
00774   {
00775     NamedRegionTimer T("Instruction Scheduling", GroupName,
00776                        TimePassesIsEnabled);
00777     Scheduler->Run(CurDAG, FuncInfo->MBB);
00778   }
00779 
00780   if (ViewSUnitDAGs) Scheduler->viewGraph();
00781 
00782   // Emit machine code to BB.  This can change 'BB' to the last block being
00783   // inserted into.
00784   MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
00785   {
00786     NamedRegionTimer T("Instruction Creation", GroupName, TimePassesIsEnabled);
00787 
00788     // FuncInfo->InsertPt is passed by reference and set to the end of the
00789     // scheduled instructions.
00790     LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
00791   }
00792 
00793   // If the block was split, make sure we update any references that are used to
00794   // update PHI nodes later on.
00795   if (FirstMBB != LastMBB)
00796     SDB->UpdateSplitBlock(FirstMBB, LastMBB);
00797 
00798   // Free the scheduler state.
00799   {
00800     NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName,
00801                        TimePassesIsEnabled);
00802     delete Scheduler;
00803   }
00804 
00805   // Free the SelectionDAG state, now that we're finished with it.
00806   CurDAG->clear();
00807 }
00808 
00809 namespace {
00810 /// ISelUpdater - helper class to handle updates of the instruction selection
00811 /// graph.
00812 class ISelUpdater : public SelectionDAG::DAGUpdateListener {
00813   SelectionDAG::allnodes_iterator &ISelPosition;
00814 public:
00815   ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
00816     : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
00817 
00818   /// NodeDeleted - Handle nodes deleted from the graph. If the node being
00819   /// deleted is the current ISelPosition node, update ISelPosition.
00820   ///
00821   void NodeDeleted(SDNode *N, SDNode *E) override {
00822     if (ISelPosition == SelectionDAG::allnodes_iterator(N))
00823       ++ISelPosition;
00824   }
00825 };
00826 } // end anonymous namespace
00827 
00828 void SelectionDAGISel::DoInstructionSelection() {
00829   DEBUG(dbgs() << "===== Instruction selection begins: BB#"
00830         << FuncInfo->MBB->getNumber()
00831         << " '" << FuncInfo->MBB->getName() << "'\n");
00832 
00833   PreprocessISelDAG();
00834 
00835   // Select target instructions for the DAG.
00836   {
00837     // Number all nodes with a topological order and set DAGSize.
00838     DAGSize = CurDAG->AssignTopologicalOrder();
00839 
00840     // Create a dummy node (which is not added to allnodes), that adds
00841     // a reference to the root node, preventing it from being deleted,
00842     // and tracking any changes of the root.
00843     HandleSDNode Dummy(CurDAG->getRoot());
00844     SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode());
00845     ++ISelPosition;
00846 
00847     // Make sure that ISelPosition gets properly updated when nodes are deleted
00848     // in calls made from this function.
00849     ISelUpdater ISU(*CurDAG, ISelPosition);
00850 
00851     // The AllNodes list is now topological-sorted. Visit the
00852     // nodes by starting at the end of the list (the root of the
00853     // graph) and preceding back toward the beginning (the entry
00854     // node).
00855     while (ISelPosition != CurDAG->allnodes_begin()) {
00856       SDNode *Node = --ISelPosition;
00857       // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
00858       // but there are currently some corner cases that it misses. Also, this
00859       // makes it theoretically possible to disable the DAGCombiner.
00860       if (Node->use_empty())
00861         continue;
00862 
00863       SDNode *ResNode = Select(Node);
00864 
00865       // FIXME: This is pretty gross.  'Select' should be changed to not return
00866       // anything at all and this code should be nuked with a tactical strike.
00867 
00868       // If node should not be replaced, continue with the next one.
00869       if (ResNode == Node || Node->getOpcode() == ISD::DELETED_NODE)
00870         continue;
00871       // Replace node.
00872       if (ResNode) {
00873         ReplaceUses(Node, ResNode);
00874       }
00875 
00876       // If after the replacement this node is not used any more,
00877       // remove this dead node.
00878       if (Node->use_empty()) // Don't delete EntryToken, etc.
00879         CurDAG->RemoveDeadNode(Node);
00880     }
00881 
00882     CurDAG->setRoot(Dummy.getValue());
00883   }
00884 
00885   DEBUG(dbgs() << "===== Instruction selection ends:\n");
00886 
00887   PostprocessISelDAG();
00888 }
00889 
00890 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
00891 /// do other setup for EH landing-pad blocks.
00892 void SelectionDAGISel::PrepareEHLandingPad() {
00893   MachineBasicBlock *MBB = FuncInfo->MBB;
00894 
00895   // Add a label to mark the beginning of the landing pad.  Deletion of the
00896   // landing pad can thus be detected via the MachineModuleInfo.
00897   MCSymbol *Label = MF->getMMI().addLandingPad(MBB);
00898 
00899   // Assign the call site to the landing pad's begin label.
00900   MF->getMMI().setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
00901 
00902   const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL);
00903   BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
00904     .addSym(Label);
00905 
00906   // Mark exception register as live in.
00907   const TargetRegisterClass *PtrRC = TLI->getRegClassFor(TLI->getPointerTy());
00908   if (unsigned Reg = TLI->getExceptionPointerRegister())
00909     FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
00910 
00911   // Mark exception selector register as live in.
00912   if (unsigned Reg = TLI->getExceptionSelectorRegister())
00913     FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
00914 }
00915 
00916 /// isFoldedOrDeadInstruction - Return true if the specified instruction is
00917 /// side-effect free and is either dead or folded into a generated instruction.
00918 /// Return false if it needs to be emitted.
00919 static bool isFoldedOrDeadInstruction(const Instruction *I,
00920                                       FunctionLoweringInfo *FuncInfo) {
00921   return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
00922          !isa<TerminatorInst>(I) && // Terminators aren't folded.
00923          !isa<DbgInfoIntrinsic>(I) &&  // Debug instructions aren't folded.
00924          !isa<LandingPadInst>(I) &&    // Landingpad instructions aren't folded.
00925          !FuncInfo->isExportedInst(I); // Exported instrs must be computed.
00926 }
00927 
00928 #ifndef NDEBUG
00929 // Collect per Instruction statistics for fast-isel misses.  Only those
00930 // instructions that cause the bail are accounted for.  It does not account for
00931 // instructions higher in the block.  Thus, summing the per instructions stats
00932 // will not add up to what is reported by NumFastIselFailures.
00933 static void collectFailStats(const Instruction *I) {
00934   switch (I->getOpcode()) {
00935   default: assert (0 && "<Invalid operator> ");
00936 
00937   // Terminators
00938   case Instruction::Ret:         NumFastIselFailRet++; return;
00939   case Instruction::Br:          NumFastIselFailBr++; return;
00940   case Instruction::Switch:      NumFastIselFailSwitch++; return;
00941   case Instruction::IndirectBr:  NumFastIselFailIndirectBr++; return;
00942   case Instruction::Invoke:      NumFastIselFailInvoke++; return;
00943   case Instruction::Resume:      NumFastIselFailResume++; return;
00944   case Instruction::Unreachable: NumFastIselFailUnreachable++; return;
00945 
00946   // Standard binary operators...
00947   case Instruction::Add:  NumFastIselFailAdd++; return;
00948   case Instruction::FAdd: NumFastIselFailFAdd++; return;
00949   case Instruction::Sub:  NumFastIselFailSub++; return;
00950   case Instruction::FSub: NumFastIselFailFSub++; return;
00951   case Instruction::Mul:  NumFastIselFailMul++; return;
00952   case Instruction::FMul: NumFastIselFailFMul++; return;
00953   case Instruction::UDiv: NumFastIselFailUDiv++; return;
00954   case Instruction::SDiv: NumFastIselFailSDiv++; return;
00955   case Instruction::FDiv: NumFastIselFailFDiv++; return;
00956   case Instruction::URem: NumFastIselFailURem++; return;
00957   case Instruction::SRem: NumFastIselFailSRem++; return;
00958   case Instruction::FRem: NumFastIselFailFRem++; return;
00959 
00960   // Logical operators...
00961   case Instruction::And: NumFastIselFailAnd++; return;
00962   case Instruction::Or:  NumFastIselFailOr++; return;
00963   case Instruction::Xor: NumFastIselFailXor++; return;
00964 
00965   // Memory instructions...
00966   case Instruction::Alloca:        NumFastIselFailAlloca++; return;
00967   case Instruction::Load:          NumFastIselFailLoad++; return;
00968   case Instruction::Store:         NumFastIselFailStore++; return;
00969   case Instruction::AtomicCmpXchg: NumFastIselFailAtomicCmpXchg++; return;
00970   case Instruction::AtomicRMW:     NumFastIselFailAtomicRMW++; return;
00971   case Instruction::Fence:         NumFastIselFailFence++; return;
00972   case Instruction::GetElementPtr: NumFastIselFailGetElementPtr++; return;
00973 
00974   // Convert instructions...
00975   case Instruction::Trunc:    NumFastIselFailTrunc++; return;
00976   case Instruction::ZExt:     NumFastIselFailZExt++; return;
00977   case Instruction::SExt:     NumFastIselFailSExt++; return;
00978   case Instruction::FPTrunc:  NumFastIselFailFPTrunc++; return;
00979   case Instruction::FPExt:    NumFastIselFailFPExt++; return;
00980   case Instruction::FPToUI:   NumFastIselFailFPToUI++; return;
00981   case Instruction::FPToSI:   NumFastIselFailFPToSI++; return;
00982   case Instruction::UIToFP:   NumFastIselFailUIToFP++; return;
00983   case Instruction::SIToFP:   NumFastIselFailSIToFP++; return;
00984   case Instruction::IntToPtr: NumFastIselFailIntToPtr++; return;
00985   case Instruction::PtrToInt: NumFastIselFailPtrToInt++; return;
00986   case Instruction::BitCast:  NumFastIselFailBitCast++; return;
00987 
00988   // Other instructions...
00989   case Instruction::ICmp:           NumFastIselFailICmp++; return;
00990   case Instruction::FCmp:           NumFastIselFailFCmp++; return;
00991   case Instruction::PHI:            NumFastIselFailPHI++; return;
00992   case Instruction::Select:         NumFastIselFailSelect++; return;
00993   case Instruction::Call: {
00994     if (auto const *Intrinsic = dyn_cast<IntrinsicInst>(I)) {
00995       switch (Intrinsic->getIntrinsicID()) {
00996       default:
00997         NumFastIselFailIntrinsicCall++; return;
00998       case Intrinsic::sadd_with_overflow:
00999         NumFastIselFailSAddWithOverflow++; return;
01000       case Intrinsic::uadd_with_overflow:
01001         NumFastIselFailUAddWithOverflow++; return;
01002       case Intrinsic::ssub_with_overflow:
01003         NumFastIselFailSSubWithOverflow++; return;
01004       case Intrinsic::usub_with_overflow:
01005         NumFastIselFailUSubWithOverflow++; return;
01006       case Intrinsic::smul_with_overflow:
01007         NumFastIselFailSMulWithOverflow++; return;
01008       case Intrinsic::umul_with_overflow:
01009         NumFastIselFailUMulWithOverflow++; return;
01010       case Intrinsic::frameaddress:
01011         NumFastIselFailFrameaddress++; return;
01012       case Intrinsic::sqrt:
01013           NumFastIselFailSqrt++; return;
01014       case Intrinsic::experimental_stackmap:
01015         NumFastIselFailStackMap++; return;
01016       case Intrinsic::experimental_patchpoint_void: // fall-through
01017       case Intrinsic::experimental_patchpoint_i64:
01018         NumFastIselFailPatchPoint++; return;
01019       }
01020     }
01021     NumFastIselFailCall++;
01022     return;
01023   }
01024   case Instruction::Shl:            NumFastIselFailShl++; return;
01025   case Instruction::LShr:           NumFastIselFailLShr++; return;
01026   case Instruction::AShr:           NumFastIselFailAShr++; return;
01027   case Instruction::VAArg:          NumFastIselFailVAArg++; return;
01028   case Instruction::ExtractElement: NumFastIselFailExtractElement++; return;
01029   case Instruction::InsertElement:  NumFastIselFailInsertElement++; return;
01030   case Instruction::ShuffleVector:  NumFastIselFailShuffleVector++; return;
01031   case Instruction::ExtractValue:   NumFastIselFailExtractValue++; return;
01032   case Instruction::InsertValue:    NumFastIselFailInsertValue++; return;
01033   case Instruction::LandingPad:     NumFastIselFailLandingPad++; return;
01034   }
01035 }
01036 #endif
01037 
01038 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
01039   // Initialize the Fast-ISel state, if needed.
01040   FastISel *FastIS = nullptr;
01041   if (TM.Options.EnableFastISel)
01042     FastIS = TLI->createFastISel(*FuncInfo, LibInfo);
01043 
01044   // Iterate over all basic blocks in the function.
01045   ReversePostOrderTraversal<const Function*> RPOT(&Fn);
01046   for (ReversePostOrderTraversal<const Function*>::rpo_iterator
01047        I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
01048     const BasicBlock *LLVMBB = *I;
01049 
01050     if (OptLevel != CodeGenOpt::None) {
01051       bool AllPredsVisited = true;
01052       for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB);
01053            PI != PE; ++PI) {
01054         if (!FuncInfo->VisitedBBs.count(*PI)) {
01055           AllPredsVisited = false;
01056           break;
01057         }
01058       }
01059 
01060       if (AllPredsVisited) {
01061         for (BasicBlock::const_iterator I = LLVMBB->begin();
01062              const PHINode *PN = dyn_cast<PHINode>(I); ++I)
01063           FuncInfo->ComputePHILiveOutRegInfo(PN);
01064       } else {
01065         for (BasicBlock::const_iterator I = LLVMBB->begin();
01066              const PHINode *PN = dyn_cast<PHINode>(I); ++I)
01067           FuncInfo->InvalidatePHILiveOutRegInfo(PN);
01068       }
01069 
01070       FuncInfo->VisitedBBs.insert(LLVMBB);
01071     }
01072 
01073     BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHI();
01074     BasicBlock::const_iterator const End = LLVMBB->end();
01075     BasicBlock::const_iterator BI = End;
01076 
01077     FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
01078     FuncInfo->InsertPt = FuncInfo->MBB->getFirstNonPHI();
01079 
01080     // Setup an EH landing-pad block.
01081     FuncInfo->ExceptionPointerVirtReg = 0;
01082     FuncInfo->ExceptionSelectorVirtReg = 0;
01083     if (FuncInfo->MBB->isLandingPad())
01084       PrepareEHLandingPad();
01085 
01086     // Before doing SelectionDAG ISel, see if FastISel has been requested.
01087     if (FastIS) {
01088       FastIS->startNewBlock();
01089 
01090       // Emit code for any incoming arguments. This must happen before
01091       // beginning FastISel on the entry block.
01092       if (LLVMBB == &Fn.getEntryBlock()) {
01093         ++NumEntryBlocks;
01094 
01095         // Lower any arguments needed in this block if this is the entry block.
01096         if (!FastIS->lowerArguments()) {
01097           // Fast isel failed to lower these arguments
01098           ++NumFastIselFailLowerArguments;
01099           if (EnableFastISelAbortArgs)
01100             llvm_unreachable("FastISel didn't lower all arguments");
01101 
01102           // Use SelectionDAG argument lowering
01103           LowerArguments(Fn);
01104           CurDAG->setRoot(SDB->getControlRoot());
01105           SDB->clear();
01106           CodeGenAndEmitDAG();
01107         }
01108 
01109         // If we inserted any instructions at the beginning, make a note of
01110         // where they are, so we can be sure to emit subsequent instructions
01111         // after them.
01112         if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
01113           FastIS->setLastLocalValue(std::prev(FuncInfo->InsertPt));
01114         else
01115           FastIS->setLastLocalValue(nullptr);
01116       }
01117 
01118       unsigned NumFastIselRemaining = std::distance(Begin, End);
01119       // Do FastISel on as many instructions as possible.
01120       for (; BI != Begin; --BI) {
01121         const Instruction *Inst = std::prev(BI);
01122 
01123         // If we no longer require this instruction, skip it.
01124         if (isFoldedOrDeadInstruction(Inst, FuncInfo)) {
01125           --NumFastIselRemaining;
01126           continue;
01127         }
01128 
01129         // Bottom-up: reset the insert pos at the top, after any local-value
01130         // instructions.
01131         FastIS->recomputeInsertPt();
01132 
01133         // Try to select the instruction with FastISel.
01134         if (FastIS->selectInstruction(Inst)) {
01135           --NumFastIselRemaining;
01136           ++NumFastIselSuccess;
01137           // If fast isel succeeded, skip over all the folded instructions, and
01138           // then see if there is a load right before the selected instructions.
01139           // Try to fold the load if so.
01140           const Instruction *BeforeInst = Inst;
01141           while (BeforeInst != Begin) {
01142             BeforeInst = std::prev(BasicBlock::const_iterator(BeforeInst));
01143             if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo))
01144               break;
01145           }
01146           if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
01147               BeforeInst->hasOneUse() &&
01148               FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
01149             // If we succeeded, don't re-select the load.
01150             BI = std::next(BasicBlock::const_iterator(BeforeInst));
01151             --NumFastIselRemaining;
01152             ++NumFastIselSuccess;
01153           }
01154           continue;
01155         }
01156 
01157 #ifndef NDEBUG
01158         if (EnableFastISelVerbose2)
01159           collectFailStats(Inst);
01160 #endif
01161 
01162         // Then handle certain instructions as single-LLVM-Instruction blocks.
01163         if (isa<CallInst>(Inst)) {
01164 
01165           if (EnableFastISelVerbose || EnableFastISelAbort) {
01166             dbgs() << "FastISel missed call: ";
01167             Inst->dump();
01168           }
01169 
01170           if (!Inst->getType()->isVoidTy() && !Inst->use_empty()) {
01171             unsigned &R = FuncInfo->ValueMap[Inst];
01172             if (!R)
01173               R = FuncInfo->CreateRegs(Inst->getType());
01174           }
01175 
01176           bool HadTailCall = false;
01177           MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
01178           SelectBasicBlock(Inst, BI, HadTailCall);
01179 
01180           // If the call was emitted as a tail call, we're done with the block.
01181           // We also need to delete any previously emitted instructions.
01182           if (HadTailCall) {
01183             FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
01184             --BI;
01185             break;
01186           }
01187 
01188           // Recompute NumFastIselRemaining as Selection DAG instruction
01189           // selection may have handled the call, input args, etc.
01190           unsigned RemainingNow = std::distance(Begin, BI);
01191           NumFastIselFailures += NumFastIselRemaining - RemainingNow;
01192           NumFastIselRemaining = RemainingNow;
01193           continue;
01194         }
01195 
01196         if (isa<TerminatorInst>(Inst) && !isa<BranchInst>(Inst)) {
01197           // Don't abort, and use a different message for terminator misses.
01198           NumFastIselFailures += NumFastIselRemaining;
01199           if (EnableFastISelVerbose || EnableFastISelAbort) {
01200             dbgs() << "FastISel missed terminator: ";
01201             Inst->dump();
01202           }
01203         } else {
01204           NumFastIselFailures += NumFastIselRemaining;
01205           if (EnableFastISelVerbose || EnableFastISelAbort) {
01206             dbgs() << "FastISel miss: ";
01207             Inst->dump();
01208           }
01209           if (EnableFastISelAbort)
01210             // The "fast" selector couldn't handle something and bailed.
01211             // For the purpose of debugging, just abort.
01212             llvm_unreachable("FastISel didn't select the entire block");
01213         }
01214         break;
01215       }
01216 
01217       FastIS->recomputeInsertPt();
01218     } else {
01219       // Lower any arguments needed in this block if this is the entry block.
01220       if (LLVMBB == &Fn.getEntryBlock()) {
01221         ++NumEntryBlocks;
01222         LowerArguments(Fn);
01223       }
01224     }
01225 
01226     if (Begin != BI)
01227       ++NumDAGBlocks;
01228     else
01229       ++NumFastIselBlocks;
01230 
01231     if (Begin != BI) {
01232       // Run SelectionDAG instruction selection on the remainder of the block
01233       // not handled by FastISel. If FastISel is not run, this is the entire
01234       // block.
01235       bool HadTailCall;
01236       SelectBasicBlock(Begin, BI, HadTailCall);
01237     }
01238 
01239     FinishBasicBlock();
01240     FuncInfo->PHINodesToUpdate.clear();
01241   }
01242 
01243   delete FastIS;
01244   SDB->clearDanglingDebugInfo();
01245   SDB->SPDescriptor.resetPerFunctionState();
01246 }
01247 
01248 /// Given that the input MI is before a partial terminator sequence TSeq, return
01249 /// true if M + TSeq also a partial terminator sequence.
01250 ///
01251 /// A Terminator sequence is a sequence of MachineInstrs which at this point in
01252 /// lowering copy vregs into physical registers, which are then passed into
01253 /// terminator instructors so we can satisfy ABI constraints. A partial
01254 /// terminator sequence is an improper subset of a terminator sequence (i.e. it
01255 /// may be the whole terminator sequence).
01256 static bool MIIsInTerminatorSequence(const MachineInstr *MI) {
01257   // If we do not have a copy or an implicit def, we return true if and only if
01258   // MI is a debug value.
01259   if (!MI->isCopy() && !MI->isImplicitDef())
01260     // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the
01261     // physical registers if there is debug info associated with the terminator
01262     // of our mbb. We want to include said debug info in our terminator
01263     // sequence, so we return true in that case.
01264     return MI->isDebugValue();
01265 
01266   // We have left the terminator sequence if we are not doing one of the
01267   // following:
01268   //
01269   // 1. Copying a vreg into a physical register.
01270   // 2. Copying a vreg into a vreg.
01271   // 3. Defining a register via an implicit def.
01272 
01273   // OPI should always be a register definition...
01274   MachineInstr::const_mop_iterator OPI = MI->operands_begin();
01275   if (!OPI->isReg() || !OPI->isDef())
01276     return false;
01277 
01278   // Defining any register via an implicit def is always ok.
01279   if (MI->isImplicitDef())
01280     return true;
01281 
01282   // Grab the copy source...
01283   MachineInstr::const_mop_iterator OPI2 = OPI;
01284   ++OPI2;
01285   assert(OPI2 != MI->operands_end()
01286          && "Should have a copy implying we should have 2 arguments.");
01287 
01288   // Make sure that the copy dest is not a vreg when the copy source is a
01289   // physical register.
01290   if (!OPI2->isReg() ||
01291       (!TargetRegisterInfo::isPhysicalRegister(OPI->getReg()) &&
01292        TargetRegisterInfo::isPhysicalRegister(OPI2->getReg())))
01293     return false;
01294 
01295   return true;
01296 }
01297 
01298 /// Find the split point at which to splice the end of BB into its success stack
01299 /// protector check machine basic block.
01300 ///
01301 /// On many platforms, due to ABI constraints, terminators, even before register
01302 /// allocation, use physical registers. This creates an issue for us since
01303 /// physical registers at this point can not travel across basic
01304 /// blocks. Luckily, selectiondag always moves physical registers into vregs
01305 /// when they enter functions and moves them through a sequence of copies back
01306 /// into the physical registers right before the terminator creating a
01307 /// ``Terminator Sequence''. This function is searching for the beginning of the
01308 /// terminator sequence so that we can ensure that we splice off not just the
01309 /// terminator, but additionally the copies that move the vregs into the
01310 /// physical registers.
01311 static MachineBasicBlock::iterator
01312 FindSplitPointForStackProtector(MachineBasicBlock *BB, DebugLoc DL) {
01313   MachineBasicBlock::iterator SplitPoint = BB->getFirstTerminator();
01314   //
01315   if (SplitPoint == BB->begin())
01316     return SplitPoint;
01317 
01318   MachineBasicBlock::iterator Start = BB->begin();
01319   MachineBasicBlock::iterator Previous = SplitPoint;
01320   --Previous;
01321 
01322   while (MIIsInTerminatorSequence(Previous)) {
01323     SplitPoint = Previous;
01324     if (Previous == Start)
01325       break;
01326     --Previous;
01327   }
01328 
01329   return SplitPoint;
01330 }
01331 
01332 void
01333 SelectionDAGISel::FinishBasicBlock() {
01334 
01335   DEBUG(dbgs() << "Total amount of phi nodes to update: "
01336                << FuncInfo->PHINodesToUpdate.size() << "\n";
01337         for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i)
01338           dbgs() << "Node " << i << " : ("
01339                  << FuncInfo->PHINodesToUpdate[i].first
01340                  << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
01341 
01342   const bool MustUpdatePHINodes = SDB->SwitchCases.empty() &&
01343                                   SDB->JTCases.empty() &&
01344                                   SDB->BitTestCases.empty();
01345 
01346   // Next, now that we know what the last MBB the LLVM BB expanded is, update
01347   // PHI nodes in successors.
01348   if (MustUpdatePHINodes) {
01349     for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
01350       MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
01351       assert(PHI->isPHI() &&
01352              "This is not a machine PHI node that we are updating!");
01353       if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
01354         continue;
01355       PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
01356     }
01357   }
01358 
01359   // Handle stack protector.
01360   if (SDB->SPDescriptor.shouldEmitStackProtector()) {
01361     MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
01362     MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB();
01363 
01364     // Find the split point to split the parent mbb. At the same time copy all
01365     // physical registers used in the tail of parent mbb into virtual registers
01366     // before the split point and back into physical registers after the split
01367     // point. This prevents us needing to deal with Live-ins and many other
01368     // register allocation issues caused by us splitting the parent mbb. The
01369     // register allocator will clean up said virtual copies later on.
01370     MachineBasicBlock::iterator SplitPoint =
01371       FindSplitPointForStackProtector(ParentMBB, SDB->getCurDebugLoc());
01372 
01373     // Splice the terminator of ParentMBB into SuccessMBB.
01374     SuccessMBB->splice(SuccessMBB->end(), ParentMBB,
01375                        SplitPoint,
01376                        ParentMBB->end());
01377 
01378     // Add compare/jump on neq/jump to the parent BB.
01379     FuncInfo->MBB = ParentMBB;
01380     FuncInfo->InsertPt = ParentMBB->end();
01381     SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
01382     CurDAG->setRoot(SDB->getRoot());
01383     SDB->clear();
01384     CodeGenAndEmitDAG();
01385 
01386     // CodeGen Failure MBB if we have not codegened it yet.
01387     MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB();
01388     if (!FailureMBB->size()) {
01389       FuncInfo->MBB = FailureMBB;
01390       FuncInfo->InsertPt = FailureMBB->end();
01391       SDB->visitSPDescriptorFailure(SDB->SPDescriptor);
01392       CurDAG->setRoot(SDB->getRoot());
01393       SDB->clear();
01394       CodeGenAndEmitDAG();
01395     }
01396 
01397     // Clear the Per-BB State.
01398     SDB->SPDescriptor.resetPerBBState();
01399   }
01400 
01401   // If we updated PHI Nodes, return early.
01402   if (MustUpdatePHINodes)
01403     return;
01404 
01405   for (unsigned i = 0, e = SDB->BitTestCases.size(); i != e; ++i) {
01406     // Lower header first, if it wasn't already lowered
01407     if (!SDB->BitTestCases[i].Emitted) {
01408       // Set the current basic block to the mbb we wish to insert the code into
01409       FuncInfo->MBB = SDB->BitTestCases[i].Parent;
01410       FuncInfo->InsertPt = FuncInfo->MBB->end();
01411       // Emit the code
01412       SDB->visitBitTestHeader(SDB->BitTestCases[i], FuncInfo->MBB);
01413       CurDAG->setRoot(SDB->getRoot());
01414       SDB->clear();
01415       CodeGenAndEmitDAG();
01416     }
01417 
01418     uint32_t UnhandledWeight = 0;
01419     for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j)
01420       UnhandledWeight += SDB->BitTestCases[i].Cases[j].ExtraWeight;
01421 
01422     for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j) {
01423       UnhandledWeight -= SDB->BitTestCases[i].Cases[j].ExtraWeight;
01424       // Set the current basic block to the mbb we wish to insert the code into
01425       FuncInfo->MBB = SDB->BitTestCases[i].Cases[j].ThisBB;
01426       FuncInfo->InsertPt = FuncInfo->MBB->end();
01427       // Emit the code
01428       if (j+1 != ej)
01429         SDB->visitBitTestCase(SDB->BitTestCases[i],
01430                               SDB->BitTestCases[i].Cases[j+1].ThisBB,
01431                               UnhandledWeight,
01432                               SDB->BitTestCases[i].Reg,
01433                               SDB->BitTestCases[i].Cases[j],
01434                               FuncInfo->MBB);
01435       else
01436         SDB->visitBitTestCase(SDB->BitTestCases[i],
01437                               SDB->BitTestCases[i].Default,
01438                               UnhandledWeight,
01439                               SDB->BitTestCases[i].Reg,
01440                               SDB->BitTestCases[i].Cases[j],
01441                               FuncInfo->MBB);
01442 
01443 
01444       CurDAG->setRoot(SDB->getRoot());
01445       SDB->clear();
01446       CodeGenAndEmitDAG();
01447     }
01448 
01449     // Update PHI Nodes
01450     for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
01451          pi != pe; ++pi) {
01452       MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
01453       MachineBasicBlock *PHIBB = PHI->getParent();
01454       assert(PHI->isPHI() &&
01455              "This is not a machine PHI node that we are updating!");
01456       // This is "default" BB. We have two jumps to it. From "header" BB and
01457       // from last "case" BB.
01458       if (PHIBB == SDB->BitTestCases[i].Default)
01459         PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
01460            .addMBB(SDB->BitTestCases[i].Parent)
01461            .addReg(FuncInfo->PHINodesToUpdate[pi].second)
01462            .addMBB(SDB->BitTestCases[i].Cases.back().ThisBB);
01463       // One of "cases" BB.
01464       for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size();
01465            j != ej; ++j) {
01466         MachineBasicBlock* cBB = SDB->BitTestCases[i].Cases[j].ThisBB;
01467         if (cBB->isSuccessor(PHIBB))
01468           PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB);
01469       }
01470     }
01471   }
01472   SDB->BitTestCases.clear();
01473 
01474   // If the JumpTable record is filled in, then we need to emit a jump table.
01475   // Updating the PHI nodes is tricky in this case, since we need to determine
01476   // whether the PHI is a successor of the range check MBB or the jump table MBB
01477   for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
01478     // Lower header first, if it wasn't already lowered
01479     if (!SDB->JTCases[i].first.Emitted) {
01480       // Set the current basic block to the mbb we wish to insert the code into
01481       FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB;
01482       FuncInfo->InsertPt = FuncInfo->MBB->end();
01483       // Emit the code
01484       SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first,
01485                                 FuncInfo->MBB);
01486       CurDAG->setRoot(SDB->getRoot());
01487       SDB->clear();
01488       CodeGenAndEmitDAG();
01489     }
01490 
01491     // Set the current basic block to the mbb we wish to insert the code into
01492     FuncInfo->MBB = SDB->JTCases[i].second.MBB;
01493     FuncInfo->InsertPt = FuncInfo->MBB->end();
01494     // Emit the code
01495     SDB->visitJumpTable(SDB->JTCases[i].second);
01496     CurDAG->setRoot(SDB->getRoot());
01497     SDB->clear();
01498     CodeGenAndEmitDAG();
01499 
01500     // Update PHI Nodes
01501     for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
01502          pi != pe; ++pi) {
01503       MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
01504       MachineBasicBlock *PHIBB = PHI->getParent();
01505       assert(PHI->isPHI() &&
01506              "This is not a machine PHI node that we are updating!");
01507       // "default" BB. We can go there only from header BB.
01508       if (PHIBB == SDB->JTCases[i].second.Default)
01509         PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
01510            .addMBB(SDB->JTCases[i].first.HeaderBB);
01511       // JT BB. Just iterate over successors here
01512       if (FuncInfo->MBB->isSuccessor(PHIBB))
01513         PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
01514     }
01515   }
01516   SDB->JTCases.clear();
01517 
01518   // If the switch block involved a branch to one of the actual successors, we
01519   // need to update PHI nodes in that block.
01520   for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
01521     MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
01522     assert(PHI->isPHI() &&
01523            "This is not a machine PHI node that we are updating!");
01524     if (FuncInfo->MBB->isSuccessor(PHI->getParent()))
01525       PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
01526   }
01527 
01528   // If we generated any switch lowering information, build and codegen any
01529   // additional DAGs necessary.
01530   for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
01531     // Set the current basic block to the mbb we wish to insert the code into
01532     FuncInfo->MBB = SDB->SwitchCases[i].ThisBB;
01533     FuncInfo->InsertPt = FuncInfo->MBB->end();
01534 
01535     // Determine the unique successors.
01536     SmallVector<MachineBasicBlock *, 2> Succs;
01537     Succs.push_back(SDB->SwitchCases[i].TrueBB);
01538     if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB)
01539       Succs.push_back(SDB->SwitchCases[i].FalseBB);
01540 
01541     // Emit the code. Note that this could result in FuncInfo->MBB being split.
01542     SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB);
01543     CurDAG->setRoot(SDB->getRoot());
01544     SDB->clear();
01545     CodeGenAndEmitDAG();
01546 
01547     // Remember the last block, now that any splitting is done, for use in
01548     // populating PHI nodes in successors.
01549     MachineBasicBlock *ThisBB = FuncInfo->MBB;
01550 
01551     // Handle any PHI nodes in successors of this chunk, as if we were coming
01552     // from the original BB before switch expansion.  Note that PHI nodes can
01553     // occur multiple times in PHINodesToUpdate.  We have to be very careful to
01554     // handle them the right number of times.
01555     for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
01556       FuncInfo->MBB = Succs[i];
01557       FuncInfo->InsertPt = FuncInfo->MBB->end();
01558       // FuncInfo->MBB may have been removed from the CFG if a branch was
01559       // constant folded.
01560       if (ThisBB->isSuccessor(FuncInfo->MBB)) {
01561         for (MachineBasicBlock::iterator
01562              MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
01563              MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
01564           MachineInstrBuilder PHI(*MF, MBBI);
01565           // This value for this PHI node is recorded in PHINodesToUpdate.
01566           for (unsigned pn = 0; ; ++pn) {
01567             assert(pn != FuncInfo->PHINodesToUpdate.size() &&
01568                    "Didn't find PHI entry!");
01569             if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
01570               PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
01571               break;
01572             }
01573           }
01574         }
01575       }
01576     }
01577   }
01578   SDB->SwitchCases.clear();
01579 }
01580 
01581 
01582 /// Create the scheduler. If a specific scheduler was specified
01583 /// via the SchedulerRegistry, use it, otherwise select the
01584 /// one preferred by the target.
01585 ///
01586 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
01587   RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
01588 
01589   if (!Ctor) {
01590     Ctor = ISHeuristic;
01591     RegisterScheduler::setDefault(Ctor);
01592   }
01593 
01594   return Ctor(this, OptLevel);
01595 }
01596 
01597 //===----------------------------------------------------------------------===//
01598 // Helper functions used by the generated instruction selector.
01599 //===----------------------------------------------------------------------===//
01600 // Calls to these methods are generated by tblgen.
01601 
01602 /// CheckAndMask - The isel is trying to match something like (and X, 255).  If
01603 /// the dag combiner simplified the 255, we still want to match.  RHS is the
01604 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
01605 /// specified in the .td file (e.g. 255).
01606 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
01607                                     int64_t DesiredMaskS) const {
01608   const APInt &ActualMask = RHS->getAPIntValue();
01609   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
01610 
01611   // If the actual mask exactly matches, success!
01612   if (ActualMask == DesiredMask)
01613     return true;
01614 
01615   // If the actual AND mask is allowing unallowed bits, this doesn't match.
01616   if (ActualMask.intersects(~DesiredMask))
01617     return false;
01618 
01619   // Otherwise, the DAG Combiner may have proven that the value coming in is
01620   // either already zero or is not demanded.  Check for known zero input bits.
01621   APInt NeededMask = DesiredMask & ~ActualMask;
01622   if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
01623     return true;
01624 
01625   // TODO: check to see if missing bits are just not demanded.
01626 
01627   // Otherwise, this pattern doesn't match.
01628   return false;
01629 }
01630 
01631 /// CheckOrMask - The isel is trying to match something like (or X, 255).  If
01632 /// the dag combiner simplified the 255, we still want to match.  RHS is the
01633 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
01634 /// specified in the .td file (e.g. 255).
01635 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
01636                                    int64_t DesiredMaskS) const {
01637   const APInt &ActualMask = RHS->getAPIntValue();
01638   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
01639 
01640   // If the actual mask exactly matches, success!
01641   if (ActualMask == DesiredMask)
01642     return true;
01643 
01644   // If the actual AND mask is allowing unallowed bits, this doesn't match.
01645   if (ActualMask.intersects(~DesiredMask))
01646     return false;
01647 
01648   // Otherwise, the DAG Combiner may have proven that the value coming in is
01649   // either already zero or is not demanded.  Check for known zero input bits.
01650   APInt NeededMask = DesiredMask & ~ActualMask;
01651 
01652   APInt KnownZero, KnownOne;
01653   CurDAG->computeKnownBits(LHS, KnownZero, KnownOne);
01654 
01655   // If all the missing bits in the or are already known to be set, match!
01656   if ((NeededMask & KnownOne) == NeededMask)
01657     return true;
01658 
01659   // TODO: check to see if missing bits are just not demanded.
01660 
01661   // Otherwise, this pattern doesn't match.
01662   return false;
01663 }
01664 
01665 
01666 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
01667 /// by tblgen.  Others should not call it.
01668 void SelectionDAGISel::
01669 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
01670   std::vector<SDValue> InOps;
01671   std::swap(InOps, Ops);
01672 
01673   Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
01674   Ops.push_back(InOps[InlineAsm::Op_AsmString]);  // 1
01675   Ops.push_back(InOps[InlineAsm::Op_MDNode]);     // 2, !srcloc
01676   Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]);  // 3 (SideEffect, AlignStack)
01677 
01678   unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
01679   if (InOps[e-1].getValueType() == MVT::Glue)
01680     --e;  // Don't process a glue operand if it is here.
01681 
01682   while (i != e) {
01683     unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
01684     if (!InlineAsm::isMemKind(Flags)) {
01685       // Just skip over this operand, copying the operands verbatim.
01686       Ops.insert(Ops.end(), InOps.begin()+i,
01687                  InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
01688       i += InlineAsm::getNumOperandRegisters(Flags) + 1;
01689     } else {
01690       assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
01691              "Memory operand with multiple values?");
01692       // Otherwise, this is a memory operand.  Ask the target to select it.
01693       std::vector<SDValue> SelOps;
01694       if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps))
01695         report_fatal_error("Could not match memory address.  Inline asm"
01696                            " failure!");
01697 
01698       // Add this to the output node.
01699       unsigned NewFlags =
01700         InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
01701       Ops.push_back(CurDAG->getTargetConstant(NewFlags, MVT::i32));
01702       Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
01703       i += 2;
01704     }
01705   }
01706 
01707   // Add the glue input back if present.
01708   if (e != InOps.size())
01709     Ops.push_back(InOps.back());
01710 }
01711 
01712 /// findGlueUse - Return use of MVT::Glue value produced by the specified
01713 /// SDNode.
01714 ///
01715 static SDNode *findGlueUse(SDNode *N) {
01716   unsigned FlagResNo = N->getNumValues()-1;
01717   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
01718     SDUse &Use = I.getUse();
01719     if (Use.getResNo() == FlagResNo)
01720       return Use.getUser();
01721   }
01722   return nullptr;
01723 }
01724 
01725 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
01726 /// This function recursively traverses up the operand chain, ignoring
01727 /// certain nodes.
01728 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
01729                           SDNode *Root, SmallPtrSetImpl<SDNode*> &Visited,
01730                           bool IgnoreChains) {
01731   // The NodeID's are given uniques ID's where a node ID is guaranteed to be
01732   // greater than all of its (recursive) operands.  If we scan to a point where
01733   // 'use' is smaller than the node we're scanning for, then we know we will
01734   // never find it.
01735   //
01736   // The Use may be -1 (unassigned) if it is a newly allocated node.  This can
01737   // happen because we scan down to newly selected nodes in the case of glue
01738   // uses.
01739   if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1))
01740     return false;
01741 
01742   // Don't revisit nodes if we already scanned it and didn't fail, we know we
01743   // won't fail if we scan it again.
01744   if (!Visited.insert(Use).second)
01745     return false;
01746 
01747   for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
01748     // Ignore chain uses, they are validated by HandleMergeInputChains.
01749     if (Use->getOperand(i).getValueType() == MVT::Other && IgnoreChains)
01750       continue;
01751 
01752     SDNode *N = Use->getOperand(i).getNode();
01753     if (N == Def) {
01754       if (Use == ImmedUse || Use == Root)
01755         continue;  // We are not looking for immediate use.
01756       assert(N != Root);
01757       return true;
01758     }
01759 
01760     // Traverse up the operand chain.
01761     if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains))
01762       return true;
01763   }
01764   return false;
01765 }
01766 
01767 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
01768 /// operand node N of U during instruction selection that starts at Root.
01769 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
01770                                           SDNode *Root) const {
01771   if (OptLevel == CodeGenOpt::None) return false;
01772   return N.hasOneUse();
01773 }
01774 
01775 /// IsLegalToFold - Returns true if the specific operand node N of
01776 /// U can be folded during instruction selection that starts at Root.
01777 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
01778                                      CodeGenOpt::Level OptLevel,
01779                                      bool IgnoreChains) {
01780   if (OptLevel == CodeGenOpt::None) return false;
01781 
01782   // If Root use can somehow reach N through a path that that doesn't contain
01783   // U then folding N would create a cycle. e.g. In the following
01784   // diagram, Root can reach N through X. If N is folded into into Root, then
01785   // X is both a predecessor and a successor of U.
01786   //
01787   //          [N*]           //
01788   //         ^   ^           //
01789   //        /     \          //
01790   //      [U*]    [X]?       //
01791   //        ^     ^          //
01792   //         \   /           //
01793   //          \ /            //
01794   //         [Root*]         //
01795   //
01796   // * indicates nodes to be folded together.
01797   //
01798   // If Root produces glue, then it gets (even more) interesting. Since it
01799   // will be "glued" together with its glue use in the scheduler, we need to
01800   // check if it might reach N.
01801   //
01802   //          [N*]           //
01803   //         ^   ^           //
01804   //        /     \          //
01805   //      [U*]    [X]?       //
01806   //        ^       ^        //
01807   //         \       \       //
01808   //          \      |       //
01809   //         [Root*] |       //
01810   //          ^      |       //
01811   //          f      |       //
01812   //          |      /       //
01813   //         [Y]    /        //
01814   //           ^   /         //
01815   //           f  /          //
01816   //           | /           //
01817   //          [GU]           //
01818   //
01819   // If GU (glue use) indirectly reaches N (the load), and Root folds N
01820   // (call it Fold), then X is a predecessor of GU and a successor of
01821   // Fold. But since Fold and GU are glued together, this will create
01822   // a cycle in the scheduling graph.
01823 
01824   // If the node has glue, walk down the graph to the "lowest" node in the
01825   // glueged set.
01826   EVT VT = Root->getValueType(Root->getNumValues()-1);
01827   while (VT == MVT::Glue) {
01828     SDNode *GU = findGlueUse(Root);
01829     if (!GU)
01830       break;
01831     Root = GU;
01832     VT = Root->getValueType(Root->getNumValues()-1);
01833 
01834     // If our query node has a glue result with a use, we've walked up it.  If
01835     // the user (which has already been selected) has a chain or indirectly uses
01836     // the chain, our WalkChainUsers predicate will not consider it.  Because of
01837     // this, we cannot ignore chains in this predicate.
01838     IgnoreChains = false;
01839   }
01840 
01841 
01842   SmallPtrSet<SDNode*, 16> Visited;
01843   return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
01844 }
01845 
01846 SDNode *SelectionDAGISel::Select_INLINEASM(SDNode *N) {
01847   std::vector<SDValue> Ops(N->op_begin(), N->op_end());
01848   SelectInlineAsmMemoryOperands(Ops);
01849 
01850   EVT VTs[] = { MVT::Other, MVT::Glue };
01851   SDValue New = CurDAG->getNode(ISD::INLINEASM, SDLoc(N), VTs, Ops);
01852   New->setNodeId(-1);
01853   return New.getNode();
01854 }
01855 
01856 SDNode
01857 *SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) {
01858   SDLoc dl(Op);
01859   MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(0));
01860   const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0));
01861   unsigned Reg =
01862       TLI->getRegisterByName(RegStr->getString().data(), Op->getValueType(0));
01863   SDValue New = CurDAG->getCopyFromReg(
01864                         CurDAG->getEntryNode(), dl, Reg, Op->getValueType(0));
01865   New->setNodeId(-1);
01866   return New.getNode();
01867 }
01868 
01869 SDNode
01870 *SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) {
01871   SDLoc dl(Op);
01872   MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1));
01873   const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0));
01874   unsigned Reg = TLI->getRegisterByName(RegStr->getString().data(),
01875                                         Op->getOperand(2).getValueType());
01876   SDValue New = CurDAG->getCopyToReg(
01877                         CurDAG->getEntryNode(), dl, Reg, Op->getOperand(2));
01878   New->setNodeId(-1);
01879   return New.getNode();
01880 }
01881 
01882 
01883 
01884 SDNode *SelectionDAGISel::Select_UNDEF(SDNode *N) {
01885   return CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF,N->getValueType(0));
01886 }
01887 
01888 /// GetVBR - decode a vbr encoding whose top bit is set.
01889 LLVM_ATTRIBUTE_ALWAYS_INLINE static uint64_t
01890 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
01891   assert(Val >= 128 && "Not a VBR");
01892   Val &= 127;  // Remove first vbr bit.
01893 
01894   unsigned Shift = 7;
01895   uint64_t NextBits;
01896   do {
01897     NextBits = MatcherTable[Idx++];
01898     Val |= (NextBits&127) << Shift;
01899     Shift += 7;
01900   } while (NextBits & 128);
01901 
01902   return Val;
01903 }
01904 
01905 
01906 /// UpdateChainsAndGlue - When a match is complete, this method updates uses of
01907 /// interior glue and chain results to use the new glue and chain results.
01908 void SelectionDAGISel::
01909 UpdateChainsAndGlue(SDNode *NodeToMatch, SDValue InputChain,
01910                     const SmallVectorImpl<SDNode*> &ChainNodesMatched,
01911                     SDValue InputGlue,
01912                     const SmallVectorImpl<SDNode*> &GlueResultNodesMatched,
01913                     bool isMorphNodeTo) {
01914   SmallVector<SDNode*, 4> NowDeadNodes;
01915 
01916   // Now that all the normal results are replaced, we replace the chain and
01917   // glue results if present.
01918   if (!ChainNodesMatched.empty()) {
01919     assert(InputChain.getNode() &&
01920            "Matched input chains but didn't produce a chain");
01921     // Loop over all of the nodes we matched that produced a chain result.
01922     // Replace all the chain results with the final chain we ended up with.
01923     for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
01924       SDNode *ChainNode = ChainNodesMatched[i];
01925 
01926       // If this node was already deleted, don't look at it.
01927       if (ChainNode->getOpcode() == ISD::DELETED_NODE)
01928         continue;
01929 
01930       // Don't replace the results of the root node if we're doing a
01931       // MorphNodeTo.
01932       if (ChainNode == NodeToMatch && isMorphNodeTo)
01933         continue;
01934 
01935       SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
01936       if (ChainVal.getValueType() == MVT::Glue)
01937         ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
01938       assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
01939       CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain);
01940 
01941       // If the node became dead and we haven't already seen it, delete it.
01942       if (ChainNode->use_empty() &&
01943           !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
01944         NowDeadNodes.push_back(ChainNode);
01945     }
01946   }
01947 
01948   // If the result produces glue, update any glue results in the matched
01949   // pattern with the glue result.
01950   if (InputGlue.getNode()) {
01951     // Handle any interior nodes explicitly marked.
01952     for (unsigned i = 0, e = GlueResultNodesMatched.size(); i != e; ++i) {
01953       SDNode *FRN = GlueResultNodesMatched[i];
01954 
01955       // If this node was already deleted, don't look at it.
01956       if (FRN->getOpcode() == ISD::DELETED_NODE)
01957         continue;
01958 
01959       assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Glue &&
01960              "Doesn't have a glue result");
01961       CurDAG->ReplaceAllUsesOfValueWith(SDValue(FRN, FRN->getNumValues()-1),
01962                                         InputGlue);
01963 
01964       // If the node became dead and we haven't already seen it, delete it.
01965       if (FRN->use_empty() &&
01966           !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), FRN))
01967         NowDeadNodes.push_back(FRN);
01968     }
01969   }
01970 
01971   if (!NowDeadNodes.empty())
01972     CurDAG->RemoveDeadNodes(NowDeadNodes);
01973 
01974   DEBUG(dbgs() << "ISEL: Match complete!\n");
01975 }
01976 
01977 enum ChainResult {
01978   CR_Simple,
01979   CR_InducesCycle,
01980   CR_LeadsToInteriorNode
01981 };
01982 
01983 /// WalkChainUsers - Walk down the users of the specified chained node that is
01984 /// part of the pattern we're matching, looking at all of the users we find.
01985 /// This determines whether something is an interior node, whether we have a
01986 /// non-pattern node in between two pattern nodes (which prevent folding because
01987 /// it would induce a cycle) and whether we have a TokenFactor node sandwiched
01988 /// between pattern nodes (in which case the TF becomes part of the pattern).
01989 ///
01990 /// The walk we do here is guaranteed to be small because we quickly get down to
01991 /// already selected nodes "below" us.
01992 static ChainResult
01993 WalkChainUsers(const SDNode *ChainedNode,
01994                SmallVectorImpl<SDNode*> &ChainedNodesInPattern,
01995                SmallVectorImpl<SDNode*> &InteriorChainedNodes) {
01996   ChainResult Result = CR_Simple;
01997 
01998   for (SDNode::use_iterator UI = ChainedNode->use_begin(),
01999          E = ChainedNode->use_end(); UI != E; ++UI) {
02000     // Make sure the use is of the chain, not some other value we produce.
02001     if (UI.getUse().getValueType() != MVT::Other) continue;
02002 
02003     SDNode *User = *UI;
02004 
02005     if (User->getOpcode() == ISD::HANDLENODE)  // Root of the graph.
02006       continue;
02007 
02008     // If we see an already-selected machine node, then we've gone beyond the
02009     // pattern that we're selecting down into the already selected chunk of the
02010     // DAG.
02011     unsigned UserOpcode = User->getOpcode();
02012     if (User->isMachineOpcode() ||
02013         UserOpcode == ISD::CopyToReg ||
02014         UserOpcode == ISD::CopyFromReg ||
02015         UserOpcode == ISD::INLINEASM ||
02016         UserOpcode == ISD::EH_LABEL ||
02017         UserOpcode == ISD::LIFETIME_START ||
02018         UserOpcode == ISD::LIFETIME_END) {
02019       // If their node ID got reset to -1 then they've already been selected.
02020       // Treat them like a MachineOpcode.
02021       if (User->getNodeId() == -1)
02022         continue;
02023     }
02024 
02025     // If we have a TokenFactor, we handle it specially.
02026     if (User->getOpcode() != ISD::TokenFactor) {
02027       // If the node isn't a token factor and isn't part of our pattern, then it
02028       // must be a random chained node in between two nodes we're selecting.
02029       // This happens when we have something like:
02030       //   x = load ptr
02031       //   call
02032       //   y = x+4
02033       //   store y -> ptr
02034       // Because we structurally match the load/store as a read/modify/write,
02035       // but the call is chained between them.  We cannot fold in this case
02036       // because it would induce a cycle in the graph.
02037       if (!std::count(ChainedNodesInPattern.begin(),
02038                       ChainedNodesInPattern.end(), User))
02039         return CR_InducesCycle;
02040 
02041       // Otherwise we found a node that is part of our pattern.  For example in:
02042       //   x = load ptr
02043       //   y = x+4
02044       //   store y -> ptr
02045       // This would happen when we're scanning down from the load and see the
02046       // store as a user.  Record that there is a use of ChainedNode that is
02047       // part of the pattern and keep scanning uses.
02048       Result = CR_LeadsToInteriorNode;
02049       InteriorChainedNodes.push_back(User);
02050       continue;
02051     }
02052 
02053     // If we found a TokenFactor, there are two cases to consider: first if the
02054     // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
02055     // uses of the TF are in our pattern) we just want to ignore it.  Second,
02056     // the TokenFactor can be sandwiched in between two chained nodes, like so:
02057     //     [Load chain]
02058     //         ^
02059     //         |
02060     //       [Load]
02061     //       ^    ^
02062     //       |    \                    DAG's like cheese
02063     //      /       \                       do you?
02064     //     /         |
02065     // [TokenFactor] [Op]
02066     //     ^          ^
02067     //     |          |
02068     //      \        /
02069     //       \      /
02070     //       [Store]
02071     //
02072     // In this case, the TokenFactor becomes part of our match and we rewrite it
02073     // as a new TokenFactor.
02074     //
02075     // To distinguish these two cases, do a recursive walk down the uses.
02076     switch (WalkChainUsers(User, ChainedNodesInPattern, InteriorChainedNodes)) {
02077     case CR_Simple:
02078       // If the uses of the TokenFactor are just already-selected nodes, ignore
02079       // it, it is "below" our pattern.
02080       continue;
02081     case CR_InducesCycle:
02082       // If the uses of the TokenFactor lead to nodes that are not part of our
02083       // pattern that are not selected, folding would turn this into a cycle,
02084       // bail out now.
02085       return CR_InducesCycle;
02086     case CR_LeadsToInteriorNode:
02087       break;  // Otherwise, keep processing.
02088     }
02089 
02090     // Okay, we know we're in the interesting interior case.  The TokenFactor
02091     // is now going to be considered part of the pattern so that we rewrite its
02092     // uses (it may have uses that are not part of the pattern) with the
02093     // ultimate chain result of the generated code.  We will also add its chain
02094     // inputs as inputs to the ultimate TokenFactor we create.
02095     Result = CR_LeadsToInteriorNode;
02096     ChainedNodesInPattern.push_back(User);
02097     InteriorChainedNodes.push_back(User);
02098     continue;
02099   }
02100 
02101   return Result;
02102 }
02103 
02104 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
02105 /// operation for when the pattern matched at least one node with a chains.  The
02106 /// input vector contains a list of all of the chained nodes that we match.  We
02107 /// must determine if this is a valid thing to cover (i.e. matching it won't
02108 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
02109 /// be used as the input node chain for the generated nodes.
02110 static SDValue
02111 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
02112                        SelectionDAG *CurDAG) {
02113   // Walk all of the chained nodes we've matched, recursively scanning down the
02114   // users of the chain result. This adds any TokenFactor nodes that are caught
02115   // in between chained nodes to the chained and interior nodes list.
02116   SmallVector<SDNode*, 3> InteriorChainedNodes;
02117   for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
02118     if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
02119                        InteriorChainedNodes) == CR_InducesCycle)
02120       return SDValue(); // Would induce a cycle.
02121   }
02122 
02123   // Okay, we have walked all the matched nodes and collected TokenFactor nodes
02124   // that we are interested in.  Form our input TokenFactor node.
02125   SmallVector<SDValue, 3> InputChains;
02126   for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
02127     // Add the input chain of this node to the InputChains list (which will be
02128     // the operands of the generated TokenFactor) if it's not an interior node.
02129     SDNode *N = ChainNodesMatched[i];
02130     if (N->getOpcode() != ISD::TokenFactor) {
02131       if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
02132         continue;
02133 
02134       // Otherwise, add the input chain.
02135       SDValue InChain = ChainNodesMatched[i]->getOperand(0);
02136       assert(InChain.getValueType() == MVT::Other && "Not a chain");
02137       InputChains.push_back(InChain);
02138       continue;
02139     }
02140 
02141     // If we have a token factor, we want to add all inputs of the token factor
02142     // that are not part of the pattern we're matching.
02143     for (unsigned op = 0, e = N->getNumOperands(); op != e; ++op) {
02144       if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
02145                       N->getOperand(op).getNode()))
02146         InputChains.push_back(N->getOperand(op));
02147     }
02148   }
02149 
02150   if (InputChains.size() == 1)
02151     return InputChains[0];
02152   return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
02153                          MVT::Other, InputChains);
02154 }
02155 
02156 /// MorphNode - Handle morphing a node in place for the selector.
02157 SDNode *SelectionDAGISel::
02158 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
02159           ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) {
02160   // It is possible we're using MorphNodeTo to replace a node with no
02161   // normal results with one that has a normal result (or we could be
02162   // adding a chain) and the input could have glue and chains as well.
02163   // In this case we need to shift the operands down.
02164   // FIXME: This is a horrible hack and broken in obscure cases, no worse
02165   // than the old isel though.
02166   int OldGlueResultNo = -1, OldChainResultNo = -1;
02167 
02168   unsigned NTMNumResults = Node->getNumValues();
02169   if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
02170     OldGlueResultNo = NTMNumResults-1;
02171     if (NTMNumResults != 1 &&
02172         Node->getValueType(NTMNumResults-2) == MVT::Other)
02173       OldChainResultNo = NTMNumResults-2;
02174   } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
02175     OldChainResultNo = NTMNumResults-1;
02176 
02177   // Call the underlying SelectionDAG routine to do the transmogrification. Note
02178   // that this deletes operands of the old node that become dead.
02179   SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops);
02180 
02181   // MorphNodeTo can operate in two ways: if an existing node with the
02182   // specified operands exists, it can just return it.  Otherwise, it
02183   // updates the node in place to have the requested operands.
02184   if (Res == Node) {
02185     // If we updated the node in place, reset the node ID.  To the isel,
02186     // this should be just like a newly allocated machine node.
02187     Res->setNodeId(-1);
02188   }
02189 
02190   unsigned ResNumResults = Res->getNumValues();
02191   // Move the glue if needed.
02192   if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
02193       (unsigned)OldGlueResultNo != ResNumResults-1)
02194     CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldGlueResultNo),
02195                                       SDValue(Res, ResNumResults-1));
02196 
02197   if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
02198     --ResNumResults;
02199 
02200   // Move the chain reference if needed.
02201   if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
02202       (unsigned)OldChainResultNo != ResNumResults-1)
02203     CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
02204                                       SDValue(Res, ResNumResults-1));
02205 
02206   // Otherwise, no replacement happened because the node already exists. Replace
02207   // Uses of the old node with the new one.
02208   if (Res != Node)
02209     CurDAG->ReplaceAllUsesWith(Node, Res);
02210 
02211   return Res;
02212 }
02213 
02214 /// CheckSame - Implements OP_CheckSame.
02215 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02216 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02217           SDValue N,
02218           const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
02219   // Accept if it is exactly the same as a previously recorded node.
02220   unsigned RecNo = MatcherTable[MatcherIndex++];
02221   assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
02222   return N == RecordedNodes[RecNo].first;
02223 }
02224 
02225 /// CheckChildSame - Implements OP_CheckChildXSame.
02226 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02227 CheckChildSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02228              SDValue N,
02229              const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes,
02230              unsigned ChildNo) {
02231   if (ChildNo >= N.getNumOperands())
02232     return false;  // Match fails if out of range child #.
02233   return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo),
02234                      RecordedNodes);
02235 }
02236 
02237 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
02238 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02239 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02240                       const SelectionDAGISel &SDISel) {
02241   return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
02242 }
02243 
02244 /// CheckNodePredicate - Implements OP_CheckNodePredicate.
02245 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02246 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02247                    const SelectionDAGISel &SDISel, SDNode *N) {
02248   return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
02249 }
02250 
02251 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02252 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02253             SDNode *N) {
02254   uint16_t Opc = MatcherTable[MatcherIndex++];
02255   Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
02256   return N->getOpcode() == Opc;
02257 }
02258 
02259 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02260 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02261           SDValue N, const TargetLowering *TLI) {
02262   MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
02263   if (N.getValueType() == VT) return true;
02264 
02265   // Handle the case when VT is iPTR.
02266   return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy();
02267 }
02268 
02269 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02270 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02271                SDValue N, const TargetLowering *TLI, unsigned ChildNo) {
02272   if (ChildNo >= N.getNumOperands())
02273     return false;  // Match fails if out of range child #.
02274   return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI);
02275 }
02276 
02277 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02278 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02279               SDValue N) {
02280   return cast<CondCodeSDNode>(N)->get() ==
02281       (ISD::CondCode)MatcherTable[MatcherIndex++];
02282 }
02283 
02284 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02285 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02286                SDValue N, const TargetLowering *TLI) {
02287   MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
02288   if (cast<VTSDNode>(N)->getVT() == VT)
02289     return true;
02290 
02291   // Handle the case when VT is iPTR.
02292   return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy();
02293 }
02294 
02295 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02296 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02297              SDValue N) {
02298   int64_t Val = MatcherTable[MatcherIndex++];
02299   if (Val & 128)
02300     Val = GetVBR(Val, MatcherTable, MatcherIndex);
02301 
02302   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
02303   return C && C->getSExtValue() == Val;
02304 }
02305 
02306 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02307 CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02308                   SDValue N, unsigned ChildNo) {
02309   if (ChildNo >= N.getNumOperands())
02310     return false;  // Match fails if out of range child #.
02311   return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo));
02312 }
02313 
02314 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02315 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02316             SDValue N, const SelectionDAGISel &SDISel) {
02317   int64_t Val = MatcherTable[MatcherIndex++];
02318   if (Val & 128)
02319     Val = GetVBR(Val, MatcherTable, MatcherIndex);
02320 
02321   if (N->getOpcode() != ISD::AND) return false;
02322 
02323   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
02324   return C && SDISel.CheckAndMask(N.getOperand(0), C, Val);
02325 }
02326 
02327 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02328 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02329            SDValue N, const SelectionDAGISel &SDISel) {
02330   int64_t Val = MatcherTable[MatcherIndex++];
02331   if (Val & 128)
02332     Val = GetVBR(Val, MatcherTable, MatcherIndex);
02333 
02334   if (N->getOpcode() != ISD::OR) return false;
02335 
02336   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
02337   return C && SDISel.CheckOrMask(N.getOperand(0), C, Val);
02338 }
02339 
02340 /// IsPredicateKnownToFail - If we know how and can do so without pushing a
02341 /// scope, evaluate the current node.  If the current predicate is known to
02342 /// fail, set Result=true and return anything.  If the current predicate is
02343 /// known to pass, set Result=false and return the MatcherIndex to continue
02344 /// with.  If the current predicate is unknown, set Result=false and return the
02345 /// MatcherIndex to continue with.
02346 static unsigned IsPredicateKnownToFail(const unsigned char *Table,
02347                                        unsigned Index, SDValue N,
02348                                        bool &Result,
02349                                        const SelectionDAGISel &SDISel,
02350                  SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
02351   switch (Table[Index++]) {
02352   default:
02353     Result = false;
02354     return Index-1;  // Could not evaluate this predicate.
02355   case SelectionDAGISel::OPC_CheckSame:
02356     Result = !::CheckSame(Table, Index, N, RecordedNodes);
02357     return Index;
02358   case SelectionDAGISel::OPC_CheckChild0Same:
02359   case SelectionDAGISel::OPC_CheckChild1Same:
02360   case SelectionDAGISel::OPC_CheckChild2Same:
02361   case SelectionDAGISel::OPC_CheckChild3Same:
02362     Result = !::CheckChildSame(Table, Index, N, RecordedNodes,
02363                         Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Same);
02364     return Index;
02365   case SelectionDAGISel::OPC_CheckPatternPredicate:
02366     Result = !::CheckPatternPredicate(Table, Index, SDISel);
02367     return Index;
02368   case SelectionDAGISel::OPC_CheckPredicate:
02369     Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
02370     return Index;
02371   case SelectionDAGISel::OPC_CheckOpcode:
02372     Result = !::CheckOpcode(Table, Index, N.getNode());
02373     return Index;
02374   case SelectionDAGISel::OPC_CheckType:
02375     Result = !::CheckType(Table, Index, N, SDISel.TLI);
02376     return Index;
02377   case SelectionDAGISel::OPC_CheckChild0Type:
02378   case SelectionDAGISel::OPC_CheckChild1Type:
02379   case SelectionDAGISel::OPC_CheckChild2Type:
02380   case SelectionDAGISel::OPC_CheckChild3Type:
02381   case SelectionDAGISel::OPC_CheckChild4Type:
02382   case SelectionDAGISel::OPC_CheckChild5Type:
02383   case SelectionDAGISel::OPC_CheckChild6Type:
02384   case SelectionDAGISel::OPC_CheckChild7Type:
02385     Result = !::CheckChildType(Table, Index, N, SDISel.TLI,
02386                                Table[Index - 1] -
02387                                    SelectionDAGISel::OPC_CheckChild0Type);
02388     return Index;
02389   case SelectionDAGISel::OPC_CheckCondCode:
02390     Result = !::CheckCondCode(Table, Index, N);
02391     return Index;
02392   case SelectionDAGISel::OPC_CheckValueType:
02393     Result = !::CheckValueType(Table, Index, N, SDISel.TLI);
02394     return Index;
02395   case SelectionDAGISel::OPC_CheckInteger:
02396     Result = !::CheckInteger(Table, Index, N);
02397     return Index;
02398   case SelectionDAGISel::OPC_CheckChild0Integer:
02399   case SelectionDAGISel::OPC_CheckChild1Integer:
02400   case SelectionDAGISel::OPC_CheckChild2Integer:
02401   case SelectionDAGISel::OPC_CheckChild3Integer:
02402   case SelectionDAGISel::OPC_CheckChild4Integer:
02403     Result = !::CheckChildInteger(Table, Index, N,
02404                      Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Integer);
02405     return Index;
02406   case SelectionDAGISel::OPC_CheckAndImm:
02407     Result = !::CheckAndImm(Table, Index, N, SDISel);
02408     return Index;
02409   case SelectionDAGISel::OPC_CheckOrImm:
02410     Result = !::CheckOrImm(Table, Index, N, SDISel);
02411     return Index;
02412   }
02413 }
02414 
02415 namespace {
02416 
02417 struct MatchScope {
02418   /// FailIndex - If this match fails, this is the index to continue with.
02419   unsigned FailIndex;
02420 
02421   /// NodeStack - The node stack when the scope was formed.
02422   SmallVector<SDValue, 4> NodeStack;
02423 
02424   /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
02425   unsigned NumRecordedNodes;
02426 
02427   /// NumMatchedMemRefs - The number of matched memref entries.
02428   unsigned NumMatchedMemRefs;
02429 
02430   /// InputChain/InputGlue - The current chain/glue
02431   SDValue InputChain, InputGlue;
02432 
02433   /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
02434   bool HasChainNodesMatched, HasGlueResultNodesMatched;
02435 };
02436 
02437 /// \\brief A DAG update listener to keep the matching state
02438 /// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to
02439 /// change the DAG while matching.  X86 addressing mode matcher is an example
02440 /// for this.
02441 class MatchStateUpdater : public SelectionDAG::DAGUpdateListener
02442 {
02443       SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes;
02444       SmallVectorImpl<MatchScope> &MatchScopes;
02445 public:
02446   MatchStateUpdater(SelectionDAG &DAG,
02447                     SmallVectorImpl<std::pair<SDValue, SDNode*> > &RN,
02448                     SmallVectorImpl<MatchScope> &MS) :
02449     SelectionDAG::DAGUpdateListener(DAG),
02450     RecordedNodes(RN), MatchScopes(MS) { }
02451 
02452   void NodeDeleted(SDNode *N, SDNode *E) {
02453     // Some early-returns here to avoid the search if we deleted the node or
02454     // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we
02455     // do, so it's unnecessary to update matching state at that point).
02456     // Neither of these can occur currently because we only install this
02457     // update listener during matching a complex patterns.
02458     if (!E || E->isMachineOpcode())
02459       return;
02460     // Performing linear search here does not matter because we almost never
02461     // run this code.  You'd have to have a CSE during complex pattern
02462     // matching.
02463     for (auto &I : RecordedNodes)
02464       if (I.first.getNode() == N)
02465         I.first.setNode(E);
02466 
02467     for (auto &I : MatchScopes)
02468       for (auto &J : I.NodeStack)
02469         if (J.getNode() == N)
02470           J.setNode(E);
02471   }
02472 };
02473 }
02474 
02475 SDNode *SelectionDAGISel::
02476 SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
02477                  unsigned TableSize) {
02478   // FIXME: Should these even be selected?  Handle these cases in the caller?
02479   switch (NodeToMatch->getOpcode()) {
02480   default:
02481     break;
02482   case ISD::EntryToken:       // These nodes remain the same.
02483   case ISD::BasicBlock:
02484   case ISD::Register:
02485   case ISD::RegisterMask:
02486   case ISD::HANDLENODE:
02487   case ISD::MDNODE_SDNODE:
02488   case ISD::TargetConstant:
02489   case ISD::TargetConstantFP:
02490   case ISD::TargetConstantPool:
02491   case ISD::TargetFrameIndex:
02492   case ISD::TargetExternalSymbol:
02493   case ISD::TargetBlockAddress:
02494   case ISD::TargetJumpTable:
02495   case ISD::TargetGlobalTLSAddress:
02496   case ISD::TargetGlobalAddress:
02497   case ISD::TokenFactor:
02498   case ISD::CopyFromReg:
02499   case ISD::CopyToReg:
02500   case ISD::EH_LABEL:
02501   case ISD::LIFETIME_START:
02502   case ISD::LIFETIME_END:
02503     NodeToMatch->setNodeId(-1); // Mark selected.
02504     return nullptr;
02505   case ISD::AssertSext:
02506   case ISD::AssertZext:
02507     CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0),
02508                                       NodeToMatch->getOperand(0));
02509     return nullptr;
02510   case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
02511   case ISD::READ_REGISTER: return Select_READ_REGISTER(NodeToMatch);
02512   case ISD::WRITE_REGISTER: return Select_WRITE_REGISTER(NodeToMatch);
02513   case ISD::UNDEF:     return Select_UNDEF(NodeToMatch);
02514   }
02515 
02516   assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
02517 
02518   // Set up the node stack with NodeToMatch as the only node on the stack.
02519   SmallVector<SDValue, 8> NodeStack;
02520   SDValue N = SDValue(NodeToMatch, 0);
02521   NodeStack.push_back(N);
02522 
02523   // MatchScopes - Scopes used when matching, if a match failure happens, this
02524   // indicates where to continue checking.
02525   SmallVector<MatchScope, 8> MatchScopes;
02526 
02527   // RecordedNodes - This is the set of nodes that have been recorded by the
02528   // state machine.  The second value is the parent of the node, or null if the
02529   // root is recorded.
02530   SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
02531 
02532   // MatchedMemRefs - This is the set of MemRef's we've seen in the input
02533   // pattern.
02534   SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
02535 
02536   // These are the current input chain and glue for use when generating nodes.
02537   // Various Emit operations change these.  For example, emitting a copytoreg
02538   // uses and updates these.
02539   SDValue InputChain, InputGlue;
02540 
02541   // ChainNodesMatched - If a pattern matches nodes that have input/output
02542   // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
02543   // which ones they are.  The result is captured into this list so that we can
02544   // update the chain results when the pattern is complete.
02545   SmallVector<SDNode*, 3> ChainNodesMatched;
02546   SmallVector<SDNode*, 3> GlueResultNodesMatched;
02547 
02548   DEBUG(dbgs() << "ISEL: Starting pattern match on root node: ";
02549         NodeToMatch->dump(CurDAG);
02550         dbgs() << '\n');
02551 
02552   // Determine where to start the interpreter.  Normally we start at opcode #0,
02553   // but if the state machine starts with an OPC_SwitchOpcode, then we
02554   // accelerate the first lookup (which is guaranteed to be hot) with the
02555   // OpcodeOffset table.
02556   unsigned MatcherIndex = 0;
02557 
02558   if (!OpcodeOffset.empty()) {
02559     // Already computed the OpcodeOffset table, just index into it.
02560     if (N.getOpcode() < OpcodeOffset.size())
02561       MatcherIndex = OpcodeOffset[N.getOpcode()];
02562     DEBUG(dbgs() << "  Initial Opcode index to " << MatcherIndex << "\n");
02563 
02564   } else if (MatcherTable[0] == OPC_SwitchOpcode) {
02565     // Otherwise, the table isn't computed, but the state machine does start
02566     // with an OPC_SwitchOpcode instruction.  Populate the table now, since this
02567     // is the first time we're selecting an instruction.
02568     unsigned Idx = 1;
02569     while (1) {
02570       // Get the size of this case.
02571       unsigned CaseSize = MatcherTable[Idx++];
02572       if (CaseSize & 128)
02573         CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
02574       if (CaseSize == 0) break;
02575 
02576       // Get the opcode, add the index to the table.
02577       uint16_t Opc = MatcherTable[Idx++];
02578       Opc |= (unsigned short)MatcherTable[Idx++] << 8;
02579       if (Opc >= OpcodeOffset.size())
02580         OpcodeOffset.resize((Opc+1)*2);
02581       OpcodeOffset[Opc] = Idx;
02582       Idx += CaseSize;
02583     }
02584 
02585     // Okay, do the lookup for the first opcode.
02586     if (N.getOpcode() < OpcodeOffset.size())
02587       MatcherIndex = OpcodeOffset[N.getOpcode()];
02588   }
02589 
02590   while (1) {
02591     assert(MatcherIndex < TableSize && "Invalid index");
02592 #ifndef NDEBUG
02593     unsigned CurrentOpcodeIndex = MatcherIndex;
02594 #endif
02595     BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
02596     switch (Opcode) {
02597     case OPC_Scope: {
02598       // Okay, the semantics of this operation are that we should push a scope
02599       // then evaluate the first child.  However, pushing a scope only to have
02600       // the first check fail (which then pops it) is inefficient.  If we can
02601       // determine immediately that the first check (or first several) will
02602       // immediately fail, don't even bother pushing a scope for them.
02603       unsigned FailIndex;
02604 
02605       while (1) {
02606         unsigned NumToSkip = MatcherTable[MatcherIndex++];
02607         if (NumToSkip & 128)
02608           NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
02609         // Found the end of the scope with no match.
02610         if (NumToSkip == 0) {
02611           FailIndex = 0;
02612           break;
02613         }
02614 
02615         FailIndex = MatcherIndex+NumToSkip;
02616 
02617         unsigned MatcherIndexOfPredicate = MatcherIndex;
02618         (void)MatcherIndexOfPredicate; // silence warning.
02619 
02620         // If we can't evaluate this predicate without pushing a scope (e.g. if
02621         // it is a 'MoveParent') or if the predicate succeeds on this node, we
02622         // push the scope and evaluate the full predicate chain.
02623         bool Result;
02624         MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
02625                                               Result, *this, RecordedNodes);
02626         if (!Result)
02627           break;
02628 
02629         DEBUG(dbgs() << "  Skipped scope entry (due to false predicate) at "
02630                      << "index " << MatcherIndexOfPredicate
02631                      << ", continuing at " << FailIndex << "\n");
02632         ++NumDAGIselRetries;
02633 
02634         // Otherwise, we know that this case of the Scope is guaranteed to fail,
02635         // move to the next case.
02636         MatcherIndex = FailIndex;
02637       }
02638 
02639       // If the whole scope failed to match, bail.
02640       if (FailIndex == 0) break;
02641 
02642       // Push a MatchScope which indicates where to go if the first child fails
02643       // to match.
02644       MatchScope NewEntry;
02645       NewEntry.FailIndex = FailIndex;
02646       NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
02647       NewEntry.NumRecordedNodes = RecordedNodes.size();
02648       NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
02649       NewEntry.InputChain = InputChain;
02650       NewEntry.InputGlue = InputGlue;
02651       NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
02652       NewEntry.HasGlueResultNodesMatched = !GlueResultNodesMatched.empty();
02653       MatchScopes.push_back(NewEntry);
02654       continue;
02655     }
02656     case OPC_RecordNode: {
02657       // Remember this node, it may end up being an operand in the pattern.
02658       SDNode *Parent = nullptr;
02659       if (NodeStack.size() > 1)
02660         Parent = NodeStack[NodeStack.size()-2].getNode();
02661       RecordedNodes.push_back(std::make_pair(N, Parent));
02662       continue;
02663     }
02664 
02665     case OPC_RecordChild0: case OPC_RecordChild1:
02666     case OPC_RecordChild2: case OPC_RecordChild3:
02667     case OPC_RecordChild4: case OPC_RecordChild5:
02668     case OPC_RecordChild6: case OPC_RecordChild7: {
02669       unsigned ChildNo = Opcode-OPC_RecordChild0;
02670       if (ChildNo >= N.getNumOperands())
02671         break;  // Match fails if out of range child #.
02672 
02673       RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
02674                                              N.getNode()));
02675       continue;
02676     }
02677     case OPC_RecordMemRef:
02678       MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
02679       continue;
02680 
02681     case OPC_CaptureGlueInput:
02682       // If the current node has an input glue, capture it in InputGlue.
02683       if (N->getNumOperands() != 0 &&
02684           N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
02685         InputGlue = N->getOperand(N->getNumOperands()-1);
02686       continue;
02687 
02688     case OPC_MoveChild: {
02689       unsigned ChildNo = MatcherTable[MatcherIndex++];
02690       if (ChildNo >= N.getNumOperands())
02691         break;  // Match fails if out of range child #.
02692       N = N.getOperand(ChildNo);
02693       NodeStack.push_back(N);
02694       continue;
02695     }
02696 
02697     case OPC_MoveParent:
02698       // Pop the current node off the NodeStack.
02699       NodeStack.pop_back();
02700       assert(!NodeStack.empty() && "Node stack imbalance!");
02701       N = NodeStack.back();
02702       continue;
02703 
02704     case OPC_CheckSame:
02705       if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
02706       continue;
02707 
02708     case OPC_CheckChild0Same: case OPC_CheckChild1Same:
02709     case OPC_CheckChild2Same: case OPC_CheckChild3Same:
02710       if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes,
02711                             Opcode-OPC_CheckChild0Same))
02712         break;
02713       continue;
02714 
02715     case OPC_CheckPatternPredicate:
02716       if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
02717       continue;
02718     case OPC_CheckPredicate:
02719       if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
02720                                 N.getNode()))
02721         break;
02722       continue;
02723     case OPC_CheckComplexPat: {
02724       unsigned CPNum = MatcherTable[MatcherIndex++];
02725       unsigned RecNo = MatcherTable[MatcherIndex++];
02726       assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
02727 
02728       // If target can modify DAG during matching, keep the matching state
02729       // consistent.
02730       std::unique_ptr<MatchStateUpdater> MSU;
02731       if (ComplexPatternFuncMutatesDAG())
02732         MSU.reset(new MatchStateUpdater(*CurDAG, RecordedNodes,
02733                                         MatchScopes));
02734 
02735       if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
02736                                RecordedNodes[RecNo].first, CPNum,
02737                                RecordedNodes))
02738         break;
02739       continue;
02740     }
02741     case OPC_CheckOpcode:
02742       if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
02743       continue;
02744 
02745     case OPC_CheckType:
02746       if (!::CheckType(MatcherTable, MatcherIndex, N, TLI))
02747         break;
02748       continue;
02749 
02750     case OPC_SwitchOpcode: {
02751       unsigned CurNodeOpcode = N.getOpcode();
02752       unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
02753       unsigned CaseSize;
02754       while (1) {
02755         // Get the size of this case.
02756         CaseSize = MatcherTable[MatcherIndex++];
02757         if (CaseSize & 128)
02758           CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
02759         if (CaseSize == 0) break;
02760 
02761         uint16_t Opc = MatcherTable[MatcherIndex++];
02762         Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
02763 
02764         // If the opcode matches, then we will execute this case.
02765         if (CurNodeOpcode == Opc)
02766           break;
02767 
02768         // Otherwise, skip over this case.
02769         MatcherIndex += CaseSize;
02770       }
02771 
02772       // If no cases matched, bail out.
02773       if (CaseSize == 0) break;
02774 
02775       // Otherwise, execute the case we found.
02776       DEBUG(dbgs() << "  OpcodeSwitch from " << SwitchStart
02777                    << " to " << MatcherIndex << "\n");
02778       continue;
02779     }
02780 
02781     case OPC_SwitchType: {
02782       MVT CurNodeVT = N.getSimpleValueType();
02783       unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
02784       unsigned CaseSize;
02785       while (1) {
02786         // Get the size of this case.
02787         CaseSize = MatcherTable[MatcherIndex++];
02788         if (CaseSize & 128)
02789           CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
02790         if (CaseSize == 0) break;
02791 
02792         MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
02793         if (CaseVT == MVT::iPTR)
02794           CaseVT = TLI->getPointerTy();
02795 
02796         // If the VT matches, then we will execute this case.
02797         if (CurNodeVT == CaseVT)
02798           break;
02799 
02800         // Otherwise, skip over this case.
02801         MatcherIndex += CaseSize;
02802       }
02803 
02804       // If no cases matched, bail out.
02805       if (CaseSize == 0) break;
02806 
02807       // Otherwise, execute the case we found.
02808       DEBUG(dbgs() << "  TypeSwitch[" << EVT(CurNodeVT).getEVTString()
02809                    << "] from " << SwitchStart << " to " << MatcherIndex<<'\n');
02810       continue;
02811     }
02812     case OPC_CheckChild0Type: case OPC_CheckChild1Type:
02813     case OPC_CheckChild2Type: case OPC_CheckChild3Type:
02814     case OPC_CheckChild4Type: case OPC_CheckChild5Type:
02815     case OPC_CheckChild6Type: case OPC_CheckChild7Type:
02816       if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
02817                             Opcode-OPC_CheckChild0Type))
02818         break;
02819       continue;
02820     case OPC_CheckCondCode:
02821       if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
02822       continue;
02823     case OPC_CheckValueType:
02824       if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI))
02825         break;
02826       continue;
02827     case OPC_CheckInteger:
02828       if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
02829       continue;
02830     case OPC_CheckChild0Integer: case OPC_CheckChild1Integer:
02831     case OPC_CheckChild2Integer: case OPC_CheckChild3Integer:
02832     case OPC_CheckChild4Integer:
02833       if (!::CheckChildInteger(MatcherTable, MatcherIndex, N,
02834                                Opcode-OPC_CheckChild0Integer)) break;
02835       continue;
02836     case OPC_CheckAndImm:
02837       if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
02838       continue;
02839     case OPC_CheckOrImm:
02840       if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
02841       continue;
02842 
02843     case OPC_CheckFoldableChainNode: {
02844       assert(NodeStack.size() != 1 && "No parent node");
02845       // Verify that all intermediate nodes between the root and this one have
02846       // a single use.
02847       bool HasMultipleUses = false;
02848       for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
02849         if (!NodeStack[i].hasOneUse()) {
02850           HasMultipleUses = true;
02851           break;
02852         }
02853       if (HasMultipleUses) break;
02854 
02855       // Check to see that the target thinks this is profitable to fold and that
02856       // we can fold it without inducing cycles in the graph.
02857       if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
02858                               NodeToMatch) ||
02859           !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
02860                          NodeToMatch, OptLevel,
02861                          true/*We validate our own chains*/))
02862         break;
02863 
02864       continue;
02865     }
02866     case OPC_EmitInteger: {
02867       MVT::SimpleValueType VT =
02868         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
02869       int64_t Val = MatcherTable[MatcherIndex++];
02870       if (Val & 128)
02871         Val = GetVBR(Val, MatcherTable, MatcherIndex);
02872       RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
02873                               CurDAG->getTargetConstant(Val, VT), nullptr));
02874       continue;
02875     }
02876     case OPC_EmitRegister: {
02877       MVT::SimpleValueType VT =
02878         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
02879       unsigned RegNo = MatcherTable[MatcherIndex++];
02880       RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
02881                               CurDAG->getRegister(RegNo, VT), nullptr));
02882       continue;
02883     }
02884     case OPC_EmitRegister2: {
02885       // For targets w/ more than 256 register names, the register enum
02886       // values are stored in two bytes in the matcher table (just like
02887       // opcodes).
02888       MVT::SimpleValueType VT =
02889         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
02890       unsigned RegNo = MatcherTable[MatcherIndex++];
02891       RegNo |= MatcherTable[MatcherIndex++] << 8;
02892       RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
02893                               CurDAG->getRegister(RegNo, VT), nullptr));
02894       continue;
02895     }
02896 
02897     case OPC_EmitConvertToTarget:  {
02898       // Convert from IMM/FPIMM to target version.
02899       unsigned RecNo = MatcherTable[MatcherIndex++];
02900       assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget");
02901       SDValue Imm = RecordedNodes[RecNo].first;
02902 
02903       if (Imm->getOpcode() == ISD::Constant) {
02904         const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
02905         Imm = CurDAG->getConstant(*Val, Imm.getValueType(), true);
02906       } else if (Imm->getOpcode() == ISD::ConstantFP) {
02907         const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
02908         Imm = CurDAG->getConstantFP(*Val, Imm.getValueType(), true);
02909       }
02910 
02911       RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
02912       continue;
02913     }
02914 
02915     case OPC_EmitMergeInputChains1_0:    // OPC_EmitMergeInputChains, 1, 0
02916     case OPC_EmitMergeInputChains1_1: {  // OPC_EmitMergeInputChains, 1, 1
02917       // These are space-optimized forms of OPC_EmitMergeInputChains.
02918       assert(!InputChain.getNode() &&
02919              "EmitMergeInputChains should be the first chain producing node");
02920       assert(ChainNodesMatched.empty() &&
02921              "Should only have one EmitMergeInputChains per match");
02922 
02923       // Read all of the chained nodes.
02924       unsigned RecNo = Opcode == OPC_EmitMergeInputChains1_1;
02925       assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
02926       ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
02927 
02928       // FIXME: What if other value results of the node have uses not matched
02929       // by this pattern?
02930       if (ChainNodesMatched.back() != NodeToMatch &&
02931           !RecordedNodes[RecNo].first.hasOneUse()) {
02932         ChainNodesMatched.clear();
02933         break;
02934       }
02935 
02936       // Merge the input chains if they are not intra-pattern references.
02937       InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
02938 
02939       if (!InputChain.getNode())
02940         break;  // Failed to merge.
02941       continue;
02942     }
02943 
02944     case OPC_EmitMergeInputChains: {
02945       assert(!InputChain.getNode() &&
02946              "EmitMergeInputChains should be the first chain producing node");
02947       // This node gets a list of nodes we matched in the input that have
02948       // chains.  We want to token factor all of the input chains to these nodes
02949       // together.  However, if any of the input chains is actually one of the
02950       // nodes matched in this pattern, then we have an intra-match reference.
02951       // Ignore these because the newly token factored chain should not refer to
02952       // the old nodes.
02953       unsigned NumChains = MatcherTable[MatcherIndex++];
02954       assert(NumChains != 0 && "Can't TF zero chains");
02955 
02956       assert(ChainNodesMatched.empty() &&
02957              "Should only have one EmitMergeInputChains per match");
02958 
02959       // Read all of the chained nodes.
02960       for (unsigned i = 0; i != NumChains; ++i) {
02961         unsigned RecNo = MatcherTable[MatcherIndex++];
02962         assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
02963         ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
02964 
02965         // FIXME: What if other value results of the node have uses not matched
02966         // by this pattern?
02967         if (ChainNodesMatched.back() != NodeToMatch &&
02968             !RecordedNodes[RecNo].first.hasOneUse()) {
02969           ChainNodesMatched.clear();
02970           break;
02971         }
02972       }
02973 
02974       // If the inner loop broke out, the match fails.
02975       if (ChainNodesMatched.empty())
02976         break;
02977 
02978       // Merge the input chains if they are not intra-pattern references.
02979       InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
02980 
02981       if (!InputChain.getNode())
02982         break;  // Failed to merge.
02983 
02984       continue;
02985     }
02986 
02987     case OPC_EmitCopyToReg: {
02988       unsigned RecNo = MatcherTable[MatcherIndex++];
02989       assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg");
02990       unsigned DestPhysReg = MatcherTable[MatcherIndex++];
02991 
02992       if (!InputChain.getNode())
02993         InputChain = CurDAG->getEntryNode();
02994 
02995       InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
02996                                         DestPhysReg, RecordedNodes[RecNo].first,
02997                                         InputGlue);
02998 
02999       InputGlue = InputChain.getValue(1);
03000       continue;
03001     }
03002 
03003     case OPC_EmitNodeXForm: {
03004       unsigned XFormNo = MatcherTable[MatcherIndex++];
03005       unsigned RecNo = MatcherTable[MatcherIndex++];
03006       assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm");
03007       SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
03008       RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr));
03009       continue;
03010     }
03011 
03012     case OPC_EmitNode:
03013     case OPC_MorphNodeTo: {
03014       uint16_t TargetOpc = MatcherTable[MatcherIndex++];
03015       TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
03016       unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
03017       // Get the result VT list.
03018       unsigned NumVTs = MatcherTable[MatcherIndex++];
03019       SmallVector<EVT, 4> VTs;
03020       for (unsigned i = 0; i != NumVTs; ++i) {
03021         MVT::SimpleValueType VT =
03022           (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
03023         if (VT == MVT::iPTR)
03024           VT = TLI->getPointerTy().SimpleTy;
03025         VTs.push_back(VT);
03026       }
03027 
03028       if (EmitNodeInfo & OPFL_Chain)
03029         VTs.push_back(MVT::Other);
03030       if (EmitNodeInfo & OPFL_GlueOutput)
03031         VTs.push_back(MVT::Glue);
03032 
03033       // This is hot code, so optimize the two most common cases of 1 and 2
03034       // results.
03035       SDVTList VTList;
03036       if (VTs.size() == 1)
03037         VTList = CurDAG->getVTList(VTs[0]);
03038       else if (VTs.size() == 2)
03039         VTList = CurDAG->getVTList(VTs[0], VTs[1]);
03040       else
03041         VTList = CurDAG->getVTList(VTs);
03042 
03043       // Get the operand list.
03044       unsigned NumOps = MatcherTable[MatcherIndex++];
03045       SmallVector<SDValue, 8> Ops;
03046       for (unsigned i = 0; i != NumOps; ++i) {
03047         unsigned RecNo = MatcherTable[MatcherIndex++];
03048         if (RecNo & 128)
03049           RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
03050 
03051         assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
03052         Ops.push_back(RecordedNodes[RecNo].first);
03053       }
03054 
03055       // If there are variadic operands to add, handle them now.
03056       if (EmitNodeInfo & OPFL_VariadicInfo) {
03057         // Determine the start index to copy from.
03058         unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
03059         FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
03060         assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
03061                "Invalid variadic node");
03062         // Copy all of the variadic operands, not including a potential glue
03063         // input.
03064         for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
03065              i != e; ++i) {
03066           SDValue V = NodeToMatch->getOperand(i);
03067           if (V.getValueType() == MVT::Glue) break;
03068           Ops.push_back(V);
03069         }
03070       }
03071 
03072       // If this has chain/glue inputs, add them.
03073       if (EmitNodeInfo & OPFL_Chain)
03074         Ops.push_back(InputChain);
03075       if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr)
03076         Ops.push_back(InputGlue);
03077 
03078       // Create the node.
03079       SDNode *Res = nullptr;
03080       if (Opcode != OPC_MorphNodeTo) {
03081         // If this is a normal EmitNode command, just create the new node and
03082         // add the results to the RecordedNodes list.
03083         Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
03084                                      VTList, Ops);
03085 
03086         // Add all the non-glue/non-chain results to the RecordedNodes list.
03087         for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
03088           if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
03089           RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
03090                                                              nullptr));
03091         }
03092 
03093       } else if (NodeToMatch->getOpcode() != ISD::DELETED_NODE) {
03094         Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops, EmitNodeInfo);
03095       } else {
03096         // NodeToMatch was eliminated by CSE when the target changed the DAG.
03097         // We will visit the equivalent node later.
03098         DEBUG(dbgs() << "Node was eliminated by CSE\n");
03099         return nullptr;
03100       }
03101 
03102       // If the node had chain/glue results, update our notion of the current
03103       // chain and glue.
03104       if (EmitNodeInfo & OPFL_GlueOutput) {
03105         InputGlue = SDValue(Res, VTs.size()-1);
03106         if (EmitNodeInfo & OPFL_Chain)
03107           InputChain = SDValue(Res, VTs.size()-2);
03108       } else if (EmitNodeInfo & OPFL_Chain)
03109         InputChain = SDValue(Res, VTs.size()-1);
03110 
03111       // If the OPFL_MemRefs glue is set on this node, slap all of the
03112       // accumulated memrefs onto it.
03113       //
03114       // FIXME: This is vastly incorrect for patterns with multiple outputs
03115       // instructions that access memory and for ComplexPatterns that match
03116       // loads.
03117       if (EmitNodeInfo & OPFL_MemRefs) {
03118         // Only attach load or store memory operands if the generated
03119         // instruction may load or store.
03120         const MCInstrDesc &MCID = TII->get(TargetOpc);
03121         bool mayLoad = MCID.mayLoad();
03122         bool mayStore = MCID.mayStore();
03123 
03124         unsigned NumMemRefs = 0;
03125         for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
03126                MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
03127           if ((*I)->isLoad()) {
03128             if (mayLoad)
03129               ++NumMemRefs;
03130           } else if ((*I)->isStore()) {
03131             if (mayStore)
03132               ++NumMemRefs;
03133           } else {
03134             ++NumMemRefs;
03135           }
03136         }
03137 
03138         MachineSDNode::mmo_iterator MemRefs =
03139           MF->allocateMemRefsArray(NumMemRefs);
03140 
03141         MachineSDNode::mmo_iterator MemRefsPos = MemRefs;
03142         for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
03143                MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
03144           if ((*I)->isLoad()) {
03145             if (mayLoad)
03146               *MemRefsPos++ = *I;
03147           } else if ((*I)->isStore()) {
03148             if (mayStore)
03149               *MemRefsPos++ = *I;
03150           } else {
03151             *MemRefsPos++ = *I;
03152           }
03153         }
03154 
03155         cast<MachineSDNode>(Res)
03156           ->setMemRefs(MemRefs, MemRefs + NumMemRefs);
03157       }
03158 
03159       DEBUG(dbgs() << "  "
03160                    << (Opcode == OPC_MorphNodeTo ? "Morphed" : "Created")
03161                    << " node: "; Res->dump(CurDAG); dbgs() << "\n");
03162 
03163       // If this was a MorphNodeTo then we're completely done!
03164       if (Opcode == OPC_MorphNodeTo) {
03165         // Update chain and glue uses.
03166         UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
03167                             InputGlue, GlueResultNodesMatched, true);
03168         return Res;
03169       }
03170 
03171       continue;
03172     }
03173 
03174     case OPC_MarkGlueResults: {
03175       unsigned NumNodes = MatcherTable[MatcherIndex++];
03176 
03177       // Read and remember all the glue-result nodes.
03178       for (unsigned i = 0; i != NumNodes; ++i) {
03179         unsigned RecNo = MatcherTable[MatcherIndex++];
03180         if (RecNo & 128)
03181           RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
03182 
03183         assert(RecNo < RecordedNodes.size() && "Invalid MarkGlueResults");
03184         GlueResultNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
03185       }
03186       continue;
03187     }
03188 
03189     case OPC_CompleteMatch: {
03190       // The match has been completed, and any new nodes (if any) have been
03191       // created.  Patch up references to the matched dag to use the newly
03192       // created nodes.
03193       unsigned NumResults = MatcherTable[MatcherIndex++];
03194 
03195       for (unsigned i = 0; i != NumResults; ++i) {
03196         unsigned ResSlot = MatcherTable[MatcherIndex++];
03197         if (ResSlot & 128)
03198           ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
03199 
03200         assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch");
03201         SDValue Res = RecordedNodes[ResSlot].first;
03202 
03203         assert(i < NodeToMatch->getNumValues() &&
03204                NodeToMatch->getValueType(i) != MVT::Other &&
03205                NodeToMatch->getValueType(i) != MVT::Glue &&
03206                "Invalid number of results to complete!");
03207         assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
03208                 NodeToMatch->getValueType(i) == MVT::iPTR ||
03209                 Res.getValueType() == MVT::iPTR ||
03210                 NodeToMatch->getValueType(i).getSizeInBits() ==
03211                     Res.getValueType().getSizeInBits()) &&
03212                "invalid replacement");
03213         CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
03214       }
03215 
03216       // If the root node defines glue, add it to the glue nodes to update list.
03217       if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) == MVT::Glue)
03218         GlueResultNodesMatched.push_back(NodeToMatch);
03219 
03220       // Update chain and glue uses.
03221       UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
03222                           InputGlue, GlueResultNodesMatched, false);
03223 
03224       assert(NodeToMatch->use_empty() &&
03225              "Didn't replace all uses of the node?");
03226 
03227       // FIXME: We just return here, which interacts correctly with SelectRoot
03228       // above.  We should fix this to not return an SDNode* anymore.
03229       return nullptr;
03230     }
03231     }
03232 
03233     // If the code reached this point, then the match failed.  See if there is
03234     // another child to try in the current 'Scope', otherwise pop it until we
03235     // find a case to check.
03236     DEBUG(dbgs() << "  Match failed at index " << CurrentOpcodeIndex << "\n");
03237     ++NumDAGIselRetries;
03238     while (1) {
03239       if (MatchScopes.empty()) {
03240         CannotYetSelect(NodeToMatch);
03241         return nullptr;
03242       }
03243 
03244       // Restore the interpreter state back to the point where the scope was
03245       // formed.
03246       MatchScope &LastScope = MatchScopes.back();
03247       RecordedNodes.resize(LastScope.NumRecordedNodes);
03248       NodeStack.clear();
03249       NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
03250       N = NodeStack.back();
03251 
03252       if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
03253         MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
03254       MatcherIndex = LastScope.FailIndex;
03255 
03256       DEBUG(dbgs() << "  Continuing at " << MatcherIndex << "\n");
03257 
03258       InputChain = LastScope.InputChain;
03259       InputGlue = LastScope.InputGlue;
03260       if (!LastScope.HasChainNodesMatched)
03261         ChainNodesMatched.clear();
03262       if (!LastScope.HasGlueResultNodesMatched)
03263         GlueResultNodesMatched.clear();
03264 
03265       // Check to see what the offset is at the new MatcherIndex.  If it is zero
03266       // we have reached the end of this scope, otherwise we have another child
03267       // in the current scope to try.
03268       unsigned NumToSkip = MatcherTable[MatcherIndex++];
03269       if (NumToSkip & 128)
03270         NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
03271 
03272       // If we have another child in this scope to match, update FailIndex and
03273       // try it.
03274       if (NumToSkip != 0) {
03275         LastScope.FailIndex = MatcherIndex+NumToSkip;
03276         break;
03277       }
03278 
03279       // End of this scope, pop it and try the next child in the containing
03280       // scope.
03281       MatchScopes.pop_back();
03282     }
03283   }
03284 }
03285 
03286 
03287 
03288 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
03289   std::string msg;
03290   raw_string_ostream Msg(msg);
03291   Msg << "Cannot select: ";
03292 
03293   if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
03294       N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
03295       N->getOpcode() != ISD::INTRINSIC_VOID) {
03296     N->printrFull(Msg, CurDAG);
03297     Msg << "\nIn function: " << MF->getName();
03298   } else {
03299     bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
03300     unsigned iid =
03301       cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
03302     if (iid < Intrinsic::num_intrinsics)
03303       Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid);
03304     else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
03305       Msg << "target intrinsic %" << TII->getName(iid);
03306     else
03307       Msg << "unknown intrinsic #" << iid;
03308   }
03309   report_fatal_error(Msg.str());
03310 }
03311 
03312 char SelectionDAGISel::ID = 0;