SelectionDAGISel.cpp revision 9cd02c5e750dea8637fe300b27a0bf14a53e22bd
1//===-- SelectionDAGISel.cpp - Implement the SelectionDAGISel class -------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This implements the SelectionDAGISel class.
11//
12//===----------------------------------------------------------------------===//
13
14#define DEBUG_TYPE "isel"
15#include "ScheduleDAGSDNodes.h"
16#include "SelectionDAGBuild.h"
17#include "llvm/CodeGen/SelectionDAGISel.h"
18#include "llvm/Analysis/AliasAnalysis.h"
19#include "llvm/Analysis/DebugInfo.h"
20#include "llvm/Constants.h"
21#include "llvm/CallingConv.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/Function.h"
24#include "llvm/GlobalVariable.h"
25#include "llvm/InlineAsm.h"
26#include "llvm/Instructions.h"
27#include "llvm/Intrinsics.h"
28#include "llvm/IntrinsicInst.h"
29#include "llvm/CodeGen/FastISel.h"
30#include "llvm/CodeGen/GCStrategy.h"
31#include "llvm/CodeGen/GCMetadata.h"
32#include "llvm/CodeGen/MachineFunction.h"
33#include "llvm/CodeGen/MachineFunctionAnalysis.h"
34#include "llvm/CodeGen/MachineFrameInfo.h"
35#include "llvm/CodeGen/MachineInstrBuilder.h"
36#include "llvm/CodeGen/MachineJumpTableInfo.h"
37#include "llvm/CodeGen/MachineModuleInfo.h"
38#include "llvm/CodeGen/MachineRegisterInfo.h"
39#include "llvm/CodeGen/ScheduleHazardRecognizer.h"
40#include "llvm/CodeGen/SchedulerRegistry.h"
41#include "llvm/CodeGen/SelectionDAG.h"
42#include "llvm/CodeGen/DwarfWriter.h"
43#include "llvm/Target/TargetRegisterInfo.h"
44#include "llvm/Target/TargetData.h"
45#include "llvm/Target/TargetFrameInfo.h"
46#include "llvm/Target/TargetInstrInfo.h"
47#include "llvm/Target/TargetLowering.h"
48#include "llvm/Target/TargetMachine.h"
49#include "llvm/Target/TargetOptions.h"
50#include "llvm/Support/Compiler.h"
51#include "llvm/Support/Debug.h"
52#include "llvm/Support/ErrorHandling.h"
53#include "llvm/Support/MathExtras.h"
54#include "llvm/Support/Timer.h"
55#include "llvm/Support/raw_ostream.h"
56#include <algorithm>
57using namespace llvm;
58
59static cl::opt<bool>
60DisableLegalizeTypes("disable-legalize-types", cl::Hidden);
61static cl::opt<bool>
62EnableFastISelVerbose("fast-isel-verbose", cl::Hidden,
63          cl::desc("Enable verbose messages in the \"fast\" "
64                   "instruction selector"));
65static cl::opt<bool>
66EnableFastISelAbort("fast-isel-abort", cl::Hidden,
67          cl::desc("Enable abort calls when \"fast\" instruction fails"));
68static cl::opt<bool>
69SchedLiveInCopies("schedule-livein-copies",
70                  cl::desc("Schedule copies of livein registers"),
71                  cl::init(false));
72
73#ifndef NDEBUG
74static cl::opt<bool>
75ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
76          cl::desc("Pop up a window to show dags before the first "
77                   "dag combine pass"));
78static cl::opt<bool>
79ViewLegalizeTypesDAGs("view-legalize-types-dags", cl::Hidden,
80          cl::desc("Pop up a window to show dags before legalize types"));
81static cl::opt<bool>
82ViewLegalizeDAGs("view-legalize-dags", cl::Hidden,
83          cl::desc("Pop up a window to show dags before legalize"));
84static cl::opt<bool>
85ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
86          cl::desc("Pop up a window to show dags before the second "
87                   "dag combine pass"));
88static cl::opt<bool>
89ViewDAGCombineLT("view-dag-combine-lt-dags", cl::Hidden,
90          cl::desc("Pop up a window to show dags before the post legalize types"
91                   " dag combine pass"));
92static cl::opt<bool>
93ViewISelDAGs("view-isel-dags", cl::Hidden,
94          cl::desc("Pop up a window to show isel dags as they are selected"));
95static cl::opt<bool>
96ViewSchedDAGs("view-sched-dags", cl::Hidden,
97          cl::desc("Pop up a window to show sched dags as they are processed"));
98static cl::opt<bool>
99ViewSUnitDAGs("view-sunit-dags", cl::Hidden,
100      cl::desc("Pop up a window to show SUnit dags after they are processed"));
101#else
102static const bool ViewDAGCombine1 = false,
103                  ViewLegalizeTypesDAGs = false, ViewLegalizeDAGs = false,
104                  ViewDAGCombine2 = false,
105                  ViewDAGCombineLT = false,
106                  ViewISelDAGs = false, ViewSchedDAGs = false,
107                  ViewSUnitDAGs = false;
108#endif
109
110//===---------------------------------------------------------------------===//
111///
112/// RegisterScheduler class - Track the registration of instruction schedulers.
113///
114//===---------------------------------------------------------------------===//
115MachinePassRegistry RegisterScheduler::Registry;
116
117//===---------------------------------------------------------------------===//
118///
119/// ISHeuristic command line option for instruction schedulers.
120///
121//===---------------------------------------------------------------------===//
122static cl::opt<RegisterScheduler::FunctionPassCtor, false,
123               RegisterPassParser<RegisterScheduler> >
124ISHeuristic("pre-RA-sched",
125            cl::init(&createDefaultScheduler),
126            cl::desc("Instruction schedulers available (before register"
127                     " allocation):"));
128
129static RegisterScheduler
130defaultListDAGScheduler("default", "Best scheduler for the target",
131                        createDefaultScheduler);
132
133namespace llvm {
134  //===--------------------------------------------------------------------===//
135  /// createDefaultScheduler - This creates an instruction scheduler appropriate
136  /// for the target.
137  ScheduleDAGSDNodes* createDefaultScheduler(SelectionDAGISel *IS,
138                                             CodeGenOpt::Level OptLevel) {
139    const TargetLowering &TLI = IS->getTargetLowering();
140
141    if (OptLevel == CodeGenOpt::None)
142      return createFastDAGScheduler(IS, OptLevel);
143    if (TLI.getSchedulingPreference() == TargetLowering::SchedulingForLatency)
144      return createTDListDAGScheduler(IS, OptLevel);
145    assert(TLI.getSchedulingPreference() ==
146         TargetLowering::SchedulingForRegPressure && "Unknown sched type!");
147    return createBURRListDAGScheduler(IS, OptLevel);
148  }
149}
150
151// EmitInstrWithCustomInserter - This method should be implemented by targets
152// that mark instructions with the 'usesCustomDAGSchedInserter' flag.  These
153// instructions are special in various ways, which require special support to
154// insert.  The specified MachineInstr is created but not inserted into any
155// basic blocks, and the scheduler passes ownership of it to this method.
156MachineBasicBlock *TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
157                                                         MachineBasicBlock *MBB,
158                   DenseMap<MachineBasicBlock*, MachineBasicBlock*> *EM) const {
159#ifndef NDEBUG
160  errs() << "If a target marks an instruction with "
161          "'usesCustomDAGSchedInserter', it must implement "
162          "TargetLowering::EmitInstrWithCustomInserter!";
163#endif
164  llvm_unreachable(0);
165  return 0;
166}
167
168/// EmitLiveInCopy - Emit a copy for a live in physical register. If the
169/// physical register has only a single copy use, then coalesced the copy
170/// if possible.
171static void EmitLiveInCopy(MachineBasicBlock *MBB,
172                           MachineBasicBlock::iterator &InsertPos,
173                           unsigned VirtReg, unsigned PhysReg,
174                           const TargetRegisterClass *RC,
175                           DenseMap<MachineInstr*, unsigned> &CopyRegMap,
176                           const MachineRegisterInfo &MRI,
177                           const TargetRegisterInfo &TRI,
178                           const TargetInstrInfo &TII) {
179  unsigned NumUses = 0;
180  MachineInstr *UseMI = NULL;
181  for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg),
182         UE = MRI.use_end(); UI != UE; ++UI) {
183    UseMI = &*UI;
184    if (++NumUses > 1)
185      break;
186  }
187
188  // If the number of uses is not one, or the use is not a move instruction,
189  // don't coalesce. Also, only coalesce away a virtual register to virtual
190  // register copy.
191  bool Coalesced = false;
192  unsigned SrcReg, DstReg, SrcSubReg, DstSubReg;
193  if (NumUses == 1 &&
194      TII.isMoveInstr(*UseMI, SrcReg, DstReg, SrcSubReg, DstSubReg) &&
195      TargetRegisterInfo::isVirtualRegister(DstReg)) {
196    VirtReg = DstReg;
197    Coalesced = true;
198  }
199
200  // Now find an ideal location to insert the copy.
201  MachineBasicBlock::iterator Pos = InsertPos;
202  while (Pos != MBB->begin()) {
203    MachineInstr *PrevMI = prior(Pos);
204    DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI);
205    // copyRegToReg might emit multiple instructions to do a copy.
206    unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second;
207    if (CopyDstReg && !TRI.regsOverlap(CopyDstReg, PhysReg))
208      // This is what the BB looks like right now:
209      // r1024 = mov r0
210      // ...
211      // r1    = mov r1024
212      //
213      // We want to insert "r1025 = mov r1". Inserting this copy below the
214      // move to r1024 makes it impossible for that move to be coalesced.
215      //
216      // r1025 = mov r1
217      // r1024 = mov r0
218      // ...
219      // r1    = mov 1024
220      // r2    = mov 1025
221      break; // Woot! Found a good location.
222    --Pos;
223  }
224
225  bool Emitted = TII.copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC);
226  assert(Emitted && "Unable to issue a live-in copy instruction!\n");
227  (void) Emitted;
228
229CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg));
230  if (Coalesced) {
231    if (&*InsertPos == UseMI) ++InsertPos;
232    MBB->erase(UseMI);
233  }
234}
235
236/// EmitLiveInCopies - If this is the first basic block in the function,
237/// and if it has live ins that need to be copied into vregs, emit the
238/// copies into the block.
239static void EmitLiveInCopies(MachineBasicBlock *EntryMBB,
240                             const MachineRegisterInfo &MRI,
241                             const TargetRegisterInfo &TRI,
242                             const TargetInstrInfo &TII) {
243  if (SchedLiveInCopies) {
244    // Emit the copies at a heuristically-determined location in the block.
245    DenseMap<MachineInstr*, unsigned> CopyRegMap;
246    MachineBasicBlock::iterator InsertPos = EntryMBB->begin();
247    for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
248           E = MRI.livein_end(); LI != E; ++LI)
249      if (LI->second) {
250        const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
251        EmitLiveInCopy(EntryMBB, InsertPos, LI->second, LI->first,
252                       RC, CopyRegMap, MRI, TRI, TII);
253      }
254  } else {
255    // Emit the copies into the top of the block.
256    for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
257           E = MRI.livein_end(); LI != E; ++LI)
258      if (LI->second) {
259        const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
260        bool Emitted = TII.copyRegToReg(*EntryMBB, EntryMBB->begin(),
261                                        LI->second, LI->first, RC, RC);
262        assert(Emitted && "Unable to issue a live-in copy instruction!\n");
263        (void) Emitted;
264      }
265  }
266}
267
268//===----------------------------------------------------------------------===//
269// SelectionDAGISel code
270//===----------------------------------------------------------------------===//
271
272SelectionDAGISel::SelectionDAGISel(TargetMachine &tm, CodeGenOpt::Level OL) :
273  MachineFunctionPass(&ID), TM(tm), TLI(*tm.getTargetLowering()),
274  FuncInfo(new FunctionLoweringInfo(TLI)),
275  CurDAG(new SelectionDAG(TLI, *FuncInfo)),
276  SDL(new SelectionDAGLowering(*CurDAG, TLI, *FuncInfo, OL)),
277  GFI(),
278  OptLevel(OL),
279  DAGSize(0)
280{}
281
282SelectionDAGISel::~SelectionDAGISel() {
283  delete SDL;
284  delete CurDAG;
285  delete FuncInfo;
286}
287
288unsigned SelectionDAGISel::MakeReg(EVT VT) {
289  return RegInfo->createVirtualRegister(TLI.getRegClassFor(VT));
290}
291
292void SelectionDAGISel::getAnalysisUsage(AnalysisUsage &AU) const {
293  AU.addRequired<AliasAnalysis>();
294  AU.addPreserved<AliasAnalysis>();
295  AU.addRequired<GCModuleInfo>();
296  AU.addPreserved<GCModuleInfo>();
297  AU.addRequired<DwarfWriter>();
298  AU.addPreserved<DwarfWriter>();
299  MachineFunctionPass::getAnalysisUsage(AU);
300}
301
302bool SelectionDAGISel::runOnMachineFunction(MachineFunction &mf) {
303  Function &Fn = *mf.getFunction();
304
305  // Do some sanity-checking on the command-line options.
306  assert((!EnableFastISelVerbose || EnableFastISel) &&
307         "-fast-isel-verbose requires -fast-isel");
308  assert((!EnableFastISelAbort || EnableFastISel) &&
309         "-fast-isel-abort requires -fast-isel");
310
311  // Get alias analysis for load/store combining.
312  AA = &getAnalysis<AliasAnalysis>();
313
314  MF = &mf;
315  const TargetInstrInfo &TII = *TM.getInstrInfo();
316  const TargetRegisterInfo &TRI = *TM.getRegisterInfo();
317
318  if (Fn.hasGC())
319    GFI = &getAnalysis<GCModuleInfo>().getFunctionInfo(Fn);
320  else
321    GFI = 0;
322  RegInfo = &MF->getRegInfo();
323  DEBUG(errs() << "\n\n\n=== " << Fn.getName() << "\n");
324
325  MachineModuleInfo *MMI = getAnalysisIfAvailable<MachineModuleInfo>();
326  DwarfWriter *DW = getAnalysisIfAvailable<DwarfWriter>();
327  CurDAG->init(*MF, MMI, DW);
328  FuncInfo->set(Fn, *MF, *CurDAG, EnableFastISel);
329  SDL->init(GFI, *AA);
330
331  for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
332    if (InvokeInst *Invoke = dyn_cast<InvokeInst>(I->getTerminator()))
333      // Mark landing pad.
334      FuncInfo->MBBMap[Invoke->getSuccessor(1)]->setIsLandingPad();
335
336  SelectAllBasicBlocks(Fn, *MF, MMI, DW, TII);
337
338  // If the first basic block in the function has live ins that need to be
339  // copied into vregs, emit the copies into the top of the block before
340  // emitting the code for the block.
341  EmitLiveInCopies(MF->begin(), *RegInfo, TRI, TII);
342
343  // Add function live-ins to entry block live-in set.
344  for (MachineRegisterInfo::livein_iterator I = RegInfo->livein_begin(),
345         E = RegInfo->livein_end(); I != E; ++I)
346    MF->begin()->addLiveIn(I->first);
347
348#ifndef NDEBUG
349  assert(FuncInfo->CatchInfoFound.size() == FuncInfo->CatchInfoLost.size() &&
350         "Not all catch info was assigned to a landing pad!");
351#endif
352
353  FuncInfo->clear();
354
355  return true;
356}
357
358static void copyCatchInfo(BasicBlock *SrcBB, BasicBlock *DestBB,
359                          MachineModuleInfo *MMI, FunctionLoweringInfo &FLI) {
360  for (BasicBlock::iterator I = SrcBB->begin(), E = --SrcBB->end(); I != E; ++I)
361    if (EHSelectorInst *EHSel = dyn_cast<EHSelectorInst>(I)) {
362      // Apply the catch info to DestBB.
363      AddCatchInfo(*EHSel, MMI, FLI.MBBMap[DestBB]);
364#ifndef NDEBUG
365      if (!FLI.MBBMap[SrcBB]->isLandingPad())
366        FLI.CatchInfoFound.insert(EHSel);
367#endif
368    }
369}
370
371void SelectionDAGISel::SelectBasicBlock(BasicBlock *LLVMBB,
372                                        BasicBlock::iterator Begin,
373                                        BasicBlock::iterator End) {
374  SDL->setCurrentBasicBlock(BB);
375  MetadataContext &TheMetadata = LLVMBB->getParent()->getContext().getMetadata();
376  unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
377
378  // Lower all of the non-terminator instructions. If a call is emitted
379  // as a tail call, cease emitting nodes for this block.
380  for (BasicBlock::iterator I = Begin; I != End && !SDL->HasTailCall; ++I) {
381    if (MDDbgKind) {
382      // Update DebugLoc if debug information is attached with this
383      // instruction.
384      if (MDNode *Dbg = TheMetadata.getMD(MDDbgKind, I)) {
385        DILocation DILoc(Dbg);
386        DebugLoc Loc = ExtractDebugLocation(DILoc, MF->getDebugLocInfo());
387        SDL->setCurDebugLoc(Loc);
388        if (MF->getDefaultDebugLoc().isUnknown())
389          MF->setDefaultDebugLoc(Loc);
390      }
391    }
392    if (!isa<TerminatorInst>(I))
393      SDL->visit(*I);
394  }
395
396  if (!SDL->HasTailCall) {
397    // Ensure that all instructions which are used outside of their defining
398    // blocks are available as virtual registers.  Invoke is handled elsewhere.
399    for (BasicBlock::iterator I = Begin; I != End; ++I)
400      if (!isa<PHINode>(I) && !isa<InvokeInst>(I))
401        SDL->CopyToExportRegsIfNeeded(I);
402
403    // Handle PHI nodes in successor blocks.
404    if (End == LLVMBB->end()) {
405      HandlePHINodesInSuccessorBlocks(LLVMBB);
406
407      // Lower the terminator after the copies are emitted.
408      SDL->visit(*LLVMBB->getTerminator());
409    }
410  }
411
412  // Make sure the root of the DAG is up-to-date.
413  CurDAG->setRoot(SDL->getControlRoot());
414
415  // Final step, emit the lowered DAG as machine code.
416  CodeGenAndEmitDAG();
417  SDL->clear();
418}
419
420void SelectionDAGISel::ComputeLiveOutVRegInfo() {
421  SmallPtrSet<SDNode*, 128> VisitedNodes;
422  SmallVector<SDNode*, 128> Worklist;
423
424  Worklist.push_back(CurDAG->getRoot().getNode());
425
426  APInt Mask;
427  APInt KnownZero;
428  APInt KnownOne;
429
430  while (!Worklist.empty()) {
431    SDNode *N = Worklist.back();
432    Worklist.pop_back();
433
434    // If we've already seen this node, ignore it.
435    if (!VisitedNodes.insert(N))
436      continue;
437
438    // Otherwise, add all chain operands to the worklist.
439    for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
440      if (N->getOperand(i).getValueType() == MVT::Other)
441        Worklist.push_back(N->getOperand(i).getNode());
442
443    // If this is a CopyToReg with a vreg dest, process it.
444    if (N->getOpcode() != ISD::CopyToReg)
445      continue;
446
447    unsigned DestReg = cast<RegisterSDNode>(N->getOperand(1))->getReg();
448    if (!TargetRegisterInfo::isVirtualRegister(DestReg))
449      continue;
450
451    // Ignore non-scalar or non-integer values.
452    SDValue Src = N->getOperand(2);
453    EVT SrcVT = Src.getValueType();
454    if (!SrcVT.isInteger() || SrcVT.isVector())
455      continue;
456
457    unsigned NumSignBits = CurDAG->ComputeNumSignBits(Src);
458    Mask = APInt::getAllOnesValue(SrcVT.getSizeInBits());
459    CurDAG->ComputeMaskedBits(Src, Mask, KnownZero, KnownOne);
460
461    // Only install this information if it tells us something.
462    if (NumSignBits != 1 || KnownZero != 0 || KnownOne != 0) {
463      DestReg -= TargetRegisterInfo::FirstVirtualRegister;
464      if (DestReg >= FuncInfo->LiveOutRegInfo.size())
465        FuncInfo->LiveOutRegInfo.resize(DestReg+1);
466      FunctionLoweringInfo::LiveOutInfo &LOI =
467        FuncInfo->LiveOutRegInfo[DestReg];
468      LOI.NumSignBits = NumSignBits;
469      LOI.KnownOne = KnownOne;
470      LOI.KnownZero = KnownZero;
471    }
472  }
473}
474
475void SelectionDAGISel::CodeGenAndEmitDAG() {
476  std::string GroupName;
477  if (TimePassesIsEnabled)
478    GroupName = "Instruction Selection and Scheduling";
479  std::string BlockName;
480  if (ViewDAGCombine1 || ViewLegalizeTypesDAGs || ViewLegalizeDAGs ||
481      ViewDAGCombine2 || ViewDAGCombineLT || ViewISelDAGs || ViewSchedDAGs ||
482      ViewSUnitDAGs)
483    BlockName = MF->getFunction()->getNameStr() + ":" +
484                BB->getBasicBlock()->getNameStr();
485
486  DEBUG(errs() << "Initial selection DAG:\n");
487  DEBUG(CurDAG->dump());
488
489  if (ViewDAGCombine1) CurDAG->viewGraph("dag-combine1 input for " + BlockName);
490
491  // Run the DAG combiner in pre-legalize mode.
492  if (TimePassesIsEnabled) {
493    NamedRegionTimer T("DAG Combining 1", GroupName);
494    CurDAG->Combine(Unrestricted, *AA, OptLevel);
495  } else {
496    CurDAG->Combine(Unrestricted, *AA, OptLevel);
497  }
498
499  DEBUG(errs() << "Optimized lowered selection DAG:\n");
500  DEBUG(CurDAG->dump());
501
502  // Second step, hack on the DAG until it only uses operations and types that
503  // the target supports.
504  if (!DisableLegalizeTypes) {
505    if (ViewLegalizeTypesDAGs) CurDAG->viewGraph("legalize-types input for " +
506                                                 BlockName);
507
508    bool Changed;
509    if (TimePassesIsEnabled) {
510      NamedRegionTimer T("Type Legalization", GroupName);
511      Changed = CurDAG->LegalizeTypes();
512    } else {
513      Changed = CurDAG->LegalizeTypes();
514    }
515
516    DEBUG(errs() << "Type-legalized selection DAG:\n");
517    DEBUG(CurDAG->dump());
518
519    if (Changed) {
520      if (ViewDAGCombineLT)
521        CurDAG->viewGraph("dag-combine-lt input for " + BlockName);
522
523      // Run the DAG combiner in post-type-legalize mode.
524      if (TimePassesIsEnabled) {
525        NamedRegionTimer T("DAG Combining after legalize types", GroupName);
526        CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
527      } else {
528        CurDAG->Combine(NoIllegalTypes, *AA, OptLevel);
529      }
530
531      DEBUG(errs() << "Optimized type-legalized selection DAG:\n");
532      DEBUG(CurDAG->dump());
533    }
534
535    if (TimePassesIsEnabled) {
536      NamedRegionTimer T("Vector Legalization", GroupName);
537      Changed = CurDAG->LegalizeVectors();
538    } else {
539      Changed = CurDAG->LegalizeVectors();
540    }
541
542    if (Changed) {
543      if (TimePassesIsEnabled) {
544        NamedRegionTimer T("Type Legalization 2", GroupName);
545        Changed = CurDAG->LegalizeTypes();
546      } else {
547        Changed = CurDAG->LegalizeTypes();
548      }
549
550      if (ViewDAGCombineLT)
551        CurDAG->viewGraph("dag-combine-lv input for " + BlockName);
552
553      // Run the DAG combiner in post-type-legalize mode.
554      if (TimePassesIsEnabled) {
555        NamedRegionTimer T("DAG Combining after legalize vectors", GroupName);
556        CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
557      } else {
558        CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
559      }
560
561      DEBUG(errs() << "Optimized vector-legalized selection DAG:\n");
562      DEBUG(CurDAG->dump());
563    }
564  }
565
566  if (ViewLegalizeDAGs) CurDAG->viewGraph("legalize input for " + BlockName);
567
568  if (TimePassesIsEnabled) {
569    NamedRegionTimer T("DAG Legalization", GroupName);
570    CurDAG->Legalize(DisableLegalizeTypes, OptLevel);
571  } else {
572    CurDAG->Legalize(DisableLegalizeTypes, OptLevel);
573  }
574
575  DEBUG(errs() << "Legalized selection DAG:\n");
576  DEBUG(CurDAG->dump());
577
578  if (ViewDAGCombine2) CurDAG->viewGraph("dag-combine2 input for " + BlockName);
579
580  // Run the DAG combiner in post-legalize mode.
581  if (TimePassesIsEnabled) {
582    NamedRegionTimer T("DAG Combining 2", GroupName);
583    CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
584  } else {
585    CurDAG->Combine(NoIllegalOperations, *AA, OptLevel);
586  }
587
588  DEBUG(errs() << "Optimized legalized selection DAG:\n");
589  DEBUG(CurDAG->dump());
590
591  if (ViewISelDAGs) CurDAG->viewGraph("isel input for " + BlockName);
592
593  if (OptLevel != CodeGenOpt::None)
594    ComputeLiveOutVRegInfo();
595
596  // Third, instruction select all of the operations to machine code, adding the
597  // code to the MachineBasicBlock.
598  if (TimePassesIsEnabled) {
599    NamedRegionTimer T("Instruction Selection", GroupName);
600    InstructionSelect();
601  } else {
602    InstructionSelect();
603  }
604
605  DEBUG(errs() << "Selected selection DAG:\n");
606  DEBUG(CurDAG->dump());
607
608  if (ViewSchedDAGs) CurDAG->viewGraph("scheduler input for " + BlockName);
609
610  // Schedule machine code.
611  ScheduleDAGSDNodes *Scheduler = CreateScheduler();
612  if (TimePassesIsEnabled) {
613    NamedRegionTimer T("Instruction Scheduling", GroupName);
614    Scheduler->Run(CurDAG, BB, BB->end());
615  } else {
616    Scheduler->Run(CurDAG, BB, BB->end());
617  }
618
619  if (ViewSUnitDAGs) Scheduler->viewGraph();
620
621  // Emit machine code to BB.  This can change 'BB' to the last block being
622  // inserted into.
623  if (TimePassesIsEnabled) {
624    NamedRegionTimer T("Instruction Creation", GroupName);
625    BB = Scheduler->EmitSchedule(&SDL->EdgeMapping);
626  } else {
627    BB = Scheduler->EmitSchedule(&SDL->EdgeMapping);
628  }
629
630  // Free the scheduler state.
631  if (TimePassesIsEnabled) {
632    NamedRegionTimer T("Instruction Scheduling Cleanup", GroupName);
633    delete Scheduler;
634  } else {
635    delete Scheduler;
636  }
637
638  DEBUG(errs() << "Selected machine code:\n");
639  DEBUG(BB->dump());
640}
641
642void SelectionDAGISel::SelectAllBasicBlocks(Function &Fn,
643                                            MachineFunction &MF,
644                                            MachineModuleInfo *MMI,
645                                            DwarfWriter *DW,
646                                            const TargetInstrInfo &TII) {
647  // Initialize the Fast-ISel state, if needed.
648  FastISel *FastIS = 0;
649  if (EnableFastISel)
650    FastIS = TLI.createFastISel(MF, MMI, DW,
651                                FuncInfo->ValueMap,
652                                FuncInfo->MBBMap,
653                                FuncInfo->StaticAllocaMap
654#ifndef NDEBUG
655                                , FuncInfo->CatchInfoLost
656#endif
657                                );
658
659  MetadataContext &TheMetadata = Fn.getContext().getMetadata();
660  unsigned MDDbgKind = TheMetadata.getMDKind("dbg");
661
662  // Iterate over all basic blocks in the function.
663  for (Function::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) {
664    BasicBlock *LLVMBB = &*I;
665    BB = FuncInfo->MBBMap[LLVMBB];
666
667    BasicBlock::iterator const Begin = LLVMBB->begin();
668    BasicBlock::iterator const End = LLVMBB->end();
669    BasicBlock::iterator BI = Begin;
670
671    // Lower any arguments needed in this block if this is the entry block.
672    bool SuppressFastISel = false;
673    if (LLVMBB == &Fn.getEntryBlock()) {
674      LowerArguments(LLVMBB);
675
676      // If any of the arguments has the byval attribute, forgo
677      // fast-isel in the entry block.
678      if (FastIS) {
679        unsigned j = 1;
680        for (Function::arg_iterator I = Fn.arg_begin(), E = Fn.arg_end();
681             I != E; ++I, ++j)
682          if (Fn.paramHasAttr(j, Attribute::ByVal)) {
683            if (EnableFastISelVerbose || EnableFastISelAbort)
684              errs() << "FastISel skips entry block due to byval argument\n";
685            SuppressFastISel = true;
686            break;
687          }
688      }
689    }
690
691    if (MMI && BB->isLandingPad()) {
692      // Add a label to mark the beginning of the landing pad.  Deletion of the
693      // landing pad can thus be detected via the MachineModuleInfo.
694      unsigned LabelID = MMI->addLandingPad(BB);
695
696      const TargetInstrDesc &II = TII.get(TargetInstrInfo::EH_LABEL);
697      BuildMI(BB, SDL->getCurDebugLoc(), II).addImm(LabelID);
698
699      // Mark exception register as live in.
700      unsigned Reg = TLI.getExceptionAddressRegister();
701      if (Reg) BB->addLiveIn(Reg);
702
703      // Mark exception selector register as live in.
704      Reg = TLI.getExceptionSelectorRegister();
705      if (Reg) BB->addLiveIn(Reg);
706
707      // FIXME: Hack around an exception handling flaw (PR1508): the personality
708      // function and list of typeids logically belong to the invoke (or, if you
709      // like, the basic block containing the invoke), and need to be associated
710      // with it in the dwarf exception handling tables.  Currently however the
711      // information is provided by an intrinsic (eh.selector) that can be moved
712      // to unexpected places by the optimizers: if the unwind edge is critical,
713      // then breaking it can result in the intrinsics being in the successor of
714      // the landing pad, not the landing pad itself.  This results in exceptions
715      // not being caught because no typeids are associated with the invoke.
716      // This may not be the only way things can go wrong, but it is the only way
717      // we try to work around for the moment.
718      BranchInst *Br = dyn_cast<BranchInst>(LLVMBB->getTerminator());
719
720      if (Br && Br->isUnconditional()) { // Critical edge?
721        BasicBlock::iterator I, E;
722        for (I = LLVMBB->begin(), E = --LLVMBB->end(); I != E; ++I)
723          if (isa<EHSelectorInst>(I))
724            break;
725
726        if (I == E)
727          // No catch info found - try to extract some from the successor.
728          copyCatchInfo(Br->getSuccessor(0), LLVMBB, MMI, *FuncInfo);
729      }
730    }
731
732    // Before doing SelectionDAG ISel, see if FastISel has been requested.
733    if (FastIS && !SuppressFastISel) {
734      // Emit code for any incoming arguments. This must happen before
735      // beginning FastISel on the entry block.
736      if (LLVMBB == &Fn.getEntryBlock()) {
737        CurDAG->setRoot(SDL->getControlRoot());
738        CodeGenAndEmitDAG();
739        SDL->clear();
740      }
741      FastIS->startNewBlock(BB);
742      // Do FastISel on as many instructions as possible.
743      for (; BI != End; ++BI) {
744        if (MDDbgKind) {
745          // Update DebugLoc if debug information is attached with this
746          // instruction.
747          if (MDNode *Dbg = TheMetadata.getMD(MDDbgKind, BI)) {
748            DILocation DILoc(Dbg);
749            DebugLoc Loc = ExtractDebugLocation(DILoc,
750                                                MF.getDebugLocInfo());
751            FastIS->setCurDebugLoc(Loc);
752            if (MF.getDefaultDebugLoc().isUnknown())
753              MF.setDefaultDebugLoc(Loc);
754          }
755        }
756
757        // Just before the terminator instruction, insert instructions to
758        // feed PHI nodes in successor blocks.
759        if (isa<TerminatorInst>(BI))
760          if (!HandlePHINodesInSuccessorBlocksFast(LLVMBB, FastIS)) {
761            if (EnableFastISelVerbose || EnableFastISelAbort) {
762              errs() << "FastISel miss: ";
763              BI->dump();
764            }
765            assert(!EnableFastISelAbort &&
766                   "FastISel didn't handle a PHI in a successor");
767            break;
768          }
769
770        // First try normal tablegen-generated "fast" selection.
771        if (FastIS->SelectInstruction(BI))
772          continue;
773
774        // Next, try calling the target to attempt to handle the instruction.
775        if (FastIS->TargetSelectInstruction(BI))
776          continue;
777
778        // Then handle certain instructions as single-LLVM-Instruction blocks.
779        if (isa<CallInst>(BI)) {
780          if (EnableFastISelVerbose || EnableFastISelAbort) {
781            errs() << "FastISel missed call: ";
782            BI->dump();
783          }
784
785          if (BI->getType() != Type::getVoidTy(*CurDAG->getContext())) {
786            unsigned &R = FuncInfo->ValueMap[BI];
787            if (!R)
788              R = FuncInfo->CreateRegForValue(BI);
789          }
790
791          SDL->setCurDebugLoc(FastIS->getCurDebugLoc());
792          SelectBasicBlock(LLVMBB, BI, next(BI));
793          // If the instruction was codegen'd with multiple blocks,
794          // inform the FastISel object where to resume inserting.
795          FastIS->setCurrentBlock(BB);
796          continue;
797        }
798
799        // Otherwise, give up on FastISel for the rest of the block.
800        // For now, be a little lenient about non-branch terminators.
801        if (!isa<TerminatorInst>(BI) || isa<BranchInst>(BI)) {
802          if (EnableFastISelVerbose || EnableFastISelAbort) {
803            errs() << "FastISel miss: ";
804            BI->dump();
805          }
806          if (EnableFastISelAbort)
807            // The "fast" selector couldn't handle something and bailed.
808            // For the purpose of debugging, just abort.
809            llvm_unreachable("FastISel didn't select the entire block");
810        }
811        break;
812      }
813    }
814
815    // Run SelectionDAG instruction selection on the remainder of the block
816    // not handled by FastISel. If FastISel is not run, this is the entire
817    // block.
818    if (BI != End) {
819      // If FastISel is run and it has known DebugLoc then use it.
820      if (FastIS && !FastIS->getCurDebugLoc().isUnknown())
821        SDL->setCurDebugLoc(FastIS->getCurDebugLoc());
822      SelectBasicBlock(LLVMBB, BI, End);
823    }
824
825    FinishBasicBlock();
826  }
827
828  delete FastIS;
829}
830
831void
832SelectionDAGISel::FinishBasicBlock() {
833
834  DEBUG(errs() << "Target-post-processed machine code:\n");
835  DEBUG(BB->dump());
836
837  DEBUG(errs() << "Total amount of phi nodes to update: "
838               << SDL->PHINodesToUpdate.size() << "\n");
839  DEBUG(for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i)
840          errs() << "Node " << i << " : ("
841                 << SDL->PHINodesToUpdate[i].first
842                 << ", " << SDL->PHINodesToUpdate[i].second << ")\n");
843
844  // Next, now that we know what the last MBB the LLVM BB expanded is, update
845  // PHI nodes in successors.
846  if (SDL->SwitchCases.empty() &&
847      SDL->JTCases.empty() &&
848      SDL->BitTestCases.empty()) {
849    for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
850      MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
851      assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
852             "This is not a machine PHI node that we are updating!");
853      PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
854                                                false));
855      PHI->addOperand(MachineOperand::CreateMBB(BB));
856    }
857    SDL->PHINodesToUpdate.clear();
858    return;
859  }
860
861  for (unsigned i = 0, e = SDL->BitTestCases.size(); i != e; ++i) {
862    // Lower header first, if it wasn't already lowered
863    if (!SDL->BitTestCases[i].Emitted) {
864      // Set the current basic block to the mbb we wish to insert the code into
865      BB = SDL->BitTestCases[i].Parent;
866      SDL->setCurrentBasicBlock(BB);
867      // Emit the code
868      SDL->visitBitTestHeader(SDL->BitTestCases[i]);
869      CurDAG->setRoot(SDL->getRoot());
870      CodeGenAndEmitDAG();
871      SDL->clear();
872    }
873
874    for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size(); j != ej; ++j) {
875      // Set the current basic block to the mbb we wish to insert the code into
876      BB = SDL->BitTestCases[i].Cases[j].ThisBB;
877      SDL->setCurrentBasicBlock(BB);
878      // Emit the code
879      if (j+1 != ej)
880        SDL->visitBitTestCase(SDL->BitTestCases[i].Cases[j+1].ThisBB,
881                              SDL->BitTestCases[i].Reg,
882                              SDL->BitTestCases[i].Cases[j]);
883      else
884        SDL->visitBitTestCase(SDL->BitTestCases[i].Default,
885                              SDL->BitTestCases[i].Reg,
886                              SDL->BitTestCases[i].Cases[j]);
887
888
889      CurDAG->setRoot(SDL->getRoot());
890      CodeGenAndEmitDAG();
891      SDL->clear();
892    }
893
894    // Update PHI Nodes
895    for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
896      MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
897      MachineBasicBlock *PHIBB = PHI->getParent();
898      assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
899             "This is not a machine PHI node that we are updating!");
900      // This is "default" BB. We have two jumps to it. From "header" BB and
901      // from last "case" BB.
902      if (PHIBB == SDL->BitTestCases[i].Default) {
903        PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
904                                                  false));
905        PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Parent));
906        PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
907                                                  false));
908        PHI->addOperand(MachineOperand::CreateMBB(SDL->BitTestCases[i].Cases.
909                                                  back().ThisBB));
910      }
911      // One of "cases" BB.
912      for (unsigned j = 0, ej = SDL->BitTestCases[i].Cases.size();
913           j != ej; ++j) {
914        MachineBasicBlock* cBB = SDL->BitTestCases[i].Cases[j].ThisBB;
915        if (cBB->succ_end() !=
916            std::find(cBB->succ_begin(),cBB->succ_end(), PHIBB)) {
917          PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second,
918                                                    false));
919          PHI->addOperand(MachineOperand::CreateMBB(cBB));
920        }
921      }
922    }
923  }
924  SDL->BitTestCases.clear();
925
926  // If the JumpTable record is filled in, then we need to emit a jump table.
927  // Updating the PHI nodes is tricky in this case, since we need to determine
928  // whether the PHI is a successor of the range check MBB or the jump table MBB
929  for (unsigned i = 0, e = SDL->JTCases.size(); i != e; ++i) {
930    // Lower header first, if it wasn't already lowered
931    if (!SDL->JTCases[i].first.Emitted) {
932      // Set the current basic block to the mbb we wish to insert the code into
933      BB = SDL->JTCases[i].first.HeaderBB;
934      SDL->setCurrentBasicBlock(BB);
935      // Emit the code
936      SDL->visitJumpTableHeader(SDL->JTCases[i].second, SDL->JTCases[i].first);
937      CurDAG->setRoot(SDL->getRoot());
938      CodeGenAndEmitDAG();
939      SDL->clear();
940    }
941
942    // Set the current basic block to the mbb we wish to insert the code into
943    BB = SDL->JTCases[i].second.MBB;
944    SDL->setCurrentBasicBlock(BB);
945    // Emit the code
946    SDL->visitJumpTable(SDL->JTCases[i].second);
947    CurDAG->setRoot(SDL->getRoot());
948    CodeGenAndEmitDAG();
949    SDL->clear();
950
951    // Update PHI Nodes
952    for (unsigned pi = 0, pe = SDL->PHINodesToUpdate.size(); pi != pe; ++pi) {
953      MachineInstr *PHI = SDL->PHINodesToUpdate[pi].first;
954      MachineBasicBlock *PHIBB = PHI->getParent();
955      assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
956             "This is not a machine PHI node that we are updating!");
957      // "default" BB. We can go there only from header BB.
958      if (PHIBB == SDL->JTCases[i].second.Default) {
959        PHI->addOperand
960          (MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second, false));
961        PHI->addOperand
962          (MachineOperand::CreateMBB(SDL->JTCases[i].first.HeaderBB));
963      }
964      // JT BB. Just iterate over successors here
965      if (BB->succ_end() != std::find(BB->succ_begin(),BB->succ_end(), PHIBB)) {
966        PHI->addOperand
967          (MachineOperand::CreateReg(SDL->PHINodesToUpdate[pi].second, false));
968        PHI->addOperand(MachineOperand::CreateMBB(BB));
969      }
970    }
971  }
972  SDL->JTCases.clear();
973
974  // If the switch block involved a branch to one of the actual successors, we
975  // need to update PHI nodes in that block.
976  for (unsigned i = 0, e = SDL->PHINodesToUpdate.size(); i != e; ++i) {
977    MachineInstr *PHI = SDL->PHINodesToUpdate[i].first;
978    assert(PHI->getOpcode() == TargetInstrInfo::PHI &&
979           "This is not a machine PHI node that we are updating!");
980    if (BB->isSuccessor(PHI->getParent())) {
981      PHI->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[i].second,
982                                                false));
983      PHI->addOperand(MachineOperand::CreateMBB(BB));
984    }
985  }
986
987  // If we generated any switch lowering information, build and codegen any
988  // additional DAGs necessary.
989  for (unsigned i = 0, e = SDL->SwitchCases.size(); i != e; ++i) {
990    // Set the current basic block to the mbb we wish to insert the code into
991    MachineBasicBlock *ThisBB = BB = SDL->SwitchCases[i].ThisBB;
992    SDL->setCurrentBasicBlock(BB);
993
994    // Emit the code
995    SDL->visitSwitchCase(SDL->SwitchCases[i]);
996    CurDAG->setRoot(SDL->getRoot());
997    CodeGenAndEmitDAG();
998
999    // Handle any PHI nodes in successors of this chunk, as if we were coming
1000    // from the original BB before switch expansion.  Note that PHI nodes can
1001    // occur multiple times in PHINodesToUpdate.  We have to be very careful to
1002    // handle them the right number of times.
1003    while ((BB = SDL->SwitchCases[i].TrueBB)) {  // Handle LHS and RHS.
1004      // If new BB's are created during scheduling, the edges may have been
1005      // updated. That is, the edge from ThisBB to BB may have been split and
1006      // BB's predecessor is now another block.
1007      DenseMap<MachineBasicBlock*, MachineBasicBlock*>::iterator EI =
1008        SDL->EdgeMapping.find(BB);
1009      if (EI != SDL->EdgeMapping.end())
1010        ThisBB = EI->second;
1011      for (MachineBasicBlock::iterator Phi = BB->begin();
1012           Phi != BB->end() && Phi->getOpcode() == TargetInstrInfo::PHI; ++Phi){
1013        // This value for this PHI node is recorded in PHINodesToUpdate, get it.
1014        for (unsigned pn = 0; ; ++pn) {
1015          assert(pn != SDL->PHINodesToUpdate.size() &&
1016                 "Didn't find PHI entry!");
1017          if (SDL->PHINodesToUpdate[pn].first == Phi) {
1018            Phi->addOperand(MachineOperand::CreateReg(SDL->PHINodesToUpdate[pn].
1019                                                      second, false));
1020            Phi->addOperand(MachineOperand::CreateMBB(ThisBB));
1021            break;
1022          }
1023        }
1024      }
1025
1026      // Don't process RHS if same block as LHS.
1027      if (BB == SDL->SwitchCases[i].FalseBB)
1028        SDL->SwitchCases[i].FalseBB = 0;
1029
1030      // If we haven't handled the RHS, do so now.  Otherwise, we're done.
1031      SDL->SwitchCases[i].TrueBB = SDL->SwitchCases[i].FalseBB;
1032      SDL->SwitchCases[i].FalseBB = 0;
1033    }
1034    assert(SDL->SwitchCases[i].TrueBB == 0 && SDL->SwitchCases[i].FalseBB == 0);
1035    SDL->clear();
1036  }
1037  SDL->SwitchCases.clear();
1038
1039  SDL->PHINodesToUpdate.clear();
1040}
1041
1042
1043/// Create the scheduler. If a specific scheduler was specified
1044/// via the SchedulerRegistry, use it, otherwise select the
1045/// one preferred by the target.
1046///
1047ScheduleDAGSDNodes *SelectionDAGISel::CreateScheduler() {
1048  RegisterScheduler::FunctionPassCtor Ctor = RegisterScheduler::getDefault();
1049
1050  if (!Ctor) {
1051    Ctor = ISHeuristic;
1052    RegisterScheduler::setDefault(Ctor);
1053  }
1054
1055  return Ctor(this, OptLevel);
1056}
1057
1058ScheduleHazardRecognizer *SelectionDAGISel::CreateTargetHazardRecognizer() {
1059  return new ScheduleHazardRecognizer();
1060}
1061
1062//===----------------------------------------------------------------------===//
1063// Helper functions used by the generated instruction selector.
1064//===----------------------------------------------------------------------===//
1065// Calls to these methods are generated by tblgen.
1066
1067/// CheckAndMask - The isel is trying to match something like (and X, 255).  If
1068/// the dag combiner simplified the 255, we still want to match.  RHS is the
1069/// actual value in the DAG on the RHS of an AND, and DesiredMaskS is the value
1070/// specified in the .td file (e.g. 255).
1071bool SelectionDAGISel::CheckAndMask(SDValue LHS, ConstantSDNode *RHS,
1072                                    int64_t DesiredMaskS) const {
1073  const APInt &ActualMask = RHS->getAPIntValue();
1074  const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1075
1076  // If the actual mask exactly matches, success!
1077  if (ActualMask == DesiredMask)
1078    return true;
1079
1080  // If the actual AND mask is allowing unallowed bits, this doesn't match.
1081  if (ActualMask.intersects(~DesiredMask))
1082    return false;
1083
1084  // Otherwise, the DAG Combiner may have proven that the value coming in is
1085  // either already zero or is not demanded.  Check for known zero input bits.
1086  APInt NeededMask = DesiredMask & ~ActualMask;
1087  if (CurDAG->MaskedValueIsZero(LHS, NeededMask))
1088    return true;
1089
1090  // TODO: check to see if missing bits are just not demanded.
1091
1092  // Otherwise, this pattern doesn't match.
1093  return false;
1094}
1095
1096/// CheckOrMask - The isel is trying to match something like (or X, 255).  If
1097/// the dag combiner simplified the 255, we still want to match.  RHS is the
1098/// actual value in the DAG on the RHS of an OR, and DesiredMaskS is the value
1099/// specified in the .td file (e.g. 255).
1100bool SelectionDAGISel::CheckOrMask(SDValue LHS, ConstantSDNode *RHS,
1101                                   int64_t DesiredMaskS) const {
1102  const APInt &ActualMask = RHS->getAPIntValue();
1103  const APInt &DesiredMask = APInt(LHS.getValueSizeInBits(), DesiredMaskS);
1104
1105  // If the actual mask exactly matches, success!
1106  if (ActualMask == DesiredMask)
1107    return true;
1108
1109  // If the actual AND mask is allowing unallowed bits, this doesn't match.
1110  if (ActualMask.intersects(~DesiredMask))
1111    return false;
1112
1113  // Otherwise, the DAG Combiner may have proven that the value coming in is
1114  // either already zero or is not demanded.  Check for known zero input bits.
1115  APInt NeededMask = DesiredMask & ~ActualMask;
1116
1117  APInt KnownZero, KnownOne;
1118  CurDAG->ComputeMaskedBits(LHS, NeededMask, KnownZero, KnownOne);
1119
1120  // If all the missing bits in the or are already known to be set, match!
1121  if ((NeededMask & KnownOne) == NeededMask)
1122    return true;
1123
1124  // TODO: check to see if missing bits are just not demanded.
1125
1126  // Otherwise, this pattern doesn't match.
1127  return false;
1128}
1129
1130
1131/// SelectInlineAsmMemoryOperands - Calls to this are automatically generated
1132/// by tblgen.  Others should not call it.
1133void SelectionDAGISel::
1134SelectInlineAsmMemoryOperands(std::vector<SDValue> &Ops) {
1135  std::vector<SDValue> InOps;
1136  std::swap(InOps, Ops);
1137
1138  Ops.push_back(InOps[0]);  // input chain.
1139  Ops.push_back(InOps[1]);  // input asm string.
1140
1141  unsigned i = 2, e = InOps.size();
1142  if (InOps[e-1].getValueType() == MVT::Flag)
1143    --e;  // Don't process a flag operand if it is here.
1144
1145  while (i != e) {
1146    unsigned Flags = cast<ConstantSDNode>(InOps[i])->getZExtValue();
1147    if ((Flags & 7) != 4 /*MEM*/) {
1148      // Just skip over this operand, copying the operands verbatim.
1149      Ops.insert(Ops.end(), InOps.begin()+i,
1150                 InOps.begin()+i+InlineAsm::getNumOperandRegisters(Flags) + 1);
1151      i += InlineAsm::getNumOperandRegisters(Flags) + 1;
1152    } else {
1153      assert(InlineAsm::getNumOperandRegisters(Flags) == 1 &&
1154             "Memory operand with multiple values?");
1155      // Otherwise, this is a memory operand.  Ask the target to select it.
1156      std::vector<SDValue> SelOps;
1157      if (SelectInlineAsmMemoryOperand(InOps[i+1], 'm', SelOps)) {
1158        llvm_report_error("Could not match memory address.  Inline asm"
1159                          " failure!");
1160      }
1161
1162      // Add this to the output node.
1163      EVT IntPtrTy = TLI.getPointerTy();
1164      Ops.push_back(CurDAG->getTargetConstant(4/*MEM*/ | (SelOps.size()<< 3),
1165                                              IntPtrTy));
1166      Ops.insert(Ops.end(), SelOps.begin(), SelOps.end());
1167      i += 2;
1168    }
1169  }
1170
1171  // Add the flag input back if present.
1172  if (e != InOps.size())
1173    Ops.push_back(InOps.back());
1174}
1175
1176/// findFlagUse - Return use of EVT::Flag value produced by the specified
1177/// SDNode.
1178///
1179static SDNode *findFlagUse(SDNode *N) {
1180  unsigned FlagResNo = N->getNumValues()-1;
1181  for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
1182    SDUse &Use = I.getUse();
1183    if (Use.getResNo() == FlagResNo)
1184      return Use.getUser();
1185  }
1186  return NULL;
1187}
1188
1189/// findNonImmUse - Return true if "Use" is a non-immediate use of "Def".
1190/// This function recursively traverses up the operand chain, ignoring
1191/// certain nodes.
1192static bool findNonImmUse(SDNode *Use, SDNode* Def, SDNode *ImmedUse,
1193                          SDNode *Root,
1194                          SmallPtrSet<SDNode*, 16> &Visited) {
1195  if (Use->getNodeId() < Def->getNodeId() ||
1196      !Visited.insert(Use))
1197    return false;
1198
1199  for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
1200    SDNode *N = Use->getOperand(i).getNode();
1201    if (N == Def) {
1202      if (Use == ImmedUse || Use == Root)
1203        continue;  // We are not looking for immediate use.
1204      assert(N != Root);
1205      return true;
1206    }
1207
1208    // Traverse up the operand chain.
1209    if (findNonImmUse(N, Def, ImmedUse, Root, Visited))
1210      return true;
1211  }
1212  return false;
1213}
1214
1215/// isNonImmUse - Start searching from Root up the DAG to check is Def can
1216/// be reached. Return true if that's the case. However, ignore direct uses
1217/// by ImmedUse (which would be U in the example illustrated in
1218/// IsLegalAndProfitableToFold) and by Root (which can happen in the store
1219/// case).
1220/// FIXME: to be really generic, we should allow direct use by any node
1221/// that is being folded. But realisticly since we only fold loads which
1222/// have one non-chain use, we only need to watch out for load/op/store
1223/// and load/op/cmp case where the root (store / cmp) may reach the load via
1224/// its chain operand.
1225static inline bool isNonImmUse(SDNode *Root, SDNode *Def, SDNode *ImmedUse) {
1226  SmallPtrSet<SDNode*, 16> Visited;
1227  return findNonImmUse(Root, Def, ImmedUse, Root, Visited);
1228}
1229
1230/// IsLegalAndProfitableToFold - Returns true if the specific operand node N of
1231/// U can be folded during instruction selection that starts at Root and
1232/// folding N is profitable.
1233bool SelectionDAGISel::IsLegalAndProfitableToFold(SDNode *N, SDNode *U,
1234                                                  SDNode *Root) const {
1235  if (OptLevel == CodeGenOpt::None) return false;
1236
1237  // If Root use can somehow reach N through a path that that doesn't contain
1238  // U then folding N would create a cycle. e.g. In the following
1239  // diagram, Root can reach N through X. If N is folded into into Root, then
1240  // X is both a predecessor and a successor of U.
1241  //
1242  //          [N*]           //
1243  //         ^   ^           //
1244  //        /     \          //
1245  //      [U*]    [X]?       //
1246  //        ^     ^          //
1247  //         \   /           //
1248  //          \ /            //
1249  //         [Root*]         //
1250  //
1251  // * indicates nodes to be folded together.
1252  //
1253  // If Root produces a flag, then it gets (even more) interesting. Since it
1254  // will be "glued" together with its flag use in the scheduler, we need to
1255  // check if it might reach N.
1256  //
1257  //          [N*]           //
1258  //         ^   ^           //
1259  //        /     \          //
1260  //      [U*]    [X]?       //
1261  //        ^       ^        //
1262  //         \       \       //
1263  //          \      |       //
1264  //         [Root*] |       //
1265  //          ^      |       //
1266  //          f      |       //
1267  //          |      /       //
1268  //         [Y]    /        //
1269  //           ^   /         //
1270  //           f  /          //
1271  //           | /           //
1272  //          [FU]           //
1273  //
1274  // If FU (flag use) indirectly reaches N (the load), and Root folds N
1275  // (call it Fold), then X is a predecessor of FU and a successor of
1276  // Fold. But since Fold and FU are flagged together, this will create
1277  // a cycle in the scheduling graph.
1278
1279  EVT VT = Root->getValueType(Root->getNumValues()-1);
1280  while (VT == MVT::Flag) {
1281    SDNode *FU = findFlagUse(Root);
1282    if (FU == NULL)
1283      break;
1284    Root = FU;
1285    VT = Root->getValueType(Root->getNumValues()-1);
1286  }
1287
1288  return !isNonImmUse(Root, N, U);
1289}
1290
1291
1292char SelectionDAGISel::ID = 0;
1293