ScheduleDAGInstrs.cpp revision 977679d6034791fd48a344e5b990503ba50fc242
1//===---- ScheduleDAGInstrs.cpp - MachineInstr Rescheduling ---------------===//
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 ScheduleDAGInstrs class, which implements re-scheduling
11// of MachineInstrs.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "sched-instrs"
16#include "ScheduleDAGInstrs.h"
17#include "llvm/Operator.h"
18#include "llvm/Analysis/AliasAnalysis.h"
19#include "llvm/Analysis/ValueTracking.h"
20#include "llvm/CodeGen/MachineFunctionPass.h"
21#include "llvm/CodeGen/MachineMemOperand.h"
22#include "llvm/CodeGen/MachineRegisterInfo.h"
23#include "llvm/CodeGen/PseudoSourceValue.h"
24#include "llvm/MC/MCInstrItineraries.h"
25#include "llvm/Target/TargetMachine.h"
26#include "llvm/Target/TargetInstrInfo.h"
27#include "llvm/Target/TargetRegisterInfo.h"
28#include "llvm/Target/TargetSubtargetInfo.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/raw_ostream.h"
31#include "llvm/ADT/SmallSet.h"
32using namespace llvm;
33
34ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
35                                     const MachineLoopInfo &mli,
36                                     const MachineDominatorTree &mdt)
37  : ScheduleDAG(mf), MLI(mli), MDT(mdt), MFI(mf.getFrameInfo()),
38    InstrItins(mf.getTarget().getInstrItineraryData()),
39    Defs(TRI->getNumRegs()), Uses(TRI->getNumRegs()),
40    LoopRegs(MLI, MDT), FirstDbgValue(0) {
41  DbgValues.clear();
42}
43
44/// Run - perform scheduling.
45///
46void ScheduleDAGInstrs::Run(MachineBasicBlock *bb,
47                            MachineBasicBlock::iterator begin,
48                            MachineBasicBlock::iterator end,
49                            unsigned endcount) {
50  BB = bb;
51  Begin = begin;
52  InsertPosIndex = endcount;
53
54  ScheduleDAG::Run(bb, end);
55}
56
57/// getUnderlyingObjectFromInt - This is the function that does the work of
58/// looking through basic ptrtoint+arithmetic+inttoptr sequences.
59static const Value *getUnderlyingObjectFromInt(const Value *V) {
60  do {
61    if (const Operator *U = dyn_cast<Operator>(V)) {
62      // If we find a ptrtoint, we can transfer control back to the
63      // regular getUnderlyingObjectFromInt.
64      if (U->getOpcode() == Instruction::PtrToInt)
65        return U->getOperand(0);
66      // If we find an add of a constant or a multiplied value, it's
67      // likely that the other operand will lead us to the base
68      // object. We don't have to worry about the case where the
69      // object address is somehow being computed by the multiply,
70      // because our callers only care when the result is an
71      // identifibale object.
72      if (U->getOpcode() != Instruction::Add ||
73          (!isa<ConstantInt>(U->getOperand(1)) &&
74           Operator::getOpcode(U->getOperand(1)) != Instruction::Mul))
75        return V;
76      V = U->getOperand(0);
77    } else {
78      return V;
79    }
80    assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
81  } while (1);
82}
83
84/// getUnderlyingObject - This is a wrapper around GetUnderlyingObject
85/// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
86static const Value *getUnderlyingObject(const Value *V) {
87  // First just call Value::getUnderlyingObject to let it do what it does.
88  do {
89    V = GetUnderlyingObject(V);
90    // If it found an inttoptr, use special code to continue climing.
91    if (Operator::getOpcode(V) != Instruction::IntToPtr)
92      break;
93    const Value *O = getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
94    // If that succeeded in finding a pointer, continue the search.
95    if (!O->getType()->isPointerTy())
96      break;
97    V = O;
98  } while (1);
99  return V;
100}
101
102/// getUnderlyingObjectForInstr - If this machine instr has memory reference
103/// information and it can be tracked to a normal reference to a known
104/// object, return the Value for that object. Otherwise return null.
105static const Value *getUnderlyingObjectForInstr(const MachineInstr *MI,
106                                                const MachineFrameInfo *MFI,
107                                                bool &MayAlias) {
108  MayAlias = true;
109  if (!MI->hasOneMemOperand() ||
110      !(*MI->memoperands_begin())->getValue() ||
111      (*MI->memoperands_begin())->isVolatile())
112    return 0;
113
114  const Value *V = (*MI->memoperands_begin())->getValue();
115  if (!V)
116    return 0;
117
118  V = getUnderlyingObject(V);
119  if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
120    // For now, ignore PseudoSourceValues which may alias LLVM IR values
121    // because the code that uses this function has no way to cope with
122    // such aliases.
123    if (PSV->isAliased(MFI))
124      return 0;
125
126    MayAlias = PSV->mayAlias(MFI);
127    return V;
128  }
129
130  if (isIdentifiedObject(V))
131    return V;
132
133  return 0;
134}
135
136void ScheduleDAGInstrs::StartBlock(MachineBasicBlock *BB) {
137  LoopRegs.Deps.clear();
138  if (MachineLoop *ML = MLI.getLoopFor(BB))
139    if (BB == ML->getLoopLatch())
140      LoopRegs.VisitLoop(ML);
141}
142
143/// AddSchedBarrierDeps - Add dependencies from instructions in the current
144/// list of instructions being scheduled to scheduling barrier by adding
145/// the exit SU to the register defs and use list. This is because we want to
146/// make sure instructions which define registers that are either used by
147/// the terminator or are live-out are properly scheduled. This is
148/// especially important when the definition latency of the return value(s)
149/// are too high to be hidden by the branch or when the liveout registers
150/// used by instructions in the fallthrough block.
151void ScheduleDAGInstrs::AddSchedBarrierDeps() {
152  MachineInstr *ExitMI = InsertPos != BB->end() ? &*InsertPos : 0;
153  ExitSU.setInstr(ExitMI);
154  bool AllDepKnown = ExitMI &&
155    (ExitMI->isCall() || ExitMI->isBarrier());
156  if (ExitMI && AllDepKnown) {
157    // If it's a call or a barrier, add dependencies on the defs and uses of
158    // instruction.
159    for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
160      const MachineOperand &MO = ExitMI->getOperand(i);
161      if (!MO.isReg() || MO.isDef()) continue;
162      unsigned Reg = MO.getReg();
163      if (Reg == 0) continue;
164
165      assert(TRI->isPhysicalRegister(Reg) && "Virtual register encountered!");
166      Uses[Reg].push_back(&ExitSU);
167    }
168  } else {
169    // For others, e.g. fallthrough, conditional branch, assume the exit
170    // uses all the registers that are livein to the successor blocks.
171    SmallSet<unsigned, 8> Seen;
172    for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
173           SE = BB->succ_end(); SI != SE; ++SI)
174      for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
175             E = (*SI)->livein_end(); I != E; ++I) {
176        unsigned Reg = *I;
177        if (Seen.insert(Reg))
178          Uses[Reg].push_back(&ExitSU);
179      }
180  }
181}
182
183void ScheduleDAGInstrs::BuildSchedGraph(AliasAnalysis *AA) {
184  // We'll be allocating one SUnit for each instruction, plus one for
185  // the region exit node.
186  SUnits.reserve(BB->size());
187
188  // We build scheduling units by walking a block's instruction list from bottom
189  // to top.
190
191  // Remember where a generic side-effecting instruction is as we procede.
192  SUnit *BarrierChain = 0, *AliasChain = 0;
193
194  // Memory references to specific known memory locations are tracked
195  // so that they can be given more precise dependencies. We track
196  // separately the known memory locations that may alias and those
197  // that are known not to alias
198  std::map<const Value *, SUnit *> AliasMemDefs, NonAliasMemDefs;
199  std::map<const Value *, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
200
201  // Check to see if the scheduler cares about latencies.
202  bool UnitLatencies = ForceUnitLatencies();
203
204  // Ask the target if address-backscheduling is desirable, and if so how much.
205  const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
206  unsigned SpecialAddressLatency = ST.getSpecialAddressLatency();
207
208  // Remove any stale debug info; sometimes BuildSchedGraph is called again
209  // without emitting the info from the previous call.
210  DbgValues.clear();
211  FirstDbgValue = NULL;
212
213  // Model data dependencies between instructions being scheduled and the
214  // ExitSU.
215  AddSchedBarrierDeps();
216
217  for (int i = 0, e = TRI->getNumRegs(); i != e; ++i) {
218    assert(Defs[i].empty() && "Only BuildGraph should push/pop Defs");
219  }
220
221  // Walk the list of instructions, from bottom moving up.
222  MachineInstr *PrevMI = NULL;
223  for (MachineBasicBlock::iterator MII = InsertPos, MIE = Begin;
224       MII != MIE; --MII) {
225    MachineInstr *MI = prior(MII);
226    if (MI && PrevMI) {
227      DbgValues.push_back(std::make_pair(PrevMI, MI));
228      PrevMI = NULL;
229    }
230
231    if (MI->isDebugValue()) {
232      PrevMI = MI;
233      continue;
234    }
235
236    assert(!MI->isTerminator() && !MI->isLabel() &&
237           "Cannot schedule terminators or labels!");
238    // Create the SUnit for this MI.
239    SUnit *SU = NewSUnit(MI);
240    SU->isCall = MI->isCall();
241    SU->isCommutable = MI->isCommutable();
242
243    // Assign the Latency field of SU using target-provided information.
244    if (UnitLatencies)
245      SU->Latency = 1;
246    else
247      ComputeLatency(SU);
248
249    // Add register-based dependencies (data, anti, and output).
250    for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
251      const MachineOperand &MO = MI->getOperand(j);
252      if (!MO.isReg()) continue;
253      unsigned Reg = MO.getReg();
254      if (Reg == 0) continue;
255
256      assert(TRI->isPhysicalRegister(Reg) && "Virtual register encountered!");
257
258      // Optionally add output and anti dependencies. For anti
259      // dependencies we use a latency of 0 because for a multi-issue
260      // target we want to allow the defining instruction to issue
261      // in the same cycle as the using instruction.
262      // TODO: Using a latency of 1 here for output dependencies assumes
263      //       there's no cost for reusing registers.
264      SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
265      for (const unsigned *Alias = TRI->getOverlaps(Reg); *Alias; ++Alias) {
266        std::vector<SUnit *> &DefList = Defs[*Alias];
267        for (unsigned i = 0, e = DefList.size(); i != e; ++i) {
268          SUnit *DefSU = DefList[i];
269          if (DefSU == &ExitSU)
270            continue;
271          if (DefSU != SU &&
272              (Kind != SDep::Output || !MO.isDead() ||
273               !DefSU->getInstr()->registerDefIsDead(*Alias))) {
274            if (Kind == SDep::Anti)
275              DefSU->addPred(SDep(SU, Kind, 0, /*Reg=*/*Alias));
276            else {
277              unsigned AOLat = TII->getOutputLatency(InstrItins, MI, j,
278                                                     DefSU->getInstr());
279              DefSU->addPred(SDep(SU, Kind, AOLat, /*Reg=*/*Alias));
280            }
281          }
282        }
283      }
284
285      // Retrieve the UseList to add data dependencies and update uses.
286      std::vector<SUnit *> &UseList = Uses[Reg];
287      if (MO.isDef()) {
288        // Update DefList. Defs are pushed in the order they are visited and
289        // never reordered.
290        std::vector<SUnit *> &DefList = Defs[Reg];
291
292        // Add any data dependencies.
293        unsigned DataLatency = SU->Latency;
294        for (unsigned i = 0, e = UseList.size(); i != e; ++i) {
295          SUnit *UseSU = UseList[i];
296          if (UseSU == SU)
297            continue;
298          unsigned LDataLatency = DataLatency;
299          // Optionally add in a special extra latency for nodes that
300          // feed addresses.
301          // TODO: Do this for register aliases too.
302          // TODO: Perhaps we should get rid of
303          // SpecialAddressLatency and just move this into
304          // adjustSchedDependency for the targets that care about it.
305          if (SpecialAddressLatency != 0 && !UnitLatencies &&
306              UseSU != &ExitSU) {
307            MachineInstr *UseMI = UseSU->getInstr();
308            const MCInstrDesc &UseMCID = UseMI->getDesc();
309            int RegUseIndex = UseMI->findRegisterUseOperandIdx(Reg);
310            assert(RegUseIndex >= 0 && "UseMI doesn's use register!");
311            if (RegUseIndex >= 0 &&
312                (UseMI->mayLoad() || UseMI->mayStore()) &&
313                (unsigned)RegUseIndex < UseMCID.getNumOperands() &&
314                UseMCID.OpInfo[RegUseIndex].isLookupPtrRegClass())
315              LDataLatency += SpecialAddressLatency;
316          }
317          // Adjust the dependence latency using operand def/use
318          // information (if any), and then allow the target to
319          // perform its own adjustments.
320          const SDep& dep = SDep(SU, SDep::Data, LDataLatency, Reg);
321          if (!UnitLatencies) {
322            ComputeOperandLatency(SU, UseSU, const_cast<SDep &>(dep));
323            ST.adjustSchedDependency(SU, UseSU, const_cast<SDep &>(dep));
324          }
325          UseSU->addPred(dep);
326        }
327        for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
328          std::vector<SUnit *> &UseList = Uses[*Alias];
329          for (unsigned i = 0, e = UseList.size(); i != e; ++i) {
330            SUnit *UseSU = UseList[i];
331            if (UseSU == SU)
332              continue;
333            const SDep& dep = SDep(SU, SDep::Data, DataLatency, *Alias);
334            if (!UnitLatencies) {
335              ComputeOperandLatency(SU, UseSU, const_cast<SDep &>(dep));
336              ST.adjustSchedDependency(SU, UseSU, const_cast<SDep &>(dep));
337            }
338            UseSU->addPred(dep);
339          }
340        }
341
342        // If a def is going to wrap back around to the top of the loop,
343        // backschedule it.
344        if (!UnitLatencies && DefList.empty()) {
345          LoopDependencies::LoopDeps::iterator I = LoopRegs.Deps.find(Reg);
346          if (I != LoopRegs.Deps.end()) {
347            const MachineOperand *UseMO = I->second.first;
348            unsigned Count = I->second.second;
349            const MachineInstr *UseMI = UseMO->getParent();
350            unsigned UseMOIdx = UseMO - &UseMI->getOperand(0);
351            const MCInstrDesc &UseMCID = UseMI->getDesc();
352            // TODO: If we knew the total depth of the region here, we could
353            // handle the case where the whole loop is inside the region but
354            // is large enough that the isScheduleHigh trick isn't needed.
355            if (UseMOIdx < UseMCID.getNumOperands()) {
356              // Currently, we only support scheduling regions consisting of
357              // single basic blocks. Check to see if the instruction is in
358              // the same region by checking to see if it has the same parent.
359              if (UseMI->getParent() != MI->getParent()) {
360                unsigned Latency = SU->Latency;
361                if (UseMCID.OpInfo[UseMOIdx].isLookupPtrRegClass())
362                  Latency += SpecialAddressLatency;
363                // This is a wild guess as to the portion of the latency which
364                // will be overlapped by work done outside the current
365                // scheduling region.
366                Latency -= std::min(Latency, Count);
367                // Add the artificial edge.
368                ExitSU.addPred(SDep(SU, SDep::Order, Latency,
369                                    /*Reg=*/0, /*isNormalMemory=*/false,
370                                    /*isMustAlias=*/false,
371                                    /*isArtificial=*/true));
372              } else if (SpecialAddressLatency > 0 &&
373                         UseMCID.OpInfo[UseMOIdx].isLookupPtrRegClass()) {
374                // The entire loop body is within the current scheduling region
375                // and the latency of this operation is assumed to be greater
376                // than the latency of the loop.
377                // TODO: Recursively mark data-edge predecessors as
378                //       isScheduleHigh too.
379                SU->isScheduleHigh = true;
380              }
381            }
382            LoopRegs.Deps.erase(I);
383          }
384        }
385
386        UseList.clear();
387        if (!MO.isDead())
388          DefList.clear();
389
390        // Calls will not be reordered because of chain dependencies (see
391        // below). Since call operands are dead, calls may continue to be added
392        // to the DefList making dependence checking quadratic in the size of
393        // the block. Instead, we leave only one call at the back of the
394        // DefList.
395        if (SU->isCall) {
396          while (!DefList.empty() && DefList.back()->isCall)
397            DefList.pop_back();
398        }
399        DefList.push_back(SU);
400      } else {
401        UseList.push_back(SU);
402      }
403    }
404
405    // Add chain dependencies.
406    // Chain dependencies used to enforce memory order should have
407    // latency of 0 (except for true dependency of Store followed by
408    // aliased Load... we estimate that with a single cycle of latency
409    // assuming the hardware will bypass)
410    // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
411    // after stack slots are lowered to actual addresses.
412    // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
413    // produce more precise dependence information.
414#define STORE_LOAD_LATENCY 1
415    unsigned TrueMemOrderLatency = 0;
416    if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
417        (MI->hasVolatileMemoryRef() &&
418         (!MI->mayLoad() || !MI->isInvariantLoad(AA)))) {
419      // Be conservative with these and add dependencies on all memory
420      // references, even those that are known to not alias.
421      for (std::map<const Value *, SUnit *>::iterator I =
422             NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
423        I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
424      }
425      for (std::map<const Value *, std::vector<SUnit *> >::iterator I =
426             NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
427        for (unsigned i = 0, e = I->second.size(); i != e; ++i)
428          I->second[i]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency));
429      }
430      NonAliasMemDefs.clear();
431      NonAliasMemUses.clear();
432      // Add SU to the barrier chain.
433      if (BarrierChain)
434        BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
435      BarrierChain = SU;
436
437      // fall-through
438    new_alias_chain:
439      // Chain all possibly aliasing memory references though SU.
440      if (AliasChain)
441        AliasChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
442      AliasChain = SU;
443      for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
444        PendingLoads[k]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency));
445      for (std::map<const Value *, SUnit *>::iterator I = AliasMemDefs.begin(),
446           E = AliasMemDefs.end(); I != E; ++I) {
447        I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
448      }
449      for (std::map<const Value *, std::vector<SUnit *> >::iterator I =
450           AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
451        for (unsigned i = 0, e = I->second.size(); i != e; ++i)
452          I->second[i]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency));
453      }
454      PendingLoads.clear();
455      AliasMemDefs.clear();
456      AliasMemUses.clear();
457    } else if (MI->mayStore()) {
458      bool MayAlias = true;
459      TrueMemOrderLatency = STORE_LOAD_LATENCY;
460      if (const Value *V = getUnderlyingObjectForInstr(MI, MFI, MayAlias)) {
461        // A store to a specific PseudoSourceValue. Add precise dependencies.
462        // Record the def in MemDefs, first adding a dep if there is
463        // an existing def.
464        std::map<const Value *, SUnit *>::iterator I =
465          ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
466        std::map<const Value *, SUnit *>::iterator IE =
467          ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
468        if (I != IE) {
469          I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0, /*Reg=*/0,
470                                  /*isNormalMemory=*/true));
471          I->second = SU;
472        } else {
473          if (MayAlias)
474            AliasMemDefs[V] = SU;
475          else
476            NonAliasMemDefs[V] = SU;
477        }
478        // Handle the uses in MemUses, if there are any.
479        std::map<const Value *, std::vector<SUnit *> >::iterator J =
480          ((MayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
481        std::map<const Value *, std::vector<SUnit *> >::iterator JE =
482          ((MayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
483        if (J != JE) {
484          for (unsigned i = 0, e = J->second.size(); i != e; ++i)
485            J->second[i]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency,
486                                       /*Reg=*/0, /*isNormalMemory=*/true));
487          J->second.clear();
488        }
489        if (MayAlias) {
490          // Add dependencies from all the PendingLoads, i.e. loads
491          // with no underlying object.
492          for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
493            PendingLoads[k]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency));
494          // Add dependence on alias chain, if needed.
495          if (AliasChain)
496            AliasChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
497        }
498        // Add dependence on barrier chain, if needed.
499        if (BarrierChain)
500          BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
501      } else {
502        // Treat all other stores conservatively.
503        goto new_alias_chain;
504      }
505
506      if (!ExitSU.isPred(SU))
507        // Push store's up a bit to avoid them getting in between cmp
508        // and branches.
509        ExitSU.addPred(SDep(SU, SDep::Order, 0,
510                            /*Reg=*/0, /*isNormalMemory=*/false,
511                            /*isMustAlias=*/false,
512                            /*isArtificial=*/true));
513    } else if (MI->mayLoad()) {
514      bool MayAlias = true;
515      TrueMemOrderLatency = 0;
516      if (MI->isInvariantLoad(AA)) {
517        // Invariant load, no chain dependencies needed!
518      } else {
519        if (const Value *V =
520            getUnderlyingObjectForInstr(MI, MFI, MayAlias)) {
521          // A load from a specific PseudoSourceValue. Add precise dependencies.
522          std::map<const Value *, SUnit *>::iterator I =
523            ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
524          std::map<const Value *, SUnit *>::iterator IE =
525            ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
526          if (I != IE)
527            I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0, /*Reg=*/0,
528                                    /*isNormalMemory=*/true));
529          if (MayAlias)
530            AliasMemUses[V].push_back(SU);
531          else
532            NonAliasMemUses[V].push_back(SU);
533        } else {
534          // A load with no underlying object. Depend on all
535          // potentially aliasing stores.
536          for (std::map<const Value *, SUnit *>::iterator I =
537                 AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
538            I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
539
540          PendingLoads.push_back(SU);
541          MayAlias = true;
542        }
543
544        // Add dependencies on alias and barrier chains, if needed.
545        if (MayAlias && AliasChain)
546          AliasChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
547        if (BarrierChain)
548          BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0));
549      }
550    }
551  }
552  if (PrevMI)
553    FirstDbgValue = PrevMI;
554
555  for (int i = 0, e = TRI->getNumRegs(); i != e; ++i) {
556    Defs[i].clear();
557    Uses[i].clear();
558  }
559  PendingLoads.clear();
560}
561
562void ScheduleDAGInstrs::FinishBlock() {
563  // Nothing to do.
564}
565
566void ScheduleDAGInstrs::ComputeLatency(SUnit *SU) {
567  // Compute the latency for the node.
568  if (!InstrItins || InstrItins->isEmpty()) {
569    SU->Latency = 1;
570
571    // Simplistic target-independent heuristic: assume that loads take
572    // extra time.
573    if (SU->getInstr()->mayLoad())
574      SU->Latency += 2;
575  } else {
576    SU->Latency = TII->getInstrLatency(InstrItins, SU->getInstr());
577  }
578}
579
580void ScheduleDAGInstrs::ComputeOperandLatency(SUnit *Def, SUnit *Use,
581                                              SDep& dep) const {
582  if (!InstrItins || InstrItins->isEmpty())
583    return;
584
585  // For a data dependency with a known register...
586  if ((dep.getKind() != SDep::Data) || (dep.getReg() == 0))
587    return;
588
589  const unsigned Reg = dep.getReg();
590
591  // ... find the definition of the register in the defining
592  // instruction
593  MachineInstr *DefMI = Def->getInstr();
594  int DefIdx = DefMI->findRegisterDefOperandIdx(Reg);
595  if (DefIdx != -1) {
596    const MachineOperand &MO = DefMI->getOperand(DefIdx);
597    if (MO.isReg() && MO.isImplicit() &&
598        DefIdx >= (int)DefMI->getDesc().getNumOperands()) {
599      // This is an implicit def, getOperandLatency() won't return the correct
600      // latency. e.g.
601      //   %D6<def>, %D7<def> = VLD1q16 %R2<kill>, 0, ..., %Q3<imp-def>
602      //   %Q1<def> = VMULv8i16 %Q1<kill>, %Q3<kill>, ...
603      // What we want is to compute latency between def of %D6/%D7 and use of
604      // %Q3 instead.
605      DefIdx = DefMI->findRegisterDefOperandIdx(Reg, false, true, TRI);
606    }
607    MachineInstr *UseMI = Use->getInstr();
608    // For all uses of the register, calculate the maxmimum latency
609    int Latency = -1;
610    if (UseMI) {
611      for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
612        const MachineOperand &MO = UseMI->getOperand(i);
613        if (!MO.isReg() || !MO.isUse())
614          continue;
615        unsigned MOReg = MO.getReg();
616        if (MOReg != Reg)
617          continue;
618
619        int UseCycle = TII->getOperandLatency(InstrItins, DefMI, DefIdx,
620                                              UseMI, i);
621        Latency = std::max(Latency, UseCycle);
622      }
623    } else {
624      // UseMI is null, then it must be a scheduling barrier.
625      if (!InstrItins || InstrItins->isEmpty())
626        return;
627      unsigned DefClass = DefMI->getDesc().getSchedClass();
628      Latency = InstrItins->getOperandCycle(DefClass, DefIdx);
629    }
630
631    // If we found a latency, then replace the existing dependence latency.
632    if (Latency >= 0)
633      dep.setLatency(Latency);
634  }
635}
636
637void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
638  SU->getInstr()->dump();
639}
640
641std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
642  std::string s;
643  raw_string_ostream oss(s);
644  if (SU == &EntrySU)
645    oss << "<entry>";
646  else if (SU == &ExitSU)
647    oss << "<exit>";
648  else
649    SU->getInstr()->print(oss);
650  return oss.str();
651}
652
653// EmitSchedule - Emit the machine code in scheduled order.
654MachineBasicBlock *ScheduleDAGInstrs::EmitSchedule() {
655  Begin = InsertPos;
656
657  // If first instruction was a DBG_VALUE then put it back.
658  if (FirstDbgValue)
659    BB->splice(InsertPos, BB, FirstDbgValue);
660
661  // Then re-insert them according to the given schedule.
662  for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
663    if (SUnit *SU = Sequence[i])
664      BB->splice(InsertPos, BB, SU->getInstr());
665    else
666      // Null SUnit* is a noop.
667      EmitNoop();
668
669    // Update the Begin iterator, as the first instruction in the block
670    // may have been scheduled later.
671    if (i == 0)
672      Begin = prior(InsertPos);
673  }
674
675  // Reinsert any remaining debug_values.
676  for (std::vector<std::pair<MachineInstr *, MachineInstr *> >::iterator
677         DI = DbgValues.end(), DE = DbgValues.begin(); DI != DE; --DI) {
678    std::pair<MachineInstr *, MachineInstr *> P = *prior(DI);
679    MachineInstr *DbgValue = P.first;
680    MachineBasicBlock::iterator OrigPrivMI = P.second;
681    BB->splice(++OrigPrivMI, BB, DbgValue);
682  }
683  DbgValues.clear();
684  FirstDbgValue = NULL;
685  return BB;
686}
687