LLVM  14.0.0git
SelectionDAGISel.cpp
Go to the documentation of this file.
1 //===- SelectionDAGISel.cpp - Implement the SelectionDAGISel class --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This implements the SelectionDAGISel class.
10 //
11 //===----------------------------------------------------------------------===//
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"
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"
28 #include "llvm/Analysis/CFG.h"
36 #include "llvm/CodeGen/FastISel.h"
61 #include "llvm/IR/BasicBlock.h"
62 #include "llvm/IR/Constants.h"
63 #include "llvm/IR/DataLayout.h"
65 #include "llvm/IR/DebugLoc.h"
66 #include "llvm/IR/DiagnosticInfo.h"
67 #include "llvm/IR/Dominators.h"
68 #include "llvm/IR/Function.h"
69 #include "llvm/IR/InlineAsm.h"
70 #include "llvm/IR/InstIterator.h"
71 #include "llvm/IR/InstrTypes.h"
72 #include "llvm/IR/Instruction.h"
73 #include "llvm/IR/Instructions.h"
74 #include "llvm/IR/IntrinsicInst.h"
75 #include "llvm/IR/Intrinsics.h"
76 #include "llvm/IR/IntrinsicsWebAssembly.h"
77 #include "llvm/IR/Metadata.h"
78 #include "llvm/IR/Statepoint.h"
79 #include "llvm/IR/Type.h"
80 #include "llvm/IR/User.h"
81 #include "llvm/IR/Value.h"
82 #include "llvm/InitializePasses.h"
83 #include "llvm/MC/MCInstrDesc.h"
84 #include "llvm/MC/MCRegisterInfo.h"
85 #include "llvm/Pass.h"
87 #include "llvm/Support/Casting.h"
88 #include "llvm/Support/CodeGen.h"
90 #include "llvm/Support/Compiler.h"
91 #include "llvm/Support/Debug.h"
93 #include "llvm/Support/KnownBits.h"
95 #include "llvm/Support/Timer.h"
101 #include <algorithm>
102 #include <cassert>
103 #include <cstdint>
104 #include <iterator>
105 #include <limits>
106 #include <memory>
107 #include <string>
108 #include <utility>
109 #include <vector>
110 
111 using namespace llvm;
112 
113 #define DEBUG_TYPE "isel"
114 
115 STATISTIC(NumFastIselFailures, "Number of instructions fast isel failed on");
116 STATISTIC(NumFastIselSuccess, "Number of instructions fast isel selected");
117 STATISTIC(NumFastIselBlocks, "Number of blocks selected entirely by fast isel");
118 STATISTIC(NumDAGBlocks, "Number of blocks selected using DAG");
119 STATISTIC(NumDAGIselRetries,"Number of times dag isel has to try another path");
120 STATISTIC(NumEntryBlocks, "Number of entry blocks encountered");
121 STATISTIC(NumFastIselFailLowerArguments,
122  "Number of entry blocks where fast isel failed to lower arguments");
123 
125  "fast-isel-abort", cl::Hidden,
126  cl::desc("Enable abort calls when \"fast\" instruction selection "
127  "fails to lower an instruction: 0 disable the abort, 1 will "
128  "abort but for args, calls and terminators, 2 will also "
129  "abort for argument lowering, and 3 will never fallback "
130  "to SelectionDAG."));
131 
133  "fast-isel-report-on-fallback", cl::Hidden,
134  cl::desc("Emit a diagnostic when \"fast\" instruction selection "
135  "falls back to SelectionDAG."));
136 
137 static cl::opt<bool>
138 UseMBPI("use-mbpi",
139  cl::desc("use Machine Branch Probability Info"),
140  cl::init(true), cl::Hidden);
141 
142 #ifndef NDEBUG
144 FilterDAGBasicBlockName("filter-view-dags", cl::Hidden,
145  cl::desc("Only display the basic block whose name "
146  "matches this for all view-*-dags options"));
147 static cl::opt<bool>
148 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
149  cl::desc("Pop up a window to show dags before the first "
150  "dag combine pass"));
151 static cl::opt<bool>
152 ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
153  cl::desc("Pop up a window to show dags before legalize types"));
154 static cl::opt<bool>
155  ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
156  cl::desc("Pop up a window to show dags before the post "
157  "legalize types dag combine pass"));
158 static cl::opt<bool>
159  ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
160  cl::desc("Pop up a window to show dags before legalize"));
161 static cl::opt<bool>
162 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
163  cl::desc("Pop up a window to show dags before the second "
164  "dag combine pass"));
165 static cl::opt<bool>
166 ViewISelDAGs("view-isel-dags", cl::Hidden,
167  cl::desc("Pop up a window to show isel dags as they are selected"));
168 static cl::opt<bool>
169 ViewSchedDAGs("view-sched-dags", cl::Hidden,
170  cl::desc("Pop up a window to show sched dags as they are processed"));
171 static cl::opt<bool>
172 ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
173  cl::desc("Pop up a window to show SUnit dags after they are processed"));
174 #else
175 static const bool ViewDAGCombine1 = false, ViewLegalizeTypesDAGs = false,
176  ViewDAGCombineLT = false, ViewLegalizeDAGs = false,
177  ViewDAGCombine2 = false, ViewISelDAGs = false,
178  ViewSchedDAGs = false, ViewSUnitDAGs = false;
179 #endif
180 
181 //===---------------------------------------------------------------------===//
182 ///
183 /// RegisterScheduler class - Track the registration of instruction schedulers.
184 ///
185 //===---------------------------------------------------------------------===//
188 
189 //===---------------------------------------------------------------------===//
190 ///
191 /// ISHeuristic command line option for instruction schedulers.
192 ///
193 //===---------------------------------------------------------------------===//
196 ISHeuristic("pre-RA-sched",
198  cl::desc("Instruction schedulers available (before register"
199  " allocation):"));
200 
201 static RegisterScheduler
202 defaultListDAGScheduler("default", "Best scheduler for the target",
204 
205 namespace llvm {
206 
207  //===--------------------------------------------------------------------===//
208  /// This class is used by SelectionDAGISel to temporarily override
209  /// the optimization level on a per-function basis.
211  SelectionDAGISel &IS;
212  CodeGenOpt::Level SavedOptLevel;
213  bool SavedFastISel;
214 
215  public:
217  CodeGenOpt::Level NewOptLevel) : IS(ISel) {
218  SavedOptLevel = IS.OptLevel;
219  SavedFastISel = IS.TM.Options.EnableFastISel;
220  if (NewOptLevel == SavedOptLevel)
221  return;
222  IS.OptLevel = NewOptLevel;
223  IS.TM.setOptLevel(NewOptLevel);
224  LLVM_DEBUG(dbgs() << "\nChanging optimization level for Function "
225  << IS.MF->getFunction().getName() << "\n");
226  LLVM_DEBUG(dbgs() << "\tBefore: -O" << SavedOptLevel << " ; After: -O"
227  << NewOptLevel << "\n");
228  if (NewOptLevel == CodeGenOpt::None) {
230  LLVM_DEBUG(
231  dbgs() << "\tFastISel is "
232  << (IS.TM.Options.EnableFastISel ? "enabled" : "disabled")
233  << "\n");
234  }
235  }
236 
238  if (IS.OptLevel == SavedOptLevel)
239  return;
240  LLVM_DEBUG(dbgs() << "\nRestoring optimization level for Function "
241  << IS.MF->getFunction().getName() << "\n");
242  LLVM_DEBUG(dbgs() << "\tBefore: -O" << IS.OptLevel << " ; After: -O"
243  << SavedOptLevel << "\n");
244  IS.OptLevel = SavedOptLevel;
245  IS.TM.setOptLevel(SavedOptLevel);
246  IS.TM.setFastISel(SavedFastISel);
247  }
248  };
249 
250  //===--------------------------------------------------------------------===//
251  /// createDefaultScheduler - This creates an instruction scheduler appropriate
252  /// for the target.
254  CodeGenOpt::Level OptLevel) {
255  const TargetLowering *TLI = IS->TLI;
256  const TargetSubtargetInfo &ST = IS->MF->getSubtarget();
257 
258  // Try first to see if the Target has its own way of selecting a scheduler
259  if (auto *SchedulerCtor = ST.getDAGScheduler(OptLevel)) {
260  return SchedulerCtor(IS, OptLevel);
261  }
262 
263  if (OptLevel == CodeGenOpt::None ||
264  (ST.enableMachineScheduler() && ST.enableMachineSchedDefaultSched()) ||
266  return createSourceListDAGScheduler(IS, OptLevel);
268  return createBURRListDAGScheduler(IS, OptLevel);
270  return createHybridListDAGScheduler(IS, OptLevel);
271  if (TLI->getSchedulingPreference() == Sched::VLIW)
272  return createVLIWDAGScheduler(IS, OptLevel);
273  if (TLI->getSchedulingPreference() == Sched::Fast)
274  return createFastDAGScheduler(IS, OptLevel);
276  return createDAGLinearizer(IS, OptLevel);
278  "Unknown sched type!");
279  return createILPListDAGScheduler(IS, OptLevel);
280  }
281 
282 } // end namespace llvm
283 
284 // EmitInstrWithCustomInserter - This method should be implemented by targets
285 // that mark instructions with the 'usesCustomInserter' flag. These
286 // instructions are special in various ways, which require special support to
287 // insert. The specified MachineInstr is created but not inserted into any
288 // basic blocks, and this method is called to expand it into a sequence of
289 // instructions, potentially also creating new basic blocks and control flow.
290 // When new basic blocks are inserted and the edges from MBB to its successors
291 // are modified, the method should insert pairs of <OldSucc, NewSucc> into the
292 // DenseMap.
295  MachineBasicBlock *MBB) const {
296 #ifndef NDEBUG
297  dbgs() << "If a target marks an instruction with "
298  "'usesCustomInserter', it must implement "
299  "TargetLowering::EmitInstrWithCustomInserter!";
300 #endif
301  llvm_unreachable(nullptr);
302 }
303 
305  SDNode *Node) const {
306  assert(!MI.hasPostISelHook() &&
307  "If a target marks an instruction with 'hasPostISelHook', "
308  "it must implement TargetLowering::AdjustInstrPostInstrSelection!");
309 }
310 
311 //===----------------------------------------------------------------------===//
312 // SelectionDAGISel code
313 //===----------------------------------------------------------------------===//
314 
316  : MachineFunctionPass(ID), TM(tm), FuncInfo(new FunctionLoweringInfo()),
317  SwiftError(new SwiftErrorValueTracking()),
318  CurDAG(new SelectionDAG(tm, OL)),
319  SDB(std::make_unique<SelectionDAGBuilder>(*CurDAG, *FuncInfo, *SwiftError,
320  OL)),
321  AA(), GFI(), OptLevel(OL), DAGSize(0) {
327 }
328 
330  delete CurDAG;
331  delete SwiftError;
332 }
333 
335  if (OptLevel != CodeGenOpt::None)
345  if (OptLevel != CodeGenOpt::None)
348 }
349 
350 /// SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that
351 /// may trap on it. In this case we have to split the edge so that the path
352 /// through the predecessor block that doesn't go to the phi block doesn't
353 /// execute the possibly trapping instruction. If available, we pass domtree
354 /// and loop info to be updated when we split critical edges. This is because
355 /// SelectionDAGISel preserves these analyses.
356 /// This is required for correctness, so it must be done at -O0.
357 ///
359  LoopInfo *LI) {
360  // Loop for blocks with phi nodes.
361  for (BasicBlock &BB : Fn) {
362  PHINode *PN = dyn_cast<PHINode>(BB.begin());
363  if (!PN) continue;
364 
365  ReprocessBlock:
366  // For each block with a PHI node, check to see if any of the input values
367  // are potentially trapping constant expressions. Constant expressions are
368  // the only potentially trapping value that can occur as the argument to a
369  // PHI.
370  for (BasicBlock::iterator I = BB.begin(); (PN = dyn_cast<PHINode>(I)); ++I)
371  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
372  ConstantExpr *CE = dyn_cast<ConstantExpr>(PN->getIncomingValue(i));
373  if (!CE || !CE->canTrap()) continue;
374 
375  // The only case we have to worry about is when the edge is critical.
376  // Since this block has a PHI Node, we assume it has multiple input
377  // edges: check to see if the pred has multiple successors.
378  BasicBlock *Pred = PN->getIncomingBlock(i);
379  if (Pred->getTerminator()->getNumSuccessors() == 1)
380  continue;
381 
382  // Okay, we have to split this edge.
384  Pred->getTerminator(), GetSuccessorNumber(Pred, &BB),
385  CriticalEdgeSplittingOptions(DT, LI).setMergeIdenticalEdges());
386  goto ReprocessBlock;
387  }
388  }
389 }
390 
391 static void computeUsesMSVCFloatingPoint(const Triple &TT, const Function &F,
392  MachineModuleInfo &MMI) {
393  // Only needed for MSVC
394  if (!TT.isWindowsMSVCEnvironment())
395  return;
396 
397  // If it's already set, nothing to do.
398  if (MMI.usesMSVCFloatingPoint())
399  return;
400 
401  for (const Instruction &I : instructions(F)) {
402  if (I.getType()->isFPOrFPVectorTy()) {
403  MMI.setUsesMSVCFloatingPoint(true);
404  return;
405  }
406  for (const auto &Op : I.operands()) {
407  if (Op->getType()->isFPOrFPVectorTy()) {
408  MMI.setUsesMSVCFloatingPoint(true);
409  return;
410  }
411  }
412  }
413 }
414 
416  // If we already selected that function, we do not need to run SDISel.
417  if (mf.getProperties().hasProperty(
419  return false;
420  // Do some sanity-checking on the command-line options.
422  "-fast-isel-abort > 0 requires -fast-isel");
423 
424  const Function &Fn = mf.getFunction();
425  MF = &mf;
426 
427  // Reset the target options before resetting the optimization
428  // level below.
429  // FIXME: This is a horrible hack and should be processed via
430  // codegen looking at the optimization level explicitly when
431  // it wants to look at it.
433  // Reset OptLevel to None for optnone functions.
434  CodeGenOpt::Level NewOptLevel = OptLevel;
435  if (OptLevel != CodeGenOpt::None && skipFunction(Fn))
436  NewOptLevel = CodeGenOpt::None;
437  OptLevelChanger OLC(*this, NewOptLevel);
438 
441  RegInfo = &MF->getRegInfo();
442  LibInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(Fn);
443  GFI = Fn.hasGC() ? &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn) : nullptr;
444  ORE = std::make_unique<OptimizationRemarkEmitter>(&Fn);
445  auto *DTWP = getAnalysisIfAvailable<DominatorTreeWrapperPass>();
446  DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
447  auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
448  LoopInfo *LI = LIWP ? &LIWP->getLoopInfo() : nullptr;
449  auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
450  BlockFrequencyInfo *BFI = nullptr;
451  if (PSI && PSI->hasProfileSummary() && OptLevel != CodeGenOpt::None)
452  BFI = &getAnalysis<LazyBlockFrequencyInfoPass>().getBFI();
453 
454  LLVM_DEBUG(dbgs() << "\n\n\n=== " << Fn.getName() << "\n");
455 
456  SplitCriticalSideEffectEdges(const_cast<Function &>(Fn), DT, LI);
457 
458  CurDAG->init(*MF, *ORE, this, LibInfo,
459  getAnalysisIfAvailable<LegacyDivergenceAnalysis>(), PSI, BFI);
460  FuncInfo->set(Fn, *MF, CurDAG);
462 
463  // Now get the optional analyzes if we want to.
464  // This is based on the possibly changed OptLevel (after optnone is taken
465  // into account). That's unfortunate but OK because it just means we won't
466  // ask for passes that have been required anyway.
467 
469  FuncInfo->BPI = &getAnalysis<BranchProbabilityInfoWrapperPass>().getBPI();
470  else
471  FuncInfo->BPI = nullptr;
472 
473  if (OptLevel != CodeGenOpt::None)
474  AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
475  else
476  AA = nullptr;
477 
478  SDB->init(GFI, AA, LibInfo);
479 
480  MF->setHasInlineAsm(false);
481 
482  FuncInfo->SplitCSR = false;
483 
484  // We split CSR if the target supports it for the given function
485  // and the function has only return exits.
487  FuncInfo->SplitCSR = true;
488 
489  // Collect all the return blocks.
490  for (const BasicBlock &BB : Fn) {
491  if (!succ_empty(&BB))
492  continue;
493 
494  const Instruction *Term = BB.getTerminator();
495  if (isa<UnreachableInst>(Term) || isa<ReturnInst>(Term))
496  continue;
497 
498  // Bail out if the exit block is not Return nor Unreachable.
499  FuncInfo->SplitCSR = false;
500  break;
501  }
502  }
503 
504  MachineBasicBlock *EntryMBB = &MF->front();
505  if (FuncInfo->SplitCSR)
506  // This performs initialization so lowering for SplitCSR will be correct.
507  TLI->initializeSplitCSR(EntryMBB);
508 
509  SelectAllBasicBlocks(Fn);
511  DiagnosticInfoISelFallback DiagFallback(Fn);
512  Fn.getContext().diagnose(DiagFallback);
513  }
514 
515  // Replace forward-declared registers with the registers containing
516  // the desired value.
517  // Note: it is important that this happens **before** the call to
518  // EmitLiveInCopies, since implementations can skip copies of unused
519  // registers. If we don't apply the reg fixups before, some registers may
520  // appear as unused and will be skipped, resulting in bad MI.
522  for (DenseMap<Register, Register>::iterator I = FuncInfo->RegFixups.begin(),
523  E = FuncInfo->RegFixups.end();
524  I != E; ++I) {
525  Register From = I->first;
526  Register To = I->second;
527  // If To is also scheduled to be replaced, find what its ultimate
528  // replacement is.
529  while (true) {
530  DenseMap<Register, Register>::iterator J = FuncInfo->RegFixups.find(To);
531  if (J == E)
532  break;
533  To = J->second;
534  }
535  // Make sure the new register has a sufficiently constrained register class.
538  // Replace it.
539 
540  // Replacing one register with another won't touch the kill flags.
541  // We need to conservatively clear the kill flags as a kill on the old
542  // register might dominate existing uses of the new register.
543  if (!MRI.use_empty(To))
545  MRI.replaceRegWith(From, To);
546  }
547 
548  // If the first basic block in the function has live ins that need to be
549  // copied into vregs, emit the copies into the top of the block before
550  // emitting the code for the block.
552  RegInfo->EmitLiveInCopies(EntryMBB, TRI, *TII);
553 
554  // Insert copies in the entry block and the return blocks.
555  if (FuncInfo->SplitCSR) {
557  // Collect all the return blocks.
558  for (MachineBasicBlock &MBB : mf) {
559  if (!MBB.succ_empty())
560  continue;
561 
563  if (Term != MBB.end() && Term->isReturn()) {
564  Returns.push_back(&MBB);
565  continue;
566  }
567  }
568  TLI->insertCopiesSplitCSR(EntryMBB, Returns);
569  }
570 
572  if (!FuncInfo->ArgDbgValues.empty())
573  for (std::pair<unsigned, unsigned> LI : RegInfo->liveins())
574  if (LI.second)
575  LiveInMap.insert(LI);
576 
577  // Insert DBG_VALUE instructions for function arguments to the entry block.
578  bool InstrRef = TM.Options.ValueTrackingVariableLocations;
579  for (unsigned i = 0, e = FuncInfo->ArgDbgValues.size(); i != e; ++i) {
580  MachineInstr *MI = FuncInfo->ArgDbgValues[e - i - 1];
581  assert(MI->getOpcode() != TargetOpcode::DBG_VALUE_LIST &&
582  "Function parameters should not be described by DBG_VALUE_LIST.");
583  bool hasFI = MI->getOperand(0).isFI();
584  Register Reg =
585  hasFI ? TRI.getFrameRegister(*MF) : MI->getOperand(0).getReg();
587  EntryMBB->insert(EntryMBB->begin(), MI);
588  else {
590  if (Def) {
591  MachineBasicBlock::iterator InsertPos = Def;
592  // FIXME: VR def may not be in entry block.
593  Def->getParent()->insert(std::next(InsertPos), MI);
594  } else
595  LLVM_DEBUG(dbgs() << "Dropping debug info for dead vreg"
596  << Register::virtReg2Index(Reg) << "\n");
597  }
598 
599  // Don't try and extend through copies in instruction referencing mode.
600  if (InstrRef)
601  continue;
602 
603  // If Reg is live-in then update debug info to track its copy in a vreg.
605  if (LDI != LiveInMap.end()) {
606  assert(!hasFI && "There's no handling of frame pointer updating here yet "
607  "- add if needed");
608  MachineInstr *Def = RegInfo->getVRegDef(LDI->second);
609  MachineBasicBlock::iterator InsertPos = Def;
610  const MDNode *Variable = MI->getDebugVariable();
611  const MDNode *Expr = MI->getDebugExpression();
612  DebugLoc DL = MI->getDebugLoc();
613  bool IsIndirect = MI->isIndirectDebugValue();
614  if (IsIndirect)
615  assert(MI->getOperand(1).getImm() == 0 &&
616  "DBG_VALUE with nonzero offset");
617  assert(cast<DILocalVariable>(Variable)->isValidLocationForIntrinsic(DL) &&
618  "Expected inlined-at fields to agree");
619  assert(MI->getOpcode() != TargetOpcode::DBG_VALUE_LIST &&
620  "Didn't expect to see a DBG_VALUE_LIST here");
621  // Def is never a terminator here, so it is ok to increment InsertPos.
622  BuildMI(*EntryMBB, ++InsertPos, DL, TII->get(TargetOpcode::DBG_VALUE),
623  IsIndirect, LDI->second, Variable, Expr);
624 
625  // If this vreg is directly copied into an exported register then
626  // that COPY instructions also need DBG_VALUE, if it is the only
627  // user of LDI->second.
628  MachineInstr *CopyUseMI = nullptr;
630  UI = RegInfo->use_instr_begin(LDI->second),
631  E = RegInfo->use_instr_end(); UI != E; ) {
632  MachineInstr *UseMI = &*(UI++);
633  if (UseMI->isDebugValue()) continue;
634  if (UseMI->isCopy() && !CopyUseMI && UseMI->getParent() == EntryMBB) {
635  CopyUseMI = UseMI; continue;
636  }
637  // Otherwise this is another use or second copy use.
638  CopyUseMI = nullptr; break;
639  }
640  if (CopyUseMI &&
641  TRI.getRegSizeInBits(LDI->second, MRI) ==
642  TRI.getRegSizeInBits(CopyUseMI->getOperand(0).getReg(), MRI)) {
643  // Use MI's debug location, which describes where Variable was
644  // declared, rather than whatever is attached to CopyUseMI.
645  MachineInstr *NewMI =
646  BuildMI(*MF, DL, TII->get(TargetOpcode::DBG_VALUE), IsIndirect,
647  CopyUseMI->getOperand(0).getReg(), Variable, Expr);
648  MachineBasicBlock::iterator Pos = CopyUseMI;
649  EntryMBB->insertAfter(Pos, NewMI);
650  }
651  }
652  }
653 
654  // For debug-info, in instruction referencing mode, we need to perform some
655  // post-isel maintenence.
657 
658  // Determine if there are any calls in this machine function.
659  MachineFrameInfo &MFI = MF->getFrameInfo();
660  for (const auto &MBB : *MF) {
661  if (MFI.hasCalls() && MF->hasInlineAsm())
662  break;
663 
664  for (const auto &MI : MBB) {
665  const MCInstrDesc &MCID = TII->get(MI.getOpcode());
666  if ((MCID.isCall() && !MCID.isReturn()) ||
667  MI.isStackAligningInlineAsm()) {
668  MFI.setHasCalls(true);
669  }
670  if (MI.isInlineAsm()) {
671  MF->setHasInlineAsm(true);
672  }
673  }
674  }
675 
676  // Determine if there is a call to setjmp in the machine function.
678 
679  // Determine if floating point is used for msvc
681 
682  // Release function-specific state. SDB and CurDAG are already cleared
683  // at this point.
684  FuncInfo->clear();
685 
686  LLVM_DEBUG(dbgs() << "*** MachineFunction at end of ISel ***\n");
687  LLVM_DEBUG(MF->print(dbgs()));
688 
689  return true;
690 }
691 
695  bool ShouldAbort) {
696  // Print the function name explicitly if we don't have a debug location (which
697  // makes the diagnostic less useful) or if we're going to emit a raw error.
698  if (!R.getLocation().isValid() || ShouldAbort)
699  R << (" (in function: " + MF.getName() + ")").str();
700 
701  if (ShouldAbort)
702  report_fatal_error(R.getMsg());
703 
704  ORE.emit(R);
705 }
706 
707 void SelectionDAGISel::SelectBasicBlock(BasicBlock::const_iterator Begin,
709  bool &HadTailCall) {
710  // Allow creating illegal types during DAG building for the basic block.
712 
713  // Lower the instructions. If a call is emitted as a tail call, cease emitting
714  // nodes for this block.
715  for (BasicBlock::const_iterator I = Begin; I != End && !SDB->HasTailCall; ++I) {
716  if (!ElidedArgCopyInstrs.count(&*I))
717  SDB->visit(*I);
718  }
719 
720  // Make sure the root of the DAG is up-to-date.
721  CurDAG->setRoot(SDB->getControlRoot());
722  HadTailCall = SDB->HasTailCall;
723  SDB->resolveOrClearDbgInfo();
724  SDB->clear();
725 
726  // Final step, emit the lowered DAG as machine code.
727  CodeGenAndEmitDAG();
728 }
729 
730 void SelectionDAGISel::ComputeLiveOutVRegInfo() {
732  SmallVector<SDNode*, 128> Worklist;
733 
734  Worklist.push_back(CurDAG->getRoot().getNode());
735  Added.insert(CurDAG->getRoot().getNode());
736 
737  KnownBits Known;
738 
739  do {
740  SDNode *N = Worklist.pop_back_val();
741 
742  // Otherwise, add all chain operands to the worklist.
743  for (const SDValue &Op : N->op_values())
744  if (Op.getValueType() == MVT::Other && Added.insert(Op.getNode()).second)
745  Worklist.push_back(Op.getNode());
746 
747  // If this is a CopyToReg with a vreg dest, process it.
748  if (N->getOpcode() != ISD::CopyToReg)
749  continue;
750 
751  unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
752  if (!Register::isVirtualRegister(DestReg))
753  continue;
754 
755  // Ignore non-integer values.
756  SDValue Src = N->getOperand(2);
757  EVT SrcVT = Src.getValueType();
758  if (!SrcVT.isInteger())
759  continue;
760 
761  unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
762  Known = CurDAG->computeKnownBits(Src);
763  FuncInfo->AddLiveOutRegInfo(DestReg, NumSignBits, Known);
764  } while (!Worklist.empty());
765 }
766 
767 void SelectionDAGISel::CodeGenAndEmitDAG() {
768  StringRef GroupName = "sdag";
769  StringRef GroupDescription = "Instruction Selection and Scheduling";
770  std::string BlockName;
771  bool MatchFilterBB = false; (void)MatchFilterBB;
772 #ifndef NDEBUG
774  getAnalysis<TargetTransformInfoWrapperPass>().getTTI(*FuncInfo->Fn);
775 #endif
776 
777  // Pre-type legalization allow creation of any node types.
779 
780 #ifndef NDEBUG
781  MatchFilterBB = (FilterDAGBasicBlockName.empty() ||
783  FuncInfo->MBB->getBasicBlock()->getName());
784 #endif
785 #ifdef NDEBUG
789 #endif
790  {
791  BlockName =
792  (MF->getName() + ":" + FuncInfo->MBB->getBasicBlock()->getName()).str();
793  }
794  LLVM_DEBUG(dbgs() << "Initial selection DAG: "
795  << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
796  << "'\n";
797  CurDAG->dump());
798 
799 #ifndef NDEBUG
800  if (TTI.hasBranchDivergence())
802 #endif
803 
804  if (ViewDAGCombine1 && MatchFilterBB)
805  CurDAG->viewGraph("dag-combine1 input for " + BlockName);
806 
807  // Run the DAG combiner in pre-legalize mode.
808  {
809  NamedRegionTimer T("combine1", "DAG Combining 1", GroupName,
810  GroupDescription, TimePassesIsEnabled);
812  }
813 
814  LLVM_DEBUG(dbgs() << "Optimized lowered selection DAG: "
815  << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
816  << "'\n";
817  CurDAG->dump());
818 
819 #ifndef NDEBUG
820  if (TTI.hasBranchDivergence())
822 #endif
823 
824  // Second step, hack on the DAG until it only uses operations and types that
825  // the target supports.
826  if (ViewLegalizeTypesDAGs && MatchFilterBB)
827  CurDAG->viewGraph("legalize-types input for " + BlockName);
828 
829  bool Changed;
830  {
831  NamedRegionTimer T("legalize_types", "Type Legalization", GroupName,
832  GroupDescription, TimePassesIsEnabled);
833  Changed = CurDAG->LegalizeTypes();
834  }
835 
836  LLVM_DEBUG(dbgs() << "Type-legalized selection DAG: "
837  << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
838  << "'\n";
839  CurDAG->dump());
840 
841 #ifndef NDEBUG
842  if (TTI.hasBranchDivergence())
844 #endif
845 
846  // Only allow creation of legal node types.
848 
849  if (Changed) {
850  if (ViewDAGCombineLT && MatchFilterBB)
851  CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
852 
853  // Run the DAG combiner in post-type-legalize mode.
854  {
855  NamedRegionTimer T("combine_lt", "DAG Combining after legalize types",
856  GroupName, GroupDescription, TimePassesIsEnabled);
858  }
859 
860  LLVM_DEBUG(dbgs() << "Optimized type-legalized selection DAG: "
861  << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
862  << "'\n";
863  CurDAG->dump());
864 
865 #ifndef NDEBUG
866  if (TTI.hasBranchDivergence())
868 #endif
869  }
870 
871  {
872  NamedRegionTimer T("legalize_vec", "Vector Legalization", GroupName,
873  GroupDescription, TimePassesIsEnabled);
874  Changed = CurDAG->LegalizeVectors();
875  }
876 
877  if (Changed) {
878  LLVM_DEBUG(dbgs() << "Vector-legalized selection DAG: "
879  << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
880  << "'\n";
881  CurDAG->dump());
882 
883 #ifndef NDEBUG
884  if (TTI.hasBranchDivergence())
886 #endif
887 
888  {
889  NamedRegionTimer T("legalize_types2", "Type Legalization 2", GroupName,
890  GroupDescription, TimePassesIsEnabled);
892  }
893 
894  LLVM_DEBUG(dbgs() << "Vector/type-legalized selection DAG: "
895  << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
896  << "'\n";
897  CurDAG->dump());
898 
899 #ifndef NDEBUG
900  if (TTI.hasBranchDivergence())
902 #endif
903 
904  if (ViewDAGCombineLT && MatchFilterBB)
905  CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
906 
907  // Run the DAG combiner in post-type-legalize mode.
908  {
909  NamedRegionTimer T("combine_lv", "DAG Combining after legalize vectors",
910  GroupName, GroupDescription, TimePassesIsEnabled);
912  }
913 
914  LLVM_DEBUG(dbgs() << "Optimized vector-legalized selection DAG: "
915  << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
916  << "'\n";
917  CurDAG->dump());
918 
919 #ifndef NDEBUG
920  if (TTI.hasBranchDivergence())
922 #endif
923  }
924 
925  if (ViewLegalizeDAGs && MatchFilterBB)
926  CurDAG->viewGraph("legalize input for " + BlockName);
927 
928  {
929  NamedRegionTimer T("legalize", "DAG Legalization", GroupName,
930  GroupDescription, TimePassesIsEnabled);
931  CurDAG->Legalize();
932  }
933 
934  LLVM_DEBUG(dbgs() << "Legalized selection DAG: "
935  << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
936  << "'\n";
937  CurDAG->dump());
938 
939 #ifndef NDEBUG
940  if (TTI.hasBranchDivergence())
942 #endif
943 
944  if (ViewDAGCombine2 && MatchFilterBB)
945  CurDAG->viewGraph("dag-combine2 input for " + BlockName);
946 
947  // Run the DAG combiner in post-legalize mode.
948  {
949  NamedRegionTimer T("combine2", "DAG Combining 2", GroupName,
950  GroupDescription, TimePassesIsEnabled);
952  }
953 
954  LLVM_DEBUG(dbgs() << "Optimized legalized selection DAG: "
955  << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
956  << "'\n";
957  CurDAG->dump());
958 
959 #ifndef NDEBUG
960  if (TTI.hasBranchDivergence())
962 #endif
963 
964  if (OptLevel != CodeGenOpt::None)
965  ComputeLiveOutVRegInfo();
966 
967  if (ViewISelDAGs && MatchFilterBB)
968  CurDAG->viewGraph("isel input for " + BlockName);
969 
970  // Third, instruction select all of the operations to machine code, adding the
971  // code to the MachineBasicBlock.
972  {
973  NamedRegionTimer T("isel", "Instruction Selection", GroupName,
974  GroupDescription, TimePassesIsEnabled);
975  DoInstructionSelection();
976  }
977 
978  LLVM_DEBUG(dbgs() << "Selected selection DAG: "
979  << printMBBReference(*FuncInfo->MBB) << " '" << BlockName
980  << "'\n";
981  CurDAG->dump());
982 
983  if (ViewSchedDAGs && MatchFilterBB)
984  CurDAG->viewGraph("scheduler input for " + BlockName);
985 
986  // Schedule machine code.
987  ScheduleDAGSDNodes *Scheduler = CreateScheduler();
988  {
989  NamedRegionTimer T("sched", "Instruction Scheduling", GroupName,
990  GroupDescription, TimePassesIsEnabled);
991  Scheduler->Run(CurDAG, FuncInfo->MBB);
992  }
993 
994  if (ViewSUnitDAGs && MatchFilterBB)
995  Scheduler->viewGraph();
996 
997  // Emit machine code to BB. This can change 'BB' to the last block being
998  // inserted into.
999  MachineBasicBlock *FirstMBB = FuncInfo->MBB, *LastMBB;
1000  {
1001  NamedRegionTimer T("emit", "Instruction Creation", GroupName,
1002  GroupDescription, TimePassesIsEnabled);
1003 
1004  // FuncInfo->InsertPt is passed by reference and set to the end of the
1005  // scheduled instructions.
1006  LastMBB = FuncInfo->MBB = Scheduler->EmitSchedule(FuncInfo->InsertPt);
1007  }
1008 
1009  // If the block was split, make sure we update any references that are used to
1010  // update PHI nodes later on.
1011  if (FirstMBB != LastMBB)
1012  SDB->UpdateSplitBlock(FirstMBB, LastMBB);
1013 
1014  // Free the scheduler state.
1015  {
1016  NamedRegionTimer T("cleanup", "Instruction Scheduling Cleanup", GroupName,
1017  GroupDescription, TimePassesIsEnabled);
1018  delete Scheduler;
1019  }
1020 
1021  // Free the SelectionDAG state, now that we're finished with it.
1022  CurDAG->clear();
1023 }
1024 
1025 namespace {
1026 
1027 /// ISelUpdater - helper class to handle updates of the instruction selection
1028 /// graph.
1029 class ISelUpdater : public SelectionDAG::DAGUpdateListener {
1030  SelectionDAG::allnodes_iterator &ISelPosition;
1031 
1032 public:
1033  ISelUpdater(SelectionDAG &DAG, SelectionDAG::allnodes_iterator &isp)
1034  : SelectionDAG::DAGUpdateListener(DAG), ISelPosition(isp) {}
1035 
1036  /// NodeDeleted - Handle nodes deleted from the graph. If the node being
1037  /// deleted is the current ISelPosition node, update ISelPosition.
1038  ///
1039  void NodeDeleted(SDNode *N, SDNode *E) override {
1040  if (ISelPosition == SelectionDAG::allnodes_iterator(N))
1041  ++ISelPosition;
1042  }
1043 };
1044 
1045 } // end anonymous namespace
1046 
1047 // This function is used to enforce the topological node id property
1048 // property leveraged during Instruction selection. Before selection all
1049 // nodes are given a non-negative id such that all nodes have a larger id than
1050 // their operands. As this holds transitively we can prune checks that a node N
1051 // is a predecessor of M another by not recursively checking through M's
1052 // operands if N's ID is larger than M's ID. This is significantly improves
1053 // performance of for various legality checks (e.g. IsLegalToFold /
1054 // UpdateChains).
1055 
1056 // However, when we fuse multiple nodes into a single node
1057 // during selection we may induce a predecessor relationship between inputs and
1058 // outputs of distinct nodes being merged violating the topological property.
1059 // Should a fused node have a successor which has yet to be selected, our
1060 // legality checks would be incorrect. To avoid this we mark all unselected
1061 // sucessor nodes, i.e. id != -1 as invalid for pruning by bit-negating (x =>
1062 // (-(x+1))) the ids and modify our pruning check to ignore negative Ids of M.
1063 // We use bit-negation to more clearly enforce that node id -1 can only be
1064 // achieved by selected nodes). As the conversion is reversable the original Id,
1065 // topological pruning can still be leveraged when looking for unselected nodes.
1066 // This method is call internally in all ISel replacement calls.
1069  Nodes.push_back(Node);
1070 
1071  while (!Nodes.empty()) {
1072  SDNode *N = Nodes.pop_back_val();
1073  for (auto *U : N->uses()) {
1074  auto UId = U->getNodeId();
1075  if (UId > 0) {
1076  InvalidateNodeId(U);
1077  Nodes.push_back(U);
1078  }
1079  }
1080  }
1081 }
1082 
1083 // InvalidateNodeId - As discusses in EnforceNodeIdInvariant, mark a
1084 // NodeId with the equivalent node id which is invalid for topological
1085 // pruning.
1087  int InvalidId = -(N->getNodeId() + 1);
1088  N->setNodeId(InvalidId);
1089 }
1090 
1091 // getUninvalidatedNodeId - get original uninvalidated node id.
1093  int Id = N->getNodeId();
1094  if (Id < -1)
1095  return -(Id + 1);
1096  return Id;
1097 }
1098 
1099 void SelectionDAGISel::DoInstructionSelection() {
1100  LLVM_DEBUG(dbgs() << "===== Instruction selection begins: "
1101  << printMBBReference(*FuncInfo->MBB) << " '"
1102  << FuncInfo->MBB->getName() << "'\n");
1103 
1105 
1106  // Select target instructions for the DAG.
1107  {
1108  // Number all nodes with a topological order and set DAGSize.
1110 
1111  // Create a dummy node (which is not added to allnodes), that adds
1112  // a reference to the root node, preventing it from being deleted,
1113  // and tracking any changes of the root.
1116  ++ISelPosition;
1117 
1118  // Make sure that ISelPosition gets properly updated when nodes are deleted
1119  // in calls made from this function.
1120  ISelUpdater ISU(*CurDAG, ISelPosition);
1121 
1122  // The AllNodes list is now topological-sorted. Visit the
1123  // nodes by starting at the end of the list (the root of the
1124  // graph) and preceding back toward the beginning (the entry
1125  // node).
1126  while (ISelPosition != CurDAG->allnodes_begin()) {
1127  SDNode *Node = &*--ISelPosition;
1128  // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
1129  // but there are currently some corner cases that it misses. Also, this
1130  // makes it theoretically possible to disable the DAGCombiner.
1131  if (Node->use_empty())
1132  continue;
1133 
1134 #ifndef NDEBUG
1136  Nodes.push_back(Node);
1137 
1138  while (!Nodes.empty()) {
1139  auto N = Nodes.pop_back_val();
1140  if (N->getOpcode() == ISD::TokenFactor || N->getNodeId() < 0)
1141  continue;
1142  for (const SDValue &Op : N->op_values()) {
1143  if (Op->getOpcode() == ISD::TokenFactor)
1144  Nodes.push_back(Op.getNode());
1145  else {
1146  // We rely on topological ordering of node ids for checking for
1147  // cycles when fusing nodes during selection. All unselected nodes
1148  // successors of an already selected node should have a negative id.
1149  // This assertion will catch such cases. If this assertion triggers
1150  // it is likely you using DAG-level Value/Node replacement functions
1151  // (versus equivalent ISEL replacement) in backend-specific
1152  // selections. See comment in EnforceNodeIdInvariant for more
1153  // details.
1154  assert(Op->getNodeId() != -1 &&
1155  "Node has already selected predecessor node");
1156  }
1157  }
1158  }
1159 #endif
1160 
1161  // When we are using non-default rounding modes or FP exception behavior
1162  // FP operations are represented by StrictFP pseudo-operations. For
1163  // targets that do not (yet) understand strict FP operations directly,
1164  // we convert them to normal FP opcodes instead at this point. This
1165  // will allow them to be handled by existing target-specific instruction
1166  // selectors.
1167  if (!TLI->isStrictFPEnabled() && Node->isStrictFPOpcode()) {
1168  // For some opcodes, we need to call TLI->getOperationAction using
1169  // the first operand type instead of the result type. Note that this
1170  // must match what SelectionDAGLegalize::LegalizeOp is doing.
1171  EVT ActionVT;
1172  switch (Node->getOpcode()) {
1175  case ISD::STRICT_LRINT:
1176  case ISD::STRICT_LLRINT:
1177  case ISD::STRICT_LROUND:
1178  case ISD::STRICT_LLROUND:
1179  case ISD::STRICT_FSETCC:
1180  case ISD::STRICT_FSETCCS:
1181  ActionVT = Node->getOperand(1).getValueType();
1182  break;
1183  default:
1184  ActionVT = Node->getValueType(0);
1185  break;
1186  }
1187  if (TLI->getOperationAction(Node->getOpcode(), ActionVT)
1189  Node = CurDAG->mutateStrictFPToFP(Node);
1190  }
1191 
1192  LLVM_DEBUG(dbgs() << "\nISEL: Starting selection on root node: ";
1193  Node->dump(CurDAG));
1194 
1195  Select(Node);
1196  }
1197 
1198  CurDAG->setRoot(Dummy.getValue());
1199  }
1200 
1201  LLVM_DEBUG(dbgs() << "\n===== Instruction selection ends:\n");
1202 
1204 }
1205 
1207  for (const User *U : CPI->users()) {
1208  if (const IntrinsicInst *EHPtrCall = dyn_cast<IntrinsicInst>(U)) {
1209  Intrinsic::ID IID = EHPtrCall->getIntrinsicID();
1210  if (IID == Intrinsic::eh_exceptionpointer ||
1211  IID == Intrinsic::eh_exceptioncode)
1212  return true;
1213  }
1214  }
1215  return false;
1216 }
1217 
1218 // wasm.landingpad.index intrinsic is for associating a landing pad index number
1219 // with a catchpad instruction. Retrieve the landing pad index in the intrinsic
1220 // and store the mapping in the function.
1222  const CatchPadInst *CPI) {
1223  MachineFunction *MF = MBB->getParent();
1224  // In case of single catch (...), we don't emit LSDA, so we don't need
1225  // this information.
1226  bool IsSingleCatchAllClause =
1227  CPI->getNumArgOperands() == 1 &&
1228  cast<Constant>(CPI->getArgOperand(0))->isNullValue();
1229  if (!IsSingleCatchAllClause) {
1230  // Create a mapping from landing pad label to landing pad index.
1231  bool IntrFound = false;
1232  for (const User *U : CPI->users()) {
1233  if (const auto *Call = dyn_cast<IntrinsicInst>(U)) {
1234  Intrinsic::ID IID = Call->getIntrinsicID();
1235  if (IID == Intrinsic::wasm_landingpad_index) {
1236  Value *IndexArg = Call->getArgOperand(1);
1237  int Index = cast<ConstantInt>(IndexArg)->getZExtValue();
1239  IntrFound = true;
1240  break;
1241  }
1242  }
1243  }
1244  assert(IntrFound && "wasm.landingpad.index intrinsic not found!");
1245  (void)IntrFound;
1246  }
1247 }
1248 
1249 /// PrepareEHLandingPad - Emit an EH_LABEL, set up live-in registers, and
1250 /// do other setup for EH landing-pad blocks.
1251 bool SelectionDAGISel::PrepareEHLandingPad() {
1252  MachineBasicBlock *MBB = FuncInfo->MBB;
1253  const Constant *PersonalityFn = FuncInfo->Fn->getPersonalityFn();
1254  const BasicBlock *LLVMBB = MBB->getBasicBlock();
1255  const TargetRegisterClass *PtrRC =
1257 
1258  auto Pers = classifyEHPersonality(PersonalityFn);
1259 
1260  // Catchpads have one live-in register, which typically holds the exception
1261  // pointer or code.
1262  if (isFuncletEHPersonality(Pers)) {
1263  if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI())) {
1264  if (hasExceptionPointerOrCodeUser(CPI)) {
1265  // Get or create the virtual register to hold the pointer or code. Mark
1266  // the live in physreg and copy into the vreg.
1267  MCPhysReg EHPhysReg = TLI->getExceptionPointerRegister(PersonalityFn);
1268  assert(EHPhysReg && "target lacks exception pointer register");
1269  MBB->addLiveIn(EHPhysReg);
1270  unsigned VReg = FuncInfo->getCatchPadExceptionPointerVReg(CPI, PtrRC);
1271  BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(),
1272  TII->get(TargetOpcode::COPY), VReg)
1273  .addReg(EHPhysReg, RegState::Kill);
1274  }
1275  }
1276  return true;
1277  }
1278 
1279  // Add a label to mark the beginning of the landing pad. Deletion of the
1280  // landing pad can thus be detected via the MachineModuleInfo.
1282 
1283  const MCInstrDesc &II = TII->get(TargetOpcode::EH_LABEL);
1284  BuildMI(*MBB, FuncInfo->InsertPt, SDB->getCurDebugLoc(), II)
1285  .addSym(Label);
1286 
1287  // If the unwinder does not preserve all registers, ensure that the
1288  // function marks the clobbered registers as used.
1290  if (auto *RegMask = TRI.getCustomEHPadPreservedMask(*MF))
1292 
1293  if (Pers == EHPersonality::Wasm_CXX) {
1294  if (const auto *CPI = dyn_cast<CatchPadInst>(LLVMBB->getFirstNonPHI()))
1296  } else {
1297  // Assign the call site to the landing pad's begin label.
1298  MF->setCallSiteLandingPad(Label, SDB->LPadToCallSiteMap[MBB]);
1299  // Mark exception register as live in.
1300  if (unsigned Reg = TLI->getExceptionPointerRegister(PersonalityFn))
1301  FuncInfo->ExceptionPointerVirtReg = MBB->addLiveIn(Reg, PtrRC);
1302  // Mark exception selector register as live in.
1303  if (unsigned Reg = TLI->getExceptionSelectorRegister(PersonalityFn))
1304  FuncInfo->ExceptionSelectorVirtReg = MBB->addLiveIn(Reg, PtrRC);
1305  }
1306 
1307  return true;
1308 }
1309 
1310 /// isFoldedOrDeadInstruction - Return true if the specified instruction is
1311 /// side-effect free and is either dead or folded into a generated instruction.
1312 /// Return false if it needs to be emitted.
1314  const FunctionLoweringInfo &FuncInfo) {
1315  return !I->mayWriteToMemory() && // Side-effecting instructions aren't folded.
1316  !I->isTerminator() && // Terminators aren't folded.
1317  !isa<DbgInfoIntrinsic>(I) && // Debug instructions aren't folded.
1318  !I->isEHPad() && // EH pad instructions aren't folded.
1319  !FuncInfo.isExportedInst(I); // Exported instrs must be computed.
1320 }
1321 
1322 /// Collect llvm.dbg.declare information. This is done after argument lowering
1323 /// in case the declarations refer to arguments.
1325  MachineFunction *MF = FuncInfo.MF;
1326  const DataLayout &DL = MF->getDataLayout();
1327  for (const BasicBlock &BB : *FuncInfo.Fn) {
1328  for (const Instruction &I : BB) {
1329  const DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(&I);
1330  if (!DI)
1331  continue;
1332 
1333  assert(DI->getVariable() && "Missing variable");
1334  assert(DI->getDebugLoc() && "Missing location");
1335  const Value *Address = DI->getAddress();
1336  if (!Address) {
1337  LLVM_DEBUG(dbgs() << "processDbgDeclares skipping " << *DI
1338  << " (bad address)\n");
1339  continue;
1340  }
1341 
1342  // Look through casts and constant offset GEPs. These mostly come from
1343  // inalloca.
1344  APInt Offset(DL.getTypeSizeInBits(Address->getType()), 0);
1345  Address = Address->stripAndAccumulateInBoundsConstantOffsets(DL, Offset);
1346 
1347  // Check if the variable is a static alloca or a byval or inalloca
1348  // argument passed in memory. If it is not, then we will ignore this
1349  // intrinsic and handle this during isel like dbg.value.
1350  int FI = std::numeric_limits<int>::max();
1351  if (const auto *AI = dyn_cast<AllocaInst>(Address)) {
1352  auto SI = FuncInfo.StaticAllocaMap.find(AI);
1353  if (SI != FuncInfo.StaticAllocaMap.end())
1354  FI = SI->second;
1355  } else if (const auto *Arg = dyn_cast<Argument>(Address))
1356  FI = FuncInfo.getArgumentFrameIndex(Arg);
1357 
1358  if (FI == std::numeric_limits<int>::max())
1359  continue;
1360 
1361  DIExpression *Expr = DI->getExpression();
1362  if (Offset.getBoolValue())
1364  Offset.getZExtValue());
1365  LLVM_DEBUG(dbgs() << "processDbgDeclares: setVariableDbgInfo FI=" << FI
1366  << ", " << *DI << "\n");
1367  MF->setVariableDbgInfo(DI->getVariable(), Expr, FI, DI->getDebugLoc());
1368  }
1369  }
1370 }
1371 
1372 void SelectionDAGISel::SelectAllBasicBlocks(const Function &Fn) {
1373  FastISelFailed = false;
1374  // Initialize the Fast-ISel state, if needed.
1375  FastISel *FastIS = nullptr;
1376  if (TM.Options.EnableFastISel) {
1377  LLVM_DEBUG(dbgs() << "Enabling fast-isel\n");
1378  FastIS = TLI->createFastISel(*FuncInfo, LibInfo);
1379  }
1380 
1382 
1383  // Lower arguments up front. An RPO iteration always visits the entry block
1384  // first.
1385  assert(*RPOT.begin() == &Fn.getEntryBlock());
1386  ++NumEntryBlocks;
1387 
1388  // Set up FuncInfo for ISel. Entry blocks never have PHIs.
1389  FuncInfo->MBB = FuncInfo->MBBMap[&Fn.getEntryBlock()];
1390  FuncInfo->InsertPt = FuncInfo->MBB->begin();
1391 
1393 
1394  if (!FastIS) {
1395  LowerArguments(Fn);
1396  } else {
1397  // See if fast isel can lower the arguments.
1398  FastIS->startNewBlock();
1399  if (!FastIS->lowerArguments()) {
1400  FastISelFailed = true;
1401  // Fast isel failed to lower these arguments
1402  ++NumFastIselFailLowerArguments;
1403 
1404  OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1405  Fn.getSubprogram(),
1406  &Fn.getEntryBlock());
1407  R << "FastISel didn't lower all arguments: "
1408  << ore::NV("Prototype", Fn.getType());
1410 
1411  // Use SelectionDAG argument lowering
1412  LowerArguments(Fn);
1413  CurDAG->setRoot(SDB->getControlRoot());
1414  SDB->clear();
1415  CodeGenAndEmitDAG();
1416  }
1417 
1418  // If we inserted any instructions at the beginning, make a note of
1419  // where they are, so we can be sure to emit subsequent instructions
1420  // after them.
1421  if (FuncInfo->InsertPt != FuncInfo->MBB->begin())
1422  FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
1423  else
1424  FastIS->setLastLocalValue(nullptr);
1425  }
1426 
1427  bool Inserted = SwiftError->createEntriesInEntryBlock(SDB->getCurDebugLoc());
1428 
1429  if (FastIS && Inserted)
1430  FastIS->setLastLocalValue(&*std::prev(FuncInfo->InsertPt));
1431 
1433 
1434  // Iterate over all basic blocks in the function.
1435  StackProtector &SP = getAnalysis<StackProtector>();
1436  for (const BasicBlock *LLVMBB : RPOT) {
1437  if (OptLevel != CodeGenOpt::None) {
1438  bool AllPredsVisited = true;
1439  for (const BasicBlock *Pred : predecessors(LLVMBB)) {
1440  if (!FuncInfo->VisitedBBs.count(Pred)) {
1441  AllPredsVisited = false;
1442  break;
1443  }
1444  }
1445 
1446  if (AllPredsVisited) {
1447  for (const PHINode &PN : LLVMBB->phis())
1448  FuncInfo->ComputePHILiveOutRegInfo(&PN);
1449  } else {
1450  for (const PHINode &PN : LLVMBB->phis())
1451  FuncInfo->InvalidatePHILiveOutRegInfo(&PN);
1452  }
1453 
1454  FuncInfo->VisitedBBs.insert(LLVMBB);
1455  }
1456 
1457  BasicBlock::const_iterator const Begin =
1458  LLVMBB->getFirstNonPHI()->getIterator();
1459  BasicBlock::const_iterator const End = LLVMBB->end();
1460  BasicBlock::const_iterator BI = End;
1461 
1462  FuncInfo->MBB = FuncInfo->MBBMap[LLVMBB];
1463  if (!FuncInfo->MBB)
1464  continue; // Some blocks like catchpads have no code or MBB.
1465 
1466  // Insert new instructions after any phi or argument setup code.
1467  FuncInfo->InsertPt = FuncInfo->MBB->end();
1468 
1469  // Setup an EH landing-pad block.
1470  FuncInfo->ExceptionPointerVirtReg = 0;
1471  FuncInfo->ExceptionSelectorVirtReg = 0;
1472  if (LLVMBB->isEHPad())
1473  if (!PrepareEHLandingPad())
1474  continue;
1475 
1476  // Before doing SelectionDAG ISel, see if FastISel has been requested.
1477  if (FastIS) {
1478  if (LLVMBB != &Fn.getEntryBlock())
1479  FastIS->startNewBlock();
1480 
1481  unsigned NumFastIselRemaining = std::distance(Begin, End);
1482 
1483  // Pre-assign swifterror vregs.
1484  SwiftError->preassignVRegs(FuncInfo->MBB, Begin, End);
1485 
1486  // Do FastISel on as many instructions as possible.
1487  for (; BI != Begin; --BI) {
1488  const Instruction *Inst = &*std::prev(BI);
1489 
1490  // If we no longer require this instruction, skip it.
1491  if (isFoldedOrDeadInstruction(Inst, *FuncInfo) ||
1492  ElidedArgCopyInstrs.count(Inst)) {
1493  --NumFastIselRemaining;
1494  continue;
1495  }
1496 
1497  // Bottom-up: reset the insert pos at the top, after any local-value
1498  // instructions.
1499  FastIS->recomputeInsertPt();
1500 
1501  // Try to select the instruction with FastISel.
1502  if (FastIS->selectInstruction(Inst)) {
1503  --NumFastIselRemaining;
1504  ++NumFastIselSuccess;
1505  // If fast isel succeeded, skip over all the folded instructions, and
1506  // then see if there is a load right before the selected instructions.
1507  // Try to fold the load if so.
1508  const Instruction *BeforeInst = Inst;
1509  while (BeforeInst != &*Begin) {
1510  BeforeInst = &*std::prev(BasicBlock::const_iterator(BeforeInst));
1511  if (!isFoldedOrDeadInstruction(BeforeInst, *FuncInfo))
1512  break;
1513  }
1514  if (BeforeInst != Inst && isa<LoadInst>(BeforeInst) &&
1515  BeforeInst->hasOneUse() &&
1516  FastIS->tryToFoldLoad(cast<LoadInst>(BeforeInst), Inst)) {
1517  // If we succeeded, don't re-select the load.
1518  BI = std::next(BasicBlock::const_iterator(BeforeInst));
1519  --NumFastIselRemaining;
1520  ++NumFastIselSuccess;
1521  }
1522  continue;
1523  }
1524 
1525  FastISelFailed = true;
1526 
1527  // Then handle certain instructions as single-LLVM-Instruction blocks.
1528  // We cannot separate out GCrelocates to their own blocks since we need
1529  // to keep track of gc-relocates for a particular gc-statepoint. This is
1530  // done by SelectionDAGBuilder::LowerAsSTATEPOINT, called before
1531  // visitGCRelocate.
1532  if (isa<CallInst>(Inst) && !isa<GCStatepointInst>(Inst) &&
1533  !isa<GCRelocateInst>(Inst) && !isa<GCResultInst>(Inst)) {
1534  OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1535  Inst->getDebugLoc(), LLVMBB);
1536 
1537  R << "FastISel missed call";
1538 
1539  if (R.isEnabled() || EnableFastISelAbort) {
1540  std::string InstStrStorage;
1541  raw_string_ostream InstStr(InstStrStorage);
1542  InstStr << *Inst;
1543 
1544  R << ": " << InstStr.str();
1545  }
1546 
1548 
1549  if (!Inst->getType()->isVoidTy() && !Inst->getType()->isTokenTy() &&
1550  !Inst->use_empty()) {
1551  Register &R = FuncInfo->ValueMap[Inst];
1552  if (!R)
1553  R = FuncInfo->CreateRegs(Inst);
1554  }
1555 
1556  bool HadTailCall = false;
1557  MachineBasicBlock::iterator SavedInsertPt = FuncInfo->InsertPt;
1558  SelectBasicBlock(Inst->getIterator(), BI, HadTailCall);
1559 
1560  // If the call was emitted as a tail call, we're done with the block.
1561  // We also need to delete any previously emitted instructions.
1562  if (HadTailCall) {
1563  FastIS->removeDeadCode(SavedInsertPt, FuncInfo->MBB->end());
1564  --BI;
1565  break;
1566  }
1567 
1568  // Recompute NumFastIselRemaining as Selection DAG instruction
1569  // selection may have handled the call, input args, etc.
1570  unsigned RemainingNow = std::distance(Begin, BI);
1571  NumFastIselFailures += NumFastIselRemaining - RemainingNow;
1572  NumFastIselRemaining = RemainingNow;
1573  continue;
1574  }
1575 
1576  OptimizationRemarkMissed R("sdagisel", "FastISelFailure",
1577  Inst->getDebugLoc(), LLVMBB);
1578 
1579  bool ShouldAbort = EnableFastISelAbort;
1580  if (Inst->isTerminator()) {
1581  // Use a different message for terminator misses.
1582  R << "FastISel missed terminator";
1583  // Don't abort for terminator unless the level is really high
1584  ShouldAbort = (EnableFastISelAbort > 2);
1585  } else {
1586  R << "FastISel missed";
1587  }
1588 
1589  if (R.isEnabled() || EnableFastISelAbort) {
1590  std::string InstStrStorage;
1591  raw_string_ostream InstStr(InstStrStorage);
1592  InstStr << *Inst;
1593  R << ": " << InstStr.str();
1594  }
1595 
1596  reportFastISelFailure(*MF, *ORE, R, ShouldAbort);
1597 
1598  NumFastIselFailures += NumFastIselRemaining;
1599  break;
1600  }
1601 
1602  FastIS->recomputeInsertPt();
1603  }
1604 
1605  if (SP.shouldEmitSDCheck(*LLVMBB)) {
1606  bool FunctionBasedInstrumentation =
1608  SDB->SPDescriptor.initialize(LLVMBB, FuncInfo->MBBMap[LLVMBB],
1609  FunctionBasedInstrumentation);
1610  }
1611 
1612  if (Begin != BI)
1613  ++NumDAGBlocks;
1614  else
1615  ++NumFastIselBlocks;
1616 
1617  if (Begin != BI) {
1618  // Run SelectionDAG instruction selection on the remainder of the block
1619  // not handled by FastISel. If FastISel is not run, this is the entire
1620  // block.
1621  bool HadTailCall;
1622  SelectBasicBlock(Begin, BI, HadTailCall);
1623 
1624  // But if FastISel was run, we already selected some of the block.
1625  // If we emitted a tail-call, we need to delete any previously emitted
1626  // instruction that follows it.
1627  if (FastIS && HadTailCall && FuncInfo->InsertPt != FuncInfo->MBB->end())
1628  FastIS->removeDeadCode(FuncInfo->InsertPt, FuncInfo->MBB->end());
1629  }
1630 
1631  if (FastIS)
1632  FastIS->finishBasicBlock();
1633  FinishBasicBlock();
1634  FuncInfo->PHINodesToUpdate.clear();
1635  ElidedArgCopyInstrs.clear();
1636  }
1637 
1639 
1641 
1642  delete FastIS;
1643  SDB->clearDanglingDebugInfo();
1644  SDB->SPDescriptor.resetPerFunctionState();
1645 }
1646 
1647 /// Given that the input MI is before a partial terminator sequence TSeq, return
1648 /// true if M + TSeq also a partial terminator sequence.
1649 ///
1650 /// A Terminator sequence is a sequence of MachineInstrs which at this point in
1651 /// lowering copy vregs into physical registers, which are then passed into
1652 /// terminator instructors so we can satisfy ABI constraints. A partial
1653 /// terminator sequence is an improper subset of a terminator sequence (i.e. it
1654 /// may be the whole terminator sequence).
1656  // If we do not have a copy or an implicit def, we return true if and only if
1657  // MI is a debug value.
1658  if (!MI.isCopy() && !MI.isImplicitDef())
1659  // Sometimes DBG_VALUE MI sneak in between the copies from the vregs to the
1660  // physical registers if there is debug info associated with the terminator
1661  // of our mbb. We want to include said debug info in our terminator
1662  // sequence, so we return true in that case.
1663  return MI.isDebugInstr();
1664 
1665  // We have left the terminator sequence if we are not doing one of the
1666  // following:
1667  //
1668  // 1. Copying a vreg into a physical register.
1669  // 2. Copying a vreg into a vreg.
1670  // 3. Defining a register via an implicit def.
1671 
1672  // OPI should always be a register definition...
1673  MachineInstr::const_mop_iterator OPI = MI.operands_begin();
1674  if (!OPI->isReg() || !OPI->isDef())
1675  return false;
1676 
1677  // Defining any register via an implicit def is always ok.
1678  if (MI.isImplicitDef())
1679  return true;
1680 
1681  // Grab the copy source...
1683  ++OPI2;
1684  assert(OPI2 != MI.operands_end()
1685  && "Should have a copy implying we should have 2 arguments.");
1686 
1687  // Make sure that the copy dest is not a vreg when the copy source is a
1688  // physical register.
1689  if (!OPI2->isReg() || (!Register::isPhysicalRegister(OPI->getReg()) &&
1691  return false;
1692 
1693  return true;
1694 }
1695 
1696 /// Find the split point at which to splice the end of BB into its success stack
1697 /// protector check machine basic block.
1698 ///
1699 /// On many platforms, due to ABI constraints, terminators, even before register
1700 /// allocation, use physical registers. This creates an issue for us since
1701 /// physical registers at this point can not travel across basic
1702 /// blocks. Luckily, selectiondag always moves physical registers into vregs
1703 /// when they enter functions and moves them through a sequence of copies back
1704 /// into the physical registers right before the terminator creating a
1705 /// ``Terminator Sequence''. This function is searching for the beginning of the
1706 /// terminator sequence so that we can ensure that we splice off not just the
1707 /// terminator, but additionally the copies that move the vregs into the
1708 /// physical registers.
1711  const TargetInstrInfo &TII) {
1712  MachineBasicBlock::iterator SplitPoint = BB->getFirstTerminator();
1713  if (SplitPoint == BB->begin())
1714  return SplitPoint;
1715 
1716  MachineBasicBlock::iterator Start = BB->begin();
1717  MachineBasicBlock::iterator Previous = SplitPoint;
1718  --Previous;
1719 
1720  if (TII.isTailCall(*SplitPoint) &&
1721  Previous->getOpcode() == TII.getCallFrameDestroyOpcode()) {
1722  // call itself, then we must insert before the sequence even starts. For
1723  // example:
1724  // <split point>
1725  // ADJCALLSTACKDOWN ...
1726  // <Moves>
1727  // ADJCALLSTACKUP ...
1728  // TAILJMP somewhere
1729  // On the other hand, it could be an unrelated call in which case this tail call
1730  // has to register moves of its own and should be the split point. For example:
1731  // ADJCALLSTACKDOWN
1732  // CALL something_else
1733  // ADJCALLSTACKUP
1734  // <split point>
1735  // TAILJMP somewhere
1736  do {
1737  --Previous;
1738  if (Previous->isCall())
1739  return SplitPoint;
1740  } while(Previous->getOpcode() != TII.getCallFrameSetupOpcode());
1741 
1742  return Previous;
1743  }
1744 
1745  while (MIIsInTerminatorSequence(*Previous)) {
1746  SplitPoint = Previous;
1747  if (Previous == Start)
1748  break;
1749  --Previous;
1750  }
1751 
1752  return SplitPoint;
1753 }
1754 
1755 void
1756 SelectionDAGISel::FinishBasicBlock() {
1757  LLVM_DEBUG(dbgs() << "Total amount of phi nodes to update: "
1758  << FuncInfo->PHINodesToUpdate.size() << "\n";
1759  for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e;
1760  ++i) dbgs()
1761  << "Node " << i << " : (" << FuncInfo->PHINodesToUpdate[i].first
1762  << ", " << FuncInfo->PHINodesToUpdate[i].second << ")\n");
1763 
1764  // Next, now that we know what the last MBB the LLVM BB expanded is, update
1765  // PHI nodes in successors.
1766  for (unsigned i = 0, e = FuncInfo->PHINodesToUpdate.size(); i != e; ++i) {
1767  MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[i].first);
1768  assert(PHI->isPHI() &&
1769  "This is not a machine PHI node that we are updating!");
1770  if (!FuncInfo->MBB->isSuccessor(PHI->getParent()))
1771  continue;
1772  PHI.addReg(FuncInfo->PHINodesToUpdate[i].second).addMBB(FuncInfo->MBB);
1773  }
1774 
1775  // Handle stack protector.
1776  if (SDB->SPDescriptor.shouldEmitFunctionBasedCheckStackProtector()) {
1777  // The target provides a guard check function. There is no need to
1778  // generate error handling code or to split current basic block.
1779  MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1780 
1781  // Add load and check to the basicblock.
1782  FuncInfo->MBB = ParentMBB;
1783  FuncInfo->InsertPt =
1784  FindSplitPointForStackProtector(ParentMBB, *TII);
1785  SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
1786  CurDAG->setRoot(SDB->getRoot());
1787  SDB->clear();
1788  CodeGenAndEmitDAG();
1789 
1790  // Clear the Per-BB State.
1791  SDB->SPDescriptor.resetPerBBState();
1792  } else if (SDB->SPDescriptor.shouldEmitStackProtector()) {
1793  MachineBasicBlock *ParentMBB = SDB->SPDescriptor.getParentMBB();
1794  MachineBasicBlock *SuccessMBB = SDB->SPDescriptor.getSuccessMBB();
1795 
1796  // Find the split point to split the parent mbb. At the same time copy all
1797  // physical registers used in the tail of parent mbb into virtual registers
1798  // before the split point and back into physical registers after the split
1799  // point. This prevents us needing to deal with Live-ins and many other
1800  // register allocation issues caused by us splitting the parent mbb. The
1801  // register allocator will clean up said virtual copies later on.
1802  MachineBasicBlock::iterator SplitPoint =
1803  FindSplitPointForStackProtector(ParentMBB, *TII);
1804 
1805  // Splice the terminator of ParentMBB into SuccessMBB.
1806  SuccessMBB->splice(SuccessMBB->end(), ParentMBB,
1807  SplitPoint,
1808  ParentMBB->end());
1809 
1810  // Add compare/jump on neq/jump to the parent BB.
1811  FuncInfo->MBB = ParentMBB;
1812  FuncInfo->InsertPt = ParentMBB->end();
1813  SDB->visitSPDescriptorParent(SDB->SPDescriptor, ParentMBB);
1814  CurDAG->setRoot(SDB->getRoot());
1815  SDB->clear();
1816  CodeGenAndEmitDAG();
1817 
1818  // CodeGen Failure MBB if we have not codegened it yet.
1819  MachineBasicBlock *FailureMBB = SDB->SPDescriptor.getFailureMBB();
1820  if (FailureMBB->empty()) {
1821  FuncInfo->MBB = FailureMBB;
1822  FuncInfo->InsertPt = FailureMBB->end();
1823  SDB->visitSPDescriptorFailure(SDB->SPDescriptor);
1824  CurDAG->setRoot(SDB->getRoot());
1825  SDB->clear();
1826  CodeGenAndEmitDAG();
1827  }
1828 
1829  // Clear the Per-BB State.
1830  SDB->SPDescriptor.resetPerBBState();
1831  }
1832 
1833  // Lower each BitTestBlock.
1834  for (auto &BTB : SDB->SL->BitTestCases) {
1835  // Lower header first, if it wasn't already lowered
1836  if (!BTB.Emitted) {
1837  // Set the current basic block to the mbb we wish to insert the code into
1838  FuncInfo->MBB = BTB.Parent;
1839  FuncInfo->InsertPt = FuncInfo->MBB->end();
1840  // Emit the code
1841  SDB->visitBitTestHeader(BTB, FuncInfo->MBB);
1842  CurDAG->setRoot(SDB->getRoot());
1843  SDB->clear();
1844  CodeGenAndEmitDAG();
1845  }
1846 
1847  BranchProbability UnhandledProb = BTB.Prob;
1848  for (unsigned j = 0, ej = BTB.Cases.size(); j != ej; ++j) {
1849  UnhandledProb -= BTB.Cases[j].ExtraProb;
1850  // Set the current basic block to the mbb we wish to insert the code into
1851  FuncInfo->MBB = BTB.Cases[j].ThisBB;
1852  FuncInfo->InsertPt = FuncInfo->MBB->end();
1853  // Emit the code
1854 
1855  // If all cases cover a contiguous range, it is not necessary to jump to
1856  // the default block after the last bit test fails. This is because the
1857  // range check during bit test header creation has guaranteed that every
1858  // case here doesn't go outside the range. In this case, there is no need
1859  // to perform the last bit test, as it will always be true. Instead, make
1860  // the second-to-last bit-test fall through to the target of the last bit
1861  // test, and delete the last bit test.
1862 
1863  MachineBasicBlock *NextMBB;
1864  if (BTB.ContiguousRange && j + 2 == ej) {
1865  // Second-to-last bit-test with contiguous range: fall through to the
1866  // target of the final bit test.
1867  NextMBB = BTB.Cases[j + 1].TargetBB;
1868  } else if (j + 1 == ej) {
1869  // For the last bit test, fall through to Default.
1870  NextMBB = BTB.Default;
1871  } else {
1872  // Otherwise, fall through to the next bit test.
1873  NextMBB = BTB.Cases[j + 1].ThisBB;
1874  }
1875 
1876  SDB->visitBitTestCase(BTB, NextMBB, UnhandledProb, BTB.Reg, BTB.Cases[j],
1877  FuncInfo->MBB);
1878 
1879  CurDAG->setRoot(SDB->getRoot());
1880  SDB->clear();
1881  CodeGenAndEmitDAG();
1882 
1883  if (BTB.ContiguousRange && j + 2 == ej) {
1884  // Since we're not going to use the final bit test, remove it.
1885  BTB.Cases.pop_back();
1886  break;
1887  }
1888  }
1889 
1890  // Update PHI Nodes
1891  for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1892  pi != pe; ++pi) {
1893  MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1894  MachineBasicBlock *PHIBB = PHI->getParent();
1895  assert(PHI->isPHI() &&
1896  "This is not a machine PHI node that we are updating!");
1897  // This is "default" BB. We have two jumps to it. From "header" BB and
1898  // from last "case" BB, unless the latter was skipped.
1899  if (PHIBB == BTB.Default) {
1900  PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(BTB.Parent);
1901  if (!BTB.ContiguousRange) {
1902  PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1903  .addMBB(BTB.Cases.back().ThisBB);
1904  }
1905  }
1906  // One of "cases" BB.
1907  for (unsigned j = 0, ej = BTB.Cases.size();
1908  j != ej; ++j) {
1909  MachineBasicBlock* cBB = BTB.Cases[j].ThisBB;
1910  if (cBB->isSuccessor(PHIBB))
1911  PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(cBB);
1912  }
1913  }
1914  }
1915  SDB->SL->BitTestCases.clear();
1916 
1917  // If the JumpTable record is filled in, then we need to emit a jump table.
1918  // Updating the PHI nodes is tricky in this case, since we need to determine
1919  // whether the PHI is a successor of the range check MBB or the jump table MBB
1920  for (unsigned i = 0, e = SDB->SL->JTCases.size(); i != e; ++i) {
1921  // Lower header first, if it wasn't already lowered
1922  if (!SDB->SL->JTCases[i].first.Emitted) {
1923  // Set the current basic block to the mbb we wish to insert the code into
1924  FuncInfo->MBB = SDB->SL->JTCases[i].first.HeaderBB;
1925  FuncInfo->InsertPt = FuncInfo->MBB->end();
1926  // Emit the code
1927  SDB->visitJumpTableHeader(SDB->SL->JTCases[i].second,
1928  SDB->SL->JTCases[i].first, FuncInfo->MBB);
1929  CurDAG->setRoot(SDB->getRoot());
1930  SDB->clear();
1931  CodeGenAndEmitDAG();
1932  }
1933 
1934  // Set the current basic block to the mbb we wish to insert the code into
1935  FuncInfo->MBB = SDB->SL->JTCases[i].second.MBB;
1936  FuncInfo->InsertPt = FuncInfo->MBB->end();
1937  // Emit the code
1938  SDB->visitJumpTable(SDB->SL->JTCases[i].second);
1939  CurDAG->setRoot(SDB->getRoot());
1940  SDB->clear();
1941  CodeGenAndEmitDAG();
1942 
1943  // Update PHI Nodes
1944  for (unsigned pi = 0, pe = FuncInfo->PHINodesToUpdate.size();
1945  pi != pe; ++pi) {
1946  MachineInstrBuilder PHI(*MF, FuncInfo->PHINodesToUpdate[pi].first);
1947  MachineBasicBlock *PHIBB = PHI->getParent();
1948  assert(PHI->isPHI() &&
1949  "This is not a machine PHI node that we are updating!");
1950  // "default" BB. We can go there only from header BB.
1951  if (PHIBB == SDB->SL->JTCases[i].second.Default)
1952  PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second)
1953  .addMBB(SDB->SL->JTCases[i].first.HeaderBB);
1954  // JT BB. Just iterate over successors here
1955  if (FuncInfo->MBB->isSuccessor(PHIBB))
1956  PHI.addReg(FuncInfo->PHINodesToUpdate[pi].second).addMBB(FuncInfo->MBB);
1957  }
1958  }
1959  SDB->SL->JTCases.clear();
1960 
1961  // If we generated any switch lowering information, build and codegen any
1962  // additional DAGs necessary.
1963  for (unsigned i = 0, e = SDB->SL->SwitchCases.size(); i != e; ++i) {
1964  // Set the current basic block to the mbb we wish to insert the code into
1965  FuncInfo->MBB = SDB->SL->SwitchCases[i].ThisBB;
1966  FuncInfo->InsertPt = FuncInfo->MBB->end();
1967 
1968  // Determine the unique successors.
1970  Succs.push_back(SDB->SL->SwitchCases[i].TrueBB);
1971  if (SDB->SL->SwitchCases[i].TrueBB != SDB->SL->SwitchCases[i].FalseBB)
1972  Succs.push_back(SDB->SL->SwitchCases[i].FalseBB);
1973 
1974  // Emit the code. Note that this could result in FuncInfo->MBB being split.
1975  SDB->visitSwitchCase(SDB->SL->SwitchCases[i], FuncInfo->MBB);
1976  CurDAG->setRoot(SDB->getRoot());
1977  SDB->clear();
1978  CodeGenAndEmitDAG();
1979 
1980  // Remember the last block, now that any splitting is done, for use in
1981  // populating PHI nodes in successors.
1982  MachineBasicBlock *ThisBB = FuncInfo->MBB;
1983 
1984  // Handle any PHI nodes in successors of this chunk, as if we were coming
1985  // from the original BB before switch expansion. Note that PHI nodes can
1986  // occur multiple times in PHINodesToUpdate. We have to be very careful to
1987  // handle them the right number of times.
1988  for (unsigned i = 0, e = Succs.size(); i != e; ++i) {
1989  FuncInfo->MBB = Succs[i];
1990  FuncInfo->InsertPt = FuncInfo->MBB->end();
1991  // FuncInfo->MBB may have been removed from the CFG if a branch was
1992  // constant folded.
1993  if (ThisBB->isSuccessor(FuncInfo->MBB)) {
1995  MBBI = FuncInfo->MBB->begin(), MBBE = FuncInfo->MBB->end();
1996  MBBI != MBBE && MBBI->isPHI(); ++MBBI) {
1997  MachineInstrBuilder PHI(*MF, MBBI);
1998  // This value for this PHI node is recorded in PHINodesToUpdate.
1999  for (unsigned pn = 0; ; ++pn) {
2000  assert(pn != FuncInfo->PHINodesToUpdate.size() &&
2001  "Didn't find PHI entry!");
2002  if (FuncInfo->PHINodesToUpdate[pn].first == PHI) {
2003  PHI.addReg(FuncInfo->PHINodesToUpdate[pn].second).addMBB(ThisBB);
2004  break;
2005  }
2006  }
2007  }
2008  }
2009  }
2010  }
2011  SDB->SL->SwitchCases.clear();
2012 }
2013 
2014 /// Create the scheduler. If a specific scheduler was specified
2015 /// via the SchedulerRegistry, use it, otherwise select the
2016 /// one preferred by the target.
2017 ///
2018 ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
2019  return ISHeuristic(this, OptLevel);
2020 }
2021 
2022 //===----------------------------------------------------------------------===//
2023 // Helper functions used by the generated instruction selector.
2024 //===----------------------------------------------------------------------===//
2025 // Calls to these methods are generated by tblgen.
2026 
2027 /// CheckAndMask - The isel is trying to match something like (and X, 255). If
2028 /// the dag combiner simplified the 255, we still want to match. RHS is the
2029 /// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
2030 /// specified in the .td file (e.g. 255).
2032  int64_t DesiredMaskS) const {
2033  const APInt &ActualMask = RHS->getAPIntValue();
2034  const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
2035 
2036  // If the actual mask exactly matches, success!
2037  if (ActualMask == DesiredMask)
2038  return true;
2039 
2040  // If the actual AND mask is allowing unallowed bits, this doesn't match.
2041  if (!ActualMask.isSubsetOf(DesiredMask))
2042  return false;
2043 
2044  // Otherwise, the DAG Combiner may have proven that the value coming in is
2045  // either already zero or is not demanded. Check for known zero input bits.
2046  APInt NeededMask = DesiredMask & ~ActualMask;
2047  if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
2048  return true;
2049 
2050  // TODO: check to see if missing bits are just not demanded.
2051 
2052  // Otherwise, this pattern doesn't match.
2053  return false;
2054 }
2055 
2056 /// CheckOrMask - The isel is trying to match something like (or X, 255). If
2057 /// the dag combiner simplified the 255, we still want to match. RHS is the
2058 /// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
2059 /// specified in the .td file (e.g. 255).
2061  int64_t DesiredMaskS) const {
2062  const APInt &ActualMask = RHS->getAPIntValue();
2063  const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
2064 
2065  // If the actual mask exactly matches, success!
2066  if (ActualMask == DesiredMask)
2067  return true;
2068 
2069  // If the actual AND mask is allowing unallowed bits, this doesn't match.
2070  if (!ActualMask.isSubsetOf(DesiredMask))
2071  return false;
2072 
2073  // Otherwise, the DAG Combiner may have proven that the value coming in is
2074  // either already zero or is not demanded. Check for known zero input bits.
2075  APInt NeededMask = DesiredMask & ~ActualMask;
2076  KnownBits Known = CurDAG->computeKnownBits(LHS);
2077 
2078  // If all the missing bits in the or are already known to be set, match!
2079  if (NeededMask.isSubsetOf(Known.One))
2080  return true;
2081 
2082  // TODO: check to see if missing bits are just not demanded.
2083 
2084  // Otherwise, this pattern doesn't match.
2085  return false;
2086 }
2087 
2088 /// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
2089 /// by tblgen. Others should not call it.
2091  const SDLoc &DL) {
2092  std::vector<SDValue> InOps;
2093  std::swap(InOps, Ops);
2094 
2095  Ops.push_back(InOps[InlineAsm::Op_InputChain]); // 0
2096  Ops.push_back(InOps[InlineAsm::Op_AsmString]); // 1
2097  Ops.push_back(InOps[InlineAsm::Op_MDNode]); // 2, !srcloc
2098  Ops.push_back(InOps[InlineAsm::Op_ExtraInfo]); // 3 (SideEffect, AlignStack)
2099 
2100  unsigned i = InlineAsm::Op_FirstOperand, e = InOps.size();
2101  if (InOps[e-1].getValueType() == MVT::Glue)
2102  --e; // Don't process a glue operand if it is here.
2103 
2104  while (i != e) {
2105  unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
2106  if (!InlineAsm::isMemKind(Flags)) {
2107  // Just skip over this operand, copying the operands verbatim.
2108  Ops.insert(Ops.end(), InOps.begin()+i,
2109  InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
2110  i += InlineAsm::getNumOperandRegisters(Flags) + 1;
2111  } else {
2113  "Memory operand with multiple values?");
2114 
2115  unsigned TiedToOperand;
2116  if (InlineAsm::isUseOperandTiedToDef(Flags, TiedToOperand)) {
2117  // We need the constraint ID from the operand this is tied to.
2118  unsigned CurOp = InlineAsm::Op_FirstOperand;
2119  Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue();
2120  for (; TiedToOperand; --TiedToOperand) {
2121  CurOp += InlineAsm::getNumOperandRegisters(Flags)+1;
2122  Flags = cast<ConstantSDNode>(InOps[CurOp])->getZExtValue();
2123  }
2124  }
2125 
2126  // Otherwise, this is a memory operand. Ask the target to select it.
2127  std::vector<SDValue> SelOps;
2128  unsigned ConstraintID = InlineAsm::getMemoryConstraintID(Flags);
2129  if (SelectInlineAsmMemoryOperand(InOps[i+1], ConstraintID, SelOps))
2130  report_fatal_error("Could not match memory address. Inline asm"
2131  " failure!");
2132 
2133  // Add this to the output node.
2134  unsigned NewFlags =
2136  NewFlags = InlineAsm::getFlagWordForMem(NewFlags, ConstraintID);
2137  Ops.push_back(CurDAG->getTargetConstant(NewFlags, DL, MVT::i32));
2138  llvm::append_range(Ops, SelOps);
2139  i += 2;
2140  }
2141  }
2142 
2143  // Add the glue input back if present.
2144  if (e != InOps.size())
2145  Ops.push_back(InOps.back());
2146 }
2147 
2148 /// findGlueUse - Return use of MVT::Glue value produced by the specified
2149 /// SDNode.
2150 ///
2152  unsigned FlagResNo = N->getNumValues()-1;
2153  for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
2154  SDUse &Use = I.getUse();
2155  if (Use.getResNo() == FlagResNo)
2156  return Use.getUser();
2157  }
2158  return nullptr;
2159 }
2160 
2161 /// findNonImmUse - Return true if "Def" is a predecessor of "Root" via a path
2162 /// beyond "ImmedUse". We may ignore chains as they are checked separately.
2163 static bool findNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse,
2164  bool IgnoreChains) {
2167  // Only check if we have non-immediate uses of Def.
2168  if (ImmedUse->isOnlyUserOf(Def))
2169  return false;
2170 
2171  // We don't care about paths to Def that go through ImmedUse so mark it
2172  // visited and mark non-def operands as used.
2173  Visited.insert(ImmedUse);
2174  for (const SDValue &Op : ImmedUse->op_values()) {
2175  SDNode *N = Op.getNode();
2176  // Ignore chain deps (they are validated by
2177  // HandleMergeInputChains) and immediate uses
2178  if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def)
2179  continue;
2180  if (!Visited.insert(N).second)
2181  continue;
2182  WorkList.push_back(N);
2183  }
2184 
2185  // Initialize worklist to operands of Root.
2186  if (Root != ImmedUse) {
2187  for (const SDValue &Op : Root->op_values()) {
2188  SDNode *N = Op.getNode();
2189  // Ignore chains (they are validated by HandleMergeInputChains)
2190  if ((Op.getValueType() == MVT::Other && IgnoreChains) || N == Def)
2191  continue;
2192  if (!Visited.insert(N).second)
2193  continue;
2194  WorkList.push_back(N);
2195  }
2196  }
2197 
2198  return SDNode::hasPredecessorHelper(Def, Visited, WorkList, 0, true);
2199 }
2200 
2201 /// IsProfitableToFold - Returns true if it's profitable to fold the specific
2202 /// operand node N of U during instruction selection that starts at Root.
2204  SDNode *Root) const {
2205  if (OptLevel == CodeGenOpt::None) return false;
2206  return N.hasOneUse();
2207 }
2208 
2209 /// IsLegalToFold - Returns true if the specific operand node N of
2210 /// U can be folded during instruction selection that starts at Root.
2212  CodeGenOpt::Level OptLevel,
2213  bool IgnoreChains) {
2214  if (OptLevel == CodeGenOpt::None) return false;
2215 
2216  // If Root use can somehow reach N through a path that that doesn't contain
2217  // U then folding N would create a cycle. e.g. In the following
2218  // diagram, Root can reach N through X. If N is folded into Root, then
2219  // X is both a predecessor and a successor of U.
2220  //
2221  // [N*] //
2222  // ^ ^ //
2223  // / \ //
2224  // [U*] [X]? //
2225  // ^ ^ //
2226  // \ / //
2227  // \ / //
2228  // [Root*] //
2229  //
2230  // * indicates nodes to be folded together.
2231  //
2232  // If Root produces glue, then it gets (even more) interesting. Since it
2233  // will be "glued" together with its glue use in the scheduler, we need to
2234  // check if it might reach N.
2235  //
2236  // [N*] //
2237  // ^ ^ //
2238  // / \ //
2239  // [U*] [X]? //
2240  // ^ ^ //
2241  // \ \ //
2242  // \ | //
2243  // [Root*] | //
2244  // ^ | //
2245  // f | //
2246  // | / //
2247  // [Y] / //
2248  // ^ / //
2249  // f / //
2250  // | / //
2251  // [GU] //
2252  //
2253  // If GU (glue use) indirectly reaches N (the load), and Root folds N
2254  // (call it Fold), then X is a predecessor of GU and a successor of
2255  // Fold. But since Fold and GU are glued together, this will create
2256  // a cycle in the scheduling graph.
2257 
2258  // If the node has glue, walk down the graph to the "lowest" node in the
2259  // glueged set.
2260  EVT VT = Root->getValueType(Root->getNumValues()-1);
2261  while (VT == MVT::Glue) {
2262  SDNode *GU = findGlueUse(Root);
2263  if (!GU)
2264  break;
2265  Root = GU;
2266  VT = Root->getValueType(Root->getNumValues()-1);
2267 
2268  // If our query node has a glue result with a use, we've walked up it. If
2269  // the user (which has already been selected) has a chain or indirectly uses
2270  // the chain, HandleMergeInputChains will not consider it. Because of
2271  // this, we cannot ignore chains in this predicate.
2272  IgnoreChains = false;
2273  }
2274 
2275  return !findNonImmUse(Root, N.getNode(), U, IgnoreChains);
2276 }
2277 
2278 void SelectionDAGISel::Select_INLINEASM(SDNode *N) {
2279  SDLoc DL(N);
2280 
2281  std::vector<SDValue> Ops(N->op_begin(), N->op_end());
2283 
2284  const EVT VTs[] = {MVT::Other, MVT::Glue};
2285  SDValue New = CurDAG->getNode(N->getOpcode(), DL, VTs, Ops);
2286  New->setNodeId(-1);
2287  ReplaceUses(N, New.getNode());
2289 }
2290 
2291 void SelectionDAGISel::Select_READ_REGISTER(SDNode *Op) {
2292  SDLoc dl(Op);
2293  MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1));
2294  const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0));
2295 
2296  EVT VT = Op->getValueType(0);
2297  LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
2298  Register Reg =
2299  TLI->getRegisterByName(RegStr->getString().data(), Ty,
2302  Op->getOperand(0), dl, Reg, Op->getValueType(0));
2303  New->setNodeId(-1);
2304  ReplaceUses(Op, New.getNode());
2306 }
2307 
2308 void SelectionDAGISel::Select_WRITE_REGISTER(SDNode *Op) {
2309  SDLoc dl(Op);
2310  MDNodeSDNode *MD = cast<MDNodeSDNode>(Op->getOperand(1));
2311  const MDString *RegStr = cast<MDString>(MD->getMD()->getOperand(0));
2312 
2313  EVT VT = Op->getOperand(2).getValueType();
2314  LLT Ty = VT.isSimple() ? getLLTForMVT(VT.getSimpleVT()) : LLT();
2315 
2316  Register Reg = TLI->getRegisterByName(RegStr->getString().data(), Ty,
2319  Op->getOperand(0), dl, Reg, Op->getOperand(2));
2320  New->setNodeId(-1);
2321  ReplaceUses(Op, New.getNode());
2323 }
2324 
2325 void SelectionDAGISel::Select_UNDEF(SDNode *N) {
2326  CurDAG->SelectNodeTo(N, TargetOpcode::IMPLICIT_DEF, N->getValueType(0));
2327 }
2328 
2329 void SelectionDAGISel::Select_FREEZE(SDNode *N) {
2330  // TODO: We don't have FREEZE pseudo-instruction in MachineInstr-level now.
2331  // If FREEZE instruction is added later, the code below must be changed as
2332  // well.
2333  CurDAG->SelectNodeTo(N, TargetOpcode::COPY, N->getValueType(0),
2334  N->getOperand(0));
2335 }
2336 
2337 void SelectionDAGISel::Select_ARITH_FENCE(SDNode *N) {
2338  CurDAG->SelectNodeTo(N, TargetOpcode::ARITH_FENCE, N->getValueType(0),
2339  N->getOperand(0));
2340 }
2341 
2342 /// GetVBR - decode a vbr encoding whose top bit is set.
2344 GetVBR(uint64_t Val, const unsigned char *MatcherTable, unsigned &Idx) {
2345  assert(Val >= 128 && "Not a VBR");
2346  Val &= 127; // Remove first vbr bit.
2347 
2348  unsigned Shift = 7;
2349  uint64_t NextBits;
2350  do {
2351  NextBits = MatcherTable[Idx++];
2352  Val |= (NextBits&127) << Shift;
2353  Shift += 7;
2354  } while (NextBits & 128);
2355 
2356  return Val;
2357 }
2358 
2359 /// When a match is complete, this method updates uses of interior chain results
2360 /// to use the new results.
2361 void SelectionDAGISel::UpdateChains(
2362  SDNode *NodeToMatch, SDValue InputChain,
2363  SmallVectorImpl<SDNode *> &ChainNodesMatched, bool isMorphNodeTo) {
2364  SmallVector<SDNode*, 4> NowDeadNodes;
2365 
2366  // Now that all the normal results are replaced, we replace the chain and
2367  // glue results if present.
2368  if (!ChainNodesMatched.empty()) {
2369  assert(InputChain.getNode() &&
2370  "Matched input chains but didn't produce a chain");
2371  // Loop over all of the nodes we matched that produced a chain result.
2372  // Replace all the chain results with the final chain we ended up with.
2373  for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
2374  SDNode *ChainNode = ChainNodesMatched[i];
2375  // If ChainNode is null, it's because we replaced it on a previous
2376  // iteration and we cleared it out of the map. Just skip it.
2377  if (!ChainNode)
2378  continue;
2379 
2380  assert(ChainNode->getOpcode() != ISD::DELETED_NODE &&
2381  "Deleted node left in chain");
2382 
2383  // Don't replace the results of the root node if we're doing a
2384  // MorphNodeTo.
2385  if (ChainNode == NodeToMatch && isMorphNodeTo)
2386  continue;
2387 
2388  SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
2389  if (ChainVal.getValueType() == MVT::Glue)
2390  ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
2391  assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
2393  *CurDAG, [&](SDNode *N, SDNode *E) {
2394  std::replace(ChainNodesMatched.begin(), ChainNodesMatched.end(), N,
2395  static_cast<SDNode *>(nullptr));
2396  });
2397  if (ChainNode->getOpcode() != ISD::TokenFactor)
2398  ReplaceUses(ChainVal, InputChain);
2399 
2400  // If the node became dead and we haven't already seen it, delete it.
2401  if (ChainNode != NodeToMatch && ChainNode->use_empty() &&
2402  !llvm::is_contained(NowDeadNodes, ChainNode))
2403  NowDeadNodes.push_back(ChainNode);
2404  }
2405  }
2406 
2407  if (!NowDeadNodes.empty())
2408  CurDAG->RemoveDeadNodes(NowDeadNodes);
2409 
2410  LLVM_DEBUG(dbgs() << "ISEL: Match complete!\n");
2411 }
2412 
2413 /// HandleMergeInputChains - This implements the OPC_EmitMergeInputChains
2414 /// operation for when the pattern matched at least one node with a chains. The
2415 /// input vector contains a list of all of the chained nodes that we match. We
2416 /// must determine if this is a valid thing to cover (i.e. matching it won't
2417 /// induce cycles in the DAG) and if so, creating a TokenFactor node. that will
2418 /// be used as the input node chain for the generated nodes.
2419 static SDValue
2421  SelectionDAG *CurDAG) {
2422 
2425  SmallVector<SDValue, 3> InputChains;
2426  unsigned int Max = 8192;
2427 
2428  // Quick exit on trivial merge.
2429  if (ChainNodesMatched.size() == 1)
2430  return ChainNodesMatched[0]->getOperand(0);
2431 
2432  // Add chains that aren't already added (internal). Peek through
2433  // token factors.
2434  std::function<void(const SDValue)> AddChains = [&](const SDValue V) {
2435  if (V.getValueType() != MVT::Other)
2436  return;
2437  if (V->getOpcode() == ISD::EntryToken)
2438  return;
2439  if (!Visited.insert(V.getNode()).second)
2440  return;
2441  if (V->getOpcode() == ISD::TokenFactor) {
2442  for (const SDValue &Op : V->op_values())
2443  AddChains(Op);
2444  } else
2445  InputChains.push_back(V);
2446  };
2447 
2448  for (auto *N : ChainNodesMatched) {
2449  Worklist.push_back(N);
2450  Visited.insert(N);
2451  }
2452 
2453  while (!Worklist.empty())
2454  AddChains(Worklist.pop_back_val()->getOperand(0));
2455 
2456  // Skip the search if there are no chain dependencies.
2457  if (InputChains.size() == 0)
2458  return CurDAG->getEntryNode();
2459 
2460  // If one of these chains is a successor of input, we must have a
2461  // node that is both the predecessor and successor of the
2462  // to-be-merged nodes. Fail.
2463  Visited.clear();
2464  for (SDValue V : InputChains)
2465  Worklist.push_back(V.getNode());
2466 
2467  for (auto *N : ChainNodesMatched)
2468  if (SDNode::hasPredecessorHelper(N, Visited, Worklist, Max, true))
2469  return SDValue();
2470 
2471  // Return merged chain.
2472  if (InputChains.size() == 1)
2473  return InputChains[0];
2474  return CurDAG->getNode(ISD::TokenFactor, SDLoc(ChainNodesMatched[0]),
2475  MVT::Other, InputChains);
2476 }
2477 
2478 /// MorphNode - Handle morphing a node in place for the selector.
2479 SDNode *SelectionDAGISel::
2480 MorphNode(SDNode *Node, unsigned TargetOpc, SDVTList VTList,
2481  ArrayRef<SDValue> Ops, unsigned EmitNodeInfo) {
2482  // It is possible we're using MorphNodeTo to replace a node with no
2483  // normal results with one that has a normal result (or we could be
2484  // adding a chain) and the input could have glue and chains as well.
2485  // In this case we need to shift the operands down.
2486  // FIXME: This is a horrible hack and broken in obscure cases, no worse
2487  // than the old isel though.
2488  int OldGlueResultNo = -1, OldChainResultNo = -1;
2489 
2490  unsigned NTMNumResults = Node->getNumValues();
2491  if (Node->getValueType(NTMNumResults-1) == MVT::Glue) {
2492  OldGlueResultNo = NTMNumResults-1;
2493  if (NTMNumResults != 1 &&
2494  Node->getValueType(NTMNumResults-2) == MVT::Other)
2495  OldChainResultNo = NTMNumResults-2;
2496  } else if (Node->getValueType(NTMNumResults-1) == MVT::Other)
2497  OldChainResultNo = NTMNumResults-1;
2498 
2499  // Call the underlying SelectionDAG routine to do the transmogrification. Note
2500  // that this deletes operands of the old node that become dead.
2501  SDNode *Res = CurDAG->MorphNodeTo(Node, ~TargetOpc, VTList, Ops);
2502 
2503  // MorphNodeTo can operate in two ways: if an existing node with the
2504  // specified operands exists, it can just return it. Otherwise, it
2505  // updates the node in place to have the requested operands.
2506  if (Res == Node) {
2507  // If we updated the node in place, reset the node ID. To the isel,
2508  // this should be just like a newly allocated machine node.
2509  Res->setNodeId(-1);
2510  }
2511 
2512  unsigned ResNumResults = Res->getNumValues();
2513  // Move the glue if needed.
2514  if ((EmitNodeInfo & OPFL_GlueOutput) && OldGlueResultNo != -1 &&
2515  (unsigned)OldGlueResultNo != ResNumResults-1)
2516  ReplaceUses(SDValue(Node, OldGlueResultNo),
2517  SDValue(Res, ResNumResults - 1));
2518 
2519  if ((EmitNodeInfo & OPFL_GlueOutput) != 0)
2520  --ResNumResults;
2521 
2522  // Move the chain reference if needed.
2523  if ((EmitNodeInfo & OPFL_Chain) && OldChainResultNo != -1 &&
2524  (unsigned)OldChainResultNo != ResNumResults-1)
2525  ReplaceUses(SDValue(Node, OldChainResultNo),
2526  SDValue(Res, ResNumResults - 1));
2527 
2528  // Otherwise, no replacement happened because the node already exists. Replace
2529  // Uses of the old node with the new one.
2530  if (Res != Node) {
2531  ReplaceNode(Node, Res);
2532  } else {
2534  }
2535 
2536  return Res;
2537 }
2538 
2539 /// CheckSame - Implements OP_CheckSame.
2540 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2541 CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2542  const SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes) {
2543  // Accept if it is exactly the same as a previously recorded node.
2544  unsigned RecNo = MatcherTable[MatcherIndex++];
2545  assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
2546  return N == RecordedNodes[RecNo].first;
2547 }
2548 
2549 /// CheckChildSame - Implements OP_CheckChildXSame.
2551  const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2552  const SmallVectorImpl<std::pair<SDValue, SDNode *>> &RecordedNodes,
2553  unsigned ChildNo) {
2554  if (ChildNo >= N.getNumOperands())
2555  return false; // Match fails if out of range child #.
2556  return ::CheckSame(MatcherTable, MatcherIndex, N.getOperand(ChildNo),
2557  RecordedNodes);
2558 }
2559 
2560 /// CheckPatternPredicate - Implements OP_CheckPatternPredicate.
2561 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2562 CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2563  const SelectionDAGISel &SDISel) {
2564  return SDISel.CheckPatternPredicate(MatcherTable[MatcherIndex++]);
2565 }
2566 
2567 /// CheckNodePredicate - Implements OP_CheckNodePredicate.
2568 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2569 CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2570  const SelectionDAGISel &SDISel, SDNode *N) {
2571  return SDISel.CheckNodePredicate(N, MatcherTable[MatcherIndex++]);
2572 }
2573 
2574 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2575 CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2576  SDNode *N) {
2577  uint16_t Opc = MatcherTable[MatcherIndex++];
2578  Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
2579  return N->getOpcode() == Opc;
2580 }
2581 
2582 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2583 CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2584  const TargetLowering *TLI, const DataLayout &DL) {
2585  MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2586  if (N.getValueType() == VT) return true;
2587 
2588  // Handle the case when VT is iPTR.
2589  return VT == MVT::iPTR && N.getValueType() == TLI->getPointerTy(DL);
2590 }
2591 
2592 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2593 CheckChildType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2594  SDValue N, const TargetLowering *TLI, const DataLayout &DL,
2595  unsigned ChildNo) {
2596  if (ChildNo >= N.getNumOperands())
2597  return false; // Match fails if out of range child #.
2598  return ::CheckType(MatcherTable, MatcherIndex, N.getOperand(ChildNo), TLI,
2599  DL);
2600 }
2601 
2602 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2603 CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2604  SDValue N) {
2605  return cast<CondCodeSDNode>(N)->get() ==
2606  (ISD::CondCode)MatcherTable[MatcherIndex++];
2607 }
2608 
2609 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2610 CheckChild2CondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2611  SDValue N) {
2612  if (2 >= N.getNumOperands())
2613  return false;
2614  return ::CheckCondCode(MatcherTable, MatcherIndex, N.getOperand(2));
2615 }
2616 
2617 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2618 CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2619  SDValue N, const TargetLowering *TLI, const DataLayout &DL) {
2620  MVT::SimpleValueType VT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
2621  if (cast<VTSDNode>(N)->getVT() == VT)
2622  return true;
2623 
2624  // Handle the case when VT is iPTR.
2625  return VT == MVT::iPTR && cast<VTSDNode>(N)->getVT() == TLI->getPointerTy(DL);
2626 }
2627 
2628 // Bit 0 stores the sign of the immediate. The upper bits contain the magnitude
2629 // shifted left by 1.
2631  if ((V & 1) == 0)
2632  return V >> 1;
2633  if (V != 1)
2634  return -(V >> 1);
2635  // There is no such thing as -0 with integers. "-0" really means MININT.
2636  return 1ULL << 63;
2637 }
2638 
2639 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2640 CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2641  SDValue N) {
2642  int64_t Val = MatcherTable[MatcherIndex++];
2643  if (Val & 128)
2644  Val = GetVBR(Val, MatcherTable, MatcherIndex);
2645 
2646  Val = decodeSignRotatedValue(Val);
2647 
2648  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N);
2649  return C && C->getSExtValue() == Val;
2650 }
2651 
2652 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2653 CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2654  SDValue N, unsigned ChildNo) {
2655  if (ChildNo >= N.getNumOperands())
2656  return false; // Match fails if out of range child #.
2657  return ::CheckInteger(MatcherTable, MatcherIndex, N.getOperand(ChildNo));
2658 }
2659 
2660 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2661 CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex,
2662  SDValue N, const SelectionDAGISel &SDISel) {
2663  int64_t Val = MatcherTable[MatcherIndex++];
2664  if (Val & 128)
2665  Val = GetVBR(Val, MatcherTable, MatcherIndex);
2666 
2667  if (N->getOpcode() != ISD::AND) return false;
2668 
2669  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2670  return C && SDISel.CheckAndMask(N.getOperand(0), C, Val);
2671 }
2672 
2673 LLVM_ATTRIBUTE_ALWAYS_INLINE static bool
2674 CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N,
2675  const SelectionDAGISel &SDISel) {
2676  int64_t Val = MatcherTable[MatcherIndex++];
2677  if (Val & 128)
2678  Val = GetVBR(Val, MatcherTable, MatcherIndex);
2679 
2680  if (N->getOpcode() != ISD::OR) return false;
2681 
2682  ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
2683  return C && SDISel.CheckOrMask(N.getOperand(0), C, Val);
2684 }
2685 
2686 /// IsPredicateKnownToFail - If we know how and can do so without pushing a
2687 /// scope, evaluate the current node. If the current predicate is known to
2688 /// fail, set Result=true and return anything. If the current predicate is
2689 /// known to pass, set Result=false and return the MatcherIndex to continue
2690 /// with. If the current predicate is unknown, set Result=false and return the
2691 /// MatcherIndex to continue with.
2692 static unsigned IsPredicateKnownToFail(const unsigned char *Table,
2693  unsigned Index, SDValue N,
2694  bool &Result,
2695  const SelectionDAGISel &SDISel,
2696  SmallVectorImpl<std::pair<SDValue, SDNode*>> &RecordedNodes) {
2697  switch (Table[Index++]) {
2698  default:
2699  Result = false;
2700  return Index-1; // Could not evaluate this predicate.
2702  Result = !::CheckSame(Table, Index, N, RecordedNodes);
2703  return Index;
2708  Result = !::CheckChildSame(Table, Index, N, RecordedNodes,
2710  return Index;
2712  Result = !::CheckPatternPredicate(Table, Index, SDISel);
2713  return Index;
2715  Result = !::CheckNodePredicate(Table, Index, SDISel, N.getNode());
2716  return Index;
2718  Result = !::CheckOpcode(Table, Index, N.getNode());
2719  return Index;
2721  Result = !::CheckType(Table, Index, N, SDISel.TLI,
2722  SDISel.CurDAG->getDataLayout());
2723  return Index;
2725  unsigned Res = Table[Index++];
2726  Result = !::CheckType(Table, Index, N.getValue(Res), SDISel.TLI,
2727  SDISel.CurDAG->getDataLayout());
2728  return Index;
2729  }
2738  Result = !::CheckChildType(
2739  Table, Index, N, SDISel.TLI, SDISel.CurDAG->getDataLayout(),
2741  return Index;
2743  Result = !::CheckCondCode(Table, Index, N);
2744  return Index;
2746  Result = !::CheckChild2CondCode(Table, Index, N);
2747  return Index;
2749  Result = !::CheckValueType(Table, Index, N, SDISel.TLI,
2750  SDISel.CurDAG->getDataLayout());
2751  return Index;
2753  Result = !::CheckInteger(Table, Index, N);
2754  return Index;
2760  Result = !::CheckChildInteger(Table, Index, N,
2762  return Index;
2764  Result = !::CheckAndImm(Table, Index, N, SDISel);
2765  return Index;
2767  Result = !::CheckOrImm(Table, Index, N, SDISel);
2768  return Index;
2769  }
2770 }
2771 
2772 namespace {
2773 
2774 struct MatchScope {
2775  /// FailIndex - If this match fails, this is the index to continue with.
2776  unsigned FailIndex;
2777 
2778  /// NodeStack - The node stack when the scope was formed.
2779  SmallVector<SDValue, 4> NodeStack;
2780 
2781  /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
2782  unsigned NumRecordedNodes;
2783 
2784  /// NumMatchedMemRefs - The number of matched memref entries.
2785  unsigned NumMatchedMemRefs;
2786 
2787  /// InputChain/InputGlue - The current chain/glue
2788  SDValue InputChain, InputGlue;
2789 
2790  /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
2791  bool HasChainNodesMatched;
2792 };
2793 
2794 /// \A DAG update listener to keep the matching state
2795 /// (i.e. RecordedNodes and MatchScope) uptodate if the target is allowed to
2796 /// change the DAG while matching. X86 addressing mode matcher is an example
2797 /// for this.
2798 class MatchStateUpdater : public SelectionDAG::DAGUpdateListener
2799 {
2800  SDNode **NodeToMatch;
2802  SmallVectorImpl<MatchScope> &MatchScopes;
2803 
2804 public:
2805  MatchStateUpdater(SelectionDAG &DAG, SDNode **NodeToMatch,
2806  SmallVectorImpl<std::pair<SDValue, SDNode *>> &RN,
2808  : SelectionDAG::DAGUpdateListener(DAG), NodeToMatch(NodeToMatch),
2809  RecordedNodes(RN), MatchScopes(MS) {}
2810 
2811  void NodeDeleted(SDNode *N, SDNode *E) override {
2812  // Some early-returns here to avoid the search if we deleted the node or
2813  // if the update comes from MorphNodeTo (MorphNodeTo is the last thing we
2814  // do, so it's unnecessary to update matching state at that point).
2815  // Neither of these can occur currently because we only install this
2816  // update listener during matching a complex patterns.
2817  if (!E || E->isMachineOpcode())
2818  return;
2819  // Check if NodeToMatch was updated.
2820  if (N == *NodeToMatch)
2821  *NodeToMatch = E;
2822  // Performing linear search here does not matter because we almost never
2823  // run this code. You'd have to have a CSE during complex pattern
2824  // matching.
2825  for (auto &I : RecordedNodes)
2826  if (I.first.getNode() == N)
2827  I.first.setNode(E);
2828 
2829  for (auto &I : MatchScopes)
2830  for (auto &J : I.NodeStack)
2831  if (J.getNode() == N)
2832  J.setNode(E);
2833  }
2834 };
2835 
2836 } // end anonymous namespace
2837 
2839  const unsigned char *MatcherTable,
2840  unsigned TableSize) {
2841  // FIXME: Should these even be selected? Handle these cases in the caller?
2842  switch (NodeToMatch->getOpcode()) {
2843  default:
2844  break;
2845  case ISD::EntryToken: // These nodes remain the same.
2846  case ISD::BasicBlock:
2847  case ISD::Register:
2848  case ISD::RegisterMask:
2849  case ISD::HANDLENODE:
2850  case ISD::MDNODE_SDNODE:
2851  case ISD::TargetConstant:
2852  case ISD::TargetConstantFP:
2854  case ISD::TargetFrameIndex:
2856  case ISD::MCSymbol:
2858  case ISD::TargetJumpTable:
2861  case ISD::TokenFactor:
2862  case ISD::CopyFromReg:
2863  case ISD::CopyToReg:
2864  case ISD::EH_LABEL:
2865  case ISD::ANNOTATION_LABEL:
2866  case ISD::LIFETIME_START:
2867  case ISD::LIFETIME_END:
2868  case ISD::PSEUDO_PROBE:
2869  NodeToMatch->setNodeId(-1); // Mark selected.
2870  return;
2871  case ISD::AssertSext:
2872  case ISD::AssertZext:
2873  case ISD::AssertAlign:
2874  ReplaceUses(SDValue(NodeToMatch, 0), NodeToMatch->getOperand(0));
2875  CurDAG->RemoveDeadNode(NodeToMatch);
2876  return;
2877  case ISD::INLINEASM:
2878  case ISD::INLINEASM_BR:
2879  Select_INLINEASM(NodeToMatch);
2880  return;
2881  case ISD::READ_REGISTER:
2882  Select_READ_REGISTER(NodeToMatch);
2883  return;
2884  case ISD::WRITE_REGISTER:
2885  Select_WRITE_REGISTER(NodeToMatch);
2886  return;
2887  case ISD::UNDEF:
2888  Select_UNDEF(NodeToMatch);
2889  return;
2890  case ISD::FREEZE:
2891  Select_FREEZE(NodeToMatch);
2892  return;
2893  case ISD::ARITH_FENCE:
2894  Select_ARITH_FENCE(NodeToMatch);
2895  return;
2896  }
2897 
2898  assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
2899 
2900  // Set up the node stack with NodeToMatch as the only node on the stack.
2901  SmallVector<SDValue, 8> NodeStack;
2902  SDValue N = SDValue(NodeToMatch, 0);
2903  NodeStack.push_back(N);
2904 
2905  // MatchScopes - Scopes used when matching, if a match failure happens, this
2906  // indicates where to continue checking.
2907  SmallVector<MatchScope, 8> MatchScopes;
2908 
2909  // RecordedNodes - This is the set of nodes that have been recorded by the
2910  // state machine. The second value is the parent of the node, or null if the
2911  // root is recorded.
2912  SmallVector<std::pair<SDValue, SDNode*>, 8> RecordedNodes;
2913 
2914  // MatchedMemRefs - This is the set of MemRef's we've seen in the input
2915  // pattern.
2916  SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
2917 
2918  // These are the current input chain and glue for use when generating nodes.
2919  // Various Emit operations change these. For example, emitting a copytoreg
2920  // uses and updates these.
2921  SDValue InputChain, InputGlue;
2922 
2923  // ChainNodesMatched - If a pattern matches nodes that have input/output
2924  // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
2925  // which ones they are. The result is captured into this list so that we can
2926  // update the chain results when the pattern is complete.
2927  SmallVector<SDNode*, 3> ChainNodesMatched;
2928 
2929  LLVM_DEBUG(dbgs() << "ISEL: Starting pattern match\n");
2930 
2931  // Determine where to start the interpreter. Normally we start at opcode #0,
2932  // but if the state machine starts with an OPC_SwitchOpcode, then we
2933  // accelerate the first lookup (which is guaranteed to be hot) with the
2934  // OpcodeOffset table.
2935  unsigned MatcherIndex = 0;
2936 
2937  if (!OpcodeOffset.empty()) {
2938  // Already computed the OpcodeOffset table, just index into it.
2939  if (N.getOpcode() < OpcodeOffset.size())
2940  MatcherIndex = OpcodeOffset[N.getOpcode()];
2941  LLVM_DEBUG(dbgs() << " Initial Opcode index to " << MatcherIndex << "\n");
2942 
2943  } else if (MatcherTable[0] == OPC_SwitchOpcode) {
2944  // Otherwise, the table isn't computed, but the state machine does start
2945  // with an OPC_SwitchOpcode instruction. Populate the table now, since this
2946  // is the first time we're selecting an instruction.
2947  unsigned Idx = 1;
2948  while (true) {
2949  // Get the size of this case.
2950  unsigned CaseSize = MatcherTable[Idx++];
2951  if (CaseSize & 128)
2952  CaseSize = GetVBR(CaseSize, MatcherTable, Idx);
2953  if (CaseSize == 0) break;
2954 
2955  // Get the opcode, add the index to the table.
2956  uint16_t Opc = MatcherTable[Idx++];
2957  Opc |= (unsigned short)MatcherTable[Idx++] << 8;
2958  if (Opc >= OpcodeOffset.size())
2959  OpcodeOffset.resize((Opc+1)*2);
2960  OpcodeOffset[Opc] = Idx;
2961  Idx += CaseSize;
2962  }
2963 
2964  // Okay, do the lookup for the first opcode.
2965  if (N.getOpcode() < OpcodeOffset.size())
2966  MatcherIndex = OpcodeOffset[N.getOpcode()];
2967  }
2968 
2969  while (true) {
2970  assert(MatcherIndex < TableSize && "Invalid index");
2971 #ifndef NDEBUG
2972  unsigned CurrentOpcodeIndex = MatcherIndex;
2973 #endif
2974  BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
2975  switch (Opcode) {
2976  case OPC_Scope: {
2977  // Okay, the semantics of this operation are that we should push a scope
2978  // then evaluate the first child. However, pushing a scope only to have
2979  // the first check fail (which then pops it) is inefficient. If we can
2980  // determine immediately that the first check (or first several) will
2981  // immediately fail, don't even bother pushing a scope for them.
2982  unsigned FailIndex;
2983 
2984  while (true) {
2985  unsigned NumToSkip = MatcherTable[MatcherIndex++];
2986  if (NumToSkip & 128)
2987  NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
2988  // Found the end of the scope with no match.
2989  if (NumToSkip == 0) {
2990  FailIndex = 0;
2991  break;
2992  }
2993 
2994  FailIndex = MatcherIndex+NumToSkip;
2995 
2996  unsigned MatcherIndexOfPredicate = MatcherIndex;
2997  (void)MatcherIndexOfPredicate; // silence warning.
2998 
2999  // If we can't evaluate this predicate without pushing a scope (e.g. if
3000  // it is a 'MoveParent') or if the predicate succeeds on this node, we
3001  // push the scope and evaluate the full predicate chain.
3002  bool Result;
3003  MatcherIndex = IsPredicateKnownToFail(MatcherTable, MatcherIndex, N,
3004  Result, *this, RecordedNodes);
3005  if (!Result)
3006  break;
3007 
3008  LLVM_DEBUG(
3009  dbgs() << " Skipped scope entry (due to false predicate) at "
3010  << "index " << MatcherIndexOfPredicate << ", continuing at "
3011  << FailIndex << "\n");
3012  ++NumDAGIselRetries;
3013 
3014  // Otherwise, we know that this case of the Scope is guaranteed to fail,
3015  // move to the next case.
3016  MatcherIndex = FailIndex;
3017  }
3018 
3019  // If the whole scope failed to match, bail.
3020  if (FailIndex == 0) break;
3021 
3022  // Push a MatchScope which indicates where to go if the first child fails
3023  // to match.
3024  MatchScope NewEntry;
3025  NewEntry.FailIndex = FailIndex;
3026  NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
3027  NewEntry.NumRecordedNodes = RecordedNodes.size();
3028  NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
3029  NewEntry.InputChain = InputChain;
3030  NewEntry.InputGlue = InputGlue;
3031  NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
3032  MatchScopes.push_back(NewEntry);
3033  continue;
3034  }
3035  case OPC_RecordNode: {
3036  // Remember this node, it may end up being an operand in the pattern.
3037  SDNode *Parent = nullptr;
3038  if (NodeStack.size() > 1)
3039  Parent = NodeStack[NodeStack.size()-2].getNode();
3040  RecordedNodes.push_back(std::make_pair(N, Parent));
3041  continue;
3042  }
3043 
3047  case OPC_RecordChild6: case OPC_RecordChild7: {
3048  unsigned ChildNo = Opcode-OPC_RecordChild0;
3049  if (ChildNo >= N.getNumOperands())
3050  break; // Match fails if out of range child #.
3051 
3052  RecordedNodes.push_back(std::make_pair(N->getOperand(ChildNo),
3053  N.getNode()));
3054  continue;
3055  }
3056  case OPC_RecordMemRef:
3057  if (auto *MN = dyn_cast<MemSDNode>(N))
3058  MatchedMemRefs.push_back(MN->getMemOperand());
3059  else {
3060  LLVM_DEBUG(dbgs() << "Expected MemSDNode "; N->dump(CurDAG);
3061  dbgs() << '\n');
3062  }
3063 
3064  continue;
3065 
3066  case OPC_CaptureGlueInput:
3067  // If the current node has an input glue, capture it in InputGlue.
3068  if (N->getNumOperands() != 0 &&
3069  N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue)
3070  InputGlue = N->getOperand(N->getNumOperands()-1);
3071  continue;
3072 
3073  case OPC_MoveChild: {
3074  unsigned ChildNo = MatcherTable[MatcherIndex++];
3075  if (ChildNo >= N.getNumOperands())
3076  break; // Match fails if out of range child #.
3077  N = N.getOperand(ChildNo);
3078  NodeStack.push_back(N);
3079  continue;
3080  }
3081 
3082  case OPC_MoveChild0: case OPC_MoveChild1:
3083  case OPC_MoveChild2: case OPC_MoveChild3:
3084  case OPC_MoveChild4: case OPC_MoveChild5:
3085  case OPC_MoveChild6: case OPC_MoveChild7: {
3086  unsigned ChildNo = Opcode-OPC_MoveChild0;
3087  if (ChildNo >= N.getNumOperands())
3088  break; // Match fails if out of range child #.
3089  N = N.getOperand(ChildNo);
3090  NodeStack.push_back(N);
3091  continue;
3092  }
3093 
3094  case OPC_MoveParent:
3095  // Pop the current node off the NodeStack.
3096  NodeStack.pop_back();
3097  assert(!NodeStack.empty() && "Node stack imbalance!");
3098  N = NodeStack.back();
3099  continue;
3100 
3101  case OPC_CheckSame:
3102  if (!::CheckSame(MatcherTable, MatcherIndex, N, RecordedNodes)) break;
3103  continue;
3104 
3107  if (!::CheckChildSame(MatcherTable, MatcherIndex, N, RecordedNodes,
3108  Opcode-OPC_CheckChild0Same))
3109  break;
3110  continue;
3111 
3113  if (!::CheckPatternPredicate(MatcherTable, MatcherIndex, *this)) break;
3114  continue;
3115  case OPC_CheckPredicate:
3116  if (!::CheckNodePredicate(MatcherTable, MatcherIndex, *this,
3117  N.getNode()))
3118  break;
3119  continue;
3121  unsigned OpNum = MatcherTable[MatcherIndex++];
3123 
3124  for (unsigned i = 0; i < OpNum; ++i)
3125  Operands.push_back(RecordedNodes[MatcherTable[MatcherIndex++]].first);
3126 
3127  unsigned PredNo = MatcherTable[MatcherIndex++];
3128  if (!CheckNodePredicateWithOperands(N.getNode(), PredNo, Operands))
3129  break;
3130  continue;
3131  }
3132  case OPC_CheckComplexPat: {
3133  unsigned CPNum = MatcherTable[MatcherIndex++];
3134  unsigned RecNo = MatcherTable[MatcherIndex++];
3135  assert(RecNo < RecordedNodes.size() && "Invalid CheckComplexPat");
3136 
3137  // If target can modify DAG during matching, keep the matching state
3138  // consistent.
3139  std::unique_ptr<MatchStateUpdater> MSU;
3141  MSU.reset(new MatchStateUpdater(*CurDAG, &NodeToMatch, RecordedNodes,
3142  MatchScopes));
3143 
3144  if (!CheckComplexPattern(NodeToMatch, RecordedNodes[RecNo].second,
3145  RecordedNodes[RecNo].first, CPNum,
3146  RecordedNodes))
3147  break;
3148  continue;
3149  }
3150  case OPC_CheckOpcode:
3151  if (!::CheckOpcode(MatcherTable, MatcherIndex, N.getNode())) break;
3152  continue;
3153 
3154  case OPC_CheckType:
3155  if (!::CheckType(MatcherTable, MatcherIndex, N, TLI,
3156  CurDAG->getDataLayout()))
3157  break;
3158  continue;
3159 
3160  case OPC_CheckTypeRes: {
3161  unsigned Res = MatcherTable[MatcherIndex++];
3162  if (!::CheckType(MatcherTable, MatcherIndex, N.getValue(Res), TLI,
3163  CurDAG->getDataLayout()))
3164  break;
3165  continue;
3166  }
3167 
3168  case OPC_SwitchOpcode: {
3169  unsigned CurNodeOpcode = N.getOpcode();
3170  unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3171  unsigned CaseSize;
3172  while (true) {
3173  // Get the size of this case.
3174  CaseSize = MatcherTable[MatcherIndex++];
3175  if (CaseSize & 128)
3176  CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3177  if (CaseSize == 0) break;
3178 
3179  uint16_t Opc = MatcherTable[MatcherIndex++];
3180  Opc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
3181 
3182  // If the opcode matches, then we will execute this case.
3183  if (CurNodeOpcode == Opc)
3184  break;
3185 
3186  // Otherwise, skip over this case.
3187  MatcherIndex += CaseSize;
3188  }
3189 
3190  // If no cases matched, bail out.
3191  if (CaseSize == 0) break;
3192 
3193  // Otherwise, execute the case we found.
3194  LLVM_DEBUG(dbgs() << " OpcodeSwitch from " << SwitchStart << " to "
3195  << MatcherIndex << "\n");
3196  continue;
3197  }
3198 
3199  case OPC_SwitchType: {
3200  MVT CurNodeVT = N.getSimpleValueType();
3201  unsigned SwitchStart = MatcherIndex-1; (void)SwitchStart;
3202  unsigned CaseSize;
3203  while (true) {
3204  // Get the size of this case.
3205  CaseSize = MatcherTable[MatcherIndex++];
3206  if (CaseSize & 128)
3207  CaseSize = GetVBR(CaseSize, MatcherTable, MatcherIndex);
3208  if (CaseSize == 0) break;
3209 
3210  MVT CaseVT = (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3211  if (CaseVT == MVT::iPTR)
3212  CaseVT = TLI->getPointerTy(CurDAG->getDataLayout());
3213 
3214  // If the VT matches, then we will execute this case.
3215  if (CurNodeVT == CaseVT)
3216  break;
3217 
3218  // Otherwise, skip over this case.
3219  MatcherIndex += CaseSize;
3220  }
3221 
3222  // If no cases matched, bail out.
3223  if (CaseSize == 0) break;
3224 
3225  // Otherwise, execute the case we found.
3226  LLVM_DEBUG(dbgs() << " TypeSwitch[" << EVT(CurNodeVT).getEVTString()
3227  << "] from " << SwitchStart << " to " << MatcherIndex
3228  << '\n');
3229  continue;
3230  }
3235  if (!::CheckChildType(MatcherTable, MatcherIndex, N, TLI,
3236  CurDAG->getDataLayout(),
3237  Opcode - OPC_CheckChild0Type))
3238  break;
3239  continue;
3240  case OPC_CheckCondCode:
3241  if (!::CheckCondCode(MatcherTable, MatcherIndex, N)) break;
3242  continue;
3244  if (!::CheckChild2CondCode(MatcherTable, MatcherIndex, N)) break;
3245  continue;
3246  case OPC_CheckValueType:
3247  if (!::CheckValueType(MatcherTable, MatcherIndex, N, TLI,
3248  CurDAG->getDataLayout()))
3249  break;
3250  continue;
3251  case OPC_CheckInteger:
3252  if (!::CheckInteger(MatcherTable, MatcherIndex, N)) break;
3253  continue;
3257  if (!::CheckChildInteger(MatcherTable, MatcherIndex, N,
3258  Opcode-OPC_CheckChild0Integer)) break;
3259  continue;
3260  case OPC_CheckAndImm:
3261  if (!::CheckAndImm(MatcherTable, MatcherIndex, N, *this)) break;
3262  continue;
3263  case OPC_CheckOrImm:
3264  if (!::CheckOrImm(MatcherTable, MatcherIndex, N, *this)) break;
3265  continue;
3266  case OPC_CheckImmAllOnesV:
3267  if (!ISD::isConstantSplatVectorAllOnes(N.getNode()))
3268  break;
3269  continue;
3270  case OPC_CheckImmAllZerosV:
3271  if (!ISD::isConstantSplatVectorAllZeros(N.getNode()))
3272  break;
3273  continue;
3274 
3276  assert(NodeStack.size() != 1 && "No parent node");
3277  // Verify that all intermediate nodes between the root and this one have
3278  // a single use (ignoring chains, which are handled in UpdateChains).
3279  bool HasMultipleUses = false;
3280  for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i) {
3281  unsigned NNonChainUses = 0;
3282  SDNode *NS = NodeStack[i].getNode();
3283  for (auto UI = NS->use_begin(), UE = NS->use_end(); UI != UE; ++UI)
3284  if (UI.getUse().getValueType() != MVT::Other)
3285  if (++NNonChainUses > 1) {
3286  HasMultipleUses = true;
3287  break;
3288  }
3289  if (HasMultipleUses) break;
3290  }
3291  if (HasMultipleUses) break;
3292 
3293  // Check to see that the target thinks this is profitable to fold and that
3294  // we can fold it without inducing cycles in the graph.
3295  if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
3296  NodeToMatch) ||
3297  !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
3298  NodeToMatch, OptLevel,
3299  true/*We validate our own chains*/))
3300  break;
3301 
3302  continue;
3303  }
3304  case OPC_EmitInteger:
3305  case OPC_EmitStringInteger: {
3307  (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3308  int64_t Val = MatcherTable[MatcherIndex++];
3309  if (Val & 128)
3310  Val = GetVBR(Val, MatcherTable, MatcherIndex);
3311  if (Opcode == OPC_EmitInteger)
3312  Val = decodeSignRotatedValue(Val);
3313  RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3314  CurDAG->getTargetConstant(Val, SDLoc(NodeToMatch),
3315  VT), nullptr));
3316  continue;
3317  }
3318  case OPC_EmitRegister: {
3320  (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3321  unsigned RegNo = MatcherTable[MatcherIndex++];
3322  RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3323  CurDAG->getRegister(RegNo, VT), nullptr));
3324  continue;
3325  }
3326  case OPC_EmitRegister2: {
3327  // For targets w/ more than 256 register names, the register enum
3328  // values are stored in two bytes in the matcher table (just like
3329  // opcodes).
3331  (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3332  unsigned RegNo = MatcherTable[MatcherIndex++];
3333  RegNo |= MatcherTable[MatcherIndex++] << 8;
3334  RecordedNodes.push_back(std::pair<SDValue, SDNode*>(
3335  CurDAG->getRegister(RegNo, VT), nullptr));
3336  continue;
3337  }
3338 
3339  case OPC_EmitConvertToTarget: {
3340  // Convert from IMM/FPIMM to target version.
3341  unsigned RecNo = MatcherTable[MatcherIndex++];
3342  assert(RecNo < RecordedNodes.size() && "Invalid EmitConvertToTarget");
3343  SDValue Imm = RecordedNodes[RecNo].first;
3344 
3345  if (Imm->getOpcode() == ISD::Constant) {
3346  const ConstantInt *Val=cast<ConstantSDNode>(Imm)->getConstantIntValue();
3347  Imm = CurDAG->getTargetConstant(*Val, SDLoc(NodeToMatch),
3348  Imm.getValueType());
3349  } else if (Imm->getOpcode() == ISD::ConstantFP) {
3350  const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
3351  Imm = CurDAG->getTargetConstantFP(*Val, SDLoc(NodeToMatch),
3352  Imm.getValueType());
3353  }
3354 
3355  RecordedNodes.push_back(std::make_pair(Imm, RecordedNodes[RecNo].second));
3356  continue;
3357  }
3358 
3359  case OPC_EmitMergeInputChains1_0: // OPC_EmitMergeInputChains, 1, 0
3360  case OPC_EmitMergeInputChains1_1: // OPC_EmitMergeInputChains, 1, 1
3361  case OPC_EmitMergeInputChains1_2: { // OPC_EmitMergeInputChains, 1, 2
3362  // These are space-optimized forms of OPC_EmitMergeInputChains.
3363  assert(!InputChain.getNode() &&
3364  "EmitMergeInputChains should be the first chain producing node");
3365  assert(ChainNodesMatched.empty() &&
3366  "Should only have one EmitMergeInputChains per match");
3367 
3368  // Read all of the chained nodes.
3369  unsigned RecNo = Opcode - OPC_EmitMergeInputChains1_0;
3370  assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
3371  ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3372 
3373  // FIXME: What if other value results of the node have uses not matched
3374  // by this pattern?
3375  if (ChainNodesMatched.back() != NodeToMatch &&
3376  !RecordedNodes[RecNo].first.hasOneUse()) {
3377  ChainNodesMatched.clear();
3378  break;
3379  }
3380 
3381  // Merge the input chains if they are not intra-pattern references.
3382  InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
3383 
3384  if (!InputChain.getNode())
3385  break; // Failed to merge.
3386  continue;
3387  }
3388 
3389  case OPC_EmitMergeInputChains: {
3390  assert(!InputChain.getNode() &&
3391  "EmitMergeInputChains should be the first chain producing node");
3392  // This node gets a list of nodes we matched in the input that have
3393  // chains. We want to token factor all of the input chains to these nodes
3394  // together. However, if any of the input chains is actually one of the
3395  // nodes matched in this pattern, then we have an intra-match reference.
3396  // Ignore these because the newly token factored chain should not refer to
3397  // the old nodes.
3398  unsigned NumChains = MatcherTable[MatcherIndex++];
3399  assert(NumChains != 0 && "Can't TF zero chains");
3400 
3401  assert(ChainNodesMatched.empty() &&
3402  "Should only have one EmitMergeInputChains per match");
3403 
3404  // Read all of the chained nodes.
3405  for (unsigned i = 0; i != NumChains; ++i) {
3406  unsigned RecNo = MatcherTable[MatcherIndex++];
3407  assert(RecNo < RecordedNodes.size() && "Invalid EmitMergeInputChains");
3408  ChainNodesMatched.push_back(RecordedNodes[RecNo].first.getNode());
3409 
3410  // FIXME: What if other value results of the node have uses not matched
3411  // by this pattern?
3412  if (ChainNodesMatched.back() != NodeToMatch &&
3413  !RecordedNodes[RecNo].first.hasOneUse()) {
3414  ChainNodesMatched.clear();
3415  break;
3416  }
3417  }
3418 
3419  // If the inner loop broke out, the match fails.
3420  if (ChainNodesMatched.empty())
3421  break;
3422 
3423  // Merge the input chains if they are not intra-pattern references.
3424  InputChain = HandleMergeInputChains(ChainNodesMatched, CurDAG);
3425 
3426  if (!InputChain.getNode())
3427  break; // Failed to merge.
3428 
3429  continue;
3430  }
3431 
3432  case OPC_EmitCopyToReg:
3433  case OPC_EmitCopyToReg2: {
3434  unsigned RecNo = MatcherTable[MatcherIndex++];
3435  assert(RecNo < RecordedNodes.size() && "Invalid EmitCopyToReg");
3436  unsigned DestPhysReg = MatcherTable[MatcherIndex++];
3437  if (Opcode == OPC_EmitCopyToReg2)
3438  DestPhysReg |= MatcherTable[MatcherIndex++] << 8;
3439 
3440  if (!InputChain.getNode())
3441  InputChain = CurDAG->getEntryNode();
3442 
3443  InputChain = CurDAG->getCopyToReg(InputChain, SDLoc(NodeToMatch),
3444  DestPhysReg, RecordedNodes[RecNo].first,
3445  InputGlue);
3446 
3447  InputGlue = InputChain.getValue(1);
3448  continue;
3449  }
3450 
3451  case OPC_EmitNodeXForm: {
3452  unsigned XFormNo = MatcherTable[MatcherIndex++];
3453  unsigned RecNo = MatcherTable[MatcherIndex++];
3454  assert(RecNo < RecordedNodes.size() && "Invalid EmitNodeXForm");
3455  SDValue Res = RunSDNodeXForm(RecordedNodes[RecNo].first, XFormNo);
3456  RecordedNodes.push_back(std::pair<SDValue,SDNode*>(Res, nullptr));
3457  continue;
3458  }
3459  case OPC_Coverage: {
3460  // This is emitted right before MorphNode/EmitNode.
3461  // So it should be safe to assume that this node has been selected
3462  unsigned index = MatcherTable[MatcherIndex++];
3463  index |= (MatcherTable[MatcherIndex++] << 8);
3464  dbgs() << "COVERED: " << getPatternForIndex(index) << "\n";
3465  dbgs() << "INCLUDED: " << getIncludePathForIndex(index) << "\n";
3466  continue;
3467  }
3468 
3469  case OPC_EmitNode: case OPC_MorphNodeTo:
3470  case OPC_EmitNode0: case OPC_EmitNode1: case OPC_EmitNode2:
3472  uint16_t TargetOpc = MatcherTable[MatcherIndex++];
3473  TargetOpc |= (unsigned short)MatcherTable[MatcherIndex++] << 8;
3474  unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
3475  // Get the result VT list.
3476  unsigned NumVTs;
3477  // If this is one of the compressed forms, get the number of VTs based
3478  // on the Opcode. Otherwise read the next byte from the table.
3479  if (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2)
3480  NumVTs = Opcode - OPC_MorphNodeTo0;
3481  else if (Opcode >= OPC_EmitNode0 && Opcode <= OPC_EmitNode2)
3482  NumVTs = Opcode - OPC_EmitNode0;
3483  else
3484  NumVTs = MatcherTable[MatcherIndex++];
3485  SmallVector<EVT, 4> VTs;
3486  for (unsigned i = 0; i != NumVTs; ++i) {
3488  (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
3489  if (VT == MVT::iPTR)
3490  VT = TLI->getPointerTy(CurDAG->getDataLayout()).SimpleTy;
3491  VTs.push_back(VT);
3492  }
3493 
3494  if (EmitNodeInfo & OPFL_Chain)
3495  VTs.push_back(MVT::Other);
3496  if (EmitNodeInfo & OPFL_GlueOutput)
3497  VTs.push_back(MVT::Glue);
3498 
3499  // This is hot code, so optimize the two most common cases of 1 and 2
3500  // results.
3501  SDVTList VTList;
3502  if (VTs.size() == 1)
3503  VTList = CurDAG->getVTList(VTs[0]);
3504  else if (VTs.size() == 2)
3505  VTList = CurDAG->getVTList(VTs[0], VTs[1]);
3506  else
3507  VTList = CurDAG->getVTList(VTs);
3508 
3509  // Get the operand list.
3510  unsigned NumOps = MatcherTable[MatcherIndex++];
3512  for (unsigned i = 0; i != NumOps; ++i) {
3513  unsigned RecNo = MatcherTable[MatcherIndex++];
3514  if (RecNo & 128)
3515  RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
3516 
3517  assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
3518  Ops.push_back(RecordedNodes[RecNo].first);
3519  }
3520 
3521  // If there are variadic operands to add, handle them now.
3522  if (EmitNodeInfo & OPFL_VariadicInfo) {
3523  // Determine the start index to copy from.
3524  unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
3525  FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
3526  assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
3527  "Invalid variadic node");
3528  // Copy all of the variadic operands, not including a potential glue
3529  // input.
3530  for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
3531  i != e; ++i) {
3532  SDValue V = NodeToMatch->getOperand(i);
3533  if (V.getValueType() == MVT::Glue) break;
3534  Ops.push_back(V);
3535  }
3536  }
3537 
3538  // If this has chain/glue inputs, add them.
3539  if (EmitNodeInfo & OPFL_Chain)
3540  Ops.push_back(InputChain);
3541  if ((EmitNodeInfo & OPFL_GlueInput) && InputGlue.getNode() != nullptr)
3542  Ops.push_back(InputGlue);
3543 
3544  // Check whether any matched node could raise an FP exception. Since all
3545  // such nodes must have a chain, it suffices to check ChainNodesMatched.
3546  // We need to perform this check before potentially modifying one of the
3547  // nodes via MorphNode.
3548  bool MayRaiseFPException = false;
3549  for (auto *N : ChainNodesMatched)
3550  if (mayRaiseFPException(N) && !N->getFlags().hasNoFPExcept()) {
3551  MayRaiseFPException = true;
3552  break;
3553  }
3554 
3555  // Create the node.
3556  MachineSDNode *Res = nullptr;
3557  bool IsMorphNodeTo = Opcode == OPC_MorphNodeTo ||
3558  (Opcode >= OPC_MorphNodeTo0 && Opcode <= OPC_MorphNodeTo2);
3559  if (!IsMorphNodeTo) {
3560  // If this is a normal EmitNode command, just create the new node and
3561  // add the results to the RecordedNodes list.
3562  Res = CurDAG->getMachineNode(TargetOpc, SDLoc(NodeToMatch),
3563  VTList, Ops);
3564 
3565  // Add all the non-glue/non-chain results to the RecordedNodes list.
3566  for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
3567  if (VTs[i] == MVT::Other || VTs[i] == MVT::Glue) break;
3568  RecordedNodes.push_back(std::pair<SDValue,SDNode*>(SDValue(Res, i),
3569  nullptr));
3570  }
3571  } else {
3572  assert(NodeToMatch->getOpcode() != ISD::DELETED_NODE &&
3573  "NodeToMatch was removed partway through selection");
3575  SDNode *E) {
3577  auto &Chain = ChainNodesMatched;
3578  assert((!E || !is_contained(Chain, N)) &&
3579  "Chain node replaced during MorphNode");
3580  llvm::erase_value(Chain, N);
3581  });
3582  Res = cast<MachineSDNode>(MorphNode(NodeToMatch, TargetOpc, VTList,
3583  Ops, EmitNodeInfo));
3584  }
3585 
3586  // Set the NoFPExcept flag when no original matched node could
3587  // raise an FP exception, but the new node potentially might.
3589  SDNodeFlags Flags = Res->getFlags();
3590  Flags.setNoFPExcept(true);
3591  Res->setFlags(Flags);
3592  }
3593 
3594  // If the node had chain/glue results, update our notion of the current
3595  // chain and glue.
3596  if (EmitNodeInfo & OPFL_GlueOutput) {
3597  InputGlue = SDValue(Res, VTs.size()-1);
3598  if (EmitNodeInfo & OPFL_Chain)
3599  InputChain = SDValue(Res, VTs.size()-2);
3600  } else if (EmitNodeInfo & OPFL_Chain)
3601  InputChain = SDValue(Res, VTs.size()-1);
3602 
3603  // If the OPFL_MemRefs glue is set on this node, slap all of the
3604  // accumulated memrefs onto it.
3605  //
3606  // FIXME: This is vastly incorrect for patterns with multiple outputs
3607  // instructions that access memory and for ComplexPatterns that match
3608  // loads.
3609  if (EmitNodeInfo & OPFL_MemRefs) {
3610  // Only attach load or store memory operands if the generated
3611  // instruction may load or store.
3612  const MCInstrDesc &MCID = TII->get(TargetOpc);
3613  bool mayLoad = MCID.mayLoad();
3614  bool mayStore = MCID.mayStore();
3615 
3616  // We expect to have relatively few of these so just filter them into a
3617  // temporary buffer so that we can easily add them to the instruction.
3618  SmallVector<MachineMemOperand *, 4> FilteredMemRefs;
3619  for (MachineMemOperand *MMO : MatchedMemRefs) {
3620  if (MMO->isLoad()) {
3621  if (mayLoad)
3622  FilteredMemRefs.push_back(MMO);
3623  } else if (MMO->isStore()) {
3624  if (mayStore)
3625  FilteredMemRefs.push_back(MMO);
3626  } else {
3627  FilteredMemRefs.push_back(MMO);
3628  }
3629  }
3630 
3631  CurDAG->setNodeMemRefs(Res, FilteredMemRefs);
3632  }
3633 
3634  LLVM_DEBUG(if (!MatchedMemRefs.empty() && Res->memoperands_empty()) dbgs()
3635  << " Dropping mem operands\n";
3636  dbgs() << " " << (IsMorphNodeTo ? "Morphed" : "Created")
3637  << " node: ";
3638  Res->dump(CurDAG););
3639 
3640  // If this was a MorphNodeTo then we're completely done!
3641  if (IsMorphNodeTo) {
3642  // Update chain uses.
3643  UpdateChains(Res, InputChain, ChainNodesMatched, true);
3644  return;
3645  }
3646  continue;
3647  }
3648 
3649  case OPC_CompleteMatch: {
3650  // The match has been completed, and any new nodes (if any) have been
3651  // created. Patch up references to the matched dag to use the newly
3652  // created nodes.
3653  unsigned NumResults = MatcherTable[MatcherIndex++];
3654 
3655  for (unsigned i = 0; i != NumResults; ++i) {
3656  unsigned ResSlot = MatcherTable[MatcherIndex++];
3657  if (ResSlot & 128)
3658  ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
3659 
3660  assert(ResSlot < RecordedNodes.size() && "Invalid CompleteMatch");
3661  SDValue Res = RecordedNodes[ResSlot].first;
3662 
3663  assert(i < NodeToMatch->getNumValues() &&
3664  NodeToMatch->getValueType(i) != MVT::Other &&
3665  NodeToMatch->getValueType(i) != MVT::Glue &&
3666  "Invalid number of results to complete!");
3667  assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
3668  NodeToMatch->getValueType(i) == MVT::iPTR ||
3669  Res.getValueType() == MVT::iPTR ||
3670  NodeToMatch->getValueType(i).getSizeInBits() ==
3671  Res.getValueSizeInBits()) &&
3672  "invalid replacement");
3673  ReplaceUses(SDValue(NodeToMatch, i), Res);
3674  }
3675 
3676  // Update chain uses.
3677  UpdateChains(NodeToMatch, InputChain, ChainNodesMatched, false);
3678 
3679  // If the root node defines glue, we need to update it to the glue result.
3680  // TODO: This never happens in our tests and I think it can be removed /
3681  // replaced with an assert, but if we do it this the way the change is
3682  // NFC.
3683  if (NodeToMatch->getValueType(NodeToMatch->getNumValues() - 1) ==
3684  MVT::Glue &&
3685  InputGlue.getNode())
3686  ReplaceUses(SDValue(NodeToMatch, NodeToMatch->getNumValues() - 1),
3687  InputGlue);
3688 
3689  assert(NodeToMatch->use_empty() &&
3690  "Didn't replace all uses of the node?");
3691  CurDAG->RemoveDeadNode(NodeToMatch);
3692 
3693  return;
3694  }
3695  }
3696 
3697  // If the code reached this point, then the match failed. See if there is
3698  // another child to try in the current 'Scope', otherwise pop it until we
3699  // find a case to check.
3700  LLVM_DEBUG(dbgs() << " Match failed at index " << CurrentOpcodeIndex
3701  << "\n");
3702  ++NumDAGIselRetries;
3703  while (true) {
3704  if (MatchScopes.empty()) {
3705  CannotYetSelect(NodeToMatch);
3706  return;
3707  }
3708 
3709  // Restore the interpreter state back to the point where the scope was
3710  // formed.
3711  MatchScope &LastScope = MatchScopes.back();
3712  RecordedNodes.resize(LastScope.NumRecordedNodes);
3713  NodeStack.clear();
3714  NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
3715  N = NodeStack.back();
3716 
3717  if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
3718  MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
3719  MatcherIndex = LastScope.FailIndex;
3720 
3721  LLVM_DEBUG(dbgs() << " Continuing at " << MatcherIndex << "\n");
3722 
3723  InputChain = LastScope.InputChain;
3724  InputGlue = LastScope.InputGlue;
3725  if (!LastScope.HasChainNodesMatched)
3726  ChainNodesMatched.clear();
3727 
3728  // Check to see what the offset is at the new MatcherIndex. If it is zero
3729  // we have reached the end of this scope, otherwise we have another child
3730  // in the current scope to try.
3731  unsigned NumToSkip = MatcherTable[MatcherIndex++];
3732  if (NumToSkip & 128)
3733  NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
3734 
3735  // If we have another child in this scope to match, update FailIndex and
3736  // try it.
3737  if (NumToSkip != 0) {
3738  LastScope.FailIndex = MatcherIndex+NumToSkip;
3739  break;
3740  }
3741 
3742  // End of this scope, pop it and try the next child in the containing
3743  // scope.
3744  MatchScopes.pop_back();
3745  }
3746  }
3747 }
3748 
3749 /// Return whether the node may raise an FP exception.
3751  // For machine opcodes, consult the MCID flag.
3752  if (N->isMachineOpcode()) {
3753  const MCInstrDesc &MCID = TII->get(N->getMachineOpcode());
3754  return MCID.mayRaiseFPException();
3755  }
3756 
3757  // For ISD opcodes, only StrictFP opcodes may raise an FP
3758  // exception.
3759  if (N->isTargetOpcode())
3760  return N->isTargetStrictFPOpcode();
3761  return N->isStrictFPOpcode();
3762 }
3763 
3765  assert(N->getOpcode() == ISD::OR && "Unexpected opcode");
3766  auto *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
3767  if (!C)
3768  return false;
3769 
3770  // Detect when "or" is used to add an offset to a stack object.
3771  if (auto *FN = dyn_cast<FrameIndexSDNode>(N->getOperand(0))) {
3772  MachineFrameInfo &MFI = MF->getFrameInfo();
3773  Align A = MFI.getObjectAlign(FN->getIndex());
3774  int32_t Off = C->getSExtValue();
3775  // If the alleged offset fits in the zero bits guaranteed by
3776  // the alignment, then this or is really an add.
3777  return (Off >= 0) && (((A.value() - 1) & Off) == unsigned(Off));
3778  }
3779  return false;
3780 }
3781 
3782 void SelectionDAGISel::CannotYetSelect(SDNode *N) {
3783  std::string msg;
3784  raw_string_ostream Msg(msg);
3785  Msg << "Cannot select: ";
3786 
3787  if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&
3788  N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&
3789  N->getOpcode() != ISD::INTRINSIC_VOID) {
3790  N->printrFull(Msg, CurDAG);
3791  Msg << "\nIn function: " << MF->getName();
3792  } else {
3793  bool HasInputChain = N->getOperand(0).getValueType() == MVT::Other;
3794  unsigned iid =
3795  cast<ConstantSDNode>(N->getOperand(HasInputChain))->getZExtValue();
3796  if (iid < Intrinsic::num_intrinsics)
3797  Msg << "intrinsic %" << Intrinsic::getBaseName((Intrinsic::ID)iid);
3798  else if (const TargetIntrinsicInfo *TII = TM.getIntrinsicInfo())
3799  Msg << "target intrinsic %" << TII->getName(iid);
3800  else
3801  Msg << "unknown intrinsic #" << iid;
3802  }
3803  report_fatal_error(Msg.str());
3804 }
3805 
3806 char SelectionDAGISel::ID = 0;
llvm::DIExpression::prepend
static DIExpression * prepend(const DIExpression *Expr, uint8_t Flags, int64_t Offset=0)
Prepend DIExpr with a deref and offset operation and optionally turn it into a stack value or/and an ...
Definition: DebugInfoMetadata.cpp:1285
llvm::FunctionLoweringInfo::Fn
const Function * Fn
Definition: FunctionLoweringInfo.h:55
llvm::Intrinsic::getBaseName
StringRef getBaseName(ID id)
Return the LLVM name for an intrinsic, without encoded types for overloading, such as "llvm....
Definition: Function.cpp:831
llvm::MachineInstr::isDebugValue
bool isDebugValue() const
Definition: MachineInstr.h:1216
llvm::SelectionDAGISel::OPC_MoveChild2
@ OPC_MoveChild2
Definition: SelectionDAGISel.h:123
i
i
Definition: README.txt:29
llvm::HexagonInstrInfo::isTailCall
bool isTailCall(const MachineInstr &MI) const override
Definition: HexagonInstrInfo.cpp:2611
llvm::MachineFunction::hasInlineAsm
bool hasInlineAsm() const
Returns true if the function contains any inline assembly.
Definition: MachineFunction.h:695
ValueTypes.h
CheckSame
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SmallVectorImpl< std::pair< SDValue, SDNode * >> &RecordedNodes)
CheckSame - Implements OP_CheckSame.
Definition: SelectionDAGISel.cpp:2541
llvm::SelectionDAGISel::FastISelFailed
bool FastISelFailed
Definition: SelectionDAGISel.h:54
llvm::DbgVariableIntrinsic::getExpression
DIExpression * getExpression() const
Definition: IntrinsicInst.h:257
llvm::ConstantSDNode
Definition: SelectionDAGNodes.h:1542
llvm::SelectionDAGISel::OPC_CheckComplexPat
@ OPC_CheckComplexPat
Definition: SelectionDAGISel.h:145
llvm::BasicBlock::end
iterator end()
Definition: BasicBlock.h:298
llvm::ISD::STRICT_FSETCC
@ STRICT_FSETCC
STRICT_FSETCC/STRICT_FSETCCS - Constrained versions of SETCC, used for floating-point operands only.
Definition: ISDOpcodes.h:462
llvm::FunctionLoweringInfo::StaticAllocaMap
DenseMap< const AllocaInst *, int > StaticAllocaMap
StaticAllocaMap - Keep track of frame indices for fixed sized allocas in the entry block.
Definition: FunctionLoweringInfo.h:125
StackProtector.h
llvm::SelectionDAGISel::OPC_EmitInteger
@ OPC_EmitInteger
Definition: SelectionDAGISel.h:151
llvm::OptimizationRemarkMissed
Diagnostic information for missed-optimization remarks.
Definition: DiagnosticInfo.h:729
llvm::createDAGLinearizer
ScheduleDAGSDNodes * createDAGLinearizer(SelectionDAGISel *IS, CodeGenOpt::Level OptLevel)
createDAGLinearizer - This creates a "no-scheduling" scheduler which linearize the DAG using topologi...
Definition: ScheduleDAGFast.cpp:802
llvm::predecessors
pred_range predecessors(BasicBlock *BB)
Definition: CFG.h:127
isFoldedOrDeadInstruction
static bool isFoldedOrDeadInstruction(const Instruction *I, const FunctionLoweringInfo &FuncInfo)
isFoldedOrDeadInstruction - Return true if the specified instruction is side-effect free and is eithe...
Definition: SelectionDAGISel.cpp:1313
llvm::SelectionDAG::VerifyDAGDiverence
void VerifyDAGDiverence()
Definition: SelectionDAG.cpp:9309
llvm::MachineFunctionProperties::hasProperty
bool hasProperty(Property P) const
Definition: MachineFunction.h:165
llvm::ISD::INTRINSIC_VOID
@ INTRINSIC_VOID
OUTCHAIN = INTRINSIC_VOID(INCHAIN, INTRINSICID, arg1, arg2, ...) This node represents a target intrin...
Definition: ISDOpcodes.h:199
llvm::SDUse
Represents a use of a SDNode.
Definition: SelectionDAGNodes.h:277
llvm::SelectionDAGISel::OPC_CheckChild2Integer
@ OPC_CheckChild2Integer
Definition: SelectionDAGISel.h:141
MI
IRTranslator LLVM IR MI
Definition: IRTranslator.cpp:102
MachineInstr.h
llvm::SelectionDAGISel::TLI
const TargetLowering * TLI
Definition: SelectionDAGISel.h:53
llvm
---------------------— PointerInfo ------------------------------------—
Definition: AllocatorList.h:23
llvm::SelectionDAGISel::getIncludePathForIndex
virtual StringRef getIncludePathForIndex(unsigned index)
getIncludePathForIndex - get the td source location of pattern instantiation
Definition: SelectionDAGISel.h:244
llvm::tgtok::Def
@ Def
Definition: TGLexer.h:50
llvm::DbgDeclareInst::getAddress
Value * getAddress() const
Definition: IntrinsicInst.h:310
llvm::DiagnosticInfoISelFallback
Diagnostic information for ISel fallback path.
Definition: DiagnosticInfo.h:949
Reg
unsigned Reg
Definition: MachineSink.cpp:1566
llvm::SelectionDAG::AssignTopologicalOrder
unsigned AssignTopologicalOrder()
Topological-sort the AllNodes list and a assign a unique node id for each node in the DAG based on th...
Definition: SelectionDAG.cpp:9382
GCMetadata.h
llvm::SelectionDAGISel::TM
TargetMachine & TM
Definition: SelectionDAGISel.h:41
llvm::MCSymbol
MCSymbol - Instances of this class represent a symbol name in the MC file, and MCSymbols are created ...
Definition: MCSymbol.h:41
llvm::SDNode::getValueType
EVT getValueType(unsigned ResNo) const
Return the type of a specified result.
Definition: SelectionDAGNodes.h:958
UseMI
MachineInstrBuilder & UseMI
Definition: AArch64ExpandPseudoInsts.cpp:102
llvm::SelectionDAGISel::isOrEquivalentToAdd
bool isOrEquivalentToAdd(const SDNode *N) const
Definition: SelectionDAGISel.cpp:3764
llvm::ScheduleDAGSDNodes
ScheduleDAGSDNodes - A ScheduleDAG for scheduling SDNode-based DAGs.
Definition: ScheduleDAGSDNodes.h:46
llvm::SelectionDAGISel::OPFL_GlueInput
@ OPFL_GlueInput
Definition: SelectionDAGISel.h:177
llvm::SDLoc
Wrapper class for IR location info (IR ordering and DebugLoc) to be passed into SDNode creation funct...
Definition: SelectionDAGNodes.h:1078
llvm::SelectionDAGISel::OPC_EmitMergeInputChains1_2
@ OPC_EmitMergeInputChains1_2
Definition: SelectionDAGISel.h:159
llvm::DataLayout
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:112
llvm::ISD::OR
@ OR
Definition: ISDOpcodes.h:633
llvm::SelectionDAGISel::EnforceNodeIdInvariant
static void EnforceNodeIdInvariant(SDNode *N)
Definition: SelectionDAGISel.cpp:1067
llvm::TargetLowering::EmitInstrWithCustomInserter
virtual MachineBasicBlock * EmitInstrWithCustomInserter(MachineInstr &MI, MachineBasicBlock *MBB) const
This method should be implemented by targets that mark instructions with the 'usesCustomInserter' fla...
Definition: SelectionDAGISel.cpp:294
CheckChildSame
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckChildSame(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SmallVectorImpl< std::pair< SDValue, SDNode * >> &RecordedNodes, unsigned ChildNo)
CheckChildSame - Implements OP_CheckChildXSame.
Definition: SelectionDAGISel.cpp:2550
llvm::Value::hasOneUse
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition: Value.h:435
llvm::MachineBasicBlock::getBasicBlock
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
Definition: MachineBasicBlock.h:202
llvm::SelectionDAGISel::CheckComplexPattern
virtual bool CheckComplexPattern(SDNode *Root, SDNode *Parent, SDValue N, unsigned PatternNo, SmallVectorImpl< std::pair< SDValue, SDNode * > > &Result)
Definition: SelectionDAGISel.h:287
Metadata.h
llvm::ISD::LIFETIME_END
@ LIFETIME_END
Definition: ISDOpcodes.h:1178
llvm::SelectionDAGISel::OPC_RecordChild7
@ OPC_RecordChild7
Definition: SelectionDAGISel.h:119
llvm::SelectionDAGISel::PostprocessISelDAG
virtual void PostprocessISelDAG()
PostprocessISelDAG() - This hook allows the target to hack on the graph right after selection.
Definition: SelectionDAGISel.h:81
llvm::BasicBlock::iterator
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:90
llvm::TargetLoweringBase::isStrictFPEnabled
bool isStrictFPEnabled() const
Return true if the target support strict float operation.
Definition: TargetLowering.h:329
llvm::ConstantSDNode::getAPIntValue
const APInt & getAPIntValue() const
Definition: SelectionDAGNodes.h:1556
IntrinsicInst.h
computeUsesMSVCFloatingPoint
static void computeUsesMSVCFloatingPoint(const Triple &TT, const Function &F, MachineModuleInfo &MMI)
Definition: SelectionDAGISel.cpp:391
hasExceptionPointerOrCodeUser
static bool hasExceptionPointerOrCodeUser(const CatchPadInst *CPI)
Definition: SelectionDAGISel.cpp:1206
DebugInfoMetadata.h
llvm::ISD::AssertSext
@ AssertSext
AssertSext, AssertZext - These nodes record if a register contains a value that has already been zero...
Definition: ISDOpcodes.h:61
llvm::SelectionDAG::getCopyToReg
SDValue getCopyToReg(SDValue Chain, const SDLoc &dl, unsigned Reg, SDValue N)
Definition: SelectionDAG.h:735
MCInstrDesc.h
llvm::SelectionDAGISel::DAGSize
unsigned DAGSize
DAGSize - Size of DAG being instruction selected.
Definition: SelectionDAGISel.h:202
EnableFastISelAbort
static cl::opt< int > EnableFastISelAbort("fast-isel-abort", cl::Hidden, cl::desc("Enable abort calls when \"fast\" instruction selection " "fails to lower an instruction: 0 disable the abort, 1 will " "abort but for args, calls and terminators, 2 will also " "abort for argument lowering, and 3 will never fallback " "to SelectionDAG."))
InstIterator.h
MachinePassRegistry.h
llvm::MachineRegisterInfo
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
Definition: MachineRegisterInfo.h:52
llvm::SDValue::getNode
SDNode * getNode() const
get the SDNode which holds the desired result
Definition: SelectionDAGNodes.h:152
llvm::SelectionDAGISel::OPC_EmitNode
@ OPC_EmitNode
Definition: SelectionDAGISel.h:163
llvm::InlineAsm::Op_FirstOperand
@ Op_FirstOperand
Definition: InlineAsm.h:215
llvm::Function
Definition: Function.h:61
llvm::ISD::ConstantFP
@ ConstantFP
Definition: ISDOpcodes.h:77
StringRef.h
llvm::ISD::LIFETIME_START
@ LIFETIME_START
This corresponds to the llvm.lifetime.
Definition: ISDOpcodes.h:1177
Pass.h
SchedulerRegistry.h
llvm::TargetSubtargetInfo::getInstrInfo
virtual const TargetInstrInfo * getInstrInfo() const
Definition: TargetSubtargetInfo.h:92
llvm::ISD::STRICT_UINT_TO_FP
@ STRICT_UINT_TO_FP
Definition: ISDOpcodes.h:436
llvm::SelectionDAGISel::SelectInlineAsmMemoryOperands
void SelectInlineAsmMemoryOperands(std::vector< SDValue > &Ops, const SDLoc &DL)
SelectInlineAsmMemoryOperands - Calls to this are automatically generated by tblgen.
Definition: SelectionDAGISel.cpp:2090
llvm::StackProtector::copyToMachineFrameInfo
void copyToMachineFrameInfo(MachineFrameInfo &MFI) const
Definition: StackProtector.cpp:598
llvm::raw_string_ostream
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:623
llvm::SDNode::op_values
iterator_range< value_op_iterator > op_values() const
Definition: SelectionDAGNodes.h:919
llvm::FuncletPadInst::getNumArgOperands
unsigned getNumArgOperands() const
getNumArgOperands - Return the number of funcletpad arguments.
Definition: InstrTypes.h:2320
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1168
llvm::TargetMachine::getO0WantsFastISel
bool getO0WantsFastISel()
Definition: TargetMachine.h:241
Statistic.h
llvm::SelectionDAG::init
void init(MachineFunction &NewMF, OptimizationRemarkEmitter &NewORE, Pass *PassPtr, const TargetLibraryInfo *LibraryInfo, LegacyDivergenceAnalysis *Divergence, ProfileSummaryInfo *PSIin, BlockFrequencyInfo *BFIin)
Prepare this SelectionDAG to process code in the given MachineFunction.
Definition: SelectionDAG.cpp:1141
llvm::SelectionDAGISel::OPFL_GlueOutput
@ OPFL_GlueOutput
Definition: SelectionDAGISel.h:178
InlineAsm.h
CheckType
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const TargetLowering *TLI, const DataLayout &DL)
Definition: SelectionDAGISel.cpp:2583
llvm::SelectionDAG::getVTList
SDVTList getVTList(EVT VT)
Return an SDVTList that represents the list of values specified.
Definition: SelectionDAG.cpp:8157
llvm::FastISel::finishBasicBlock
void finishBasicBlock()
Flush the local value map.
Definition: FastISel.cpp:137
llvm::printMBBReference
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
Definition: MachineBasicBlock.cpp:119
llvm::FunctionPass::skipFunction
bool skipFunction(const Function &F) const
Optional passes call this function to check whether the pass should be skipped.
Definition: Pass.cpp:163
llvm::Function::getSubprogram
DISubprogram * getSubprogram() const
Get the attached subprogram.
Definition: Metadata.cpp:1532
llvm::MachineSDNode
An SDNode that represents everything that will be needed to construct a MachineInstr.
Definition: SelectionDAGNodes.h:2530
llvm::createDefaultScheduler
ScheduleDAGSDNodes * createDefaultScheduler(SelectionDAGISel *IS, CodeGenOpt::Level OptLevel)
createDefaultScheduler - This creates an instruction scheduler appropriate for the target.
Definition: SelectionDAGISel.cpp:253
ErrorHandling.h
llvm::FastISel::lowerArguments
bool lowerArguments()
Do "fast" instruction selection for function arguments and append the machine instructions to the cur...
Definition: FastISel.cpp:139
llvm::TargetTransformInfo
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Definition: TargetTransformInfo.h:168
LazyBlockFrequencyInfo.h
llvm::SelectionDAGISel::OPC_CheckOrImm
@ OPC_CheckOrImm
Definition: SelectionDAGISel.h:146
llvm::SelectionDAGISel::OPC_RecordChild3
@ OPC_RecordChild3
Definition: SelectionDAGISel.h:118
llvm::Function::getEntryBlock
const BasicBlock & getEntryBlock() const
Definition: Function.h:762
llvm::Sched::ILP
@ ILP
Definition: TargetLowering.h:102
llvm::SelectionDAG::allnodes_begin
allnodes_const_iterator allnodes_begin() const
Definition: SelectionDAG.h:493
llvm::SelectionDAG::getRoot
const SDValue & getRoot() const
Return the root tag of the SelectionDAG.
Definition: SelectionDAG.h:513
llvm::SelectionDAGISel::OPC_EmitNode1
@ OPC_EmitNode1
Definition: SelectionDAGISel.h:165
llvm::SwiftErrorValueTracking::createEntriesInEntryBlock
bool createEntriesInEntryBlock(DebugLoc DbgLoc)
Create initial definitions of swifterror values in the entry block of the current function.
Definition: SwiftErrorValueTracking.cpp:115
llvm::SwiftErrorValueTracking::propagateVRegs
void propagateVRegs()
Propagate assigned swifterror vregs through a function, synthesizing PHI nodes when needed to maintai...
Definition: SwiftErrorValueTracking.cpp:147
llvm::ISD::EH_LABEL
@ EH_LABEL
EH_LABEL - Represents a label in mid basic block used to track locations needed for debug and excepti...
Definition: ISDOpcodes.h:988
llvm::SelectionDAGISel::OPC_CheckChild1Integer
@ OPC_CheckChild1Integer
Definition: SelectionDAGISel.h:141
llvm::SelectionDAGISel::OPC_CheckFoldableChainNode
@ OPC_CheckFoldableChainNode
Definition: SelectionDAGISel.h:149
llvm::MachineRegisterInfo::defusechain_instr_iterator
defusechain_iterator - This class provides iterator support for machine operands in the function that...
Definition: MachineRegisterInfo.h:269
llvm::HandleSDNode
This class is used to form a handle around another node that is persistent and is updated across invo...
Definition: SelectionDAGNodes.h:1204
llvm::MachineFunctionPass
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
Definition: MachineFunctionPass.h:30
llvm::RegState::Kill
@ Kill
The last use of a register.
Definition: MachineInstrBuilder.h:48
llvm::createFastDAGScheduler
ScheduleDAGSDNodes * createFastDAGScheduler(SelectionDAGISel *IS, CodeGenOpt::Level OptLevel)
createFastDAGScheduler - This creates a "fast" scheduler.
Definition: ScheduleDAGFast.cpp:797
llvm::SelectionDAGISel::OPC_CheckChild1Same
@ OPC_CheckChild1Same
Definition: SelectionDAGISel.h:127
OptimizationRemarkEmitter.h
llvm::SDNode
Represents one node in the SelectionDAG.
Definition: SelectionDAGNodes.h:455
llvm::DominatorTree
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:151
llvm::Triple
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:45
MachineBasicBlock.h
llvm::TargetSubtargetInfo::getRegisterInfo
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
Definition: TargetSubtargetInfo.h:124
llvm::cl::Hidden
@ Hidden
Definition: CommandLine.h:143
llvm::MVT::Glue
@ Glue
Definition: MachineValueType.h:262
llvm::SelectionDAGISel::OPC_MorphNodeTo2
@ OPC_MorphNodeTo2
Definition: SelectionDAGISel.h:168
llvm::SelectionDAGISel::OPC_MoveChild7
@ OPC_MoveChild7
Definition: SelectionDAGISel.h:124
llvm::SDNode::use_iterator
This class provides iterator support for SDUse operands that use a specific SDNode.
Definition: SelectionDAGNodes.h:719
APInt.h
llvm::TargetRegisterInfo
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
Definition: TargetRegisterInfo.h:231
llvm::SelectionDAGISel::OPFL_Chain
@ OPFL_Chain
Definition: SelectionDAGISel.h:176
llvm::MachineSDNode::memoperands_empty
bool memoperands_empty() const
Definition: SelectionDAGNodes.h:2574
llvm::SelectionDAGISel::CheckPatternPredicate
virtual bool CheckPatternPredicate(unsigned PredNo) const
CheckPatternPredicate - This function is generated by tblgen in the target.
Definition: SelectionDAGISel.h:264
llvm::LazyBlockFrequencyInfoPass::getLazyBFIAnalysisUsage
static void getLazyBFIAnalysisUsage(AnalysisUsage &AU)
Helper for client passes to set up the analysis usage on behalf of this pass.
Definition: LazyBlockFrequencyInfo.cpp:62
llvm::Function::getContext
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function.
Definition: Function.cpp:321
llvm::DenseMapIterator
Definition: DenseMap.h:56
Shift
bool Shift
Definition: README.txt:468
llvm::InlineAsm::isUseOperandTiedToDef
static bool isUseOperandTiedToDef(unsigned Flag, unsigned &Idx)
isUseOperandTiedToDef - Return true if the flag of the inline asm operand indicates it is an use oper...
Definition: InlineAsm.h:345
ViewSchedDAGs
static cl::opt< bool > ViewSchedDAGs("view-sched-dags", cl::Hidden, cl::desc("Pop up a window to show sched dags as they are processed"))
DenseMap.h
llvm::SplitCriticalEdge
BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions(), const Twine &BBName="")
If this edge is a critical edge, insert a new node to split the critical edge.
Definition: BreakCriticalEdges.cpp:103
llvm::TargetLowering::initializeSplitCSR
virtual void initializeSplitCSR(MachineBasicBlock *Entry) const
Perform necessary initialization to handle a subset of CSRs explicitly via copies.
Definition: TargetLowering.h:3644
llvm::TimePassesIsEnabled
bool TimePassesIsEnabled
If the user specifies the -time-passes argument on an LLVM tool command line then the value of this b...
Definition: PassTimingInfo.cpp:37
CheckChildInteger
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckChildInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, unsigned ChildNo)
Definition: SelectionDAGISel.cpp:2653
llvm::SelectionDAGISel::OPC_CaptureGlueInput
@ OPC_CaptureGlueInput
Definition: SelectionDAGISel.h:121
llvm::SelectionDAGISel::OPC_EmitNodeXForm
@ OPC_EmitNodeXForm
Definition: SelectionDAGISel.h:162
TargetInstrInfo.h
llvm::MachineModuleInfo::setUsesMSVCFloatingPoint
void setUsesMSVCFloatingPoint(bool b)
Definition: MachineModuleInfo.h:208
llvm::MachineMemOperand
A description of a memory reference used in the backend.
Definition: MachineMemOperand.h:128
llvm::FunctionLoweringInfo::isExportedInst
bool isExportedInst(const Value *V) const
isExportedInst - Return true if the specified value is an instruction exported from its block.
Definition: FunctionLoweringInfo.h:195
EHPersonalities.h
llvm::TargetLoweringBase::getExceptionPointerRegister
virtual Register getExceptionPointerRegister(const Constant *PersonalityFn) const
If a physical register, this returns the register that receives the exception address on entry to an ...
Definition: TargetLowering.h:1744
llvm::RegisterScheduler::Registry
static MachinePassRegistry< FunctionPassCtor > Registry
RegisterScheduler class - Track the registration of instruction schedulers.
Definition: SchedulerRegistry.h:38
ViewDAGCombine1
static cl::opt< bool > ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden, cl::desc("Pop up a window to show dags before the first " "dag combine pass"))
llvm::MachineFunction::setCallSiteLandingPad
void setCallSiteLandingPad(MCSymbol *Sym, ArrayRef< unsigned > Sites)
Map the landing pad's EH symbol to the call site indexes.
Definition: MachineFunction.cpp:855
llvm::SelectionDAGISel::OPC_CheckChild0Same
@ OPC_CheckChild0Same
Definition: SelectionDAGISel.h:127
llvm::DbgVariableIntrinsic::getVariable
DILocalVariable * getVariable() const
Definition: IntrinsicInst.h:253
LLVM_ATTRIBUTE_ALWAYS_INLINE
#define LLVM_ATTRIBUTE_ALWAYS_INLINE
LLVM_ATTRIBUTE_ALWAYS_INLINE - On compilers where we have a directive to do so, mark a method "always...
Definition: Compiler.h:242
T
#define T
Definition: Mips16ISelLowering.cpp:341
llvm::M68kBeads::Term
@ Term
Definition: M68kBaseInfo.h:71
llvm::MachineInstr::isCopy
bool isCopy() const
Definition: MachineInstr.h:1291
llvm::SelectionDAGISel::OPC_CheckPredicate
@ OPC_CheckPredicate
Definition: SelectionDAGISel.h:130
Offset
uint64_t Offset
Definition: ELFObjHandler.cpp:81
llvm::SmallPtrSet
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:449
llvm::ore::NV
DiagnosticInfoOptimizationBase::Argument NV
Definition: OptimizationRemarkEmitter.h:136
llvm::SelectionDAGISel::OPC_Coverage
@ OPC_Coverage
Definition: SelectionDAGISel.h:171
llvm::ISD::isConstantSplatVectorAllZeros
bool isConstantSplatVectorAllZeros(const SDNode *N, bool BuildVectorOnly=false)
Return true if the specified node is a BUILD_VECTOR or SPLAT_VECTOR where all of the elements are 0 o...
Definition: SelectionDAG.cpp:220
llvm::TargetLowering::supportSplitCSR
virtual bool supportSplitCSR(MachineFunction *MF) const
Return true if the target supports that a subset of CSRs for the given machine function is handled ex...
Definition: TargetLowering.h:3637
llvm::SelectionDAG::RemoveDeadNodes
void RemoveDeadNodes()
This method deletes all unreachable nodes in the SelectionDAG.
Definition: SelectionDAG.cpp:802
STLExtras.h
llvm::SmallVectorImpl::pop_back_val
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:635
llvm::DIExpression
DWARF expression.
Definition: DebugInfoMetadata.h:2557
llvm::AfterLegalizeTypes
@ AfterLegalizeTypes
Definition: DAGCombine.h:17
llvm::SelectionDAGISel::OPC_CheckAndImm
@ OPC_CheckAndImm
Definition: SelectionDAGISel.h:146
llvm::SelectionDAGISel::OPC_EmitCopyToReg
@ OPC_EmitCopyToReg
Definition: SelectionDAGISel.h:160
llvm::SelectionDAGISel::OPC_SwitchType
@ OPC_SwitchType
Definition: SelectionDAGISel.h:136
llvm::Sched::Fast
@ Fast
Definition: TargetLowering.h:104
llvm::succ_empty
bool succ_empty(const Instruction *I)
Definition: CFG.h:256
llvm::SelectionDAGISel::OPC_CheckChild0Type
@ OPC_CheckChild0Type
Definition: SelectionDAGISel.h:137
replace
static void replace(Module &M, GlobalVariable *Old, GlobalVariable *New)
Definition: ConstantMerge.cpp:116
llvm::Sched::Linearize
@ Linearize
Definition: TargetLowering.h:105
llvm::SelectionDAGISel::OPC_CheckCondCode
@ OPC_CheckCondCode
Definition: SelectionDAGISel.h:143
SelectionDAG.h
llvm::SelectionDAGISel::OPC_CheckChild7Type
@ OPC_CheckChild7Type
Definition: SelectionDAGISel.h:139
llvm::initializeGCModuleInfoPass
void initializeGCModuleInfoPass(PassRegistry &)
processDbgDeclares
static void processDbgDeclares(FunctionLoweringInfo &FuncInfo)
Collect llvm.dbg.declare information.
Definition: SelectionDAGISel.cpp:1324
llvm::ISD::FREEZE
@ FREEZE
Definition: ISDOpcodes.h:216
TRI
unsigned const TargetRegisterInfo * TRI
Definition: MachineSink.cpp:1567
llvm::SelectionDAG::clear
void clear()
Clear state and free memory necessary to make this SelectionDAG ready to process a new block.
Definition: SelectionDAG.cpp:1221
FilterDAGBasicBlockName
static cl::opt< std::string > FilterDAGBasicBlockName("filter-view-dags", cl::Hidden, cl::desc("Only display the basic block whose name " "matches this for all view-*-dags options"))
llvm::TargetLoweringBase::getOperationAction
LegalizeAction getOperationAction(unsigned Op, EVT VT) const
Return how this operation should be treated: either it is legal, needs to be promoted to a larger siz...
Definition: TargetLowering.h:1046
llvm::initializeTargetLibraryInfoWrapperPassPass
void initializeTargetLibraryInfoWrapperPassPass(PassRegistry &)
llvm::SelectionDAGISel::OPC_CheckChild1Type
@ OPC_CheckChild1Type
Definition: SelectionDAGISel.h:137
llvm::SelectionDAGISel::OPC_EmitStringInteger
@ OPC_EmitStringInteger
Definition: SelectionDAGISel.h:152
llvm::MachineFunctionPass::getAnalysisUsage
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Definition: MachineFunctionPass.cpp:102
LLVM_DEBUG
#define LLVM_DEBUG(X)
Definition: Debug.h:122
new
Common register allocation spilling lr str ldr sxth r3 ldr mla r4 can lr mov lr str ldr sxth r3 mla r4 and then merge mul and lr str ldr sxth r3 mla r4 It also increase the likelihood the store may become dead bb27 Successors according to LLVM ID Predecessors according to mbb< bb27, 0x8b0a7c0 > Note ADDri is not a two address instruction its result reg1037 is an operand of the PHI node in bb76 and its operand reg1039 is the result of the PHI node We should treat it as a two address code and make sure the ADDri is scheduled after any node that reads reg1039 Use info(i.e. register scavenger) to assign it a free register to allow reuse the collector could move the objects and invalidate the derived pointer This is bad enough in the first but safe points can crop up unpredictably **array_addr i32 n y store obj * new
Definition: README.txt:125
F
#define F(x, y, z)
Definition: MD5.cpp:56
llvm::RISCVFenceField::R
@ R
Definition: RISCVBaseInfo.h:180
MachineRegisterInfo.h
KnownBits.h
llvm::SelectionDAGISel::PreprocessISelDAG
virtual void PreprocessISelDAG()
PreprocessISelDAG - This hook allows targets to hack on the graph before instruction selection starts...
Definition: SelectionDAGISel.h:77
llvm::ISD::ARITH_FENCE
@ ARITH_FENCE
ARITH_FENCE - This corresponds to a arithmetic fence intrinsic.
Definition: ISDOpcodes.h:1105
llvm::SelectionDAG::getRegister
SDValue getRegister(unsigned Reg, EVT VT)
Definition: SelectionDAG.cpp:1960
llvm::BasicBlock
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
llvm::ISD::INLINEASM
@ INLINEASM
INLINEASM - Represents an inline asm block.
Definition: ISDOpcodes.h:980
llvm::EVT::isSimple
bool isSimple() const
Test if the given EVT is simple (as opposed to being extended).
Definition: ValueTypes.h:130
llvm::ISD::PSEUDO_PROBE
@ PSEUDO_PROBE
Pseudo probe for AutoFDO, as a place holder in a basic block to improve the sample counts quality.
Definition: ISDOpcodes.h:1197
llvm::TargetIntrinsicInfo
TargetIntrinsicInfo - Interface to description of machine instruction set.
Definition: TargetIntrinsicInfo.h:29
mapWasmLandingPadIndex
static void mapWasmLandingPadIndex(MachineBasicBlock *MBB, const CatchPadInst *CPI)
Definition: SelectionDAGISel.cpp:1221
CheckAndImm
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckAndImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SelectionDAGISel &SDISel)
Definition: SelectionDAGISel.cpp:2661
AliasAnalysis.h
UseMBPI
static cl::opt< bool > UseMBPI("use-mbpi", cl::desc("use Machine Branch Probability Info"), cl::init(true), cl::Hidden)
MachineValueType.h
llvm::MVT::SimpleValueType
SimpleValueType
Definition: MachineValueType.h:33
llvm::MachineFunction::setExposesReturnsTwice
void setExposesReturnsTwice(bool B)
setCallsSetJmp - Set a flag that indicates if there's a call to a "returns twice" function.
Definition: MachineFunction.h:690
llvm::dbgs
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
llvm::classifyEHPersonality
EHPersonality classifyEHPersonality(const Value *Pers)
See if the given exception handling personality function is one that we understand.
Definition: EHPersonalities.cpp:21
llvm::MachineFunction::setWasmLandingPadIndex
void setWasmLandingPadIndex(const MachineBasicBlock *LPad, unsigned Index)
Map the landing pad to its index. Used for Wasm exception handling.
Definition: MachineFunction.h:1098
Arg
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
Definition: AMDGPULibCalls.cpp:206
llvm::TargetLowering::AdjustInstrPostInstrSelection
virtual void AdjustInstrPostInstrSelection(MachineInstr &MI, SDNode *Node) const
This method should be implemented by targets that mark instructions with the 'hasPostISelHook' flag.
Definition: SelectionDAGISel.cpp:304
llvm::SelectionDAGISel::OPC_EmitMergeInputChains1_0
@ OPC_EmitMergeInputChains1_0
Definition: SelectionDAGISel.h:157
llvm::SelectionDAGISel::ElidedArgCopyInstrs
SmallPtrSet< const Instruction *, 4 > ElidedArgCopyInstrs
Definition: SelectionDAGISel.h:55
llvm::SelectionDAGISel::OPC_MoveChild5
@ OPC_MoveChild5
Definition: SelectionDAGISel.h:124
Instruction.h
CommandLine.h
llvm::BeforeLegalizeTypes
@ BeforeLegalizeTypes
Definition: DAGCombine.h:16
TargetLowering.h
llvm::ConstantInt
This is the shared class of boolean and integer constants.
Definition: Constants.h:79
llvm::Instruction::getNumSuccessors
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Definition: Instruction.cpp:765
llvm::FuncletPadInst::getArgOperand
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th funcletpad argument.
Definition: InstrTypes.h:2336
llvm::SDNode::getOpcode
unsigned getOpcode() const
Return the SelectionDAG opcode value for this node.
Definition: SelectionDAGNodes.h:621
llvm::MachineFunction::front
const MachineBasicBlock & front() const
Definition: MachineFunction.h:816
llvm::BlockFrequencyInfo
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Definition: BlockFrequencyInfo.h:37
llvm::MachineFunction::getRegInfo
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Definition: MachineFunction.h:632
reportFastISelFailure
static void reportFastISelFailure(MachineFunction &MF, OptimizationRemarkEmitter &ORE, OptimizationRemarkMissed &R, bool ShouldAbort)
Definition: SelectionDAGISel.cpp:692
llvm::SelectionDAGISel::OPC_RecordChild6
@ OPC_RecordChild6
Definition: SelectionDAGISel.h:119
llvm::MachineBasicBlock::insertAfter
iterator insertAfter(iterator I, MachineInstr *MI)
Insert MI into the instruction list after I.
Definition: MachineBasicBlock.h:871
llvm::TargetInstrInfo
TargetInstrInfo - Interface to description of machine instruction set.
Definition: TargetInstrInfo.h:97
llvm::SelectionDAGISel::OPC_RecordChild1
@ OPC_RecordChild1
Definition: SelectionDAGISel.h:118
llvm::SDValue::getValueType
EVT getValueType() const
Return the ValueType of the referenced return value.
Definition: SelectionDAGNodes.h:1113
ViewDAGCombineLT
static cl::opt< bool > ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden, cl::desc("Pop up a window to show dags before the post " "legalize types dag combine pass"))
CheckValueType
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckValueType(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const TargetLowering *TLI, const DataLayout &DL)
Definition: SelectionDAGISel.cpp:2618
llvm::MachineFunctionProperties::Property::Selected
@ Selected
TargetMachine.h
llvm::PassRegistry::getPassRegistry
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Definition: PassRegistry.cpp:31
CheckOrImm
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckOrImm(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N, const SelectionDAGISel &SDISel)
Definition: SelectionDAGISel.cpp:2674
llvm::SelectionDAGISel::OPC_EmitNode0
@ OPC_EmitNode0
Definition: SelectionDAGISel.h:165
llvm::SelectionDAG
This is used to represent a portion of an LLVM function in a low-level Data Dependence DAG representa...
Definition: SelectionDAG.h:216
SelectionDAGNodes.h
Constants.h
llvm::SelectionDAGISel::RunSDNodeXForm
virtual SDValue RunSDNodeXForm(SDValue V, unsigned XFormNo)
Definition: SelectionDAGISel.h:293
llvm::ISD::Constant
@ Constant
Definition: ISDOpcodes.h:76
llvm::SelectionDAGISel::SDB
std::unique_ptr< SelectionDAGBuilder > SDB
Definition: SelectionDAGISel.h:48
llvm::PHINode::getIncomingValue
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
Definition: Instructions.h:2723
llvm::SelectionDAGISel::OPC_CheckOpcode
@ OPC_CheckOpcode
Definition: SelectionDAGISel.h:132
llvm::InlineAsm::Op_MDNode
@ Op_MDNode
Definition: InlineAsm.h:213
llvm::SelectionDAGISel::OPC_CheckPatternPredicate
@ OPC_CheckPatternPredicate
Definition: SelectionDAGISel.h:129
llvm::BranchProbabilityInfoWrapperPass
Legacy analysis pass which computes BranchProbabilityInfo.
Definition: BranchProbabilityInfo.h:440
FunctionLoweringInfo.h
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
SplitCriticalSideEffectEdges
static void SplitCriticalSideEffectEdges(Function &Fn, DominatorTree *DT, LoopInfo *LI)
SplitCriticalSideEffectEdges - Look for critical edges with a PHI value that may trap on it.
Definition: SelectionDAGISel.cpp:358
llvm::SmallVectorImpl::append
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
Definition: SmallVector.h:648
llvm::SelectionDAG::LegalizeTypes
bool LegalizeTypes()
This transforms the SelectionDAG into a SelectionDAG that only uses types natively supported by the t...
Definition: LegalizeTypes.cpp:1055
llvm::DIExpression::ApplyOffset
@ ApplyOffset
Definition: DebugInfoMetadata.h:2764
llvm::User
Definition: User.h:44
llvm::SelectionDAGISel::OPC_MoveChild
@ OPC_MoveChild
Definition: SelectionDAGISel.h:122
llvm::ISD::CopyToReg
@ CopyToReg
CopyToReg - This node has three operands: a chain, a register number to set to this value,...
Definition: ISDOpcodes.h:203
llvm::SDNode::setFlags
void setFlags(SDNodeFlags NewFlags)
Definition: SelectionDAGNodes.h:948
llvm::EVT
Extended Value Type.
Definition: ValueTypes.h:35
llvm::SelectionDAGISel::RegInfo
MachineRegisterInfo * RegInfo
Definition: SelectionDAGISel.h:46
Intrinsics.h
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
llvm::MachineInstr::getOperand
const MachineOperand & getOperand(unsigned i) const
Definition: MachineInstr.h:499
llvm::SelectionDAGISel::OptLevel
CodeGenOpt::Level OptLevel
Definition: SelectionDAGISel.h:51
llvm::SelectionDAGISel::CheckNodePredicate
virtual bool CheckNodePredicate(SDNode *N, unsigned PredNo) const
CheckNodePredicate - This function is generated by tblgen in the target.
Definition: SelectionDAGISel.h:272
llvm::getLLTForMVT
LLT getLLTForMVT(MVT Ty)
Get a rough equivalent of an LLT for a given MVT.
Definition: LowLevelType.cpp:55
InstrTypes.h
llvm::TargetMachine::getIntrinsicInfo
virtual const TargetIntrinsicInfo * getIntrinsicInfo() const
If intrinsic information is available, return it. If not, return null.
Definition: TargetMachine.h:209
llvm::TargetLowering
This class defines information used to lower LLVM code to legal SelectionDAG operators that the targe...
Definition: TargetLowering.h:3170
ViewLegalizeTypesDAGs
static cl::opt< bool > ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden, cl::desc("Pop up a window to show dags before legalize types"))
llvm::KnownBits::One
APInt One
Definition: KnownBits.h:25
llvm::SelectionDAGISel::ComplexPatternFuncMutatesDAG
virtual bool ComplexPatternFuncMutatesDAG() const
Return true if complex patterns for this target can mutate the DAG.
Definition: SelectionDAGISel.h:302
llvm::TargetTransformInfo::hasBranchDivergence
bool hasBranchDivergence() const
Return true if branch divergence exists.
Definition: TargetTransformInfo.cpp:236
llvm::MachineBasicBlock::isSuccessor
bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
Definition: MachineBasicBlock.cpp:908
llvm::StackProtector
Definition: StackProtector.h:37
llvm::SelectionDAG::MaskedValueIsZero
bool MaskedValueIsZero(SDValue Op, const APInt &Mask, unsigned Depth=0) const
Return true if 'Op & Mask' is known to be zero.
Definition: SelectionDAG.cpp:2438
llvm::createILPListDAGScheduler
ScheduleDAGSDNodes * createILPListDAGScheduler(SelectionDAGISel *IS, CodeGenOpt::Level)
createILPListDAGScheduler - This creates a bottom up register pressure aware list scheduler that trie...
Definition: ScheduleDAGRRList.cpp:3179
llvm::Register::isPhysicalRegister
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
Definition: Register.h:65
llvm::TargetRegisterClass
Definition: TargetRegisterInfo.h:46
llvm::AnalysisUsage
Represent the analysis usage information of a pass.
Definition: PassAnalysisSupport.h:47
llvm::SelectionDAG::Legalize
void Legalize()
This transforms the SelectionDAG into a SelectionDAG that is compatible with the target instruction s...
Definition: LegalizeDAG.cpp:4933
ViewLegalizeDAGs
static cl::opt< bool > ViewLegalizeDAGs("view-legalize-dags", cl::Hidden, cl::desc("Pop up a window to show dags before legalize"))
CheckInteger
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckInteger(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N)
Definition: SelectionDAGISel.cpp:2640
llvm::MachineFunction::getProperties
const MachineFunctionProperties & getProperties() const
Get the function properties.
Definition: MachineFunction.h:713
TargetLibraryInfo.h
llvm::CriticalEdgeSplittingOptions
Option class for critical edge splitting.
Definition: BasicBlockUtils.h:136
llvm::SelectionDAGISel::ReplaceNode
void ReplaceNode(SDNode *F, SDNode *T)
Replace all uses of F with T, then remove F from the DAG.
Definition: SelectionDAGISel.h:227
llvm::SelectionDAGISel::ORE
std::unique_ptr< OptimizationRemarkEmitter > ORE
Current optimization remark emitter.
Definition: SelectionDAGISel.h:59
llvm::SelectionDAGISel::OPC_MorphNodeTo1
@ OPC_MorphNodeTo1
Definition: SelectionDAGISel.h:168
TII
const HexagonInstrInfo * TII
Definition: HexagonCopyToCombine.cpp:129
llvm::ISD::DELETED_NODE
@ DELETED_NODE
DELETED_NODE - This is an illegal value that is used to catch errors.
Definition: ISDOpcodes.h:44
llvm::MCInstrDesc
Describe properties that are true of each instruction in the target description file.
Definition: MCInstrDesc.h:195
llvm::MachineOperand
MachineOperand class - Representation of each machine instruction operand.
Definition: MachineOperand.h:49
CheckCondCode
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckCondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N)
Definition: SelectionDAGISel.cpp:2603
llvm::SelectionDAG::setRoot
const SDValue & setRoot(SDValue N)
Set the current root tag of the SelectionDAG.
Definition: SelectionDAG.h:522
llvm::EVT::isInteger
bool isInteger() const
Return true if this is an integer or a vector integer type.
Definition: ValueTypes.h:145
llvm::Instruction
Definition: Instruction.h:45
llvm::MachineModuleInfo
This class contains meta information specific to a module.
Definition: MachineModuleInfo.h:78
llvm::ISD::MDNODE_SDNODE
@ MDNODE_SDNODE
MDNODE_SDNODE - This is a node that holdes an MDNode*, which is used to reference metadata in the IR.
Definition: ISDOpcodes.h:1057
llvm::createSourceListDAGScheduler
ScheduleDAGSDNodes * createSourceListDAGScheduler(SelectionDAGISel *IS, CodeGenOpt::Level OptLevel)
createBURRListDAGScheduler - This creates a bottom up list scheduler that schedules nodes in source c...
Definition: ScheduleDAGRRList.cpp:3149
llvm::SDNode::use_empty
bool use_empty() const
Return true if there are no uses of this node.
Definition: SelectionDAGNodes.h:689
llvm::report_fatal_error
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:140
llvm::BasicBlock::phis
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition: BasicBlock.h:354
llvm::STATISTIC
STATISTIC(NumFunctions, "Total number of functions")
decodeSignRotatedValue
static uint64_t decodeSignRotatedValue(uint64_t V)
Decode a signed value stored with the sign bit in the LSB for dense VBR encoding.
Definition: SelectionDAGISel.cpp:2630
CheckPatternPredicate
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckPatternPredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex, const SelectionDAGISel &SDISel)
CheckPatternPredicate - Implements OP_CheckPatternPredicate.
Definition: SelectionDAGISel.cpp:2562
llvm::SelectionDAG::DAGNodeDeletedListener
Definition: SelectionDAG.h:314
ScheduleDAGSDNodes.h
llvm::ConstantFP
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:257
llvm::SmallVectorImpl::resize
void resize(size_type N)
Definition: SmallVector.h:606
llvm::Use::getUser
User * getUser() const
Returns the User that contains this Use.
Definition: Use.h:73
llvm::SelectionDAG::dump
void dump() const
Definition: SelectionDAGDumper.cpp:913
llvm::SelectionDAGISel::ID
static char ID
Definition: SelectionDAGISel.h:61
llvm::ISD::AssertAlign
@ AssertAlign
AssertAlign - These nodes record if a register contains a value that has a known alignment and the tr...
Definition: ISDOpcodes.h:68
DebugLoc.h
SmallPtrSet.h
llvm::SwiftErrorValueTracking::preassignVRegs
void preassignVRegs(MachineBasicBlock *MBB, BasicBlock::const_iterator Begin, BasicBlock::const_iterator End)
Definition: SwiftErrorValueTracking.cpp:259
llvm::RegisterScheduler::FunctionPassCtor
ScheduleDAGSDNodes *(*)(SelectionDAGISel *, CodeGenOpt::Level) FunctionPassCtor
Definition: SchedulerRegistry.h:36
llvm::ISD::AND
@ AND
Bitwise operators - logical and, logical or, logical xor.
Definition: ISDOpcodes.h:632
llvm::ISD::TargetGlobalAddress
@ TargetGlobalAddress
TargetGlobalAddress - Like GlobalAddress, but the DAG does no folding or anything else with this node...
Definition: ISDOpcodes.h:164
llvm::BasicBlock::getFirstNonPHI
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:212
llvm::ISD::EntryToken
@ EntryToken
EntryToken - This is the marker used to indicate the start of a region.
Definition: ISDOpcodes.h:47
CheckNodePredicate
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckNodePredicate(const unsigned char *MatcherTable, unsigned &MatcherIndex, const SelectionDAGISel &SDISel, SDNode *N)
CheckNodePredicate - Implements OP_CheckNodePredicate.
Definition: SelectionDAGISel.cpp:2569
llvm::Align
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
FindSplitPointForStackProtector
static MachineBasicBlock::iterator FindSplitPointForStackProtector(MachineBasicBlock *BB, const TargetInstrInfo &TII)
Find the split point at which to splice the end of BB into its success stack protector check machine ...
Definition: SelectionDAGISel.cpp:1710
findNonImmUse
static bool findNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse, bool IgnoreChains)
findNonImmUse - Return true if "Def" is a predecessor of "Root" via a path beyond "ImmedUse".
Definition: SelectionDAGISel.cpp:2163
llvm::SelectionDAGISel::OPC_CheckSame
@ OPC_CheckSame
Definition: SelectionDAGISel.h:126
llvm::MachineRegisterInfo::getVRegDef
MachineInstr * getVRegDef(Register Reg) const
getVRegDef - Return the machine instr that defines the specified virtual register or null if none is ...
Definition: MachineRegisterInfo.cpp:400
ViewISelDAGs
static cl::opt< bool > ViewISelDAGs("view-isel-dags", cl::Hidden, cl::desc("Pop up a window to show isel dags as they are selected"))
llvm::SDValue::getValueSizeInBits
TypeSize getValueSizeInBits() const
Returns the size of the value in bits.
Definition: SelectionDAGNodes.h:192
llvm::ISD::CopyFromReg
@ CopyFromReg
CopyFromReg - This node indicates that the input value is a virtual or physical register that is defi...
Definition: ISDOpcodes.h:208
llvm::PHINode::getNumIncomingValues
unsigned getNumIncomingValues() const
Return the number of incoming edges.
Definition: Instructions.h:2719
llvm::RegisterPassParser
RegisterPassParser class - Handle the addition of new machine passes.
Definition: MachinePassRegistry.h:135
llvm::EHPersonality::Wasm_CXX
@ Wasm_CXX
llvm::MachineRegisterInfo::use_empty
bool use_empty(Register RegNo) const
use_empty - Return true if there are no instructions using the specified register.
Definition: MachineRegisterInfo.h:506
Statepoint.h
llvm::erase_value
void erase_value(Container &C, ValueType V)
Wrapper function to remove a value from a container:
Definition: STLExtras.h:1736
Type.h
BranchProbability.h
llvm::MachineBasicBlock
Definition: MachineBasicBlock.h:95
llvm::TargetMachine::resetTargetOptions
void resetTargetOptions(const Function &F) const
Reset the target options based on the function's attributes.
Definition: TargetMachine.cpp:56
llvm::Sched::RegPressure
@ RegPressure
Definition: TargetLowering.h:100
ViewSUnitDAGs
static cl::opt< bool > ViewSUnitDAGs("view-sunit-dags", cl::Hidden, cl::desc("Pop up a window to show SUnit dags after they are processed"))
llvm::InlineAsm::isMemKind
static bool isMemKind(unsigned Flag)
Definition: InlineAsm.h:280
MIIsInTerminatorSequence
static bool MIIsInTerminatorSequence(const MachineInstr &MI)
Given that the input MI is before a partial terminator sequence TSeq, return true if M + TSeq also a ...
Definition: SelectionDAGISel.cpp:1655
llvm::OptLevelChanger::~OptLevelChanger
~OptLevelChanger()
Definition: SelectionDAGISel.cpp:237
llvm::TargetOptions::ValueTrackingVariableLocations
unsigned ValueTrackingVariableLocations
Definition: TargetOptions.h:314
llvm::TargetLowering::createFastISel
virtual FastISel * createFastISel(FunctionLoweringInfo &, const TargetLibraryInfo *) const
This method returns a target specific FastISel object, or null if the target does not support "fast" ...
Definition: TargetLowering.h:4118
Operands
mir Rename Register Operands
Definition: MIRNamerPass.cpp:78
llvm::MachineRegisterInfo::getRegClass
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
Definition: MachineRegisterInfo.h:634
llvm::MCID::MayRaiseFPException
@ MayRaiseFPException
Definition: MCInstrDesc.h:167
llvm::SelectionDAGISel::OPFL_VariadicInfo
@ OPFL_VariadicInfo
Definition: SelectionDAGISel.h:188
llvm::ISD::TargetConstantFP
@ TargetConstantFP
Definition: ISDOpcodes.h:159
llvm::SelectionDAGISel::InvalidateNodeId
static void InvalidateNodeId(SDNode *N)
Definition: SelectionDAGISel.cpp:1086
llvm::APInt::isSubsetOf
bool isSubsetOf(const APInt &RHS) const
This operation checks that all bits set in this APInt are also set in RHS.
Definition: APInt.h:1349
llvm::MDNode::getOperand
const MDOperand & getOperand(unsigned I) const
Definition: Metadata.h:1102
llvm::TargetLowering::insertCopiesSplitCSR
virtual void insertCopiesSplitCSR(MachineBasicBlock *Entry, const SmallVectorImpl< MachineBasicBlock * > &Exits) const
Insert explicit copies in entry and exit blocks.
Definition: TargetLowering.h:3652
llvm::MachineFunction::getMMI
MachineModuleInfo & getMMI() const
Definition: MachineFunction.h:573
llvm::ISD::STRICT_FSETCCS
@ STRICT_FSETCCS
Definition: ISDOpcodes.h:463
llvm::MachineRegisterInfo::clearKillFlags
void clearKillFlags(Register Reg) const
clearKillFlags - Iterate over all the uses of the given register and clear the kill flag from the Mac...
Definition: MachineRegisterInfo.cpp:431
llvm::MachineFunction::getSubtarget
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Definition: MachineFunction.h:622
llvm::MCInstrDesc::mayLoad
bool mayLoad() const
Return true if this instruction could possibly read memory.
Definition: MCInstrDesc.h:429
llvm::ISD::WRITE_REGISTER
@ WRITE_REGISTER
Definition: ISDOpcodes.h:119
Timer.h
BasicBlock.h
llvm::cl::opt
Definition: CommandLine.h:1422
llvm::MachineFunction::setHasInlineAsm
void setHasInlineAsm(bool B)
Set a flag that indicates that the function contains inline assembly.
Definition: MachineFunction.h:700
llvm::SDNode::use_begin
use_iterator use_begin() const
Provide iteration support to walk over all uses of an SDNode.
Definition: SelectionDAGNodes.h:775
llvm::ISD::Register
@ Register
Definition: ISDOpcodes.h:74
llvm::SelectionDAGISel::OPC_CheckChild4Integer
@ OPC_CheckChild4Integer
Definition: SelectionDAGISel.h:142
llvm::instructions
inst_range instructions(Function *F)
Definition: InstIterator.h:133
llvm::FastISel::selectInstruction
bool selectInstruction(const Instruction *I)
Do "fast" instruction selection for the given LLVM IR instruction and append the generated machine in...
Definition: FastISel.cpp:1493
llvm::SelectionDAGISel::OPC_CheckValueType
@ OPC_CheckValueType
Definition: SelectionDAGISel.h:144
llvm::Constant
This is an important base class in LLVM.
Definition: Constant.h:41
llvm::SelectionDAG::RemoveDeadNode
void RemoveDeadNode(SDNode *N)
Remove the specified node from the system.
Definition: SelectionDAG.cpp:856
llvm::SelectionDAGISel::OPC_CheckImmAllZerosV
@ OPC_CheckImmAllZerosV
Definition: SelectionDAGISel.h:148
BranchProbabilityInfo.h
llvm::SelectionDAGISel::OPC_CheckInteger
@ OPC_CheckInteger
Definition: SelectionDAGISel.h:140
llvm::EVT::getSizeInBits
TypeSize getSizeInBits() const
Return the size of the specified value type in bits.
Definition: ValueTypes.h:341
llvm::SelectionDAGISel::IsProfitableToFold
virtual bool IsProfitableToFold(SDValue N, SDNode *U, SDNode *Root) const
IsProfitableToFold - Returns true if it's profitable to fold the specific operand node N of U during ...
Definition: SelectionDAGISel.cpp:2203
llvm::AfterLegalizeDAG
@ AfterLegalizeDAG
Definition: DAGCombine.h:19
CheckChild2CondCode
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckChild2CondCode(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDValue N)
Definition: SelectionDAGISel.cpp:2610
Index
uint32_t Index
Definition: ELFObjHandler.cpp:84
llvm::MachineOperand::isReg
bool isReg() const
isReg - Tests if this is a MO_Register operand.
Definition: MachineOperand.h:321
llvm::MachineInstr
Representation of each machine instruction.
Definition: MachineInstr.h:64
index
splat index
Definition: README_ALTIVEC.txt:181
llvm::MachineInstrBuilder
Definition: MachineInstrBuilder.h:69
llvm::SelectionDAGISel::OPC_RecordMemRef
@ OPC_RecordMemRef
Definition: SelectionDAGISel.h:120
llvm::TargetLibraryInfoWrapperPass
Definition: TargetLibraryInfo.h:463
uint64_t
ProfileSummaryInfo.h
llvm::SelectionDAGISel::getAnalysisUsage
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
Definition: SelectionDAGISel.cpp:334
llvm::TargetTransformInfoWrapperPass
Wrapper pass for TargetTransformInfo.
Definition: TargetTransformInfo.h:2369
llvm::SelectionDAGISel::TII
const TargetInstrInfo * TII
Definition: SelectionDAGISel.h:52
llvm::GlobalValue::getParent
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:572
llvm::MCInstrDesc::isCall
bool isCall() const
Return true if the instruction is a call.
Definition: MCInstrDesc.h:279
llvm::DbgDeclareInst
This represents the llvm.dbg.declare instruction.
Definition: IntrinsicInst.h:308
llvm::ARM_MB::ST
@ ST
Definition: ARMBaseInfo.h:73
llvm::MachineRegisterInfo::use_instr_begin
use_instr_iterator use_instr_begin(Register RegNo) const
Definition: MachineRegisterInfo.h:477
llvm::SelectionDAGISel::OPC_RecordChild0
@ OPC_RecordChild0
Definition: SelectionDAGISel.h:118
HandleMergeInputChains
static SDValue HandleMergeInputChains(SmallVectorImpl< SDNode * > &ChainNodesMatched, SelectionDAG *CurDAG)
HandleMergeInputChains - This implements the OPC_EmitMergeInputChains operation for when the pattern ...
Definition: SelectionDAGISel.cpp:2420
llvm::ISD::AssertZext
@ AssertZext
Definition: ISDOpcodes.h:62
llvm::Function::hasGC
bool hasGC() const
hasGC/getGC/setGC/clearGC - The name of the garbage collection algorithm to use during code generatio...
Definition: Function.h:393
llvm::ISD::STRICT_LRINT
@ STRICT_LRINT
Definition: ISDOpcodes.h:419
llvm::SelectionDAG::mutateStrictFPToFP
SDNode * mutateStrictFPToFP(SDNode *Node)
Mutate the specified strict FP node to its non-strict equivalent, unlinking the node from its chain a...
Definition: SelectionDAG.cpp:8547
llvm::SelectionDAGISel::FuncInfo
std::unique_ptr< FunctionLoweringInfo > FuncInfo
Definition: SelectionDAGISel.h:43
llvm::TargetRegisterInfo::getFrameRegister
virtual Register getFrameRegister(const MachineFunction &MF) const =0
Debug information queries.
llvm::numbers::e
constexpr double e
Definition: MathExtras.h:57
llvm::SDNode::setNodeId
void setNodeId(int Id)
Set unique node id.
Definition: SelectionDAGNodes.h:702
llvm::SelectionDAGISel::OPFL_MemRefs
@ OPFL_MemRefs
Definition: SelectionDAGISel.h:179
llvm::SelectionDAG::getCopyFromReg
SDValue getCopyFromReg(SDValue Chain, const SDLoc &dl, unsigned Reg, EVT VT)
Definition: SelectionDAG.h:761
llvm::DenseMap< unsigned, unsigned >
llvm::SelectionDAGISel::IsLegalToFold
static bool IsLegalToFold(SDValue N, SDNode *U, SDNode *Root, CodeGenOpt::Level OptLevel, bool IgnoreChains=false)
IsLegalToFold - Returns true if the specific operand node N of U can be folded during instruction sel...
Definition: SelectionDAGISel.cpp:2211
llvm::SelectionDAGISel::mayRaiseFPException
bool mayRaiseFPException(SDNode *Node) const
Return whether the node may raise an FP exception.
Definition: SelectionDAGISel.cpp:3750
llvm::SelectionDAGISel::OPC_CheckChild2Same
@ OPC_CheckChild2Same
Definition: SelectionDAGISel.h:128
llvm::SDNode::getOperand
const SDValue & getOperand(unsigned Num) const
Definition: SelectionDAGNodes.h:896
I
#define I(x, y, z)
Definition: MD5.cpp:59
llvm::SwiftErrorValueTracking
Definition: SwiftErrorValueTracking.h:36
llvm::MCPhysReg
uint16_t MCPhysReg
An unsigned integer type large enough to represent all physical registers, but not necessarily virtua...
Definition: MCRegister.h:20
llvm::SelectionDAG::getNode
SDValue getNode(unsigned Opcode, const SDLoc &DL, EVT VT, ArrayRef< SDUse > Ops)
Gets or creates the specified node.
Definition: SelectionDAG.cpp:7922
CheckOpcode
static LLVM_ATTRIBUTE_ALWAYS_INLINE bool CheckOpcode(const unsigned char *MatcherTable, unsigned &MatcherIndex, SDNode *N)
Definition: SelectionDAGISel.cpp:2575
llvm::MachineFrameInfo::getObjectAlign
Align getObjectAlign(int ObjectIdx) const
Return the alignment of the specified stack object.
Definition: MachineFrameInfo.h:465
llvm::SelectionDAGISel::OPC_CheckChild4Type
@ OPC_CheckChild4Type
Definition: SelectionDAGISel.h:138
llvm::cl::init
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
MCRegisterInfo.h
llvm::ProfileSummaryInfoWrapperPass
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Definition: ProfileSummaryInfo.h:185
llvm::is_contained
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.
Definition: STLExtras.h:1612
llvm::SDNode::dump
void dump() const
Dump this node, for debugging.
Definition: SelectionDAGDumper.cpp:539
llvm::MachineRegisterInfo::liveins
ArrayRef< std::pair< MCRegister, Register > > liveins() const
Definition: MachineRegisterInfo.h:956
llvm::MachineFunction::finalizeDebugInstrRefs
void finalizeDebugInstrRefs()
Finalise any partially emitted debug instructions.
Definition: MachineFunction.cpp:1167
llvm::SelectionDAGISel::getPatternForIndex
virtual StringRef getPatternForIndex(unsigned index)
getPatternForIndex - Patterns selected by tablegen during ISEL
Definition: SelectionDAGISel.h:239
MachineFunctionPass.h
llvm::HighlightColor::Address
@ Address
llvm::SelectionDAG::MorphNodeTo
SDNode * MorphNodeTo(SDNode *N, unsigned Opc, SDVTList VTs, ArrayRef< SDValue > Ops)
This mutates the specified node to have the specified return type, opcode, and operands.
Definition: SelectionDAG.cpp:8494
llvm::SelectionDAG::NewNodesMustHaveLegalTypes
bool NewNodesMustHaveLegalTypes
When true, additional steps are taken to ensure that getConstant() and similar functions return DAG n...
Definition: SelectionDAG.h:355
llvm::Register::isVirtualRegister
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:71
llvm::SelectionDAGISel::OPC_CheckImmAllOnesV
@ OPC_CheckImmAllOnesV
Definition: SelectionDAGISel.h:147
llvm::SelectionDAGISel::OPC_SwitchOpcode
@ OPC_SwitchOpcode
Definition: SelectionDAGISel.h:133
llvm::DenseMapBase::find
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:150
llvm::MachineFunction::getName
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
Definition: MachineFunction.cpp:541
llvm::SelectionDAGISel::OPC_CheckChild3Integer
@ OPC_CheckChild3Integer
Definition: SelectionDAGISel.h:142
llvm::ISD::STRICT_LROUND
@ STRICT_LROUND
Definition: ISDOpcodes.h:417
llvm::SDValue::getValue
SDValue getValue(unsigned R) const
Definition: SelectionDAGNodes.h:172
llvm::TargetMachine::Options
TargetOptions Options
Definition: TargetMachine.h:115
llvm::InlineAsm::Kind_Mem
@ Kind_Mem
Definition: InlineAsm.h:238
llvm::SelectionDAGISel::CheckOrMask
bool CheckOrMask(SDValue LHS, ConstantSDNode *RHS, int64_t DesiredMaskS) const
CheckOrMask - The isel is trying to match something like (or X, 255).
Definition: SelectionDAGISel.cpp:2060
assert
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
llvm::TargetMachine
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:77
llvm::SelectionDAGISel::~SelectionDAGISel
~SelectionDAGISel() override
Definition: SelectionDAGISel.cpp:329
llvm::FunctionLoweringInfo
FunctionLoweringInfo - This contains information that is global to a function that is used when lower...
Definition: FunctionLoweringInfo.h:53
llvm::MVT::Other
@ Other
Definition: MachineValueType.h:42
llvm::SDNode::getNodeId
int getNodeId() const
Return the unique node id.
Definition: SelectionDAGNodes.h:699
llvm::createVLIWDAGScheduler
ScheduleDAGSDNodes * createVLIWDAGScheduler(SelectionDAGISel *IS, CodeGenOpt::Level OptLevel)
createVLIWDAGScheduler - Scheduler for VLIW targets.
Definition: ScheduleDAGVLIW.cpp:273
std::swap
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:840
llvm::MachineFunction::getFrameInfo
MachineFrameInfo & getFrameInfo()
getFrameInfo - Return the frame info object for the current function.
Definition: MachineFunction.h:638
SI
StandardInstrumentations SI(Debug, VerifyEach)
llvm::MachineBasicBlock::getParent
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
Definition: MachineBasicBlock.h:225
llvm::OptimizationRemarkEmitter::emit
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Definition: OptimizationRemarkEmitter.cpp:77
llvm::SelectionDAGISel::OPC_EmitMergeInputChains
@ OPC_EmitMergeInputChains
Definition: SelectionDAGISel.h:156
llvm::InlineAsm::getMemoryConstraintID
static unsigned getMemoryConstraintID(unsigned Flag)
Definition: InlineAsm.h:332
llvm::ISD::CondCode
CondCode
ISD::CondCode enum - These are ordered carefully to make the bitfields below work out,...
Definition: ISDOpcodes.h:1355
llvm::ISD::BasicBlock
@ BasicBlock
Various leaf nodes.
Definition: ISDOpcodes.h:71
llvm::SelectionDAGISel::CurDAG
SelectionDAG * CurDAG
Definition: SelectionDAGISel.h:47
function
print Print MemDeps of function
Definition: MemDepPrinter.cpp:83
llvm::SelectionDAG::getMachineNode
MachineSDNode * getMachineNode(unsigned Opcode, const SDLoc &dl, EVT VT)
These are used for target selectors to create a new node with specified return type(s),...
Definition: SelectionDAG.cpp:8595
MachineModuleInfo.h
llvm::ISD::TargetGlobalTLSAddress
@ TargetGlobalTLSAddress
Definition: ISDOpcodes.h:165
llvm::Sched::VLIW
@ VLIW
Definition: TargetLowering.h:103
llvm::MVT
Machine Value Type.
Definition: MachineValueType.h:31
llvm::MachineInstrBuilder::addReg
const MachineInstrBuilder & addReg(Register RegNo, unsigned flags=0, unsigned SubReg=0) const
Add a new virtual register operand.
Definition: MachineInstrBuilder.h:97
llvm::SwiftErrorValueTracking::setFunction
void setFunction(MachineFunction &MF)
Initialize data structures for specified new function.
Definition: SwiftErrorValueTracking.cpp:79
llvm::FastISel
This is a fast-path instruction selection class that generates poor code and doesn't support illegal ...
Definition: FastISel.h:65
llvm::MachineOperand::getReg
Register getReg() const
getReg - Returns the register number.
Definition: MachineOperand.h:360
llvm::SelectionDAGISel::getUninvalidatedNodeId
static int getUninvalidatedNodeId(SDNode *N)
Definition: SelectionDAGISel.cpp:1092
llvm::SelectionDAGISel::SelectionDAGISel
SelectionDAGISel(TargetMachine &tm, CodeGenOpt::Level OL=CodeGenOpt::Default)
Definition: SelectionDAGISel.cpp:315
llvm::SelectionDAG::setNodeMemRefs
void setNodeMemRefs(MachineSDNode *N, ArrayRef< MachineMemOperand * > NewMemRefs)
Mutate the specified machine node's memory references to the provided list.
Definition: SelectionDAG.cpp:8363
SwiftErrorValueTracking.h
llvm::MDNode
Metadata node.
Definition: Metadata.h:897
llvm::ISD::STRICT_LLRINT
@ STRICT_LLRINT
Definition: ISDOpcodes.h:420
llvm::AfterLegalizeVectorOps
@ AfterLegalizeVectorOps
Definition: DAGCombine.h:18
llvm::MCInstrInfo::getName
StringRef getName(unsigned Opcode) const
Returns the name for the instructions with the given opcode.
Definition: MCInstrInfo.h:68
llvm::SelectionDAG::SelectNodeTo
SDNode * SelectNodeTo(SDNode *N, unsigned MachineOpc, EVT VT)
These are used for target selectors to mutate the specified node to have the specified return type,...
Definition: SelectionDAG.cpp:8387
llvm::TargetOptions::EnableFastISel
unsigned EnableFastISel
EnableFastISel - This flag enables fast-path instruction selection which trades away generated code q...
Definition: TargetOptions.h:213
llvm::SDNode::isMachineOpcode
bool isMachineOpcode() const
Test if this node has a post-isel opcode, directly corresponding to a MachineInstr opcode.
Definition: SelectionDAGNodes.h:673
llvm::ISD::TargetBlockAddress
@ TargetBlockAddress
Definition: ISDOpcodes.h:170
llvm::SelectionDAGISel::OPC_CheckPredicateWithOperands
@ OPC_CheckPredicateWithOperands
Definition: SelectionDAGISel.h:131
llvm::APInt
Class for arbitrary precision integers.
Definition: APInt.h:70
llvm::MachineFunction
Definition: MachineFunction.h:230
llvm::MCInstrDesc::mayStore
bool mayStore() const
Return true if this instruction could possibly modify memory.
Definition: MCInstrDesc.h:435
llvm::ISD::ANNOTATION_LABEL
@ ANNOTATION_LABEL
ANNOTATION_LABEL - Represents a mid basic block label used by annotations.
Definition: ISDOpcodes.h:994
llvm::SelectionDAGISel::CheckNodePredicateWithOperands
virtual bool CheckNodePredicateWithOperands(SDNode *N, unsigned PredNo, const SmallVectorImpl< SDValue > &Operands) const
CheckNodePredicateWithOperands - This function is generated by tblgen in the target.
Definition: SelectionDAGISel.h:281
llvm::MDNodeSDNode
Definition: SelectionDAGNodes.h:2063
llvm::createHybridListDAGScheduler
ScheduleDAGSDNodes * createHybridListDAGScheduler(SelectionDAGISel *IS, CodeGenOpt::Level)
createHybridListDAGScheduler - This creates a bottom up register pressure aware list scheduler that m...
Definition: ScheduleDAGRRList.cpp:3163
llvm::GetSuccessorNumber
unsigned GetSuccessorNumber(const BasicBlock *BB, const BasicBlock *Succ)
Search for the specified successor of basic block BB and return its position in the terminator instru...
Definition: CFG.cpp:79
llvm::CodeGenOpt::None
@ None
Definition: CodeGen.h:53
CFG.h
llvm::ISD::HANDLENODE
@ HANDLENODE
HANDLENODE node - Used as a handle for various purposes.
Definition: ISDOpcodes.h:1071
llvm::MachineBasicBlock::succ_empty
bool succ_empty() const
Definition: MachineBasicBlock.h:347
TargetOptions.h
SelectionDAGISel.h
ViewDAGCombine2
static cl::opt< bool > ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden, cl::desc("Pop up a window to show dags before the second " "dag combine pass"))
llvm::ISD::TargetConstantPool
@ TargetConstantPool
Definition: ISDOpcodes.h:168
Scheduler
Machine Instruction Scheduler
Definition: MachineScheduler.cpp:220
llvm::NVPTXISD::Dummy
@ Dummy
Definition: NVPTXISelLowering.h:60
llvm::MachinePassRegistry
MachinePassRegistry - Track the registration of machine passes.
Definition: MachinePassRegistry.h:73
llvm::MachineBasicBlock::getFirstTerminator
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
Definition: MachineBasicBlock.cpp:242
llvm::SmallPtrSetImplBase::clear
void clear()
Definition: SmallPtrSet.h:94
llvm::Sched::Source
@ Source
Definition: TargetLowering.h:99
llvm::initializeAAResultsWrapperPassPass
void initializeAAResultsWrapperPassPass(PassRegistry &)
llvm::ArrayRef
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: APInt.h:32
llvm::LoopInfo
Definition: LoopInfo.h:1083
llvm::StackProtector::shouldEmitSDCheck
bool shouldEmitSDCheck(const BasicBlock &BB) const
Definition: StackProtector.cpp:594
None.h
llvm::OptimizationRemarkEmitter
The optimization diagnostic interface.
Definition: OptimizationRemarkEmitter.h:33
llvm::SDNode::use_end
static use_iterator use_end()
Definition: SelectionDAGNodes.h:779
llvm::MachineFrameInfo::setHasCalls
void setHasCalls(bool V)
Definition: MachineFrameInfo.h:580
DataLayout.h
llvm::SelectionDAGISel::OPC_CheckChild3Type
@ OPC_CheckChild3Type
Definition: SelectionDAGISel.h:138
llvm::StringRef
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:58
llvm::MachineBasicBlock::splice
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
Definition: MachineBasicBlock.h:950
llvm::SelectionDAGISel::SelectInlineAsmMemoryOperand
virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID, std::vector< SDValue > &OutOps)
SelectInlineAsmMemoryOperand - Select the specified address as a target addressing mode,...
Definition: SelectionDAGISel.h:91
<