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