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.getInstrInfo();
00415   const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
00416   const TargetLowering *TLI = TM.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 = TM.getInstrInfo()->get(MI.getOpcode());
00538       if ((MCID.isCall() && !MCID.isReturn()) ||
00539           MI.isStackAligningInlineAsm()) {
00540         MFI->setHasCalls(true);
00541       }
00542       if (MI.isInlineAsm()) {
00543         MF->setHasInlineAsm(true);
00544       }
00545     }
00546   }
00547 
00548   // Determine if there is a call to setjmp in the machine function.
00549   MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice());
00550 
00551   // Replace forward-declared registers with the registers containing
00552   // the desired value.
00553   MachineRegisterInfo &MRI = MF->getRegInfo();
00554   for (DenseMap<unsigned, unsigned>::iterator
00555        I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end();
00556        I != E; ++I) {
00557     unsigned From = I->first;
00558     unsigned To = I->second;
00559     // If To is also scheduled to be replaced, find what its ultimate
00560     // replacement is.
00561     for (;;) {
00562       DenseMap<unsigned, unsigned>::iterator J = FuncInfo->RegFixups.find(To);
00563       if (J == E) break;
00564       To = J->second;
00565     }
00566     // Make sure the new register has a sufficiently constrained register class.
00567     if (TargetRegisterInfo::isVirtualRegister(From) &&
00568         TargetRegisterInfo::isVirtualRegister(To))
00569       MRI.constrainRegClass(To, MRI.getRegClass(From));
00570     // Replace it.
00571     MRI.replaceRegWith(From, To);
00572   }
00573 
00574   // Freeze the set of reserved registers now that MachineFrameInfo has been
00575   // set up. All the information required by getReservedRegs() should be
00576   // available now.
00577   MRI.freezeReservedRegs(*MF);
00578 
00579   // Release function-specific state. SDB and CurDAG are already cleared
00580   // at this point.
00581   FuncInfo->clear();
00582 
00583   DEBUG(dbgs() << "*** MachineFunction at end of ISel ***\n");
00584   DEBUG(MF->print(dbgs()));
00585 
00586   return true;
00587 }
00588 
00589 void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
00590                                         BasicBlock::const_iterator End,
00591                                         bool &HadTailCall) {
00592   // Lower all of the non-terminator instructions. If a call is emitted
00593   // as a tail call, cease emitting nodes for this block. Terminators
00594   // are handled below.
00595   for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I)
00596     SDB->visit(*I);
00597 
00598   // Make sure the root of the DAG is up-to-date.
00599   CurDAG->setRoot(SDB->getControlRoot());
00600   HadTailCall = SDB->HasTailCall;
00601   SDB->clear();
00602 
00603   // Final step, emit the lowered DAG as machine code.
00604   CodeGenAndEmitDAG();
00605 }
00606 
00607 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
00608   SmallPtrSet<SDNode*, 128> VisitedNodes;
00609   SmallVector<SDNode*, 128> Worklist;
00610 
00611   Worklist.push_back(CurDAG->getRoot().getNode());
00612 
00613   APInt KnownZero;
00614   APInt KnownOne;
00615 
00616   do {
00617     SDNode *N = Worklist.pop_back_val();
00618 
00619     // If we've already seen this node, ignore it.
00620     if (!VisitedNodes.insert(N))
00621       continue;
00622 
00623     // Otherwise, add all chain operands to the worklist.
00624     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00625       if (N->getOperand(i).getValueType() == MVT::Other)
00626         Worklist.push_back(N->getOperand(i).getNode());
00627 
00628     // If this is a CopyToReg with a vreg dest, process it.
00629     if (N->getOpcode() != ISD::CopyToReg)
00630       continue;
00631 
00632     unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
00633     if (!TargetRegisterInfo::isVirtualRegister(DestReg))
00634       continue;
00635 
00636     // Ignore non-scalar or non-integer values.
00637     SDValue Src = N->getOperand(2);
00638     EVT SrcVT = Src.getValueType();
00639     if (!SrcVT.isInteger() || SrcVT.isVector())
00640       continue;
00641 
00642     unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
00643     CurDAG->computeKnownBits(Src, KnownZero, KnownOne);
00644     FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, KnownZero, KnownOne);
00645   } while (!Worklist.empty());
00646 }
00647 
00648 void SelectionDAGISel::CodeGenAndEmitDAG() {
00649   std::string GroupName;
00650   if (TimePassesIsEnabled)
00651     GroupName = "Instruction Selection and Scheduling";
00652   std::string BlockName;
00653   int BlockNumber = -1;
00654   (void)BlockNumber;
00655 #ifdef NDEBUG
00656   if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
00657       ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
00658       ViewSUnitDAGs)
00659 #endif
00660   {
00661     BlockNumber = FuncInfo->MBB->getNumber();
00662     BlockName = MF->getName().str() + ":" +
00663                 FuncInfo->MBB->getBasicBlock()->getName().str();
00664   }
00665   DEBUG(dbgs() << "Initial selection DAG: BB#" << BlockNumber
00666         << " '" << BlockName << "'\n"; CurDAG->dump());
00667 
00668   if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
00669 
00670   // Run the DAG combiner in pre-legalize mode.
00671   {
00672     NamedRegionTimer T("DAG Combining 1", GroupName, TimePassesIsEnabled);
00673     CurDAG->Combine(BeforeLegalizeTypes, *AA, OptLevel);
00674   }
00675 
00676   DEBUG(dbgs() << "Optimized lowered selection DAG: BB#" << BlockNumber
00677         << " '" << BlockName << "'\n"; CurDAG->dump());
00678 
00679   // Second step, hack on the DAG until it only uses operations and types that
00680   // the target supports.
00681   if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
00682                                                BlockName);
00683 
00684   bool Changed;
00685   {
00686     NamedRegionTimer T("Type Legalization", GroupName, TimePassesIsEnabled);
00687     Changed = CurDAG->LegalizeTypes();
00688   }
00689 
00690   DEBUG(dbgs() << "Type-legalized selection DAG: BB#" << BlockNumber
00691         << " '" << BlockName << "'\n"; CurDAG->dump());
00692 
00693   CurDAG->NewNodesMustHaveLegalTypes = true;
00694 
00695   if (Changed) {
00696     if (ViewDAGCombineLT)
00697       CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
00698 
00699     // Run the DAG combiner in post-type-legalize mode.
00700     {
00701       NamedRegionTimer T("DAG Combining after legalize types", GroupName,
00702                          TimePassesIsEnabled);
00703       CurDAG->Combine(AfterLegalizeTypes, *AA, OptLevel);
00704     }
00705 
00706     DEBUG(dbgs() << "Optimized type-legalized selection DAG: BB#" << BlockNumber
00707           << " '" << BlockName << "'\n"; CurDAG->dump());
00708 
00709   }
00710 
00711   {
00712     NamedRegionTimer T("Vector Legalization", GroupName, TimePassesIsEnabled);
00713     Changed = CurDAG->LegalizeVectors();
00714   }
00715 
00716   if (Changed) {
00717     {
00718       NamedRegionTimer T("Type Legalization 2", GroupName, TimePassesIsEnabled);
00719       CurDAG->LegalizeTypes();
00720     }
00721 
00722     if (ViewDAGCombineLT)
00723       CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
00724 
00725     // Run the DAG combiner in post-type-legalize mode.
00726     {
00727       NamedRegionTimer T("DAG Combining after legalize vectors", GroupName,
00728                          TimePassesIsEnabled);
00729       CurDAG->Combine(AfterLegalizeVectorOps, *AA, OptLevel);
00730     }
00731 
00732     DEBUG(dbgs() << "Optimized vector-legalized selection DAG: BB#"
00733           << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump());
00734   }
00735 
00736   if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
00737 
00738   {
00739     NamedRegionTimer T("DAG Legalization", GroupName, TimePassesIsEnabled);
00740     CurDAG->Legalize();
00741   }
00742 
00743   DEBUG(dbgs() << "Legalized selection DAG: BB#" << BlockNumber
00744         << " '" << BlockName << "'\n"; CurDAG->dump());
00745 
00746   if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
00747 
00748   // Run the DAG combiner in post-legalize mode.
00749   {
00750     NamedRegionTimer T("DAG Combining 2", GroupName, TimePassesIsEnabled);
00751     CurDAG->Combine(AfterLegalizeDAG, *AA, OptLevel);
00752   }
00753 
00754   DEBUG(dbgs() << "Optimized legalized selection DAG: BB#" << BlockNumber
00755         << " '" << BlockName << "'\n"; CurDAG->dump());
00756 
00757   if (OptLevel != CodeGenOpt::None)
00758     ComputeLiveOutVRegInfo();
00759 
00760   if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
00761 
00762   // Third, instruction select all of the operations to machine code, adding the
00763   // code to the MachineBasicBlock.
00764   {
00765     NamedRegionTimer T("Instruction Selection", GroupName, TimePassesIsEnabled);
00766     DoInstructionSelection();
00767   }
00768 
00769   DEBUG(dbgs() << "Selected selection DAG: BB#" << BlockNumber
00770         << " '" << BlockName << "'\n"; CurDAG->dump());
00771 
00772   if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
00773 
00774   // Schedule machine code.
00775   ScheduleDAGSDNodes *Scheduler = CreateScheduler();
00776   {
00777     NamedRegionTimer T("Instruction Scheduling", GroupName,
00778                        TimePassesIsEnabled);
00779     Scheduler->Run(CurDAG, FuncInfo->MBB);
00780   }
00781 
00782   if (ViewSUnitDAGs) Scheduler->viewGraph();
00783 
00784   // Emit machine code to BB.  This can change 'BB' to the last block being
00785   // inserted into.
00786   MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
00787   {
00788     NamedRegionTimer T("Instruction Creation", GroupName, TimePassesIsEnabled);
00789 
00790     // FuncInfo->InsertPt is passed by reference and set to the end of the
00791     // scheduled instructions.
00792     LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
00793   }
00794 
00795   // If the block was split, make sure we update any references that are used to
00796   // update PHI nodes later on.
00797   if (FirstMBB != LastMBB)
00798     SDB->UpdateSplitBlock(FirstMBB, LastMBB);
00799 
00800   // Free the scheduler state.
00801   {
00802     NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName,
00803                        TimePassesIsEnabled);
00804     delete Scheduler;
00805   }
00806 
00807   // Free the SelectionDAG state, now that we're finished with it.
00808   CurDAG->clear();
00809 }
00810 
00811 namespace {
00812 /// ISelUpdater - helper class to handle updates of the instruction selection
00813 /// graph.
00814 class ISelUpdater : public SelectionDAG::DAGUpdateListener {
00815   SelectionDAG::allnodes_iterator &ISelPosition;
00816 public:
00817   ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
00818     : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
00819 
00820   /// NodeDeleted - Handle nodes deleted from the graph. If the node being
00821   /// deleted is the current ISelPosition node, update ISelPosition.
00822   ///
00823   void NodeDeleted(SDNode *N, SDNode *E) override {
00824     if (ISelPosition == SelectionDAG::allnodes_iterator(N))
00825       ++ISelPosition;
00826   }
00827 };
00828 } // end anonymous namespace
00829 
00830 void SelectionDAGISel::DoInstructionSelection() {
00831   DEBUG(dbgs() << "===== Instruction selection begins: BB#"
00832         << FuncInfo->MBB->getNumber()
00833         << " '" << FuncInfo->MBB->getName() << "'\n");
00834 
00835   PreprocessISelDAG();
00836 
00837   // Select target instructions for the DAG.
00838   {
00839     // Number all nodes with a topological order and set DAGSize.
00840     DAGSize = CurDAG->AssignTopologicalOrder();
00841 
00842     // Create a dummy node (which is not added to allnodes), that adds
00843     // a reference to the root node, preventing it from being deleted,
00844     // and tracking any changes of the root.
00845     HandleSDNode Dummy(CurDAG->getRoot());
00846     SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode());
00847     ++ISelPosition;
00848 
00849     // Make sure that ISelPosition gets properly updated when nodes are deleted
00850     // in calls made from this function.
00851     ISelUpdater ISU(*CurDAG, ISelPosition);
00852 
00853     // The AllNodes list is now topological-sorted. Visit the
00854     // nodes by starting at the end of the list (the root of the
00855     // graph) and preceding back toward the beginning (the entry
00856     // node).
00857     while (ISelPosition != CurDAG->allnodes_begin()) {
00858       SDNode *Node = --ISelPosition;
00859       // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
00860       // but there are currently some corner cases that it misses. Also, this
00861       // makes it theoretically possible to disable the DAGCombiner.
00862       if (Node->use_empty())
00863         continue;
00864 
00865       SDNode *ResNode = Select(Node);
00866 
00867       // FIXME: This is pretty gross.  'Select' should be changed to not return
00868       // anything at all and this code should be nuked with a tactical strike.
00869 
00870       // If node should not be replaced, continue with the next one.
00871       if (ResNode == Node || Node->getOpcode() == ISD::DELETED_NODE)
00872         continue;
00873       // Replace node.
00874       if (ResNode) {
00875         ReplaceUses(Node, ResNode);
00876       }
00877 
00878       // If after the replacement this node is not used any more,
00879       // remove this dead node.
00880       if (Node->use_empty()) // Don't delete EntryToken, etc.
00881         CurDAG->RemoveDeadNode(Node);
00882     }
00883 
00884     CurDAG->setRoot(Dummy.getValue());
00885   }
00886 
00887   DEBUG(dbgs() << "===== Instruction selection ends:\n");
00888 
00889   PostprocessISelDAG();
00890 }
00891 
00892 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
00893 /// do other setup for EH landing-pad blocks.
00894 void SelectionDAGISel::PrepareEHLandingPad() {
00895   MachineBasicBlock *MBB = FuncInfo->MBB;
00896 
00897   // Add a label to mark the beginning of the landing pad.  Deletion of the
00898   // landing pad can thus be detected via the MachineModuleInfo.
00899   MCSymbol *Label = MF->getMMI().addLandingPad(MBB);
00900 
00901   // Assign the call site to the landing pad's begin label.
00902   MF->getMMI().setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
00903 
00904   const MCInstrDesc &II = TM.getInstrInfo()->get(TargetOpcode::EH_LABEL);
00905   BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
00906     .addSym(Label);
00907 
00908   // Mark exception register as live in.
00909   const TargetLowering *TLI = getTargetLowering();
00910   const TargetRegisterClass *PtrRC = TLI->getRegClassFor(TLI->getPointerTy());
00911   if (unsigned Reg = TLI->getExceptionPointerRegister())
00912     FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
00913 
00914   // Mark exception selector register as live in.
00915   if (unsigned Reg = TLI->getExceptionSelectorRegister())
00916     FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
00917 }
00918 
00919 /// isFoldedOrDeadInstruction - Return true if the specified instruction is
00920 /// side-effect free and is either dead or folded into a generated instruction.
00921 /// Return false if it needs to be emitted.
00922 static bool isFoldedOrDeadInstruction(const Instruction *I,
00923                                       FunctionLoweringInfo *FuncInfo) {
00924   return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
00925          !isa<TerminatorInst>(I) && // Terminators aren't folded.
00926          !isa<DbgInfoIntrinsic>(I) &&  // Debug instructions aren't folded.
00927          !isa<LandingPadInst>(I) &&    // Landingpad instructions aren't folded.
00928          !FuncInfo->isExportedInst(I); // Exported instrs must be computed.
00929 }
00930 
00931 #ifndef NDEBUG
00932 // Collect per Instruction statistics for fast-isel misses.  Only those
00933 // instructions that cause the bail are accounted for.  It does not account for
00934 // instructions higher in the block.  Thus, summing the per instructions stats
00935 // will not add up to what is reported by NumFastIselFailures.
00936 static void collectFailStats(const Instruction *I) {
00937   switch (I->getOpcode()) {
00938   default: assert (0 && "<Invalid operator> ");
00939 
00940   // Terminators
00941   case Instruction::Ret:         NumFastIselFailRet++; return;
00942   case Instruction::Br:          NumFastIselFailBr++; return;
00943   case Instruction::Switch:      NumFastIselFailSwitch++; return;
00944   case Instruction::IndirectBr:  NumFastIselFailIndirectBr++; return;
00945   case Instruction::Invoke:      NumFastIselFailInvoke++; return;
00946   case Instruction::Resume:      NumFastIselFailResume++; return;
00947   case Instruction::Unreachable: NumFastIselFailUnreachable++; return;
00948 
00949   // Standard binary operators...
00950   case Instruction::Add:  NumFastIselFailAdd++; return;
00951   case Instruction::FAdd: NumFastIselFailFAdd++; return;
00952   case Instruction::Sub:  NumFastIselFailSub++; return;
00953   case Instruction::FSub: NumFastIselFailFSub++; return;
00954   case Instruction::Mul:  NumFastIselFailMul++; return;
00955   case Instruction::FMul: NumFastIselFailFMul++; return;
00956   case Instruction::UDiv: NumFastIselFailUDiv++; return;
00957   case Instruction::SDiv: NumFastIselFailSDiv++; return;
00958   case Instruction::FDiv: NumFastIselFailFDiv++; return;
00959   case Instruction::URem: NumFastIselFailURem++; return;
00960   case Instruction::SRem: NumFastIselFailSRem++; return;
00961   case Instruction::FRem: NumFastIselFailFRem++; return;
00962 
00963   // Logical operators...
00964   case Instruction::And: NumFastIselFailAnd++; return;
00965   case Instruction::Or:  NumFastIselFailOr++; return;
00966   case Instruction::Xor: NumFastIselFailXor++; return;
00967 
00968   // Memory instructions...
00969   case Instruction::Alloca:        NumFastIselFailAlloca++; return;
00970   case Instruction::Load:          NumFastIselFailLoad++; return;
00971   case Instruction::Store:         NumFastIselFailStore++; return;
00972   case Instruction::AtomicCmpXchg: NumFastIselFailAtomicCmpXchg++; return;
00973   case Instruction::AtomicRMW:     NumFastIselFailAtomicRMW++; return;
00974   case Instruction::Fence:         NumFastIselFailFence++; return;
00975   case Instruction::GetElementPtr: NumFastIselFailGetElementPtr++; return;
00976 
00977   // Convert instructions...
00978   case Instruction::Trunc:    NumFastIselFailTrunc++; return;
00979   case Instruction::ZExt:     NumFastIselFailZExt++; return;
00980   case Instruction::SExt:     NumFastIselFailSExt++; return;
00981   case Instruction::FPTrunc:  NumFastIselFailFPTrunc++; return;
00982   case Instruction::FPExt:    NumFastIselFailFPExt++; return;
00983   case Instruction::FPToUI:   NumFastIselFailFPToUI++; return;
00984   case Instruction::FPToSI:   NumFastIselFailFPToSI++; return;
00985   case Instruction::UIToFP:   NumFastIselFailUIToFP++; return;
00986   case Instruction::SIToFP:   NumFastIselFailSIToFP++; return;
00987   case Instruction::IntToPtr: NumFastIselFailIntToPtr++; return;
00988   case Instruction::PtrToInt: NumFastIselFailPtrToInt++; return;
00989   case Instruction::BitCast:  NumFastIselFailBitCast++; return;
00990 
00991   // Other instructions...
00992   case Instruction::ICmp:           NumFastIselFailICmp++; return;
00993   case Instruction::FCmp:           NumFastIselFailFCmp++; return;
00994   case Instruction::PHI:            NumFastIselFailPHI++; return;
00995   case Instruction::Select:         NumFastIselFailSelect++; return;
00996   case Instruction::Call: {
00997     if (auto const *Intrinsic = dyn_cast<IntrinsicInst>(I)) {
00998       switch (Intrinsic->getIntrinsicID()) {
00999       default:
01000         NumFastIselFailIntrinsicCall++; return;
01001       case Intrinsic::sadd_with_overflow:
01002         NumFastIselFailSAddWithOverflow++; return;
01003       case Intrinsic::uadd_with_overflow:
01004         NumFastIselFailUAddWithOverflow++; return;
01005       case Intrinsic::ssub_with_overflow:
01006         NumFastIselFailSSubWithOverflow++; return;
01007       case Intrinsic::usub_with_overflow:
01008         NumFastIselFailUSubWithOverflow++; return;
01009       case Intrinsic::smul_with_overflow:
01010         NumFastIselFailSMulWithOverflow++; return;
01011       case Intrinsic::umul_with_overflow:
01012         NumFastIselFailUMulWithOverflow++; return;
01013       case Intrinsic::frameaddress:
01014         NumFastIselFailFrameaddress++; return;
01015       case Intrinsic::sqrt:
01016           NumFastIselFailSqrt++; return;
01017       case Intrinsic::experimental_stackmap:
01018         NumFastIselFailStackMap++; return;
01019       case Intrinsic::experimental_patchpoint_void: // fall-through
01020       case Intrinsic::experimental_patchpoint_i64:
01021         NumFastIselFailPatchPoint++; return;
01022       }
01023     }
01024     NumFastIselFailCall++;
01025     return;
01026   }
01027   case Instruction::Shl:            NumFastIselFailShl++; return;
01028   case Instruction::LShr:           NumFastIselFailLShr++; return;
01029   case Instruction::AShr:           NumFastIselFailAShr++; return;
01030   case Instruction::VAArg:          NumFastIselFailVAArg++; return;
01031   case Instruction::ExtractElement: NumFastIselFailExtractElement++; return;
01032   case Instruction::InsertElement:  NumFastIselFailInsertElement++; return;
01033   case Instruction::ShuffleVector:  NumFastIselFailShuffleVector++; return;
01034   case Instruction::ExtractValue:   NumFastIselFailExtractValue++; return;
01035   case Instruction::InsertValue:    NumFastIselFailInsertValue++; return;
01036   case Instruction::LandingPad:     NumFastIselFailLandingPad++; return;
01037   }
01038 }
01039 #endif
01040 
01041 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
01042   // Initialize the Fast-ISel state, if needed.
01043   FastISel *FastIS = nullptr;
01044   if (TM.Options.EnableFastISel)
01045     FastIS = getTargetLowering()->createFastISel(*FuncInfo, LibInfo);
01046 
01047   // Iterate over all basic blocks in the function.
01048   ReversePostOrderTraversal<const Function*> RPOT(&Fn);
01049   for (ReversePostOrderTraversal<const Function*>::rpo_iterator
01050        I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
01051     const BasicBlock *LLVMBB = *I;
01052 
01053     if (OptLevel != CodeGenOpt::None) {
01054       bool AllPredsVisited = true;
01055       for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB);
01056            PI != PE; ++PI) {
01057         if (!FuncInfo->VisitedBBs.count(*PI)) {
01058           AllPredsVisited = false;
01059           break;
01060         }
01061       }
01062 
01063       if (AllPredsVisited) {
01064         for (BasicBlock::const_iterator I = LLVMBB->begin();
01065              const PHINode *PN = dyn_cast<PHINode>(I); ++I)
01066           FuncInfo->ComputePHILiveOutRegInfo(PN);
01067       } else {
01068         for (BasicBlock::const_iterator I = LLVMBB->begin();
01069              const PHINode *PN = dyn_cast<PHINode>(I); ++I)
01070           FuncInfo->InvalidatePHILiveOutRegInfo(PN);
01071       }
01072 
01073       FuncInfo->VisitedBBs.insert(LLVMBB);
01074     }
01075 
01076     BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHI();
01077     BasicBlock::const_iterator const End = LLVMBB->end();
01078     BasicBlock::const_iterator BI = End;
01079 
01080     FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
01081     FuncInfo->InsertPt = FuncInfo->MBB->getFirstNonPHI();
01082 
01083     // Setup an EH landing-pad block.
01084     FuncInfo->ExceptionPointerVirtReg = 0;
01085     FuncInfo->ExceptionSelectorVirtReg = 0;
01086     if (FuncInfo->MBB->isLandingPad())
01087       PrepareEHLandingPad();
01088 
01089     // Before doing SelectionDAG ISel, see if FastISel has been requested.
01090     if (FastIS) {
01091       FastIS->startNewBlock();
01092 
01093       // Emit code for any incoming arguments. This must happen before
01094       // beginning FastISel on the entry block.
01095       if (LLVMBB == &Fn.getEntryBlock()) {
01096         ++NumEntryBlocks;
01097 
01098         // Lower any arguments needed in this block if this is the entry block.
01099         if (!FastIS->LowerArguments()) {
01100           // Fast isel failed to lower these arguments
01101           ++NumFastIselFailLowerArguments;
01102           if (EnableFastISelAbortArgs)
01103             llvm_unreachable("FastISel didn't lower all arguments");
01104 
01105           // Use SelectionDAG argument lowering
01106           LowerArguments(Fn);
01107           CurDAG->setRoot(SDB->getControlRoot());
01108           SDB->clear();
01109           CodeGenAndEmitDAG();
01110         }
01111 
01112         // If we inserted any instructions at the beginning, make a note of
01113         // where they are, so we can be sure to emit subsequent instructions
01114         // after them.
01115         if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
01116           FastIS->setLastLocalValue(std::prev(FuncInfo->InsertPt));
01117         else
01118           FastIS->setLastLocalValue(nullptr);
01119       }
01120 
01121       unsigned NumFastIselRemaining = std::distance(Begin, End);
01122       // Do FastISel on as many instructions as possible.
01123       for (; BI != Begin; --BI) {
01124         const Instruction *Inst = std::prev(BI);
01125 
01126         // If we no longer require this instruction, skip it.
01127         if (isFoldedOrDeadInstruction(Inst, FuncInfo)) {
01128           --NumFastIselRemaining;
01129           continue;
01130         }
01131 
01132         // Bottom-up: reset the insert pos at the top, after any local-value
01133         // instructions.
01134         FastIS->recomputeInsertPt();
01135 
01136         // Try to select the instruction with FastISel.
01137         if (FastIS->SelectInstruction(Inst)) {
01138           --NumFastIselRemaining;
01139           ++NumFastIselSuccess;
01140           // If fast isel succeeded, skip over all the folded instructions, and
01141           // then see if there is a load right before the selected instructions.
01142           // Try to fold the load if so.
01143           const Instruction *BeforeInst = Inst;
01144           while (BeforeInst != Begin) {
01145             BeforeInst = std::prev(BasicBlock::const_iterator(BeforeInst));
01146             if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo))
01147               break;
01148           }
01149           if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
01150               BeforeInst->hasOneUse() &&
01151               FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
01152             // If we succeeded, don't re-select the load.
01153             BI = std::next(BasicBlock::const_iterator(BeforeInst));
01154             --NumFastIselRemaining;
01155             ++NumFastIselSuccess;
01156           }
01157           continue;
01158         }
01159 
01160 #ifndef NDEBUG
01161         if (EnableFastISelVerbose2)
01162           collectFailStats(Inst);
01163 #endif
01164 
01165         // Then handle certain instructions as single-LLVM-Instruction blocks.
01166         if (isa<CallInst>(Inst)) {
01167 
01168           if (EnableFastISelVerbose || EnableFastISelAbort) {
01169             dbgs() << "FastISel missed call: ";
01170             Inst->dump();
01171           }
01172 
01173           if (!Inst->getType()->isVoidTy() && !Inst->use_empty()) {
01174             unsigned &R = FuncInfo->ValueMap[Inst];
01175             if (!R)
01176               R = FuncInfo->CreateRegs(Inst->getType());
01177           }
01178 
01179           bool HadTailCall = false;
01180           MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
01181           SelectBasicBlock(Inst, BI, HadTailCall);
01182 
01183           // If the call was emitted as a tail call, we're done with the block.
01184           // We also need to delete any previously emitted instructions.
01185           if (HadTailCall) {
01186             FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
01187             --BI;
01188             break;
01189           }
01190 
01191           // Recompute NumFastIselRemaining as Selection DAG instruction
01192           // selection may have handled the call, input args, etc.
01193           unsigned RemainingNow = std::distance(Begin, BI);
01194           NumFastIselFailures += NumFastIselRemaining - RemainingNow;
01195           NumFastIselRemaining = RemainingNow;
01196           continue;
01197         }
01198 
01199         if (isa<TerminatorInst>(Inst) && !isa<BranchInst>(Inst)) {
01200           // Don't abort, and use a different message for terminator misses.
01201           NumFastIselFailures += NumFastIselRemaining;
01202           if (EnableFastISelVerbose || EnableFastISelAbort) {
01203             dbgs() << "FastISel missed terminator: ";
01204             Inst->dump();
01205           }
01206         } else {
01207           NumFastIselFailures += NumFastIselRemaining;
01208           if (EnableFastISelVerbose || EnableFastISelAbort) {
01209             dbgs() << "FastISel miss: ";
01210             Inst->dump();
01211           }
01212           if (EnableFastISelAbort)
01213             // The "fast" selector couldn't handle something and bailed.
01214             // For the purpose of debugging, just abort.
01215             llvm_unreachable("FastISel didn't select the entire block");
01216         }
01217         break;
01218       }
01219 
01220       FastIS->recomputeInsertPt();
01221     } else {
01222       // Lower any arguments needed in this block if this is the entry block.
01223       if (LLVMBB == &Fn.getEntryBlock()) {
01224         ++NumEntryBlocks;
01225         LowerArguments(Fn);
01226       }
01227     }
01228 
01229     if (Begin != BI)
01230       ++NumDAGBlocks;
01231     else
01232       ++NumFastIselBlocks;
01233 
01234     if (Begin != BI) {
01235       // Run SelectionDAG instruction selection on the remainder of the block
01236       // not handled by FastISel. If FastISel is not run, this is the entire
01237       // block.
01238       bool HadTailCall;
01239       SelectBasicBlock(Begin, BI, HadTailCall);
01240     }
01241 
01242     FinishBasicBlock();
01243     FuncInfo->PHINodesToUpdate.clear();
01244   }
01245 
01246   delete FastIS;
01247   SDB->clearDanglingDebugInfo();
01248   SDB->SPDescriptor.resetPerFunctionState();
01249 }
01250 
01251 /// Given that the input MI is before a partial terminator sequence TSeq, return
01252 /// true if M + TSeq also a partial terminator sequence.
01253 ///
01254 /// A Terminator sequence is a sequence of MachineInstrs which at this point in
01255 /// lowering copy vregs into physical registers, which are then passed into
01256 /// terminator instructors so we can satisfy ABI constraints. A partial
01257 /// terminator sequence is an improper subset of a terminator sequence (i.e. it
01258 /// may be the whole terminator sequence).
01259 static bool MIIsInTerminatorSequence(const MachineInstr *MI) {
01260   // If we do not have a copy or an implicit def, we return true if and only if
01261   // MI is a debug value.
01262   if (!MI->isCopy() && !MI->isImplicitDef())
01263     // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the
01264     // physical registers if there is debug info associated with the terminator
01265     // of our mbb. We want to include said debug info in our terminator
01266     // sequence, so we return true in that case.
01267     return MI->isDebugValue();
01268 
01269   // We have left the terminator sequence if we are not doing one of the
01270   // following:
01271   //
01272   // 1. Copying a vreg into a physical register.
01273   // 2. Copying a vreg into a vreg.
01274   // 3. Defining a register via an implicit def.
01275 
01276   // OPI should always be a register definition...
01277   MachineInstr::const_mop_iterator OPI = MI->operands_begin();
01278   if (!OPI->isReg() || !OPI->isDef())
01279     return false;
01280 
01281   // Defining any register via an implicit def is always ok.
01282   if (MI->isImplicitDef())
01283     return true;
01284 
01285   // Grab the copy source...
01286   MachineInstr::const_mop_iterator OPI2 = OPI;
01287   ++OPI2;
01288   assert(OPI2 != MI->operands_end()
01289          && "Should have a copy implying we should have 2 arguments.");
01290 
01291   // Make sure that the copy dest is not a vreg when the copy source is a
01292   // physical register.
01293   if (!OPI2->isReg() ||
01294       (!TargetRegisterInfo::isPhysicalRegister(OPI->getReg()) &&
01295        TargetRegisterInfo::isPhysicalRegister(OPI2->getReg())))
01296     return false;
01297 
01298   return true;
01299 }
01300 
01301 /// Find the split point at which to splice the end of BB into its success stack
01302 /// protector check machine basic block.
01303 ///
01304 /// On many platforms, due to ABI constraints, terminators, even before register
01305 /// allocation, use physical registers. This creates an issue for us since
01306 /// physical registers at this point can not travel across basic
01307 /// blocks. Luckily, selectiondag always moves physical registers into vregs
01308 /// when they enter functions and moves them through a sequence of copies back
01309 /// into the physical registers right before the terminator creating a
01310 /// ``Terminator Sequence''. This function is searching for the beginning of the
01311 /// terminator sequence so that we can ensure that we splice off not just the
01312 /// terminator, but additionally the copies that move the vregs into the
01313 /// physical registers.
01314 static MachineBasicBlock::iterator
01315 FindSplitPointForStackProtector(MachineBasicBlock *BB, DebugLoc DL) {
01316   MachineBasicBlock::iterator SplitPoint = BB->getFirstTerminator();
01317   //
01318   if (SplitPoint == BB->begin())
01319     return SplitPoint;
01320 
01321   MachineBasicBlock::iterator Start = BB->begin();
01322   MachineBasicBlock::iterator Previous = SplitPoint;
01323   --Previous;
01324 
01325   while (MIIsInTerminatorSequence(Previous)) {
01326     SplitPoint = Previous;
01327     if (Previous == Start)
01328       break;
01329     --Previous;
01330   }
01331 
01332   return SplitPoint;
01333 }
01334 
01335 void
01336 SelectionDAGISel::FinishBasicBlock() {
01337 
01338   DEBUG(dbgs() << "Total amount of phi nodes to update: "
01339                << FuncInfo->PHINodesToUpdate.size() << "\n";
01340         for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i)
01341           dbgs() << "Node " << i << " : ("
01342                  << FuncInfo->PHINodesToUpdate[i].first
01343                  << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
01344 
01345   const bool MustUpdatePHINodes = SDB->SwitchCases.empty() &&
01346                                   SDB->JTCases.empty() &&
01347                                   SDB->BitTestCases.empty();
01348 
01349   // Next, now that we know what the last MBB the LLVM BB expanded is, update
01350   // PHI nodes in successors.
01351   if (MustUpdatePHINodes) {
01352     for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
01353       MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
01354       assert(PHI->isPHI() &&
01355              "This is not a machine PHI node that we are updating!");
01356       if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
01357         continue;
01358       PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
01359     }
01360   }
01361 
01362   // Handle stack protector.
01363   if (SDB->SPDescriptor.shouldEmitStackProtector()) {
01364     MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
01365     MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB();
01366 
01367     // Find the split point to split the parent mbb. At the same time copy all
01368     // physical registers used in the tail of parent mbb into virtual registers
01369     // before the split point and back into physical registers after the split
01370     // point. This prevents us needing to deal with Live-ins and many other
01371     // register allocation issues caused by us splitting the parent mbb. The
01372     // register allocator will clean up said virtual copies later on.
01373     MachineBasicBlock::iterator SplitPoint =
01374       FindSplitPointForStackProtector(ParentMBB, SDB->getCurDebugLoc());
01375 
01376     // Splice the terminator of ParentMBB into SuccessMBB.
01377     SuccessMBB->splice(SuccessMBB->end(), ParentMBB,
01378                        SplitPoint,
01379                        ParentMBB->end());
01380 
01381     // Add compare/jump on neq/jump to the parent BB.
01382     FuncInfo->MBB = ParentMBB;
01383     FuncInfo->InsertPt = ParentMBB->end();
01384     SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
01385     CurDAG->setRoot(SDB->getRoot());
01386     SDB->clear();
01387     CodeGenAndEmitDAG();
01388 
01389     // CodeGen Failure MBB if we have not codegened it yet.
01390     MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB();
01391     if (!FailureMBB->size()) {
01392       FuncInfo->MBB = FailureMBB;
01393       FuncInfo->InsertPt = FailureMBB->end();
01394       SDB->visitSPDescriptorFailure(SDB->SPDescriptor);
01395       CurDAG->setRoot(SDB->getRoot());
01396       SDB->clear();
01397       CodeGenAndEmitDAG();
01398     }
01399 
01400     // Clear the Per-BB State.
01401     SDB->SPDescriptor.resetPerBBState();
01402   }
01403 
01404   // If we updated PHI Nodes, return early.
01405   if (MustUpdatePHINodes)
01406     return;
01407 
01408   for (unsigned i = 0, e = SDB->BitTestCases.size(); i != e; ++i) {
01409     // Lower header first, if it wasn't already lowered
01410     if (!SDB->BitTestCases[i].Emitted) {
01411       // Set the current basic block to the mbb we wish to insert the code into
01412       FuncInfo->MBB = SDB->BitTestCases[i].Parent;
01413       FuncInfo->InsertPt = FuncInfo->MBB->end();
01414       // Emit the code
01415       SDB->visitBitTestHeader(SDB->BitTestCases[i], FuncInfo->MBB);
01416       CurDAG->setRoot(SDB->getRoot());
01417       SDB->clear();
01418       CodeGenAndEmitDAG();
01419     }
01420 
01421     uint32_t UnhandledWeight = 0;
01422     for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j)
01423       UnhandledWeight += SDB->BitTestCases[i].Cases[j].ExtraWeight;
01424 
01425     for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j) {
01426       UnhandledWeight -= SDB->BitTestCases[i].Cases[j].ExtraWeight;
01427       // Set the current basic block to the mbb we wish to insert the code into
01428       FuncInfo->MBB = SDB->BitTestCases[i].Cases[j].ThisBB;
01429       FuncInfo->InsertPt = FuncInfo->MBB->end();
01430       // Emit the code
01431       if (j+1 != ej)
01432         SDB->visitBitTestCase(SDB->BitTestCases[i],
01433                               SDB->BitTestCases[i].Cases[j+1].ThisBB,
01434                               UnhandledWeight,
01435                               SDB->BitTestCases[i].Reg,
01436                               SDB->BitTestCases[i].Cases[j],
01437                               FuncInfo->MBB);
01438       else
01439         SDB->visitBitTestCase(SDB->BitTestCases[i],
01440                               SDB->BitTestCases[i].Default,
01441                               UnhandledWeight,
01442                               SDB->BitTestCases[i].Reg,
01443                               SDB->BitTestCases[i].Cases[j],
01444                               FuncInfo->MBB);
01445 
01446 
01447       CurDAG->setRoot(SDB->getRoot());
01448       SDB->clear();
01449       CodeGenAndEmitDAG();
01450     }
01451 
01452     // Update PHI Nodes
01453     for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
01454          pi != pe; ++pi) {
01455       MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
01456       MachineBasicBlock *PHIBB = PHI->getParent();
01457       assert(PHI->isPHI() &&
01458              "This is not a machine PHI node that we are updating!");
01459       // This is "default" BB. We have two jumps to it. From "header" BB and
01460       // from last "case" BB.
01461       if (PHIBB == SDB->BitTestCases[i].Default)
01462         PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
01463            .addMBB(SDB->BitTestCases[i].Parent)
01464            .addReg(FuncInfo->PHINodesToUpdate[pi].second)
01465            .addMBB(SDB->BitTestCases[i].Cases.back().ThisBB);
01466       // One of "cases" BB.
01467       for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size();
01468            j != ej; ++j) {
01469         MachineBasicBlock* cBB = SDB->BitTestCases[i].Cases[j].ThisBB;
01470         if (cBB->isSuccessor(PHIBB))
01471           PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB);
01472       }
01473     }
01474   }
01475   SDB->BitTestCases.clear();
01476 
01477   // If the JumpTable record is filled in, then we need to emit a jump table.
01478   // Updating the PHI nodes is tricky in this case, since we need to determine
01479   // whether the PHI is a successor of the range check MBB or the jump table MBB
01480   for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
01481     // Lower header first, if it wasn't already lowered
01482     if (!SDB->JTCases[i].first.Emitted) {
01483       // Set the current basic block to the mbb we wish to insert the code into
01484       FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB;
01485       FuncInfo->InsertPt = FuncInfo->MBB->end();
01486       // Emit the code
01487       SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first,
01488                                 FuncInfo->MBB);
01489       CurDAG->setRoot(SDB->getRoot());
01490       SDB->clear();
01491       CodeGenAndEmitDAG();
01492     }
01493 
01494     // Set the current basic block to the mbb we wish to insert the code into
01495     FuncInfo->MBB = SDB->JTCases[i].second.MBB;
01496     FuncInfo->InsertPt = FuncInfo->MBB->end();
01497     // Emit the code
01498     SDB->visitJumpTable(SDB->JTCases[i].second);
01499     CurDAG->setRoot(SDB->getRoot());
01500     SDB->clear();
01501     CodeGenAndEmitDAG();
01502 
01503     // Update PHI Nodes
01504     for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
01505          pi != pe; ++pi) {
01506       MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
01507       MachineBasicBlock *PHIBB = PHI->getParent();
01508       assert(PHI->isPHI() &&
01509              "This is not a machine PHI node that we are updating!");
01510       // "default" BB. We can go there only from header BB.
01511       if (PHIBB == SDB->JTCases[i].second.Default)
01512         PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
01513            .addMBB(SDB->JTCases[i].first.HeaderBB);
01514       // JT BB. Just iterate over successors here
01515       if (FuncInfo->MBB->isSuccessor(PHIBB))
01516         PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
01517     }
01518   }
01519   SDB->JTCases.clear();
01520 
01521   // If the switch block involved a branch to one of the actual successors, we
01522   // need to update PHI nodes in that block.
01523   for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
01524     MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
01525     assert(PHI->isPHI() &&
01526            "This is not a machine PHI node that we are updating!");
01527     if (FuncInfo->MBB->isSuccessor(PHI->getParent()))
01528       PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
01529   }
01530 
01531   // If we generated any switch lowering information, build and codegen any
01532   // additional DAGs necessary.
01533   for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
01534     // Set the current basic block to the mbb we wish to insert the code into
01535     FuncInfo->MBB = SDB->SwitchCases[i].ThisBB;
01536     FuncInfo->InsertPt = FuncInfo->MBB->end();
01537 
01538     // Determine the unique successors.
01539     SmallVector<MachineBasicBlock *, 2> Succs;
01540     Succs.push_back(SDB->SwitchCases[i].TrueBB);
01541     if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB)
01542       Succs.push_back(SDB->SwitchCases[i].FalseBB);
01543 
01544     // Emit the code. Note that this could result in FuncInfo->MBB being split.
01545     SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB);
01546     CurDAG->setRoot(SDB->getRoot());
01547     SDB->clear();
01548     CodeGenAndEmitDAG();
01549 
01550     // Remember the last block, now that any splitting is done, for use in
01551     // populating PHI nodes in successors.
01552     MachineBasicBlock *ThisBB = FuncInfo->MBB;
01553 
01554     // Handle any PHI nodes in successors of this chunk, as if we were coming
01555     // from the original BB before switch expansion.  Note that PHI nodes can
01556     // occur multiple times in PHINodesToUpdate.  We have to be very careful to
01557     // handle them the right number of times.
01558     for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
01559       FuncInfo->MBB = Succs[i];
01560       FuncInfo->InsertPt = FuncInfo->MBB->end();
01561       // FuncInfo->MBB may have been removed from the CFG if a branch was
01562       // constant folded.
01563       if (ThisBB->isSuccessor(FuncInfo->MBB)) {
01564         for (MachineBasicBlock::iterator
01565              MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
01566              MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
01567           MachineInstrBuilder PHI(*MF, MBBI);
01568           // This value for this PHI node is recorded in PHINodesToUpdate.
01569           for (unsigned pn = 0; ; ++pn) {
01570             assert(pn != FuncInfo->PHINodesToUpdate.size() &&
01571                    "Didn't find PHI entry!");
01572             if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
01573               PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
01574               break;
01575             }
01576           }
01577         }
01578       }
01579     }
01580   }
01581   SDB->SwitchCases.clear();
01582 }
01583 
01584 
01585 /// Create the scheduler. If a specific scheduler was specified
01586 /// via the SchedulerRegistry, use it, otherwise select the
01587 /// one preferred by the target.
01588 ///
01589 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
01590   RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
01591 
01592   if (!Ctor) {
01593     Ctor = ISHeuristic;
01594     RegisterScheduler::setDefault(Ctor);
01595   }
01596 
01597   return Ctor(this, OptLevel);
01598 }
01599 
01600 //===----------------------------------------------------------------------===//
01601 // Helper functions used by the generated instruction selector.
01602 //===----------------------------------------------------------------------===//
01603 // Calls to these methods are generated by tblgen.
01604 
01605 /// CheckAndMask - The isel is trying to match something like (and X, 255).  If
01606 /// the dag combiner simplified the 255, we still want to match.  RHS is the
01607 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
01608 /// specified in the .td file (e.g. 255).
01609 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
01610                                     int64_t DesiredMaskS) const {
01611   const APInt &ActualMask = RHS->getAPIntValue();
01612   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
01613 
01614   // If the actual mask exactly matches, success!
01615   if (ActualMask == DesiredMask)
01616     return true;
01617 
01618   // If the actual AND mask is allowing unallowed bits, this doesn't match.
01619   if (ActualMask.intersects(~DesiredMask))
01620     return false;
01621 
01622   // Otherwise, the DAG Combiner may have proven that the value coming in is
01623   // either already zero or is not demanded.  Check for known zero input bits.
01624   APInt NeededMask = DesiredMask & ~ActualMask;
01625   if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
01626     return true;
01627 
01628   // TODO: check to see if missing bits are just not demanded.
01629 
01630   // Otherwise, this pattern doesn't match.
01631   return false;
01632 }
01633 
01634 /// CheckOrMask - The isel is trying to match something like (or X, 255).  If
01635 /// the dag combiner simplified the 255, we still want to match.  RHS is the
01636 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
01637 /// specified in the .td file (e.g. 255).
01638 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
01639                                    int64_t DesiredMaskS) const {
01640   const APInt &ActualMask = RHS->getAPIntValue();
01641   const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
01642 
01643   // If the actual mask exactly matches, success!
01644   if (ActualMask == DesiredMask)
01645     return true;
01646 
01647   // If the actual AND mask is allowing unallowed bits, this doesn't match.
01648   if (ActualMask.intersects(~DesiredMask))
01649     return false;
01650 
01651   // Otherwise, the DAG Combiner may have proven that the value coming in is
01652   // either already zero or is not demanded.  Check for known zero input bits.
01653   APInt NeededMask = DesiredMask & ~ActualMask;
01654 
01655   APInt KnownZero, KnownOne;
01656   CurDAG->computeKnownBits(LHS, KnownZero, KnownOne);
01657 
01658   // If all the missing bits in the or are already known to be set, match!
01659   if ((NeededMask & KnownOne) == NeededMask)
01660     return true;
01661 
01662   // TODO: check to see if missing bits are just not demanded.
01663 
01664   // Otherwise, this pattern doesn't match.
01665   return false;
01666 }
01667 
01668 
01669 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
01670 /// by tblgen.  Others should not call it.
01671 void SelectionDAGISel::
01672 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
01673   std::vector<SDValue> InOps;
01674   std::swap(InOps, Ops);
01675 
01676   Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
01677   Ops.push_back(InOps[InlineAsm::Op_AsmString]);  // 1
01678   Ops.push_back(InOps[InlineAsm::Op_MDNode]);     // 2, !srcloc
01679   Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]);  // 3 (SideEffect, AlignStack)
01680 
01681   unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
01682   if (InOps[e-1].getValueType() == MVT::Glue)
01683     --e;  // Don't process a glue operand if it is here.
01684 
01685   while (i != e) {
01686     unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
01687     if (!InlineAsm::isMemKind(Flags)) {
01688       // Just skip over this operand, copying the operands verbatim.
01689       Ops.insert(Ops.end(), InOps.begin()+i,
01690                  InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
01691       i += InlineAsm::getNumOperandRegisters(Flags) + 1;
01692     } else {
01693       assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
01694              "Memory operand with multiple values?");
01695       // Otherwise, this is a memory operand.  Ask the target to select it.
01696       std::vector<SDValue> SelOps;
01697       if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps))
01698         report_fatal_error("Could not match memory address.  Inline asm"
01699                            " failure!");
01700 
01701       // Add this to the output node.
01702       unsigned NewFlags =
01703         InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
01704       Ops.push_back(CurDAG->getTargetConstant(NewFlags, MVT::i32));
01705       Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
01706       i += 2;
01707     }
01708   }
01709 
01710   // Add the glue input back if present.
01711   if (e != InOps.size())
01712     Ops.push_back(InOps.back());
01713 }
01714 
01715 /// findGlueUse - Return use of MVT::Glue value produced by the specified
01716 /// SDNode.
01717 ///
01718 static SDNode *findGlueUse(SDNode *N) {
01719   unsigned FlagResNo = N->getNumValues()-1;
01720   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
01721     SDUse &Use = I.getUse();
01722     if (Use.getResNo() == FlagResNo)
01723       return Use.getUser();
01724   }
01725   return nullptr;
01726 }
01727 
01728 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
01729 /// This function recursively traverses up the operand chain, ignoring
01730 /// certain nodes.
01731 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
01732                           SDNode *Root, SmallPtrSet<SDNode*, 16> &Visited,
01733                           bool IgnoreChains) {
01734   // The NodeID's are given uniques ID's where a node ID is guaranteed to be
01735   // greater than all of its (recursive) operands.  If we scan to a point where
01736   // 'use' is smaller than the node we're scanning for, then we know we will
01737   // never find it.
01738   //
01739   // The Use may be -1 (unassigned) if it is a newly allocated node.  This can
01740   // happen because we scan down to newly selected nodes in the case of glue
01741   // uses.
01742   if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1))
01743     return false;
01744 
01745   // Don't revisit nodes if we already scanned it and didn't fail, we know we
01746   // won't fail if we scan it again.
01747   if (!Visited.insert(Use))
01748     return false;
01749 
01750   for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
01751     // Ignore chain uses, they are validated by HandleMergeInputChains.
01752     if (Use->getOperand(i).getValueType() == MVT::Other && IgnoreChains)
01753       continue;
01754 
01755     SDNode *N = Use->getOperand(i).getNode();
01756     if (N == Def) {
01757       if (Use == ImmedUse || Use == Root)
01758         continue;  // We are not looking for immediate use.
01759       assert(N != Root);
01760       return true;
01761     }
01762 
01763     // Traverse up the operand chain.
01764     if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains))
01765       return true;
01766   }
01767   return false;
01768 }
01769 
01770 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
01771 /// operand node N of U during instruction selection that starts at Root.
01772 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
01773                                           SDNode *Root) const {
01774   if (OptLevel == CodeGenOpt::None) return false;
01775   return N.hasOneUse();
01776 }
01777 
01778 /// IsLegalToFold - Returns true if the specific operand node N of
01779 /// U can be folded during instruction selection that starts at Root.
01780 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
01781                                      CodeGenOpt::Level OptLevel,
01782                                      bool IgnoreChains) {
01783   if (OptLevel == CodeGenOpt::None) return false;
01784 
01785   // If Root use can somehow reach N through a path that that doesn't contain
01786   // U then folding N would create a cycle. e.g. In the following
01787   // diagram, Root can reach N through X. If N is folded into into Root, then
01788   // X is both a predecessor and a successor of U.
01789   //
01790   //          [N*]           //
01791   //         ^   ^           //
01792   //        /     \          //
01793   //      [U*]    [X]?       //
01794   //        ^     ^          //
01795   //         \   /           //
01796   //          \ /            //
01797   //         [Root*]         //
01798   //
01799   // * indicates nodes to be folded together.
01800   //
01801   // If Root produces glue, then it gets (even more) interesting. Since it
01802   // will be "glued" together with its glue use in the scheduler, we need to
01803   // check if it might reach N.
01804   //
01805   //          [N*]           //
01806   //         ^   ^           //
01807   //        /     \          //
01808   //      [U*]    [X]?       //
01809   //        ^       ^        //
01810   //         \       \       //
01811   //          \      |       //
01812   //         [Root*] |       //
01813   //          ^      |       //
01814   //          f      |       //
01815   //          |      /       //
01816   //         [Y]    /        //
01817   //           ^   /         //
01818   //           f  /          //
01819   //           | /           //
01820   //          [GU]           //
01821   //
01822   // If GU (glue use) indirectly reaches N (the load), and Root folds N
01823   // (call it Fold), then X is a predecessor of GU and a successor of
01824   // Fold. But since Fold and GU are glued together, this will create
01825   // a cycle in the scheduling graph.
01826 
01827   // If the node has glue, walk down the graph to the "lowest" node in the
01828   // glueged set.
01829   EVT VT = Root->getValueType(Root->getNumValues()-1);
01830   while (VT == MVT::Glue) {
01831     SDNode *GU = findGlueUse(Root);
01832     if (!GU)
01833       break;
01834     Root = GU;
01835     VT = Root->getValueType(Root->getNumValues()-1);
01836 
01837     // If our query node has a glue result with a use, we've walked up it.  If
01838     // the user (which has already been selected) has a chain or indirectly uses
01839     // the chain, our WalkChainUsers predicate will not consider it.  Because of
01840     // this, we cannot ignore chains in this predicate.
01841     IgnoreChains = false;
01842   }
01843 
01844 
01845   SmallPtrSet<SDNode*, 16> Visited;
01846   return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
01847 }
01848 
01849 SDNode *SelectionDAGISel::Select_INLINEASM(SDNode *N) {
01850   std::vector<SDValue> Ops(N->op_begin(), N->op_end());
01851   SelectInlineAsmMemoryOperands(Ops);
01852 
01853   EVT VTs[] = { MVT::Other, MVT::Glue };
01854   SDValue New = CurDAG->getNode(ISD::INLINEASM, SDLoc(N), VTs, Ops);
01855   New->setNodeId(-1);
01856   return New.getNode();
01857 }
01858 
01859 SDNode
01860 *SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) {
01861   SDLoc dl(Op);
01862   MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(0));
01863   const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0));
01864   unsigned Reg = getTargetLowering()->getRegisterByName(
01865                  RegStr->getString().data(), Op->getValueType(0));
01866   SDValue New = CurDAG->getCopyFromReg(
01867                         CurDAG->getEntryNode(), dl, Reg, Op->getValueType(0));
01868   New->setNodeId(-1);
01869   return New.getNode();
01870 }
01871 
01872 SDNode
01873 *SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) {
01874   SDLoc dl(Op);
01875   MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1));
01876   const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0));
01877   unsigned Reg = getTargetLowering()->getRegisterByName(
01878                  RegStr->getString().data(), Op->getOperand(2).getValueType());
01879   SDValue New = CurDAG->getCopyToReg(
01880                         CurDAG->getEntryNode(), dl, Reg, Op->getOperand(2));
01881   New->setNodeId(-1);
01882   return New.getNode();
01883 }
01884 
01885 
01886 
01887 SDNode *SelectionDAGISel::Select_UNDEF(SDNode *N) {
01888   return CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF,N->getValueType(0));
01889 }
01890 
01891 /// GetVBR - decode a vbr encoding whose top bit is set.
01892 LLVM_ATTRIBUTE_ALWAYS_INLINE static uint64_t
01893 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
01894   assert(Val >= 128 && "Not a VBR");
01895   Val &= 127;  // Remove first vbr bit.
01896 
01897   unsigned Shift = 7;
01898   uint64_t NextBits;
01899   do {
01900     NextBits = MatcherTable[Idx++];
01901     Val |= (NextBits&127) << Shift;
01902     Shift += 7;
01903   } while (NextBits & 128);
01904 
01905   return Val;
01906 }
01907 
01908 
01909 /// UpdateChainsAndGlue - When a match is complete, this method updates uses of
01910 /// interior glue and chain results to use the new glue and chain results.
01911 void SelectionDAGISel::
01912 UpdateChainsAndGlue(SDNode *NodeToMatch, SDValue InputChain,
01913                     const SmallVectorImpl<SDNode*> &ChainNodesMatched,
01914                     SDValue InputGlue,
01915                     const SmallVectorImpl<SDNode*> &GlueResultNodesMatched,
01916                     bool isMorphNodeTo) {
01917   SmallVector<SDNode*, 4> NowDeadNodes;
01918 
01919   // Now that all the normal results are replaced, we replace the chain and
01920   // glue results if present.
01921   if (!ChainNodesMatched.empty()) {
01922     assert(InputChain.getNode() &&
01923            "Matched input chains but didn't produce a chain");
01924     // Loop over all of the nodes we matched that produced a chain result.
01925     // Replace all the chain results with the final chain we ended up with.
01926     for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
01927       SDNode *ChainNode = ChainNodesMatched[i];
01928 
01929       // If this node was already deleted, don't look at it.
01930       if (ChainNode->getOpcode() == ISD::DELETED_NODE)
01931         continue;
01932 
01933       // Don't replace the results of the root node if we're doing a
01934       // MorphNodeTo.
01935       if (ChainNode == NodeToMatch && isMorphNodeTo)
01936         continue;
01937 
01938       SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
01939       if (ChainVal.getValueType() == MVT::Glue)
01940         ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
01941       assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
01942       CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain);
01943 
01944       // If the node became dead and we haven't already seen it, delete it.
01945       if (ChainNode->use_empty() &&
01946           !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
01947         NowDeadNodes.push_back(ChainNode);
01948     }
01949   }
01950 
01951   // If the result produces glue, update any glue results in the matched
01952   // pattern with the glue result.
01953   if (InputGlue.getNode()) {
01954     // Handle any interior nodes explicitly marked.
01955     for (unsigned i = 0, e = GlueResultNodesMatched.size(); i != e; ++i) {
01956       SDNode *FRN = GlueResultNodesMatched[i];
01957 
01958       // If this node was already deleted, don't look at it.
01959       if (FRN->getOpcode() == ISD::DELETED_NODE)
01960         continue;
01961 
01962       assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Glue &&
01963              "Doesn't have a glue result");
01964       CurDAG->ReplaceAllUsesOfValueWith(SDValue(FRN, FRN->getNumValues()-1),
01965                                         InputGlue);
01966 
01967       // If the node became dead and we haven't already seen it, delete it.
01968       if (FRN->use_empty() &&
01969           !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), FRN))
01970         NowDeadNodes.push_back(FRN);
01971     }
01972   }
01973 
01974   if (!NowDeadNodes.empty())
01975     CurDAG->RemoveDeadNodes(NowDeadNodes);
01976 
01977   DEBUG(dbgs() << "ISEL: Match complete!\n");
01978 }
01979 
01980 enum ChainResult {
01981   CR_Simple,
01982   CR_InducesCycle,
01983   CR_LeadsToInteriorNode
01984 };
01985 
01986 /// WalkChainUsers - Walk down the users of the specified chained node that is
01987 /// part of the pattern we're matching, looking at all of the users we find.
01988 /// This determines whether something is an interior node, whether we have a
01989 /// non-pattern node in between two pattern nodes (which prevent folding because
01990 /// it would induce a cycle) and whether we have a TokenFactor node sandwiched
01991 /// between pattern nodes (in which case the TF becomes part of the pattern).
01992 ///
01993 /// The walk we do here is guaranteed to be small because we quickly get down to
01994 /// already selected nodes "below" us.
01995 static ChainResult
01996 WalkChainUsers(const SDNode *ChainedNode,
01997                SmallVectorImpl<SDNode*> &ChainedNodesInPattern,
01998                SmallVectorImpl<SDNode*> &InteriorChainedNodes) {
01999   ChainResult Result = CR_Simple;
02000 
02001   for (SDNode::use_iterator UI = ChainedNode->use_begin(),
02002          E = ChainedNode->use_end(); UI != E; ++UI) {
02003     // Make sure the use is of the chain, not some other value we produce.
02004     if (UI.getUse().getValueType() != MVT::Other) continue;
02005 
02006     SDNode *User = *UI;
02007 
02008     if (User->getOpcode() == ISD::HANDLENODE)  // Root of the graph.
02009       continue;
02010 
02011     // If we see an already-selected machine node, then we've gone beyond the
02012     // pattern that we're selecting down into the already selected chunk of the
02013     // DAG.
02014     unsigned UserOpcode = User->getOpcode();
02015     if (User->isMachineOpcode() ||
02016         UserOpcode == ISD::CopyToReg ||
02017         UserOpcode == ISD::CopyFromReg ||
02018         UserOpcode == ISD::INLINEASM ||
02019         UserOpcode == ISD::EH_LABEL ||
02020         UserOpcode == ISD::LIFETIME_START ||
02021         UserOpcode == ISD::LIFETIME_END) {
02022       // If their node ID got reset to -1 then they've already been selected.
02023       // Treat them like a MachineOpcode.
02024       if (User->getNodeId() == -1)
02025         continue;
02026     }
02027 
02028     // If we have a TokenFactor, we handle it specially.
02029     if (User->getOpcode() != ISD::TokenFactor) {
02030       // If the node isn't a token factor and isn't part of our pattern, then it
02031       // must be a random chained node in between two nodes we're selecting.
02032       // This happens when we have something like:
02033       //   x = load ptr
02034       //   call
02035       //   y = x+4
02036       //   store y -> ptr
02037       // Because we structurally match the load/store as a read/modify/write,
02038       // but the call is chained between them.  We cannot fold in this case
02039       // because it would induce a cycle in the graph.
02040       if (!std::count(ChainedNodesInPattern.begin(),
02041                       ChainedNodesInPattern.end(), User))
02042         return CR_InducesCycle;
02043 
02044       // Otherwise we found a node that is part of our pattern.  For example in:
02045       //   x = load ptr
02046       //   y = x+4
02047       //   store y -> ptr
02048       // This would happen when we're scanning down from the load and see the
02049       // store as a user.  Record that there is a use of ChainedNode that is
02050       // part of the pattern and keep scanning uses.
02051       Result = CR_LeadsToInteriorNode;
02052       InteriorChainedNodes.push_back(User);
02053       continue;
02054     }
02055 
02056     // If we found a TokenFactor, there are two cases to consider: first if the
02057     // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
02058     // uses of the TF are in our pattern) we just want to ignore it.  Second,
02059     // the TokenFactor can be sandwiched in between two chained nodes, like so:
02060     //     [Load chain]
02061     //         ^
02062     //         |
02063     //       [Load]
02064     //       ^    ^
02065     //       |    \                    DAG's like cheese
02066     //      /       \                       do you?
02067     //     /         |
02068     // [TokenFactor] [Op]
02069     //     ^          ^
02070     //     |          |
02071     //      \        /
02072     //       \      /
02073     //       [Store]
02074     //
02075     // In this case, the TokenFactor becomes part of our match and we rewrite it
02076     // as a new TokenFactor.
02077     //
02078     // To distinguish these two cases, do a recursive walk down the uses.
02079     switch (WalkChainUsers(User, ChainedNodesInPattern, InteriorChainedNodes)) {
02080     case CR_Simple:
02081       // If the uses of the TokenFactor are just already-selected nodes, ignore
02082       // it, it is "below" our pattern.
02083       continue;
02084     case CR_InducesCycle:
02085       // If the uses of the TokenFactor lead to nodes that are not part of our
02086       // pattern that are not selected, folding would turn this into a cycle,
02087       // bail out now.
02088       return CR_InducesCycle;
02089     case CR_LeadsToInteriorNode:
02090       break;  // Otherwise, keep processing.
02091     }
02092 
02093     // Okay, we know we're in the interesting interior case.  The TokenFactor
02094     // is now going to be considered part of the pattern so that we rewrite its
02095     // uses (it may have uses that are not part of the pattern) with the
02096     // ultimate chain result of the generated code.  We will also add its chain
02097     // inputs as inputs to the ultimate TokenFactor we create.
02098     Result = CR_LeadsToInteriorNode;
02099     ChainedNodesInPattern.push_back(User);
02100     InteriorChainedNodes.push_back(User);
02101     continue;
02102   }
02103 
02104   return Result;
02105 }
02106 
02107 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
02108 /// operation for when the pattern matched at least one node with a chains.  The
02109 /// input vector contains a list of all of the chained nodes that we match.  We
02110 /// must determine if this is a valid thing to cover (i.e. matching it won't
02111 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
02112 /// be used as the input node chain for the generated nodes.
02113 static SDValue
02114 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
02115                        SelectionDAG *CurDAG) {
02116   // Walk all of the chained nodes we've matched, recursively scanning down the
02117   // users of the chain result. This adds any TokenFactor nodes that are caught
02118   // in between chained nodes to the chained and interior nodes list.
02119   SmallVector<SDNode*, 3> InteriorChainedNodes;
02120   for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
02121     if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
02122                        InteriorChainedNodes) == CR_InducesCycle)
02123       return SDValue(); // Would induce a cycle.
02124   }
02125 
02126   // Okay, we have walked all the matched nodes and collected TokenFactor nodes
02127   // that we are interested in.  Form our input TokenFactor node.
02128   SmallVector<SDValue, 3> InputChains;
02129   for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
02130     // Add the input chain of this node to the InputChains list (which will be
02131     // the operands of the generated TokenFactor) if it's not an interior node.
02132     SDNode *N = ChainNodesMatched[i];
02133     if (N->getOpcode() != ISD::TokenFactor) {
02134       if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
02135         continue;
02136 
02137       // Otherwise, add the input chain.
02138       SDValue InChain = ChainNodesMatched[i]->getOperand(0);
02139       assert(InChain.getValueType() == MVT::Other && "Not a chain");
02140       InputChains.push_back(InChain);
02141       continue;
02142     }
02143 
02144     // If we have a token factor, we want to add all inputs of the token factor
02145     // that are not part of the pattern we're matching.
02146     for (unsigned op = 0, e = N->getNumOperands(); op != e; ++op) {
02147       if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
02148                       N->getOperand(op).getNode()))
02149         InputChains.push_back(N->getOperand(op));
02150     }
02151   }
02152 
02153   if (InputChains.size() == 1)
02154     return InputChains[0];
02155   return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
02156                          MVT::Other, InputChains);
02157 }
02158 
02159 /// MorphNode - Handle morphing a node in place for the selector.
02160 SDNode *SelectionDAGISel::
02161 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
02162           ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) {
02163   // It is possible we're using MorphNodeTo to replace a node with no
02164   // normal results with one that has a normal result (or we could be
02165   // adding a chain) and the input could have glue and chains as well.
02166   // In this case we need to shift the operands down.
02167   // FIXME: This is a horrible hack and broken in obscure cases, no worse
02168   // than the old isel though.
02169   int OldGlueResultNo = -1, OldChainResultNo = -1;
02170 
02171   unsigned NTMNumResults = Node->getNumValues();
02172   if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
02173     OldGlueResultNo = NTMNumResults-1;
02174     if (NTMNumResults != 1 &&
02175         Node->getValueType(NTMNumResults-2) == MVT::Other)
02176       OldChainResultNo = NTMNumResults-2;
02177   } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
02178     OldChainResultNo = NTMNumResults-1;
02179 
02180   // Call the underlying SelectionDAG routine to do the transmogrification. Note
02181   // that this deletes operands of the old node that become dead.
02182   SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops);
02183 
02184   // MorphNodeTo can operate in two ways: if an existing node with the
02185   // specified operands exists, it can just return it.  Otherwise, it
02186   // updates the node in place to have the requested operands.
02187   if (Res == Node) {
02188     // If we updated the node in place, reset the node ID.  To the isel,
02189     // this should be just like a newly allocated machine node.
02190     Res->setNodeId(-1);
02191   }
02192 
02193   unsigned ResNumResults = Res->getNumValues();
02194   // Move the glue if needed.
02195   if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
02196       (unsigned)OldGlueResultNo != ResNumResults-1)
02197     CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldGlueResultNo),
02198                                       SDValue(Res, ResNumResults-1));
02199 
02200   if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
02201     --ResNumResults;
02202 
02203   // Move the chain reference if needed.
02204   if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
02205       (unsigned)OldChainResultNo != ResNumResults-1)
02206     CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
02207                                       SDValue(Res, ResNumResults-1));
02208 
02209   // Otherwise, no replacement happened because the node already exists. Replace
02210   // Uses of the old node with the new one.
02211   if (Res != Node)
02212     CurDAG->ReplaceAllUsesWith(Node, Res);
02213 
02214   return Res;
02215 }
02216 
02217 /// CheckSame - Implements OP_CheckSame.
02218 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02219 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02220           SDValue N,
02221           const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
02222   // Accept if it is exactly the same as a previously recorded node.
02223   unsigned RecNo = MatcherTable[MatcherIndex++];
02224   assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
02225   return N == RecordedNodes[RecNo].first;
02226 }
02227 
02228 /// CheckChildSame - Implements OP_CheckChildXSame.
02229 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02230 CheckChildSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02231              SDValue N,
02232              const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes,
02233              unsigned ChildNo) {
02234   if (ChildNo >= N.getNumOperands())
02235     return false;  // Match fails if out of range child #.
02236   return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo),
02237                      RecordedNodes);
02238 }
02239 
02240 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
02241 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02242 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02243                       const SelectionDAGISel &SDISel) {
02244   return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
02245 }
02246 
02247 /// CheckNodePredicate - Implements OP_CheckNodePredicate.
02248 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02249 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02250                    const SelectionDAGISel &SDISel, SDNode *N) {
02251   return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
02252 }
02253 
02254 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02255 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02256             SDNode *N) {
02257   uint16_t Opc = MatcherTable[MatcherIndex++];
02258   Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
02259   return N->getOpcode() == Opc;
02260 }
02261 
02262 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02263 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02264           SDValue N, const TargetLowering *TLI) {
02265   MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
02266   if (N.getValueType() == VT) return true;
02267 
02268   // Handle the case when VT is iPTR.
02269   return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy();
02270 }
02271 
02272 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02273 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02274                SDValue N, const TargetLowering *TLI, unsigned ChildNo) {
02275   if (ChildNo >= N.getNumOperands())
02276     return false;  // Match fails if out of range child #.
02277   return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI);
02278 }
02279 
02280 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02281 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02282               SDValue N) {
02283   return cast<CondCodeSDNode>(N)->get() ==
02284       (ISD::CondCode)MatcherTable[MatcherIndex++];
02285 }
02286 
02287 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02288 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02289                SDValue N, const TargetLowering *TLI) {
02290   MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
02291   if (cast<VTSDNode>(N)->getVT() == VT)
02292     return true;
02293 
02294   // Handle the case when VT is iPTR.
02295   return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy();
02296 }
02297 
02298 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02299 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02300              SDValue N) {
02301   int64_t Val = MatcherTable[MatcherIndex++];
02302   if (Val & 128)
02303     Val = GetVBR(Val, MatcherTable, MatcherIndex);
02304 
02305   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
02306   return C && C->getSExtValue() == Val;
02307 }
02308 
02309 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02310 CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02311                   SDValue N, unsigned ChildNo) {
02312   if (ChildNo >= N.getNumOperands())
02313     return false;  // Match fails if out of range child #.
02314   return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo));
02315 }
02316 
02317 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02318 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02319             SDValue N, const SelectionDAGISel &SDISel) {
02320   int64_t Val = MatcherTable[MatcherIndex++];
02321   if (Val & 128)
02322     Val = GetVBR(Val, MatcherTable, MatcherIndex);
02323 
02324   if (N->getOpcode() != ISD::AND) return false;
02325 
02326   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
02327   return C && SDISel.CheckAndMask(N.getOperand(0), C, Val);
02328 }
02329 
02330 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
02331 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
02332            SDValue N, const SelectionDAGISel &SDISel) {
02333   int64_t Val = MatcherTable[MatcherIndex++];
02334   if (Val & 128)
02335     Val = GetVBR(Val, MatcherTable, MatcherIndex);
02336 
02337   if (N->getOpcode() != ISD::OR) return false;
02338 
02339   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
02340   return C && SDISel.CheckOrMask(N.getOperand(0), C, Val);
02341 }
02342 
02343 /// IsPredicateKnownToFail - If we know how and can do so without pushing a
02344 /// scope, evaluate the current node.  If the current predicate is known to
02345 /// fail, set Result=true and return anything.  If the current predicate is
02346 /// known to pass, set Result=false and return the MatcherIndex to continue
02347 /// with.  If the current predicate is unknown, set Result=false and return the
02348 /// MatcherIndex to continue with.
02349 static unsigned IsPredicateKnownToFail(const unsigned char *Table,
02350                                        unsigned Index, SDValue N,
02351                                        bool &Result,
02352                                        const SelectionDAGISel &SDISel,
02353                  SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
02354   switch (Table[Index++]) {
02355   default:
02356     Result = false;
02357     return Index-1;  // Could not evaluate this predicate.
02358   case SelectionDAGISel::OPC_CheckSame:
02359     Result = !::CheckSame(Table, Index, N, RecordedNodes);
02360     return Index;
02361   case SelectionDAGISel::OPC_CheckChild0Same:
02362   case SelectionDAGISel::OPC_CheckChild1Same:
02363   case SelectionDAGISel::OPC_CheckChild2Same:
02364   case SelectionDAGISel::OPC_CheckChild3Same:
02365     Result = !::CheckChildSame(Table, Index, N, RecordedNodes,
02366                         Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Same);
02367     return Index;
02368   case SelectionDAGISel::OPC_CheckPatternPredicate:
02369     Result = !::CheckPatternPredicate(Table, Index, SDISel);
02370     return Index;
02371   case SelectionDAGISel::OPC_CheckPredicate:
02372     Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
02373     return Index;
02374   case SelectionDAGISel::OPC_CheckOpcode:
02375     Result = !::CheckOpcode(Table, Index, N.getNode());
02376     return Index;
02377   case SelectionDAGISel::OPC_CheckType:
02378     Result = !::CheckType(Table, Index, N, SDISel.getTargetLowering());
02379     return Index;
02380   case SelectionDAGISel::OPC_CheckChild0Type:
02381   case SelectionDAGISel::OPC_CheckChild1Type:
02382   case SelectionDAGISel::OPC_CheckChild2Type:
02383   case SelectionDAGISel::OPC_CheckChild3Type:
02384   case SelectionDAGISel::OPC_CheckChild4Type:
02385   case SelectionDAGISel::OPC_CheckChild5Type:
02386   case SelectionDAGISel::OPC_CheckChild6Type:
02387   case SelectionDAGISel::OPC_CheckChild7Type:
02388     Result = !::CheckChildType(Table, Index, N, SDISel.getTargetLowering(),
02389                         Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Type);
02390     return Index;
02391   case SelectionDAGISel::OPC_CheckCondCode:
02392     Result = !::CheckCondCode(Table, Index, N);
02393     return Index;
02394   case SelectionDAGISel::OPC_CheckValueType:
02395     Result = !::CheckValueType(Table, Index, N, SDISel.getTargetLowering());
02396     return Index;
02397   case SelectionDAGISel::OPC_CheckInteger:
02398     Result = !::CheckInteger(Table, Index, N);
02399     return Index;
02400   case SelectionDAGISel::OPC_CheckChild0Integer:
02401   case SelectionDAGISel::OPC_CheckChild1Integer:
02402   case SelectionDAGISel::OPC_CheckChild2Integer:
02403   case SelectionDAGISel::OPC_CheckChild3Integer:
02404   case SelectionDAGISel::OPC_CheckChild4Integer:
02405     Result = !::CheckChildInteger(Table, Index, N,
02406                      Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Integer);
02407     return Index;
02408   case SelectionDAGISel::OPC_CheckAndImm:
02409     Result = !::CheckAndImm(Table, Index, N, SDISel);
02410     return Index;
02411   case SelectionDAGISel::OPC_CheckOrImm:
02412     Result = !::CheckOrImm(Table, Index, N, SDISel);
02413     return Index;
02414   }
02415 }
02416 
02417 namespace {
02418 
02419 struct MatchScope {
02420   /// FailIndex - If this match fails, this is the index to continue with.
02421   unsigned FailIndex;
02422 
02423   /// NodeStack - The node stack when the scope was formed.
02424   SmallVector<SDValue, 4> NodeStack;
02425 
02426   /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
02427   unsigned NumRecordedNodes;
02428 
02429   /// NumMatchedMemRefs - The number of matched memref entries.
02430   unsigned NumMatchedMemRefs;
02431 
02432   /// InputChain/InputGlue - The current chain/glue
02433   SDValue InputChain, InputGlue;
02434 
02435   /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
02436   bool HasChainNodesMatched, HasGlueResultNodesMatched;
02437 };
02438 
02439 }
02440 
02441 SDNode *SelectionDAGISel::
02442 SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
02443                  unsigned TableSize) {
02444   // FIXME: Should these even be selected?  Handle these cases in the caller?
02445   switch (NodeToMatch->getOpcode()) {
02446   default:
02447     break;
02448   case ISD::EntryToken:       // These nodes remain the same.
02449   case ISD::BasicBlock:
02450   case ISD::Register:
02451   case ISD::RegisterMask:
02452   //case ISD::VALUETYPE:
02453   //case ISD::CONDCODE:
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 = TM.getInstrInfo()->get(TargetOpc);
03080         bool mayLoad = MCID.mayLoad();
03081         bool mayStore = MCID.mayStore();
03082 
03083         unsigned NumMemRefs = 0;
03084         for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
03085                MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
03086           if ((*I)->isLoad()) {
03087             if (mayLoad)
03088               ++NumMemRefs;
03089           } else if ((*I)->isStore()) {
03090             if (mayStore)
03091               ++NumMemRefs;
03092           } else {
03093             ++NumMemRefs;
03094           }
03095         }
03096 
03097         MachineSDNode::mmo_iterator MemRefs =
03098           MF->allocateMemRefsArray(NumMemRefs);
03099 
03100         MachineSDNode::mmo_iterator MemRefsPos = MemRefs;
03101         for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
03102                MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
03103           if ((*I)->isLoad()) {
03104             if (mayLoad)
03105               *MemRefsPos++ = *I;
03106           } else if ((*I)->isStore()) {
03107             if (mayStore)
03108               *MemRefsPos++ = *I;
03109           } else {
03110             *MemRefsPos++ = *I;
03111           }
03112         }
03113 
03114         cast<MachineSDNode>(Res)
03115           ->setMemRefs(MemRefs, MemRefs + NumMemRefs);
03116       }
03117 
03118       DEBUG(dbgs() << "  "
03119                    << (Opcode == OPC_MorphNodeTo ? "Morphed" : "Created")
03120                    << " node: "; Res->dump(CurDAG); dbgs() << "\n");
03121 
03122       // If this was a MorphNodeTo then we're completely done!
03123       if (Opcode == OPC_MorphNodeTo) {
03124         // Update chain and glue uses.
03125         UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
03126                             InputGlue, GlueResultNodesMatched, true);
03127         return Res;
03128       }
03129 
03130       continue;
03131     }
03132 
03133     case OPC_MarkGlueResults: {
03134       unsigned NumNodes = MatcherTable[MatcherIndex++];
03135 
03136       // Read and remember all the glue-result nodes.
03137       for (unsigned i = 0; i != NumNodes; ++i) {
03138         unsigned RecNo = MatcherTable[MatcherIndex++];
03139         if (RecNo & 128)
03140           RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
03141 
03142         assert(RecNo < RecordedNodes.size() && "Invalid MarkGlueResults");
03143         GlueResultNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
03144       }
03145       continue;
03146     }
03147 
03148     case OPC_CompleteMatch: {
03149       // The match has been completed, and any new nodes (if any) have been
03150       // created.  Patch up references to the matched dag to use the newly
03151       // created nodes.
03152       unsigned NumResults = MatcherTable[MatcherIndex++];
03153 
03154       for (unsigned i = 0; i != NumResults; ++i) {
03155         unsigned ResSlot = MatcherTable[MatcherIndex++];
03156         if (ResSlot & 128)
03157           ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
03158 
03159         assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch");
03160         SDValue Res = RecordedNodes[ResSlot].first;
03161 
03162         assert(i < NodeToMatch->getNumValues() &&
03163                NodeToMatch->getValueType(i) != MVT::Other &&
03164                NodeToMatch->getValueType(i) != MVT::Glue &&
03165                "Invalid number of results to complete!");
03166         assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
03167                 NodeToMatch->getValueType(i) == MVT::iPTR ||
03168                 Res.getValueType() == MVT::iPTR ||
03169                 NodeToMatch->getValueType(i).getSizeInBits() ==
03170                     Res.getValueType().getSizeInBits()) &&
03171                "invalid replacement");
03172         CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
03173       }
03174 
03175       // If the root node defines glue, add it to the glue nodes to update list.
03176       if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) == MVT::Glue)
03177         GlueResultNodesMatched.push_back(NodeToMatch);
03178 
03179       // Update chain and glue uses.
03180       UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
03181                           InputGlue, GlueResultNodesMatched, false);
03182 
03183       assert(NodeToMatch->use_empty() &&
03184              "Didn't replace all uses of the node?");
03185 
03186       // FIXME: We just return here, which interacts correctly with SelectRoot
03187       // above.  We should fix this to not return an SDNode* anymore.
03188       return nullptr;
03189     }
03190     }
03191 
03192     // If the code reached this point, then the match failed.  See if there is
03193     // another child to try in the current 'Scope', otherwise pop it until we
03194     // find a case to check.
03195     DEBUG(dbgs() << "  Match failed at index " << CurrentOpcodeIndex << "\n");
03196     ++NumDAGIselRetries;
03197     while (1) {
03198       if (MatchScopes.empty()) {
03199         CannotYetSelect(NodeToMatch);
03200         return nullptr;
03201       }
03202 
03203       // Restore the interpreter state back to the point where the scope was
03204       // formed.
03205       MatchScope &LastScope = MatchScopes.back();
03206       RecordedNodes.resize(LastScope.NumRecordedNodes);
03207       NodeStack.clear();
03208       NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
03209       N = NodeStack.back();
03210 
03211       if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
03212         MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
03213       MatcherIndex = LastScope.FailIndex;
03214 
03215       DEBUG(dbgs() << "  Continuing at " << MatcherIndex << "\n");
03216 
03217       InputChain = LastScope.InputChain;
03218       InputGlue = LastScope.InputGlue;
03219       if (!LastScope.HasChainNodesMatched)
03220         ChainNodesMatched.clear();
03221       if (!LastScope.HasGlueResultNodesMatched)
03222         GlueResultNodesMatched.clear();
03223 
03224       // Check to see what the offset is at the new MatcherIndex.  If it is zero
03225       // we have reached the end of this scope, otherwise we have another child
03226       // in the current scope to try.
03227       unsigned NumToSkip = MatcherTable[MatcherIndex++];
03228       if (NumToSkip & 128)
03229         NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
03230 
03231       // If we have another child in this scope to match, update FailIndex and
03232       // try it.
03233       if (NumToSkip != 0) {
03234         LastScope.FailIndex = MatcherIndex+NumToSkip;
03235         break;
03236       }
03237 
03238       // End of this scope, pop it and try the next child in the containing
03239       // scope.
03240       MatchScopes.pop_back();
03241     }
03242   }
03243 }
03244 
03245 
03246 
03247 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
03248   std::string msg;
03249   raw_string_ostream Msg(msg);
03250   Msg << "Cannot select: ";
03251 
03252   if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
03253       N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
03254       N->getOpcode() != ISD::INTRINSIC_VOID) {
03255     N->printrFull(Msg, CurDAG);
03256     Msg << "\nIn function: " << MF->getName();
03257   } else {
03258     bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
03259     unsigned iid =
03260       cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
03261     if (iid < Intrinsic::num_intrinsics)
03262       Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid);
03263     else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
03264       Msg << "target intrinsic %" << TII->getName(iid);
03265     else
03266       Msg << "unknown intrinsic #" << iid;
03267   }
03268   report_fatal_error(Msg.str());
03269 }
03270 
03271 char SelectionDAGISel::ID = 0;