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 #include "llvm/CodeGen/GCStrategy.h"
15 #include "ScheduleDAGSDNodes.h"
16 #include "SelectionDAGBuilder.h"
17 #include "llvm/ADT/PostOrderIterator.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Analysis/BranchProbabilityInfo.h"
21 #include "llvm/Analysis/CFG.h"
22 #include "llvm/Analysis/EHPersonalities.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/CodeGen/Analysis.h"
25 #include "llvm/CodeGen/FastISel.h"
26 #include "llvm/CodeGen/FunctionLoweringInfo.h"
27 #include "llvm/CodeGen/GCMetadata.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineFunction.h"
30 #include "llvm/CodeGen/MachineInstrBuilder.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/ScheduleHazardRecognizer.h"
34 #include "llvm/CodeGen/SchedulerRegistry.h"
35 #include "llvm/CodeGen/SelectionDAG.h"
36 #include "llvm/CodeGen/SelectionDAGISel.h"
37 #include "llvm/CodeGen/WinEHFuncInfo.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DebugInfo.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/InlineAsm.h"
42 #include "llvm/IR/Instructions.h"
43 #include "llvm/IR/IntrinsicInst.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/IR/LLVMContext.h"
46 #include "llvm/IR/Module.h"
47 #include "llvm/MC/MCAsmInfo.h"
48 #include "llvm/Support/Compiler.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/ErrorHandling.h"
51 #include "llvm/Support/Timer.h"
52 #include "llvm/Support/raw_ostream.h"
53 #include "llvm/Target/TargetInstrInfo.h"
54 #include "llvm/Target/TargetIntrinsicInfo.h"
55 #include "llvm/Target/TargetLowering.h"
56 #include "llvm/Target/TargetMachine.h"
57 #include "llvm/Target/TargetOptions.h"
58 #include "llvm/Target/TargetRegisterInfo.h"
59 #include "llvm/Target/TargetSubtargetInfo.h"
60 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
64 #define DEBUG_TYPE "isel"
66 STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
67 STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
68 STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
69 STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
70 STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
71 STATISTIC(NumEntryBlocks, "Number of entry blocks encountered");
72 STATISTIC(NumFastIselFailLowerArguments,
73 "Number of entry blocks where fast isel failed to lower arguments");
77 EnableFastISelVerbose2("fast-isel-verbose2", cl::Hidden,
78 cl::desc("Enable extra verbose messages in the \"fast\" "
79 "instruction selector"));
82 STATISTIC(NumFastIselFailRet,"Fast isel fails on Ret");
83 STATISTIC(NumFastIselFailBr,"Fast isel fails on Br");
84 STATISTIC(NumFastIselFailSwitch,"Fast isel fails on Switch");
85 STATISTIC(NumFastIselFailIndirectBr,"Fast isel fails on IndirectBr");
86 STATISTIC(NumFastIselFailInvoke,"Fast isel fails on Invoke");
87 STATISTIC(NumFastIselFailResume,"Fast isel fails on Resume");
88 STATISTIC(NumFastIselFailUnreachable,"Fast isel fails on Unreachable");
90 // Standard binary operators...
91 STATISTIC(NumFastIselFailAdd,"Fast isel fails on Add");
92 STATISTIC(NumFastIselFailFAdd,"Fast isel fails on FAdd");
93 STATISTIC(NumFastIselFailSub,"Fast isel fails on Sub");
94 STATISTIC(NumFastIselFailFSub,"Fast isel fails on FSub");
95 STATISTIC(NumFastIselFailMul,"Fast isel fails on Mul");
96 STATISTIC(NumFastIselFailFMul,"Fast isel fails on FMul");
97 STATISTIC(NumFastIselFailUDiv,"Fast isel fails on UDiv");
98 STATISTIC(NumFastIselFailSDiv,"Fast isel fails on SDiv");
99 STATISTIC(NumFastIselFailFDiv,"Fast isel fails on FDiv");
100 STATISTIC(NumFastIselFailURem,"Fast isel fails on URem");
101 STATISTIC(NumFastIselFailSRem,"Fast isel fails on SRem");
102 STATISTIC(NumFastIselFailFRem,"Fast isel fails on FRem");
104 // Logical operators...
105 STATISTIC(NumFastIselFailAnd,"Fast isel fails on And");
106 STATISTIC(NumFastIselFailOr,"Fast isel fails on Or");
107 STATISTIC(NumFastIselFailXor,"Fast isel fails on Xor");
109 // Memory instructions...
110 STATISTIC(NumFastIselFailAlloca,"Fast isel fails on Alloca");
111 STATISTIC(NumFastIselFailLoad,"Fast isel fails on Load");
112 STATISTIC(NumFastIselFailStore,"Fast isel fails on Store");
113 STATISTIC(NumFastIselFailAtomicCmpXchg,"Fast isel fails on AtomicCmpXchg");
114 STATISTIC(NumFastIselFailAtomicRMW,"Fast isel fails on AtomicRWM");
115 STATISTIC(NumFastIselFailFence,"Fast isel fails on Frence");
116 STATISTIC(NumFastIselFailGetElementPtr,"Fast isel fails on GetElementPtr");
118 // Convert instructions...
119 STATISTIC(NumFastIselFailTrunc,"Fast isel fails on Trunc");
120 STATISTIC(NumFastIselFailZExt,"Fast isel fails on ZExt");
121 STATISTIC(NumFastIselFailSExt,"Fast isel fails on SExt");
122 STATISTIC(NumFastIselFailFPTrunc,"Fast isel fails on FPTrunc");
123 STATISTIC(NumFastIselFailFPExt,"Fast isel fails on FPExt");
124 STATISTIC(NumFastIselFailFPToUI,"Fast isel fails on FPToUI");
125 STATISTIC(NumFastIselFailFPToSI,"Fast isel fails on FPToSI");
126 STATISTIC(NumFastIselFailUIToFP,"Fast isel fails on UIToFP");
127 STATISTIC(NumFastIselFailSIToFP,"Fast isel fails on SIToFP");
128 STATISTIC(NumFastIselFailIntToPtr,"Fast isel fails on IntToPtr");
129 STATISTIC(NumFastIselFailPtrToInt,"Fast isel fails on PtrToInt");
130 STATISTIC(NumFastIselFailBitCast,"Fast isel fails on BitCast");
132 // Other instructions...
133 STATISTIC(NumFastIselFailICmp,"Fast isel fails on ICmp");
134 STATISTIC(NumFastIselFailFCmp,"Fast isel fails on FCmp");
135 STATISTIC(NumFastIselFailPHI,"Fast isel fails on PHI");
136 STATISTIC(NumFastIselFailSelect,"Fast isel fails on Select");
137 STATISTIC(NumFastIselFailCall,"Fast isel fails on Call");
138 STATISTIC(NumFastIselFailShl,"Fast isel fails on Shl");
139 STATISTIC(NumFastIselFailLShr,"Fast isel fails on LShr");
140 STATISTIC(NumFastIselFailAShr,"Fast isel fails on AShr");
141 STATISTIC(NumFastIselFailVAArg,"Fast isel fails on VAArg");
142 STATISTIC(NumFastIselFailExtractElement,"Fast isel fails on ExtractElement");
143 STATISTIC(NumFastIselFailInsertElement,"Fast isel fails on InsertElement");
144 STATISTIC(NumFastIselFailShuffleVector,"Fast isel fails on ShuffleVector");
145 STATISTIC(NumFastIselFailExtractValue,"Fast isel fails on ExtractValue");
146 STATISTIC(NumFastIselFailInsertValue,"Fast isel fails on InsertValue");
147 STATISTIC(NumFastIselFailLandingPad,"Fast isel fails on LandingPad");
149 // Intrinsic instructions...
150 STATISTIC(NumFastIselFailIntrinsicCall, "Fast isel fails on Intrinsic call");
151 STATISTIC(NumFastIselFailSAddWithOverflow,
152 "Fast isel fails on sadd.with.overflow");
153 STATISTIC(NumFastIselFailUAddWithOverflow,
154 "Fast isel fails on uadd.with.overflow");
155 STATISTIC(NumFastIselFailSSubWithOverflow,
156 "Fast isel fails on ssub.with.overflow");
157 STATISTIC(NumFastIselFailUSubWithOverflow,
158 "Fast isel fails on usub.with.overflow");
159 STATISTIC(NumFastIselFailSMulWithOverflow,
160 "Fast isel fails on smul.with.overflow");
161 STATISTIC(NumFastIselFailUMulWithOverflow,
162 "Fast isel fails on umul.with.overflow");
163 STATISTIC(NumFastIselFailFrameaddress, "Fast isel fails on Frameaddress");
164 STATISTIC(NumFastIselFailSqrt, "Fast isel fails on sqrt call");
165 STATISTIC(NumFastIselFailStackMap, "Fast isel fails on StackMap call");
166 STATISTIC(NumFastIselFailPatchPoint, "Fast isel fails on PatchPoint call");
170 EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
171 cl::desc("Enable verbose messages in the \"fast\" "
172 "instruction selector"));
173 static cl::opt<int> EnableFastISelAbort(
174 "fast-isel-abort", cl::Hidden,
175 cl::desc("Enable abort calls when \"fast\" instruction selection "
176 "fails to lower an instruction: 0 disable the abort, 1 will "
177 "abort but for args, calls and terminators, 2 will also "
178 "abort for argument lowering, and 3 will never fallback "
179 "to SelectionDAG."));
183 cl::desc("use Machine Branch Probability Info"),
184 cl::init(true), cl::Hidden);
187 static cl::opt<std::string>
188 FilterDAGBasicBlockName("filter-view-dags", cl::Hidden,
189 cl::desc("Only display the basic block whose name "
190 "matches this for all view-*-dags options"));
192 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
193 cl::desc("Pop up a window to show dags before the first "
194 "dag combine pass"));
196 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
197 cl::desc("Pop up a window to show dags before legalize types"));
199 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
200 cl::desc("Pop up a window to show dags before legalize"));
202 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
203 cl::desc("Pop up a window to show dags before the second "
204 "dag combine pass"));
206 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
207 cl::desc("Pop up a window to show dags before the post legalize types"
208 " dag combine pass"));
210 ViewISelDAGs("view-isel-dags", cl::Hidden,
211 cl::desc("Pop up a window to show isel dags as they are selected"));
213 ViewSchedDAGs("view-sched-dags", cl::Hidden,
214 cl::desc("Pop up a window to show sched dags as they are processed"));
216 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
217 cl::desc("Pop up a window to show SUnit dags after they are processed"));
219 static const bool ViewDAGCombine1 = false,
220 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
221 ViewDAGCombine2 = false,
222 ViewDAGCombineLT = false,
223 ViewISelDAGs = false, ViewSchedDAGs = false,
224 ViewSUnitDAGs = false;
227 //===---------------------------------------------------------------------===//
229 /// RegisterScheduler class - Track the registration of instruction schedulers.
231 //===---------------------------------------------------------------------===//
232 MachinePassRegistry RegisterScheduler::Registry;
234 //===---------------------------------------------------------------------===//
236 /// ISHeuristic command line option for instruction schedulers.
238 //===---------------------------------------------------------------------===//
239 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
240 RegisterPassParser<RegisterScheduler> >
241 ISHeuristic("pre-RA-sched",
242 cl::init(&createDefaultScheduler), cl::Hidden,
243 cl::desc("Instruction schedulers available (before register"
246 static RegisterScheduler
247 defaultListDAGScheduler("default", "Best scheduler for the target",
248 createDefaultScheduler);
251 //===--------------------------------------------------------------------===//
252 /// \brief This class is used by SelectionDAGISel to temporarily override
253 /// the optimization level on a per-function basis.
254 class OptLevelChanger {
255 SelectionDAGISel &IS;
256 CodeGenOpt::Level SavedOptLevel;
260 OptLevelChanger(SelectionDAGISel &ISel,
261 CodeGenOpt::Level NewOptLevel) : IS(ISel) {
262 SavedOptLevel = IS.OptLevel;
263 if (NewOptLevel == SavedOptLevel)
265 IS.OptLevel = NewOptLevel;
266 IS.TM.setOptLevel(NewOptLevel);
267 DEBUG(dbgs() << "\nChanging optimization level for Function "
268 << IS.MF->getFunction()->getName() << "\n");
269 DEBUG(dbgs() << "\tBefore: -O" << SavedOptLevel
270 << " ; After: -O" << NewOptLevel << "\n");
271 SavedFastISel = IS.TM.Options.EnableFastISel;
272 if (NewOptLevel == CodeGenOpt::None) {
273 IS.TM.setFastISel(IS.TM.getO0WantsFastISel());
274 DEBUG(dbgs() << "\tFastISel is "
275 << (IS.TM.Options.EnableFastISel ? "enabled" : "disabled")
281 if (IS.OptLevel == SavedOptLevel)
283 DEBUG(dbgs() << "\nRestoring optimization level for Function "
284 << IS.MF->getFunction()->getName() << "\n");
285 DEBUG(dbgs() << "\tBefore: -O" << IS.OptLevel
286 << " ; After: -O" << SavedOptLevel << "\n");
287 IS.OptLevel = SavedOptLevel;
288 IS.TM.setOptLevel(SavedOptLevel);
289 IS.TM.setFastISel(SavedFastISel);
293 //===--------------------------------------------------------------------===//
294 /// createDefaultScheduler - This creates an instruction scheduler appropriate
296 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
297 CodeGenOpt::Level OptLevel) {
298 const TargetLowering *TLI = IS->TLI;
299 const TargetSubtargetInfo &ST = IS->MF->getSubtarget();
301 // Try first to see if the Target has its own way of selecting a scheduler
302 if (auto *SchedulerCtor = ST.getDAGScheduler(OptLevel)) {
303 return SchedulerCtor(IS, OptLevel);
306 if (OptLevel == CodeGenOpt::None ||
307 (ST.enableMachineScheduler() && ST.enableMachineSchedDefaultSched()) ||
308 TLI->getSchedulingPreference() == Sched::Source)
309 return createSourceListDAGScheduler(IS, OptLevel);
310 if (TLI->getSchedulingPreference() == Sched::RegPressure)
311 return createBURRListDAGScheduler(IS, OptLevel);
312 if (TLI->getSchedulingPreference() == Sched::Hybrid)
313 return createHybridListDAGScheduler(IS, OptLevel);
314 if (TLI->getSchedulingPreference() == Sched::VLIW)
315 return createVLIWDAGScheduler(IS, OptLevel);
316 assert(TLI->getSchedulingPreference() == Sched::ILP &&
317 "Unknown sched type!");
318 return createILPListDAGScheduler(IS, OptLevel);
322 // EmitInstrWithCustomInserter - This method should be implemented by targets
323 // that mark instructions with the 'usesCustomInserter' flag. These
324 // instructions are special in various ways, which require special support to
325 // insert. The specified MachineInstr is created but not inserted into any
326 // basic blocks, and this method is called to expand it into a sequence of
327 // instructions, potentially also creating new basic blocks and control flow.
328 // When new basic blocks are inserted and the edges from MBB to its successors
329 // are modified, the method should insert pairs of <OldSucc, NewSucc> into the
332 TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
333 MachineBasicBlock *MBB) const {
335 dbgs() << "If a target marks an instruction with "
336 "'usesCustomInserter', it must implement "
337 "TargetLowering::EmitInstrWithCustomInserter!";
339 llvm_unreachable(nullptr);
342 void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr *MI,
343 SDNode *Node) const {
344 assert(!MI->hasPostISelHook() &&
345 "If a target marks an instruction with 'hasPostISelHook', "
346 "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
349 //===----------------------------------------------------------------------===//
350 // SelectionDAGISel code
351 //===----------------------------------------------------------------------===//
353 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm,
354 CodeGenOpt::Level OL) :
355 MachineFunctionPass(ID), TM(tm),
356 FuncInfo(new FunctionLoweringInfo()),
357 CurDAG(new SelectionDAG(tm, OL)),
358 SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)),
362 initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
363 initializeBranchProbabilityInfoWrapperPassPass(
364 *PassRegistry::getPassRegistry());
365 initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
366 initializeTargetLibraryInfoWrapperPassPass(
367 *PassRegistry::getPassRegistry());
370 SelectionDAGISel::~SelectionDAGISel() {
376 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
377 AU.addRequired<AAResultsWrapperPass>();
378 AU.addRequired<GCModuleInfo>();
379 AU.addPreserved<GCModuleInfo>();
380 AU.addRequired<TargetLibraryInfoWrapperPass>();
381 if (UseMBPI && OptLevel != CodeGenOpt::None)
382 AU.addRequired<BranchProbabilityInfoWrapperPass>();
383 MachineFunctionPass::getAnalysisUsage(AU);
386 /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that
387 /// may trap on it. In this case we have to split the edge so that the path
388 /// through the predecessor block that doesn't go to the phi block doesn't
389 /// execute the possibly trapping instruction.
391 /// This is required for correctness, so it must be done at -O0.
393 static void SplitCriticalSideEffectEdges(Function &Fn) {
394 // Loop for blocks with phi nodes.
395 for (BasicBlock &BB : Fn) {
396 PHINode *PN = dyn_cast<PHINode>(BB.begin());
400 // For each block with a PHI node, check to see if any of the input values
401 // are potentially trapping constant expressions. Constant expressions are
402 // the only potentially trapping value that can occur as the argument to a
404 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I)); ++I)
405 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
406 ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i));
407 if (!CE || !CE->canTrap()) continue;
409 // The only case we have to worry about is when the edge is critical.
410 // Since this block has a PHI Node, we assume it has multiple input
411 // edges: check to see if the pred has multiple successors.
412 BasicBlock *Pred = PN->getIncomingBlock(i);
413 if (Pred->getTerminator()->getNumSuccessors() == 1)
416 // Okay, we have to split this edge.
418 Pred->getTerminator(), GetSuccessorNumber(Pred, &BB),
419 CriticalEdgeSplittingOptions().setMergeIdenticalEdges());
425 bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
426 // Do some sanity-checking on the command-line options.
427 assert((!EnableFastISelVerbose || TM.Options.EnableFastISel) &&
428 "-fast-isel-verbose requires -fast-isel");
429 assert((!EnableFastISelAbort || TM.Options.EnableFastISel) &&
430 "-fast-isel-abort > 0 requires -fast-isel");
432 const Function &Fn = *mf.getFunction();
435 // Reset the target options before resetting the optimization
437 // FIXME: This is a horrible hack and should be processed via
438 // codegen looking at the optimization level explicitly when
439 // it wants to look at it.
440 TM.resetTargetOptions(Fn);
441 // Reset OptLevel to None for optnone functions.
442 CodeGenOpt::Level NewOptLevel = OptLevel;
443 if (Fn.hasFnAttribute(Attribute::OptimizeNone))
444 NewOptLevel = CodeGenOpt::None;
445 OptLevelChanger OLC(*this, NewOptLevel);
447 TII = MF->getSubtarget().getInstrInfo();
448 TLI = MF->getSubtarget().getTargetLowering();
449 RegInfo = &MF->getRegInfo();
450 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
451 LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
452 GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : nullptr;
454 DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
456 SplitCriticalSideEffectEdges(const_cast<Function &>(Fn));
459 FuncInfo->set(Fn, *MF, CurDAG);
461 if (UseMBPI && OptLevel != CodeGenOpt::None)
462 FuncInfo->BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
464 FuncInfo->BPI = nullptr;
466 SDB->init(GFI, *AA, LibInfo);
468 MF->setHasInlineAsm(false);
470 SelectAllBasicBlocks(Fn);
472 // If the first basic block in the function has live ins that need to be
473 // copied into vregs, emit the copies into the top of the block before
474 // emitting the code for the block.
475 MachineBasicBlock *EntryMBB = &MF->front();
476 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
477 RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
479 DenseMap<unsigned, unsigned> LiveInMap;
480 if (!FuncInfo->ArgDbgValues.empty())
481 for (MachineRegisterInfo::livein_iterator LI = RegInfo->livein_begin(),
482 E = RegInfo->livein_end(); LI != E; ++LI)
484 LiveInMap.insert(std::make_pair(LI->first, LI->second));
486 // Insert DBG_VALUE instructions for function arguments to the entry block.
487 for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
488 MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1];
489 bool hasFI = MI->getOperand(0).isFI();
491 hasFI ? TRI.getFrameRegister(*MF) : MI->getOperand(0).getReg();
492 if (TargetRegisterInfo::isPhysicalRegister(Reg))
493 EntryMBB->insert(EntryMBB->begin(), MI);
495 MachineInstr *Def = RegInfo->getVRegDef(Reg);
497 MachineBasicBlock::iterator InsertPos = Def;
498 // FIXME: VR def may not be in entry block.
499 Def->getParent()->insert(std::next(InsertPos), MI);
501 DEBUG(dbgs() << "Dropping debug info for dead vreg"
502 << TargetRegisterInfo::virtReg2Index(Reg) << "\n");
505 // If Reg is live-in then update debug info to track its copy in a vreg.
506 DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
507 if (LDI != LiveInMap.end()) {
508 assert(!hasFI && "There's no handling of frame pointer updating here yet "
510 MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
511 MachineBasicBlock::iterator InsertPos = Def;
512 const MDNode *Variable = MI->getDebugVariable();
513 const MDNode *Expr = MI->getDebugExpression();
514 DebugLoc DL = MI->getDebugLoc();
515 bool IsIndirect = MI->isIndirectDebugValue();
516 unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
517 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
518 "Expected inlined-at fields to agree");
519 // Def is never a terminator here, so it is ok to increment InsertPos.
520 BuildMI(*EntryMBB, ++InsertPos, DL, TII->get(TargetOpcode::DBG_VALUE),
521 IsIndirect, LDI->second, Offset, Variable, Expr);
523 // If this vreg is directly copied into an exported register then
524 // that COPY instructions also need DBG_VALUE, if it is the only
525 // user of LDI->second.
526 MachineInstr *CopyUseMI = nullptr;
527 for (MachineRegisterInfo::use_instr_iterator
528 UI = RegInfo->use_instr_begin(LDI->second),
529 E = RegInfo->use_instr_end(); UI != E; ) {
530 MachineInstr *UseMI = &*(UI++);
531 if (UseMI->isDebugValue()) continue;
532 if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
533 CopyUseMI = UseMI; continue;
535 // Otherwise this is another use or second copy use.
536 CopyUseMI = nullptr; break;
539 // Use MI's debug location, which describes where Variable was
540 // declared, rather than whatever is attached to CopyUseMI.
541 MachineInstr *NewMI =
542 BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
543 CopyUseMI->getOperand(0).getReg(), Offset, Variable, Expr);
544 MachineBasicBlock::iterator Pos = CopyUseMI;
545 EntryMBB->insertAfter(Pos, NewMI);
550 // Determine if there are any calls in this machine function.
551 MachineFrameInfo *MFI = MF->getFrameInfo();
552 for (const auto &MBB : *MF) {
553 if (MFI->hasCalls() && MF->hasInlineAsm())
556 for (const auto &MI : MBB) {
557 const MCInstrDesc &MCID = TII->get(MI.getOpcode());
558 if ((MCID.isCall() && !MCID.isReturn()) ||
559 MI.isStackAligningInlineAsm()) {
560 MFI->setHasCalls(true);
562 if (MI.isInlineAsm()) {
563 MF->setHasInlineAsm(true);
568 // Determine if there is a call to setjmp in the machine function.
569 MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice());
571 // Replace forward-declared registers with the registers containing
572 // the desired value.
573 MachineRegisterInfo &MRI = MF->getRegInfo();
574 for (DenseMap<unsigned, unsigned>::iterator
575 I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end();
577 unsigned From = I->first;
578 unsigned To = I->second;
579 // If To is also scheduled to be replaced, find what its ultimate
582 DenseMap<unsigned, unsigned>::iterator J = FuncInfo->RegFixups.find(To);
586 // Make sure the new register has a sufficiently constrained register class.
587 if (TargetRegisterInfo::isVirtualRegister(From) &&
588 TargetRegisterInfo::isVirtualRegister(To))
589 MRI.constrainRegClass(To, MRI.getRegClass(From));
593 // Replacing one register with another won't touch the kill flags.
594 // We need to conservatively clear the kill flags as a kill on the old
595 // register might dominate existing uses of the new register.
596 if (!MRI.use_empty(To))
597 MRI.clearKillFlags(From);
598 MRI.replaceRegWith(From, To);
601 // Freeze the set of reserved registers now that MachineFrameInfo has been
602 // set up. All the information required by getReservedRegs() should be
604 MRI.freezeReservedRegs(*MF);
606 // Release function-specific state. SDB and CurDAG are already cleared
610 DEBUG(dbgs() << "*** MachineFunction at end of ISel ***\n");
611 DEBUG(MF->print(dbgs()));
616 void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
617 BasicBlock::const_iterator End,
619 // Lower the instructions. If a call is emitted as a tail call, cease emitting
620 // nodes for this block.
621 for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I)
624 // Make sure the root of the DAG is up-to-date.
625 CurDAG->setRoot(SDB->getControlRoot());
626 HadTailCall = SDB->HasTailCall;
629 // Final step, emit the lowered DAG as machine code.
633 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
634 SmallPtrSet<SDNode*, 128> VisitedNodes;
635 SmallVector<SDNode*, 128> Worklist;
637 Worklist.push_back(CurDAG->getRoot().getNode());
643 SDNode *N = Worklist.pop_back_val();
645 // If we've already seen this node, ignore it.
646 if (!VisitedNodes.insert(N).second)
649 // Otherwise, add all chain operands to the worklist.
650 for (const SDValue &Op : N->op_values())
651 if (Op.getValueType() == MVT::Other)
652 Worklist.push_back(Op.getNode());
654 // If this is a CopyToReg with a vreg dest, process it.
655 if (N->getOpcode() != ISD::CopyToReg)
658 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
659 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
662 // Ignore non-scalar or non-integer values.
663 SDValue Src = N->getOperand(2);
664 EVT SrcVT = Src.getValueType();
665 if (!SrcVT.isInteger() || SrcVT.isVector())
668 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
669 CurDAG->computeKnownBits(Src, KnownZero, KnownOne);
670 FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, KnownZero, KnownOne);
671 } while (!Worklist.empty());
674 void SelectionDAGISel::CodeGenAndEmitDAG() {
675 std::string GroupName;
676 if (TimePassesIsEnabled)
677 GroupName = "Instruction Selection and Scheduling";
678 std::string BlockName;
679 int BlockNumber = -1;
681 bool MatchFilterBB = false; (void)MatchFilterBB;
683 MatchFilterBB = (FilterDAGBasicBlockName.empty() ||
684 FilterDAGBasicBlockName ==
685 FuncInfo->MBB->getBasicBlock()->getName().str());
688 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
689 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
693 BlockNumber = FuncInfo->MBB->getNumber();
695 (MF->getName() + ":" + FuncInfo->MBB->getBasicBlock()->getName()).str();
697 DEBUG(dbgs() << "Initial selection DAG: BB#" << BlockNumber
698 << " '" << BlockName << "'\n"; CurDAG->dump());
700 if (ViewDAGCombine1 && MatchFilterBB)
701 CurDAG->viewGraph("dag-combine1 input for " + BlockName);
703 // Run the DAG combiner in pre-legalize mode.
705 NamedRegionTimer T("DAG Combining 1", GroupName, TimePassesIsEnabled);
706 CurDAG->Combine(BeforeLegalizeTypes, *AA, OptLevel);
709 DEBUG(dbgs() << "Optimized lowered selection DAG: BB#" << BlockNumber
710 << " '" << BlockName << "'\n"; CurDAG->dump());
712 // Second step, hack on the DAG until it only uses operations and types that
713 // the target supports.
714 if (ViewLegalizeTypesDAGs && MatchFilterBB)
715 CurDAG->viewGraph("legalize-types input for " + BlockName);
719 NamedRegionTimer T("Type Legalization", GroupName, TimePassesIsEnabled);
720 Changed = CurDAG->LegalizeTypes();
723 DEBUG(dbgs() << "Type-legalized selection DAG: BB#" << BlockNumber
724 << " '" << BlockName << "'\n"; CurDAG->dump());
726 CurDAG->NewNodesMustHaveLegalTypes = true;
729 if (ViewDAGCombineLT && MatchFilterBB)
730 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
732 // Run the DAG combiner in post-type-legalize mode.
734 NamedRegionTimer T("DAG Combining after legalize types", GroupName,
735 TimePassesIsEnabled);
736 CurDAG->Combine(AfterLegalizeTypes, *AA, OptLevel);
739 DEBUG(dbgs() << "Optimized type-legalized selection DAG: BB#" << BlockNumber
740 << " '" << BlockName << "'\n"; CurDAG->dump());
745 NamedRegionTimer T("Vector Legalization", GroupName, TimePassesIsEnabled);
746 Changed = CurDAG->LegalizeVectors();
751 NamedRegionTimer T("Type Legalization 2", GroupName, TimePassesIsEnabled);
752 CurDAG->LegalizeTypes();
755 if (ViewDAGCombineLT && MatchFilterBB)
756 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
758 // Run the DAG combiner in post-type-legalize mode.
760 NamedRegionTimer T("DAG Combining after legalize vectors", GroupName,
761 TimePassesIsEnabled);
762 CurDAG->Combine(AfterLegalizeVectorOps, *AA, OptLevel);
765 DEBUG(dbgs() << "Optimized vector-legalized selection DAG: BB#"
766 << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump());
769 if (ViewLegalizeDAGs && MatchFilterBB)
770 CurDAG->viewGraph("legalize input for " + BlockName);
773 NamedRegionTimer T("DAG Legalization", GroupName, TimePassesIsEnabled);
777 DEBUG(dbgs() << "Legalized selection DAG: BB#" << BlockNumber
778 << " '" << BlockName << "'\n"; CurDAG->dump());
780 if (ViewDAGCombine2 && MatchFilterBB)
781 CurDAG->viewGraph("dag-combine2 input for " + BlockName);
783 // Run the DAG combiner in post-legalize mode.
785 NamedRegionTimer T("DAG Combining 2", GroupName, TimePassesIsEnabled);
786 CurDAG->Combine(AfterLegalizeDAG, *AA, OptLevel);
789 DEBUG(dbgs() << "Optimized legalized selection DAG: BB#" << BlockNumber
790 << " '" << BlockName << "'\n"; CurDAG->dump());
792 if (OptLevel != CodeGenOpt::None)
793 ComputeLiveOutVRegInfo();
795 if (ViewISelDAGs && MatchFilterBB)
796 CurDAG->viewGraph("isel input for " + BlockName);
798 // Third, instruction select all of the operations to machine code, adding the
799 // code to the MachineBasicBlock.
801 NamedRegionTimer T("Instruction Selection", GroupName, TimePassesIsEnabled);
802 DoInstructionSelection();
805 DEBUG(dbgs() << "Selected selection DAG: BB#" << BlockNumber
806 << " '" << BlockName << "'\n"; CurDAG->dump());
808 if (ViewSchedDAGs && MatchFilterBB)
809 CurDAG->viewGraph("scheduler input for " + BlockName);
811 // Schedule machine code.
812 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
814 NamedRegionTimer T("Instruction Scheduling", GroupName,
815 TimePassesIsEnabled);
816 Scheduler->Run(CurDAG, FuncInfo->MBB);
819 if (ViewSUnitDAGs && MatchFilterBB) Scheduler->viewGraph();
821 // Emit machine code to BB. This can change 'BB' to the last block being
823 MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
825 NamedRegionTimer T("Instruction Creation", GroupName, TimePassesIsEnabled);
827 // FuncInfo->InsertPt is passed by reference and set to the end of the
828 // scheduled instructions.
829 LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
832 // If the block was split, make sure we update any references that are used to
833 // update PHI nodes later on.
834 if (FirstMBB != LastMBB)
835 SDB->UpdateSplitBlock(FirstMBB, LastMBB);
837 // Free the scheduler state.
839 NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName,
840 TimePassesIsEnabled);
844 // Free the SelectionDAG state, now that we're finished with it.
849 /// ISelUpdater - helper class to handle updates of the instruction selection
851 class ISelUpdater : public SelectionDAG::DAGUpdateListener {
852 SelectionDAG::allnodes_iterator &ISelPosition;
854 ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
855 : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
857 /// NodeDeleted - Handle nodes deleted from the graph. If the node being
858 /// deleted is the current ISelPosition node, update ISelPosition.
860 void NodeDeleted(SDNode *N, SDNode *E) override {
861 if (ISelPosition == SelectionDAG::allnodes_iterator(N))
865 } // end anonymous namespace
867 void SelectionDAGISel::DoInstructionSelection() {
868 DEBUG(dbgs() << "===== Instruction selection begins: BB#"
869 << FuncInfo->MBB->getNumber()
870 << " '" << FuncInfo->MBB->getName() << "'\n");
874 // Select target instructions for the DAG.
876 // Number all nodes with a topological order and set DAGSize.
877 DAGSize = CurDAG->AssignTopologicalOrder();
879 // Create a dummy node (which is not added to allnodes), that adds
880 // a reference to the root node, preventing it from being deleted,
881 // and tracking any changes of the root.
882 HandleSDNode Dummy(CurDAG->getRoot());
883 SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode());
886 // Make sure that ISelPosition gets properly updated when nodes are deleted
887 // in calls made from this function.
888 ISelUpdater ISU(*CurDAG, ISelPosition);
890 // The AllNodes list is now topological-sorted. Visit the
891 // nodes by starting at the end of the list (the root of the
892 // graph) and preceding back toward the beginning (the entry
894 while (ISelPosition != CurDAG->allnodes_begin()) {
895 SDNode *Node = &*--ISelPosition;
896 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
897 // but there are currently some corner cases that it misses. Also, this
898 // makes it theoretically possible to disable the DAGCombiner.
899 if (Node->use_empty())
902 SDNode *ResNode = Select(Node);
904 // FIXME: This is pretty gross. 'Select' should be changed to not return
905 // anything at all and this code should be nuked with a tactical strike.
907 // If node should not be replaced, continue with the next one.
908 if (ResNode == Node || Node->getOpcode() == ISD::DELETED_NODE)
912 ReplaceUses(Node, ResNode);
915 // If after the replacement this node is not used any more,
916 // remove this dead node.
917 if (Node->use_empty()) // Don't delete EntryToken, etc.
918 CurDAG->RemoveDeadNode(Node);
921 CurDAG->setRoot(Dummy.getValue());
924 DEBUG(dbgs() << "===== Instruction selection ends:\n");
926 PostprocessISelDAG();
929 static bool hasExceptionPointerOrCodeUser(const CatchPadInst *CPI) {
930 for (const User *U : CPI->users()) {
931 if (const IntrinsicInst *EHPtrCall = dyn_cast<IntrinsicInst>(U)) {
932 Intrinsic::ID IID = EHPtrCall->getIntrinsicID();
933 if (IID == Intrinsic::eh_exceptionpointer ||
934 IID == Intrinsic::eh_exceptioncode)
941 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
942 /// do other setup for EH landing-pad blocks.
943 bool SelectionDAGISel::PrepareEHLandingPad() {
944 MachineBasicBlock *MBB = FuncInfo->MBB;
945 const Constant *PersonalityFn = FuncInfo->Fn->getPersonalityFn();
946 const BasicBlock *LLVMBB = MBB->getBasicBlock();
947 const TargetRegisterClass *PtrRC =
948 TLI->getRegClassFor(TLI->getPointerTy(CurDAG->getDataLayout()));
950 // Catchpads have one live-in register, which typically holds the exception
952 if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) {
953 if (hasExceptionPointerOrCodeUser(CPI)) {
954 // Get or create the virtual register to hold the pointer or code. Mark
955 // the live in physreg and copy into the vreg.
956 MCPhysReg EHPhysReg = TLI->getExceptionPointerRegister(PersonalityFn);
957 assert(EHPhysReg && "target lacks exception pointer register");
958 MBB->addLiveIn(EHPhysReg);
959 unsigned VReg = FuncInfo->getCatchPadExceptionPointerVReg(CPI, PtrRC);
960 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(),
961 TII->get(TargetOpcode::COPY), VReg)
962 .addReg(EHPhysReg, RegState::Kill);
967 if (!LLVMBB->isLandingPad())
970 // Add a label to mark the beginning of the landing pad. Deletion of the
971 // landing pad can thus be detected via the MachineModuleInfo.
972 MCSymbol *Label = MF->getMMI().addLandingPad(MBB);
974 // Assign the call site to the landing pad's begin label.
975 MF->getMMI().setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
977 const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL);
978 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
981 // Mark exception register as live in.
982 if (unsigned Reg = TLI->getExceptionPointerRegister(PersonalityFn))
983 FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
985 // Mark exception selector register as live in.
986 if (unsigned Reg = TLI->getExceptionSelectorRegister(PersonalityFn))
987 FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
992 /// isFoldedOrDeadInstruction - Return true if the specified instruction is
993 /// side-effect free and is either dead or folded into a generated instruction.
994 /// Return false if it needs to be emitted.
995 static bool isFoldedOrDeadInstruction(const Instruction *I,
996 FunctionLoweringInfo *FuncInfo) {
997 return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
998 !isa<TerminatorInst>(I) && // Terminators aren't folded.
999 !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded.
1000 !I->isEHPad() && // EH pad instructions aren't folded.
1001 !FuncInfo->isExportedInst(I); // Exported instrs must be computed.
1005 // Collect per Instruction statistics for fast-isel misses. Only those
1006 // instructions that cause the bail are accounted for. It does not account for
1007 // instructions higher in the block. Thus, summing the per instructions stats
1008 // will not add up to what is reported by NumFastIselFailures.
1009 static void collectFailStats(const Instruction *I) {
1010 switch (I->getOpcode()) {
1011 default: assert (0 && "<Invalid operator> ");
1014 case Instruction::Ret: NumFastIselFailRet++; return;
1015 case Instruction::Br: NumFastIselFailBr++; return;
1016 case Instruction::Switch: NumFastIselFailSwitch++; return;
1017 case Instruction::IndirectBr: NumFastIselFailIndirectBr++; return;
1018 case Instruction::Invoke: NumFastIselFailInvoke++; return;
1019 case Instruction::Resume: NumFastIselFailResume++; return;
1020 case Instruction::Unreachable: NumFastIselFailUnreachable++; return;
1022 // Standard binary operators...
1023 case Instruction::Add: NumFastIselFailAdd++; return;
1024 case Instruction::FAdd: NumFastIselFailFAdd++; return;
1025 case Instruction::Sub: NumFastIselFailSub++; return;
1026 case Instruction::FSub: NumFastIselFailFSub++; return;
1027 case Instruction::Mul: NumFastIselFailMul++; return;
1028 case Instruction::FMul: NumFastIselFailFMul++; return;
1029 case Instruction::UDiv: NumFastIselFailUDiv++; return;
1030 case Instruction::SDiv: NumFastIselFailSDiv++; return;
1031 case Instruction::FDiv: NumFastIselFailFDiv++; return;
1032 case Instruction::URem: NumFastIselFailURem++; return;
1033 case Instruction::SRem: NumFastIselFailSRem++; return;
1034 case Instruction::FRem: NumFastIselFailFRem++; return;
1036 // Logical operators...
1037 case Instruction::And: NumFastIselFailAnd++; return;
1038 case Instruction::Or: NumFastIselFailOr++; return;
1039 case Instruction::Xor: NumFastIselFailXor++; return;
1041 // Memory instructions...
1042 case Instruction::Alloca: NumFastIselFailAlloca++; return;
1043 case Instruction::Load: NumFastIselFailLoad++; return;
1044 case Instruction::Store: NumFastIselFailStore++; return;
1045 case Instruction::AtomicCmpXchg: NumFastIselFailAtomicCmpXchg++; return;
1046 case Instruction::AtomicRMW: NumFastIselFailAtomicRMW++; return;
1047 case Instruction::Fence: NumFastIselFailFence++; return;
1048 case Instruction::GetElementPtr: NumFastIselFailGetElementPtr++; return;
1050 // Convert instructions...
1051 case Instruction::Trunc: NumFastIselFailTrunc++; return;
1052 case Instruction::ZExt: NumFastIselFailZExt++; return;
1053 case Instruction::SExt: NumFastIselFailSExt++; return;
1054 case Instruction::FPTrunc: NumFastIselFailFPTrunc++; return;
1055 case Instruction::FPExt: NumFastIselFailFPExt++; return;
1056 case Instruction::FPToUI: NumFastIselFailFPToUI++; return;
1057 case Instruction::FPToSI: NumFastIselFailFPToSI++; return;
1058 case Instruction::UIToFP: NumFastIselFailUIToFP++; return;
1059 case Instruction::SIToFP: NumFastIselFailSIToFP++; return;
1060 case Instruction::IntToPtr: NumFastIselFailIntToPtr++; return;
1061 case Instruction::PtrToInt: NumFastIselFailPtrToInt++; return;
1062 case Instruction::BitCast: NumFastIselFailBitCast++; return;
1064 // Other instructions...
1065 case Instruction::ICmp: NumFastIselFailICmp++; return;
1066 case Instruction::FCmp: NumFastIselFailFCmp++; return;
1067 case Instruction::PHI: NumFastIselFailPHI++; return;
1068 case Instruction::Select: NumFastIselFailSelect++; return;
1069 case Instruction::Call: {
1070 if (auto const *Intrinsic = dyn_cast<IntrinsicInst>(I)) {
1071 switch (Intrinsic->getIntrinsicID()) {
1073 NumFastIselFailIntrinsicCall++; return;
1074 case Intrinsic::sadd_with_overflow:
1075 NumFastIselFailSAddWithOverflow++; return;
1076 case Intrinsic::uadd_with_overflow:
1077 NumFastIselFailUAddWithOverflow++; return;
1078 case Intrinsic::ssub_with_overflow:
1079 NumFastIselFailSSubWithOverflow++; return;
1080 case Intrinsic::usub_with_overflow:
1081 NumFastIselFailUSubWithOverflow++; return;
1082 case Intrinsic::smul_with_overflow:
1083 NumFastIselFailSMulWithOverflow++; return;
1084 case Intrinsic::umul_with_overflow:
1085 NumFastIselFailUMulWithOverflow++; return;
1086 case Intrinsic::frameaddress:
1087 NumFastIselFailFrameaddress++; return;
1088 case Intrinsic::sqrt:
1089 NumFastIselFailSqrt++; return;
1090 case Intrinsic::experimental_stackmap:
1091 NumFastIselFailStackMap++; return;
1092 case Intrinsic::experimental_patchpoint_void: // fall-through
1093 case Intrinsic::experimental_patchpoint_i64:
1094 NumFastIselFailPatchPoint++; return;
1097 NumFastIselFailCall++;
1100 case Instruction::Shl: NumFastIselFailShl++; return;
1101 case Instruction::LShr: NumFastIselFailLShr++; return;
1102 case Instruction::AShr: NumFastIselFailAShr++; return;
1103 case Instruction::VAArg: NumFastIselFailVAArg++; return;
1104 case Instruction::ExtractElement: NumFastIselFailExtractElement++; return;
1105 case Instruction::InsertElement: NumFastIselFailInsertElement++; return;
1106 case Instruction::ShuffleVector: NumFastIselFailShuffleVector++; return;
1107 case Instruction::ExtractValue: NumFastIselFailExtractValue++; return;
1108 case Instruction::InsertValue: NumFastIselFailInsertValue++; return;
1109 case Instruction::LandingPad: NumFastIselFailLandingPad++; return;
1114 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
1115 // Initialize the Fast-ISel state, if needed.
1116 FastISel *FastIS = nullptr;
1117 if (TM.Options.EnableFastISel)
1118 FastIS = TLI->createFastISel(*FuncInfo, LibInfo);
1120 // Iterate over all basic blocks in the function.
1121 ReversePostOrderTraversal<const Function*> RPOT(&Fn);
1122 for (ReversePostOrderTraversal<const Function*>::rpo_iterator
1123 I = RPOT.begin(), E = RPOT.end(); I != E; ++I) {
1124 const BasicBlock *LLVMBB = *I;
1126 if (OptLevel != CodeGenOpt::None) {
1127 bool AllPredsVisited = true;
1128 for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB);
1130 if (!FuncInfo->VisitedBBs.count(*PI)) {
1131 AllPredsVisited = false;
1136 if (AllPredsVisited) {
1137 for (BasicBlock::const_iterator I = LLVMBB->begin();
1138 const PHINode *PN = dyn_cast<PHINode>(I); ++I)
1139 FuncInfo->ComputePHILiveOutRegInfo(PN);
1141 for (BasicBlock::const_iterator I = LLVMBB->begin();
1142 const PHINode *PN = dyn_cast<PHINode>(I); ++I)
1143 FuncInfo->InvalidatePHILiveOutRegInfo(PN);
1146 FuncInfo->VisitedBBs.insert(LLVMBB);
1149 BasicBlock::const_iterator const Begin =
1150 LLVMBB->getFirstNonPHI()->getIterator();
1151 BasicBlock::const_iterator const End = LLVMBB->end();
1152 BasicBlock::const_iterator BI = End;
1154 FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
1156 continue; // Some blocks like catchpads have no code or MBB.
1157 FuncInfo->InsertPt = FuncInfo->MBB->getFirstNonPHI();
1159 // Setup an EH landing-pad block.
1160 FuncInfo->ExceptionPointerVirtReg = 0;
1161 FuncInfo->ExceptionSelectorVirtReg = 0;
1162 if (LLVMBB->isEHPad())
1163 if (!PrepareEHLandingPad())
1166 // Before doing SelectionDAG ISel, see if FastISel has been requested.
1168 FastIS->startNewBlock();
1170 // Emit code for any incoming arguments. This must happen before
1171 // beginning FastISel on the entry block.
1172 if (LLVMBB == &Fn.getEntryBlock()) {
1175 // Lower any arguments needed in this block if this is the entry block.
1176 if (!FastIS->lowerArguments()) {
1177 // Fast isel failed to lower these arguments
1178 ++NumFastIselFailLowerArguments;
1179 if (EnableFastISelAbort > 1)
1180 report_fatal_error("FastISel didn't lower all arguments");
1182 // Use SelectionDAG argument lowering
1184 CurDAG->setRoot(SDB->getControlRoot());
1186 CodeGenAndEmitDAG();
1189 // If we inserted any instructions at the beginning, make a note of
1190 // where they are, so we can be sure to emit subsequent instructions
1192 if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
1193 FastIS->setLastLocalValue(std::prev(FuncInfo->InsertPt));
1195 FastIS->setLastLocalValue(nullptr);
1198 unsigned NumFastIselRemaining = std::distance(Begin, End);
1199 // Do FastISel on as many instructions as possible.
1200 for (; BI != Begin; --BI) {
1201 const Instruction *Inst = &*std::prev(BI);
1203 // If we no longer require this instruction, skip it.
1204 if (isFoldedOrDeadInstruction(Inst, FuncInfo)) {
1205 --NumFastIselRemaining;
1209 // Bottom-up: reset the insert pos at the top, after any local-value
1211 FastIS->recomputeInsertPt();
1213 // Try to select the instruction with FastISel.
1214 if (FastIS->selectInstruction(Inst)) {
1215 --NumFastIselRemaining;
1216 ++NumFastIselSuccess;
1217 // If fast isel succeeded, skip over all the folded instructions, and
1218 // then see if there is a load right before the selected instructions.
1219 // Try to fold the load if so.
1220 const Instruction *BeforeInst = Inst;
1221 while (BeforeInst != &*Begin) {
1222 BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst));
1223 if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo))
1226 if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
1227 BeforeInst->hasOneUse() &&
1228 FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
1229 // If we succeeded, don't re-select the load.
1230 BI = std::next(BasicBlock::const_iterator(BeforeInst));
1231 --NumFastIselRemaining;
1232 ++NumFastIselSuccess;
1238 if (EnableFastISelVerbose2)
1239 collectFailStats(Inst);
1242 // Then handle certain instructions as single-LLVM-Instruction blocks.
1243 if (isa<CallInst>(Inst)) {
1245 if (EnableFastISelVerbose || EnableFastISelAbort) {
1246 dbgs() << "FastISel missed call: ";
1249 if (EnableFastISelAbort > 2)
1250 // FastISel selector couldn't handle something and bailed.
1251 // For the purpose of debugging, just abort.
1252 report_fatal_error("FastISel didn't select the entire block");
1254 if (!Inst->getType()->isVoidTy() && !Inst->getType()->isTokenTy() &&
1255 !Inst->use_empty()) {
1256 unsigned &R = FuncInfo->ValueMap[Inst];
1258 R = FuncInfo->CreateRegs(Inst->getType());
1261 bool HadTailCall = false;
1262 MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
1263 SelectBasicBlock(Inst->getIterator(), BI, HadTailCall);
1265 // If the call was emitted as a tail call, we're done with the block.
1266 // We also need to delete any previously emitted instructions.
1268 FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
1273 // Recompute NumFastIselRemaining as Selection DAG instruction
1274 // selection may have handled the call, input args, etc.
1275 unsigned RemainingNow = std::distance(Begin, BI);
1276 NumFastIselFailures += NumFastIselRemaining - RemainingNow;
1277 NumFastIselRemaining = RemainingNow;
1281 bool ShouldAbort = EnableFastISelAbort;
1282 if (EnableFastISelVerbose || EnableFastISelAbort) {
1283 if (isa<TerminatorInst>(Inst)) {
1284 // Use a different message for terminator misses.
1285 dbgs() << "FastISel missed terminator: ";
1286 // Don't abort unless for terminator unless the level is really high
1287 ShouldAbort = (EnableFastISelAbort > 2);
1289 dbgs() << "FastISel miss: ";
1294 // FastISel selector couldn't handle something and bailed.
1295 // For the purpose of debugging, just abort.
1296 report_fatal_error("FastISel didn't select the entire block");
1298 NumFastIselFailures += NumFastIselRemaining;
1302 FastIS->recomputeInsertPt();
1304 // Lower any arguments needed in this block if this is the entry block.
1305 if (LLVMBB == &Fn.getEntryBlock()) {
1314 ++NumFastIselBlocks;
1317 // Run SelectionDAG instruction selection on the remainder of the block
1318 // not handled by FastISel. If FastISel is not run, this is the entire
1321 SelectBasicBlock(Begin, BI, HadTailCall);
1325 FuncInfo->PHINodesToUpdate.clear();
1329 SDB->clearDanglingDebugInfo();
1330 SDB->SPDescriptor.resetPerFunctionState();
1333 /// Given that the input MI is before a partial terminator sequence TSeq, return
1334 /// true if M + TSeq also a partial terminator sequence.
1336 /// A Terminator sequence is a sequence of MachineInstrs which at this point in
1337 /// lowering copy vregs into physical registers, which are then passed into
1338 /// terminator instructors so we can satisfy ABI constraints. A partial
1339 /// terminator sequence is an improper subset of a terminator sequence (i.e. it
1340 /// may be the whole terminator sequence).
1341 static bool MIIsInTerminatorSequence(const MachineInstr *MI) {
1342 // If we do not have a copy or an implicit def, we return true if and only if
1343 // MI is a debug value.
1344 if (!MI->isCopy() && !MI->isImplicitDef())
1345 // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the
1346 // physical registers if there is debug info associated with the terminator
1347 // of our mbb. We want to include said debug info in our terminator
1348 // sequence, so we return true in that case.
1349 return MI->isDebugValue();
1351 // We have left the terminator sequence if we are not doing one of the
1354 // 1. Copying a vreg into a physical register.
1355 // 2. Copying a vreg into a vreg.
1356 // 3. Defining a register via an implicit def.
1358 // OPI should always be a register definition...
1359 MachineInstr::const_mop_iterator OPI = MI->operands_begin();
1360 if (!OPI->isReg() || !OPI->isDef())
1363 // Defining any register via an implicit def is always ok.
1364 if (MI->isImplicitDef())
1367 // Grab the copy source...
1368 MachineInstr::const_mop_iterator OPI2 = OPI;
1370 assert(OPI2 != MI->operands_end()
1371 && "Should have a copy implying we should have 2 arguments.");
1373 // Make sure that the copy dest is not a vreg when the copy source is a
1374 // physical register.
1375 if (!OPI2->isReg() ||
1376 (!TargetRegisterInfo::isPhysicalRegister(OPI->getReg()) &&
1377 TargetRegisterInfo::isPhysicalRegister(OPI2->getReg())))
1383 /// Find the split point at which to splice the end of BB into its success stack
1384 /// protector check machine basic block.
1386 /// On many platforms, due to ABI constraints, terminators, even before register
1387 /// allocation, use physical registers. This creates an issue for us since
1388 /// physical registers at this point can not travel across basic
1389 /// blocks. Luckily, selectiondag always moves physical registers into vregs
1390 /// when they enter functions and moves them through a sequence of copies back
1391 /// into the physical registers right before the terminator creating a
1392 /// ``Terminator Sequence''. This function is searching for the beginning of the
1393 /// terminator sequence so that we can ensure that we splice off not just the
1394 /// terminator, but additionally the copies that move the vregs into the
1395 /// physical registers.
1396 static MachineBasicBlock::iterator
1397 FindSplitPointForStackProtector(MachineBasicBlock *BB, DebugLoc DL) {
1398 MachineBasicBlock::iterator SplitPoint = BB->getFirstTerminator();
1400 if (SplitPoint == BB->begin())
1403 MachineBasicBlock::iterator Start = BB->begin();
1404 MachineBasicBlock::iterator Previous = SplitPoint;
1407 while (MIIsInTerminatorSequence(Previous)) {
1408 SplitPoint = Previous;
1409 if (Previous == Start)
1418 SelectionDAGISel::FinishBasicBlock() {
1420 DEBUG(dbgs() << "Total amount of phi nodes to update: "
1421 << FuncInfo->PHINodesToUpdate.size() << "\n";
1422 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i)
1423 dbgs() << "Node " << i << " : ("
1424 << FuncInfo->PHINodesToUpdate[i].first
1425 << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
1427 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1428 // PHI nodes in successors.
1429 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1430 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
1431 assert(PHI->isPHI() &&
1432 "This is not a machine PHI node that we are updating!");
1433 if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
1435 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
1438 // Handle stack protector.
1439 if (SDB->SPDescriptor.shouldEmitStackProtector()) {
1440 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1441 MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB();
1443 // Find the split point to split the parent mbb. At the same time copy all
1444 // physical registers used in the tail of parent mbb into virtual registers
1445 // before the split point and back into physical registers after the split
1446 // point. This prevents us needing to deal with Live-ins and many other
1447 // register allocation issues caused by us splitting the parent mbb. The
1448 // register allocator will clean up said virtual copies later on.
1449 MachineBasicBlock::iterator SplitPoint =
1450 FindSplitPointForStackProtector(ParentMBB, SDB->getCurDebugLoc());
1452 // Splice the terminator of ParentMBB into SuccessMBB.
1453 SuccessMBB->splice(SuccessMBB->end(), ParentMBB,
1457 // Add compare/jump on neq/jump to the parent BB.
1458 FuncInfo->MBB = ParentMBB;
1459 FuncInfo->InsertPt = ParentMBB->end();
1460 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
1461 CurDAG->setRoot(SDB->getRoot());
1463 CodeGenAndEmitDAG();
1465 // CodeGen Failure MBB if we have not codegened it yet.
1466 MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB();
1467 if (!FailureMBB->size()) {
1468 FuncInfo->MBB = FailureMBB;
1469 FuncInfo->InsertPt = FailureMBB->end();
1470 SDB->visitSPDescriptorFailure(SDB->SPDescriptor);
1471 CurDAG->setRoot(SDB->getRoot());
1473 CodeGenAndEmitDAG();
1476 // Clear the Per-BB State.
1477 SDB->SPDescriptor.resetPerBBState();
1480 for (unsigned i = 0, e = SDB->BitTestCases.size(); i != e; ++i) {
1481 // Lower header first, if it wasn't already lowered
1482 if (!SDB->BitTestCases[i].Emitted) {
1483 // Set the current basic block to the mbb we wish to insert the code into
1484 FuncInfo->MBB = SDB->BitTestCases[i].Parent;
1485 FuncInfo->InsertPt = FuncInfo->MBB->end();
1487 SDB->visitBitTestHeader(SDB->BitTestCases[i], FuncInfo->MBB);
1488 CurDAG->setRoot(SDB->getRoot());
1490 CodeGenAndEmitDAG();
1493 BranchProbability UnhandledProb = SDB->BitTestCases[i].Prob;
1494 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size(); j != ej; ++j) {
1495 UnhandledProb -= SDB->BitTestCases[i].Cases[j].ExtraProb;
1496 // Set the current basic block to the mbb we wish to insert the code into
1497 FuncInfo->MBB = SDB->BitTestCases[i].Cases[j].ThisBB;
1498 FuncInfo->InsertPt = FuncInfo->MBB->end();
1501 // If all cases cover a contiguous range, it is not necessary to jump to
1502 // the default block after the last bit test fails. This is because the
1503 // range check during bit test header creation has guaranteed that every
1504 // case here doesn't go outside the range.
1505 MachineBasicBlock *NextMBB;
1506 if (SDB->BitTestCases[i].ContiguousRange && j + 2 == ej)
1507 NextMBB = SDB->BitTestCases[i].Cases[j + 1].TargetBB;
1508 else if (j + 1 != ej)
1509 NextMBB = SDB->BitTestCases[i].Cases[j + 1].ThisBB;
1511 NextMBB = SDB->BitTestCases[i].Default;
1513 SDB->visitBitTestCase(SDB->BitTestCases[i],
1516 SDB->BitTestCases[i].Reg,
1517 SDB->BitTestCases[i].Cases[j],
1520 CurDAG->setRoot(SDB->getRoot());
1522 CodeGenAndEmitDAG();
1524 if (SDB->BitTestCases[i].ContiguousRange && j + 2 == ej)
1529 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1531 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1532 MachineBasicBlock *PHIBB = PHI->getParent();
1533 assert(PHI->isPHI() &&
1534 "This is not a machine PHI node that we are updating!");
1535 // This is "default" BB. We have two jumps to it. From "header" BB and
1536 // from last "case" BB.
1537 if (PHIBB == SDB->BitTestCases[i].Default)
1538 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1539 .addMBB(SDB->BitTestCases[i].Parent)
1540 .addReg(FuncInfo->PHINodesToUpdate[pi].second)
1541 .addMBB(SDB->BitTestCases[i].Cases.back().ThisBB);
1542 // One of "cases" BB.
1543 for (unsigned j = 0, ej = SDB->BitTestCases[i].Cases.size();
1545 MachineBasicBlock* cBB = SDB->BitTestCases[i].Cases[j].ThisBB;
1546 if (cBB->isSuccessor(PHIBB))
1547 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB);
1551 SDB->BitTestCases.clear();
1553 // If the JumpTable record is filled in, then we need to emit a jump table.
1554 // Updating the PHI nodes is tricky in this case, since we need to determine
1555 // whether the PHI is a successor of the range check MBB or the jump table MBB
1556 for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
1557 // Lower header first, if it wasn't already lowered
1558 if (!SDB->JTCases[i].first.Emitted) {
1559 // Set the current basic block to the mbb we wish to insert the code into
1560 FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB;
1561 FuncInfo->InsertPt = FuncInfo->MBB->end();
1563 SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first,
1565 CurDAG->setRoot(SDB->getRoot());
1567 CodeGenAndEmitDAG();
1570 // Set the current basic block to the mbb we wish to insert the code into
1571 FuncInfo->MBB = SDB->JTCases[i].second.MBB;
1572 FuncInfo->InsertPt = FuncInfo->MBB->end();
1574 SDB->visitJumpTable(SDB->JTCases[i].second);
1575 CurDAG->setRoot(SDB->getRoot());
1577 CodeGenAndEmitDAG();
1580 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1582 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1583 MachineBasicBlock *PHIBB = PHI->getParent();
1584 assert(PHI->isPHI() &&
1585 "This is not a machine PHI node that we are updating!");
1586 // "default" BB. We can go there only from header BB.
1587 if (PHIBB == SDB->JTCases[i].second.Default)
1588 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1589 .addMBB(SDB->JTCases[i].first.HeaderBB);
1590 // JT BB. Just iterate over successors here
1591 if (FuncInfo->MBB->isSuccessor(PHIBB))
1592 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
1595 SDB->JTCases.clear();
1597 // If we generated any switch lowering information, build and codegen any
1598 // additional DAGs necessary.
1599 for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
1600 // Set the current basic block to the mbb we wish to insert the code into
1601 FuncInfo->MBB = SDB->SwitchCases[i].ThisBB;
1602 FuncInfo->InsertPt = FuncInfo->MBB->end();
1604 // Determine the unique successors.
1605 SmallVector<MachineBasicBlock *, 2> Succs;
1606 Succs.push_back(SDB->SwitchCases[i].TrueBB);
1607 if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB)
1608 Succs.push_back(SDB->SwitchCases[i].FalseBB);
1610 // Emit the code. Note that this could result in FuncInfo->MBB being split.
1611 SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB);
1612 CurDAG->setRoot(SDB->getRoot());
1614 CodeGenAndEmitDAG();
1616 // Remember the last block, now that any splitting is done, for use in
1617 // populating PHI nodes in successors.
1618 MachineBasicBlock *ThisBB = FuncInfo->MBB;
1620 // Handle any PHI nodes in successors of this chunk, as if we were coming
1621 // from the original BB before switch expansion. Note that PHI nodes can
1622 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1623 // handle them the right number of times.
1624 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1625 FuncInfo->MBB = Succs[i];
1626 FuncInfo->InsertPt = FuncInfo->MBB->end();
1627 // FuncInfo->MBB may have been removed from the CFG if a branch was
1629 if (ThisBB->isSuccessor(FuncInfo->MBB)) {
1630 for (MachineBasicBlock::iterator
1631 MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
1632 MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
1633 MachineInstrBuilder PHI(*MF, MBBI);
1634 // This value for this PHI node is recorded in PHINodesToUpdate.
1635 for (unsigned pn = 0; ; ++pn) {
1636 assert(pn != FuncInfo->PHINodesToUpdate.size() &&
1637 "Didn't find PHI entry!");
1638 if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
1639 PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
1647 SDB->SwitchCases.clear();
1651 /// Create the scheduler. If a specific scheduler was specified
1652 /// via the SchedulerRegistry, use it, otherwise select the
1653 /// one preferred by the target.
1655 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1656 return ISHeuristic(this, OptLevel);
1659 //===----------------------------------------------------------------------===//
1660 // Helper functions used by the generated instruction selector.
1661 //===----------------------------------------------------------------------===//
1662 // Calls to these methods are generated by tblgen.
1664 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
1665 /// the dag combiner simplified the 255, we still want to match. RHS is the
1666 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1667 /// specified in the .td file (e.g. 255).
1668 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1669 int64_t DesiredMaskS) const {
1670 const APInt &ActualMask = RHS->getAPIntValue();
1671 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1673 // If the actual mask exactly matches, success!
1674 if (ActualMask == DesiredMask)
1677 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1678 if (ActualMask.intersects(~DesiredMask))
1681 // Otherwise, the DAG Combiner may have proven that the value coming in is
1682 // either already zero or is not demanded. Check for known zero input bits.
1683 APInt NeededMask = DesiredMask & ~ActualMask;
1684 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1687 // TODO: check to see if missing bits are just not demanded.
1689 // Otherwise, this pattern doesn't match.
1693 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
1694 /// the dag combiner simplified the 255, we still want to match. RHS is the
1695 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1696 /// specified in the .td file (e.g. 255).
1697 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
1698 int64_t DesiredMaskS) const {
1699 const APInt &ActualMask = RHS->getAPIntValue();
1700 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1702 // If the actual mask exactly matches, success!
1703 if (ActualMask == DesiredMask)
1706 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1707 if (ActualMask.intersects(~DesiredMask))
1710 // Otherwise, the DAG Combiner may have proven that the value coming in is
1711 // either already zero or is not demanded. Check for known zero input bits.
1712 APInt NeededMask = DesiredMask & ~ActualMask;
1714 APInt KnownZero, KnownOne;
1715 CurDAG->computeKnownBits(LHS, KnownZero, KnownOne);
1717 // If all the missing bits in the or are already known to be set, match!
1718 if ((NeededMask & KnownOne) == NeededMask)
1721 // TODO: check to see if missing bits are just not demanded.
1723 // Otherwise, this pattern doesn't match.
1727 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1728 /// by tblgen. Others should not call it.
1729 void SelectionDAGISel::
1730 SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops, SDLoc DL) {
1731 std::vector<SDValue> InOps;
1732 std::swap(InOps, Ops);
1734 Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
1735 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1
1736 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc
1737 Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack)
1739 unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
1740 if (InOps[e-1].getValueType() == MVT::Glue)
1741 --e; // Don't process a glue operand if it is here.
1744 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1745 if (!InlineAsm::isMemKind(Flags)) {
1746 // Just skip over this operand, copying the operands verbatim.
1747 Ops.insert(Ops.end(), InOps.begin()+i,
1748 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1749 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
1751 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1752 "Memory operand with multiple values?");
1754 unsigned TiedToOperand;
1755 if (InlineAsm::isUseOperandTiedToDef(Flags, TiedToOperand)) {
1756 // We need the constraint ID from the operand this is tied to.
1757 unsigned CurOp = InlineAsm::Op_FirstOperand;
1758 Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue();
1759 for (; TiedToOperand; --TiedToOperand) {
1760 CurOp += InlineAsm::getNumOperandRegisters(Flags)+1;
1761 Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue();
1765 // Otherwise, this is a memory operand. Ask the target to select it.
1766 std::vector<SDValue> SelOps;
1767 if (SelectInlineAsmMemoryOperand(InOps[i+1],
1768 InlineAsm::getMemoryConstraintID(Flags),
1770 report_fatal_error("Could not match memory address. Inline asm"
1773 // Add this to the output node.
1775 InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
1776 Ops.push_back(CurDAG->getTargetConstant(NewFlags, DL, MVT::i32));
1777 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1782 // Add the glue input back if present.
1783 if (e != InOps.size())
1784 Ops.push_back(InOps.back());
1787 /// findGlueUse - Return use of MVT::Glue value produced by the specified
1790 static SDNode *findGlueUse(SDNode *N) {
1791 unsigned FlagResNo = N->getNumValues()-1;
1792 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1793 SDUse &Use = I.getUse();
1794 if (Use.getResNo() == FlagResNo)
1795 return Use.getUser();
1800 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1801 /// This function recursively traverses up the operand chain, ignoring
1803 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
1804 SDNode *Root, SmallPtrSetImpl<SDNode*> &Visited,
1805 bool IgnoreChains) {
1806 // The NodeID's are given uniques ID's where a node ID is guaranteed to be
1807 // greater than all of its (recursive) operands. If we scan to a point where
1808 // 'use' is smaller than the node we're scanning for, then we know we will
1811 // The Use may be -1 (unassigned) if it is a newly allocated node. This can
1812 // happen because we scan down to newly selected nodes in the case of glue
1814 if ((Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1))
1817 // Don't revisit nodes if we already scanned it and didn't fail, we know we
1818 // won't fail if we scan it again.
1819 if (!Visited.insert(Use).second)
1822 for (const SDValue &Op : Use->op_values()) {
1823 // Ignore chain uses, they are validated by HandleMergeInputChains.
1824 if (Op.getValueType() == MVT::Other && IgnoreChains)
1827 SDNode *N = Op.getNode();
1829 if (Use == ImmedUse || Use == Root)
1830 continue; // We are not looking for immediate use.
1835 // Traverse up the operand chain.
1836 if (findNonImmUse(N, Def, ImmedUse, Root, Visited, IgnoreChains))
1842 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
1843 /// operand node N of U during instruction selection that starts at Root.
1844 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
1845 SDNode *Root) const {
1846 if (OptLevel == CodeGenOpt::None) return false;
1847 return N.hasOneUse();
1850 /// IsLegalToFold - Returns true if the specific operand node N of
1851 /// U can be folded during instruction selection that starts at Root.
1852 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
1853 CodeGenOpt::Level OptLevel,
1854 bool IgnoreChains) {
1855 if (OptLevel == CodeGenOpt::None) return false;
1857 // If Root use can somehow reach N through a path that that doesn't contain
1858 // U then folding N would create a cycle. e.g. In the following
1859 // diagram, Root can reach N through X. If N is folded into into Root, then
1860 // X is both a predecessor and a successor of U.
1871 // * indicates nodes to be folded together.
1873 // If Root produces glue, then it gets (even more) interesting. Since it
1874 // will be "glued" together with its glue use in the scheduler, we need to
1875 // check if it might reach N.
1894 // If GU (glue use) indirectly reaches N (the load), and Root folds N
1895 // (call it Fold), then X is a predecessor of GU and a successor of
1896 // Fold. But since Fold and GU are glued together, this will create
1897 // a cycle in the scheduling graph.
1899 // If the node has glue, walk down the graph to the "lowest" node in the
1901 EVT VT = Root->getValueType(Root->getNumValues()-1);
1902 while (VT == MVT::Glue) {
1903 SDNode *GU = findGlueUse(Root);
1907 VT = Root->getValueType(Root->getNumValues()-1);
1909 // If our query node has a glue result with a use, we've walked up it. If
1910 // the user (which has already been selected) has a chain or indirectly uses
1911 // the chain, our WalkChainUsers predicate will not consider it. Because of
1912 // this, we cannot ignore chains in this predicate.
1913 IgnoreChains = false;
1917 SmallPtrSet<SDNode*, 16> Visited;
1918 return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
1921 SDNode *SelectionDAGISel::Select_INLINEASM(SDNode *N) {
1924 std::vector<SDValue> Ops(N->op_begin(), N->op_end());
1925 SelectInlineAsmMemoryOperands(Ops, DL);
1927 const EVT VTs[] = {MVT::Other, MVT::Glue};
1928 SDValue New = CurDAG->getNode(ISD::INLINEASM, DL, VTs, Ops);
1930 return New.getNode();
1934 *SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) {
1936 MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1));
1937 const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0));
1939 TLI->getRegisterByName(RegStr->getString().data(), Op->getValueType(0),
1941 SDValue New = CurDAG->getCopyFromReg(
1942 Op->getOperand(0), dl, Reg, Op->getValueType(0));
1944 return New.getNode();
1948 *SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) {
1950 MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1));
1951 const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0));
1952 unsigned Reg = TLI->getRegisterByName(RegStr->getString().data(),
1953 Op->getOperand(2).getValueType(),
1955 SDValue New = CurDAG->getCopyToReg(
1956 Op->getOperand(0), dl, Reg, Op->getOperand(2));
1958 return New.getNode();
1963 SDNode *SelectionDAGISel::Select_UNDEF(SDNode *N) {
1964 return CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF,N->getValueType(0));
1967 /// GetVBR - decode a vbr encoding whose top bit is set.
1968 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline uint64_t
1969 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
1970 assert(Val >= 128 && "Not a VBR");
1971 Val &= 127; // Remove first vbr bit.
1976 NextBits = MatcherTable[Idx++];
1977 Val |= (NextBits&127) << Shift;
1979 } while (NextBits & 128);
1985 /// UpdateChainsAndGlue - When a match is complete, this method updates uses of
1986 /// interior glue and chain results to use the new glue and chain results.
1987 void SelectionDAGISel::
1988 UpdateChainsAndGlue(SDNode *NodeToMatch, SDValue InputChain,
1989 const SmallVectorImpl<SDNode*> &ChainNodesMatched,
1991 const SmallVectorImpl<SDNode*> &GlueResultNodesMatched,
1992 bool isMorphNodeTo) {
1993 SmallVector<SDNode*, 4> NowDeadNodes;
1995 // Now that all the normal results are replaced, we replace the chain and
1996 // glue results if present.
1997 if (!ChainNodesMatched.empty()) {
1998 assert(InputChain.getNode() &&
1999 "Matched input chains but didn't produce a chain");
2000 // Loop over all of the nodes we matched that produced a chain result.
2001 // Replace all the chain results with the final chain we ended up with.
2002 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2003 SDNode *ChainNode = ChainNodesMatched[i];
2005 // If this node was already deleted, don't look at it.
2006 if (ChainNode->getOpcode() == ISD::DELETED_NODE)
2009 // Don't replace the results of the root node if we're doing a
2011 if (ChainNode == NodeToMatch && isMorphNodeTo)
2014 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
2015 if (ChainVal.getValueType() == MVT::Glue)
2016 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
2017 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
2018 CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain);
2020 // If the node became dead and we haven't already seen it, delete it.
2021 if (ChainNode->use_empty() &&
2022 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
2023 NowDeadNodes.push_back(ChainNode);
2027 // If the result produces glue, update any glue results in the matched
2028 // pattern with the glue result.
2029 if (InputGlue.getNode()) {
2030 // Handle any interior nodes explicitly marked.
2031 for (unsigned i = 0, e = GlueResultNodesMatched.size(); i != e; ++i) {
2032 SDNode *FRN = GlueResultNodesMatched[i];
2034 // If this node was already deleted, don't look at it.
2035 if (FRN->getOpcode() == ISD::DELETED_NODE)
2038 assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Glue &&
2039 "Doesn't have a glue result");
2040 CurDAG->ReplaceAllUsesOfValueWith(SDValue(FRN, FRN->getNumValues()-1),
2043 // If the node became dead and we haven't already seen it, delete it.
2044 if (FRN->use_empty() &&
2045 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), FRN))
2046 NowDeadNodes.push_back(FRN);
2050 if (!NowDeadNodes.empty())
2051 CurDAG->RemoveDeadNodes(NowDeadNodes);
2053 DEBUG(dbgs() << "ISEL: Match complete!\n");
2059 CR_LeadsToInteriorNode
2062 /// WalkChainUsers - Walk down the users of the specified chained node that is
2063 /// part of the pattern we're matching, looking at all of the users we find.
2064 /// This determines whether something is an interior node, whether we have a
2065 /// non-pattern node in between two pattern nodes (which prevent folding because
2066 /// it would induce a cycle) and whether we have a TokenFactor node sandwiched
2067 /// between pattern nodes (in which case the TF becomes part of the pattern).
2069 /// The walk we do here is guaranteed to be small because we quickly get down to
2070 /// already selected nodes "below" us.
2072 WalkChainUsers(const SDNode *ChainedNode,
2073 SmallVectorImpl<SDNode*> &ChainedNodesInPattern,
2074 SmallVectorImpl<SDNode*> &InteriorChainedNodes) {
2075 ChainResult Result = CR_Simple;
2077 for (SDNode::use_iterator UI = ChainedNode->use_begin(),
2078 E = ChainedNode->use_end(); UI != E; ++UI) {
2079 // Make sure the use is of the chain, not some other value we produce.
2080 if (UI.getUse().getValueType() != MVT::Other) continue;
2084 if (User->getOpcode() == ISD::HANDLENODE) // Root of the graph.
2087 // If we see an already-selected machine node, then we've gone beyond the
2088 // pattern that we're selecting down into the already selected chunk of the
2090 unsigned UserOpcode = User->getOpcode();
2091 if (User->isMachineOpcode() ||
2092 UserOpcode == ISD::CopyToReg ||
2093 UserOpcode == ISD::CopyFromReg ||
2094 UserOpcode == ISD::INLINEASM ||
2095 UserOpcode == ISD::EH_LABEL ||
2096 UserOpcode == ISD::LIFETIME_START ||
2097 UserOpcode == ISD::LIFETIME_END) {
2098 // If their node ID got reset to -1 then they've already been selected.
2099 // Treat them like a MachineOpcode.
2100 if (User->getNodeId() == -1)
2104 // If we have a TokenFactor, we handle it specially.
2105 if (User->getOpcode() != ISD::TokenFactor) {
2106 // If the node isn't a token factor and isn't part of our pattern, then it
2107 // must be a random chained node in between two nodes we're selecting.
2108 // This happens when we have something like:
2113 // Because we structurally match the load/store as a read/modify/write,
2114 // but the call is chained between them. We cannot fold in this case
2115 // because it would induce a cycle in the graph.
2116 if (!std::count(ChainedNodesInPattern.begin(),
2117 ChainedNodesInPattern.end(), User))
2118 return CR_InducesCycle;
2120 // Otherwise we found a node that is part of our pattern. For example in:
2124 // This would happen when we're scanning down from the load and see the
2125 // store as a user. Record that there is a use of ChainedNode that is
2126 // part of the pattern and keep scanning uses.
2127 Result = CR_LeadsToInteriorNode;
2128 InteriorChainedNodes.push_back(User);
2132 // If we found a TokenFactor, there are two cases to consider: first if the
2133 // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
2134 // uses of the TF are in our pattern) we just want to ignore it. Second,
2135 // the TokenFactor can be sandwiched in between two chained nodes, like so:
2141 // | \ DAG's like cheese
2144 // [TokenFactor] [Op]
2151 // In this case, the TokenFactor becomes part of our match and we rewrite it
2152 // as a new TokenFactor.
2154 // To distinguish these two cases, do a recursive walk down the uses.
2155 switch (WalkChainUsers(User, ChainedNodesInPattern, InteriorChainedNodes)) {
2157 // If the uses of the TokenFactor are just already-selected nodes, ignore
2158 // it, it is "below" our pattern.
2160 case CR_InducesCycle:
2161 // If the uses of the TokenFactor lead to nodes that are not part of our
2162 // pattern that are not selected, folding would turn this into a cycle,
2164 return CR_InducesCycle;
2165 case CR_LeadsToInteriorNode:
2166 break; // Otherwise, keep processing.
2169 // Okay, we know we're in the interesting interior case. The TokenFactor
2170 // is now going to be considered part of the pattern so that we rewrite its
2171 // uses (it may have uses that are not part of the pattern) with the
2172 // ultimate chain result of the generated code. We will also add its chain
2173 // inputs as inputs to the ultimate TokenFactor we create.
2174 Result = CR_LeadsToInteriorNode;
2175 ChainedNodesInPattern.push_back(User);
2176 InteriorChainedNodes.push_back(User);
2183 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
2184 /// operation for when the pattern matched at least one node with a chains. The
2185 /// input vector contains a list of all of the chained nodes that we match. We
2186 /// must determine if this is a valid thing to cover (i.e. matching it won't
2187 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
2188 /// be used as the input node chain for the generated nodes.
2190 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
2191 SelectionDAG *CurDAG) {
2192 // Walk all of the chained nodes we've matched, recursively scanning down the
2193 // users of the chain result. This adds any TokenFactor nodes that are caught
2194 // in between chained nodes to the chained and interior nodes list.
2195 SmallVector<SDNode*, 3> InteriorChainedNodes;
2196 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2197 if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
2198 InteriorChainedNodes) == CR_InducesCycle)
2199 return SDValue(); // Would induce a cycle.
2202 // Okay, we have walked all the matched nodes and collected TokenFactor nodes
2203 // that we are interested in. Form our input TokenFactor node.
2204 SmallVector<SDValue, 3> InputChains;
2205 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2206 // Add the input chain of this node to the InputChains list (which will be
2207 // the operands of the generated TokenFactor) if it's not an interior node.
2208 SDNode *N = ChainNodesMatched[i];
2209 if (N->getOpcode() != ISD::TokenFactor) {
2210 if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
2213 // Otherwise, add the input chain.
2214 SDValue InChain = ChainNodesMatched[i]->getOperand(0);
2215 assert(InChain.getValueType() == MVT::Other && "Not a chain");
2216 InputChains.push_back(InChain);
2220 // If we have a token factor, we want to add all inputs of the token factor
2221 // that are not part of the pattern we're matching.
2222 for (const SDValue &Op : N->op_values()) {
2223 if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
2225 InputChains.push_back(Op);
2229 if (InputChains.size() == 1)
2230 return InputChains[0];
2231 return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
2232 MVT::Other, InputChains);
2235 /// MorphNode - Handle morphing a node in place for the selector.
2236 SDNode *SelectionDAGISel::
2237 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
2238 ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) {
2239 // It is possible we're using MorphNodeTo to replace a node with no
2240 // normal results with one that has a normal result (or we could be
2241 // adding a chain) and the input could have glue and chains as well.
2242 // In this case we need to shift the operands down.
2243 // FIXME: This is a horrible hack and broken in obscure cases, no worse
2244 // than the old isel though.
2245 int OldGlueResultNo = -1, OldChainResultNo = -1;
2247 unsigned NTMNumResults = Node->getNumValues();
2248 if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
2249 OldGlueResultNo = NTMNumResults-1;
2250 if (NTMNumResults != 1 &&
2251 Node->getValueType(NTMNumResults-2) == MVT::Other)
2252 OldChainResultNo = NTMNumResults-2;
2253 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
2254 OldChainResultNo = NTMNumResults-1;
2256 // Call the underlying SelectionDAG routine to do the transmogrification. Note
2257 // that this deletes operands of the old node that become dead.
2258 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops);
2260 // MorphNodeTo can operate in two ways: if an existing node with the
2261 // specified operands exists, it can just return it. Otherwise, it
2262 // updates the node in place to have the requested operands.
2264 // If we updated the node in place, reset the node ID. To the isel,
2265 // this should be just like a newly allocated machine node.
2269 unsigned ResNumResults = Res->getNumValues();
2270 // Move the glue if needed.
2271 if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
2272 (unsigned)OldGlueResultNo != ResNumResults-1)
2273 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldGlueResultNo),
2274 SDValue(Res, ResNumResults-1));
2276 if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
2279 // Move the chain reference if needed.
2280 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
2281 (unsigned)OldChainResultNo != ResNumResults-1)
2282 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
2283 SDValue(Res, ResNumResults-1));
2285 // Otherwise, no replacement happened because the node already exists. Replace
2286 // Uses of the old node with the new one.
2288 CurDAG->ReplaceAllUsesWith(Node, Res);
2293 /// CheckSame - Implements OP_CheckSame.
2294 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2295 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2297 const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
2298 // Accept if it is exactly the same as a previously recorded node.
2299 unsigned RecNo = MatcherTable[MatcherIndex++];
2300 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2301 return N == RecordedNodes[RecNo].first;
2304 /// CheckChildSame - Implements OP_CheckChildXSame.
2305 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2306 CheckChildSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2308 const SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes,
2310 if (ChildNo >= N.getNumOperands())
2311 return false; // Match fails if out of range child #.
2312 return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo),
2316 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
2317 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2318 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2319 const SelectionDAGISel &SDISel) {
2320 return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
2323 /// CheckNodePredicate - Implements OP_CheckNodePredicate.
2324 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2325 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2326 const SelectionDAGISel &SDISel, SDNode *N) {
2327 return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
2330 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2331 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2333 uint16_t Opc = MatcherTable[MatcherIndex++];
2334 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2335 return N->getOpcode() == Opc;
2338 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2339 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2340 const TargetLowering *TLI, const DataLayout &DL) {
2341 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2342 if (N.getValueType() == VT) return true;
2344 // Handle the case when VT is iPTR.
2345 return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL);
2348 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2349 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2350 SDValue N, const TargetLowering *TLI, const DataLayout &DL,
2352 if (ChildNo >= N.getNumOperands())
2353 return false; // Match fails if out of range child #.
2354 return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI,
2358 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2359 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2361 return cast<CondCodeSDNode>(N)->get() ==
2362 (ISD::CondCode)MatcherTable[MatcherIndex++];
2365 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2366 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2367 SDValue N, const TargetLowering *TLI, const DataLayout &DL) {
2368 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2369 if (cast<VTSDNode>(N)->getVT() == VT)
2372 // Handle the case when VT is iPTR.
2373 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL);
2376 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2377 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2379 int64_t Val = MatcherTable[MatcherIndex++];
2381 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2383 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
2384 return C && C->getSExtValue() == Val;
2387 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2388 CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2389 SDValue N, unsigned ChildNo) {
2390 if (ChildNo >= N.getNumOperands())
2391 return false; // Match fails if out of range child #.
2392 return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo));
2395 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2396 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2397 SDValue N, const SelectionDAGISel &SDISel) {
2398 int64_t Val = MatcherTable[MatcherIndex++];
2400 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2402 if (N->getOpcode() != ISD::AND) return false;
2404 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2405 return C && SDISel.CheckAndMask(N.getOperand(0), C, Val);
2408 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2409 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2410 SDValue N, const SelectionDAGISel &SDISel) {
2411 int64_t Val = MatcherTable[MatcherIndex++];
2413 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2415 if (N->getOpcode() != ISD::OR) return false;
2417 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2418 return C && SDISel.CheckOrMask(N.getOperand(0), C, Val);
2421 /// IsPredicateKnownToFail - If we know how and can do so without pushing a
2422 /// scope, evaluate the current node. If the current predicate is known to
2423 /// fail, set Result=true and return anything. If the current predicate is
2424 /// known to pass, set Result=false and return the MatcherIndex to continue
2425 /// with. If the current predicate is unknown, set Result=false and return the
2426 /// MatcherIndex to continue with.
2427 static unsigned IsPredicateKnownToFail(const unsigned char *Table,
2428 unsigned Index, SDValue N,
2430 const SelectionDAGISel &SDISel,
2431 SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes) {
2432 switch (Table[Index++]) {
2435 return Index-1; // Could not evaluate this predicate.
2436 case SelectionDAGISel::OPC_CheckSame:
2437 Result = !::CheckSame(Table, Index, N, RecordedNodes);
2439 case SelectionDAGISel::OPC_CheckChild0Same:
2440 case SelectionDAGISel::OPC_CheckChild1Same:
2441 case SelectionDAGISel::OPC_CheckChild2Same:
2442 case SelectionDAGISel::OPC_CheckChild3Same:
2443 Result = !::CheckChildSame(Table, Index, N, RecordedNodes,
2444 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Same);
2446 case SelectionDAGISel::OPC_CheckPatternPredicate:
2447 Result = !::CheckPatternPredicate(Table, Index, SDISel);
2449 case SelectionDAGISel::OPC_CheckPredicate:
2450 Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
2452 case SelectionDAGISel::OPC_CheckOpcode:
2453 Result = !::CheckOpcode(Table, Index, N.getNode());
2455 case SelectionDAGISel::OPC_CheckType:
2456 Result = !::CheckType(Table, Index, N, SDISel.TLI,
2457 SDISel.CurDAG->getDataLayout());
2459 case SelectionDAGISel::OPC_CheckChild0Type:
2460 case SelectionDAGISel::OPC_CheckChild1Type:
2461 case SelectionDAGISel::OPC_CheckChild2Type:
2462 case SelectionDAGISel::OPC_CheckChild3Type:
2463 case SelectionDAGISel::OPC_CheckChild4Type:
2464 case SelectionDAGISel::OPC_CheckChild5Type:
2465 case SelectionDAGISel::OPC_CheckChild6Type:
2466 case SelectionDAGISel::OPC_CheckChild7Type:
2467 Result = !::CheckChildType(
2468 Table, Index, N, SDISel.TLI, SDISel.CurDAG->getDataLayout(),
2469 Table[Index - 1] - SelectionDAGISel::OPC_CheckChild0Type);
2471 case SelectionDAGISel::OPC_CheckCondCode:
2472 Result = !::CheckCondCode(Table, Index, N);
2474 case SelectionDAGISel::OPC_CheckValueType:
2475 Result = !::CheckValueType(Table, Index, N, SDISel.TLI,
2476 SDISel.CurDAG->getDataLayout());
2478 case SelectionDAGISel::OPC_CheckInteger:
2479 Result = !::CheckInteger(Table, Index, N);
2481 case SelectionDAGISel::OPC_CheckChild0Integer:
2482 case SelectionDAGISel::OPC_CheckChild1Integer:
2483 case SelectionDAGISel::OPC_CheckChild2Integer:
2484 case SelectionDAGISel::OPC_CheckChild3Integer:
2485 case SelectionDAGISel::OPC_CheckChild4Integer:
2486 Result = !::CheckChildInteger(Table, Index, N,
2487 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Integer);
2489 case SelectionDAGISel::OPC_CheckAndImm:
2490 Result = !::CheckAndImm(Table, Index, N, SDISel);
2492 case SelectionDAGISel::OPC_CheckOrImm:
2493 Result = !::CheckOrImm(Table, Index, N, SDISel);
2501 /// FailIndex - If this match fails, this is the index to continue with.
2504 /// NodeStack - The node stack when the scope was formed.
2505 SmallVector<SDValue, 4> NodeStack;
2507 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
2508 unsigned NumRecordedNodes;
2510 /// NumMatchedMemRefs - The number of matched memref entries.
2511 unsigned NumMatchedMemRefs;
2513 /// InputChain/InputGlue - The current chain/glue
2514 SDValue InputChain, InputGlue;
2516 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
2517 bool HasChainNodesMatched, HasGlueResultNodesMatched;
2520 /// \\brief A DAG update listener to keep the matching state
2521 /// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to
2522 /// change the DAG while matching. X86 addressing mode matcher is an example
2524 class MatchStateUpdater : public SelectionDAG::DAGUpdateListener
2526 SmallVectorImpl<std::pair<SDValue, SDNode*> > &RecordedNodes;
2527 SmallVectorImpl<MatchScope> &MatchScopes;
2529 MatchStateUpdater(SelectionDAG &DAG,
2530 SmallVectorImpl<std::pair<SDValue, SDNode*> > &RN,
2531 SmallVectorImpl<MatchScope> &MS) :
2532 SelectionDAG::DAGUpdateListener(DAG),
2533 RecordedNodes(RN), MatchScopes(MS) { }
2535 void NodeDeleted(SDNode *N, SDNode *E) override {
2536 // Some early-returns here to avoid the search if we deleted the node or
2537 // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we
2538 // do, so it's unnecessary to update matching state at that point).
2539 // Neither of these can occur currently because we only install this
2540 // update listener during matching a complex patterns.
2541 if (!E || E->isMachineOpcode())
2543 // Performing linear search here does not matter because we almost never
2544 // run this code. You'd have to have a CSE during complex pattern
2546 for (auto &I : RecordedNodes)
2547 if (I.first.getNode() == N)
2550 for (auto &I : MatchScopes)
2551 for (auto &J : I.NodeStack)
2552 if (J.getNode() == N)
2558 SDNode *SelectionDAGISel::
2559 SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
2560 unsigned TableSize) {
2561 // FIXME: Should these even be selected? Handle these cases in the caller?
2562 switch (NodeToMatch->getOpcode()) {
2565 case ISD::EntryToken: // These nodes remain the same.
2566 case ISD::BasicBlock:
2568 case ISD::RegisterMask:
2569 case ISD::HANDLENODE:
2570 case ISD::MDNODE_SDNODE:
2571 case ISD::TargetConstant:
2572 case ISD::TargetConstantFP:
2573 case ISD::TargetConstantPool:
2574 case ISD::TargetFrameIndex:
2575 case ISD::TargetExternalSymbol:
2577 case ISD::TargetBlockAddress:
2578 case ISD::TargetJumpTable:
2579 case ISD::TargetGlobalTLSAddress:
2580 case ISD::TargetGlobalAddress:
2581 case ISD::TokenFactor:
2582 case ISD::CopyFromReg:
2583 case ISD::CopyToReg:
2585 case ISD::LIFETIME_START:
2586 case ISD::LIFETIME_END:
2587 NodeToMatch->setNodeId(-1); // Mark selected.
2589 case ISD::AssertSext:
2590 case ISD::AssertZext:
2591 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0),
2592 NodeToMatch->getOperand(0));
2594 case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
2595 case ISD::READ_REGISTER: return Select_READ_REGISTER(NodeToMatch);
2596 case ISD::WRITE_REGISTER: return Select_WRITE_REGISTER(NodeToMatch);
2597 case ISD::UNDEF: return Select_UNDEF(NodeToMatch);
2600 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
2602 // Set up the node stack with NodeToMatch as the only node on the stack.
2603 SmallVector<SDValue, 8> NodeStack;
2604 SDValue N = SDValue(NodeToMatch, 0);
2605 NodeStack.push_back(N);
2607 // MatchScopes - Scopes used when matching, if a match failure happens, this
2608 // indicates where to continue checking.
2609 SmallVector<MatchScope, 8> MatchScopes;
2611 // RecordedNodes - This is the set of nodes that have been recorded by the
2612 // state machine. The second value is the parent of the node, or null if the
2613 // root is recorded.
2614 SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
2616 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
2618 SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
2620 // These are the current input chain and glue for use when generating nodes.
2621 // Various Emit operations change these. For example, emitting a copytoreg
2622 // uses and updates these.
2623 SDValue InputChain, InputGlue;
2625 // ChainNodesMatched - If a pattern matches nodes that have input/output
2626 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
2627 // which ones they are. The result is captured into this list so that we can
2628 // update the chain results when the pattern is complete.
2629 SmallVector<SDNode*, 3> ChainNodesMatched;
2630 SmallVector<SDNode*, 3> GlueResultNodesMatched;
2632 DEBUG(dbgs() << "ISEL: Starting pattern match on root node: ";
2633 NodeToMatch->dump(CurDAG);
2636 // Determine where to start the interpreter. Normally we start at opcode #0,
2637 // but if the state machine starts with an OPC_SwitchOpcode, then we
2638 // accelerate the first lookup (which is guaranteed to be hot) with the
2639 // OpcodeOffset table.
2640 unsigned MatcherIndex = 0;
2642 if (!OpcodeOffset.empty()) {
2643 // Already computed the OpcodeOffset table, just index into it.
2644 if (N.getOpcode() < OpcodeOffset.size())
2645 MatcherIndex = OpcodeOffset[N.getOpcode()];
2646 DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n");
2648 } else if (MatcherTable[0] == OPC_SwitchOpcode) {
2649 // Otherwise, the table isn't computed, but the state machine does start
2650 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
2651 // is the first time we're selecting an instruction.
2654 // Get the size of this case.
2655 unsigned CaseSize = MatcherTable[Idx++];
2657 CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
2658 if (CaseSize == 0) break;
2660 // Get the opcode, add the index to the table.
2661 uint16_t Opc = MatcherTable[Idx++];
2662 Opc |= (unsigned short)MatcherTable[Idx++] << 8;
2663 if (Opc >= OpcodeOffset.size())
2664 OpcodeOffset.resize((Opc+1)*2);
2665 OpcodeOffset[Opc] = Idx;
2669 // Okay, do the lookup for the first opcode.
2670 if (N.getOpcode() < OpcodeOffset.size())
2671 MatcherIndex = OpcodeOffset[N.getOpcode()];
2675 assert(MatcherIndex < TableSize && "Invalid index");
2677 unsigned CurrentOpcodeIndex = MatcherIndex;
2679 BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
2682 // Okay, the semantics of this operation are that we should push a scope
2683 // then evaluate the first child. However, pushing a scope only to have
2684 // the first check fail (which then pops it) is inefficient. If we can
2685 // determine immediately that the first check (or first several) will
2686 // immediately fail, don't even bother pushing a scope for them.
2690 unsigned NumToSkip = MatcherTable[MatcherIndex++];
2691 if (NumToSkip & 128)
2692 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2693 // Found the end of the scope with no match.
2694 if (NumToSkip == 0) {
2699 FailIndex = MatcherIndex+NumToSkip;
2701 unsigned MatcherIndexOfPredicate = MatcherIndex;
2702 (void)MatcherIndexOfPredicate; // silence warning.
2704 // If we can't evaluate this predicate without pushing a scope (e.g. if
2705 // it is a 'MoveParent') or if the predicate succeeds on this node, we
2706 // push the scope and evaluate the full predicate chain.
2708 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
2709 Result, *this, RecordedNodes);
2713 DEBUG(dbgs() << " Skipped scope entry (due to false predicate) at "
2714 << "index " << MatcherIndexOfPredicate
2715 << ", continuing at " << FailIndex << "\n");
2716 ++NumDAGIselRetries;
2718 // Otherwise, we know that this case of the Scope is guaranteed to fail,
2719 // move to the next case.
2720 MatcherIndex = FailIndex;
2723 // If the whole scope failed to match, bail.
2724 if (FailIndex == 0) break;
2726 // Push a MatchScope which indicates where to go if the first child fails
2728 MatchScope NewEntry;
2729 NewEntry.FailIndex = FailIndex;
2730 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
2731 NewEntry.NumRecordedNodes = RecordedNodes.size();
2732 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
2733 NewEntry.InputChain = InputChain;
2734 NewEntry.InputGlue = InputGlue;
2735 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
2736 NewEntry.HasGlueResultNodesMatched = !GlueResultNodesMatched.empty();
2737 MatchScopes.push_back(NewEntry);
2740 case OPC_RecordNode: {
2741 // Remember this node, it may end up being an operand in the pattern.
2742 SDNode *Parent = nullptr;
2743 if (NodeStack.size() > 1)
2744 Parent = NodeStack[NodeStack.size()-2].getNode();
2745 RecordedNodes.push_back(std::make_pair(N, Parent));
2749 case OPC_RecordChild0: case OPC_RecordChild1:
2750 case OPC_RecordChild2: case OPC_RecordChild3:
2751 case OPC_RecordChild4: case OPC_RecordChild5:
2752 case OPC_RecordChild6: case OPC_RecordChild7: {
2753 unsigned ChildNo = Opcode-OPC_RecordChild0;
2754 if (ChildNo >= N.getNumOperands())
2755 break; // Match fails if out of range child #.
2757 RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
2761 case OPC_RecordMemRef:
2762 MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
2765 case OPC_CaptureGlueInput:
2766 // If the current node has an input glue, capture it in InputGlue.
2767 if (N->getNumOperands() != 0 &&
2768 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
2769 InputGlue = N->getOperand(N->getNumOperands()-1);
2772 case OPC_MoveChild: {
2773 unsigned ChildNo = MatcherTable[MatcherIndex++];
2774 if (ChildNo >= N.getNumOperands())
2775 break; // Match fails if out of range child #.
2776 N = N.getOperand(ChildNo);
2777 NodeStack.push_back(N);
2781 case OPC_MoveParent:
2782 // Pop the current node off the NodeStack.
2783 NodeStack.pop_back();
2784 assert(!NodeStack.empty() && "Node stack imbalance!");
2785 N = NodeStack.back();
2789 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
2792 case OPC_CheckChild0Same: case OPC_CheckChild1Same:
2793 case OPC_CheckChild2Same: case OPC_CheckChild3Same:
2794 if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes,
2795 Opcode-OPC_CheckChild0Same))
2799 case OPC_CheckPatternPredicate:
2800 if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
2802 case OPC_CheckPredicate:
2803 if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
2807 case OPC_CheckComplexPat: {
2808 unsigned CPNum = MatcherTable[MatcherIndex++];
2809 unsigned RecNo = MatcherTable[MatcherIndex++];
2810 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
2812 // If target can modify DAG during matching, keep the matching state
2814 std::unique_ptr<MatchStateUpdater> MSU;
2815 if (ComplexPatternFuncMutatesDAG())
2816 MSU.reset(new MatchStateUpdater(*CurDAG, RecordedNodes,
2819 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
2820 RecordedNodes[RecNo].first, CPNum,
2825 case OPC_CheckOpcode:
2826 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
2830 if (!::CheckType(MatcherTable, MatcherIndex, N, TLI,
2831 CurDAG->getDataLayout()))
2835 case OPC_SwitchOpcode: {
2836 unsigned CurNodeOpcode = N.getOpcode();
2837 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2840 // Get the size of this case.
2841 CaseSize = MatcherTable[MatcherIndex++];
2843 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2844 if (CaseSize == 0) break;
2846 uint16_t Opc = MatcherTable[MatcherIndex++];
2847 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2849 // If the opcode matches, then we will execute this case.
2850 if (CurNodeOpcode == Opc)
2853 // Otherwise, skip over this case.
2854 MatcherIndex += CaseSize;
2857 // If no cases matched, bail out.
2858 if (CaseSize == 0) break;
2860 // Otherwise, execute the case we found.
2861 DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart
2862 << " to " << MatcherIndex << "\n");
2866 case OPC_SwitchType: {
2867 MVT CurNodeVT = N.getSimpleValueType();
2868 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
2871 // Get the size of this case.
2872 CaseSize = MatcherTable[MatcherIndex++];
2874 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
2875 if (CaseSize == 0) break;
2877 MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2878 if (CaseVT == MVT::iPTR)
2879 CaseVT = TLI->getPointerTy(CurDAG->getDataLayout());
2881 // If the VT matches, then we will execute this case.
2882 if (CurNodeVT == CaseVT)
2885 // Otherwise, skip over this case.
2886 MatcherIndex += CaseSize;
2889 // If no cases matched, bail out.
2890 if (CaseSize == 0) break;
2892 // Otherwise, execute the case we found.
2893 DEBUG(dbgs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString()
2894 << "] from " << SwitchStart << " to " << MatcherIndex<<'\n');
2897 case OPC_CheckChild0Type: case OPC_CheckChild1Type:
2898 case OPC_CheckChild2Type: case OPC_CheckChild3Type:
2899 case OPC_CheckChild4Type: case OPC_CheckChild5Type:
2900 case OPC_CheckChild6Type: case OPC_CheckChild7Type:
2901 if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
2902 CurDAG->getDataLayout(),
2903 Opcode - OPC_CheckChild0Type))
2906 case OPC_CheckCondCode:
2907 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
2909 case OPC_CheckValueType:
2910 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI,
2911 CurDAG->getDataLayout()))
2914 case OPC_CheckInteger:
2915 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
2917 case OPC_CheckChild0Integer: case OPC_CheckChild1Integer:
2918 case OPC_CheckChild2Integer: case OPC_CheckChild3Integer:
2919 case OPC_CheckChild4Integer:
2920 if (!::CheckChildInteger(MatcherTable, MatcherIndex, N,
2921 Opcode-OPC_CheckChild0Integer)) break;
2923 case OPC_CheckAndImm:
2924 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
2926 case OPC_CheckOrImm:
2927 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
2930 case OPC_CheckFoldableChainNode: {
2931 assert(NodeStack.size() != 1 && "No parent node");
2932 // Verify that all intermediate nodes between the root and this one have
2934 bool HasMultipleUses = false;
2935 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
2936 if (!NodeStack[i].hasOneUse()) {
2937 HasMultipleUses = true;
2940 if (HasMultipleUses) break;
2942 // Check to see that the target thinks this is profitable to fold and that
2943 // we can fold it without inducing cycles in the graph.
2944 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2946 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
2947 NodeToMatch, OptLevel,
2948 true/*We validate our own chains*/))
2953 case OPC_EmitInteger: {
2954 MVT::SimpleValueType VT =
2955 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2956 int64_t Val = MatcherTable[MatcherIndex++];
2958 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2959 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2960 CurDAG->getTargetConstant(Val, SDLoc(NodeToMatch),
2964 case OPC_EmitRegister: {
2965 MVT::SimpleValueType VT =
2966 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2967 unsigned RegNo = MatcherTable[MatcherIndex++];
2968 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2969 CurDAG->getRegister(RegNo, VT), nullptr));
2972 case OPC_EmitRegister2: {
2973 // For targets w/ more than 256 register names, the register enum
2974 // values are stored in two bytes in the matcher table (just like
2976 MVT::SimpleValueType VT =
2977 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2978 unsigned RegNo = MatcherTable[MatcherIndex++];
2979 RegNo |= MatcherTable[MatcherIndex++] << 8;
2980 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
2981 CurDAG->getRegister(RegNo, VT), nullptr));
2985 case OPC_EmitConvertToTarget: {
2986 // Convert from IMM/FPIMM to target version.
2987 unsigned RecNo = MatcherTable[MatcherIndex++];
2988 assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget");
2989 SDValue Imm = RecordedNodes[RecNo].first;
2991 if (Imm->getOpcode() == ISD::Constant) {
2992 const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
2993 Imm = CurDAG->getConstant(*Val, SDLoc(NodeToMatch), Imm.getValueType(),
2995 } else if (Imm->getOpcode() == ISD::ConstantFP) {
2996 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
2997 Imm = CurDAG->getConstantFP(*Val, SDLoc(NodeToMatch),
2998 Imm.getValueType(), true);
3001 RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
3005 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
3006 case OPC_EmitMergeInputChains1_1: { // OPC_EmitMergeInputChains, 1, 1
3007 // These are space-optimized forms of OPC_EmitMergeInputChains.
3008 assert(!InputChain.getNode() &&
3009 "EmitMergeInputChains should be the first chain producing node");
3010 assert(ChainNodesMatched.empty() &&
3011 "Should only have one EmitMergeInputChains per match");
3013 // Read all of the chained nodes.
3014 unsigned RecNo = Opcode == OPC_EmitMergeInputChains1_1;
3015 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
3016 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3018 // FIXME: What if other value results of the node have uses not matched
3020 if (ChainNodesMatched.back() != NodeToMatch &&
3021 !RecordedNodes[RecNo].first.hasOneUse()) {
3022 ChainNodesMatched.clear();
3026 // Merge the input chains if they are not intra-pattern references.
3027 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
3029 if (!InputChain.getNode())
3030 break; // Failed to merge.
3034 case OPC_EmitMergeInputChains: {
3035 assert(!InputChain.getNode() &&
3036 "EmitMergeInputChains should be the first chain producing node");
3037 // This node gets a list of nodes we matched in the input that have
3038 // chains. We want to token factor all of the input chains to these nodes
3039 // together. However, if any of the input chains is actually one of the
3040 // nodes matched in this pattern, then we have an intra-match reference.
3041 // Ignore these because the newly token factored chain should not refer to
3043 unsigned NumChains = MatcherTable[MatcherIndex++];
3044 assert(NumChains != 0 && "Can't TF zero chains");
3046 assert(ChainNodesMatched.empty() &&
3047 "Should only have one EmitMergeInputChains per match");
3049 // Read all of the chained nodes.
3050 for (unsigned i = 0; i != NumChains; ++i) {
3051 unsigned RecNo = MatcherTable[MatcherIndex++];
3052 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
3053 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3055 // FIXME: What if other value results of the node have uses not matched
3057 if (ChainNodesMatched.back() != NodeToMatch &&
3058 !RecordedNodes[RecNo].first.hasOneUse()) {
3059 ChainNodesMatched.clear();
3064 // If the inner loop broke out, the match fails.
3065 if (ChainNodesMatched.empty())
3068 // Merge the input chains if they are not intra-pattern references.
3069 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
3071 if (!InputChain.getNode())
3072 break; // Failed to merge.
3077 case OPC_EmitCopyToReg: {
3078 unsigned RecNo = MatcherTable[MatcherIndex++];
3079 assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg");
3080 unsigned DestPhysReg = MatcherTable[MatcherIndex++];
3082 if (!InputChain.getNode())
3083 InputChain = CurDAG->getEntryNode();
3085 InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
3086 DestPhysReg, RecordedNodes[RecNo].first,
3089 InputGlue = InputChain.getValue(1);
3093 case OPC_EmitNodeXForm: {
3094 unsigned XFormNo = MatcherTable[MatcherIndex++];
3095 unsigned RecNo = MatcherTable[MatcherIndex++];
3096 assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm");
3097 SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
3098 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr));
3103 case OPC_MorphNodeTo: {
3104 uint16_t TargetOpc = MatcherTable[MatcherIndex++];
3105 TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
3106 unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
3107 // Get the result VT list.
3108 unsigned NumVTs = MatcherTable[MatcherIndex++];
3109 SmallVector<EVT, 4> VTs;
3110 for (unsigned i = 0; i != NumVTs; ++i) {
3111 MVT::SimpleValueType VT =
3112 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3113 if (VT == MVT::iPTR)
3114 VT = TLI->getPointerTy(CurDAG->getDataLayout()).SimpleTy;
3118 if (EmitNodeInfo & OPFL_Chain)
3119 VTs.push_back(MVT::Other);
3120 if (EmitNodeInfo & OPFL_GlueOutput)
3121 VTs.push_back(MVT::Glue);
3123 // This is hot code, so optimize the two most common cases of 1 and 2
3126 if (VTs.size() == 1)
3127 VTList = CurDAG->getVTList(VTs[0]);
3128 else if (VTs.size() == 2)
3129 VTList = CurDAG->getVTList(VTs[0], VTs[1]);
3131 VTList = CurDAG->getVTList(VTs);
3133 // Get the operand list.
3134 unsigned NumOps = MatcherTable[MatcherIndex++];
3135 SmallVector<SDValue, 8> Ops;
3136 for (unsigned i = 0; i != NumOps; ++i) {
3137 unsigned RecNo = MatcherTable[MatcherIndex++];
3139 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
3141 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
3142 Ops.push_back(RecordedNodes[RecNo].first);
3145 // If there are variadic operands to add, handle them now.
3146 if (EmitNodeInfo & OPFL_VariadicInfo) {
3147 // Determine the start index to copy from.
3148 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
3149 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
3150 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
3151 "Invalid variadic node");
3152 // Copy all of the variadic operands, not including a potential glue
3154 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
3156 SDValue V = NodeToMatch->getOperand(i);
3157 if (V.getValueType() == MVT::Glue) break;
3162 // If this has chain/glue inputs, add them.
3163 if (EmitNodeInfo & OPFL_Chain)
3164 Ops.push_back(InputChain);
3165 if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr)
3166 Ops.push_back(InputGlue);
3169 SDNode *Res = nullptr;
3170 if (Opcode != OPC_MorphNodeTo) {
3171 // If this is a normal EmitNode command, just create the new node and
3172 // add the results to the RecordedNodes list.
3173 Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
3176 // Add all the non-glue/non-chain results to the RecordedNodes list.
3177 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
3178 if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
3179 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
3183 } else if (NodeToMatch->getOpcode() != ISD::DELETED_NODE) {
3184 Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops, EmitNodeInfo);
3186 // NodeToMatch was eliminated by CSE when the target changed the DAG.
3187 // We will visit the equivalent node later.
3188 DEBUG(dbgs() << "Node was eliminated by CSE\n");
3192 // If the node had chain/glue results, update our notion of the current
3194 if (EmitNodeInfo & OPFL_GlueOutput) {
3195 InputGlue = SDValue(Res, VTs.size()-1);
3196 if (EmitNodeInfo & OPFL_Chain)
3197 InputChain = SDValue(Res, VTs.size()-2);
3198 } else if (EmitNodeInfo & OPFL_Chain)
3199 InputChain = SDValue(Res, VTs.size()-1);
3201 // If the OPFL_MemRefs glue is set on this node, slap all of the
3202 // accumulated memrefs onto it.
3204 // FIXME: This is vastly incorrect for patterns with multiple outputs
3205 // instructions that access memory and for ComplexPatterns that match
3207 if (EmitNodeInfo & OPFL_MemRefs) {
3208 // Only attach load or store memory operands if the generated
3209 // instruction may load or store.
3210 const MCInstrDesc &MCID = TII->get(TargetOpc);
3211 bool mayLoad = MCID.mayLoad();
3212 bool mayStore = MCID.mayStore();
3214 unsigned NumMemRefs = 0;
3215 for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
3216 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
3217 if ((*I)->isLoad()) {
3220 } else if ((*I)->isStore()) {
3228 MachineSDNode::mmo_iterator MemRefs =
3229 MF->allocateMemRefsArray(NumMemRefs);
3231 MachineSDNode::mmo_iterator MemRefsPos = MemRefs;
3232 for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
3233 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
3234 if ((*I)->isLoad()) {
3237 } else if ((*I)->isStore()) {
3245 cast<MachineSDNode>(Res)
3246 ->setMemRefs(MemRefs, MemRefs + NumMemRefs);
3250 << (Opcode == OPC_MorphNodeTo ? "Morphed" : "Created")
3251 << " node: "; Res->dump(CurDAG); dbgs() << "\n");
3253 // If this was a MorphNodeTo then we're completely done!
3254 if (Opcode == OPC_MorphNodeTo) {
3255 // Update chain and glue uses.
3256 UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
3257 InputGlue, GlueResultNodesMatched, true);
3264 case OPC_MarkGlueResults: {
3265 unsigned NumNodes = MatcherTable[MatcherIndex++];
3267 // Read and remember all the glue-result nodes.
3268 for (unsigned i = 0; i != NumNodes; ++i) {
3269 unsigned RecNo = MatcherTable[MatcherIndex++];
3271 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
3273 assert(RecNo < RecordedNodes.size() && "Invalid MarkGlueResults");
3274 GlueResultNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3279 case OPC_CompleteMatch: {
3280 // The match has been completed, and any new nodes (if any) have been
3281 // created. Patch up references to the matched dag to use the newly
3283 unsigned NumResults = MatcherTable[MatcherIndex++];
3285 for (unsigned i = 0; i != NumResults; ++i) {
3286 unsigned ResSlot = MatcherTable[MatcherIndex++];
3288 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
3290 assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch");
3291 SDValue Res = RecordedNodes[ResSlot].first;
3293 assert(i < NodeToMatch->getNumValues() &&
3294 NodeToMatch->getValueType(i) != MVT::Other &&
3295 NodeToMatch->getValueType(i) != MVT::Glue &&
3296 "Invalid number of results to complete!");
3297 assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
3298 NodeToMatch->getValueType(i) == MVT::iPTR ||
3299 Res.getValueType() == MVT::iPTR ||
3300 NodeToMatch->getValueType(i).getSizeInBits() ==
3301 Res.getValueType().getSizeInBits()) &&
3302 "invalid replacement");
3303 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
3306 // If the root node defines glue, add it to the glue nodes to update list.
3307 if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) == MVT::Glue)
3308 GlueResultNodesMatched.push_back(NodeToMatch);
3310 // Update chain and glue uses.
3311 UpdateChainsAndGlue(NodeToMatch, InputChain, ChainNodesMatched,
3312 InputGlue, GlueResultNodesMatched, false);
3314 assert(NodeToMatch->use_empty() &&
3315 "Didn't replace all uses of the node?");
3317 // FIXME: We just return here, which interacts correctly with SelectRoot
3318 // above. We should fix this to not return an SDNode* anymore.
3323 // If the code reached this point, then the match failed. See if there is
3324 // another child to try in the current 'Scope', otherwise pop it until we
3325 // find a case to check.
3326 DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex << "\n");
3327 ++NumDAGIselRetries;
3329 if (MatchScopes.empty()) {
3330 CannotYetSelect(NodeToMatch);
3334 // Restore the interpreter state back to the point where the scope was
3336 MatchScope &LastScope = MatchScopes.back();
3337 RecordedNodes.resize(LastScope.NumRecordedNodes);
3339 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
3340 N = NodeStack.back();
3342 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
3343 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
3344 MatcherIndex = LastScope.FailIndex;
3346 DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n");
3348 InputChain = LastScope.InputChain;
3349 InputGlue = LastScope.InputGlue;
3350 if (!LastScope.HasChainNodesMatched)
3351 ChainNodesMatched.clear();
3352 if (!LastScope.HasGlueResultNodesMatched)
3353 GlueResultNodesMatched.clear();
3355 // Check to see what the offset is at the new MatcherIndex. If it is zero
3356 // we have reached the end of this scope, otherwise we have another child
3357 // in the current scope to try.
3358 unsigned NumToSkip = MatcherTable[MatcherIndex++];
3359 if (NumToSkip & 128)
3360 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
3362 // If we have another child in this scope to match, update FailIndex and
3364 if (NumToSkip != 0) {
3365 LastScope.FailIndex = MatcherIndex+NumToSkip;
3369 // End of this scope, pop it and try the next child in the containing
3371 MatchScopes.pop_back();
3378 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
3380 raw_string_ostream Msg(msg);
3381 Msg << "Cannot select: ";
3383 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
3384 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
3385 N->getOpcode() != ISD::INTRINSIC_VOID) {
3386 N->printrFull(Msg, CurDAG);
3387 Msg << "\nIn function: " << MF->getName();
3389 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
3391 cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
3392 if (iid < Intrinsic::num_intrinsics)
3393 Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid);
3394 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
3395 Msg << "target intrinsic %" << TII->getName(iid);
3397 Msg << "unknown intrinsic #" << iid;
3399 report_fatal_error(Msg.str());
3402 char SelectionDAGISel::ID = 0;