ScheduleDAGInstrs.cpp revision c9a5b9e38b442c2ae6b115213a07df3fcd14708d
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 "llvm/CodeGen/MachineDominators.h"
17#include "llvm/CodeGen/MachineFunctionPass.h"
18#include "llvm/CodeGen/MachineLoopInfo.h"
19#include "llvm/CodeGen/MachineRegisterInfo.h"
20#include "llvm/CodeGen/ScheduleDAGInstrs.h"
21#include "llvm/CodeGen/PseudoSourceValue.h"
22#include "llvm/Target/TargetMachine.h"
23#include "llvm/Target/TargetInstrInfo.h"
24#include "llvm/Target/TargetRegisterInfo.h"
25#include "llvm/Target/TargetSubtarget.h"
26#include "llvm/Support/Compiler.h"
27#include "llvm/Support/Debug.h"
28#include "llvm/Support/raw_ostream.h"
29#include "llvm/ADT/SmallSet.h"
30#include <map>
31using namespace llvm;
32
33namespace {
34  class VISIBILITY_HIDDEN LoopDependencies {
35    const MachineLoopInfo &MLI;
36    const MachineDominatorTree &MDT;
37
38  public:
39    typedef std::map<unsigned, std::pair<const MachineOperand *, unsigned> >
40      LoopDeps;
41    LoopDeps Deps;
42
43    LoopDependencies(const MachineLoopInfo &mli,
44                     const MachineDominatorTree &mdt) :
45      MLI(mli), MDT(mdt) {}
46
47    void VisitLoop(const MachineLoop *Loop) {
48      Deps.clear();
49      MachineBasicBlock *Header = Loop->getHeader();
50      SmallSet<unsigned, 8> LoopLiveIns;
51      for (MachineBasicBlock::livein_iterator LI = Header->livein_begin(),
52           LE = Header->livein_end(); LI != LE; ++LI)
53        LoopLiveIns.insert(*LI);
54
55      VisitRegion(MDT.getNode(Header), Loop, LoopLiveIns);
56    }
57
58  private:
59    void VisitRegion(const MachineDomTreeNode *Node,
60                     const MachineLoop *Loop,
61                     const SmallSet<unsigned, 8> &LoopLiveIns) {
62      MachineBasicBlock *MBB = Node->getBlock();
63      if (!Loop->contains(MBB)) return;
64
65      unsigned Count = 0;
66      for (MachineBasicBlock::const_iterator I = MBB->begin(), E = MBB->end();
67           I != E; ++I, ++Count) {
68        const MachineInstr *MI = I;
69        for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
70          const MachineOperand &MO = MI->getOperand(i);
71          if (!MO.isReg() || !MO.isUse())
72            continue;
73          unsigned MOReg = MO.getReg();
74          if (LoopLiveIns.count(MOReg))
75            Deps.insert(std::make_pair(MOReg, std::make_pair(&MO, Count)));
76        }
77      }
78
79      const std::vector<MachineDomTreeNode*> &Children = Node->getChildren();
80      for (unsigned I = 0, E = Children.size(); I != E; ++I)
81        VisitRegion(Children[I], Loop, LoopLiveIns);
82    }
83  };
84}
85
86ScheduleDAGInstrs::ScheduleDAGInstrs(MachineBasicBlock *bb,
87                                     const TargetMachine &tm,
88                                     const MachineLoopInfo &mli,
89                                     const MachineDominatorTree &mdt)
90  : ScheduleDAG(0, bb, tm), MLI(mli), MDT(mdt) {}
91
92void ScheduleDAGInstrs::BuildSchedGraph() {
93  SUnits.clear();
94  SUnits.reserve(BB->size());
95
96  // We build scheduling units by walking a block's instruction list from bottom
97  // to top.
98
99  // Remember where defs and uses of each physical register are as we procede.
100  std::vector<SUnit *> Defs[TargetRegisterInfo::FirstVirtualRegister] = {};
101  std::vector<SUnit *> Uses[TargetRegisterInfo::FirstVirtualRegister] = {};
102
103  // Remember where unknown loads are after the most recent unknown store
104  // as we procede.
105  std::vector<SUnit *> PendingLoads;
106
107  // Remember where a generic side-effecting instruction is as we procede. If
108  // ChainMMO is null, this is assumed to have arbitrary side-effects. If
109  // ChainMMO is non-null, then Chain makes only a single memory reference.
110  SUnit *Chain = 0;
111  MachineMemOperand *ChainMMO = 0;
112
113  // Memory references to specific known memory locations are tracked so that
114  // they can be given more precise dependencies.
115  std::map<const Value *, SUnit *> MemDefs;
116  std::map<const Value *, std::vector<SUnit *> > MemUses;
117
118  // Terminators can perform control transfers, we we need to make sure that
119  // all the work of the block is done before the terminator.
120  SUnit *Terminator = 0;
121
122  LoopDependencies LoopRegs(MLI, MDT);
123
124  // Track which regs are live into a loop, to help guide back-edge-aware
125  // scheduling.
126  SmallSet<unsigned, 8> LoopLiveInRegs;
127  if (MachineLoop *ML = MLI.getLoopFor(BB))
128    if (BB == ML->getLoopLatch()) {
129      MachineBasicBlock *Header = ML->getHeader();
130      for (MachineBasicBlock::livein_iterator I = Header->livein_begin(),
131           E = Header->livein_end(); I != E; ++I)
132        LoopLiveInRegs.insert(*I);
133      LoopRegs.VisitLoop(ML);
134    }
135
136  // Check to see if the scheduler cares about latencies.
137  bool UnitLatencies = ForceUnitLatencies();
138
139  // Ask the target if address-backscheduling is desirable, and if so how much.
140  unsigned SpecialAddressLatency =
141    TM.getSubtarget<TargetSubtarget>().getSpecialAddressLatency();
142
143  for (MachineBasicBlock::iterator MII = BB->end(), MIE = BB->begin();
144       MII != MIE; --MII) {
145    MachineInstr *MI = prior(MII);
146    const TargetInstrDesc &TID = MI->getDesc();
147    SUnit *SU = NewSUnit(MI);
148
149    // Assign the Latency field of SU using target-provided information.
150    if (UnitLatencies)
151      SU->Latency = 1;
152    else
153      ComputeLatency(SU);
154
155    // Add register-based dependencies (data, anti, and output).
156    for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
157      const MachineOperand &MO = MI->getOperand(j);
158      if (!MO.isReg()) continue;
159      unsigned Reg = MO.getReg();
160      if (Reg == 0) continue;
161
162      assert(TRI->isPhysicalRegister(Reg) && "Virtual register encountered!");
163      std::vector<SUnit *> &UseList = Uses[Reg];
164      std::vector<SUnit *> &DefList = Defs[Reg];
165      // Optionally add output and anti dependencies.
166      // TODO: Using a latency of 1 here assumes there's no cost for
167      //       reusing registers.
168      SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
169      for (unsigned i = 0, e = DefList.size(); i != e; ++i) {
170        SUnit *DefSU = DefList[i];
171        if (DefSU != SU &&
172            (Kind != SDep::Output || !MO.isDead() ||
173             !DefSU->getInstr()->registerDefIsDead(Reg)))
174          DefSU->addPred(SDep(SU, Kind, /*Latency=*/1, /*Reg=*/Reg));
175      }
176      for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
177        std::vector<SUnit *> &DefList = Defs[*Alias];
178        for (unsigned i = 0, e = DefList.size(); i != e; ++i) {
179          SUnit *DefSU = DefList[i];
180          if (DefSU != SU &&
181              (Kind != SDep::Output || !MO.isDead() ||
182               !DefSU->getInstr()->registerDefIsDead(Reg)))
183            DefSU->addPred(SDep(SU, Kind, /*Latency=*/1, /*Reg=*/ *Alias));
184        }
185      }
186
187      if (MO.isDef()) {
188        // Add any data dependencies.
189        unsigned DataLatency = SU->Latency;
190        for (unsigned i = 0, e = UseList.size(); i != e; ++i) {
191          SUnit *UseSU = UseList[i];
192          if (UseSU != SU) {
193            unsigned LDataLatency = DataLatency;
194            // Optionally add in a special extra latency for nodes that
195            // feed addresses.
196            // TODO: Do this for register aliases too.
197            if (SpecialAddressLatency != 0 && !UnitLatencies) {
198              MachineInstr *UseMI = UseSU->getInstr();
199              const TargetInstrDesc &UseTID = UseMI->getDesc();
200              int RegUseIndex = UseMI->findRegisterUseOperandIdx(Reg);
201              assert(RegUseIndex >= 0 && "UseMI doesn's use register!");
202              if ((UseTID.mayLoad() || UseTID.mayStore()) &&
203                  (unsigned)RegUseIndex < UseTID.getNumOperands() &&
204                  UseTID.OpInfo[RegUseIndex].isLookupPtrRegClass())
205                LDataLatency += SpecialAddressLatency;
206            }
207            UseSU->addPred(SDep(SU, SDep::Data, LDataLatency, Reg));
208          }
209        }
210        for (const unsigned *Alias = TRI->getAliasSet(Reg); *Alias; ++Alias) {
211          std::vector<SUnit *> &UseList = Uses[*Alias];
212          for (unsigned i = 0, e = UseList.size(); i != e; ++i) {
213            SUnit *UseSU = UseList[i];
214            if (UseSU != SU)
215              UseSU->addPred(SDep(SU, SDep::Data, DataLatency, *Alias));
216          }
217        }
218
219        // If a def is going to wrap back around to the top of the loop,
220        // backschedule it.
221        // TODO: Blocks in loops without terminators can benefit too.
222        if (!UnitLatencies && Terminator && DefList.empty()) {
223          LoopDependencies::LoopDeps::iterator I = LoopRegs.Deps.find(Reg);
224          if (I != LoopRegs.Deps.end()) {
225            const MachineOperand *UseMO = I->second.first;
226            unsigned Count = I->second.second;
227            const MachineInstr *UseMI = UseMO->getParent();
228            unsigned UseMOIdx = UseMO - &UseMI->getOperand(0);
229            const TargetInstrDesc &UseTID = UseMI->getDesc();
230            // TODO: If we knew the total depth of the region here, we could
231            // handle the case where the whole loop is inside the region but
232            // is large enough that the isScheduleHigh trick isn't needed.
233            if (UseMOIdx < UseTID.getNumOperands()) {
234              // Currently, we only support scheduling regions consisting of
235              // single basic blocks. Check to see if the instruction is in
236              // the same region by checking to see if it has the same parent.
237              if (UseMI->getParent() != MI->getParent()) {
238                unsigned Latency = SU->Latency;
239                if (UseTID.OpInfo[UseMOIdx].isLookupPtrRegClass())
240                  Latency += SpecialAddressLatency;
241                // This is a wild guess as to the portion of the latency which
242                // will be overlapped by work done outside the current
243                // scheduling region.
244                Latency -= std::min(Latency, Count);
245                // Add the artifical edge.
246                Terminator->addPred(SDep(SU, SDep::Order, Latency,
247                                         /*Reg=*/0, /*isNormalMemory=*/false,
248                                         /*isMustAlias=*/false,
249                                         /*isArtificial=*/true));
250              } else if (SpecialAddressLatency > 0 &&
251                         UseTID.OpInfo[UseMOIdx].isLookupPtrRegClass()) {
252                // The entire loop body is within the current scheduling region
253                // and the latency of this operation is assumed to be greater
254                // than the latency of the loop.
255                // TODO: Recursively mark data-edge predecessors as
256                //       isScheduleHigh too.
257                SU->isScheduleHigh = true;
258              }
259            }
260            LoopRegs.Deps.erase(I);
261          }
262        }
263
264        UseList.clear();
265        if (!MO.isDead())
266          DefList.clear();
267        DefList.push_back(SU);
268      } else {
269        UseList.push_back(SU);
270      }
271    }
272
273    // Add chain dependencies.
274    // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
275    // after stack slots are lowered to actual addresses.
276    // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
277    // produce more precise dependence information.
278    if (TID.isCall() || TID.isTerminator() || TID.hasUnmodeledSideEffects()) {
279    new_chain:
280      // This is the conservative case. Add dependencies on all memory
281      // references.
282      if (Chain)
283        Chain->addPred(SDep(SU, SDep::Order, SU->Latency));
284      Chain = SU;
285      for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
286        PendingLoads[k]->addPred(SDep(SU, SDep::Order, SU->Latency));
287      PendingLoads.clear();
288      for (std::map<const Value *, SUnit *>::iterator I = MemDefs.begin(),
289           E = MemDefs.end(); I != E; ++I) {
290        I->second->addPred(SDep(SU, SDep::Order, SU->Latency));
291        I->second = SU;
292      }
293      for (std::map<const Value *, std::vector<SUnit *> >::iterator I =
294           MemUses.begin(), E = MemUses.end(); I != E; ++I) {
295        for (unsigned i = 0, e = I->second.size(); i != e; ++i)
296          I->second[i]->addPred(SDep(SU, SDep::Order, SU->Latency));
297        I->second.clear();
298      }
299      // See if it is known to just have a single memory reference.
300      MachineInstr *ChainMI = Chain->getInstr();
301      const TargetInstrDesc &ChainTID = ChainMI->getDesc();
302      if (!ChainTID.isCall() && !ChainTID.isTerminator() &&
303          !ChainTID.hasUnmodeledSideEffects() &&
304          ChainMI->hasOneMemOperand() &&
305          !ChainMI->memoperands_begin()->isVolatile() &&
306          ChainMI->memoperands_begin()->getValue())
307        // We know that the Chain accesses one specific memory location.
308        ChainMMO = &*ChainMI->memoperands_begin();
309      else
310        // Unknown memory accesses. Assume the worst.
311        ChainMMO = 0;
312    } else if (TID.mayStore()) {
313      if (MI->hasOneMemOperand() &&
314          MI->memoperands_begin()->getValue() &&
315          !MI->memoperands_begin()->isVolatile() &&
316          isa<PseudoSourceValue>(MI->memoperands_begin()->getValue())) {
317        // A store to a specific PseudoSourceValue. Add precise dependencies.
318        const Value *V = MI->memoperands_begin()->getValue();
319        // Handle the def in MemDefs, if there is one.
320        std::map<const Value *, SUnit *>::iterator I = MemDefs.find(V);
321        if (I != MemDefs.end()) {
322          I->second->addPred(SDep(SU, SDep::Order, SU->Latency, /*Reg=*/0,
323                                  /*isNormalMemory=*/true));
324          I->second = SU;
325        } else {
326          MemDefs[V] = SU;
327        }
328        // Handle the uses in MemUses, if there are any.
329        std::map<const Value *, std::vector<SUnit *> >::iterator J =
330          MemUses.find(V);
331        if (J != MemUses.end()) {
332          for (unsigned i = 0, e = J->second.size(); i != e; ++i)
333            J->second[i]->addPred(SDep(SU, SDep::Order, SU->Latency, /*Reg=*/0,
334                                       /*isNormalMemory=*/true));
335          J->second.clear();
336        }
337        // Add a general dependence too, if needed.
338        if (Chain)
339          Chain->addPred(SDep(SU, SDep::Order, SU->Latency));
340      } else
341        // Treat all other stores conservatively.
342        goto new_chain;
343    } else if (TID.mayLoad()) {
344      if (TII->isInvariantLoad(MI)) {
345        // Invariant load, no chain dependencies needed!
346      } else if (MI->hasOneMemOperand() &&
347                 MI->memoperands_begin()->getValue() &&
348                 !MI->memoperands_begin()->isVolatile() &&
349                 isa<PseudoSourceValue>(MI->memoperands_begin()->getValue())) {
350        // A load from a specific PseudoSourceValue. Add precise dependencies.
351        const Value *V = MI->memoperands_begin()->getValue();
352        std::map<const Value *, SUnit *>::iterator I = MemDefs.find(V);
353        if (I != MemDefs.end())
354          I->second->addPred(SDep(SU, SDep::Order, SU->Latency, /*Reg=*/0,
355                                  /*isNormalMemory=*/true));
356        MemUses[V].push_back(SU);
357
358        // Add a general dependence too, if needed.
359        if (Chain && (!ChainMMO ||
360                      (ChainMMO->isStore() || ChainMMO->isVolatile())))
361          Chain->addPred(SDep(SU, SDep::Order, SU->Latency));
362      } else if (MI->hasVolatileMemoryRef()) {
363        // Treat volatile loads conservatively. Note that this includes
364        // cases where memoperand information is unavailable.
365        goto new_chain;
366      } else {
367        // A normal load. Just depend on the general chain.
368        if (Chain)
369          Chain->addPred(SDep(SU, SDep::Order, SU->Latency));
370        PendingLoads.push_back(SU);
371      }
372    }
373
374    // Add chain edges from the terminator to ensure that all the work of the
375    // block is completed before any control transfers.
376    if (Terminator && SU->Succs.empty())
377      Terminator->addPred(SDep(SU, SDep::Order, SU->Latency));
378    if (TID.isTerminator() || MI->isLabel())
379      Terminator = SU;
380  }
381}
382
383void ScheduleDAGInstrs::ComputeLatency(SUnit *SU) {
384  const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
385
386  // Compute the latency for the node.  We use the sum of the latencies for
387  // all nodes flagged together into this SUnit.
388  SU->Latency =
389    InstrItins.getLatency(SU->getInstr()->getDesc().getSchedClass());
390
391  // Simplistic target-independent heuristic: assume that loads take
392  // extra time.
393  if (InstrItins.isEmpty())
394    if (SU->getInstr()->getDesc().mayLoad())
395      SU->Latency += 2;
396}
397
398void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
399  SU->getInstr()->dump();
400}
401
402std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
403  std::string s;
404  raw_string_ostream oss(s);
405  SU->getInstr()->print(oss);
406  return oss.str();
407}
408
409// EmitSchedule - Emit the machine code in scheduled order.
410MachineBasicBlock *ScheduleDAGInstrs::EmitSchedule() {
411  // For MachineInstr-based scheduling, we're rescheduling the instructions in
412  // the block, so start by removing them from the block.
413  while (!BB->empty())
414    BB->remove(BB->begin());
415
416  for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
417    SUnit *SU = Sequence[i];
418    if (!SU) {
419      // Null SUnit* is a noop.
420      EmitNoop();
421      continue;
422    }
423
424    BB->push_back(SU->getInstr());
425  }
426
427  return BB;
428}
429