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