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