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 "ScheduleDAGSDNodes.h"
15 #include "SelectionDAGBuilder.h"
16 #include "llvm/ADT/APInt.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/PostOrderIterator.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SmallSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/BranchProbabilityInfo.h"
28 #include "llvm/Analysis/CFG.h"
29 #include "llvm/Analysis/OptimizationDiagnosticInfo.h"
30 #include "llvm/Analysis/TargetLibraryInfo.h"
31 #include "llvm/CodeGen/FastISel.h"
32 #include "llvm/CodeGen/FunctionLoweringInfo.h"
33 #include "llvm/CodeGen/GCMetadata.h"
34 #include "llvm/CodeGen/ISDOpcodes.h"
35 #include "llvm/CodeGen/MachineBasicBlock.h"
36 #include "llvm/CodeGen/MachineFrameInfo.h"
37 #include "llvm/CodeGen/MachineFunction.h"
38 #include "llvm/CodeGen/MachineFunctionPass.h"
39 #include "llvm/CodeGen/MachineInstr.h"
40 #include "llvm/CodeGen/MachineInstrBuilder.h"
41 #include "llvm/CodeGen/MachineMemOperand.h"
42 #include "llvm/CodeGen/MachineOperand.h"
43 #include "llvm/CodeGen/MachinePassRegistry.h"
44 #include "llvm/CodeGen/MachineRegisterInfo.h"
45 #include "llvm/CodeGen/MachineValueType.h"
46 #include "llvm/CodeGen/SchedulerRegistry.h"
47 #include "llvm/CodeGen/SelectionDAG.h"
48 #include "llvm/CodeGen/SelectionDAGISel.h"
49 #include "llvm/CodeGen/SelectionDAGNodes.h"
50 #include "llvm/CodeGen/StackProtector.h"
51 #include "llvm/CodeGen/ValueTypes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constants.h"
54 #include "llvm/IR/DataLayout.h"
55 #include "llvm/IR/DebugInfoMetadata.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DiagnosticInfo.h"
58 #include "llvm/IR/Dominators.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/InlineAsm.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/Metadata.h"
67 #include "llvm/IR/Type.h"
68 #include "llvm/IR/User.h"
69 #include "llvm/IR/Value.h"
70 #include "llvm/MC/MCInstrDesc.h"
71 #include "llvm/MC/MCRegisterInfo.h"
72 #include "llvm/Pass.h"
73 #include "llvm/Support/BranchProbability.h"
74 #include "llvm/Support/Casting.h"
75 #include "llvm/Support/CodeGen.h"
76 #include "llvm/Support/CommandLine.h"
77 #include "llvm/Support/Compiler.h"
78 #include "llvm/Support/Debug.h"
79 #include "llvm/Support/ErrorHandling.h"
80 #include "llvm/Support/KnownBits.h"
81 #include "llvm/Support/Timer.h"
82 #include "llvm/Support/raw_ostream.h"
83 #include "llvm/Target/TargetInstrInfo.h"
84 #include "llvm/Target/TargetIntrinsicInfo.h"
85 #include "llvm/Target/TargetLowering.h"
86 #include "llvm/Target/TargetMachine.h"
87 #include "llvm/Target/TargetOptions.h"
88 #include "llvm/Target/TargetRegisterInfo.h"
89 #include "llvm/Target/TargetSubtargetInfo.h"
90 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
101 using namespace llvm;
103 #define DEBUG_TYPE "isel"
105 STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
106 STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
107 STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
108 STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
109 STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
110 STATISTIC(NumEntryBlocks, "Number of entry blocks encountered");
111 STATISTIC(NumFastIselFailLowerArguments,
112 "Number of entry blocks where fast isel failed to lower arguments");
114 static cl::opt<int> EnableFastISelAbort(
115 "fast-isel-abort", cl::Hidden,
116 cl::desc("Enable abort calls when \"fast\" instruction selection "
117 "fails to lower an instruction: 0 disable the abort, 1 will "
118 "abort but for args, calls and terminators, 2 will also "
119 "abort for argument lowering, and 3 will never fallback "
120 "to SelectionDAG."));
122 static cl::opt<bool> EnableFastISelFallbackReport(
123 "fast-isel-report-on-fallback", cl::Hidden,
124 cl::desc("Emit a diagnostic when \"fast\" instruction selection "
125 "falls back to SelectionDAG."));
129 cl::desc("use Machine Branch Probability Info"),
130 cl::init(true), cl::Hidden);
133 static cl::opt<std::string>
134 FilterDAGBasicBlockName("filter-view-dags", cl::Hidden,
135 cl::desc("Only display the basic block whose name "
136 "matches this for all view-*-dags options"));
138 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
139 cl::desc("Pop up a window to show dags before the first "
140 "dag combine pass"));
142 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
143 cl::desc("Pop up a window to show dags before legalize types"));
145 ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
146 cl::desc("Pop up a window to show dags before legalize"));
148 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
149 cl::desc("Pop up a window to show dags before the second "
150 "dag combine pass"));
152 ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
153 cl::desc("Pop up a window to show dags before the post legalize types"
154 " dag combine pass"));
156 ViewISelDAGs("view-isel-dags", cl::Hidden,
157 cl::desc("Pop up a window to show isel dags as they are selected"));
159 ViewSchedDAGs("view-sched-dags", cl::Hidden,
160 cl::desc("Pop up a window to show sched dags as they are processed"));
162 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
163 cl::desc("Pop up a window to show SUnit dags after they are processed"));
165 static const bool ViewDAGCombine1 = false,
166 ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
167 ViewDAGCombine2 = false,
168 ViewDAGCombineLT = false,
169 ViewISelDAGs = false, ViewSchedDAGs = false,
170 ViewSUnitDAGs = false;
173 //===---------------------------------------------------------------------===//
175 /// RegisterScheduler class - Track the registration of instruction schedulers.
177 //===---------------------------------------------------------------------===//
178 MachinePassRegistry RegisterScheduler::Registry;
180 //===---------------------------------------------------------------------===//
182 /// ISHeuristic command line option for instruction schedulers.
184 //===---------------------------------------------------------------------===//
185 static cl::opt<RegisterScheduler::FunctionPassCtor, false,
186 RegisterPassParser<RegisterScheduler>>
187 ISHeuristic("pre-RA-sched",
188 cl::init(&createDefaultScheduler), cl::Hidden,
189 cl::desc("Instruction schedulers available (before register"
192 static RegisterScheduler
193 defaultListDAGScheduler("default", "Best scheduler for the target",
194 createDefaultScheduler);
198 //===--------------------------------------------------------------------===//
199 /// \brief This class is used by SelectionDAGISel to temporarily override
200 /// the optimization level on a per-function basis.
201 class OptLevelChanger {
202 SelectionDAGISel &IS;
203 CodeGenOpt::Level SavedOptLevel;
207 OptLevelChanger(SelectionDAGISel &ISel,
208 CodeGenOpt::Level NewOptLevel) : IS(ISel) {
209 SavedOptLevel = IS.OptLevel;
210 if (NewOptLevel == SavedOptLevel)
212 IS.OptLevel = NewOptLevel;
213 IS.TM.setOptLevel(NewOptLevel);
214 DEBUG(dbgs() << "\nChanging optimization level for Function "
215 << IS.MF->getFunction()->getName() << "\n");
216 DEBUG(dbgs() << "\tBefore: -O" << SavedOptLevel
217 << " ; After: -O" << NewOptLevel << "\n");
218 SavedFastISel = IS.TM.Options.EnableFastISel;
219 if (NewOptLevel == CodeGenOpt::None) {
220 IS.TM.setFastISel(IS.TM.getO0WantsFastISel());
221 DEBUG(dbgs() << "\tFastISel is "
222 << (IS.TM.Options.EnableFastISel ? "enabled" : "disabled")
228 if (IS.OptLevel == SavedOptLevel)
230 DEBUG(dbgs() << "\nRestoring optimization level for Function "
231 << IS.MF->getFunction()->getName() << "\n");
232 DEBUG(dbgs() << "\tBefore: -O" << IS.OptLevel
233 << " ; After: -O" << SavedOptLevel << "\n");
234 IS.OptLevel = SavedOptLevel;
235 IS.TM.setOptLevel(SavedOptLevel);
236 IS.TM.setFastISel(SavedFastISel);
240 //===--------------------------------------------------------------------===//
241 /// createDefaultScheduler - This creates an instruction scheduler appropriate
243 ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
244 CodeGenOpt::Level OptLevel) {
245 const TargetLowering *TLI = IS->TLI;
246 const TargetSubtargetInfo &ST = IS->MF->getSubtarget();
248 // Try first to see if the Target has its own way of selecting a scheduler
249 if (auto *SchedulerCtor = ST.getDAGScheduler(OptLevel)) {
250 return SchedulerCtor(IS, OptLevel);
253 if (OptLevel == CodeGenOpt::None ||
254 (ST.enableMachineScheduler() && ST.enableMachineSchedDefaultSched()) ||
255 TLI->getSchedulingPreference() == Sched::Source)
256 return createSourceListDAGScheduler(IS, OptLevel);
257 if (TLI->getSchedulingPreference() == Sched::RegPressure)
258 return createBURRListDAGScheduler(IS, OptLevel);
259 if (TLI->getSchedulingPreference() == Sched::Hybrid)
260 return createHybridListDAGScheduler(IS, OptLevel);
261 if (TLI->getSchedulingPreference() == Sched::VLIW)
262 return createVLIWDAGScheduler(IS, OptLevel);
263 assert(TLI->getSchedulingPreference() == Sched::ILP &&
264 "Unknown sched type!");
265 return createILPListDAGScheduler(IS, OptLevel);
268 } // end namespace llvm
270 // EmitInstrWithCustomInserter - This method should be implemented by targets
271 // that mark instructions with the 'usesCustomInserter' flag. These
272 // instructions are special in various ways, which require special support to
273 // insert. The specified MachineInstr is created but not inserted into any
274 // basic blocks, and this method is called to expand it into a sequence of
275 // instructions, potentially also creating new basic blocks and control flow.
276 // When new basic blocks are inserted and the edges from MBB to its successors
277 // are modified, the method should insert pairs of <OldSucc, NewSucc> into the
280 TargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
281 MachineBasicBlock *MBB) const {
283 dbgs() << "If a target marks an instruction with "
284 "'usesCustomInserter', it must implement "
285 "TargetLowering::EmitInstrWithCustomInserter!";
287 llvm_unreachable(nullptr);
290 void TargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
291 SDNode *Node) const {
292 assert(!MI.hasPostISelHook() &&
293 "If a target marks an instruction with 'hasPostISelHook', "
294 "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
297 //===----------------------------------------------------------------------===//
298 // SelectionDAGISel code
299 //===----------------------------------------------------------------------===//
301 SelectionDAGISel::SelectionDAGISel(TargetMachine &tm,
302 CodeGenOpt::Level OL) :
303 MachineFunctionPass(ID), TM(tm),
304 FuncInfo(new FunctionLoweringInfo()),
305 CurDAG(new SelectionDAG(tm, OL)),
306 SDB(new SelectionDAGBuilder(*CurDAG, *FuncInfo, OL)),
310 initializeGCModuleInfoPass(*PassRegistry::getPassRegistry());
311 initializeBranchProbabilityInfoWrapperPassPass(
312 *PassRegistry::getPassRegistry());
313 initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
314 initializeTargetLibraryInfoWrapperPassPass(
315 *PassRegistry::getPassRegistry());
318 SelectionDAGISel::~SelectionDAGISel() {
324 void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
325 if (OptLevel != CodeGenOpt::None)
326 AU.addRequired<AAResultsWrapperPass>();
327 AU.addRequired<GCModuleInfo>();
328 AU.addRequired<StackProtector>();
329 AU.addPreserved<StackProtector>();
330 AU.addPreserved<GCModuleInfo>();
331 AU.addRequired<TargetLibraryInfoWrapperPass>();
332 if (UseMBPI && OptLevel != CodeGenOpt::None)
333 AU.addRequired<BranchProbabilityInfoWrapperPass>();
334 MachineFunctionPass::getAnalysisUsage(AU);
337 /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that
338 /// may trap on it. In this case we have to split the edge so that the path
339 /// through the predecessor block that doesn't go to the phi block doesn't
340 /// execute the possibly trapping instruction. If available, we pass domtree
341 /// and loop info to be updated when we split critical edges. This is because
342 /// SelectionDAGISel preserves these analyses.
343 /// This is required for correctness, so it must be done at -O0.
345 static void SplitCriticalSideEffectEdges(Function &Fn, DominatorTree *DT,
347 // Loop for blocks with phi nodes.
348 for (BasicBlock &BB : Fn) {
349 PHINode *PN = dyn_cast<PHINode>(BB.begin());
353 // For each block with a PHI node, check to see if any of the input values
354 // are potentially trapping constant expressions. Constant expressions are
355 // the only potentially trapping value that can occur as the argument to a
357 for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I)); ++I)
358 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
359 ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i));
360 if (!CE || !CE->canTrap()) continue;
362 // The only case we have to worry about is when the edge is critical.
363 // Since this block has a PHI Node, we assume it has multiple input
364 // edges: check to see if the pred has multiple successors.
365 BasicBlock *Pred = PN->getIncomingBlock(i);
366 if (Pred->getTerminator()->getNumSuccessors() == 1)
369 // Okay, we have to split this edge.
371 Pred->getTerminator(), GetSuccessorNumber(Pred, &BB),
372 CriticalEdgeSplittingOptions(DT, LI).setMergeIdenticalEdges());
378 bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
379 // If we already selected that function, we do not need to run SDISel.
380 if (mf.getProperties().hasProperty(
381 MachineFunctionProperties::Property::Selected))
383 // Do some sanity-checking on the command-line options.
384 assert((!EnableFastISelAbort || TM.Options.EnableFastISel) &&
385 "-fast-isel-abort > 0 requires -fast-isel");
387 const Function &Fn = *mf.getFunction();
390 // Reset the target options before resetting the optimization
392 // FIXME: This is a horrible hack and should be processed via
393 // codegen looking at the optimization level explicitly when
394 // it wants to look at it.
395 TM.resetTargetOptions(Fn);
396 // Reset OptLevel to None for optnone functions.
397 CodeGenOpt::Level NewOptLevel = OptLevel;
398 if (OptLevel != CodeGenOpt::None && skipFunction(Fn))
399 NewOptLevel = CodeGenOpt::None;
400 OptLevelChanger OLC(*this, NewOptLevel);
402 TII = MF->getSubtarget().getInstrInfo();
403 TLI = MF->getSubtarget().getTargetLowering();
404 RegInfo = &MF->getRegInfo();
405 LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
406 GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : nullptr;
407 ORE = make_unique<OptimizationRemarkEmitter>(&Fn);
408 auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
409 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
410 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
411 LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
413 DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
415 SplitCriticalSideEffectEdges(const_cast<Function &>(Fn), DT, LI);
417 CurDAG->init(*MF, *ORE);
418 FuncInfo->set(Fn, *MF, CurDAG);
420 // Now get the optional analyzes if we want to.
421 // This is based on the possibly changed OptLevel (after optnone is taken
422 // into account). That's unfortunate but OK because it just means we won't
423 // ask for passes that have been required anyway.
425 if (UseMBPI && OptLevel != CodeGenOpt::None)
426 FuncInfo->BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
428 FuncInfo->BPI = nullptr;
430 if (OptLevel != CodeGenOpt::None)
431 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
435 SDB->init(GFI, AA, LibInfo);
437 MF->setHasInlineAsm(false);
439 FuncInfo->SplitCSR = false;
441 // We split CSR if the target supports it for the given function
442 // and the function has only return exits.
443 if (OptLevel != CodeGenOpt::None && TLI->supportSplitCSR(MF)) {
444 FuncInfo->SplitCSR = true;
446 // Collect all the return blocks.
447 for (const BasicBlock &BB : Fn) {
448 if (!succ_empty(&BB))
451 const TerminatorInst *Term = BB.getTerminator();
452 if (isa<UnreachableInst>(Term) || isa<ReturnInst>(Term))
455 // Bail out if the exit block is not Return nor Unreachable.
456 FuncInfo->SplitCSR = false;
461 MachineBasicBlock *EntryMBB = &MF->front();
462 if (FuncInfo->SplitCSR)
463 // This performs initialization so lowering for SplitCSR will be correct.
464 TLI->initializeSplitCSR(EntryMBB);
466 SelectAllBasicBlocks(Fn);
467 if (FastISelFailed && EnableFastISelFallbackReport) {
468 DiagnosticInfoISelFallback DiagFallback(Fn);
469 Fn.getContext().diagnose(DiagFallback);
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 const TargetRegisterInfo &TRI = *MF->getSubtarget().getRegisterInfo();
476 RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
478 // Insert copies in the entry block and the return blocks.
479 if (FuncInfo->SplitCSR) {
480 SmallVector<MachineBasicBlock*, 4> Returns;
481 // Collect all the return blocks.
482 for (MachineBasicBlock &MBB : mf) {
483 if (!MBB.succ_empty())
486 MachineBasicBlock::iterator Term = MBB.getFirstTerminator();
487 if (Term != MBB.end() && Term->isReturn()) {
488 Returns.push_back(&MBB);
492 TLI->insertCopiesSplitCSR(EntryMBB, Returns);
495 DenseMap<unsigned, unsigned> LiveInMap;
496 if (!FuncInfo->ArgDbgValues.empty())
497 for (MachineRegisterInfo::livein_iterator LI = RegInfo->livein_begin(),
498 E = RegInfo->livein_end(); LI != E; ++LI)
500 LiveInMap.insert(std::make_pair(LI->first, LI->second));
502 // Insert DBG_VALUE instructions for function arguments to the entry block.
503 for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
504 MachineInstr *MI = FuncInfo->ArgDbgValues[e-i-1];
505 bool hasFI = MI->getOperand(0).isFI();
507 hasFI ? TRI.getFrameRegister(*MF) : MI->getOperand(0).getReg();
508 if (TargetRegisterInfo::isPhysicalRegister(Reg))
509 EntryMBB->insert(EntryMBB->begin(), MI);
511 MachineInstr *Def = RegInfo->getVRegDef(Reg);
513 MachineBasicBlock::iterator InsertPos = Def;
514 // FIXME: VR def may not be in entry block.
515 Def->getParent()->insert(std::next(InsertPos), MI);
517 DEBUG(dbgs() << "Dropping debug info for dead vreg"
518 << TargetRegisterInfo::virtReg2Index(Reg) << "\n");
521 // If Reg is live-in then update debug info to track its copy in a vreg.
522 DenseMap<unsigned, unsigned>::iterator LDI = LiveInMap.find(Reg);
523 if (LDI != LiveInMap.end()) {
524 assert(!hasFI && "There's no handling of frame pointer updating here yet "
526 MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
527 MachineBasicBlock::iterator InsertPos = Def;
528 const MDNode *Variable = MI->getDebugVariable();
529 const MDNode *Expr = MI->getDebugExpression();
530 DebugLoc DL = MI->getDebugLoc();
531 bool IsIndirect = MI->isIndirectDebugValue();
532 unsigned Offset = IsIndirect ? MI->getOperand(1).getImm() : 0;
533 assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
534 "Expected inlined-at fields to agree");
535 // Def is never a terminator here, so it is ok to increment InsertPos.
536 BuildMI(*EntryMBB, ++InsertPos, DL, TII->get(TargetOpcode::DBG_VALUE),
537 IsIndirect, LDI->second, Offset, Variable, Expr);
539 // If this vreg is directly copied into an exported register then
540 // that COPY instructions also need DBG_VALUE, if it is the only
541 // user of LDI->second.
542 MachineInstr *CopyUseMI = nullptr;
543 for (MachineRegisterInfo::use_instr_iterator
544 UI = RegInfo->use_instr_begin(LDI->second),
545 E = RegInfo->use_instr_end(); UI != E; ) {
546 MachineInstr *UseMI = &*(UI++);
547 if (UseMI->isDebugValue()) continue;
548 if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
549 CopyUseMI = UseMI; continue;
551 // Otherwise this is another use or second copy use.
552 CopyUseMI = nullptr; break;
555 // Use MI's debug location, which describes where Variable was
556 // declared, rather than whatever is attached to CopyUseMI.
557 MachineInstr *NewMI =
558 BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
559 CopyUseMI->getOperand(0).getReg(), Offset, Variable, Expr);
560 MachineBasicBlock::iterator Pos = CopyUseMI;
561 EntryMBB->insertAfter(Pos, NewMI);
566 // Determine if there are any calls in this machine function.
567 MachineFrameInfo &MFI = MF->getFrameInfo();
568 for (const auto &MBB : *MF) {
569 if (MFI.hasCalls() && MF->hasInlineAsm())
572 for (const auto &MI : MBB) {
573 const MCInstrDesc &MCID = TII->get(MI.getOpcode());
574 if ((MCID.isCall() && !MCID.isReturn()) ||
575 MI.isStackAligningInlineAsm()) {
576 MFI.setHasCalls(true);
578 if (MI.isInlineAsm()) {
579 MF->setHasInlineAsm(true);
584 // Determine if there is a call to setjmp in the machine function.
585 MF->setExposesReturnsTwice(Fn.callsFunctionThatReturnsTwice());
587 // Replace forward-declared registers with the registers containing
588 // the desired value.
589 MachineRegisterInfo &MRI = MF->getRegInfo();
590 for (DenseMap<unsigned, unsigned>::iterator
591 I = FuncInfo->RegFixups.begin(), E = FuncInfo->RegFixups.end();
593 unsigned From = I->first;
594 unsigned To = I->second;
595 // If To is also scheduled to be replaced, find what its ultimate
598 DenseMap<unsigned, unsigned>::iterator J = FuncInfo->RegFixups.find(To);
602 // Make sure the new register has a sufficiently constrained register class.
603 if (TargetRegisterInfo::isVirtualRegister(From) &&
604 TargetRegisterInfo::isVirtualRegister(To))
605 MRI.constrainRegClass(To, MRI.getRegClass(From));
609 // Replacing one register with another won't touch the kill flags.
610 // We need to conservatively clear the kill flags as a kill on the old
611 // register might dominate existing uses of the new register.
612 if (!MRI.use_empty(To))
613 MRI.clearKillFlags(From);
614 MRI.replaceRegWith(From, To);
617 TLI->finalizeLowering(*MF);
619 // Release function-specific state. SDB and CurDAG are already cleared
623 DEBUG(dbgs() << "*** MachineFunction at end of ISel ***\n");
624 DEBUG(MF->print(dbgs()));
629 static void reportFastISelFailure(MachineFunction &MF,
630 OptimizationRemarkEmitter &ORE,
631 OptimizationRemarkMissed &R,
633 // Print the function name explicitly if we don't have a debug location (which
634 // makes the diagnostic less useful) or if we're going to emit a raw error.
635 if (!R.getLocation().isValid() || ShouldAbort)
636 R << (" (in function: " + MF.getName() + ")").str();
639 report_fatal_error(R.getMsg());
644 void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
645 BasicBlock::const_iterator End,
647 // Lower the instructions. If a call is emitted as a tail call, cease emitting
648 // nodes for this block.
649 for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I) {
650 if (!ElidedArgCopyInstrs.count(&*I))
654 // Make sure the root of the DAG is up-to-date.
655 CurDAG->setRoot(SDB->getControlRoot());
656 HadTailCall = SDB->HasTailCall;
659 // Final step, emit the lowered DAG as machine code.
663 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
664 SmallPtrSet<SDNode*, 16> VisitedNodes;
665 SmallVector<SDNode*, 128> Worklist;
667 Worklist.push_back(CurDAG->getRoot().getNode());
672 SDNode *N = Worklist.pop_back_val();
674 // If we've already seen this node, ignore it.
675 if (!VisitedNodes.insert(N).second)
678 // Otherwise, add all chain operands to the worklist.
679 for (const SDValue &Op : N->op_values())
680 if (Op.getValueType() == MVT::Other)
681 Worklist.push_back(Op.getNode());
683 // If this is a CopyToReg with a vreg dest, process it.
684 if (N->getOpcode() != ISD::CopyToReg)
687 unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
688 if (!TargetRegisterInfo::isVirtualRegister(DestReg))
691 // Ignore non-scalar or non-integer values.
692 SDValue Src = N->getOperand(2);
693 EVT SrcVT = Src.getValueType();
694 if (!SrcVT.isInteger() || SrcVT.isVector())
697 unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
698 CurDAG->computeKnownBits(Src, Known);
699 FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, Known);
700 } while (!Worklist.empty());
703 void SelectionDAGISel::CodeGenAndEmitDAG() {
704 StringRef GroupName = "sdag";
705 StringRef GroupDescription = "Instruction Selection and Scheduling";
706 std::string BlockName;
707 int BlockNumber = -1;
709 bool MatchFilterBB = false; (void)MatchFilterBB;
711 // Pre-type legalization allow creation of any node types.
712 CurDAG->NewNodesMustHaveLegalTypes = false;
715 MatchFilterBB = (FilterDAGBasicBlockName.empty() ||
716 FilterDAGBasicBlockName ==
717 FuncInfo->MBB->getBasicBlock()->getName().str());
720 if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
721 ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
725 BlockNumber = FuncInfo->MBB->getNumber();
727 (MF->getName() + ":" + FuncInfo->MBB->getBasicBlock()->getName()).str();
729 DEBUG(dbgs() << "Initial selection DAG: BB#" << BlockNumber
730 << " '" << BlockName << "'\n"; CurDAG->dump());
732 if (ViewDAGCombine1 && MatchFilterBB)
733 CurDAG->viewGraph("dag-combine1 input for " + BlockName);
735 // Run the DAG combiner in pre-legalize mode.
737 NamedRegionTimer T("combine1", "DAG Combining 1", GroupName,
738 GroupDescription, TimePassesIsEnabled);
739 CurDAG->Combine(BeforeLegalizeTypes, AA, OptLevel);
742 DEBUG(dbgs() << "Optimized lowered selection DAG: BB#" << BlockNumber
743 << " '" << BlockName << "'\n"; CurDAG->dump());
745 // Second step, hack on the DAG until it only uses operations and types that
746 // the target supports.
747 if (ViewLegalizeTypesDAGs && MatchFilterBB)
748 CurDAG->viewGraph("legalize-types input for " + BlockName);
752 NamedRegionTimer T("legalize_types", "Type Legalization", GroupName,
753 GroupDescription, TimePassesIsEnabled);
754 Changed = CurDAG->LegalizeTypes();
757 DEBUG(dbgs() << "Type-legalized selection DAG: BB#" << BlockNumber
758 << " '" << BlockName << "'\n"; CurDAG->dump());
760 // Only allow creation of legal node types.
761 CurDAG->NewNodesMustHaveLegalTypes = true;
764 if (ViewDAGCombineLT && MatchFilterBB)
765 CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
767 // Run the DAG combiner in post-type-legalize mode.
769 NamedRegionTimer T("combine_lt", "DAG Combining after legalize types",
770 GroupName, GroupDescription, TimePassesIsEnabled);
771 CurDAG->Combine(AfterLegalizeTypes, AA, OptLevel);
774 DEBUG(dbgs() << "Optimized type-legalized selection DAG: BB#" << BlockNumber
775 << " '" << BlockName << "'\n"; CurDAG->dump());
779 NamedRegionTimer T("legalize_vec", "Vector Legalization", GroupName,
780 GroupDescription, TimePassesIsEnabled);
781 Changed = CurDAG->LegalizeVectors();
785 DEBUG(dbgs() << "Vector-legalized selection DAG: BB#" << BlockNumber
786 << " '" << BlockName << "'\n"; CurDAG->dump());
789 NamedRegionTimer T("legalize_types2", "Type Legalization 2", GroupName,
790 GroupDescription, TimePassesIsEnabled);
791 CurDAG->LegalizeTypes();
794 DEBUG(dbgs() << "Vector/type-legalized selection DAG: BB#" << BlockNumber
795 << " '" << BlockName << "'\n"; CurDAG->dump());
797 if (ViewDAGCombineLT && MatchFilterBB)
798 CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
800 // Run the DAG combiner in post-type-legalize mode.
802 NamedRegionTimer T("combine_lv", "DAG Combining after legalize vectors",
803 GroupName, GroupDescription, TimePassesIsEnabled);
804 CurDAG->Combine(AfterLegalizeVectorOps, AA, OptLevel);
807 DEBUG(dbgs() << "Optimized vector-legalized selection DAG: BB#"
808 << BlockNumber << " '" << BlockName << "'\n"; CurDAG->dump());
811 if (ViewLegalizeDAGs && MatchFilterBB)
812 CurDAG->viewGraph("legalize input for " + BlockName);
815 NamedRegionTimer T("legalize", "DAG Legalization", GroupName,
816 GroupDescription, TimePassesIsEnabled);
820 DEBUG(dbgs() << "Legalized selection DAG: BB#" << BlockNumber
821 << " '" << BlockName << "'\n"; CurDAG->dump());
823 if (ViewDAGCombine2 && MatchFilterBB)
824 CurDAG->viewGraph("dag-combine2 input for " + BlockName);
826 // Run the DAG combiner in post-legalize mode.
828 NamedRegionTimer T("combine2", "DAG Combining 2", GroupName,
829 GroupDescription, TimePassesIsEnabled);
830 CurDAG->Combine(AfterLegalizeDAG, AA, OptLevel);
833 DEBUG(dbgs() << "Optimized legalized selection DAG: BB#" << BlockNumber
834 << " '" << BlockName << "'\n"; CurDAG->dump());
836 if (OptLevel != CodeGenOpt::None)
837 ComputeLiveOutVRegInfo();
839 if (ViewISelDAGs && MatchFilterBB)
840 CurDAG->viewGraph("isel input for " + BlockName);
842 // Third, instruction select all of the operations to machine code, adding the
843 // code to the MachineBasicBlock.
845 NamedRegionTimer T("isel", "Instruction Selection", GroupName,
846 GroupDescription, TimePassesIsEnabled);
847 DoInstructionSelection();
850 DEBUG(dbgs() << "Selected selection DAG: BB#" << BlockNumber
851 << " '" << BlockName << "'\n"; CurDAG->dump());
853 if (ViewSchedDAGs && MatchFilterBB)
854 CurDAG->viewGraph("scheduler input for " + BlockName);
856 // Schedule machine code.
857 ScheduleDAGSDNodes *Scheduler = CreateScheduler();
859 NamedRegionTimer T("sched", "Instruction Scheduling", GroupName,
860 GroupDescription, TimePassesIsEnabled);
861 Scheduler->Run(CurDAG, FuncInfo->MBB);
864 if (ViewSUnitDAGs && MatchFilterBB)
865 Scheduler->viewGraph();
867 // Emit machine code to BB. This can change 'BB' to the last block being
869 MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
871 NamedRegionTimer T("emit", "Instruction Creation", GroupName,
872 GroupDescription, TimePassesIsEnabled);
874 // FuncInfo->InsertPt is passed by reference and set to the end of the
875 // scheduled instructions.
876 LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
879 // If the block was split, make sure we update any references that are used to
880 // update PHI nodes later on.
881 if (FirstMBB != LastMBB)
882 SDB->UpdateSplitBlock(FirstMBB, LastMBB);
884 // Free the scheduler state.
886 NamedRegionTimer T("cleanup", "Instruction Scheduling Cleanup", GroupName,
887 GroupDescription, TimePassesIsEnabled);
891 // Free the SelectionDAG state, now that we're finished with it.
897 /// ISelUpdater - helper class to handle updates of the instruction selection
899 class ISelUpdater : public SelectionDAG::DAGUpdateListener {
900 SelectionDAG::allnodes_iterator &ISelPosition;
903 ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
904 : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
906 /// NodeDeleted - Handle nodes deleted from the graph. If the node being
907 /// deleted is the current ISelPosition node, update ISelPosition.
909 void NodeDeleted(SDNode *N, SDNode *E) override {
910 if (ISelPosition == SelectionDAG::allnodes_iterator(N))
915 } // end anonymous namespace
917 void SelectionDAGISel::DoInstructionSelection() {
918 DEBUG(dbgs() << "===== Instruction selection begins: BB#"
919 << FuncInfo->MBB->getNumber()
920 << " '" << FuncInfo->MBB->getName() << "'\n");
924 // Select target instructions for the DAG.
926 // Number all nodes with a topological order and set DAGSize.
927 DAGSize = CurDAG->AssignTopologicalOrder();
929 // Create a dummy node (which is not added to allnodes), that adds
930 // a reference to the root node, preventing it from being deleted,
931 // and tracking any changes of the root.
932 HandleSDNode Dummy(CurDAG->getRoot());
933 SelectionDAG::allnodes_iterator ISelPosition (CurDAG->getRoot().getNode());
936 // Make sure that ISelPosition gets properly updated when nodes are deleted
937 // in calls made from this function.
938 ISelUpdater ISU(*CurDAG, ISelPosition);
940 // The AllNodes list is now topological-sorted. Visit the
941 // nodes by starting at the end of the list (the root of the
942 // graph) and preceding back toward the beginning (the entry
944 while (ISelPosition != CurDAG->allnodes_begin()) {
945 SDNode *Node = &*--ISelPosition;
946 // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
947 // but there are currently some corner cases that it misses. Also, this
948 // makes it theoretically possible to disable the DAGCombiner.
949 if (Node->use_empty())
952 // When we are using non-default rounding modes or FP exception behavior
953 // FP operations are represented by StrictFP pseudo-operations. They
954 // need to be simplified here so that the target-specific instruction
955 // selectors know how to handle them.
957 // If the current node is a strict FP pseudo-op, the isStrictFPOp()
958 // function will provide the corresponding normal FP opcode to which the
959 // node should be mutated.
961 // FIXME: The backends need a way to handle FP constraints.
962 if (Node->isStrictFPOpcode())
963 Node = CurDAG->mutateStrictFPToFP(Node);
968 CurDAG->setRoot(Dummy.getValue());
971 DEBUG(dbgs() << "===== Instruction selection ends:\n");
973 PostprocessISelDAG();
976 static bool hasExceptionPointerOrCodeUser(const CatchPadInst *CPI) {
977 for (const User *U : CPI->users()) {
978 if (const IntrinsicInst *EHPtrCall = dyn_cast<IntrinsicInst>(U)) {
979 Intrinsic::ID IID = EHPtrCall->getIntrinsicID();
980 if (IID == Intrinsic::eh_exceptionpointer ||
981 IID == Intrinsic::eh_exceptioncode)
988 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
989 /// do other setup for EH landing-pad blocks.
990 bool SelectionDAGISel::PrepareEHLandingPad() {
991 MachineBasicBlock *MBB = FuncInfo->MBB;
992 const Constant *PersonalityFn = FuncInfo->Fn->getPersonalityFn();
993 const BasicBlock *LLVMBB = MBB->getBasicBlock();
994 const TargetRegisterClass *PtrRC =
995 TLI->getRegClassFor(TLI->getPointerTy(CurDAG->getDataLayout()));
997 // Catchpads have one live-in register, which typically holds the exception
999 if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) {
1000 if (hasExceptionPointerOrCodeUser(CPI)) {
1001 // Get or create the virtual register to hold the pointer or code. Mark
1002 // the live in physreg and copy into the vreg.
1003 MCPhysReg EHPhysReg = TLI->getExceptionPointerRegister(PersonalityFn);
1004 assert(EHPhysReg && "target lacks exception pointer register");
1005 MBB->addLiveIn(EHPhysReg);
1006 unsigned VReg = FuncInfo->getCatchPadExceptionPointerVReg(CPI, PtrRC);
1007 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(),
1008 TII->get(TargetOpcode::COPY), VReg)
1009 .addReg(EHPhysReg, RegState::Kill);
1014 if (!LLVMBB->isLandingPad())
1017 // Add a label to mark the beginning of the landing pad. Deletion of the
1018 // landing pad can thus be detected via the MachineModuleInfo.
1019 MCSymbol *Label = MF->addLandingPad(MBB);
1021 // Assign the call site to the landing pad's begin label.
1022 MF->setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
1024 const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL);
1025 BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
1028 // Mark exception register as live in.
1029 if (unsigned Reg = TLI->getExceptionPointerRegister(PersonalityFn))
1030 FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
1032 // Mark exception selector register as live in.
1033 if (unsigned Reg = TLI->getExceptionSelectorRegister(PersonalityFn))
1034 FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
1039 /// isFoldedOrDeadInstruction - Return true if the specified instruction is
1040 /// side-effect free and is either dead or folded into a generated instruction.
1041 /// Return false if it needs to be emitted.
1042 static bool isFoldedOrDeadInstruction(const Instruction *I,
1043 FunctionLoweringInfo *FuncInfo) {
1044 return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
1045 !isa<TerminatorInst>(I) && // Terminators aren't folded.
1046 !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded.
1047 !I->isEHPad() && // EH pad instructions aren't folded.
1048 !FuncInfo->isExportedInst(I); // Exported instrs must be computed.
1051 /// Set up SwiftErrorVals by going through the function. If the function has
1052 /// swifterror argument, it will be the first entry.
1053 static void setupSwiftErrorVals(const Function &Fn, const TargetLowering *TLI,
1054 FunctionLoweringInfo *FuncInfo) {
1055 if (!TLI->supportSwiftError())
1058 FuncInfo->SwiftErrorVals.clear();
1059 FuncInfo->SwiftErrorVRegDefMap.clear();
1060 FuncInfo->SwiftErrorVRegUpwardsUse.clear();
1061 FuncInfo->SwiftErrorVRegDefUses.clear();
1062 FuncInfo->SwiftErrorArg = nullptr;
1064 // Check if function has a swifterror argument.
1065 bool HaveSeenSwiftErrorArg = false;
1066 for (Function::const_arg_iterator AI = Fn.arg_begin(), AE = Fn.arg_end();
1068 if (AI->hasSwiftErrorAttr()) {
1069 assert(!HaveSeenSwiftErrorArg &&
1070 "Must have only one swifterror parameter");
1071 (void)HaveSeenSwiftErrorArg; // silence warning.
1072 HaveSeenSwiftErrorArg = true;
1073 FuncInfo->SwiftErrorArg = &*AI;
1074 FuncInfo->SwiftErrorVals.push_back(&*AI);
1077 for (const auto &LLVMBB : Fn)
1078 for (const auto &Inst : LLVMBB) {
1079 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(&Inst))
1080 if (Alloca->isSwiftError())
1081 FuncInfo->SwiftErrorVals.push_back(Alloca);
1085 static void createSwiftErrorEntriesInEntryBlock(FunctionLoweringInfo *FuncInfo,
1087 const TargetLowering *TLI,
1088 const TargetInstrInfo *TII,
1089 SelectionDAGBuilder *SDB) {
1090 if (!TLI->supportSwiftError())
1093 // We only need to do this when we have swifterror parameter or swifterror
1095 if (FuncInfo->SwiftErrorVals.empty())
1098 assert(FuncInfo->MBB == &*FuncInfo->MF->begin() &&
1099 "expected to insert into entry block");
1100 auto &DL = FuncInfo->MF->getDataLayout();
1101 auto const *RC = TLI->getRegClassFor(TLI->getPointerTy(DL));
1102 for (const auto *SwiftErrorVal : FuncInfo->SwiftErrorVals) {
1103 // We will always generate a copy from the argument. It is always used at
1104 // least by the 'return' of the swifterror.
1105 if (FuncInfo->SwiftErrorArg && FuncInfo->SwiftErrorArg == SwiftErrorVal)
1107 unsigned VReg = FuncInfo->MF->getRegInfo().createVirtualRegister(RC);
1108 // Assign Undef to Vreg. We construct MI directly to make sure it works
1110 BuildMI(*FuncInfo->MBB, FuncInfo->MBB->getFirstNonPHI(),
1111 SDB->getCurDebugLoc(), TII->get(TargetOpcode::IMPLICIT_DEF),
1114 // Keep FastIS informed about the value we just inserted.
1116 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
1118 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, SwiftErrorVal, VReg);
1122 /// Collect llvm.dbg.declare information. This is done after argument lowering
1123 /// in case the declarations refer to arguments.
1124 static void processDbgDeclares(FunctionLoweringInfo *FuncInfo) {
1125 MachineFunction *MF = FuncInfo->MF;
1126 const DataLayout &DL = MF->getDataLayout();
1127 for (const BasicBlock &BB : *FuncInfo->Fn) {
1128 for (const Instruction &I : BB) {
1129 const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(&I);
1133 assert(DI->getVariable() && "Missing variable");
1134 assert(DI->getDebugLoc() && "Missing location");
1135 const Value *Address = DI->getAddress();
1139 // Look through casts and constant offset GEPs. These mostly come from
1141 APInt Offset(DL.getPointerSizeInBits(0), 0);
1142 Address = Address->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
1144 // Check if the variable is a static alloca or a byval or inalloca
1145 // argument passed in memory. If it is not, then we will ignore this
1146 // intrinsic and handle this during isel like dbg.value.
1147 int FI = std::numeric_limits<int>::max();
1148 if (const auto *AI = dyn_cast<AllocaInst>(Address)) {
1149 auto SI = FuncInfo->StaticAllocaMap.find(AI);
1150 if (SI != FuncInfo->StaticAllocaMap.end())
1152 } else if (const auto *Arg = dyn_cast<Argument>(Address))
1153 FI = FuncInfo->getArgumentFrameIndex(Arg);
1155 if (FI == std::numeric_limits<int>::max())
1158 DIExpression *Expr = DI->getExpression();
1159 if (Offset.getBoolValue())
1160 Expr = DIExpression::prepend(Expr, DIExpression::NoDeref,
1161 Offset.getZExtValue());
1162 MF->setVariableDbgInfo(DI->getVariable(), Expr, FI, DI->getDebugLoc());
1167 /// Propagate swifterror values through the machine function CFG.
1168 static void propagateSwiftErrorVRegs(FunctionLoweringInfo *FuncInfo) {
1169 auto *TLI = FuncInfo->TLI;
1170 if (!TLI->supportSwiftError())
1173 // We only need to do this when we have swifterror parameter or swifterror
1175 if (FuncInfo->SwiftErrorVals.empty())
1178 // For each machine basic block in reverse post order.
1179 ReversePostOrderTraversal<MachineFunction *> RPOT(FuncInfo->MF);
1180 for (ReversePostOrderTraversal<MachineFunction *>::rpo_iterator
1184 MachineBasicBlock *MBB = *It;
1186 // For each swifterror value in the function.
1187 for(const auto *SwiftErrorVal : FuncInfo->SwiftErrorVals) {
1188 auto Key = std::make_pair(MBB, SwiftErrorVal);
1189 auto UUseIt = FuncInfo->SwiftErrorVRegUpwardsUse.find(Key);
1190 auto VRegDefIt = FuncInfo->SwiftErrorVRegDefMap.find(Key);
1191 bool UpwardsUse = UUseIt != FuncInfo->SwiftErrorVRegUpwardsUse.end();
1192 unsigned UUseVReg = UpwardsUse ? UUseIt->second : 0;
1193 bool DownwardDef = VRegDefIt != FuncInfo->SwiftErrorVRegDefMap.end();
1194 assert(!(UpwardsUse && !DownwardDef) &&
1195 "We can't have an upwards use but no downwards def");
1197 // If there is no upwards exposed use and an entry for the swifterror in
1198 // the def map for this value we don't need to do anything: We already
1199 // have a downward def for this basic block.
1200 if (!UpwardsUse && DownwardDef)
1203 // Otherwise we either have an upwards exposed use vreg that we need to
1204 // materialize or need to forward the downward def from predecessors.
1206 // Check whether we have a single vreg def from all predecessors.
1207 // Otherwise we need a phi.
1208 SmallVector<std::pair<MachineBasicBlock *, unsigned>, 4> VRegs;
1209 SmallSet<const MachineBasicBlock*, 8> Visited;
1210 for (auto *Pred : MBB->predecessors()) {
1211 if (!Visited.insert(Pred).second)
1213 VRegs.push_back(std::make_pair(
1214 Pred, FuncInfo->getOrCreateSwiftErrorVReg(Pred, SwiftErrorVal)));
1217 // We have a self-edge.
1218 // If there was no upwards use in this basic block there is now one: the
1219 // phi needs to use it self.
1222 UUseIt = FuncInfo->SwiftErrorVRegUpwardsUse.find(Key);
1223 assert(UUseIt != FuncInfo->SwiftErrorVRegUpwardsUse.end());
1224 UUseVReg = UUseIt->second;
1228 // We need a phi node if we have more than one predecessor with different
1231 VRegs.size() >= 1 &&
1233 VRegs.begin(), VRegs.end(),
1234 [&](const std::pair<const MachineBasicBlock *, unsigned> &V)
1235 -> bool { return V.second != VRegs[0].second; }) !=
1238 // If there is no upwards exposed used and we don't need a phi just
1239 // forward the swifterror vreg from the predecessor(s).
1240 if (!UpwardsUse && !needPHI) {
1241 assert(!VRegs.empty() &&
1242 "No predecessors? The entry block should bail out earlier");
1243 // Just forward the swifterror vreg from the predecessor(s).
1244 FuncInfo->setCurrentSwiftErrorVReg(MBB, SwiftErrorVal, VRegs[0].second);
1248 auto DLoc = isa<Instruction>(SwiftErrorVal)
1249 ? dyn_cast<Instruction>(SwiftErrorVal)->getDebugLoc()
1251 const auto *TII = FuncInfo->MF->getSubtarget().getInstrInfo();
1253 // If we don't need a phi create a copy to the upward exposed vreg.
1256 unsigned DestReg = UUseVReg;
1257 BuildMI(*MBB, MBB->getFirstNonPHI(), DLoc, TII->get(TargetOpcode::COPY),
1259 .addReg(VRegs[0].second);
1263 // We need a phi: if there is an upwards exposed use we already have a
1264 // destination virtual register number otherwise we generate a new one.
1265 auto &DL = FuncInfo->MF->getDataLayout();
1266 auto const *RC = TLI->getRegClassFor(TLI->getPointerTy(DL));
1268 UpwardsUse ? UUseVReg
1269 : FuncInfo->MF->getRegInfo().createVirtualRegister(RC);
1270 MachineInstrBuilder SwiftErrorPHI =
1271 BuildMI(*MBB, MBB->getFirstNonPHI(), DLoc,
1272 TII->get(TargetOpcode::PHI), PHIVReg);
1273 for (auto BBRegPair : VRegs) {
1274 SwiftErrorPHI.addReg(BBRegPair.second).addMBB(BBRegPair.first);
1277 // We did not have a definition in this block before: store the phi's vreg
1278 // as this block downward exposed def.
1280 FuncInfo->setCurrentSwiftErrorVReg(MBB, SwiftErrorVal, PHIVReg);
1285 void preassignSwiftErrorRegs(const TargetLowering *TLI,
1286 FunctionLoweringInfo *FuncInfo,
1287 BasicBlock::const_iterator Begin,
1288 BasicBlock::const_iterator End) {
1289 if (!TLI->supportSwiftError() || FuncInfo->SwiftErrorVals.empty())
1292 // Iterator over instructions and assign vregs to swifterror defs and uses.
1293 for (auto It = Begin; It != End; ++It) {
1294 ImmutableCallSite CS(&*It);
1296 // A call-site with a swifterror argument is both use and def.
1297 const Value *SwiftErrorAddr = nullptr;
1298 for (auto &Arg : CS.args()) {
1299 if (!Arg->isSwiftError())
1301 // Use of swifterror.
1302 assert(!SwiftErrorAddr && "Cannot have multiple swifterror arguments");
1303 SwiftErrorAddr = &*Arg;
1304 assert(SwiftErrorAddr->isSwiftError() &&
1305 "Must have a swifterror value argument");
1306 unsigned VReg; bool CreatedReg;
1307 std::tie(VReg, CreatedReg) = FuncInfo->getOrCreateSwiftErrorVRegUseAt(
1308 &*It, FuncInfo->MBB, SwiftErrorAddr);
1311 if (!SwiftErrorAddr)
1314 // Def of swifterror.
1315 unsigned VReg; bool CreatedReg;
1316 std::tie(VReg, CreatedReg) =
1317 FuncInfo->getOrCreateSwiftErrorVRegDefAt(&*It);
1319 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, SwiftErrorAddr, VReg);
1322 } else if (const LoadInst *LI = dyn_cast<const LoadInst>(&*It)) {
1323 const Value *V = LI->getOperand(0);
1324 if (!V->isSwiftError())
1327 unsigned VReg; bool CreatedReg;
1328 std::tie(VReg, CreatedReg) =
1329 FuncInfo->getOrCreateSwiftErrorVRegUseAt(LI, FuncInfo->MBB, V);
1332 // A store is a def.
1333 } else if (const StoreInst *SI = dyn_cast<const StoreInst>(&*It)) {
1334 const Value *SwiftErrorAddr = SI->getOperand(1);
1335 if (!SwiftErrorAddr->isSwiftError())
1338 // Def of swifterror.
1339 unsigned VReg; bool CreatedReg;
1340 std::tie(VReg, CreatedReg) =
1341 FuncInfo->getOrCreateSwiftErrorVRegDefAt(&*It);
1343 FuncInfo->setCurrentSwiftErrorVReg(FuncInfo->MBB, SwiftErrorAddr, VReg);
1345 // A return in a swiferror returning function is a use.
1346 } else if (const ReturnInst *R = dyn_cast<const ReturnInst>(&*It)) {
1347 const Function *F = R->getParent()->getParent();
1348 if(!F->getAttributes().hasAttrSomewhere(Attribute::SwiftError))
1351 unsigned VReg; bool CreatedReg;
1352 std::tie(VReg, CreatedReg) = FuncInfo->getOrCreateSwiftErrorVRegUseAt(
1353 R, FuncInfo->MBB, FuncInfo->SwiftErrorArg);
1359 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
1360 FastISelFailed = false;
1361 // Initialize the Fast-ISel state, if needed.
1362 FastISel *FastIS = nullptr;
1363 if (TM.Options.EnableFastISel)
1364 FastIS = TLI->createFastISel(*FuncInfo, LibInfo);
1366 setupSwiftErrorVals(Fn, TLI, FuncInfo);
1368 ReversePostOrderTraversal<const Function*> RPOT(&Fn);
1370 // Lower arguments up front. An RPO iteration always visits the entry block
1372 assert(*RPOT.begin() == &Fn.getEntryBlock());
1375 // Set up FuncInfo for ISel. Entry blocks never have PHIs.
1376 FuncInfo->MBB = FuncInfo->MBBMap[&Fn.getEntryBlock()];
1377 FuncInfo->InsertPt = FuncInfo->MBB->begin();
1382 // See if fast isel can lower the arguments.
1383 FastIS->startNewBlock();
1384 if (!FastIS->lowerArguments()) {
1385 FastISelFailed = true;
1386 // Fast isel failed to lower these arguments
1387 ++NumFastIselFailLowerArguments;
1389 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1391 &Fn.getEntryBlock());
1392 R << "FastISel didn't lower all arguments: "
1393 << ore::NV("Prototype", Fn.getType());
1394 reportFastISelFailure(*MF, *ORE, R, EnableFastISelAbort > 1);
1396 // Use SelectionDAG argument lowering
1398 CurDAG->setRoot(SDB->getControlRoot());
1400 CodeGenAndEmitDAG();
1403 // If we inserted any instructions at the beginning, make a note of
1404 // where they are, so we can be sure to emit subsequent instructions
1406 if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
1407 FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
1409 FastIS->setLastLocalValue(nullptr);
1411 createSwiftErrorEntriesInEntryBlock(FuncInfo, FastIS, TLI, TII, SDB);
1413 processDbgDeclares(FuncInfo);
1415 // Iterate over all basic blocks in the function.
1416 for (const BasicBlock *LLVMBB : RPOT) {
1417 if (OptLevel != CodeGenOpt::None) {
1418 bool AllPredsVisited = true;
1419 for (const_pred_iterator PI = pred_begin(LLVMBB), PE = pred_end(LLVMBB);
1421 if (!FuncInfo->VisitedBBs.count(*PI)) {
1422 AllPredsVisited = false;
1427 if (AllPredsVisited) {
1428 for (BasicBlock::const_iterator I = LLVMBB->begin();
1429 const PHINode *PN = dyn_cast<PHINode>(I); ++I)
1430 FuncInfo->ComputePHILiveOutRegInfo(PN);
1432 for (BasicBlock::const_iterator I = LLVMBB->begin();
1433 const PHINode *PN = dyn_cast<PHINode>(I); ++I)
1434 FuncInfo->InvalidatePHILiveOutRegInfo(PN);
1437 FuncInfo->VisitedBBs.insert(LLVMBB);
1440 BasicBlock::const_iterator const Begin =
1441 LLVMBB->getFirstNonPHI()->getIterator();
1442 BasicBlock::const_iterator const End = LLVMBB->end();
1443 BasicBlock::const_iterator BI = End;
1445 FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
1447 continue; // Some blocks like catchpads have no code or MBB.
1449 // Insert new instructions after any phi or argument setup code.
1450 FuncInfo->InsertPt = FuncInfo->MBB->end();
1452 // Setup an EH landing-pad block.
1453 FuncInfo->ExceptionPointerVirtReg = 0;
1454 FuncInfo->ExceptionSelectorVirtReg = 0;
1455 if (LLVMBB->isEHPad())
1456 if (!PrepareEHLandingPad())
1459 // Before doing SelectionDAG ISel, see if FastISel has been requested.
1461 if (LLVMBB != &Fn.getEntryBlock())
1462 FastIS->startNewBlock();
1464 unsigned NumFastIselRemaining = std::distance(Begin, End);
1466 // Pre-assign swifterror vregs.
1467 preassignSwiftErrorRegs(TLI, FuncInfo, Begin, End);
1469 // Do FastISel on as many instructions as possible.
1470 for (; BI != Begin; --BI) {
1471 const Instruction *Inst = &*std::prev(BI);
1473 // If we no longer require this instruction, skip it.
1474 if (isFoldedOrDeadInstruction(Inst, FuncInfo) ||
1475 ElidedArgCopyInstrs.count(Inst)) {
1476 --NumFastIselRemaining;
1480 // Bottom-up: reset the insert pos at the top, after any local-value
1482 FastIS->recomputeInsertPt();
1484 // Try to select the instruction with FastISel.
1485 if (FastIS->selectInstruction(Inst)) {
1486 --NumFastIselRemaining;
1487 ++NumFastIselSuccess;
1488 // If fast isel succeeded, skip over all the folded instructions, and
1489 // then see if there is a load right before the selected instructions.
1490 // Try to fold the load if so.
1491 const Instruction *BeforeInst = Inst;
1492 while (BeforeInst != &*Begin) {
1493 BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst));
1494 if (!isFoldedOrDeadInstruction(BeforeInst, FuncInfo))
1497 if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
1498 BeforeInst->hasOneUse() &&
1499 FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
1500 // If we succeeded, don't re-select the load.
1501 BI = std::next(BasicBlock::const_iterator(BeforeInst));
1502 --NumFastIselRemaining;
1503 ++NumFastIselSuccess;
1508 FastISelFailed = true;
1510 // Then handle certain instructions as single-LLVM-Instruction blocks.
1511 // We cannot separate out GCrelocates to their own blocks since we need
1512 // to keep track of gc-relocates for a particular gc-statepoint. This is
1513 // done by SelectionDAGBuilder::LowerAsSTATEPOINT, called before
1515 if (isa<CallInst>(Inst) && !isStatepoint(Inst) && !isGCRelocate(Inst)) {
1516 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1517 Inst->getDebugLoc(), LLVMBB);
1519 R << "FastISel missed call";
1521 if (R.isEnabled() || EnableFastISelAbort) {
1522 std::string InstStrStorage;
1523 raw_string_ostream InstStr(InstStrStorage);
1526 R << ": " << InstStr.str();
1529 reportFastISelFailure(*MF, *ORE, R, EnableFastISelAbort > 2);
1531 if (!Inst->getType()->isVoidTy() && !Inst->getType()->isTokenTy() &&
1532 !Inst->use_empty()) {
1533 unsigned &R = FuncInfo->ValueMap[Inst];
1535 R = FuncInfo->CreateRegs(Inst->getType());
1538 bool HadTailCall = false;
1539 MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
1540 SelectBasicBlock(Inst->getIterator(), BI, HadTailCall);
1542 // If the call was emitted as a tail call, we're done with the block.
1543 // We also need to delete any previously emitted instructions.
1545 FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
1550 // Recompute NumFastIselRemaining as Selection DAG instruction
1551 // selection may have handled the call, input args, etc.
1552 unsigned RemainingNow = std::distance(Begin, BI);
1553 NumFastIselFailures += NumFastIselRemaining - RemainingNow;
1554 NumFastIselRemaining = RemainingNow;
1558 OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1559 Inst->getDebugLoc(), LLVMBB);
1561 bool ShouldAbort = EnableFastISelAbort;
1562 if (isa<TerminatorInst>(Inst)) {
1563 // Use a different message for terminator misses.
1564 R << "FastISel missed terminator";
1565 // Don't abort for terminator unless the level is really high
1566 ShouldAbort = (EnableFastISelAbort > 2);
1568 R << "FastISel missed";
1571 if (R.isEnabled() || EnableFastISelAbort) {
1572 std::string InstStrStorage;
1573 raw_string_ostream InstStr(InstStrStorage);
1575 R << ": " << InstStr.str();
1578 reportFastISelFailure(*MF, *ORE, R, ShouldAbort);
1580 NumFastIselFailures += NumFastIselRemaining;
1584 FastIS->recomputeInsertPt();
1587 if (getAnalysis<StackProtector>().shouldEmitSDCheck(*LLVMBB)) {
1588 bool FunctionBasedInstrumentation =
1589 TLI->getSSPStackGuardCheck(*Fn.getParent());
1590 SDB->SPDescriptor.initialize(LLVMBB, FuncInfo->MBBMap[LLVMBB],
1591 FunctionBasedInstrumentation);
1597 ++NumFastIselBlocks;
1600 // Run SelectionDAG instruction selection on the remainder of the block
1601 // not handled by FastISel. If FastISel is not run, this is the entire
1604 SelectBasicBlock(Begin, BI, HadTailCall);
1606 // But if FastISel was run, we already selected some of the block.
1607 // If we emitted a tail-call, we need to delete any previously emitted
1608 // instruction that follows it.
1609 if (HadTailCall && FuncInfo->InsertPt != FuncInfo->MBB->end())
1610 FastIS->removeDeadCode(FuncInfo->InsertPt, FuncInfo->MBB->end());
1614 FuncInfo->PHINodesToUpdate.clear();
1615 ElidedArgCopyInstrs.clear();
1618 propagateSwiftErrorVRegs(FuncInfo);
1621 SDB->clearDanglingDebugInfo();
1622 SDB->SPDescriptor.resetPerFunctionState();
1625 /// Given that the input MI is before a partial terminator sequence TSeq, return
1626 /// true if M + TSeq also a partial terminator sequence.
1628 /// A Terminator sequence is a sequence of MachineInstrs which at this point in
1629 /// lowering copy vregs into physical registers, which are then passed into
1630 /// terminator instructors so we can satisfy ABI constraints. A partial
1631 /// terminator sequence is an improper subset of a terminator sequence (i.e. it
1632 /// may be the whole terminator sequence).
1633 static bool MIIsInTerminatorSequence(const MachineInstr &MI) {
1634 // If we do not have a copy or an implicit def, we return true if and only if
1635 // MI is a debug value.
1636 if (!MI.isCopy() && !MI.isImplicitDef())
1637 // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the
1638 // physical registers if there is debug info associated with the terminator
1639 // of our mbb. We want to include said debug info in our terminator
1640 // sequence, so we return true in that case.
1641 return MI.isDebugValue();
1643 // We have left the terminator sequence if we are not doing one of the
1646 // 1. Copying a vreg into a physical register.
1647 // 2. Copying a vreg into a vreg.
1648 // 3. Defining a register via an implicit def.
1650 // OPI should always be a register definition...
1651 MachineInstr::const_mop_iterator OPI = MI.operands_begin();
1652 if (!OPI->isReg() || !OPI->isDef())
1655 // Defining any register via an implicit def is always ok.
1656 if (MI.isImplicitDef())
1659 // Grab the copy source...
1660 MachineInstr::const_mop_iterator OPI2 = OPI;
1662 assert(OPI2 != MI.operands_end()
1663 && "Should have a copy implying we should have 2 arguments.");
1665 // Make sure that the copy dest is not a vreg when the copy source is a
1666 // physical register.
1667 if (!OPI2->isReg() ||
1668 (!TargetRegisterInfo::isPhysicalRegister(OPI->getReg()) &&
1669 TargetRegisterInfo::isPhysicalRegister(OPI2->getReg())))
1675 /// Find the split point at which to splice the end of BB into its success stack
1676 /// protector check machine basic block.
1678 /// On many platforms, due to ABI constraints, terminators, even before register
1679 /// allocation, use physical registers. This creates an issue for us since
1680 /// physical registers at this point can not travel across basic
1681 /// blocks. Luckily, selectiondag always moves physical registers into vregs
1682 /// when they enter functions and moves them through a sequence of copies back
1683 /// into the physical registers right before the terminator creating a
1684 /// ``Terminator Sequence''. This function is searching for the beginning of the
1685 /// terminator sequence so that we can ensure that we splice off not just the
1686 /// terminator, but additionally the copies that move the vregs into the
1687 /// physical registers.
1688 static MachineBasicBlock::iterator
1689 FindSplitPointForStackProtector(MachineBasicBlock *BB) {
1690 MachineBasicBlock::iterator SplitPoint = BB->getFirstTerminator();
1692 if (SplitPoint == BB->begin())
1695 MachineBasicBlock::iterator Start = BB->begin();
1696 MachineBasicBlock::iterator Previous = SplitPoint;
1699 while (MIIsInTerminatorSequence(*Previous)) {
1700 SplitPoint = Previous;
1701 if (Previous == Start)
1710 SelectionDAGISel::FinishBasicBlock() {
1711 DEBUG(dbgs() << "Total amount of phi nodes to update: "
1712 << FuncInfo->PHINodesToUpdate.size() << "\n";
1713 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i)
1714 dbgs() << "Node " << i << " : ("
1715 << FuncInfo->PHINodesToUpdate[i].first
1716 << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
1718 // Next, now that we know what the last MBB the LLVM BB expanded is, update
1719 // PHI nodes in successors.
1720 for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1721 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
1722 assert(PHI->isPHI() &&
1723 "This is not a machine PHI node that we are updating!");
1724 if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
1726 PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
1729 // Handle stack protector.
1730 if (SDB->SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) {
1731 // The target provides a guard check function. There is no need to
1732 // generate error handling code or to split current basic block.
1733 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1735 // Add load and check to the basicblock.
1736 FuncInfo->MBB = ParentMBB;
1737 FuncInfo->InsertPt =
1738 FindSplitPointForStackProtector(ParentMBB);
1739 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
1740 CurDAG->setRoot(SDB->getRoot());
1742 CodeGenAndEmitDAG();
1744 // Clear the Per-BB State.
1745 SDB->SPDescriptor.resetPerBBState();
1746 } else if (SDB->SPDescriptor.shouldEmitStackProtector()) {
1747 MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1748 MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB();
1750 // Find the split point to split the parent mbb. At the same time copy all
1751 // physical registers used in the tail of parent mbb into virtual registers
1752 // before the split point and back into physical registers after the split
1753 // point. This prevents us needing to deal with Live-ins and many other
1754 // register allocation issues caused by us splitting the parent mbb. The
1755 // register allocator will clean up said virtual copies later on.
1756 MachineBasicBlock::iterator SplitPoint =
1757 FindSplitPointForStackProtector(ParentMBB);
1759 // Splice the terminator of ParentMBB into SuccessMBB.
1760 SuccessMBB->splice(SuccessMBB->end(), ParentMBB,
1764 // Add compare/jump on neq/jump to the parent BB.
1765 FuncInfo->MBB = ParentMBB;
1766 FuncInfo->InsertPt = ParentMBB->end();
1767 SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
1768 CurDAG->setRoot(SDB->getRoot());
1770 CodeGenAndEmitDAG();
1772 // CodeGen Failure MBB if we have not codegened it yet.
1773 MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB();
1774 if (FailureMBB->empty()) {
1775 FuncInfo->MBB = FailureMBB;
1776 FuncInfo->InsertPt = FailureMBB->end();
1777 SDB->visitSPDescriptorFailure(SDB->SPDescriptor);
1778 CurDAG->setRoot(SDB->getRoot());
1780 CodeGenAndEmitDAG();
1783 // Clear the Per-BB State.
1784 SDB->SPDescriptor.resetPerBBState();
1787 // Lower each BitTestBlock.
1788 for (auto &BTB : SDB->BitTestCases) {
1789 // Lower header first, if it wasn't already lowered
1791 // Set the current basic block to the mbb we wish to insert the code into
1792 FuncInfo->MBB = BTB.Parent;
1793 FuncInfo->InsertPt = FuncInfo->MBB->end();
1795 SDB->visitBitTestHeader(BTB, FuncInfo->MBB);
1796 CurDAG->setRoot(SDB->getRoot());
1798 CodeGenAndEmitDAG();
1801 BranchProbability UnhandledProb = BTB.Prob;
1802 for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
1803 UnhandledProb -= BTB.Cases[j].ExtraProb;
1804 // Set the current basic block to the mbb we wish to insert the code into
1805 FuncInfo->MBB = BTB.Cases[j].ThisBB;
1806 FuncInfo->InsertPt = FuncInfo->MBB->end();
1809 // If all cases cover a contiguous range, it is not necessary to jump to
1810 // the default block after the last bit test fails. This is because the
1811 // range check during bit test header creation has guaranteed that every
1812 // case here doesn't go outside the range. In this case, there is no need
1813 // to perform the last bit test, as it will always be true. Instead, make
1814 // the second-to-last bit-test fall through to the target of the last bit
1815 // test, and delete the last bit test.
1817 MachineBasicBlock *NextMBB;
1818 if (BTB.ContiguousRange && j + 2 == ej) {
1819 // Second-to-last bit-test with contiguous range: fall through to the
1820 // target of the final bit test.
1821 NextMBB = BTB.Cases[j + 1].TargetBB;
1822 } else if (j + 1 == ej) {
1823 // For the last bit test, fall through to Default.
1824 NextMBB = BTB.Default;
1826 // Otherwise, fall through to the next bit test.
1827 NextMBB = BTB.Cases[j + 1].ThisBB;
1830 SDB->visitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j],
1833 CurDAG->setRoot(SDB->getRoot());
1835 CodeGenAndEmitDAG();
1837 if (BTB.ContiguousRange && j + 2 == ej) {
1838 // Since we're not going to use the final bit test, remove it.
1839 BTB.Cases.pop_back();
1845 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1847 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1848 MachineBasicBlock *PHIBB = PHI->getParent();
1849 assert(PHI->isPHI() &&
1850 "This is not a machine PHI node that we are updating!");
1851 // This is "default" BB. We have two jumps to it. From "header" BB and
1852 // from last "case" BB, unless the latter was skipped.
1853 if (PHIBB == BTB.Default) {
1854 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(BTB.Parent);
1855 if (!BTB.ContiguousRange) {
1856 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1857 .addMBB(BTB.Cases.back().ThisBB);
1860 // One of "cases" BB.
1861 for (unsigned j = 0, ej = BTB.Cases.size();
1863 MachineBasicBlock* cBB = BTB.Cases[j].ThisBB;
1864 if (cBB->isSuccessor(PHIBB))
1865 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB);
1869 SDB->BitTestCases.clear();
1871 // If the JumpTable record is filled in, then we need to emit a jump table.
1872 // Updating the PHI nodes is tricky in this case, since we need to determine
1873 // whether the PHI is a successor of the range check MBB or the jump table MBB
1874 for (unsigned i = 0, e = SDB->JTCases.size(); i != e; ++i) {
1875 // Lower header first, if it wasn't already lowered
1876 if (!SDB->JTCases[i].first.Emitted) {
1877 // Set the current basic block to the mbb we wish to insert the code into
1878 FuncInfo->MBB = SDB->JTCases[i].first.HeaderBB;
1879 FuncInfo->InsertPt = FuncInfo->MBB->end();
1881 SDB->visitJumpTableHeader(SDB->JTCases[i].second, SDB->JTCases[i].first,
1883 CurDAG->setRoot(SDB->getRoot());
1885 CodeGenAndEmitDAG();
1888 // Set the current basic block to the mbb we wish to insert the code into
1889 FuncInfo->MBB = SDB->JTCases[i].second.MBB;
1890 FuncInfo->InsertPt = FuncInfo->MBB->end();
1892 SDB->visitJumpTable(SDB->JTCases[i].second);
1893 CurDAG->setRoot(SDB->getRoot());
1895 CodeGenAndEmitDAG();
1898 for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1900 MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1901 MachineBasicBlock *PHIBB = PHI->getParent();
1902 assert(PHI->isPHI() &&
1903 "This is not a machine PHI node that we are updating!");
1904 // "default" BB. We can go there only from header BB.
1905 if (PHIBB == SDB->JTCases[i].second.Default)
1906 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1907 .addMBB(SDB->JTCases[i].first.HeaderBB);
1908 // JT BB. Just iterate over successors here
1909 if (FuncInfo->MBB->isSuccessor(PHIBB))
1910 PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
1913 SDB->JTCases.clear();
1915 // If we generated any switch lowering information, build and codegen any
1916 // additional DAGs necessary.
1917 for (unsigned i = 0, e = SDB->SwitchCases.size(); i != e; ++i) {
1918 // Set the current basic block to the mbb we wish to insert the code into
1919 FuncInfo->MBB = SDB->SwitchCases[i].ThisBB;
1920 FuncInfo->InsertPt = FuncInfo->MBB->end();
1922 // Determine the unique successors.
1923 SmallVector<MachineBasicBlock *, 2> Succs;
1924 Succs.push_back(SDB->SwitchCases[i].TrueBB);
1925 if (SDB->SwitchCases[i].TrueBB != SDB->SwitchCases[i].FalseBB)
1926 Succs.push_back(SDB->SwitchCases[i].FalseBB);
1928 // Emit the code. Note that this could result in FuncInfo->MBB being split.
1929 SDB->visitSwitchCase(SDB->SwitchCases[i], FuncInfo->MBB);
1930 CurDAG->setRoot(SDB->getRoot());
1932 CodeGenAndEmitDAG();
1934 // Remember the last block, now that any splitting is done, for use in
1935 // populating PHI nodes in successors.
1936 MachineBasicBlock *ThisBB = FuncInfo->MBB;
1938 // Handle any PHI nodes in successors of this chunk, as if we were coming
1939 // from the original BB before switch expansion. Note that PHI nodes can
1940 // occur multiple times in PHINodesToUpdate. We have to be very careful to
1941 // handle them the right number of times.
1942 for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1943 FuncInfo->MBB = Succs[i];
1944 FuncInfo->InsertPt = FuncInfo->MBB->end();
1945 // FuncInfo->MBB may have been removed from the CFG if a branch was
1947 if (ThisBB->isSuccessor(FuncInfo->MBB)) {
1948 for (MachineBasicBlock::iterator
1949 MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
1950 MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
1951 MachineInstrBuilder PHI(*MF, MBBI);
1952 // This value for this PHI node is recorded in PHINodesToUpdate.
1953 for (unsigned pn = 0; ; ++pn) {
1954 assert(pn != FuncInfo->PHINodesToUpdate.size() &&
1955 "Didn't find PHI entry!");
1956 if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
1957 PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
1965 SDB->SwitchCases.clear();
1968 /// Create the scheduler. If a specific scheduler was specified
1969 /// via the SchedulerRegistry, use it, otherwise select the
1970 /// one preferred by the target.
1972 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1973 return ISHeuristic(this, OptLevel);
1976 //===----------------------------------------------------------------------===//
1977 // Helper functions used by the generated instruction selector.
1978 //===----------------------------------------------------------------------===//
1979 // Calls to these methods are generated by tblgen.
1981 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
1982 /// the dag combiner simplified the 255, we still want to match. RHS is the
1983 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1984 /// specified in the .td file (e.g. 255).
1985 bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1986 int64_t DesiredMaskS) const {
1987 const APInt &ActualMask = RHS->getAPIntValue();
1988 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1990 // If the actual mask exactly matches, success!
1991 if (ActualMask == DesiredMask)
1994 // If the actual AND mask is allowing unallowed bits, this doesn't match.
1995 if (ActualMask.intersects(~DesiredMask))
1998 // Otherwise, the DAG Combiner may have proven that the value coming in is
1999 // either already zero or is not demanded. Check for known zero input bits.
2000 APInt NeededMask = DesiredMask & ~ActualMask;
2001 if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
2004 // TODO: check to see if missing bits are just not demanded.
2006 // Otherwise, this pattern doesn't match.
2010 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
2011 /// the dag combiner simplified the 255, we still want to match. RHS is the
2012 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
2013 /// specified in the .td file (e.g. 255).
2014 bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
2015 int64_t DesiredMaskS) const {
2016 const APInt &ActualMask = RHS->getAPIntValue();
2017 const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
2019 // If the actual mask exactly matches, success!
2020 if (ActualMask == DesiredMask)
2023 // If the actual AND mask is allowing unallowed bits, this doesn't match.
2024 if (ActualMask.intersects(~DesiredMask))
2027 // Otherwise, the DAG Combiner may have proven that the value coming in is
2028 // either already zero or is not demanded. Check for known zero input bits.
2029 APInt NeededMask = DesiredMask & ~ActualMask;
2032 CurDAG->computeKnownBits(LHS, Known);
2034 // If all the missing bits in the or are already known to be set, match!
2035 if (NeededMask.isSubsetOf(Known.One))
2038 // TODO: check to see if missing bits are just not demanded.
2040 // Otherwise, this pattern doesn't match.
2044 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2045 /// by tblgen. Others should not call it.
2046 void SelectionDAGISel::SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops,
2048 std::vector<SDValue> InOps;
2049 std::swap(InOps, Ops);
2051 Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
2052 Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1
2053 Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc
2054 Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack)
2056 unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
2057 if (InOps[e-1].getValueType() == MVT::Glue)
2058 --e; // Don't process a glue operand if it is here.
2061 unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
2062 if (!InlineAsm::isMemKind(Flags)) {
2063 // Just skip over this operand, copying the operands verbatim.
2064 Ops.insert(Ops.end(), InOps.begin()+i,
2065 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
2066 i += InlineAsm::getNumOperandRegisters(Flags) + 1;
2068 assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
2069 "Memory operand with multiple values?");
2071 unsigned TiedToOperand;
2072 if (InlineAsm::isUseOperandTiedToDef(Flags, TiedToOperand)) {
2073 // We need the constraint ID from the operand this is tied to.
2074 unsigned CurOp = InlineAsm::Op_FirstOperand;
2075 Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue();
2076 for (; TiedToOperand; --TiedToOperand) {
2077 CurOp += InlineAsm::getNumOperandRegisters(Flags)+1;
2078 Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue();
2082 // Otherwise, this is a memory operand. Ask the target to select it.
2083 std::vector<SDValue> SelOps;
2084 unsigned ConstraintID = InlineAsm::getMemoryConstraintID(Flags);
2085 if (SelectInlineAsmMemoryOperand(InOps[i+1], ConstraintID, SelOps))
2086 report_fatal_error("Could not match memory address. Inline asm"
2089 // Add this to the output node.
2091 InlineAsm::getFlagWord(InlineAsm::Kind_Mem, SelOps.size());
2092 NewFlags = InlineAsm::getFlagWordForMem(NewFlags, ConstraintID);
2093 Ops.push_back(CurDAG->getTargetConstant(NewFlags, DL, MVT::i32));
2094 Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
2099 // Add the glue input back if present.
2100 if (e != InOps.size())
2101 Ops.push_back(InOps.back());
2104 /// findGlueUse - Return use of MVT::Glue value produced by the specified
2107 static SDNode *findGlueUse(SDNode *N) {
2108 unsigned FlagResNo = N->getNumValues()-1;
2109 for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
2110 SDUse &Use = I.getUse();
2111 if (Use.getResNo() == FlagResNo)
2112 return Use.getUser();
2117 /// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
2118 /// This function iteratively traverses up the operand chain, ignoring
2120 static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
2121 SDNode *Root, SmallPtrSetImpl<SDNode*> &Visited,
2122 bool IgnoreChains) {
2123 // The NodeID's are given uniques ID's where a node ID is guaranteed to be
2124 // greater than all of its (recursive) operands. If we scan to a point where
2125 // 'use' is smaller than the node we're scanning for, then we know we will
2128 // The Use may be -1 (unassigned) if it is a newly allocated node. This can
2129 // happen because we scan down to newly selected nodes in the case of glue
2131 std::vector<SDNode *> WorkList;
2132 WorkList.push_back(Use);
2134 while (!WorkList.empty()) {
2135 Use = WorkList.back();
2136 WorkList.pop_back();
2137 if (Use->getNodeId() < Def->getNodeId() && Use->getNodeId() != -1)
2140 // Don't revisit nodes if we already scanned it and didn't fail, we know we
2141 // won't fail if we scan it again.
2142 if (!Visited.insert(Use).second)
2145 for (const SDValue &Op : Use->op_values()) {
2146 // Ignore chain uses, they are validated by HandleMergeInputChains.
2147 if (Op.getValueType() == MVT::Other && IgnoreChains)
2150 SDNode *N = Op.getNode();
2152 if (Use == ImmedUse || Use == Root)
2153 continue; // We are not looking for immediate use.
2158 // Traverse up the operand chain.
2159 WorkList.push_back(N);
2165 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
2166 /// operand node N of U during instruction selection that starts at Root.
2167 bool SelectionDAGISel::IsProfitableToFold(SDValue N, SDNode *U,
2168 SDNode *Root) const {
2169 if (OptLevel == CodeGenOpt::None) return false;
2170 return N.hasOneUse();
2173 /// IsLegalToFold - Returns true if the specific operand node N of
2174 /// U can be folded during instruction selection that starts at Root.
2175 bool SelectionDAGISel::IsLegalToFold(SDValue N, SDNode *U, SDNode *Root,
2176 CodeGenOpt::Level OptLevel,
2177 bool IgnoreChains) {
2178 if (OptLevel == CodeGenOpt::None) return false;
2180 // If Root use can somehow reach N through a path that that doesn't contain
2181 // U then folding N would create a cycle. e.g. In the following
2182 // diagram, Root can reach N through X. If N is folded into into Root, then
2183 // X is both a predecessor and a successor of U.
2194 // * indicates nodes to be folded together.
2196 // If Root produces glue, then it gets (even more) interesting. Since it
2197 // will be "glued" together with its glue use in the scheduler, we need to
2198 // check if it might reach N.
2217 // If GU (glue use) indirectly reaches N (the load), and Root folds N
2218 // (call it Fold), then X is a predecessor of GU and a successor of
2219 // Fold. But since Fold and GU are glued together, this will create
2220 // a cycle in the scheduling graph.
2222 // If the node has glue, walk down the graph to the "lowest" node in the
2224 EVT VT = Root->getValueType(Root->getNumValues()-1);
2225 while (VT == MVT::Glue) {
2226 SDNode *GU = findGlueUse(Root);
2230 VT = Root->getValueType(Root->getNumValues()-1);
2232 // If our query node has a glue result with a use, we've walked up it. If
2233 // the user (which has already been selected) has a chain or indirectly uses
2234 // the chain, our WalkChainUsers predicate will not consider it. Because of
2235 // this, we cannot ignore chains in this predicate.
2236 IgnoreChains = false;
2239 SmallPtrSet<SDNode*, 16> Visited;
2240 return !findNonImmUse(Root, N.getNode(), U, Root, Visited, IgnoreChains);
2243 void SelectionDAGISel::Select_INLINEASM(SDNode *N) {
2246 std::vector<SDValue> Ops(N->op_begin(), N->op_end());
2247 SelectInlineAsmMemoryOperands(Ops, DL);
2249 const EVT VTs[] = {MVT::Other, MVT::Glue};
2250 SDValue New = CurDAG->getNode(ISD::INLINEASM, DL, VTs, Ops);
2252 ReplaceUses(N, New.getNode());
2253 CurDAG->RemoveDeadNode(N);
2256 void SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) {
2258 MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1));
2259 const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0));
2261 TLI->getRegisterByName(RegStr->getString().data(), Op->getValueType(0),
2263 SDValue New = CurDAG->getCopyFromReg(
2264 Op->getOperand(0), dl, Reg, Op->getValueType(0));
2266 ReplaceUses(Op, New.getNode());
2267 CurDAG->RemoveDeadNode(Op);
2270 void SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) {
2272 MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(Op->getOperand(1));
2273 const MDString *RegStr = dyn_cast<MDString>(MD->getMD()->getOperand(0));
2274 unsigned Reg = TLI->getRegisterByName(RegStr->getString().data(),
2275 Op->getOperand(2).getValueType(),
2277 SDValue New = CurDAG->getCopyToReg(
2278 Op->getOperand(0), dl, Reg, Op->getOperand(2));
2280 ReplaceUses(Op, New.getNode());
2281 CurDAG->RemoveDeadNode(Op);
2284 void SelectionDAGISel::Select_UNDEF(SDNode *N) {
2285 CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0));
2288 /// GetVBR - decode a vbr encoding whose top bit is set.
2289 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline uint64_t
2290 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
2291 assert(Val >= 128 && "Not a VBR");
2292 Val &= 127; // Remove first vbr bit.
2297 NextBits = MatcherTable[Idx++];
2298 Val |= (NextBits&127) << Shift;
2300 } while (NextBits & 128);
2305 /// When a match is complete, this method updates uses of interior chain results
2306 /// to use the new results.
2307 void SelectionDAGISel::UpdateChains(
2308 SDNode *NodeToMatch, SDValue InputChain,
2309 SmallVectorImpl<SDNode *> &ChainNodesMatched, bool isMorphNodeTo) {
2310 SmallVector<SDNode*, 4> NowDeadNodes;
2312 // Now that all the normal results are replaced, we replace the chain and
2313 // glue results if present.
2314 if (!ChainNodesMatched.empty()) {
2315 assert(InputChain.getNode() &&
2316 "Matched input chains but didn't produce a chain");
2317 // Loop over all of the nodes we matched that produced a chain result.
2318 // Replace all the chain results with the final chain we ended up with.
2319 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2320 SDNode *ChainNode = ChainNodesMatched[i];
2321 // If ChainNode is null, it's because we replaced it on a previous
2322 // iteration and we cleared it out of the map. Just skip it.
2326 assert(ChainNode->getOpcode() != ISD::DELETED_NODE &&
2327 "Deleted node left in chain");
2329 // Don't replace the results of the root node if we're doing a
2331 if (ChainNode == NodeToMatch && isMorphNodeTo)
2334 SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
2335 if (ChainVal.getValueType() == MVT::Glue)
2336 ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
2337 assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
2338 SelectionDAG::DAGNodeDeletedListener NDL(
2339 *CurDAG, [&](SDNode *N, SDNode *E) {
2340 std::replace(ChainNodesMatched.begin(), ChainNodesMatched.end(), N,
2341 static_cast<SDNode *>(nullptr));
2343 CurDAG->ReplaceAllUsesOfValueWith(ChainVal, InputChain);
2345 // If the node became dead and we haven't already seen it, delete it.
2346 if (ChainNode != NodeToMatch && ChainNode->use_empty() &&
2347 !std::count(NowDeadNodes.begin(), NowDeadNodes.end(), ChainNode))
2348 NowDeadNodes.push_back(ChainNode);
2352 if (!NowDeadNodes.empty())
2353 CurDAG->RemoveDeadNodes(NowDeadNodes);
2355 DEBUG(dbgs() << "ISEL: Match complete!\n");
2361 CR_LeadsToInteriorNode
2364 /// WalkChainUsers - Walk down the users of the specified chained node that is
2365 /// part of the pattern we're matching, looking at all of the users we find.
2366 /// This determines whether something is an interior node, whether we have a
2367 /// non-pattern node in between two pattern nodes (which prevent folding because
2368 /// it would induce a cycle) and whether we have a TokenFactor node sandwiched
2369 /// between pattern nodes (in which case the TF becomes part of the pattern).
2371 /// The walk we do here is guaranteed to be small because we quickly get down to
2372 /// already selected nodes "below" us.
2374 WalkChainUsers(const SDNode *ChainedNode,
2375 SmallVectorImpl<SDNode *> &ChainedNodesInPattern,
2376 DenseMap<const SDNode *, ChainResult> &TokenFactorResult,
2377 SmallVectorImpl<SDNode *> &InteriorChainedNodes) {
2378 ChainResult Result = CR_Simple;
2380 for (SDNode::use_iterator UI = ChainedNode->use_begin(),
2381 E = ChainedNode->use_end(); UI != E; ++UI) {
2382 // Make sure the use is of the chain, not some other value we produce.
2383 if (UI.getUse().getValueType() != MVT::Other) continue;
2387 if (User->getOpcode() == ISD::HANDLENODE) // Root of the graph.
2390 // If we see an already-selected machine node, then we've gone beyond the
2391 // pattern that we're selecting down into the already selected chunk of the
2393 unsigned UserOpcode = User->getOpcode();
2394 if (User->isMachineOpcode() ||
2395 UserOpcode == ISD::CopyToReg ||
2396 UserOpcode == ISD::CopyFromReg ||
2397 UserOpcode == ISD::INLINEASM ||
2398 UserOpcode == ISD::EH_LABEL ||
2399 UserOpcode == ISD::LIFETIME_START ||
2400 UserOpcode == ISD::LIFETIME_END) {
2401 // If their node ID got reset to -1 then they've already been selected.
2402 // Treat them like a MachineOpcode.
2403 if (User->getNodeId() == -1)
2407 // If we have a TokenFactor, we handle it specially.
2408 if (User->getOpcode() != ISD::TokenFactor) {
2409 // If the node isn't a token factor and isn't part of our pattern, then it
2410 // must be a random chained node in between two nodes we're selecting.
2411 // This happens when we have something like:
2416 // Because we structurally match the load/store as a read/modify/write,
2417 // but the call is chained between them. We cannot fold in this case
2418 // because it would induce a cycle in the graph.
2419 if (!std::count(ChainedNodesInPattern.begin(),
2420 ChainedNodesInPattern.end(), User))
2421 return CR_InducesCycle;
2423 // Otherwise we found a node that is part of our pattern. For example in:
2427 // This would happen when we're scanning down from the load and see the
2428 // store as a user. Record that there is a use of ChainedNode that is
2429 // part of the pattern and keep scanning uses.
2430 Result = CR_LeadsToInteriorNode;
2431 InteriorChainedNodes.push_back(User);
2435 // If we found a TokenFactor, there are two cases to consider: first if the
2436 // TokenFactor is just hanging "below" the pattern we're matching (i.e. no
2437 // uses of the TF are in our pattern) we just want to ignore it. Second,
2438 // the TokenFactor can be sandwiched in between two chained nodes, like so:
2444 // | \ DAG's like cheese
2447 // [TokenFactor] [Op]
2454 // In this case, the TokenFactor becomes part of our match and we rewrite it
2455 // as a new TokenFactor.
2457 // To distinguish these two cases, do a recursive walk down the uses.
2458 auto MemoizeResult = TokenFactorResult.find(User);
2459 bool Visited = MemoizeResult != TokenFactorResult.end();
2460 // Recursively walk chain users only if the result is not memoized.
2462 auto Res = WalkChainUsers(User, ChainedNodesInPattern, TokenFactorResult,
2463 InteriorChainedNodes);
2464 MemoizeResult = TokenFactorResult.insert(std::make_pair(User, Res)).first;
2466 switch (MemoizeResult->second) {
2468 // If the uses of the TokenFactor are just already-selected nodes, ignore
2469 // it, it is "below" our pattern.
2471 case CR_InducesCycle:
2472 // If the uses of the TokenFactor lead to nodes that are not part of our
2473 // pattern that are not selected, folding would turn this into a cycle,
2475 return CR_InducesCycle;
2476 case CR_LeadsToInteriorNode:
2477 break; // Otherwise, keep processing.
2480 // Okay, we know we're in the interesting interior case. The TokenFactor
2481 // is now going to be considered part of the pattern so that we rewrite its
2482 // uses (it may have uses that are not part of the pattern) with the
2483 // ultimate chain result of the generated code. We will also add its chain
2484 // inputs as inputs to the ultimate TokenFactor we create.
2485 Result = CR_LeadsToInteriorNode;
2487 ChainedNodesInPattern.push_back(User);
2488 InteriorChainedNodes.push_back(User);
2495 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
2496 /// operation for when the pattern matched at least one node with a chains. The
2497 /// input vector contains a list of all of the chained nodes that we match. We
2498 /// must determine if this is a valid thing to cover (i.e. matching it won't
2499 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
2500 /// be used as the input node chain for the generated nodes.
2502 HandleMergeInputChains(SmallVectorImpl<SDNode*> &ChainNodesMatched,
2503 SelectionDAG *CurDAG) {
2504 // Used for memoization. Without it WalkChainUsers could take exponential
2506 DenseMap<const SDNode *, ChainResult> TokenFactorResult;
2507 // Walk all of the chained nodes we've matched, recursively scanning down the
2508 // users of the chain result. This adds any TokenFactor nodes that are caught
2509 // in between chained nodes to the chained and interior nodes list.
2510 SmallVector<SDNode*, 3> InteriorChainedNodes;
2511 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2512 if (WalkChainUsers(ChainNodesMatched[i], ChainNodesMatched,
2514 InteriorChainedNodes) == CR_InducesCycle)
2515 return SDValue(); // Would induce a cycle.
2518 // Okay, we have walked all the matched nodes and collected TokenFactor nodes
2519 // that we are interested in. Form our input TokenFactor node.
2520 SmallVector<SDValue, 3> InputChains;
2521 for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2522 // Add the input chain of this node to the InputChains list (which will be
2523 // the operands of the generated TokenFactor) if it's not an interior node.
2524 SDNode *N = ChainNodesMatched[i];
2525 if (N->getOpcode() != ISD::TokenFactor) {
2526 if (std::count(InteriorChainedNodes.begin(),InteriorChainedNodes.end(),N))
2529 // Otherwise, add the input chain.
2530 SDValue InChain = ChainNodesMatched[i]->getOperand(0);
2531 assert(InChain.getValueType() == MVT::Other && "Not a chain");
2532 InputChains.push_back(InChain);
2536 // If we have a token factor, we want to add all inputs of the token factor
2537 // that are not part of the pattern we're matching.
2538 for (const SDValue &Op : N->op_values()) {
2539 if (!std::count(ChainNodesMatched.begin(), ChainNodesMatched.end(),
2541 InputChains.push_back(Op);
2545 if (InputChains.size() == 1)
2546 return InputChains[0];
2547 return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
2548 MVT::Other, InputChains);
2551 /// MorphNode - Handle morphing a node in place for the selector.
2552 SDNode *SelectionDAGISel::
2553 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
2554 ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) {
2555 // It is possible we're using MorphNodeTo to replace a node with no
2556 // normal results with one that has a normal result (or we could be
2557 // adding a chain) and the input could have glue and chains as well.
2558 // In this case we need to shift the operands down.
2559 // FIXME: This is a horrible hack and broken in obscure cases, no worse
2560 // than the old isel though.
2561 int OldGlueResultNo = -1, OldChainResultNo = -1;
2563 unsigned NTMNumResults = Node->getNumValues();
2564 if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
2565 OldGlueResultNo = NTMNumResults-1;
2566 if (NTMNumResults != 1 &&
2567 Node->getValueType(NTMNumResults-2) == MVT::Other)
2568 OldChainResultNo = NTMNumResults-2;
2569 } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
2570 OldChainResultNo = NTMNumResults-1;
2572 // Call the underlying SelectionDAG routine to do the transmogrification. Note
2573 // that this deletes operands of the old node that become dead.
2574 SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops);
2576 // MorphNodeTo can operate in two ways: if an existing node with the
2577 // specified operands exists, it can just return it. Otherwise, it
2578 // updates the node in place to have the requested operands.
2580 // If we updated the node in place, reset the node ID. To the isel,
2581 // this should be just like a newly allocated machine node.
2585 unsigned ResNumResults = Res->getNumValues();
2586 // Move the glue if needed.
2587 if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
2588 (unsigned)OldGlueResultNo != ResNumResults-1)
2589 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldGlueResultNo),
2590 SDValue(Res, ResNumResults-1));
2592 if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
2595 // Move the chain reference if needed.
2596 if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
2597 (unsigned)OldChainResultNo != ResNumResults-1)
2598 CurDAG->ReplaceAllUsesOfValueWith(SDValue(Node, OldChainResultNo),
2599 SDValue(Res, ResNumResults-1));
2601 // Otherwise, no replacement happened because the node already exists. Replace
2602 // Uses of the old node with the new one.
2604 CurDAG->ReplaceAllUsesWith(Node, Res);
2605 CurDAG->RemoveDeadNode(Node);
2611 /// CheckSame - Implements OP_CheckSame.
2612 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2613 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2615 const SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) {
2616 // Accept if it is exactly the same as a previously recorded node.
2617 unsigned RecNo = MatcherTable[MatcherIndex++];
2618 assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2619 return N == RecordedNodes[RecNo].first;
2622 /// CheckChildSame - Implements OP_CheckChildXSame.
2623 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2624 CheckChildSame(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2626 const SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes,
2628 if (ChildNo >= N.getNumOperands())
2629 return false; // Match fails if out of range child #.
2630 return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo),
2634 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
2635 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2636 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2637 const SelectionDAGISel &SDISel) {
2638 return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
2641 /// CheckNodePredicate - Implements OP_CheckNodePredicate.
2642 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2643 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2644 const SelectionDAGISel &SDISel, SDNode *N) {
2645 return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
2648 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2649 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2651 uint16_t Opc = MatcherTable[MatcherIndex++];
2652 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2653 return N->getOpcode() == Opc;
2656 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2657 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2658 const TargetLowering *TLI, const DataLayout &DL) {
2659 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2660 if (N.getValueType() == VT) return true;
2662 // Handle the case when VT is iPTR.
2663 return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL);
2666 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2667 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2668 SDValue N, const TargetLowering *TLI, const DataLayout &DL,
2670 if (ChildNo >= N.getNumOperands())
2671 return false; // Match fails if out of range child #.
2672 return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI,
2676 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2677 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2679 return cast<CondCodeSDNode>(N)->get() ==
2680 (ISD::CondCode)MatcherTable[MatcherIndex++];
2683 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2684 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2685 SDValue N, const TargetLowering *TLI, const DataLayout &DL) {
2686 MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2687 if (cast<VTSDNode>(N)->getVT() == VT)
2690 // Handle the case when VT is iPTR.
2691 return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL);
2694 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2695 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2697 int64_t Val = MatcherTable[MatcherIndex++];
2699 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2701 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
2702 return C && C->getSExtValue() == Val;
2705 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2706 CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2707 SDValue N, unsigned ChildNo) {
2708 if (ChildNo >= N.getNumOperands())
2709 return false; // Match fails if out of range child #.
2710 return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo));
2713 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2714 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2715 SDValue N, const SelectionDAGISel &SDISel) {
2716 int64_t Val = MatcherTable[MatcherIndex++];
2718 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2720 if (N->getOpcode() != ISD::AND) return false;
2722 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2723 return C && SDISel.CheckAndMask(N.getOperand(0), C, Val);
2726 LLVM_ATTRIBUTE_ALWAYS_INLINE static inline bool
2727 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2728 SDValue N, const SelectionDAGISel &SDISel) {
2729 int64_t Val = MatcherTable[MatcherIndex++];
2731 Val = GetVBR(Val, MatcherTable, MatcherIndex);
2733 if (N->getOpcode() != ISD::OR) return false;
2735 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2736 return C && SDISel.CheckOrMask(N.getOperand(0), C, Val);
2739 /// IsPredicateKnownToFail - If we know how and can do so without pushing a
2740 /// scope, evaluate the current node. If the current predicate is known to
2741 /// fail, set Result=true and return anything. If the current predicate is
2742 /// known to pass, set Result=false and return the MatcherIndex to continue
2743 /// with. If the current predicate is unknown, set Result=false and return the
2744 /// MatcherIndex to continue with.
2745 static unsigned IsPredicateKnownToFail(const unsigned char *Table,
2746 unsigned Index, SDValue N,
2748 const SelectionDAGISel &SDISel,
2749 SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) {
2750 switch (Table[Index++]) {
2753 return Index-1; // Could not evaluate this predicate.
2754 case SelectionDAGISel::OPC_CheckSame:
2755 Result = !::CheckSame(Table, Index, N, RecordedNodes);
2757 case SelectionDAGISel::OPC_CheckChild0Same:
2758 case SelectionDAGISel::OPC_CheckChild1Same:
2759 case SelectionDAGISel::OPC_CheckChild2Same:
2760 case SelectionDAGISel::OPC_CheckChild3Same:
2761 Result = !::CheckChildSame(Table, Index, N, RecordedNodes,
2762 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Same);
2764 case SelectionDAGISel::OPC_CheckPatternPredicate:
2765 Result = !::CheckPatternPredicate(Table, Index, SDISel);
2767 case SelectionDAGISel::OPC_CheckPredicate:
2768 Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
2770 case SelectionDAGISel::OPC_CheckOpcode:
2771 Result = !::CheckOpcode(Table, Index, N.getNode());
2773 case SelectionDAGISel::OPC_CheckType:
2774 Result = !::CheckType(Table, Index, N, SDISel.TLI,
2775 SDISel.CurDAG->getDataLayout());
2777 case SelectionDAGISel::OPC_CheckChild0Type:
2778 case SelectionDAGISel::OPC_CheckChild1Type:
2779 case SelectionDAGISel::OPC_CheckChild2Type:
2780 case SelectionDAGISel::OPC_CheckChild3Type:
2781 case SelectionDAGISel::OPC_CheckChild4Type:
2782 case SelectionDAGISel::OPC_CheckChild5Type:
2783 case SelectionDAGISel::OPC_CheckChild6Type:
2784 case SelectionDAGISel::OPC_CheckChild7Type:
2785 Result = !::CheckChildType(
2786 Table, Index, N, SDISel.TLI, SDISel.CurDAG->getDataLayout(),
2787 Table[Index - 1] - SelectionDAGISel::OPC_CheckChild0Type);
2789 case SelectionDAGISel::OPC_CheckCondCode:
2790 Result = !::CheckCondCode(Table, Index, N);
2792 case SelectionDAGISel::OPC_CheckValueType:
2793 Result = !::CheckValueType(Table, Index, N, SDISel.TLI,
2794 SDISel.CurDAG->getDataLayout());
2796 case SelectionDAGISel::OPC_CheckInteger:
2797 Result = !::CheckInteger(Table, Index, N);
2799 case SelectionDAGISel::OPC_CheckChild0Integer:
2800 case SelectionDAGISel::OPC_CheckChild1Integer:
2801 case SelectionDAGISel::OPC_CheckChild2Integer:
2802 case SelectionDAGISel::OPC_CheckChild3Integer:
2803 case SelectionDAGISel::OPC_CheckChild4Integer:
2804 Result = !::CheckChildInteger(Table, Index, N,
2805 Table[Index-1] - SelectionDAGISel::OPC_CheckChild0Integer);
2807 case SelectionDAGISel::OPC_CheckAndImm:
2808 Result = !::CheckAndImm(Table, Index, N, SDISel);
2810 case SelectionDAGISel::OPC_CheckOrImm:
2811 Result = !::CheckOrImm(Table, Index, N, SDISel);
2819 /// FailIndex - If this match fails, this is the index to continue with.
2822 /// NodeStack - The node stack when the scope was formed.
2823 SmallVector<SDValue, 4> NodeStack;
2825 /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
2826 unsigned NumRecordedNodes;
2828 /// NumMatchedMemRefs - The number of matched memref entries.
2829 unsigned NumMatchedMemRefs;
2831 /// InputChain/InputGlue - The current chain/glue
2832 SDValue InputChain, InputGlue;
2834 /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
2835 bool HasChainNodesMatched;
2838 /// \\brief A DAG update listener to keep the matching state
2839 /// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to
2840 /// change the DAG while matching. X86 addressing mode matcher is an example
2842 class MatchStateUpdater : public SelectionDAG::DAGUpdateListener
2844 SDNode **NodeToMatch;
2845 SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes;
2846 SmallVectorImpl<MatchScope> &MatchScopes;
2849 MatchStateUpdater(SelectionDAG &DAG, SDNode **NodeToMatch,
2850 SmallVectorImpl<std::pair<SDValue, SDNode *>> &RN,
2851 SmallVectorImpl<MatchScope> &MS)
2852 : SelectionDAG::DAGUpdateListener(DAG), NodeToMatch(NodeToMatch),
2853 RecordedNodes(RN), MatchScopes(MS) {}
2855 void NodeDeleted(SDNode *N, SDNode *E) override {
2856 // Some early-returns here to avoid the search if we deleted the node or
2857 // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we
2858 // do, so it's unnecessary to update matching state at that point).
2859 // Neither of these can occur currently because we only install this
2860 // update listener during matching a complex patterns.
2861 if (!E || E->isMachineOpcode())
2863 // Check if NodeToMatch was updated.
2864 if (N == *NodeToMatch)
2866 // Performing linear search here does not matter because we almost never
2867 // run this code. You'd have to have a CSE during complex pattern
2869 for (auto &I : RecordedNodes)
2870 if (I.first.getNode() == N)
2873 for (auto &I : MatchScopes)
2874 for (auto &J : I.NodeStack)
2875 if (J.getNode() == N)
2880 } // end anonymous namespace
2882 void SelectionDAGISel::SelectCodeCommon(SDNode *NodeToMatch,
2883 const unsigned char *MatcherTable,
2884 unsigned TableSize) {
2885 // FIXME: Should these even be selected? Handle these cases in the caller?
2886 switch (NodeToMatch->getOpcode()) {
2889 case ISD::EntryToken: // These nodes remain the same.
2890 case ISD::BasicBlock:
2892 case ISD::RegisterMask:
2893 case ISD::HANDLENODE:
2894 case ISD::MDNODE_SDNODE:
2895 case ISD::TargetConstant:
2896 case ISD::TargetConstantFP:
2897 case ISD::TargetConstantPool:
2898 case ISD::TargetFrameIndex:
2899 case ISD::TargetExternalSymbol:
2901 case ISD::TargetBlockAddress:
2902 case ISD::TargetJumpTable:
2903 case ISD::TargetGlobalTLSAddress:
2904 case ISD::TargetGlobalAddress:
2905 case ISD::TokenFactor:
2906 case ISD::CopyFromReg:
2907 case ISD::CopyToReg:
2909 case ISD::LIFETIME_START:
2910 case ISD::LIFETIME_END:
2911 NodeToMatch->setNodeId(-1); // Mark selected.
2913 case ISD::AssertSext:
2914 case ISD::AssertZext:
2915 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, 0),
2916 NodeToMatch->getOperand(0));
2917 CurDAG->RemoveDeadNode(NodeToMatch);
2919 case ISD::INLINEASM:
2920 Select_INLINEASM(NodeToMatch);
2922 case ISD::READ_REGISTER:
2923 Select_READ_REGISTER(NodeToMatch);
2925 case ISD::WRITE_REGISTER:
2926 Select_WRITE_REGISTER(NodeToMatch);
2929 Select_UNDEF(NodeToMatch);
2933 assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
2935 // Set up the node stack with NodeToMatch as the only node on the stack.
2936 SmallVector<SDValue, 8> NodeStack;
2937 SDValue N = SDValue(NodeToMatch, 0);
2938 NodeStack.push_back(N);
2940 // MatchScopes - Scopes used when matching, if a match failure happens, this
2941 // indicates where to continue checking.
2942 SmallVector<MatchScope, 8> MatchScopes;
2944 // RecordedNodes - This is the set of nodes that have been recorded by the
2945 // state machine. The second value is the parent of the node, or null if the
2946 // root is recorded.
2947 SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
2949 // MatchedMemRefs - This is the set of MemRef's we've seen in the input
2951 SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
2953 // These are the current input chain and glue for use when generating nodes.
2954 // Various Emit operations change these. For example, emitting a copytoreg
2955 // uses and updates these.
2956 SDValue InputChain, InputGlue;
2958 // ChainNodesMatched - If a pattern matches nodes that have input/output
2959 // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
2960 // which ones they are. The result is captured into this list so that we can
2961 // update the chain results when the pattern is complete.
2962 SmallVector<SDNode*, 3> ChainNodesMatched;
2964 DEBUG(dbgs() << "ISEL: Starting pattern match on root node: ";
2965 NodeToMatch->dump(CurDAG);
2968 // Determine where to start the interpreter. Normally we start at opcode #0,
2969 // but if the state machine starts with an OPC_SwitchOpcode, then we
2970 // accelerate the first lookup (which is guaranteed to be hot) with the
2971 // OpcodeOffset table.
2972 unsigned MatcherIndex = 0;
2974 if (!OpcodeOffset.empty()) {
2975 // Already computed the OpcodeOffset table, just index into it.
2976 if (N.getOpcode() < OpcodeOffset.size())
2977 MatcherIndex = OpcodeOffset[N.getOpcode()];
2978 DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n");
2980 } else if (MatcherTable[0] == OPC_SwitchOpcode) {
2981 // Otherwise, the table isn't computed, but the state machine does start
2982 // with an OPC_SwitchOpcode instruction. Populate the table now, since this
2983 // is the first time we're selecting an instruction.
2986 // Get the size of this case.
2987 unsigned CaseSize = MatcherTable[Idx++];
2989 CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
2990 if (CaseSize == 0) break;
2992 // Get the opcode, add the index to the table.
2993 uint16_t Opc = MatcherTable[Idx++];
2994 Opc |= (unsigned short)MatcherTable[Idx++] << 8;
2995 if (Opc >= OpcodeOffset.size())
2996 OpcodeOffset.resize((Opc+1)*2);
2997 OpcodeOffset[Opc] = Idx;
3001 // Okay, do the lookup for the first opcode.
3002 if (N.getOpcode() < OpcodeOffset.size())
3003 MatcherIndex = OpcodeOffset[N.getOpcode()];
3007 assert(MatcherIndex < TableSize && "Invalid index");
3009 unsigned CurrentOpcodeIndex = MatcherIndex;
3011 BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
3014 // Okay, the semantics of this operation are that we should push a scope
3015 // then evaluate the first child. However, pushing a scope only to have
3016 // the first check fail (which then pops it) is inefficient. If we can
3017 // determine immediately that the first check (or first several) will
3018 // immediately fail, don't even bother pushing a scope for them.
3022 unsigned NumToSkip = MatcherTable[MatcherIndex++];
3023 if (NumToSkip & 128)
3024 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
3025 // Found the end of the scope with no match.
3026 if (NumToSkip == 0) {
3031 FailIndex = MatcherIndex+NumToSkip;
3033 unsigned MatcherIndexOfPredicate = MatcherIndex;
3034 (void)MatcherIndexOfPredicate; // silence warning.
3036 // If we can't evaluate this predicate without pushing a scope (e.g. if
3037 // it is a 'MoveParent') or if the predicate succeeds on this node, we
3038 // push the scope and evaluate the full predicate chain.
3040 MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
3041 Result, *this, RecordedNodes);
3045 DEBUG(dbgs() << " Skipped scope entry (due to false predicate) at "
3046 << "index " << MatcherIndexOfPredicate
3047 << ", continuing at " << FailIndex << "\n");
3048 ++NumDAGIselRetries;
3050 // Otherwise, we know that this case of the Scope is guaranteed to fail,
3051 // move to the next case.
3052 MatcherIndex = FailIndex;
3055 // If the whole scope failed to match, bail.
3056 if (FailIndex == 0) break;
3058 // Push a MatchScope which indicates where to go if the first child fails
3060 MatchScope NewEntry;
3061 NewEntry.FailIndex = FailIndex;
3062 NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
3063 NewEntry.NumRecordedNodes = RecordedNodes.size();
3064 NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
3065 NewEntry.InputChain = InputChain;
3066 NewEntry.InputGlue = InputGlue;
3067 NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
3068 MatchScopes.push_back(NewEntry);
3071 case OPC_RecordNode: {
3072 // Remember this node, it may end up being an operand in the pattern.
3073 SDNode *Parent = nullptr;
3074 if (NodeStack.size() > 1)
3075 Parent = NodeStack[NodeStack.size()-2].getNode();
3076 RecordedNodes.push_back(std::make_pair(N, Parent));
3080 case OPC_RecordChild0: case OPC_RecordChild1:
3081 case OPC_RecordChild2: case OPC_RecordChild3:
3082 case OPC_RecordChild4: case OPC_RecordChild5:
3083 case OPC_RecordChild6: case OPC_RecordChild7: {
3084 unsigned ChildNo = Opcode-OPC_RecordChild0;
3085 if (ChildNo >= N.getNumOperands())
3086 break; // Match fails if out of range child #.
3088 RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
3092 case OPC_RecordMemRef:
3093 MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
3096 case OPC_CaptureGlueInput:
3097 // If the current node has an input glue, capture it in InputGlue.
3098 if (N->getNumOperands() != 0 &&
3099 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
3100 InputGlue = N->getOperand(N->getNumOperands()-1);
3103 case OPC_MoveChild: {
3104 unsigned ChildNo = MatcherTable[MatcherIndex++];
3105 if (ChildNo >= N.getNumOperands())
3106 break; // Match fails if out of range child #.
3107 N = N.getOperand(ChildNo);
3108 NodeStack.push_back(N);
3112 case OPC_MoveChild0: case OPC_MoveChild1:
3113 case OPC_MoveChild2: case OPC_MoveChild3:
3114 case OPC_MoveChild4: case OPC_MoveChild5:
3115 case OPC_MoveChild6: case OPC_MoveChild7: {
3116 unsigned ChildNo = Opcode-OPC_MoveChild0;
3117 if (ChildNo >= N.getNumOperands())
3118 break; // Match fails if out of range child #.
3119 N = N.getOperand(ChildNo);
3120 NodeStack.push_back(N);
3124 case OPC_MoveParent:
3125 // Pop the current node off the NodeStack.
3126 NodeStack.pop_back();
3127 assert(!NodeStack.empty() && "Node stack imbalance!");
3128 N = NodeStack.back();
3132 if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
3135 case OPC_CheckChild0Same: case OPC_CheckChild1Same:
3136 case OPC_CheckChild2Same: case OPC_CheckChild3Same:
3137 if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes,
3138 Opcode-OPC_CheckChild0Same))
3142 case OPC_CheckPatternPredicate:
3143 if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
3145 case OPC_CheckPredicate:
3146 if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
3150 case OPC_CheckComplexPat: {
3151 unsigned CPNum = MatcherTable[MatcherIndex++];
3152 unsigned RecNo = MatcherTable[MatcherIndex++];
3153 assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
3155 // If target can modify DAG during matching, keep the matching state
3157 std::unique_ptr<MatchStateUpdater> MSU;
3158 if (ComplexPatternFuncMutatesDAG())
3159 MSU.reset(new MatchStateUpdater(*CurDAG, &NodeToMatch, RecordedNodes,
3162 if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
3163 RecordedNodes[RecNo].first, CPNum,
3168 case OPC_CheckOpcode:
3169 if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
3173 if (!::CheckType(MatcherTable, MatcherIndex, N, TLI,
3174 CurDAG->getDataLayout()))
3178 case OPC_SwitchOpcode: {
3179 unsigned CurNodeOpcode = N.getOpcode();
3180 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3183 // Get the size of this case.
3184 CaseSize = MatcherTable[MatcherIndex++];
3186 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3187 if (CaseSize == 0) break;
3189 uint16_t Opc = MatcherTable[MatcherIndex++];
3190 Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
3192 // If the opcode matches, then we will execute this case.
3193 if (CurNodeOpcode == Opc)
3196 // Otherwise, skip over this case.
3197 MatcherIndex += CaseSize;
3200 // If no cases matched, bail out.
3201 if (CaseSize == 0) break;
3203 // Otherwise, execute the case we found.
3204 DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart
3205 << " to " << MatcherIndex << "\n");
3209 case OPC_SwitchType: {
3210 MVT CurNodeVT = N.getSimpleValueType();
3211 unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3214 // Get the size of this case.
3215 CaseSize = MatcherTable[MatcherIndex++];
3217 CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3218 if (CaseSize == 0) break;
3220 MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3221 if (CaseVT == MVT::iPTR)
3222 CaseVT = TLI->getPointerTy(CurDAG->getDataLayout());
3224 // If the VT matches, then we will execute this case.
3225 if (CurNodeVT == CaseVT)
3228 // Otherwise, skip over this case.
3229 MatcherIndex += CaseSize;
3232 // If no cases matched, bail out.
3233 if (CaseSize == 0) break;
3235 // Otherwise, execute the case we found.
3236 DEBUG(dbgs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString()
3237 << "] from " << SwitchStart << " to " << MatcherIndex<<'\n');
3240 case OPC_CheckChild0Type: case OPC_CheckChild1Type:
3241 case OPC_CheckChild2Type: case OPC_CheckChild3Type:
3242 case OPC_CheckChild4Type: case OPC_CheckChild5Type:
3243 case OPC_CheckChild6Type: case OPC_CheckChild7Type:
3244 if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
3245 CurDAG->getDataLayout(),
3246 Opcode - OPC_CheckChild0Type))
3249 case OPC_CheckCondCode:
3250 if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
3252 case OPC_CheckValueType:
3253 if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI,
3254 CurDAG->getDataLayout()))
3257 case OPC_CheckInteger:
3258 if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
3260 case OPC_CheckChild0Integer: case OPC_CheckChild1Integer:
3261 case OPC_CheckChild2Integer: case OPC_CheckChild3Integer:
3262 case OPC_CheckChild4Integer:
3263 if (!::CheckChildInteger(MatcherTable, MatcherIndex, N,
3264 Opcode-OPC_CheckChild0Integer)) break;
3266 case OPC_CheckAndImm:
3267 if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
3269 case OPC_CheckOrImm:
3270 if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
3273 case OPC_CheckFoldableChainNode: {
3274 assert(NodeStack.size() != 1 && "No parent node");
3275 // Verify that all intermediate nodes between the root and this one have
3277 bool HasMultipleUses = false;
3278 for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
3279 if (!NodeStack[i].getNode()->hasOneUse()) {
3280 HasMultipleUses = true;
3283 if (HasMultipleUses) break;
3285 // Check to see that the target thinks this is profitable to fold and that
3286 // we can fold it without inducing cycles in the graph.
3287 if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
3289 !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
3290 NodeToMatch, OptLevel,
3291 true/*We validate our own chains*/))
3296 case OPC_EmitInteger: {
3297 MVT::SimpleValueType VT =
3298 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3299 int64_t Val = MatcherTable[MatcherIndex++];
3301 Val = GetVBR(Val, MatcherTable, MatcherIndex);
3302 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3303 CurDAG->getTargetConstant(Val, SDLoc(NodeToMatch),
3307 case OPC_EmitRegister: {
3308 MVT::SimpleValueType VT =
3309 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3310 unsigned RegNo = MatcherTable[MatcherIndex++];
3311 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3312 CurDAG->getRegister(RegNo, VT), nullptr));
3315 case OPC_EmitRegister2: {
3316 // For targets w/ more than 256 register names, the register enum
3317 // values are stored in two bytes in the matcher table (just like
3319 MVT::SimpleValueType VT =
3320 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3321 unsigned RegNo = MatcherTable[MatcherIndex++];
3322 RegNo |= MatcherTable[MatcherIndex++] << 8;
3323 RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3324 CurDAG->getRegister(RegNo, VT), nullptr));
3328 case OPC_EmitConvertToTarget: {
3329 // Convert from IMM/FPIMM to target version.
3330 unsigned RecNo = MatcherTable[MatcherIndex++];
3331 assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget");
3332 SDValue Imm = RecordedNodes[RecNo].first;
3334 if (Imm->getOpcode() == ISD::Constant) {
3335 const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
3336 Imm = CurDAG->getTargetConstant(*Val, SDLoc(NodeToMatch),
3337 Imm.getValueType());
3338 } else if (Imm->getOpcode() == ISD::ConstantFP) {
3339 const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
3340 Imm = CurDAG->getTargetConstantFP(*Val, SDLoc(NodeToMatch),
3341 Imm.getValueType());
3344 RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
3348 case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
3349 case OPC_EmitMergeInputChains1_1: // OPC_EmitMergeInputChains, 1, 1
3350 case OPC_EmitMergeInputChains1_2: { // OPC_EmitMergeInputChains, 1, 2
3351 // These are space-optimized forms of OPC_EmitMergeInputChains.
3352 assert(!InputChain.getNode() &&
3353 "EmitMergeInputChains should be the first chain producing node");
3354 assert(ChainNodesMatched.empty() &&
3355 "Should only have one EmitMergeInputChains per match");
3357 // Read all of the chained nodes.
3358 unsigned RecNo = Opcode - OPC_EmitMergeInputChains1_0;
3359 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
3360 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3362 // FIXME: What if other value results of the node have uses not matched
3364 if (ChainNodesMatched.back() != NodeToMatch &&
3365 !RecordedNodes[RecNo].first.hasOneUse()) {
3366 ChainNodesMatched.clear();
3370 // Merge the input chains if they are not intra-pattern references.
3371 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
3373 if (!InputChain.getNode())
3374 break; // Failed to merge.
3378 case OPC_EmitMergeInputChains: {
3379 assert(!InputChain.getNode() &&
3380 "EmitMergeInputChains should be the first chain producing node");
3381 // This node gets a list of nodes we matched in the input that have
3382 // chains. We want to token factor all of the input chains to these nodes
3383 // together. However, if any of the input chains is actually one of the
3384 // nodes matched in this pattern, then we have an intra-match reference.
3385 // Ignore these because the newly token factored chain should not refer to
3387 unsigned NumChains = MatcherTable[MatcherIndex++];
3388 assert(NumChains != 0 && "Can't TF zero chains");
3390 assert(ChainNodesMatched.empty() &&
3391 "Should only have one EmitMergeInputChains per match");
3393 // Read all of the chained nodes.
3394 for (unsigned i = 0; i != NumChains; ++i) {
3395 unsigned RecNo = MatcherTable[MatcherIndex++];
3396 assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
3397 ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3399 // FIXME: What if other value results of the node have uses not matched
3401 if (ChainNodesMatched.back() != NodeToMatch &&
3402 !RecordedNodes[RecNo].first.hasOneUse()) {
3403 ChainNodesMatched.clear();
3408 // If the inner loop broke out, the match fails.
3409 if (ChainNodesMatched.empty())
3412 // Merge the input chains if they are not intra-pattern references.
3413 InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
3415 if (!InputChain.getNode())
3416 break; // Failed to merge.
3421 case OPC_EmitCopyToReg: {
3422 unsigned RecNo = MatcherTable[MatcherIndex++];
3423 assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg");
3424 unsigned DestPhysReg = MatcherTable[MatcherIndex++];
3426 if (!InputChain.getNode())
3427 InputChain = CurDAG->getEntryNode();
3429 InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
3430 DestPhysReg, RecordedNodes[RecNo].first,
3433 InputGlue = InputChain.getValue(1);
3437 case OPC_EmitNodeXForm: {
3438 unsigned XFormNo = MatcherTable[MatcherIndex++];
3439 unsigned RecNo = MatcherTable[MatcherIndex++];
3440 assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm");
3441 SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
3442 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr));
3445 case OPC_Coverage: {
3446 // This is emitted right before MorphNode/EmitNode.
3447 // So it should be safe to assume that this node has been selected
3448 unsigned index = MatcherTable[MatcherIndex++];
3449 index |= (MatcherTable[MatcherIndex++] << 8);
3450 dbgs() << "COVERED: " << getPatternForIndex(index) << "\n";
3451 dbgs() << "INCLUDED: " << getIncludePathForIndex(index) << "\n";
3455 case OPC_EmitNode: case OPC_MorphNodeTo:
3456 case OPC_EmitNode0: case OPC_EmitNode1: case OPC_EmitNode2:
3457 case OPC_MorphNodeTo0: case OPC_MorphNodeTo1: case OPC_MorphNodeTo2: {
3458 uint16_t TargetOpc = MatcherTable[MatcherIndex++];
3459 TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
3460 unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
3461 // Get the result VT list.
3463 // If this is one of the compressed forms, get the number of VTs based
3464 // on the Opcode. Otherwise read the next byte from the table.
3465 if (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2)
3466 NumVTs = Opcode - OPC_MorphNodeTo0;
3467 else if (Opcode >= OPC_EmitNode0 && Opcode <= OPC_EmitNode2)
3468 NumVTs = Opcode - OPC_EmitNode0;
3470 NumVTs = MatcherTable[MatcherIndex++];
3471 SmallVector<EVT, 4> VTs;
3472 for (unsigned i = 0; i != NumVTs; ++i) {
3473 MVT::SimpleValueType VT =
3474 (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3475 if (VT == MVT::iPTR)
3476 VT = TLI->getPointerTy(CurDAG->getDataLayout()).SimpleTy;
3480 if (EmitNodeInfo & OPFL_Chain)
3481 VTs.push_back(MVT::Other);
3482 if (EmitNodeInfo & OPFL_GlueOutput)
3483 VTs.push_back(MVT::Glue);
3485 // This is hot code, so optimize the two most common cases of 1 and 2
3488 if (VTs.size() == 1)
3489 VTList = CurDAG->getVTList(VTs[0]);
3490 else if (VTs.size() == 2)
3491 VTList = CurDAG->getVTList(VTs[0], VTs[1]);
3493 VTList = CurDAG->getVTList(VTs);
3495 // Get the operand list.
3496 unsigned NumOps = MatcherTable[MatcherIndex++];
3497 SmallVector<SDValue, 8> Ops;
3498 for (unsigned i = 0; i != NumOps; ++i) {
3499 unsigned RecNo = MatcherTable[MatcherIndex++];
3501 RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
3503 assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
3504 Ops.push_back(RecordedNodes[RecNo].first);
3507 // If there are variadic operands to add, handle them now.
3508 if (EmitNodeInfo & OPFL_VariadicInfo) {
3509 // Determine the start index to copy from.
3510 unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
3511 FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
3512 assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
3513 "Invalid variadic node");
3514 // Copy all of the variadic operands, not including a potential glue
3516 for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
3518 SDValue V = NodeToMatch->getOperand(i);
3519 if (V.getValueType() == MVT::Glue) break;
3524 // If this has chain/glue inputs, add them.
3525 if (EmitNodeInfo & OPFL_Chain)
3526 Ops.push_back(InputChain);
3527 if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr)
3528 Ops.push_back(InputGlue);
3531 SDNode *Res = nullptr;
3532 bool IsMorphNodeTo = Opcode == OPC_MorphNodeTo ||
3533 (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2);
3534 if (!IsMorphNodeTo) {
3535 // If this is a normal EmitNode command, just create the new node and
3536 // add the results to the RecordedNodes list.
3537 Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
3540 // Add all the non-glue/non-chain results to the RecordedNodes list.
3541 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
3542 if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
3543 RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
3547 assert(NodeToMatch->getOpcode() != ISD::DELETED_NODE &&
3548 "NodeToMatch was removed partway through selection");
3549 SelectionDAG::DAGNodeDeletedListener NDL(*CurDAG, [&](SDNode *N,
3551 auto &Chain = ChainNodesMatched;
3552 assert((!E || !is_contained(Chain, N)) &&
3553 "Chain node replaced during MorphNode");
3554 Chain.erase(std::remove(Chain.begin(), Chain.end(), N), Chain.end());
3556 Res = MorphNode(NodeToMatch, TargetOpc, VTList, Ops, EmitNodeInfo);
3559 // If the node had chain/glue results, update our notion of the current
3561 if (EmitNodeInfo & OPFL_GlueOutput) {
3562 InputGlue = SDValue(Res, VTs.size()-1);
3563 if (EmitNodeInfo & OPFL_Chain)
3564 InputChain = SDValue(Res, VTs.size()-2);
3565 } else if (EmitNodeInfo & OPFL_Chain)
3566 InputChain = SDValue(Res, VTs.size()-1);
3568 // If the OPFL_MemRefs glue is set on this node, slap all of the
3569 // accumulated memrefs onto it.
3571 // FIXME: This is vastly incorrect for patterns with multiple outputs
3572 // instructions that access memory and for ComplexPatterns that match
3574 if (EmitNodeInfo & OPFL_MemRefs) {
3575 // Only attach load or store memory operands if the generated
3576 // instruction may load or store.
3577 const MCInstrDesc &MCID = TII->get(TargetOpc);
3578 bool mayLoad = MCID.mayLoad();
3579 bool mayStore = MCID.mayStore();
3581 unsigned NumMemRefs = 0;
3582 for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
3583 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
3584 if ((*I)->isLoad()) {
3587 } else if ((*I)->isStore()) {
3595 MachineSDNode::mmo_iterator MemRefs =
3596 MF->allocateMemRefsArray(NumMemRefs);
3598 MachineSDNode::mmo_iterator MemRefsPos = MemRefs;
3599 for (SmallVectorImpl<MachineMemOperand *>::const_iterator I =
3600 MatchedMemRefs.begin(), E = MatchedMemRefs.end(); I != E; ++I) {
3601 if ((*I)->isLoad()) {
3604 } else if ((*I)->isStore()) {
3612 cast<MachineSDNode>(Res)
3613 ->setMemRefs(MemRefs, MemRefs + NumMemRefs);
3617 << (IsMorphNodeTo ? "Morphed" : "Created")
3618 << " node: "; Res->dump(CurDAG); dbgs() << "\n");
3620 // If this was a MorphNodeTo then we're completely done!
3621 if (IsMorphNodeTo) {
3622 // Update chain uses.
3623 UpdateChains(Res, InputChain, ChainNodesMatched, true);
3629 case OPC_CompleteMatch: {
3630 // The match has been completed, and any new nodes (if any) have been
3631 // created. Patch up references to the matched dag to use the newly
3633 unsigned NumResults = MatcherTable[MatcherIndex++];
3635 for (unsigned i = 0; i != NumResults; ++i) {
3636 unsigned ResSlot = MatcherTable[MatcherIndex++];
3638 ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
3640 assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch");
3641 SDValue Res = RecordedNodes[ResSlot].first;
3643 assert(i < NodeToMatch->getNumValues() &&
3644 NodeToMatch->getValueType(i) != MVT::Other &&
3645 NodeToMatch->getValueType(i) != MVT::Glue &&
3646 "Invalid number of results to complete!");
3647 assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
3648 NodeToMatch->getValueType(i) == MVT::iPTR ||
3649 Res.getValueType() == MVT::iPTR ||
3650 NodeToMatch->getValueType(i).getSizeInBits() ==
3651 Res.getValueSizeInBits()) &&
3652 "invalid replacement");
3653 CurDAG->ReplaceAllUsesOfValueWith(SDValue(NodeToMatch, i), Res);
3656 // Update chain uses.
3657 UpdateChains(NodeToMatch, InputChain, ChainNodesMatched, false);
3659 // If the root node defines glue, we need to update it to the glue result.
3660 // TODO: This never happens in our tests and I think it can be removed /
3661 // replaced with an assert, but if we do it this the way the change is
3663 if (NodeToMatch->getValueType(NodeToMatch->getNumValues() - 1) ==
3665 InputGlue.getNode())
3666 CurDAG->ReplaceAllUsesOfValueWith(
3667 SDValue(NodeToMatch, NodeToMatch->getNumValues() - 1), InputGlue);
3669 assert(NodeToMatch->use_empty() &&
3670 "Didn't replace all uses of the node?");
3671 CurDAG->RemoveDeadNode(NodeToMatch);
3677 // If the code reached this point, then the match failed. See if there is
3678 // another child to try in the current 'Scope', otherwise pop it until we
3679 // find a case to check.
3680 DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex << "\n");
3681 ++NumDAGIselRetries;
3683 if (MatchScopes.empty()) {
3684 CannotYetSelect(NodeToMatch);
3688 // Restore the interpreter state back to the point where the scope was
3690 MatchScope &LastScope = MatchScopes.back();
3691 RecordedNodes.resize(LastScope.NumRecordedNodes);
3693 NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
3694 N = NodeStack.back();
3696 if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
3697 MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
3698 MatcherIndex = LastScope.FailIndex;
3700 DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n");
3702 InputChain = LastScope.InputChain;
3703 InputGlue = LastScope.InputGlue;
3704 if (!LastScope.HasChainNodesMatched)
3705 ChainNodesMatched.clear();
3707 // Check to see what the offset is at the new MatcherIndex. If it is zero
3708 // we have reached the end of this scope, otherwise we have another child
3709 // in the current scope to try.
3710 unsigned NumToSkip = MatcherTable[MatcherIndex++];
3711 if (NumToSkip & 128)
3712 NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
3714 // If we have another child in this scope to match, update FailIndex and
3716 if (NumToSkip != 0) {
3717 LastScope.FailIndex = MatcherIndex+NumToSkip;
3721 // End of this scope, pop it and try the next child in the containing
3723 MatchScopes.pop_back();
3728 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
3730 raw_string_ostream Msg(msg);
3731 Msg << "Cannot select: ";
3733 if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
3734 N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
3735 N->getOpcode() != ISD::INTRINSIC_VOID) {
3736 N->printrFull(Msg, CurDAG);
3737 Msg << "\nIn function: " << MF->getName();
3739 bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
3741 cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
3742 if (iid < Intrinsic::num_intrinsics)
3743 Msg << "intrinsic %" << Intrinsic::getName((Intrinsic::ID)iid, None);
3744 else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
3745 Msg << "target intrinsic %" << TII->getName(iid);
3747 Msg << "unknown intrinsic #" << iid;
3749 report_fatal_error(Msg.str());
3752 char SelectionDAGISel::ID = 0;