1 //===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the SelectionDAGISel class.
12 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "isel"
15 #include "llvm/CodeGen/SelectionDAGISel.h"
16 #include "ScheduleDAGSDNodes.h"
17 #include "SelectionDAGBuilder.h"
18 #include "llvm/ADT/PostOrderIterator.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/BranchProbabilityInfo.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/CodeGen/FastISel.h"
24 #include "llvm/CodeGen/FunctionLoweringInfo.h"
25 #include "llvm/CodeGen/GCMetadata.h"
26 #include "llvm/CodeGen/GCStrategy.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineFunction.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineModuleInfo.h"
31 #include "llvm/CodeGen/MachineRegisterInfo.h"
32 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
33 #include "llvm/CodeGen/SchedulerRegistry.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/DebugInfo.h"
36 #include "llvm/IR/Constants.h"
37 #include "llvm/IR/Function.h"
38 #include "llvm/IR/InlineAsm.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/IntrinsicInst.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/IR/LLVMContext.h"
43 #include "llvm/IR/Module.h"
44 #include "llvm/Support/Compiler.h"
45 #include "llvm/Support/Debug.h"
46 #include "llvm/Support/ErrorHandling.h"
47 #include "llvm/Support/Timer.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include "llvm/Target/TargetInstrInfo.h"
50 #include "llvm/Target/TargetIntrinsicInfo.h"
51 #include "llvm/Target/TargetLibraryInfo.h"
52 #include "llvm/Target/TargetLowering.h"
53 #include "llvm/Target/TargetMachine.h"
54 #include "llvm/Target/TargetOptions.h"
55 #include "llvm/Target/TargetRegisterInfo.h"
56 #include "llvm/Target/TargetSubtargetInfo.h"
57 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
61 STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
62 STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
63 STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
64 STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
65 STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
69 EnableFastISelVerbose2("fast-isel-verbose2", cl::Hidden,
70 cl::desc("Enable extra verbose messages in the \"fast\" "
71 "instruction selector"));
73 STATISTIC(NumFastIselFailRet,"Fast isel fails on Ret");
74 STATISTIC(NumFastIselFailBr,"Fast isel fails on Br");
75 STATISTIC(NumFastIselFailSwitch,"Fast isel fails on Switch");
76 STATISTIC(NumFastIselFailIndirectBr,"Fast isel fails on IndirectBr");
77 STATISTIC(NumFastIselFailInvoke,"Fast isel fails on Invoke");
78 STATISTIC(NumFastIselFailResume,"Fast isel fails on Resume");
79 STATISTIC(NumFastIselFailUnreachable,"Fast isel fails on Unreachable");
81 // Standard binary operators...
82 STATISTIC(NumFastIselFailAdd,"Fast isel fails on Add");
83 STATISTIC(NumFastIselFailFAdd,"Fast isel fails on FAdd");
84 STATISTIC(NumFastIselFailSub,"Fast isel fails on Sub");
85 STATISTIC(NumFastIselFailFSub,"Fast isel fails on FSub");
86 STATISTIC(NumFastIselFailMul,"Fast isel fails on Mul");
87 STATISTIC(NumFastIselFailFMul,"Fast isel fails on FMul");
88 STATISTIC(NumFastIselFailUDiv,"Fast isel fails on UDiv");
89 STATISTIC(NumFastIselFailSDiv,"Fast isel fails on SDiv");
90 STATISTIC(NumFastIselFailFDiv,"Fast isel fails on FDiv");
91 STATISTIC(NumFastIselFailURem,"Fast isel fails on URem");
92 STATISTIC(NumFastIselFailSRem,"Fast isel fails on SRem");
93 STATISTIC(NumFastIselFailFRem,"Fast isel fails on FRem");
95 // Logical operators...
96 STATISTIC(NumFastIselFailAnd,"Fast isel fails on And");
97 STATISTIC(NumFastIselFailOr,"Fast isel fails on Or");
98 STATISTIC(NumFastIselFailXor,"Fast isel fails on Xor");
100 // Memory instructions...
101 STATISTIC(NumFastIselFailAlloca,"Fast isel fails on Alloca");
102 STATISTIC(NumFastIselFailLoad,"Fast isel fails on Load");
103 STATISTIC(NumFastIselFailStore,"Fast isel fails on Store");
104 STATISTIC(NumFastIselFailAtomicCmpXchg,"Fast isel fails on AtomicCmpXchg");
105 STATISTIC(NumFastIselFailAtomicRMW,"Fast isel fails on AtomicRWM");
106 STATISTIC(NumFastIselFailFence,"Fast isel fails on Frence");
107 STATISTIC(NumFastIselFailGetElementPtr,"Fast isel fails on GetElementPtr");
109 // Convert instructions...
110 STATISTIC(NumFastIselFailTrunc,"Fast isel fails on Trunc");
111 STATISTIC(NumFastIselFailZExt,"Fast isel fails on ZExt");
112 STATISTIC(NumFastIselFailSExt,"Fast isel fails on SExt");
113 STATISTIC(NumFastIselFailFPTrunc,"Fast isel fails on FPTrunc");
114 STATISTIC(NumFastIselFailFPExt,"Fast isel fails on FPExt");
115 STATISTIC(NumFastIselFailFPToUI,"Fast isel fails on FPToUI");
116 STATISTIC(NumFastIselFailFPToSI,"Fast isel fails on FPToSI");
117 STATISTIC(NumFastIselFailUIToFP,"Fast isel fails on UIToFP");
118 STATISTIC(NumFastIselFailSIToFP,"Fast isel fails on SIToFP");
119 STATISTIC(NumFastIselFailIntToPtr,"Fast isel fails on IntToPtr");
120 STATISTIC(NumFastIselFailPtrToInt,"Fast isel fails on PtrToInt");
121 STATISTIC(NumFastIselFailBitCast,"Fast isel fails on BitCast");
123 // Other instructions...
124 STATISTIC(NumFastIselFailICmp,"Fast isel fails on ICmp");
125 STATISTIC(NumFastIselFailFCmp,"Fast isel fails on FCmp");
126 STATISTIC(NumFastIselFailPHI,"Fast isel fails on PHI");
127 STATISTIC(NumFastIselFailSelect,"Fast isel fails on Select");
128 STATISTIC(NumFastIselFailCall,"Fast isel fails on Call");
129 STATISTIC(NumFastIselFailShl,"Fast isel fails on Shl");
130 STATISTIC(NumFastIselFailLShr,"Fast isel fails on LShr");
131 STATISTIC(NumFastIselFailAShr,"Fast isel fails on AShr");
132 STATISTIC(NumFastIselFailVAArg,"Fast isel fails on VAArg");
133 STATISTIC(NumFastIselFailExtractElement,"Fast isel fails on ExtractElement");
134 STATISTIC(NumFastIselFailInsertElement,"Fast isel fails on InsertElement");
135 STATISTIC(NumFastIselFailShuffleVector,"Fast isel fails on ShuffleVector");
136 STATISTIC(NumFastIselFailExtractValue,"Fast isel fails on ExtractValue");
137 STATISTIC(NumFastIselFailInsertValue,"Fast isel fails on InsertValue");
138 STATISTIC(NumFastIselFailLandingPad,"Fast isel fails on LandingPad");
142 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
143 cl::desc("Enable verbose messages in the \"fast\" "
144 "instruction selector"));
146 EnableFastISelAbort("fast-isel-abort", cl::Hidden,
147 cl::desc("Enable abort calls when \"fast\" instruction fails"));
151 cl::desc("use Machine Branch Probability Info"),
152 cl::init(true), cl::Hidden);
156 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
157 cl::desc("Pop up a window to show dags before the first "
158 "dag combine pass"));
160 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
161 cl::desc("Pop up a window to show dags before legalize types"));
163 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
164 cl::desc("Pop up a window to show dags before legalize"));
166 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
167 cl::desc("Pop up a window to show dags before the second "
168 "dag combine pass"));
170 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
171 cl::desc("Pop up a window to show dags before the post legalize types"
172 " dag combine pass"));
174 ViewISelDAGs("view-isel-dags", cl::Hidden,
175 cl::desc("Pop up a window to show isel dags as they are selected"));
177 ViewSchedDAGs("view-sched-dags", cl::Hidden,
178 cl::desc("Pop up a window to show sched dags as they are processed"));
180 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
181 cl::desc("Pop up a window to show SUnit dags after they are processed"));
183 static const bool ViewDAGCombine1 = false,
184 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
185 ViewDAGCombine2 = false,
186 ViewDAGCombineLT = false,
187 ViewISelDAGs = false, ViewSchedDAGs = false,
188 ViewSUnitDAGs = false;
191 //===---------------------------------------------------------------------===//
193 /// RegisterScheduler class - Track the registration of instruction schedulers.
195 //===---------------------------------------------------------------------===//
196 MachinePassRegistry RegisterScheduler::Registry;
198 //===---------------------------------------------------------------------===//
200 /// ISHeuristic command line option for instruction schedulers.
202 //===---------------------------------------------------------------------===//
203 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
204 RegisterPassParser<RegisterScheduler> >
205 ISHeuristic("pre-RA-sched",
206 cl::init(&createDefaultScheduler),
207 cl::desc("Instruction schedulers available (before register"
210 static RegisterScheduler
211 defaultListDAGScheduler("default", "Best scheduler for the target",
212 createDefaultScheduler);
215 //===--------------------------------------------------------------------===//
216 /// createDefaultScheduler - This creates an instruction scheduler appropriate
218 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
219 CodeGenOpt::Level OptLevel) {
220 const TargetLowering &TLI = IS->getTargetLowering();
221 const TargetSubtargetInfo &ST = IS->TM.getSubtarget<TargetSubtargetInfo>();
223 if (OptLevel == CodeGenOpt::None || ST.enableMachineScheduler() ||
224 TLI.getSchedulingPreference() == Sched::Source)
225 return createSourceListDAGScheduler(IS, OptLevel);
226 if (TLI.getSchedulingPreference() == Sched::RegPressure)
227 return createBURRListDAGScheduler(IS, OptLevel);
228 if (TLI.getSchedulingPreference() == Sched::Hybrid)
229 return createHybridListDAGScheduler(IS, OptLevel);
230 if (TLI.getSchedulingPreference() == Sched::VLIW)
231 return createVLIWDAGScheduler(IS, OptLevel);
232 assert(TLI.getSchedulingPreference() == Sched::ILP &&
233 "Unknown sched type!");
234 return createILPListDAGScheduler(IS, OptLevel);
238 // EmitInstrWithCustomInserter - This method should be implemented by targets
239 // that mark instructions with the 'usesCustomInserter' flag. These
240 // instructions are special in various ways, which require special support to
241 // insert. The specified MachineInstr is created but not inserted into any
242 // basic blocks, and this method is called to expand it into a sequence of
243 // instructions, potentially also creating new basic blocks and control flow.
244 // When new basic blocks are inserted and the edges from MBB to its successors
245 // are modified, the method should insert pairs of <OldSucc, NewSucc> into the
248 TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
249 MachineBasicBlock *MBB) const {
251 dbgs() << "If a target marks an instruction with "
252 "'usesCustomInserter', it must implement "
253 "TargetLowering::EmitInstrWithCustomInserter!";
258 void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
259 SDNode *Node) const {
260 assert(!MI->hasPostISelHook() &&
261 "If a target marks an instruction with 'hasPostISelHook', "
262 "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
265 //===----------------------------------------------------------------------===//
266 // SelectionDAGISel code
267 //===----------------------------------------------------------------------===//
269 SelectionDAGISel::SelectionDAGISel(const TargetMachine &tm,
270 CodeGenOpt::Level OL) :
271 MachineFunctionPass(ID), TM(tm), TLI(*tm.getTargetLowering()),
272 FuncInfo(new FunctionLoweringInfo(TLI)),
273 CurDAG(new SelectionDAG(tm, OL)),
274 SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)),
278 initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
279 initializeAliasAnalysisAnalysisGroup(*PassRegistry::getPassRegistry());
280 initializeBranchProbabilityInfoPass(*PassRegistry::getPassRegistry());
281 initializeTargetLibraryInfoPass(*PassRegistry::getPassRegistry());
284 SelectionDAGISel::~SelectionDAGISel() {
290 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
291 AU.addRequired<AliasAnalysis>();
292 AU.addPreserved<AliasAnalysis>();
293 AU.addRequired<GCModuleInfo>();
294 AU.addPreserved<GCModuleInfo>();
295 AU.addRequired<TargetLibraryInfo>();
296 if (UseMBPI && OptLevel != CodeGenOpt::None)
297 AU.addRequired<BranchProbabilityInfo>();
298 MachineFunctionPass::getAnalysisUsage(AU);
301 /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that
302 /// may trap on it. In this case we have to split the edge so that the path
303 /// through the predecessor block that doesn't go to the phi block doesn't
304 /// execute the possibly trapping instruction.
306 /// This is required for correctness, so it must be done at -O0.
308 static void SplitCriticalSideEffectEdges(Function &Fn, Pass *SDISel) {
309 // Loop for blocks with phi nodes.
310 for (Function::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
311 PHINode *PN = dyn_cast<PHINode>(BB->begin());
312 if (PN == 0) continue;
315 // For each block with a PHI node, check to see if any of the input values
316 // are potentially trapping constant expressions. Constant expressions are
317 // the only potentially trapping value that can occur as the argument to a
319 for (BasicBlock::iterator I = BB->begin(); (PN = dyn_cast<PHINode>(I)); ++I)
320 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
321 ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i));
322 if (CE == 0 || !CE->canTrap()) continue;
324 // The only case we have to worry about is when the edge is critical.
325 // Since this block has a PHI Node, we assume it has multiple input
326 // edges: check to see if the pred has multiple successors.
327 BasicBlock *Pred = PN->getIncomingBlock(i);
328 if (Pred->getTerminator()->getNumSuccessors() == 1)
331 // Okay, we have to split this edge.
332 SplitCriticalEdge(Pred->getTerminator(),
333 GetSuccessorNumber(Pred, BB), SDISel, true);
339 bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
340 // Do some sanity-checking on the command-line options.
341 assert((!EnableFastISelVerbose || TM.Options.EnableFastISel) &&
342 "-fast-isel-verbose requires -fast-isel");
343 assert((!EnableFastISelAbort || TM.Options.EnableFastISel) &&
344 "-fast-isel-abort requires -fast-isel");
346 const Function &Fn = *mf.getFunction();
347 const TargetInstrInfo &TII = *TM.getInstrInfo();
348 const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
351 RegInfo = &MF->getRegInfo();
352 AA = &getAnalysis<AliasAnalysis>();
353 LibInfo = &getAnalysis<TargetLibraryInfo>();
354 TTI = getAnalysisIfAvailable<TargetTransformInfo>();
355 GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : 0;
357 DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
359 SplitCriticalSideEffectEdges(const_cast<Function&>(Fn), this);
361 CurDAG->init(*MF, TTI);
362 FuncInfo->set(Fn, *MF);
364 if (UseMBPI && OptLevel != CodeGenOpt::None)
365 FuncInfo->BPI = &getAnalysis<BranchProbabilityInfo>();
369 SDB->init(GFI, *AA, LibInfo);
371 SelectAllBasicBlocks(Fn);
373 // If the first basic block in the function has live ins that need to be
374 // copied into vregs, emit the copies into the top of the block before
375 // emitting the code for the block.
376 MachineBasicBlock *EntryMBB = MF->begin();
377 RegInfo->EmitLiveInCopies(EntryMBB, TRI, TII);
379 DenseMap<unsigned, unsigned> LiveInMap;
380 if (!FuncInfo->ArgDbgValues.empty())
381 for (MachineRegisterInfo::livein_iterator LI = RegInfo->livein_begin(),
382 E = RegInfo->livein_end(); LI != E; ++LI)
384 LiveInMap.insert(std::make_pair(LI->first, LI->second));
386 // Insert DBG_VALUE instructions for function arguments to the entry block.
387 for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
388 MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1];
389 unsigned Reg = MI->getOperand(0).getReg();
390 if (TargetRegisterInfo::isPhysicalRegister(Reg))
391 EntryMBB->insert(EntryMBB->begin(), MI);
393 MachineInstr *Def = RegInfo->getVRegDef(Reg);
394 MachineBasicBlock::iterator InsertPos = Def;
395 // FIXME: VR def may not be in entry block.
396 Def->getParent()->insert(llvm::next(InsertPos), MI);
399 // If Reg is live-in then update debug info to track its copy in a vreg.
400 DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
401 if (LDI != LiveInMap.end()) {
402 MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
403 MachineBasicBlock::iterator InsertPos = Def;
404 const MDNode *Variable =
405 MI->getOperand(MI->getNumOperands()-1).getMetadata();
406 unsigned Offset = MI->getOperand(1).getImm();
407 // Def is never a terminator here, so it is ok to increment InsertPos.
408 BuildMI(*EntryMBB, ++InsertPos, MI->getDebugLoc(),
409 TII.get(TargetOpcode::DBG_VALUE))
410 .addReg(LDI->second, RegState::Debug)
411 .addImm(Offset).addMetadata(Variable);
413 // If this vreg is directly copied into an exported register then
414 // that COPY instructions also need DBG_VALUE, if it is the only
415 // user of LDI->second.
416 MachineInstr *CopyUseMI = NULL;
417 for (MachineRegisterInfo::use_iterator
418 UI = RegInfo->use_begin(LDI->second);
419 MachineInstr *UseMI = UI.skipInstruction();) {
420 if (UseMI->isDebugValue()) continue;
421 if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
422 CopyUseMI = UseMI; continue;
424 // Otherwise this is another use or second copy use.
425 CopyUseMI = NULL; break;
428 MachineInstr *NewMI =
429 BuildMI(*MF, CopyUseMI->getDebugLoc(),
430 TII.get(TargetOpcode::DBG_VALUE))
431 .addReg(CopyUseMI->getOperand(0).getReg(), RegState::Debug)
432 .addImm(Offset).addMetadata(Variable);
433 MachineBasicBlock::iterator Pos = CopyUseMI;
434 EntryMBB->insertAfter(Pos, NewMI);
439 // Determine if there are any calls in this machine function.
440 MachineFrameInfo *MFI = MF->getFrameInfo();
441 if (!MFI->hasCalls()) {
442 for (MachineFunction::const_iterator
443 I = MF->begin(), E = MF->end(); I != E; ++I) {
444 const MachineBasicBlock *MBB = I;
445 for (MachineBasicBlock::const_iterator
446 II = MBB->begin(), IE = MBB->end(); II != IE; ++II) {
447 const MCInstrDesc &MCID = TM.getInstrInfo()->get(II->getOpcode());
449 if ((MCID.isCall() && !MCID.isReturn()) ||
450 II->isStackAligningInlineAsm()) {
451 MFI->setHasCalls(true);
459 // Determine if there is a call to setjmp in the machine function.
460 MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice());
462 // Replace forward-declared registers with the registers containing
463 // the desired value.
464 MachineRegisterInfo &MRI = MF->getRegInfo();
465 for (DenseMap<unsigned, unsigned>::iterator
466 I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end();
468 unsigned From = I->first;
469 unsigned To = I->second;
470 // If To is also scheduled to be replaced, find what its ultimate
473 DenseMap<unsigned, unsigned>::iterator J = FuncInfo->RegFixups.find(To);
478 MRI.replaceRegWith(From, To);
481 // Freeze the set of reserved registers now that MachineFrameInfo has been
482 // set up. All the information required by getReservedRegs() should be
484 MRI.freezeReservedRegs(*MF);
486 // Release function-specific state. SDB and CurDAG are already cleared
493 void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
494 BasicBlock::const_iterator End,
496 // Lower all of the non-terminator instructions. If a call is emitted
497 // as a tail call, cease emitting nodes for this block. Terminators
498 // are handled below.
499 for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I)
502 // Make sure the root of the DAG is up-to-date.
503 CurDAG->setRoot(SDB->getControlRoot());
504 HadTailCall = SDB->HasTailCall;
507 // Final step, emit the lowered DAG as machine code.
511 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
512 SmallPtrSet<SDNode*, 128> VisitedNodes;
513 SmallVector<SDNode*, 128> Worklist;
515 Worklist.push_back(CurDAG->getRoot().getNode());
521 SDNode *N = Worklist.pop_back_val();
523 // If we've already seen this node, ignore it.
524 if (!VisitedNodes.insert(N))
527 // Otherwise, add all chain operands to the worklist.
528 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
529 if (N->getOperand(i).getValueType() == MVT::Other)
530 Worklist.push_back(N->getOperand(i).getNode());
532 // If this is a CopyToReg with a vreg dest, process it.
533 if (N->getOpcode() != ISD::CopyToReg)
536 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
537 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
540 // Ignore non-scalar or non-integer values.
541 SDValue Src = N->getOperand(2);
542 EVT SrcVT = Src.getValueType();
543 if (!SrcVT.isInteger() || SrcVT.isVector())
546 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
547 CurDAG->ComputeMaskedBits(Src, KnownZero, KnownOne);
548 FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, KnownZero, KnownOne);
549 } while (!Worklist.empty());
552 void SelectionDAGISel::CodeGenAndEmitDAG() {
553 std::string GroupName;
554 if (TimePassesIsEnabled)
555 GroupName = "Instruction Selection and Scheduling";
556 std::string BlockName;
557 int BlockNumber = -1;
560 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
561 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
565 BlockNumber = FuncInfo->MBB->getNumber();
566 BlockName = MF->getName().str() + ":" +
567 FuncInfo->MBB->getBasicBlock()->getName().str();
569 DEBUG(dbgs() << "Initial selection DAG: BB#" << BlockNumber
570 << " '" << BlockName << "'\n"; CurDAG->dump());
572 if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
574 // Run the DAG combiner in pre-legalize mode.
576 NamedRegionTimer T("DAG Combining 1", GroupName, TimePassesIsEnabled);
577 CurDAG->Combine(BeforeLegalizeTypes, *AA, OptLevel);
580 DEBUG(dbgs() << "Optimized lowered selection DAG: BB#" << BlockNumber
581 << " '" << BlockName << "'\n"; CurDAG->dump());
583 // Second step, hack on the DAG until it only uses operations and types that
584 // the target supports.
585 if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
590 NamedRegionTimer T("Type Legalization", GroupName, TimePassesIsEnabled);
591 Changed = CurDAG->LegalizeTypes();
594 DEBUG(dbgs() << "Type-legalized selection DAG: BB#" << BlockNumber
595 << " '" << BlockName << "'\n"; CurDAG->dump());
598 if (ViewDAGCombineLT)
599 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
601 // Run the DAG combiner in post-type-legalize mode.
603 NamedRegionTimer T("DAG Combining after legalize types", GroupName,
604 TimePassesIsEnabled);
605 CurDAG->Combine(AfterLegalizeTypes, *AA, OptLevel);
608 DEBUG(dbgs() << "Optimized type-legalized selection DAG: BB#" << BlockNumber
609 << " '" << BlockName << "'\n"; CurDAG->dump());
613 NamedRegionTimer T("Vector Legalization", GroupName, TimePassesIsEnabled);
614 Changed = CurDAG->LegalizeVectors();
619 NamedRegionTimer T("Type Legalization 2", GroupName, TimePassesIsEnabled);
620 CurDAG->LegalizeTypes();
623 if (ViewDAGCombineLT)
624 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
626 // Run the DAG combiner in post-type-legalize mode.
628 NamedRegionTimer T("DAG Combining after legalize vectors", GroupName,
629 TimePassesIsEnabled);
630 CurDAG->Combine(AfterLegalizeVectorOps, *AA, OptLevel);
633 DEBUG(dbgs() << "Optimized vector-legalized selection DAG: BB#"
634 << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump());
637 if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
640 NamedRegionTimer T("DAG Legalization", GroupName, TimePassesIsEnabled);
644 DEBUG(dbgs() << "Legalized selection DAG: BB#" << BlockNumber
645 << " '" << BlockName << "'\n"; CurDAG->dump());
647 if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
649 // Run the DAG combiner in post-legalize mode.
651 NamedRegionTimer T("DAG Combining 2", GroupName, TimePassesIsEnabled);
652 CurDAG->Combine(AfterLegalizeDAG, *AA, OptLevel);
655 DEBUG(dbgs() << "Optimized legalized selection DAG: BB#" << BlockNumber
656 << " '" << BlockName << "'\n"; CurDAG->dump());
658 if (OptLevel != CodeGenOpt::None)
659 ComputeLiveOutVRegInfo();
661 if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
663 // Third, instruction select all of the operations to machine code, adding the
664 // code to the MachineBasicBlock.
666 NamedRegionTimer T("Instruction Selection", GroupName, TimePassesIsEnabled);
667 DoInstructionSelection();
670 DEBUG(dbgs() << "Selected selection DAG: BB#" << BlockNumber
671 << " '" << BlockName << "'\n"; CurDAG->dump());
673 if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
675 // Schedule machine code.
676 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
678 NamedRegionTimer T("Instruction Scheduling", GroupName,
679 TimePassesIsEnabled);
680 Scheduler->Run(CurDAG, FuncInfo->MBB);
683 if (ViewSUnitDAGs) Scheduler->viewGraph();
685 // Emit machine code to BB. This can change 'BB' to the last block being
687 MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
689 NamedRegionTimer T("Instruction Creation", GroupName, TimePassesIsEnabled);
691 // FuncInfo->InsertPt is passed by reference and set to the end of the
692 // scheduled instructions.
693 LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
696 // If the block was split, make sure we update any references that are used to
697 // update PHI nodes later on.
698 if (FirstMBB != LastMBB)
699 SDB->UpdateSplitBlock(FirstMBB, LastMBB);
701 // Free the scheduler state.
703 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName,
704 TimePassesIsEnabled);
708 // Free the SelectionDAG state, now that we're finished with it.
713 /// ISelUpdater - helper class to handle updates of the instruction selection
715 class ISelUpdater : public SelectionDAG::DAGUpdateListener {
716 SelectionDAG::allnodes_iterator &ISelPosition;
718 ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
719 : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
721 /// NodeDeleted - Handle nodes deleted from the graph. If the node being
722 /// deleted is the current ISelPosition node, update ISelPosition.
724 virtual void NodeDeleted(SDNode *N, SDNode *E) {
725 if (ISelPosition == SelectionDAG::allnodes_iterator(N))
729 } // end anonymous namespace
731 void SelectionDAGISel::DoInstructionSelection() {
732 DEBUG(errs() << "===== Instruction selection begins: BB#"
733 << FuncInfo->MBB->getNumber()
734 << " '" << FuncInfo->MBB->getName() << "'\n");
738 // Select target instructions for the DAG.
740 // Number all nodes with a topological order and set DAGSize.
741 DAGSize = CurDAG->AssignTopologicalOrder();
743 // Create a dummy node (which is not added to allnodes), that adds
744 // a reference to the root node, preventing it from being deleted,
745 // and tracking any changes of the root.
746 HandleSDNode Dummy(CurDAG->getRoot());
747 SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode());
750 // Make sure that ISelPosition gets properly updated when nodes are deleted
751 // in calls made from this function.
752 ISelUpdater ISU(*CurDAG, ISelPosition);
754 // The AllNodes list is now topological-sorted. Visit the
755 // nodes by starting at the end of the list (the root of the
756 // graph) and preceding back toward the beginning (the entry
758 while (ISelPosition != CurDAG->allnodes_begin()) {
759 SDNode *Node = --ISelPosition;
760 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
761 // but there are currently some corner cases that it misses. Also, this
762 // makes it theoretically possible to disable the DAGCombiner.
763 if (Node->use_empty())
766 SDNode *ResNode = Select(Node);
768 // FIXME: This is pretty gross. 'Select' should be changed to not return
769 // anything at all and this code should be nuked with a tactical strike.
771 // If node should not be replaced, continue with the next one.
772 if (ResNode == Node || Node->getOpcode() == ISD::DELETED_NODE)
776 ReplaceUses(Node, ResNode);
778 // If after the replacement this node is not used any more,
779 // remove this dead node.
780 if (Node->use_empty()) // Don't delete EntryToken, etc.
781 CurDAG->RemoveDeadNode(Node);
784 CurDAG->setRoot(Dummy.getValue());
787 DEBUG(errs() << "===== Instruction selection ends:\n");
789 PostprocessISelDAG();
792 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
793 /// do other setup for EH landing-pad blocks.
794 void SelectionDAGISel::PrepareEHLandingPad() {
795 MachineBasicBlock *MBB = FuncInfo->MBB;
797 // Add a label to mark the beginning of the landing pad. Deletion of the
798 // landing pad can thus be detected via the MachineModuleInfo.
799 MCSymbol *Label = MF->getMMI().addLandingPad(MBB);
801 // Assign the call site to the landing pad's begin label.
802 MF->getMMI().setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
804 const MCInstrDesc &II = TM.getInstrInfo()->get(TargetOpcode::EH_LABEL);
805 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
808 // Mark exception register as live in.
809 unsigned Reg = TLI.getExceptionPointerRegister();
810 if (Reg) MBB->addLiveIn(Reg);
812 // Mark exception selector register as live in.
813 Reg = TLI.getExceptionSelectorRegister();
814 if (Reg) MBB->addLiveIn(Reg);
817 /// TryToFoldFastISelLoad - We're checking to see if we can fold the specified
818 /// load into the specified FoldInst. Note that we could have a sequence where
819 /// multiple LLVM IR instructions are folded into the same machineinstr. For
820 /// example we could have:
821 /// A: x = load i32 *P
822 /// B: y = icmp A, 42
825 /// In this scenario, LI is "A", and FoldInst is "C". We know about "B" (and
826 /// any other folded instructions) because it is between A and C.
828 /// If we succeed in folding the load into the operation, return true.
830 bool SelectionDAGISel::TryToFoldFastISelLoad(const LoadInst *LI,
831 const Instruction *FoldInst,
833 // We know that the load has a single use, but don't know what it is. If it
834 // isn't one of the folded instructions, then we can't succeed here. Handle
835 // this by scanning the single-use users of the load until we get to FoldInst.
836 unsigned MaxUsers = 6; // Don't scan down huge single-use chains of instrs.
838 const Instruction *TheUser = LI->use_back();
839 while (TheUser != FoldInst && // Scan up until we find FoldInst.
840 // Stay in the right block.
841 TheUser->getParent() == FoldInst->getParent() &&
842 --MaxUsers) { // Don't scan too far.
843 // If there are multiple or no uses of this instruction, then bail out.
844 if (!TheUser->hasOneUse())
847 TheUser = TheUser->use_back();
850 // If we didn't find the fold instruction, then we failed to collapse the
852 if (TheUser != FoldInst)
855 // Don't try to fold volatile loads. Target has to deal with alignment
857 if (LI->isVolatile()) return false;
859 // Figure out which vreg this is going into. If there is no assigned vreg yet
860 // then there actually was no reference to it. Perhaps the load is referenced
861 // by a dead instruction.
862 unsigned LoadReg = FastIS->getRegForValue(LI);
866 // Check to see what the uses of this vreg are. If it has no uses, or more
867 // than one use (at the machine instr level) then we can't fold it.
868 MachineRegisterInfo::reg_iterator RI = RegInfo->reg_begin(LoadReg);
869 if (RI == RegInfo->reg_end())
872 // See if there is exactly one use of the vreg. If there are multiple uses,
873 // then the instruction got lowered to multiple machine instructions or the
874 // use of the loaded value ended up being multiple operands of the result, in
875 // either case, we can't fold this.
876 MachineRegisterInfo::reg_iterator PostRI = RI; ++PostRI;
877 if (PostRI != RegInfo->reg_end())
880 assert(RI.getOperand().isUse() &&
881 "The only use of the vreg must be a use, we haven't emitted the def!");
883 MachineInstr *User = &*RI;
885 // Set the insertion point properly. Folding the load can cause generation of
886 // other random instructions (like sign extends) for addressing modes, make
887 // sure they get inserted in a logical place before the new instruction.
888 FuncInfo->InsertPt = User;
889 FuncInfo->MBB = User->getParent();
891 // Ask the target to try folding the load.
892 return FastIS->TryToFoldLoad(User, RI.getOperandNo(), LI);
895 /// isFoldedOrDeadInstruction - Return true if the specified instruction is
896 /// side-effect free and is either dead or folded into a generated instruction.
897 /// Return false if it needs to be emitted.
898 static bool isFoldedOrDeadInstruction(const Instruction *I,
899 FunctionLoweringInfo *FuncInfo) {
900 return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
901 !isa<TerminatorInst>(I) && // Terminators aren't folded.
902 !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded.
903 !isa<LandingPadInst>(I) && // Landingpad instructions aren't folded.
904 !FuncInfo->isExportedInst(I); // Exported instrs must be computed.
908 // Collect per Instruction statistics for fast-isel misses. Only those
909 // instructions that cause the bail are accounted for. It does not account for
910 // instructions higher in the block. Thus, summing the per instructions stats
911 // will not add up to what is reported by NumFastIselFailures.
912 static void collectFailStats(const Instruction *I) {
913 switch (I->getOpcode()) {
914 default: assert (0 && "<Invalid operator> ");
917 case Instruction::Ret: NumFastIselFailRet++; return;
918 case Instruction::Br: NumFastIselFailBr++; return;
919 case Instruction::Switch: NumFastIselFailSwitch++; return;
920 case Instruction::IndirectBr: NumFastIselFailIndirectBr++; return;
921 case Instruction::Invoke: NumFastIselFailInvoke++; return;
922 case Instruction::Resume: NumFastIselFailResume++; return;
923 case Instruction::Unreachable: NumFastIselFailUnreachable++; return;
925 // Standard binary operators...
926 case Instruction::Add: NumFastIselFailAdd++; return;
927 case Instruction::FAdd: NumFastIselFailFAdd++; return;
928 case Instruction::Sub: NumFastIselFailSub++; return;
929 case Instruction::FSub: NumFastIselFailFSub++; return;
930 case Instruction::Mul: NumFastIselFailMul++; return;
931 case Instruction::FMul: NumFastIselFailFMul++; return;
932 case Instruction::UDiv: NumFastIselFailUDiv++; return;
933 case Instruction::SDiv: NumFastIselFailSDiv++; return;
934 case Instruction::FDiv: NumFastIselFailFDiv++; return;
935 case Instruction::URem: NumFastIselFailURem++; return;
936 case Instruction::SRem: NumFastIselFailSRem++; return;
937 case Instruction::FRem: NumFastIselFailFRem++; return;
939 // Logical operators...
940 case Instruction::And: NumFastIselFailAnd++; return;
941 case Instruction::Or: NumFastIselFailOr++; return;
942 case Instruction::Xor: NumFastIselFailXor++; return;
944 // Memory instructions...
945 case Instruction::Alloca: NumFastIselFailAlloca++; return;
946 case Instruction::Load: NumFastIselFailLoad++; return;
947 case Instruction::Store: NumFastIselFailStore++; return;
948 case Instruction::AtomicCmpXchg: NumFastIselFailAtomicCmpXchg++; return;
949 case Instruction::AtomicRMW: NumFastIselFailAtomicRMW++; return;
950 case Instruction::Fence: NumFastIselFailFence++; return;
951 case Instruction::GetElementPtr: NumFastIselFailGetElementPtr++; return;
953 // Convert instructions...
954 case Instruction::Trunc: NumFastIselFailTrunc++; return;
955 case Instruction::ZExt: NumFastIselFailZExt++; return;
956 case Instruction::SExt: NumFastIselFailSExt++; return;
957 case Instruction::FPTrunc: NumFastIselFailFPTrunc++; return;
958 case Instruction::FPExt: NumFastIselFailFPExt++; return;
959 case Instruction::FPToUI: NumFastIselFailFPToUI++; return;
960 case Instruction::FPToSI: NumFastIselFailFPToSI++; return;
961 case Instruction::UIToFP: NumFastIselFailUIToFP++; return;
962 case Instruction::SIToFP: NumFastIselFailSIToFP++; return;
963 case Instruction::IntToPtr: NumFastIselFailIntToPtr++; return;
964 case Instruction::PtrToInt: NumFastIselFailPtrToInt++; return;
965 case Instruction::BitCast: NumFastIselFailBitCast++; return;
967 // Other instructions...
968 case Instruction::ICmp: NumFastIselFailICmp++; return;
969 case Instruction::FCmp: NumFastIselFailFCmp++; return;
970 case Instruction::PHI: NumFastIselFailPHI++; return;
971 case Instruction::Select: NumFastIselFailSelect++; return;
972 case Instruction::Call: NumFastIselFailCall++; return;
973 case Instruction::Shl: NumFastIselFailShl++; return;
974 case Instruction::LShr: NumFastIselFailLShr++; return;
975 case Instruction::AShr: NumFastIselFailAShr++; return;
976 case Instruction::VAArg: NumFastIselFailVAArg++; return;
977 case Instruction::ExtractElement: NumFastIselFailExtractElement++; return;
978 case Instruction::InsertElement: NumFastIselFailInsertElement++; return;
979 case Instruction::ShuffleVector: NumFastIselFailShuffleVector++; return;
980 case Instruction::ExtractValue: NumFastIselFailExtractValue++; return;
981 case Instruction::InsertValue: NumFastIselFailInsertValue++; return;
982 case Instruction::LandingPad: NumFastIselFailLandingPad++; return;
987 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
988 // Initialize the Fast-ISel state, if needed.
989 FastISel *FastIS = 0;
990 if (TM.Options.EnableFastISel)
991 FastIS = TLI.createFastISel(*FuncInfo, LibInfo);
993 // Iterate over all basic blocks in the function.
994 ReversePostOrderTraversal<const Function*> RPOT(&Fn);
995 for (ReversePostOrderTraversal<const Function*>::rpo_iterator
996 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
997 const BasicBlock *LLVMBB = *I;
999 if (OptLevel != CodeGenOpt::None) {
1000 bool AllPredsVisited = true;
1001 for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB);
1003 if (!FuncInfo->VisitedBBs.count(*PI)) {
1004 AllPredsVisited = false;
1009 if (AllPredsVisited) {
1010 for (BasicBlock::const_iterator I = LLVMBB->begin();
1011 const PHINode *PN = dyn_cast<PHINode>(I); ++I)
1012 FuncInfo->ComputePHILiveOutRegInfo(PN);
1014 for (BasicBlock::const_iterator I = LLVMBB->begin();
1015 const PHINode *PN = dyn_cast<PHINode>(I); ++I)
1016 FuncInfo->InvalidatePHILiveOutRegInfo(PN);
1019 FuncInfo->VisitedBBs.insert(LLVMBB);
1022 FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
1023 FuncInfo->InsertPt = FuncInfo->MBB->getFirstNonPHI();
1025 BasicBlock::const_iterator const Begin = LLVMBB->getFirstNonPHI();
1026 BasicBlock::const_iterator const End = LLVMBB->end();
1027 BasicBlock::const_iterator BI = End;
1029 FuncInfo->InsertPt = FuncInfo->MBB->getFirstNonPHI();
1031 // Setup an EH landing-pad block.
1032 if (FuncInfo->MBB->isLandingPad())
1033 PrepareEHLandingPad();
1035 // Before doing SelectionDAG ISel, see if FastISel has been requested.
1037 FastIS->startNewBlock();
1039 // Emit code for any incoming arguments. This must happen before
1040 // beginning FastISel on the entry block.
1041 if (LLVMBB == &Fn.getEntryBlock()) {
1042 // Lower any arguments needed in this block if this is the entry block.
1043 if (!FastIS->LowerArguments()) {
1044 // Call target indepedent SDISel argument lowering code if the target
1045 // specific routine is not successful.
1046 LowerArguments(LLVMBB);
1047 CurDAG->setRoot(SDB->getControlRoot());
1049 CodeGenAndEmitDAG();
1052 // If we inserted any instructions at the beginning, make a note of
1053 // where they are, so we can be sure to emit subsequent instructions
1055 if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
1056 FastIS->setLastLocalValue(llvm::prior(FuncInfo->InsertPt));
1058 FastIS->setLastLocalValue(0);
1061 unsigned NumFastIselRemaining = std::distance(Begin, End);
1062 // Do FastISel on as many instructions as possible.
1063 for (; BI != Begin; --BI) {
1064 const Instruction *Inst = llvm::prior(BI);
1066 // If we no longer require this instruction, skip it.
1067 if (isFoldedOrDeadInstruction(Inst, FuncInfo)) {
1068 --NumFastIselRemaining;
1072 // Bottom-up: reset the insert pos at the top, after any local-value
1074 FastIS->recomputeInsertPt();
1076 // Try to select the instruction with FastISel.
1077 if (FastIS->SelectInstruction(Inst)) {
1078 --NumFastIselRemaining;
1079 ++NumFastIselSuccess;
1080 // If fast isel succeeded, skip over all the folded instructions, and
1081 // then see if there is a load right before the selected instructions.
1082 // Try to fold the load if so.
1083 const Instruction *BeforeInst = Inst;
1084 while (BeforeInst != Begin) {
1085 BeforeInst = llvm::prior(BasicBlock::const_iterator(BeforeInst));
1086 if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo))
1089 if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
1090 BeforeInst->hasOneUse() &&
1091 TryToFoldFastISelLoad(cast<LoadInst>(BeforeInst), Inst, FastIS)) {
1092 // If we succeeded, don't re-select the load.
1093 BI = llvm::next(BasicBlock::const_iterator(BeforeInst));
1094 --NumFastIselRemaining;
1095 ++NumFastIselSuccess;
1101 if (EnableFastISelVerbose2)
1102 collectFailStats(Inst);
1105 // Then handle certain instructions as single-LLVM-Instruction blocks.
1106 if (isa<CallInst>(Inst)) {
1108 if (EnableFastISelVerbose || EnableFastISelAbort) {
1109 dbgs() << "FastISel missed call: ";
1113 if (!Inst->getType()->isVoidTy() && !Inst->use_empty()) {
1114 unsigned &R = FuncInfo->ValueMap[Inst];
1116 R = FuncInfo->CreateRegs(Inst->getType());
1119 bool HadTailCall = false;
1120 MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
1121 SelectBasicBlock(Inst, BI, HadTailCall);
1123 // If the call was emitted as a tail call, we're done with the block.
1124 // We also need to delete any previously emitted instructions.
1126 FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
1131 // Recompute NumFastIselRemaining as Selection DAG instruction
1132 // selection may have handled the call, input args, etc.
1133 unsigned RemainingNow = std::distance(Begin, BI);
1134 NumFastIselFailures += NumFastIselRemaining - RemainingNow;
1135 NumFastIselRemaining = RemainingNow;
1139 if (isa<TerminatorInst>(Inst) && !isa<BranchInst>(Inst)) {
1140 // Don't abort, and use a different message for terminator misses.
1141 NumFastIselFailures += NumFastIselRemaining;
1142 if (EnableFastISelVerbose || EnableFastISelAbort) {
1143 dbgs() << "FastISel missed terminator: ";
1147 NumFastIselFailures += NumFastIselRemaining;
1148 if (EnableFastISelVerbose || EnableFastISelAbort) {
1149 dbgs() << "FastISel miss: ";
1152 if (EnableFastISelAbort)
1153 // The "fast" selector couldn't handle something and bailed.
1154 // For the purpose of debugging, just abort.
1155 llvm_unreachable("FastISel didn't select the entire block");
1160 FastIS->recomputeInsertPt();
1162 // Lower any arguments needed in this block if this is the entry block.
1163 if (LLVMBB == &Fn.getEntryBlock())
1164 LowerArguments(LLVMBB);
1170 ++NumFastIselBlocks;
1173 // Run SelectionDAG instruction selection on the remainder of the block
1174 // not handled by FastISel. If FastISel is not run, this is the entire
1177 SelectBasicBlock(Begin, BI, HadTailCall);
1181 FuncInfo->PHINodesToUpdate.clear();
1185 SDB->clearDanglingDebugInfo();
1189 SelectionDAGISel::FinishBasicBlock() {
1191 DEBUG(dbgs() << "Total amount of phi nodes to update: "
1192 << FuncInfo->PHINodesToUpdate.size() << "\n";
1193 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i)
1194 dbgs() << "Node " << i << " : ("
1195 << FuncInfo->PHINodesToUpdate[i].first
1196 << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
1198 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1199 // PHI nodes in successors.
1200 if (SDB->SwitchCases.empty() &&
1201 SDB->JTCases.empty() &&
1202 SDB->BitTestCases.empty()) {
1203 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1204 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
1205 assert(PHI->isPHI() &&
1206 "This is not a machine PHI node that we are updating!");
1207 if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
1209 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
1214 for (unsigned i = 0, e = SDB->BitTestCases.size(); i != e; ++i) {
1215 // Lower header first, if it wasn't already lowered
1216 if (!SDB->BitTestCases[i].Emitted) {
1217 // Set the current basic block to the mbb we wish to insert the code into
1218 FuncInfo->MBB = SDB->BitTestCases[i].Parent;
1219 FuncInfo->InsertPt = FuncInfo->MBB->end();
1221 SDB->visitBitTestHeader(SDB->BitTestCases[i], FuncInfo->MBB);
1222 CurDAG->setRoot(SDB->getRoot());
1224 CodeGenAndEmitDAG();
1227 uint32_t UnhandledWeight = 0;
1228 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j)
1229 UnhandledWeight += SDB->BitTestCases[i].Cases[j].ExtraWeight;
1231 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j) {
1232 UnhandledWeight -= SDB->BitTestCases[i].Cases[j].ExtraWeight;
1233 // Set the current basic block to the mbb we wish to insert the code into
1234 FuncInfo->MBB = SDB->BitTestCases[i].Cases[j].ThisBB;
1235 FuncInfo->InsertPt = FuncInfo->MBB->end();
1238 SDB->visitBitTestCase(SDB->BitTestCases[i],
1239 SDB->BitTestCases[i].Cases[j+1].ThisBB,
1241 SDB->BitTestCases[i].Reg,
1242 SDB->BitTestCases[i].Cases[j],
1245 SDB->visitBitTestCase(SDB->BitTestCases[i],
1246 SDB->BitTestCases[i].Default,
1248 SDB->BitTestCases[i].Reg,
1249 SDB->BitTestCases[i].Cases[j],
1253 CurDAG->setRoot(SDB->getRoot());
1255 CodeGenAndEmitDAG();
1259 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1261 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1262 MachineBasicBlock *PHIBB = PHI->getParent();
1263 assert(PHI->isPHI() &&
1264 "This is not a machine PHI node that we are updating!");
1265 // This is "default" BB. We have two jumps to it. From "header" BB and
1266 // from last "case" BB.
1267 if (PHIBB == SDB->BitTestCases[i].Default)
1268 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1269 .addMBB(SDB->BitTestCases[i].Parent)
1270 .addReg(FuncInfo->PHINodesToUpdate[pi].second)
1271 .addMBB(SDB->BitTestCases[i].Cases.back().ThisBB);
1272 // One of "cases" BB.
1273 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size();
1275 MachineBasicBlock* cBB = SDB->BitTestCases[i].Cases[j].ThisBB;
1276 if (cBB->isSuccessor(PHIBB))
1277 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB);
1281 SDB->BitTestCases.clear();
1283 // If the JumpTable record is filled in, then we need to emit a jump table.
1284 // Updating the PHI nodes is tricky in this case, since we need to determine
1285 // whether the PHI is a successor of the range check MBB or the jump table MBB
1286 for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
1287 // Lower header first, if it wasn't already lowered
1288 if (!SDB->JTCases[i].first.Emitted) {
1289 // Set the current basic block to the mbb we wish to insert the code into
1290 FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB;
1291 FuncInfo->InsertPt = FuncInfo->MBB->end();
1293 SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first,
1295 CurDAG->setRoot(SDB->getRoot());
1297 CodeGenAndEmitDAG();
1300 // Set the current basic block to the mbb we wish to insert the code into
1301 FuncInfo->MBB = SDB->JTCases[i].second.MBB;
1302 FuncInfo->InsertPt = FuncInfo->MBB->end();
1304 SDB->visitJumpTable(SDB->JTCases[i].second);
1305 CurDAG->setRoot(SDB->getRoot());
1307 CodeGenAndEmitDAG();
1310 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1312 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1313 MachineBasicBlock *PHIBB = PHI->getParent();
1314 assert(PHI->isPHI() &&
1315 "This is not a machine PHI node that we are updating!");
1316 // "default" BB. We can go there only from header BB.
1317 if (PHIBB == SDB->JTCases[i].second.Default)
1318 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1319 .addMBB(SDB->JTCases[i].first.HeaderBB);
1320 // JT BB. Just iterate over successors here
1321 if (FuncInfo->MBB->isSuccessor(PHIBB))
1322 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
1325 SDB->JTCases.clear();
1327 // If the switch block involved a branch to one of the actual successors, we
1328 // need to update PHI nodes in that block.
1329 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1330 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
1331 assert(PHI->isPHI() &&
1332 "This is not a machine PHI node that we are updating!");
1333 if (FuncInfo->MBB->isSuccessor(PHI->getParent()))
1334 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
1337 // If we generated any switch lowering information, build and codegen any
1338 // additional DAGs necessary.
1339 for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
1340 // Set the current basic block to the mbb we wish to insert the code into
1341 FuncInfo->MBB = SDB->SwitchCases[i].ThisBB;
1342 FuncInfo->InsertPt = FuncInfo->MBB->end();
1344 // Determine the unique successors.
1345 SmallVector<MachineBasicBlock *, 2> Succs;
1346 Succs.push_back(SDB->SwitchCases[i].TrueBB);
1347 if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB)
1348 Succs.push_back(SDB->SwitchCases[i].FalseBB);
1350 // Emit the code. Note that this could result in FuncInfo->MBB being split.
1351 SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB);
1352 CurDAG->setRoot(SDB->getRoot());
1354 CodeGenAndEmitDAG();
1356 // Remember the last block, now that any splitting is done, for use in
1357 // populating PHI nodes in successors.
1358 MachineBasicBlock *ThisBB = FuncInfo->MBB;
1360 // Handle any PHI nodes in successors of this chunk, as if we were coming
1361 // from the original BB before switch expansion. Note that PHI nodes can
1362 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1363 // handle them the right number of times.
1364 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1365 FuncInfo->MBB = Succs[i];
1366 FuncInfo->InsertPt = FuncInfo->MBB->end();
1367 // FuncInfo->MBB may have been removed from the CFG if a branch was
1369 if (ThisBB->isSuccessor(FuncInfo->MBB)) {
1370 for (MachineBasicBlock::iterator
1371 MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
1372 MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
1373 MachineInstrBuilder PHI(*MF, MBBI);
1374 // This value for this PHI node is recorded in PHINodesToUpdate.
1375 for (unsigned pn = 0; ; ++pn) {
1376 assert(pn != FuncInfo->PHINodesToUpdate.size() &&
1377 "Didn't find PHI entry!");
1378 if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
1379 PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
1387 SDB->SwitchCases.clear();
1391 /// Create the scheduler. If a specific scheduler was specified
1392 /// via the SchedulerRegistry, use it, otherwise select the
1393 /// one preferred by the target.
1395 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1396 RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
1400 RegisterScheduler::setDefault(Ctor);
1403 return Ctor(this, OptLevel);
1406 //===----------------------------------------------------------------------===//
1407 // Helper functions used by the generated instruction selector.
1408 //===----------------------------------------------------------------------===//
1409 // Calls to these methods are generated by tblgen.
1411 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
1412 /// the dag combiner simplified the 255, we still want to match. RHS is the
1413 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1414 /// specified in the .td file (e.g. 255).
1415 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1416 int64_t DesiredMaskS) const {
1417 const APInt &ActualMask = RHS->getAPIntValue();
1418 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1420 // If the actual mask exactly matches, success!
1421 if (ActualMask == DesiredMask)
1424 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1425 if (ActualMask.intersects(~DesiredMask))
1428 // Otherwise, the DAG Combiner may have proven that the value coming in is
1429 // either already zero or is not demanded. Check for known zero input bits.
1430 APInt NeededMask = DesiredMask & ~ActualMask;
1431 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1434 // TODO: check to see if missing bits are just not demanded.
1436 // Otherwise, this pattern doesn't match.
1440 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
1441 /// the dag combiner simplified the 255, we still want to match. RHS is the
1442 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1443 /// specified in the .td file (e.g. 255).
1444 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
1445 int64_t DesiredMaskS) const {
1446 const APInt &ActualMask = RHS->getAPIntValue();
1447 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1449 // If the actual mask exactly matches, success!
1450 if (ActualMask == DesiredMask)
1453 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1454 if (ActualMask.intersects(~DesiredMask))
1457 // Otherwise, the DAG Combiner may have proven that the value coming in is
1458 // either already zero or is not demanded. Check for known zero input bits.
1459 APInt NeededMask = DesiredMask & ~ActualMask;
1461 APInt KnownZero, KnownOne;
1462 CurDAG->ComputeMaskedBits(LHS, KnownZero, KnownOne);
1464 // If all the missing bits in the or are already known to be set, match!
1465 if ((NeededMask & KnownOne) == NeededMask)
1468 // TODO: check to see if missing bits are just not demanded.
1470 // Otherwise, this pattern doesn't match.
1475 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1476 /// by tblgen. Others should not call it.
1477 void SelectionDAGISel::
1478 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
1479 std::vector<SDValue> InOps;
1480 std::swap(InOps, Ops);
1482 Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
1483 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1
1484 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc
1485 Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack)
1487 unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
1488 if (InOps[e-1].getValueType() == MVT::Glue)
1489 --e; // Don't process a glue operand if it is here.
1492 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1493 if (!InlineAsm::isMemKind(Flags)) {
1494 // Just skip over this operand, copying the operands verbatim.
1495 Ops.insert(Ops.end(), InOps.begin()+i,
1496 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1497 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
1499 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1500 "Memory operand with multiple values?");
1501 // Otherwise, this is a memory operand. Ask the target to select it.
1502 std::vector<SDValue> SelOps;
1503 if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps))
1504 report_fatal_error("Could not match memory address. Inline asm"
1507 // Add this to the output node.
1509 InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
1510 Ops.push_back(CurDAG->getTargetConstant(NewFlags, MVT::i32));
1511 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1516 // Add the glue input back if present.
1517 if (e != InOps.size())
1518 Ops.push_back(InOps.back());
1521 /// findGlueUse - Return use of MVT::Glue value produced by the specified
1524 static SDNode *findGlueUse(SDNode *N) {
1525 unsigned FlagResNo = N->getNumValues()-1;
1526 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1527 SDUse &Use = I.getUse();
1528 if (Use.getResNo() == FlagResNo)
1529 return Use.getUser();
1534 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1535 /// This function recursively traverses up the operand chain, ignoring
1537 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
1538 SDNode *Root, SmallPtrSet<SDNode*, 16> &Visited,
1539 bool IgnoreChains) {
1540 // The NodeID's are given uniques ID's where a node ID is guaranteed to be
1541 // greater than all of its (recursive) operands. If we scan to a point where
1542 // 'use' is smaller than the node we're scanning for, then we know we will
1545 // The Use may be -1 (unassigned) if it is a newly allocated node. This can
1546 // happen because we scan down to newly selected nodes in the case of glue
1548 if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1))
1551 // Don't revisit nodes if we already scanned it and didn't fail, we know we
1552 // won't fail if we scan it again.
1553 if (!Visited.insert(Use))
1556 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
1557 // Ignore chain uses, they are validated by HandleMergeInputChains.
1558 if (Use->getOperand(i).getValueType() == MVT::Other && IgnoreChains)
1561 SDNode *N = Use->getOperand(i).getNode();
1563 if (Use == ImmedUse || Use == Root)
1564 continue; // We are not looking for immediate use.
1569 // Traverse up the operand chain.
1570 if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains))
1576 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
1577 /// operand node N of U during instruction selection that starts at Root.
1578 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
1579 SDNode *Root) const {
1580 if (OptLevel == CodeGenOpt::None) return false;
1581 return N.hasOneUse();
1584 /// IsLegalToFold - Returns true if the specific operand node N of
1585 /// U can be folded during instruction selection that starts at Root.
1586 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
1587 CodeGenOpt::Level OptLevel,
1588 bool IgnoreChains) {
1589 if (OptLevel == CodeGenOpt::None) return false;
1591 // If Root use can somehow reach N through a path that that doesn't contain
1592 // U then folding N would create a cycle. e.g. In the following
1593 // diagram, Root can reach N through X. If N is folded into into Root, then
1594 // X is both a predecessor and a successor of U.
1605 // * indicates nodes to be folded together.
1607 // If Root produces glue, then it gets (even more) interesting. Since it
1608 // will be "glued" together with its glue use in the scheduler, we need to
1609 // check if it might reach N.
1628 // If GU (glue use) indirectly reaches N (the load), and Root folds N
1629 // (call it Fold), then X is a predecessor of GU and a successor of
1630 // Fold. But since Fold and GU are glued together, this will create
1631 // a cycle in the scheduling graph.
1633 // If the node has glue, walk down the graph to the "lowest" node in the
1635 EVT VT = Root->getValueType(Root->getNumValues()-1);
1636 while (VT == MVT::Glue) {
1637 SDNode *GU = findGlueUse(Root);
1641 VT = Root->getValueType(Root->getNumValues()-1);
1643 // If our query node has a glue result with a use, we've walked up it. If
1644 // the user (which has already been selected) has a chain or indirectly uses
1645 // the chain, our WalkChainUsers predicate will not consider it. Because of
1646 // this, we cannot ignore chains in this predicate.
1647 IgnoreChains = false;
1651 SmallPtrSet<SDNode*, 16> Visited;
1652 return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
1655 SDNode *SelectionDAGISel::Select_INLINEASM(SDNode *N) {
1656 std::vector<SDValue> Ops(N->op_begin(), N->op_end());
1657 SelectInlineAsmMemoryOperands(Ops);
1659 std::vector<EVT> VTs;
1660 VTs.push_back(MVT::Other);
1661 VTs.push_back(MVT::Glue);
1662 SDValue New = CurDAG->getNode(ISD::INLINEASM, N->getDebugLoc(),
1663 VTs, &Ops[0], Ops.size());
1665 return New.getNode();
1668 SDNode *SelectionDAGISel::Select_UNDEF(SDNode *N) {
1669 return CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF,N->getValueType(0));
1672 /// GetVBR - decode a vbr encoding whose top bit is set.
1673 LLVM_ATTRIBUTE_ALWAYS_INLINE static uint64_t
1674 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
1675 assert(Val >= 128 && "Not a VBR");
1676 Val &= 127; // Remove first vbr bit.
1681 NextBits = MatcherTable[Idx++];
1682 Val |= (NextBits&127) << Shift;
1684 } while (NextBits & 128);
1690 /// UpdateChainsAndGlue - When a match is complete, this method updates uses of
1691 /// interior glue and chain results to use the new glue and chain results.
1692 void SelectionDAGISel::
1693 UpdateChainsAndGlue(SDNode *NodeToMatch, SDValue InputChain,
1694 const SmallVectorImpl<SDNode*> &ChainNodesMatched,
1696 const SmallVectorImpl<SDNode*> &GlueResultNodesMatched,
1697 bool isMorphNodeTo) {
1698 SmallVector<SDNode*, 4> NowDeadNodes;
1700 // Now that all the normal results are replaced, we replace the chain and
1701 // glue results if present.
1702 if (!ChainNodesMatched.empty()) {
1703 assert(InputChain.getNode() != 0 &&
1704 "Matched input chains but didn't produce a chain");
1705 // Loop over all of the nodes we matched that produced a chain result.
1706 // Replace all the chain results with the final chain we ended up with.
1707 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1708 SDNode *ChainNode = ChainNodesMatched[i];
1710 // If this node was already deleted, don't look at it.
1711 if (ChainNode->getOpcode() == ISD::DELETED_NODE)
1714 // Don't replace the results of the root node if we're doing a
1716 if (ChainNode == NodeToMatch && isMorphNodeTo)
1719 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
1720 if (ChainVal.getValueType() == MVT::Glue)
1721 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
1722 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
1723 CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain);
1725 // If the node became dead and we haven't already seen it, delete it.
1726 if (ChainNode->use_empty() &&
1727 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
1728 NowDeadNodes.push_back(ChainNode);
1732 // If the result produces glue, update any glue results in the matched
1733 // pattern with the glue result.
1734 if (InputGlue.getNode() != 0) {
1735 // Handle any interior nodes explicitly marked.
1736 for (unsigned i = 0, e = GlueResultNodesMatched.size(); i != e; ++i) {
1737 SDNode *FRN = GlueResultNodesMatched[i];
1739 // If this node was already deleted, don't look at it.
1740 if (FRN->getOpcode() == ISD::DELETED_NODE)
1743 assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Glue &&
1744 "Doesn't have a glue result");
1745 CurDAG->ReplaceAllUsesOfValueWith(SDValue(FRN, FRN->getNumValues()-1),
1748 // If the node became dead and we haven't already seen it, delete it.
1749 if (FRN->use_empty() &&
1750 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), FRN))
1751 NowDeadNodes.push_back(FRN);
1755 if (!NowDeadNodes.empty())
1756 CurDAG->RemoveDeadNodes(NowDeadNodes);
1758 DEBUG(errs() << "ISEL: Match complete!\n");
1764 CR_LeadsToInteriorNode
1767 /// WalkChainUsers - Walk down the users of the specified chained node that is
1768 /// part of the pattern we're matching, looking at all of the users we find.
1769 /// This determines whether something is an interior node, whether we have a
1770 /// non-pattern node in between two pattern nodes (which prevent folding because
1771 /// it would induce a cycle) and whether we have a TokenFactor node sandwiched
1772 /// between pattern nodes (in which case the TF becomes part of the pattern).
1774 /// The walk we do here is guaranteed to be small because we quickly get down to
1775 /// already selected nodes "below" us.
1777 WalkChainUsers(const SDNode *ChainedNode,
1778 SmallVectorImpl<SDNode*> &ChainedNodesInPattern,
1779 SmallVectorImpl<SDNode*> &InteriorChainedNodes) {
1780 ChainResult Result = CR_Simple;
1782 for (SDNode::use_iterator UI = ChainedNode->use_begin(),
1783 E = ChainedNode->use_end(); UI != E; ++UI) {
1784 // Make sure the use is of the chain, not some other value we produce.
1785 if (UI.getUse().getValueType() != MVT::Other) continue;
1789 // If we see an already-selected machine node, then we've gone beyond the
1790 // pattern that we're selecting down into the already selected chunk of the
1792 if (User->isMachineOpcode() ||
1793 User->getOpcode() == ISD::HANDLENODE) // Root of the graph.
1796 unsigned UserOpcode = User->getOpcode();
1797 if (UserOpcode == ISD::CopyToReg ||
1798 UserOpcode == ISD::CopyFromReg ||
1799 UserOpcode == ISD::INLINEASM ||
1800 UserOpcode == ISD::EH_LABEL ||
1801 UserOpcode == ISD::LIFETIME_START ||
1802 UserOpcode == ISD::LIFETIME_END) {
1803 // If their node ID got reset to -1 then they've already been selected.
1804 // Treat them like a MachineOpcode.
1805 if (User->getNodeId() == -1)
1809 // If we have a TokenFactor, we handle it specially.
1810 if (User->getOpcode() != ISD::TokenFactor) {
1811 // If the node isn't a token factor and isn't part of our pattern, then it
1812 // must be a random chained node in between two nodes we're selecting.
1813 // This happens when we have something like:
1818 // Because we structurally match the load/store as a read/modify/write,
1819 // but the call is chained between them. We cannot fold in this case
1820 // because it would induce a cycle in the graph.
1821 if (!std::count(ChainedNodesInPattern.begin(),
1822 ChainedNodesInPattern.end(), User))
1823 return CR_InducesCycle;
1825 // Otherwise we found a node that is part of our pattern. For example in:
1829 // This would happen when we're scanning down from the load and see the
1830 // store as a user. Record that there is a use of ChainedNode that is
1831 // part of the pattern and keep scanning uses.
1832 Result = CR_LeadsToInteriorNode;
1833 InteriorChainedNodes.push_back(User);
1837 // If we found a TokenFactor, there are two cases to consider: first if the
1838 // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
1839 // uses of the TF are in our pattern) we just want to ignore it. Second,
1840 // the TokenFactor can be sandwiched in between two chained nodes, like so:
1846 // | \ DAG's like cheese
1849 // [TokenFactor] [Op]
1856 // In this case, the TokenFactor becomes part of our match and we rewrite it
1857 // as a new TokenFactor.
1859 // To distinguish these two cases, do a recursive walk down the uses.
1860 switch (WalkChainUsers(User, ChainedNodesInPattern, InteriorChainedNodes)) {
1862 // If the uses of the TokenFactor are just already-selected nodes, ignore
1863 // it, it is "below" our pattern.
1865 case CR_InducesCycle:
1866 // If the uses of the TokenFactor lead to nodes that are not part of our
1867 // pattern that are not selected, folding would turn this into a cycle,
1869 return CR_InducesCycle;
1870 case CR_LeadsToInteriorNode:
1871 break; // Otherwise, keep processing.
1874 // Okay, we know we're in the interesting interior case. The TokenFactor
1875 // is now going to be considered part of the pattern so that we rewrite its
1876 // uses (it may have uses that are not part of the pattern) with the
1877 // ultimate chain result of the generated code. We will also add its chain
1878 // inputs as inputs to the ultimate TokenFactor we create.
1879 Result = CR_LeadsToInteriorNode;
1880 ChainedNodesInPattern.push_back(User);
1881 InteriorChainedNodes.push_back(User);
1888 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
1889 /// operation for when the pattern matched at least one node with a chains. The
1890 /// input vector contains a list of all of the chained nodes that we match. We
1891 /// must determine if this is a valid thing to cover (i.e. matching it won't
1892 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
1893 /// be used as the input node chain for the generated nodes.
1895 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
1896 SelectionDAG *CurDAG) {
1897 // Walk all of the chained nodes we've matched, recursively scanning down the
1898 // users of the chain result. This adds any TokenFactor nodes that are caught
1899 // in between chained nodes to the chained and interior nodes list.
1900 SmallVector<SDNode*, 3> InteriorChainedNodes;
1901 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1902 if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
1903 InteriorChainedNodes) == CR_InducesCycle)
1904 return SDValue(); // Would induce a cycle.
1907 // Okay, we have walked all the matched nodes and collected TokenFactor nodes
1908 // that we are interested in. Form our input TokenFactor node.
1909 SmallVector<SDValue, 3> InputChains;
1910 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
1911 // Add the input chain of this node to the InputChains list (which will be
1912 // the operands of the generated TokenFactor) if it's not an interior node.
1913 SDNode *N = ChainNodesMatched[i];
1914 if (N->getOpcode() != ISD::TokenFactor) {
1915 if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
1918 // Otherwise, add the input chain.
1919 SDValue InChain = ChainNodesMatched[i]->getOperand(0);
1920 assert(InChain.getValueType() == MVT::Other && "Not a chain");
1921 InputChains.push_back(InChain);
1925 // If we have a token factor, we want to add all inputs of the token factor
1926 // that are not part of the pattern we're matching.
1927 for (unsigned op = 0, e = N->getNumOperands(); op != e; ++op) {
1928 if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
1929 N->getOperand(op).getNode()))
1930 InputChains.push_back(N->getOperand(op));
1935 if (InputChains.size() == 1)
1936 return InputChains[0];
1937 return CurDAG->getNode(ISD::TokenFactor, ChainNodesMatched[0]->getDebugLoc(),
1938 MVT::Other, &InputChains[0], InputChains.size());
1941 /// MorphNode - Handle morphing a node in place for the selector.
1942 SDNode *SelectionDAGISel::
1943 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
1944 const SDValue *Ops, unsigned NumOps, unsigned EmitNodeInfo) {
1945 // It is possible we're using MorphNodeTo to replace a node with no
1946 // normal results with one that has a normal result (or we could be
1947 // adding a chain) and the input could have glue and chains as well.
1948 // In this case we need to shift the operands down.
1949 // FIXME: This is a horrible hack and broken in obscure cases, no worse
1950 // than the old isel though.
1951 int OldGlueResultNo = -1, OldChainResultNo = -1;
1953 unsigned NTMNumResults = Node->getNumValues();
1954 if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
1955 OldGlueResultNo = NTMNumResults-1;
1956 if (NTMNumResults != 1 &&
1957 Node->getValueType(NTMNumResults-2) == MVT::Other)
1958 OldChainResultNo = NTMNumResults-2;
1959 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
1960 OldChainResultNo = NTMNumResults-1;
1962 // Call the underlying SelectionDAG routine to do the transmogrification. Note
1963 // that this deletes operands of the old node that become dead.
1964 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops, NumOps);
1966 // MorphNodeTo can operate in two ways: if an existing node with the
1967 // specified operands exists, it can just return it. Otherwise, it
1968 // updates the node in place to have the requested operands.
1970 // If we updated the node in place, reset the node ID. To the isel,
1971 // this should be just like a newly allocated machine node.
1975 unsigned ResNumResults = Res->getNumValues();
1976 // Move the glue if needed.
1977 if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
1978 (unsigned)OldGlueResultNo != ResNumResults-1)
1979 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldGlueResultNo),
1980 SDValue(Res, ResNumResults-1));
1982 if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
1985 // Move the chain reference if needed.
1986 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
1987 (unsigned)OldChainResultNo != ResNumResults-1)
1988 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
1989 SDValue(Res, ResNumResults-1));
1991 // Otherwise, no replacement happened because the node already exists. Replace
1992 // Uses of the old node with the new one.
1994 CurDAG->ReplaceAllUsesWith(Node, Res);
1999 /// CheckSame - Implements OP_CheckSame.
2000 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2001 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2003 const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
2004 // Accept if it is exactly the same as a previously recorded node.
2005 unsigned RecNo = MatcherTable[MatcherIndex++];
2006 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2007 return N == RecordedNodes[RecNo].first;
2010 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
2011 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2012 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2013 const SelectionDAGISel &SDISel) {
2014 return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
2017 /// CheckNodePredicate - Implements OP_CheckNodePredicate.
2018 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2019 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2020 const SelectionDAGISel &SDISel, SDNode *N) {
2021 return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
2024 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2025 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2027 uint16_t Opc = MatcherTable[MatcherIndex++];
2028 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2029 return N->getOpcode() == Opc;
2032 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2033 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2034 SDValue N, const TargetLowering &TLI) {
2035 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2036 if (N.getValueType() == VT) return true;
2038 // Handle the case when VT is iPTR.
2039 return VT == MVT::iPTR && N.getValueType() == TLI.getPointerTy();
2042 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2043 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2044 SDValue N, const TargetLowering &TLI,
2046 if (ChildNo >= N.getNumOperands())
2047 return false; // Match fails if out of range child #.
2048 return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI);
2052 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2053 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2055 return cast<CondCodeSDNode>(N)->get() ==
2056 (ISD::CondCode)MatcherTable[MatcherIndex++];
2059 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2060 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2061 SDValue N, const TargetLowering &TLI) {
2062 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2063 if (cast<VTSDNode>(N)->getVT() == VT)
2066 // Handle the case when VT is iPTR.
2067 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI.getPointerTy();
2070 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2071 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2073 int64_t Val = MatcherTable[MatcherIndex++];
2075 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2077 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
2078 return C != 0 && C->getSExtValue() == Val;
2081 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2082 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2083 SDValue N, const SelectionDAGISel &SDISel) {
2084 int64_t Val = MatcherTable[MatcherIndex++];
2086 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2088 if (N->getOpcode() != ISD::AND) return false;
2090 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2091 return C != 0 && SDISel.CheckAndMask(N.getOperand(0), C, Val);
2094 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2095 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2096 SDValue N, const SelectionDAGISel &SDISel) {
2097 int64_t Val = MatcherTable[MatcherIndex++];
2099 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2101 if (N->getOpcode() != ISD::OR) return false;
2103 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2104 return C != 0 && SDISel.CheckOrMask(N.getOperand(0), C, Val);
2107 /// IsPredicateKnownToFail - If we know how and can do so without pushing a
2108 /// scope, evaluate the current node. If the current predicate is known to
2109 /// fail, set Result=true and return anything. If the current predicate is
2110 /// known to pass, set Result=false and return the MatcherIndex to continue
2111 /// with. If the current predicate is unknown, set Result=false and return the
2112 /// MatcherIndex to continue with.
2113 static unsigned IsPredicateKnownToFail(const unsigned char *Table,
2114 unsigned Index, SDValue N,
2116 const SelectionDAGISel &SDISel,
2117 SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
2118 switch (Table[Index++]) {
2121 return Index-1; // Could not evaluate this predicate.
2122 case SelectionDAGISel::OPC_CheckSame:
2123 Result = !::CheckSame(Table, Index, N, RecordedNodes);
2125 case SelectionDAGISel::OPC_CheckPatternPredicate:
2126 Result = !::CheckPatternPredicate(Table, Index, SDISel);
2128 case SelectionDAGISel::OPC_CheckPredicate:
2129 Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
2131 case SelectionDAGISel::OPC_CheckOpcode:
2132 Result = !::CheckOpcode(Table, Index, N.getNode());
2134 case SelectionDAGISel::OPC_CheckType:
2135 Result = !::CheckType(Table, Index, N, SDISel.TLI);
2137 case SelectionDAGISel::OPC_CheckChild0Type:
2138 case SelectionDAGISel::OPC_CheckChild1Type:
2139 case SelectionDAGISel::OPC_CheckChild2Type:
2140 case SelectionDAGISel::OPC_CheckChild3Type:
2141 case SelectionDAGISel::OPC_CheckChild4Type:
2142 case SelectionDAGISel::OPC_CheckChild5Type:
2143 case SelectionDAGISel::OPC_CheckChild6Type:
2144 case SelectionDAGISel::OPC_CheckChild7Type:
2145 Result = !::CheckChildType(Table, Index, N, SDISel.TLI,
2146 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Type);
2148 case SelectionDAGISel::OPC_CheckCondCode:
2149 Result = !::CheckCondCode(Table, Index, N);
2151 case SelectionDAGISel::OPC_CheckValueType:
2152 Result = !::CheckValueType(Table, Index, N, SDISel.TLI);
2154 case SelectionDAGISel::OPC_CheckInteger:
2155 Result = !::CheckInteger(Table, Index, N);
2157 case SelectionDAGISel::OPC_CheckAndImm:
2158 Result = !::CheckAndImm(Table, Index, N, SDISel);
2160 case SelectionDAGISel::OPC_CheckOrImm:
2161 Result = !::CheckOrImm(Table, Index, N, SDISel);
2169 /// FailIndex - If this match fails, this is the index to continue with.
2172 /// NodeStack - The node stack when the scope was formed.
2173 SmallVector<SDValue, 4> NodeStack;
2175 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
2176 unsigned NumRecordedNodes;
2178 /// NumMatchedMemRefs - The number of matched memref entries.
2179 unsigned NumMatchedMemRefs;
2181 /// InputChain/InputGlue - The current chain/glue
2182 SDValue InputChain, InputGlue;
2184 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
2185 bool HasChainNodesMatched, HasGlueResultNodesMatched;
2190 SDNode *SelectionDAGISel::
2191 SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
2192 unsigned TableSize) {
2193 // FIXME: Should these even be selected? Handle these cases in the caller?
2194 switch (NodeToMatch->getOpcode()) {
2197 case ISD::EntryToken: // These nodes remain the same.
2198 case ISD::BasicBlock:
2200 case ISD::RegisterMask:
2201 //case ISD::VALUETYPE:
2202 //case ISD::CONDCODE:
2203 case ISD::HANDLENODE:
2204 case ISD::MDNODE_SDNODE:
2205 case ISD::TargetConstant:
2206 case ISD::TargetConstantFP:
2207 case ISD::TargetConstantPool:
2208 case ISD::TargetFrameIndex:
2209 case ISD::TargetExternalSymbol:
2210 case ISD::TargetBlockAddress:
2211 case ISD::TargetJumpTable:
2212 case ISD::TargetGlobalTLSAddress:
2213 case ISD::TargetGlobalAddress:
2214 case ISD::TokenFactor:
2215 case ISD::CopyFromReg:
2216 case ISD::CopyToReg:
2218 case ISD::LIFETIME_START:
2219 case ISD::LIFETIME_END:
2220 NodeToMatch->setNodeId(-1); // Mark selected.
2222 case ISD::AssertSext:
2223 case ISD::AssertZext:
2224 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0),
2225 NodeToMatch->getOperand(0));
2227 case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
2228 case ISD::UNDEF: return Select_UNDEF(NodeToMatch);
2231 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
2233 // Set up the node stack with NodeToMatch as the only node on the stack.
2234 SmallVector<SDValue, 8> NodeStack;
2235 SDValue N = SDValue(NodeToMatch, 0);
2236 NodeStack.push_back(N);
2238 // MatchScopes - Scopes used when matching, if a match failure happens, this
2239 // indicates where to continue checking.
2240 SmallVector<MatchScope, 8> MatchScopes;
2242 // RecordedNodes - This is the set of nodes that have been recorded by the
2243 // state machine. The second value is the parent of the node, or null if the
2244 // root is recorded.
2245 SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
2247 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
2249 SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
2251 // These are the current input chain and glue for use when generating nodes.
2252 // Various Emit operations change these. For example, emitting a copytoreg
2253 // uses and updates these.
2254 SDValue InputChain, InputGlue;
2256 // ChainNodesMatched - If a pattern matches nodes that have input/output
2257 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
2258 // which ones they are. The result is captured into this list so that we can
2259 // update the chain results when the pattern is complete.
2260 SmallVector<SDNode*, 3> ChainNodesMatched;
2261 SmallVector<SDNode*, 3> GlueResultNodesMatched;
2263 DEBUG(errs() << "ISEL: Starting pattern match on root node: ";
2264 NodeToMatch->dump(CurDAG);
2267 // Determine where to start the interpreter. Normally we start at opcode #0,
2268 // but if the state machine starts with an OPC_SwitchOpcode, then we
2269 // accelerate the first lookup (which is guaranteed to be hot) with the
2270 // OpcodeOffset table.
2271 unsigned MatcherIndex = 0;
2273 if (!OpcodeOffset.empty()) {
2274 // Already computed the OpcodeOffset table, just index into it.
2275 if (N.getOpcode() < OpcodeOffset.size())
2276 MatcherIndex = OpcodeOffset[N.getOpcode()];
2277 DEBUG(errs() << " Initial Opcode index to " << MatcherIndex << "\n");
2279 } else if (MatcherTable[0] == OPC_SwitchOpcode) {
2280 // Otherwise, the table isn't computed, but the state machine does start
2281 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
2282 // is the first time we're selecting an instruction.
2285 // Get the size of this case.
2286 unsigned CaseSize = MatcherTable[Idx++];
2288 CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
2289 if (CaseSize == 0) break;
2291 // Get the opcode, add the index to the table.
2292 uint16_t Opc = MatcherTable[Idx++];
2293 Opc |= (unsigned short)MatcherTable[Idx++] << 8;
2294 if (Opc >= OpcodeOffset.size())
2295 OpcodeOffset.resize((Opc+1)*2);
2296 OpcodeOffset[Opc] = Idx;
2300 // Okay, do the lookup for the first opcode.
2301 if (N.getOpcode() < OpcodeOffset.size())
2302 MatcherIndex = OpcodeOffset[N.getOpcode()];
2306 assert(MatcherIndex < TableSize && "Invalid index");
2308 unsigned CurrentOpcodeIndex = MatcherIndex;
2310 BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
2313 // Okay, the semantics of this operation are that we should push a scope
2314 // then evaluate the first child. However, pushing a scope only to have
2315 // the first check fail (which then pops it) is inefficient. If we can
2316 // determine immediately that the first check (or first several) will
2317 // immediately fail, don't even bother pushing a scope for them.
2321 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2322 if (NumToSkip & 128)
2323 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2324 // Found the end of the scope with no match.
2325 if (NumToSkip == 0) {
2330 FailIndex = MatcherIndex+NumToSkip;
2332 unsigned MatcherIndexOfPredicate = MatcherIndex;
2333 (void)MatcherIndexOfPredicate; // silence warning.
2335 // If we can't evaluate this predicate without pushing a scope (e.g. if
2336 // it is a 'MoveParent') or if the predicate succeeds on this node, we
2337 // push the scope and evaluate the full predicate chain.
2339 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
2340 Result, *this, RecordedNodes);
2344 DEBUG(errs() << " Skipped scope entry (due to false predicate) at "
2345 << "index " << MatcherIndexOfPredicate
2346 << ", continuing at " << FailIndex << "\n");
2347 ++NumDAGIselRetries;
2349 // Otherwise, we know that this case of the Scope is guaranteed to fail,
2350 // move to the next case.
2351 MatcherIndex = FailIndex;
2354 // If the whole scope failed to match, bail.
2355 if (FailIndex == 0) break;
2357 // Push a MatchScope which indicates where to go if the first child fails
2359 MatchScope NewEntry;
2360 NewEntry.FailIndex = FailIndex;
2361 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
2362 NewEntry.NumRecordedNodes = RecordedNodes.size();
2363 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
2364 NewEntry.InputChain = InputChain;
2365 NewEntry.InputGlue = InputGlue;
2366 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
2367 NewEntry.HasGlueResultNodesMatched = !GlueResultNodesMatched.empty();
2368 MatchScopes.push_back(NewEntry);
2371 case OPC_RecordNode: {
2372 // Remember this node, it may end up being an operand in the pattern.
2374 if (NodeStack.size() > 1)
2375 Parent = NodeStack[NodeStack.size()-2].getNode();
2376 RecordedNodes.push_back(std::make_pair(N, Parent));
2380 case OPC_RecordChild0: case OPC_RecordChild1:
2381 case OPC_RecordChild2: case OPC_RecordChild3:
2382 case OPC_RecordChild4: case OPC_RecordChild5:
2383 case OPC_RecordChild6: case OPC_RecordChild7: {
2384 unsigned ChildNo = Opcode-OPC_RecordChild0;
2385 if (ChildNo >= N.getNumOperands())
2386 break; // Match fails if out of range child #.
2388 RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
2392 case OPC_RecordMemRef:
2393 MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
2396 case OPC_CaptureGlueInput:
2397 // If the current node has an input glue, capture it in InputGlue.
2398 if (N->getNumOperands() != 0 &&
2399 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
2400 InputGlue = N->getOperand(N->getNumOperands()-1);
2403 case OPC_MoveChild: {
2404 unsigned ChildNo = MatcherTable[MatcherIndex++];
2405 if (ChildNo >= N.getNumOperands())
2406 break; // Match fails if out of range child #.
2407 N = N.getOperand(ChildNo);
2408 NodeStack.push_back(N);
2412 case OPC_MoveParent:
2413 // Pop the current node off the NodeStack.
2414 NodeStack.pop_back();
2415 assert(!NodeStack.empty() && "Node stack imbalance!");
2416 N = NodeStack.back();
2420 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
2422 case OPC_CheckPatternPredicate:
2423 if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
2425 case OPC_CheckPredicate:
2426 if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
2430 case OPC_CheckComplexPat: {
2431 unsigned CPNum = MatcherTable[MatcherIndex++];
2432 unsigned RecNo = MatcherTable[MatcherIndex++];
2433 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
2434 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
2435 RecordedNodes[RecNo].first, CPNum,
2440 case OPC_CheckOpcode:
2441 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
2445 if (!::CheckType(MatcherTable, MatcherIndex, N, TLI)) break;
2448 case OPC_SwitchOpcode: {
2449 unsigned CurNodeOpcode = N.getOpcode();
2450 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2453 // Get the size of this case.
2454 CaseSize = MatcherTable[MatcherIndex++];
2456 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2457 if (CaseSize == 0) break;
2459 uint16_t Opc = MatcherTable[MatcherIndex++];
2460 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2462 // If the opcode matches, then we will execute this case.
2463 if (CurNodeOpcode == Opc)
2466 // Otherwise, skip over this case.
2467 MatcherIndex += CaseSize;
2470 // If no cases matched, bail out.
2471 if (CaseSize == 0) break;
2473 // Otherwise, execute the case we found.
2474 DEBUG(errs() << " OpcodeSwitch from " << SwitchStart
2475 << " to " << MatcherIndex << "\n");
2479 case OPC_SwitchType: {
2480 MVT CurNodeVT = N.getValueType().getSimpleVT();
2481 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2484 // Get the size of this case.
2485 CaseSize = MatcherTable[MatcherIndex++];
2487 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2488 if (CaseSize == 0) break;
2490 MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2491 if (CaseVT == MVT::iPTR)
2492 CaseVT = TLI.getPointerTy();
2494 // If the VT matches, then we will execute this case.
2495 if (CurNodeVT == CaseVT)
2498 // Otherwise, skip over this case.
2499 MatcherIndex += CaseSize;
2502 // If no cases matched, bail out.
2503 if (CaseSize == 0) break;
2505 // Otherwise, execute the case we found.
2506 DEBUG(errs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString()
2507 << "] from " << SwitchStart << " to " << MatcherIndex<<'\n');
2510 case OPC_CheckChild0Type: case OPC_CheckChild1Type:
2511 case OPC_CheckChild2Type: case OPC_CheckChild3Type:
2512 case OPC_CheckChild4Type: case OPC_CheckChild5Type:
2513 case OPC_CheckChild6Type: case OPC_CheckChild7Type:
2514 if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
2515 Opcode-OPC_CheckChild0Type))
2518 case OPC_CheckCondCode:
2519 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
2521 case OPC_CheckValueType:
2522 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI)) break;
2524 case OPC_CheckInteger:
2525 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
2527 case OPC_CheckAndImm:
2528 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
2530 case OPC_CheckOrImm:
2531 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
2534 case OPC_CheckFoldableChainNode: {
2535 assert(NodeStack.size() != 1 && "No parent node");
2536 // Verify that all intermediate nodes between the root and this one have
2538 bool HasMultipleUses = false;
2539 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
2540 if (!NodeStack[i].hasOneUse()) {
2541 HasMultipleUses = true;
2544 if (HasMultipleUses) break;
2546 // Check to see that the target thinks this is profitable to fold and that
2547 // we can fold it without inducing cycles in the graph.
2548 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2550 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2551 NodeToMatch, OptLevel,
2552 true/*We validate our own chains*/))
2557 case OPC_EmitInteger: {
2558 MVT::SimpleValueType VT =
2559 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2560 int64_t Val = MatcherTable[MatcherIndex++];
2562 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2563 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2564 CurDAG->getTargetConstant(Val, VT), (SDNode*)0));
2567 case OPC_EmitRegister: {
2568 MVT::SimpleValueType VT =
2569 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2570 unsigned RegNo = MatcherTable[MatcherIndex++];
2571 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2572 CurDAG->getRegister(RegNo, VT), (SDNode*)0));
2575 case OPC_EmitRegister2: {
2576 // For targets w/ more than 256 register names, the register enum
2577 // values are stored in two bytes in the matcher table (just like
2579 MVT::SimpleValueType VT =
2580 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2581 unsigned RegNo = MatcherTable[MatcherIndex++];
2582 RegNo |= MatcherTable[MatcherIndex++] << 8;
2583 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2584 CurDAG->getRegister(RegNo, VT), (SDNode*)0));
2588 case OPC_EmitConvertToTarget: {
2589 // Convert from IMM/FPIMM to target version.
2590 unsigned RecNo = MatcherTable[MatcherIndex++];
2591 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2592 SDValue Imm = RecordedNodes[RecNo].first;
2594 if (Imm->getOpcode() == ISD::Constant) {
2595 int64_t Val = cast<ConstantSDNode>(Imm)->getZExtValue();
2596 Imm = CurDAG->getTargetConstant(Val, Imm.getValueType());
2597 } else if (Imm->getOpcode() == ISD::ConstantFP) {
2598 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
2599 Imm = CurDAG->getTargetConstantFP(*Val, Imm.getValueType());
2602 RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
2606 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
2607 case OPC_EmitMergeInputChains1_1: { // OPC_EmitMergeInputChains, 1, 1
2608 // These are space-optimized forms of OPC_EmitMergeInputChains.
2609 assert(InputChain.getNode() == 0 &&
2610 "EmitMergeInputChains should be the first chain producing node");
2611 assert(ChainNodesMatched.empty() &&
2612 "Should only have one EmitMergeInputChains per match");
2614 // Read all of the chained nodes.
2615 unsigned RecNo = Opcode == OPC_EmitMergeInputChains1_1;
2616 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2617 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
2619 // FIXME: What if other value results of the node have uses not matched
2621 if (ChainNodesMatched.back() != NodeToMatch &&
2622 !RecordedNodes[RecNo].first.hasOneUse()) {
2623 ChainNodesMatched.clear();
2627 // Merge the input chains if they are not intra-pattern references.
2628 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2630 if (InputChain.getNode() == 0)
2631 break; // Failed to merge.
2635 case OPC_EmitMergeInputChains: {
2636 assert(InputChain.getNode() == 0 &&
2637 "EmitMergeInputChains should be the first chain producing node");
2638 // This node gets a list of nodes we matched in the input that have
2639 // chains. We want to token factor all of the input chains to these nodes
2640 // together. However, if any of the input chains is actually one of the
2641 // nodes matched in this pattern, then we have an intra-match reference.
2642 // Ignore these because the newly token factored chain should not refer to
2644 unsigned NumChains = MatcherTable[MatcherIndex++];
2645 assert(NumChains != 0 && "Can't TF zero chains");
2647 assert(ChainNodesMatched.empty() &&
2648 "Should only have one EmitMergeInputChains per match");
2650 // Read all of the chained nodes.
2651 for (unsigned i = 0; i != NumChains; ++i) {
2652 unsigned RecNo = MatcherTable[MatcherIndex++];
2653 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2654 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
2656 // FIXME: What if other value results of the node have uses not matched
2658 if (ChainNodesMatched.back() != NodeToMatch &&
2659 !RecordedNodes[RecNo].first.hasOneUse()) {
2660 ChainNodesMatched.clear();
2665 // If the inner loop broke out, the match fails.
2666 if (ChainNodesMatched.empty())
2669 // Merge the input chains if they are not intra-pattern references.
2670 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
2672 if (InputChain.getNode() == 0)
2673 break; // Failed to merge.
2678 case OPC_EmitCopyToReg: {
2679 unsigned RecNo = MatcherTable[MatcherIndex++];
2680 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2681 unsigned DestPhysReg = MatcherTable[MatcherIndex++];
2683 if (InputChain.getNode() == 0)
2684 InputChain = CurDAG->getEntryNode();
2686 InputChain = CurDAG->getCopyToReg(InputChain, NodeToMatch->getDebugLoc(),
2687 DestPhysReg, RecordedNodes[RecNo].first,
2690 InputGlue = InputChain.getValue(1);
2694 case OPC_EmitNodeXForm: {
2695 unsigned XFormNo = MatcherTable[MatcherIndex++];
2696 unsigned RecNo = MatcherTable[MatcherIndex++];
2697 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2698 SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
2699 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, (SDNode*) 0));
2704 case OPC_MorphNodeTo: {
2705 uint16_t TargetOpc = MatcherTable[MatcherIndex++];
2706 TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2707 unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
2708 // Get the result VT list.
2709 unsigned NumVTs = MatcherTable[MatcherIndex++];
2710 SmallVector<EVT, 4> VTs;
2711 for (unsigned i = 0; i != NumVTs; ++i) {
2712 MVT::SimpleValueType VT =
2713 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2714 if (VT == MVT::iPTR) VT = TLI.getPointerTy().SimpleTy;
2718 if (EmitNodeInfo & OPFL_Chain)
2719 VTs.push_back(MVT::Other);
2720 if (EmitNodeInfo & OPFL_GlueOutput)
2721 VTs.push_back(MVT::Glue);
2723 // This is hot code, so optimize the two most common cases of 1 and 2
2726 if (VTs.size() == 1)
2727 VTList = CurDAG->getVTList(VTs[0]);
2728 else if (VTs.size() == 2)
2729 VTList = CurDAG->getVTList(VTs[0], VTs[1]);
2731 VTList = CurDAG->getVTList(VTs.data(), VTs.size());
2733 // Get the operand list.
2734 unsigned NumOps = MatcherTable[MatcherIndex++];
2735 SmallVector<SDValue, 8> Ops;
2736 for (unsigned i = 0; i != NumOps; ++i) {
2737 unsigned RecNo = MatcherTable[MatcherIndex++];
2739 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2741 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
2742 Ops.push_back(RecordedNodes[RecNo].first);
2745 // If there are variadic operands to add, handle them now.
2746 if (EmitNodeInfo & OPFL_VariadicInfo) {
2747 // Determine the start index to copy from.
2748 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
2749 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
2750 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
2751 "Invalid variadic node");
2752 // Copy all of the variadic operands, not including a potential glue
2754 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
2756 SDValue V = NodeToMatch->getOperand(i);
2757 if (V.getValueType() == MVT::Glue) break;
2762 // If this has chain/glue inputs, add them.
2763 if (EmitNodeInfo & OPFL_Chain)
2764 Ops.push_back(InputChain);
2765 if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != 0)
2766 Ops.push_back(InputGlue);
2770 if (Opcode != OPC_MorphNodeTo) {
2771 // If this is a normal EmitNode command, just create the new node and
2772 // add the results to the RecordedNodes list.
2773 Res = CurDAG->getMachineNode(TargetOpc, NodeToMatch->getDebugLoc(),
2774 VTList, Ops.data(), Ops.size());
2776 // Add all the non-glue/non-chain results to the RecordedNodes list.
2777 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
2778 if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
2779 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
2783 } else if (NodeToMatch->getOpcode() != ISD::DELETED_NODE) {
2784 Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops.data(), Ops.size(),
2787 // NodeToMatch was eliminated by CSE when the target changed the DAG.
2788 // We will visit the equivalent node later.
2789 DEBUG(dbgs() << "Node was eliminated by CSE\n");
2793 // If the node had chain/glue results, update our notion of the current
2795 if (EmitNodeInfo & OPFL_GlueOutput) {
2796 InputGlue = SDValue(Res, VTs.size()-1);
2797 if (EmitNodeInfo & OPFL_Chain)
2798 InputChain = SDValue(Res, VTs.size()-2);
2799 } else if (EmitNodeInfo & OPFL_Chain)
2800 InputChain = SDValue(Res, VTs.size()-1);
2802 // If the OPFL_MemRefs glue is set on this node, slap all of the
2803 // accumulated memrefs onto it.
2805 // FIXME: This is vastly incorrect for patterns with multiple outputs
2806 // instructions that access memory and for ComplexPatterns that match
2808 if (EmitNodeInfo & OPFL_MemRefs) {
2809 // Only attach load or store memory operands if the generated
2810 // instruction may load or store.
2811 const MCInstrDesc &MCID = TM.getInstrInfo()->get(TargetOpc);
2812 bool mayLoad = MCID.mayLoad();
2813 bool mayStore = MCID.mayStore();
2815 unsigned NumMemRefs = 0;
2816 for (SmallVector<MachineMemOperand*, 2>::const_iterator I =
2817 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
2818 if ((*I)->isLoad()) {
2821 } else if ((*I)->isStore()) {
2829 MachineSDNode::mmo_iterator MemRefs =
2830 MF->allocateMemRefsArray(NumMemRefs);
2832 MachineSDNode::mmo_iterator MemRefsPos = MemRefs;
2833 for (SmallVector<MachineMemOperand*, 2>::const_iterator I =
2834 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
2835 if ((*I)->isLoad()) {
2838 } else if ((*I)->isStore()) {
2846 cast<MachineSDNode>(Res)
2847 ->setMemRefs(MemRefs, MemRefs + NumMemRefs);
2851 << (Opcode == OPC_MorphNodeTo ? "Morphed" : "Created")
2852 << " node: "; Res->dump(CurDAG); errs() << "\n");
2854 // If this was a MorphNodeTo then we're completely done!
2855 if (Opcode == OPC_MorphNodeTo) {
2856 // Update chain and glue uses.
2857 UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
2858 InputGlue, GlueResultNodesMatched, true);
2865 case OPC_MarkGlueResults: {
2866 unsigned NumNodes = MatcherTable[MatcherIndex++];
2868 // Read and remember all the glue-result nodes.
2869 for (unsigned i = 0; i != NumNodes; ++i) {
2870 unsigned RecNo = MatcherTable[MatcherIndex++];
2872 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
2874 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2875 GlueResultNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
2880 case OPC_CompleteMatch: {
2881 // The match has been completed, and any new nodes (if any) have been
2882 // created. Patch up references to the matched dag to use the newly
2884 unsigned NumResults = MatcherTable[MatcherIndex++];
2886 for (unsigned i = 0; i != NumResults; ++i) {
2887 unsigned ResSlot = MatcherTable[MatcherIndex++];
2889 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
2891 assert(ResSlot < RecordedNodes.size() && "Invalid CheckSame");
2892 SDValue Res = RecordedNodes[ResSlot].first;
2894 assert(i < NodeToMatch->getNumValues() &&
2895 NodeToMatch->getValueType(i) != MVT::Other &&
2896 NodeToMatch->getValueType(i) != MVT::Glue &&
2897 "Invalid number of results to complete!");
2898 assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
2899 NodeToMatch->getValueType(i) == MVT::iPTR ||
2900 Res.getValueType() == MVT::iPTR ||
2901 NodeToMatch->getValueType(i).getSizeInBits() ==
2902 Res.getValueType().getSizeInBits()) &&
2903 "invalid replacement");
2904 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
2907 // If the root node defines glue, add it to the glue nodes to update list.
2908 if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) == MVT::Glue)
2909 GlueResultNodesMatched.push_back(NodeToMatch);
2911 // Update chain and glue uses.
2912 UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
2913 InputGlue, GlueResultNodesMatched, false);
2915 assert(NodeToMatch->use_empty() &&
2916 "Didn't replace all uses of the node?");
2918 // FIXME: We just return here, which interacts correctly with SelectRoot
2919 // above. We should fix this to not return an SDNode* anymore.
2924 // If the code reached this point, then the match failed. See if there is
2925 // another child to try in the current 'Scope', otherwise pop it until we
2926 // find a case to check.
2927 DEBUG(errs() << " Match failed at index " << CurrentOpcodeIndex << "\n");
2928 ++NumDAGIselRetries;
2930 if (MatchScopes.empty()) {
2931 CannotYetSelect(NodeToMatch);
2935 // Restore the interpreter state back to the point where the scope was
2937 MatchScope &LastScope = MatchScopes.back();
2938 RecordedNodes.resize(LastScope.NumRecordedNodes);
2940 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
2941 N = NodeStack.back();
2943 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
2944 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
2945 MatcherIndex = LastScope.FailIndex;
2947 DEBUG(errs() << " Continuing at " << MatcherIndex << "\n");
2949 InputChain = LastScope.InputChain;
2950 InputGlue = LastScope.InputGlue;
2951 if (!LastScope.HasChainNodesMatched)
2952 ChainNodesMatched.clear();
2953 if (!LastScope.HasGlueResultNodesMatched)
2954 GlueResultNodesMatched.clear();
2956 // Check to see what the offset is at the new MatcherIndex. If it is zero
2957 // we have reached the end of this scope, otherwise we have another child
2958 // in the current scope to try.
2959 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2960 if (NumToSkip & 128)
2961 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2963 // If we have another child in this scope to match, update FailIndex and
2965 if (NumToSkip != 0) {
2966 LastScope.FailIndex = MatcherIndex+NumToSkip;
2970 // End of this scope, pop it and try the next child in the containing
2972 MatchScopes.pop_back();
2979 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
2981 raw_string_ostream Msg(msg);
2982 Msg << "Cannot select: ";
2984 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
2985 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
2986 N->getOpcode() != ISD::INTRINSIC_VOID) {
2987 N->printrFull(Msg, CurDAG);
2988 Msg << "\nIn function: " << MF->getName();
2990 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
2992 cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
2993 if (iid < Intrinsic::num_intrinsics)
2994 Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid);
2995 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
2996 Msg << "target intrinsic %" << TII->getName(iid);
2998 Msg << "unknown intrinsic #" << iid;
3000 report_fatal_error(Msg.str());
3003 char SelectionDAGISel::ID = 0;