Adds cyclic critical path computation and heuristics, temporarily disabled.
[oota-llvm.git] / lib / CodeGen / ScheduleDAGInstrs.cpp
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 "misched"
16 #include "llvm/CodeGen/ScheduleDAGInstrs.h"
17 #include "llvm/ADT/MapVector.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/ValueTracking.h"
22 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineMemOperand.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/PseudoSourceValue.h"
27 #include "llvm/CodeGen/RegisterPressure.h"
28 #include "llvm/CodeGen/ScheduleDFS.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/MC/MCInstrItineraries.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/Format.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetInstrInfo.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetRegisterInfo.h"
38 #include "llvm/Target/TargetSubtargetInfo.h"
39 #include <queue>
40
41 using namespace llvm;
42
43 static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
44     cl::ZeroOrMore, cl::init(false),
45     cl::desc("Enable use of AA during MI GAD construction"));
46
47 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
48                                      const MachineLoopInfo &mli,
49                                      const MachineDominatorTree &mdt,
50                                      bool IsPostRAFlag,
51                                      LiveIntervals *lis)
52   : ScheduleDAG(mf), MLI(mli), MDT(mdt), MFI(mf.getFrameInfo()), LIS(lis),
53     IsPostRA(IsPostRAFlag), CanHandleTerminators(false), FirstDbgValue(0) {
54   assert((IsPostRA || LIS) && "PreRA scheduling requires LiveIntervals");
55   DbgValues.clear();
56   assert(!(IsPostRA && MRI.getNumVirtRegs()) &&
57          "Virtual registers must be removed prior to PostRA scheduling");
58
59   const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
60   SchedModel.init(*ST.getSchedModel(), &ST, TII);
61 }
62
63 /// getUnderlyingObjectFromInt - This is the function that does the work of
64 /// looking through basic ptrtoint+arithmetic+inttoptr sequences.
65 static const Value *getUnderlyingObjectFromInt(const Value *V) {
66   do {
67     if (const Operator *U = dyn_cast<Operator>(V)) {
68       // If we find a ptrtoint, we can transfer control back to the
69       // regular getUnderlyingObjectFromInt.
70       if (U->getOpcode() == Instruction::PtrToInt)
71         return U->getOperand(0);
72       // If we find an add of a constant, a multiplied value, or a phi, it's
73       // likely that the other operand will lead us to the base
74       // object. We don't have to worry about the case where the
75       // object address is somehow being computed by the multiply,
76       // because our callers only care when the result is an
77       // identifiable object.
78       if (U->getOpcode() != Instruction::Add ||
79           (!isa<ConstantInt>(U->getOperand(1)) &&
80            Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
81            !isa<PHINode>(U->getOperand(1))))
82         return V;
83       V = U->getOperand(0);
84     } else {
85       return V;
86     }
87     assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
88   } while (1);
89 }
90
91 /// getUnderlyingObjects - This is a wrapper around GetUnderlyingObjects
92 /// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
93 static void getUnderlyingObjects(const Value *V,
94                                  SmallVectorImpl<Value *> &Objects) {
95   SmallPtrSet<const Value*, 16> Visited;
96   SmallVector<const Value *, 4> Working(1, V);
97   do {
98     V = Working.pop_back_val();
99
100     SmallVector<Value *, 4> Objs;
101     GetUnderlyingObjects(const_cast<Value *>(V), Objs);
102
103     for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), IE = Objs.end();
104          I != IE; ++I) {
105       V = *I;
106       if (!Visited.insert(V))
107         continue;
108       if (Operator::getOpcode(V) == Instruction::IntToPtr) {
109         const Value *O =
110           getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
111         if (O->getType()->isPointerTy()) {
112           Working.push_back(O);
113           continue;
114         }
115       }
116       Objects.push_back(const_cast<Value *>(V));
117     }
118   } while (!Working.empty());
119 }
120
121 typedef SmallVector<PointerIntPair<const Value *, 1, bool>, 4>
122 UnderlyingObjectsVector;
123
124 /// getUnderlyingObjectsForInstr - If this machine instr has memory reference
125 /// information and it can be tracked to a normal reference to a known
126 /// object, return the Value for that object.
127 static void getUnderlyingObjectsForInstr(const MachineInstr *MI,
128                                          const MachineFrameInfo *MFI,
129                                          UnderlyingObjectsVector &Objects) {
130   if (!MI->hasOneMemOperand() ||
131       !(*MI->memoperands_begin())->getValue() ||
132       (*MI->memoperands_begin())->isVolatile())
133     return;
134
135   const Value *V = (*MI->memoperands_begin())->getValue();
136   if (!V)
137     return;
138
139   SmallVector<Value *, 4> Objs;
140   getUnderlyingObjects(V, Objs);
141
142   for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), IE = Objs.end();
143          I != IE; ++I) {
144     bool MayAlias = true;
145     V = *I;
146
147     if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
148       // For now, ignore PseudoSourceValues which may alias LLVM IR values
149       // because the code that uses this function has no way to cope with
150       // such aliases.
151
152       if (PSV->isAliased(MFI)) {
153         Objects.clear();
154         return;
155       }
156
157       MayAlias = PSV->mayAlias(MFI);
158     } else if (!isIdentifiedObject(V)) {
159       Objects.clear();
160       return;
161     }
162
163     Objects.push_back(UnderlyingObjectsVector::value_type(V, MayAlias));
164   }
165 }
166
167 void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
168   BB = bb;
169 }
170
171 void ScheduleDAGInstrs::finishBlock() {
172   // Subclasses should no longer refer to the old block.
173   BB = 0;
174 }
175
176 /// Initialize the DAG and common scheduler state for the current scheduling
177 /// region. This does not actually create the DAG, only clears it. The
178 /// scheduling driver may call BuildSchedGraph multiple times per scheduling
179 /// region.
180 void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
181                                     MachineBasicBlock::iterator begin,
182                                     MachineBasicBlock::iterator end,
183                                     unsigned regioninstrs) {
184   assert(bb == BB && "startBlock should set BB");
185   RegionBegin = begin;
186   RegionEnd = end;
187   NumRegionInstrs = regioninstrs;
188   MISUnitMap.clear();
189
190   ScheduleDAG::clearDAG();
191 }
192
193 /// Close the current scheduling region. Don't clear any state in case the
194 /// driver wants to refer to the previous scheduling region.
195 void ScheduleDAGInstrs::exitRegion() {
196   // Nothing to do.
197 }
198
199 /// addSchedBarrierDeps - Add dependencies from instructions in the current
200 /// list of instructions being scheduled to scheduling barrier by adding
201 /// the exit SU to the register defs and use list. This is because we want to
202 /// make sure instructions which define registers that are either used by
203 /// the terminator or are live-out are properly scheduled. This is
204 /// especially important when the definition latency of the return value(s)
205 /// are too high to be hidden by the branch or when the liveout registers
206 /// used by instructions in the fallthrough block.
207 void ScheduleDAGInstrs::addSchedBarrierDeps() {
208   MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : 0;
209   ExitSU.setInstr(ExitMI);
210   bool AllDepKnown = ExitMI &&
211     (ExitMI->isCall() || ExitMI->isBarrier());
212   if (ExitMI && AllDepKnown) {
213     // If it's a call or a barrier, add dependencies on the defs and uses of
214     // instruction.
215     for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
216       const MachineOperand &MO = ExitMI->getOperand(i);
217       if (!MO.isReg() || MO.isDef()) continue;
218       unsigned Reg = MO.getReg();
219       if (Reg == 0) continue;
220
221       if (TRI->isPhysicalRegister(Reg))
222         Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
223       else {
224         assert(!IsPostRA && "Virtual register encountered after regalloc.");
225         if (MO.readsReg()) // ignore undef operands
226           addVRegUseDeps(&ExitSU, i);
227       }
228     }
229   } else {
230     // For others, e.g. fallthrough, conditional branch, assume the exit
231     // uses all the registers that are livein to the successor blocks.
232     assert(Uses.empty() && "Uses in set before adding deps?");
233     for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
234            SE = BB->succ_end(); SI != SE; ++SI)
235       for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
236              E = (*SI)->livein_end(); I != E; ++I) {
237         unsigned Reg = *I;
238         if (!Uses.contains(Reg))
239           Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
240       }
241   }
242 }
243
244 /// MO is an operand of SU's instruction that defines a physical register. Add
245 /// data dependencies from SU to any uses of the physical register.
246 void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
247   const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
248   assert(MO.isDef() && "expect physreg def");
249
250   // Ask the target if address-backscheduling is desirable, and if so how much.
251   const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
252
253   for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
254        Alias.isValid(); ++Alias) {
255     if (!Uses.contains(*Alias))
256       continue;
257     for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
258       SUnit *UseSU = I->SU;
259       if (UseSU == SU)
260         continue;
261
262       // Adjust the dependence latency using operand def/use information,
263       // then allow the target to perform its own adjustments.
264       int UseOp = I->OpIdx;
265       MachineInstr *RegUse = 0;
266       SDep Dep;
267       if (UseOp < 0)
268         Dep = SDep(SU, SDep::Artificial);
269       else {
270         // Set the hasPhysRegDefs only for physreg defs that have a use within
271         // the scheduling region.
272         SU->hasPhysRegDefs = true;
273         Dep = SDep(SU, SDep::Data, *Alias);
274         RegUse = UseSU->getInstr();
275       }
276       Dep.setLatency(
277         SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, RegUse,
278                                          UseOp));
279
280       ST.adjustSchedDependency(SU, UseSU, Dep);
281       UseSU->addPred(Dep);
282     }
283   }
284 }
285
286 /// addPhysRegDeps - Add register dependencies (data, anti, and output) from
287 /// this SUnit to following instructions in the same scheduling region that
288 /// depend the physical register referenced at OperIdx.
289 void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
290   const MachineInstr *MI = SU->getInstr();
291   const MachineOperand &MO = MI->getOperand(OperIdx);
292
293   // Optionally add output and anti dependencies. For anti
294   // dependencies we use a latency of 0 because for a multi-issue
295   // target we want to allow the defining instruction to issue
296   // in the same cycle as the using instruction.
297   // TODO: Using a latency of 1 here for output dependencies assumes
298   //       there's no cost for reusing registers.
299   SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
300   for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
301        Alias.isValid(); ++Alias) {
302     if (!Defs.contains(*Alias))
303       continue;
304     for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
305       SUnit *DefSU = I->SU;
306       if (DefSU == &ExitSU)
307         continue;
308       if (DefSU != SU &&
309           (Kind != SDep::Output || !MO.isDead() ||
310            !DefSU->getInstr()->registerDefIsDead(*Alias))) {
311         if (Kind == SDep::Anti)
312           DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
313         else {
314           SDep Dep(SU, Kind, /*Reg=*/*Alias);
315           Dep.setLatency(
316             SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
317           DefSU->addPred(Dep);
318         }
319       }
320     }
321   }
322
323   if (!MO.isDef()) {
324     SU->hasPhysRegUses = true;
325     // Either insert a new Reg2SUnits entry with an empty SUnits list, or
326     // retrieve the existing SUnits list for this register's uses.
327     // Push this SUnit on the use list.
328     Uses.insert(PhysRegSUOper(SU, OperIdx, MO.getReg()));
329   }
330   else {
331     addPhysRegDataDeps(SU, OperIdx);
332     unsigned Reg = MO.getReg();
333
334     // clear this register's use list
335     if (Uses.contains(Reg))
336       Uses.eraseAll(Reg);
337
338     if (!MO.isDead()) {
339       Defs.eraseAll(Reg);
340     } else if (SU->isCall) {
341       // Calls will not be reordered because of chain dependencies (see
342       // below). Since call operands are dead, calls may continue to be added
343       // to the DefList making dependence checking quadratic in the size of
344       // the block. Instead, we leave only one call at the back of the
345       // DefList.
346       Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
347       Reg2SUnitsMap::iterator B = P.first;
348       Reg2SUnitsMap::iterator I = P.second;
349       for (bool isBegin = I == B; !isBegin; /* empty */) {
350         isBegin = (--I) == B;
351         if (!I->SU->isCall)
352           break;
353         I = Defs.erase(I);
354       }
355     }
356
357     // Defs are pushed in the order they are visited and never reordered.
358     Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
359   }
360 }
361
362 /// addVRegDefDeps - Add register output and data dependencies from this SUnit
363 /// to instructions that occur later in the same scheduling region if they read
364 /// from or write to the virtual register defined at OperIdx.
365 ///
366 /// TODO: Hoist loop induction variable increments. This has to be
367 /// reevaluated. Generally, IV scheduling should be done before coalescing.
368 void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
369   const MachineInstr *MI = SU->getInstr();
370   unsigned Reg = MI->getOperand(OperIdx).getReg();
371
372   // Singly defined vregs do not have output/anti dependencies.
373   // The current operand is a def, so we have at least one.
374   // Check here if there are any others...
375   if (MRI.hasOneDef(Reg))
376     return;
377
378   // Add output dependence to the next nearest def of this vreg.
379   //
380   // Unless this definition is dead, the output dependence should be
381   // transitively redundant with antidependencies from this definition's
382   // uses. We're conservative for now until we have a way to guarantee the uses
383   // are not eliminated sometime during scheduling. The output dependence edge
384   // is also useful if output latency exceeds def-use latency.
385   VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
386   if (DefI == VRegDefs.end())
387     VRegDefs.insert(VReg2SUnit(Reg, SU));
388   else {
389     SUnit *DefSU = DefI->SU;
390     if (DefSU != SU && DefSU != &ExitSU) {
391       SDep Dep(SU, SDep::Output, Reg);
392       Dep.setLatency(
393         SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
394       DefSU->addPred(Dep);
395     }
396     DefI->SU = SU;
397   }
398 }
399
400 /// addVRegUseDeps - Add a register data dependency if the instruction that
401 /// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
402 /// register antidependency from this SUnit to instructions that occur later in
403 /// the same scheduling region if they write the virtual register.
404 ///
405 /// TODO: Handle ExitSU "uses" properly.
406 void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
407   MachineInstr *MI = SU->getInstr();
408   unsigned Reg = MI->getOperand(OperIdx).getReg();
409
410   // Record this local VReg use.
411   VRegUses.insert(VReg2SUnit(Reg, SU));
412
413   // Lookup this operand's reaching definition.
414   assert(LIS && "vreg dependencies requires LiveIntervals");
415   LiveRangeQuery LRQ(LIS->getInterval(Reg), LIS->getInstructionIndex(MI));
416   VNInfo *VNI = LRQ.valueIn();
417
418   // VNI will be valid because MachineOperand::readsReg() is checked by caller.
419   assert(VNI && "No value to read by operand");
420   MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def);
421   // Phis and other noninstructions (after coalescing) have a NULL Def.
422   if (Def) {
423     SUnit *DefSU = getSUnit(Def);
424     if (DefSU) {
425       // The reaching Def lives within this scheduling region.
426       // Create a data dependence.
427       SDep dep(DefSU, SDep::Data, Reg);
428       // Adjust the dependence latency using operand def/use information, then
429       // allow the target to perform its own adjustments.
430       int DefOp = Def->findRegisterDefOperandIdx(Reg);
431       dep.setLatency(SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx));
432
433       const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
434       ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
435       SU->addPred(dep);
436     }
437   }
438
439   // Add antidependence to the following def of the vreg it uses.
440   VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
441   if (DefI != VRegDefs.end() && DefI->SU != SU)
442     DefI->SU->addPred(SDep(SU, SDep::Anti, Reg));
443 }
444
445 /// Return true if MI is an instruction we are unable to reason about
446 /// (like a call or something with unmodeled side effects).
447 static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
448   if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
449       (MI->hasOrderedMemoryRef() &&
450        (!MI->mayLoad() || !MI->isInvariantLoad(AA))))
451     return true;
452   return false;
453 }
454
455 // This MI might have either incomplete info, or known to be unsafe
456 // to deal with (i.e. volatile object).
457 static inline bool isUnsafeMemoryObject(MachineInstr *MI,
458                                         const MachineFrameInfo *MFI) {
459   if (!MI || MI->memoperands_empty())
460     return true;
461   // We purposefully do no check for hasOneMemOperand() here
462   // in hope to trigger an assert downstream in order to
463   // finish implementation.
464   if ((*MI->memoperands_begin())->isVolatile() ||
465        MI->hasUnmodeledSideEffects())
466     return true;
467   const Value *V = (*MI->memoperands_begin())->getValue();
468   if (!V)
469     return true;
470
471   SmallVector<Value *, 4> Objs;
472   getUnderlyingObjects(V, Objs);
473   for (SmallVectorImpl<Value *>::iterator I = Objs.begin(),
474          IE = Objs.end(); I != IE; ++I) {
475     V = *I;
476
477     if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
478       // Similarly to getUnderlyingObjectForInstr:
479       // For now, ignore PseudoSourceValues which may alias LLVM IR values
480       // because the code that uses this function has no way to cope with
481       // such aliases.
482       if (PSV->isAliased(MFI))
483         return true;
484     }
485
486     // Does this pointer refer to a distinct and identifiable object?
487     if (!isIdentifiedObject(V))
488       return true;
489   }
490
491   return false;
492 }
493
494 /// This returns true if the two MIs need a chain edge betwee them.
495 /// If these are not even memory operations, we still may need
496 /// chain deps between them. The question really is - could
497 /// these two MIs be reordered during scheduling from memory dependency
498 /// point of view.
499 static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
500                              MachineInstr *MIa,
501                              MachineInstr *MIb) {
502   // Cover a trivial case - no edge is need to itself.
503   if (MIa == MIb)
504     return false;
505
506   if (isUnsafeMemoryObject(MIa, MFI) || isUnsafeMemoryObject(MIb, MFI))
507     return true;
508
509   // If we are dealing with two "normal" loads, we do not need an edge
510   // between them - they could be reordered.
511   if (!MIa->mayStore() && !MIb->mayStore())
512     return false;
513
514   // To this point analysis is generic. From here on we do need AA.
515   if (!AA)
516     return true;
517
518   MachineMemOperand *MMOa = *MIa->memoperands_begin();
519   MachineMemOperand *MMOb = *MIb->memoperands_begin();
520
521   // FIXME: Need to handle multiple memory operands to support all targets.
522   if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
523     llvm_unreachable("Multiple memory operands.");
524
525   // The following interface to AA is fashioned after DAGCombiner::isAlias
526   // and operates with MachineMemOperand offset with some important
527   // assumptions:
528   //   - LLVM fundamentally assumes flat address spaces.
529   //   - MachineOperand offset can *only* result from legalization and
530   //     cannot affect queries other than the trivial case of overlap
531   //     checking.
532   //   - These offsets never wrap and never step outside
533   //     of allocated objects.
534   //   - There should never be any negative offsets here.
535   //
536   // FIXME: Modify API to hide this math from "user"
537   // FIXME: Even before we go to AA we can reason locally about some
538   // memory objects. It can save compile time, and possibly catch some
539   // corner cases not currently covered.
540
541   assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
542   assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
543
544   int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
545   int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
546   int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
547
548   AliasAnalysis::AliasResult AAResult = AA->alias(
549   AliasAnalysis::Location(MMOa->getValue(), Overlapa,
550                           MMOa->getTBAAInfo()),
551   AliasAnalysis::Location(MMOb->getValue(), Overlapb,
552                           MMOb->getTBAAInfo()));
553
554   return (AAResult != AliasAnalysis::NoAlias);
555 }
556
557 /// This recursive function iterates over chain deps of SUb looking for
558 /// "latest" node that needs a chain edge to SUa.
559 static unsigned
560 iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI,
561                  SUnit *SUa, SUnit *SUb, SUnit *ExitSU, unsigned *Depth,
562                  SmallPtrSet<const SUnit*, 16> &Visited) {
563   if (!SUa || !SUb || SUb == ExitSU)
564     return *Depth;
565
566   // Remember visited nodes.
567   if (!Visited.insert(SUb))
568       return *Depth;
569   // If there is _some_ dependency already in place, do not
570   // descend any further.
571   // TODO: Need to make sure that if that dependency got eliminated or ignored
572   // for any reason in the future, we would not violate DAG topology.
573   // Currently it does not happen, but makes an implicit assumption about
574   // future implementation.
575   //
576   // Independently, if we encounter node that is some sort of global
577   // object (like a call) we already have full set of dependencies to it
578   // and we can stop descending.
579   if (SUa->isSucc(SUb) ||
580       isGlobalMemoryObject(AA, SUb->getInstr()))
581     return *Depth;
582
583   // If we do need an edge, or we have exceeded depth budget,
584   // add that edge to the predecessors chain of SUb,
585   // and stop descending.
586   if (*Depth > 200 ||
587       MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
588     SUb->addPred(SDep(SUa, SDep::MayAliasMem));
589     return *Depth;
590   }
591   // Track current depth.
592   (*Depth)++;
593   // Iterate over chain dependencies only.
594   for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end();
595        I != E; ++I)
596     if (I->isCtrl())
597       iterateChainSucc (AA, MFI, SUa, I->getSUnit(), ExitSU, Depth, Visited);
598   return *Depth;
599 }
600
601 /// This function assumes that "downward" from SU there exist
602 /// tail/leaf of already constructed DAG. It iterates downward and
603 /// checks whether SU can be aliasing any node dominated
604 /// by it.
605 static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI,
606                             SUnit *SU, SUnit *ExitSU, std::set<SUnit *> &CheckList,
607                             unsigned LatencyToLoad) {
608   if (!SU)
609     return;
610
611   SmallPtrSet<const SUnit*, 16> Visited;
612   unsigned Depth = 0;
613
614   for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end();
615        I != IE; ++I) {
616     if (SU == *I)
617       continue;
618     if (MIsNeedChainEdge(AA, MFI, SU->getInstr(), (*I)->getInstr())) {
619       SDep Dep(SU, SDep::MayAliasMem);
620       Dep.setLatency(((*I)->getInstr()->mayLoad()) ? LatencyToLoad : 0);
621       (*I)->addPred(Dep);
622     }
623     // Now go through all the chain successors and iterate from them.
624     // Keep track of visited nodes.
625     for (SUnit::const_succ_iterator J = (*I)->Succs.begin(),
626          JE = (*I)->Succs.end(); J != JE; ++J)
627       if (J->isCtrl())
628         iterateChainSucc (AA, MFI, SU, J->getSUnit(),
629                           ExitSU, &Depth, Visited);
630   }
631 }
632
633 /// Check whether two objects need a chain edge, if so, add it
634 /// otherwise remember the rejected SU.
635 static inline
636 void addChainDependency (AliasAnalysis *AA, const MachineFrameInfo *MFI,
637                          SUnit *SUa, SUnit *SUb,
638                          std::set<SUnit *> &RejectList,
639                          unsigned TrueMemOrderLatency = 0,
640                          bool isNormalMemory = false) {
641   // If this is a false dependency,
642   // do not add the edge, but rememeber the rejected node.
643   if (!EnableAASchedMI ||
644       MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
645     SDep Dep(SUa, isNormalMemory ? SDep::MayAliasMem : SDep::Barrier);
646     Dep.setLatency(TrueMemOrderLatency);
647     SUb->addPred(Dep);
648   }
649   else {
650     // Duplicate entries should be ignored.
651     RejectList.insert(SUb);
652     DEBUG(dbgs() << "\tReject chain dep between SU("
653           << SUa->NodeNum << ") and SU("
654           << SUb->NodeNum << ")\n");
655   }
656 }
657
658 /// Create an SUnit for each real instruction, numbered in top-down toplological
659 /// order. The instruction order A < B, implies that no edge exists from B to A.
660 ///
661 /// Map each real instruction to its SUnit.
662 ///
663 /// After initSUnits, the SUnits vector cannot be resized and the scheduler may
664 /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
665 /// instead of pointers.
666 ///
667 /// MachineScheduler relies on initSUnits numbering the nodes by their order in
668 /// the original instruction list.
669 void ScheduleDAGInstrs::initSUnits() {
670   // We'll be allocating one SUnit for each real instruction in the region,
671   // which is contained within a basic block.
672   SUnits.reserve(NumRegionInstrs);
673
674   for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
675     MachineInstr *MI = I;
676     if (MI->isDebugValue())
677       continue;
678
679     SUnit *SU = newSUnit(MI);
680     MISUnitMap[MI] = SU;
681
682     SU->isCall = MI->isCall();
683     SU->isCommutable = MI->isCommutable();
684
685     // Assign the Latency field of SU using target-provided information.
686     SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
687   }
688 }
689
690 /// If RegPressure is non null, compute register pressure as a side effect. The
691 /// DAG builder is an efficient place to do it because it already visits
692 /// operands.
693 void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
694                                         RegPressureTracker *RPTracker) {
695   // Create an SUnit for each real instruction.
696   initSUnits();
697
698   // We build scheduling units by walking a block's instruction list from bottom
699   // to top.
700
701   // Remember where a generic side-effecting instruction is as we procede.
702   SUnit *BarrierChain = 0, *AliasChain = 0;
703
704   // Memory references to specific known memory locations are tracked
705   // so that they can be given more precise dependencies. We track
706   // separately the known memory locations that may alias and those
707   // that are known not to alias
708   MapVector<const Value *, SUnit *> AliasMemDefs, NonAliasMemDefs;
709   MapVector<const Value *, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
710   std::set<SUnit*> RejectMemNodes;
711
712   // Remove any stale debug info; sometimes BuildSchedGraph is called again
713   // without emitting the info from the previous call.
714   DbgValues.clear();
715   FirstDbgValue = NULL;
716
717   assert(Defs.empty() && Uses.empty() &&
718          "Only BuildGraph should update Defs/Uses");
719   Defs.setUniverse(TRI->getNumRegs());
720   Uses.setUniverse(TRI->getNumRegs());
721
722   assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
723   VRegUses.clear();
724   VRegDefs.setUniverse(MRI.getNumVirtRegs());
725   VRegUses.setUniverse(MRI.getNumVirtRegs());
726
727   // Model data dependencies between instructions being scheduled and the
728   // ExitSU.
729   addSchedBarrierDeps();
730
731   // Walk the list of instructions, from bottom moving up.
732   MachineInstr *DbgMI = NULL;
733   for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
734        MII != MIE; --MII) {
735     MachineInstr *MI = prior(MII);
736     if (MI && DbgMI) {
737       DbgValues.push_back(std::make_pair(DbgMI, MI));
738       DbgMI = NULL;
739     }
740
741     if (MI->isDebugValue()) {
742       DbgMI = MI;
743       continue;
744     }
745     if (RPTracker) {
746       RPTracker->recede();
747       assert(RPTracker->getPos() == prior(MII) && "RPTracker can't find MI");
748     }
749
750     assert((CanHandleTerminators || (!MI->isTerminator() && !MI->isLabel())) &&
751            "Cannot schedule terminators or labels!");
752
753     SUnit *SU = MISUnitMap[MI];
754     assert(SU && "No SUnit mapped to this MI");
755
756     // Add register-based dependencies (data, anti, and output).
757     bool HasVRegDef = false;
758     for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
759       const MachineOperand &MO = MI->getOperand(j);
760       if (!MO.isReg()) continue;
761       unsigned Reg = MO.getReg();
762       if (Reg == 0) continue;
763
764       if (TRI->isPhysicalRegister(Reg))
765         addPhysRegDeps(SU, j);
766       else {
767         assert(!IsPostRA && "Virtual register encountered!");
768         if (MO.isDef()) {
769           HasVRegDef = true;
770           addVRegDefDeps(SU, j);
771         }
772         else if (MO.readsReg()) // ignore undef operands
773           addVRegUseDeps(SU, j);
774       }
775     }
776     // If we haven't seen any uses in this scheduling region, create a
777     // dependence edge to ExitSU to model the live-out latency. This is required
778     // for vreg defs with no in-region use, and prefetches with no vreg def.
779     //
780     // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
781     // check currently relies on being called before adding chain deps.
782     if (SU->NumSuccs == 0 && SU->Latency > 1
783         && (HasVRegDef || MI->mayLoad())) {
784       SDep Dep(SU, SDep::Artificial);
785       Dep.setLatency(SU->Latency - 1);
786       ExitSU.addPred(Dep);
787     }
788
789     // Add chain dependencies.
790     // Chain dependencies used to enforce memory order should have
791     // latency of 0 (except for true dependency of Store followed by
792     // aliased Load... we estimate that with a single cycle of latency
793     // assuming the hardware will bypass)
794     // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
795     // after stack slots are lowered to actual addresses.
796     // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
797     // produce more precise dependence information.
798     unsigned TrueMemOrderLatency = MI->mayStore() ? 1 : 0;
799     if (isGlobalMemoryObject(AA, MI)) {
800       // Be conservative with these and add dependencies on all memory
801       // references, even those that are known to not alias.
802       for (MapVector<const Value *, SUnit *>::iterator I =
803              NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
804         I->second->addPred(SDep(SU, SDep::Barrier));
805       }
806       for (MapVector<const Value *, std::vector<SUnit *> >::iterator I =
807              NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
808         for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
809           SDep Dep(SU, SDep::Barrier);
810           Dep.setLatency(TrueMemOrderLatency);
811           I->second[i]->addPred(Dep);
812         }
813       }
814       // Add SU to the barrier chain.
815       if (BarrierChain)
816         BarrierChain->addPred(SDep(SU, SDep::Barrier));
817       BarrierChain = SU;
818       // This is a barrier event that acts as a pivotal node in the DAG,
819       // so it is safe to clear list of exposed nodes.
820       adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
821                       TrueMemOrderLatency);
822       RejectMemNodes.clear();
823       NonAliasMemDefs.clear();
824       NonAliasMemUses.clear();
825
826       // fall-through
827     new_alias_chain:
828       // Chain all possibly aliasing memory references though SU.
829       if (AliasChain) {
830         unsigned ChainLatency = 0;
831         if (AliasChain->getInstr()->mayLoad())
832           ChainLatency = TrueMemOrderLatency;
833         addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes,
834                            ChainLatency);
835       }
836       AliasChain = SU;
837       for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
838         addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
839                            TrueMemOrderLatency);
840       for (MapVector<const Value *, SUnit *>::iterator I = AliasMemDefs.begin(),
841            E = AliasMemDefs.end(); I != E; ++I)
842         addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
843       for (MapVector<const Value *, std::vector<SUnit *> >::iterator I =
844            AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
845         for (unsigned i = 0, e = I->second.size(); i != e; ++i)
846           addChainDependency(AA, MFI, SU, I->second[i], RejectMemNodes,
847                              TrueMemOrderLatency);
848       }
849       adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
850                       TrueMemOrderLatency);
851       PendingLoads.clear();
852       AliasMemDefs.clear();
853       AliasMemUses.clear();
854     } else if (MI->mayStore()) {
855       UnderlyingObjectsVector Objs;
856       getUnderlyingObjectsForInstr(MI, MFI, Objs);
857
858       if (Objs.empty()) {
859         // Treat all other stores conservatively.
860         goto new_alias_chain;
861       }
862
863       bool MayAlias = false;
864       for (UnderlyingObjectsVector::iterator K = Objs.begin(), KE = Objs.end();
865            K != KE; ++K) {
866         const Value *V = K->getPointer();
867         bool ThisMayAlias = K->getInt();
868         if (ThisMayAlias)
869           MayAlias = true;
870
871         // A store to a specific PseudoSourceValue. Add precise dependencies.
872         // Record the def in MemDefs, first adding a dep if there is
873         // an existing def.
874         MapVector<const Value *, SUnit *>::iterator I =
875           ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
876         MapVector<const Value *, SUnit *>::iterator IE =
877           ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
878         if (I != IE) {
879           addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true);
880           I->second = SU;
881         } else {
882           if (ThisMayAlias)
883             AliasMemDefs[V] = SU;
884           else
885             NonAliasMemDefs[V] = SU;
886         }
887         // Handle the uses in MemUses, if there are any.
888         MapVector<const Value *, std::vector<SUnit *> >::iterator J =
889           ((ThisMayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
890         MapVector<const Value *, std::vector<SUnit *> >::iterator JE =
891           ((ThisMayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
892         if (J != JE) {
893           for (unsigned i = 0, e = J->second.size(); i != e; ++i)
894             addChainDependency(AA, MFI, SU, J->second[i], RejectMemNodes,
895                                TrueMemOrderLatency, true);
896           J->second.clear();
897         }
898       }
899       if (MayAlias) {
900         // Add dependencies from all the PendingLoads, i.e. loads
901         // with no underlying object.
902         for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
903           addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
904                              TrueMemOrderLatency);
905         // Add dependence on alias chain, if needed.
906         if (AliasChain)
907           addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
908         // But we also should check dependent instructions for the
909         // SU in question.
910         adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
911                         TrueMemOrderLatency);
912       }
913       // Add dependence on barrier chain, if needed.
914       // There is no point to check aliasing on barrier event. Even if
915       // SU and barrier _could_ be reordered, they should not. In addition,
916       // we have lost all RejectMemNodes below barrier.
917       if (BarrierChain)
918         BarrierChain->addPred(SDep(SU, SDep::Barrier));
919
920       if (!ExitSU.isPred(SU))
921         // Push store's up a bit to avoid them getting in between cmp
922         // and branches.
923         ExitSU.addPred(SDep(SU, SDep::Artificial));
924     } else if (MI->mayLoad()) {
925       bool MayAlias = true;
926       if (MI->isInvariantLoad(AA)) {
927         // Invariant load, no chain dependencies needed!
928       } else {
929         UnderlyingObjectsVector Objs;
930         getUnderlyingObjectsForInstr(MI, MFI, Objs);
931
932         if (Objs.empty()) {
933           // A load with no underlying object. Depend on all
934           // potentially aliasing stores.
935           for (MapVector<const Value *, SUnit *>::iterator I =
936                  AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
937             addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
938
939           PendingLoads.push_back(SU);
940           MayAlias = true;
941         } else {
942           MayAlias = false;
943         }
944
945         for (UnderlyingObjectsVector::iterator
946              J = Objs.begin(), JE = Objs.end(); J != JE; ++J) {
947           const Value *V = J->getPointer();
948           bool ThisMayAlias = J->getInt();
949
950           if (ThisMayAlias)
951             MayAlias = true;
952
953           // A load from a specific PseudoSourceValue. Add precise dependencies.
954           MapVector<const Value *, SUnit *>::iterator I =
955             ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
956           MapVector<const Value *, SUnit *>::iterator IE =
957             ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
958           if (I != IE)
959             addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true);
960           if (ThisMayAlias)
961             AliasMemUses[V].push_back(SU);
962           else
963             NonAliasMemUses[V].push_back(SU);
964         }
965         if (MayAlias)
966           adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, /*Latency=*/0);
967         // Add dependencies on alias and barrier chains, if needed.
968         if (MayAlias && AliasChain)
969           addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
970         if (BarrierChain)
971           BarrierChain->addPred(SDep(SU, SDep::Barrier));
972       }
973     }
974   }
975   if (DbgMI)
976     FirstDbgValue = DbgMI;
977
978   Defs.clear();
979   Uses.clear();
980   VRegDefs.clear();
981   PendingLoads.clear();
982 }
983
984 /// Compute the max cyclic critical path through the DAG. For loops that span
985 /// basic blocks, MachineTraceMetrics should be used for this instead.
986 unsigned ScheduleDAGInstrs::computeCyclicCriticalPath() {
987   // This only applies to single block loop.
988   if (!BB->isSuccessor(BB))
989     return 0;
990
991   unsigned MaxCyclicLatency = 0;
992   // Visit each live out vreg def to find def/use pairs that cross iterations.
993   for (SUnit::const_pred_iterator
994          PI = ExitSU.Preds.begin(), PE = ExitSU.Preds.end(); PI != PE; ++PI) {
995     MachineInstr *MI = PI->getSUnit()->getInstr();
996     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
997       const MachineOperand &MO = MI->getOperand(i);
998       if (!MO.isReg() || !MO.isDef())
999         break;
1000       unsigned Reg = MO.getReg();
1001       if (!Reg || TRI->isPhysicalRegister(Reg))
1002         continue;
1003
1004       const LiveInterval &LI = LIS->getInterval(Reg);
1005       unsigned LiveOutHeight = PI->getSUnit()->getHeight();
1006       unsigned LiveOutDepth = PI->getSUnit()->getDepth() + PI->getLatency();
1007       // Visit all local users of the vreg def.
1008       for (VReg2UseMap::iterator
1009              UI = VRegUses.find(Reg); UI != VRegUses.end(); ++UI) {
1010         if (UI->SU == &ExitSU)
1011           continue;
1012
1013         // Only consider uses of the phi.
1014         LiveRangeQuery LRQ(LI, LIS->getInstructionIndex(UI->SU->getInstr()));
1015         if (!LRQ.valueIn()->isPHIDef())
1016           continue;
1017
1018         // Cheat a bit and assume that a path spanning two iterations is a
1019         // cycle, which could overestimate in strange cases. This allows cyclic
1020         // latency to be estimated as the minimum height or depth slack.
1021         unsigned CyclicLatency = 0;
1022         if (LiveOutDepth > UI->SU->getDepth())
1023           CyclicLatency = LiveOutDepth - UI->SU->getDepth();
1024         unsigned LiveInHeight = UI->SU->getHeight() + PI->getLatency();
1025         if (LiveInHeight > LiveOutHeight) {
1026           if (LiveInHeight - LiveOutHeight < CyclicLatency)
1027             CyclicLatency = LiveInHeight - LiveOutHeight;
1028         }
1029         else
1030           CyclicLatency = 0;
1031         DEBUG(dbgs() << "Cyclic Path: SU(" << PI->getSUnit()->NodeNum
1032               << ") -> SU(" << UI->SU->NodeNum << ") = "
1033               << CyclicLatency << "\n");
1034         if (CyclicLatency > MaxCyclicLatency)
1035           MaxCyclicLatency = CyclicLatency;
1036       }
1037     }
1038   }
1039   DEBUG(dbgs() << "Cyclic Critical Path: " << MaxCyclicLatency << "\n");
1040   return MaxCyclicLatency;
1041 }
1042
1043 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
1044 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1045   SU->getInstr()->dump();
1046 #endif
1047 }
1048
1049 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
1050   std::string s;
1051   raw_string_ostream oss(s);
1052   if (SU == &EntrySU)
1053     oss << "<entry>";
1054   else if (SU == &ExitSU)
1055     oss << "<exit>";
1056   else
1057     SU->getInstr()->print(oss, &TM, /*SkipOpers=*/true);
1058   return oss.str();
1059 }
1060
1061 /// Return the basic block label. It is not necessarilly unique because a block
1062 /// contains multiple scheduling regions. But it is fine for visualization.
1063 std::string ScheduleDAGInstrs::getDAGName() const {
1064   return "dag." + BB->getFullName();
1065 }
1066
1067 //===----------------------------------------------------------------------===//
1068 // SchedDFSResult Implementation
1069 //===----------------------------------------------------------------------===//
1070
1071 namespace llvm {
1072 /// \brief Internal state used to compute SchedDFSResult.
1073 class SchedDFSImpl {
1074   SchedDFSResult &R;
1075
1076   /// Join DAG nodes into equivalence classes by their subtree.
1077   IntEqClasses SubtreeClasses;
1078   /// List PredSU, SuccSU pairs that represent data edges between subtrees.
1079   std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs;
1080
1081   struct RootData {
1082     unsigned NodeID;
1083     unsigned ParentNodeID;  // Parent node (member of the parent subtree).
1084     unsigned SubInstrCount; // Instr count in this tree only, not children.
1085
1086     RootData(unsigned id): NodeID(id),
1087                            ParentNodeID(SchedDFSResult::InvalidSubtreeID),
1088                            SubInstrCount(0) {}
1089
1090     unsigned getSparseSetIndex() const { return NodeID; }
1091   };
1092
1093   SparseSet<RootData> RootSet;
1094
1095 public:
1096   SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
1097     RootSet.setUniverse(R.DFSNodeData.size());
1098   }
1099
1100   /// Return true if this node been visited by the DFS traversal.
1101   ///
1102   /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
1103   /// ID. Later, SubtreeID is updated but remains valid.
1104   bool isVisited(const SUnit *SU) const {
1105     return R.DFSNodeData[SU->NodeNum].SubtreeID
1106       != SchedDFSResult::InvalidSubtreeID;
1107   }
1108
1109   /// Initialize this node's instruction count. We don't need to flag the node
1110   /// visited until visitPostorder because the DAG cannot have cycles.
1111   void visitPreorder(const SUnit *SU) {
1112     R.DFSNodeData[SU->NodeNum].InstrCount =
1113       SU->getInstr()->isTransient() ? 0 : 1;
1114   }
1115
1116   /// Called once for each node after all predecessors are visited. Revisit this
1117   /// node's predecessors and potentially join them now that we know the ILP of
1118   /// the other predecessors.
1119   void visitPostorderNode(const SUnit *SU) {
1120     // Mark this node as the root of a subtree. It may be joined with its
1121     // successors later.
1122     R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
1123     RootData RData(SU->NodeNum);
1124     RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
1125
1126     // If any predecessors are still in their own subtree, they either cannot be
1127     // joined or are large enough to remain separate. If this parent node's
1128     // total instruction count is not greater than a child subtree by at least
1129     // the subtree limit, then try to join it now since splitting subtrees is
1130     // only useful if multiple high-pressure paths are possible.
1131     unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
1132     for (SUnit::const_pred_iterator
1133            PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1134       if (PI->getKind() != SDep::Data)
1135         continue;
1136       unsigned PredNum = PI->getSUnit()->NodeNum;
1137       if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
1138         joinPredSubtree(*PI, SU, /*CheckLimit=*/false);
1139
1140       // Either link or merge the TreeData entry from the child to the parent.
1141       if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
1142         // If the predecessor's parent is invalid, this is a tree edge and the
1143         // current node is the parent.
1144         if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
1145           RootSet[PredNum].ParentNodeID = SU->NodeNum;
1146       }
1147       else if (RootSet.count(PredNum)) {
1148         // The predecessor is not a root, but is still in the root set. This
1149         // must be the new parent that it was just joined to. Note that
1150         // RootSet[PredNum].ParentNodeID may either be invalid or may still be
1151         // set to the original parent.
1152         RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
1153         RootSet.erase(PredNum);
1154       }
1155     }
1156     RootSet[SU->NodeNum] = RData;
1157   }
1158
1159   /// Called once for each tree edge after calling visitPostOrderNode on the
1160   /// predecessor. Increment the parent node's instruction count and
1161   /// preemptively join this subtree to its parent's if it is small enough.
1162   void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
1163     R.DFSNodeData[Succ->NodeNum].InstrCount
1164       += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
1165     joinPredSubtree(PredDep, Succ);
1166   }
1167
1168   /// Add a connection for cross edges.
1169   void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
1170     ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
1171   }
1172
1173   /// Set each node's subtree ID to the representative ID and record connections
1174   /// between trees.
1175   void finalize() {
1176     SubtreeClasses.compress();
1177     R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
1178     assert(SubtreeClasses.getNumClasses() == RootSet.size()
1179            && "number of roots should match trees");
1180     for (SparseSet<RootData>::const_iterator
1181            RI = RootSet.begin(), RE = RootSet.end(); RI != RE; ++RI) {
1182       unsigned TreeID = SubtreeClasses[RI->NodeID];
1183       if (RI->ParentNodeID != SchedDFSResult::InvalidSubtreeID)
1184         R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[RI->ParentNodeID];
1185       R.DFSTreeData[TreeID].SubInstrCount = RI->SubInstrCount;
1186       // Note that SubInstrCount may be greater than InstrCount if we joined
1187       // subtrees across a cross edge. InstrCount will be attributed to the
1188       // original parent, while SubInstrCount will be attributed to the joined
1189       // parent.
1190     }
1191     R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1192     R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1193     DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
1194     for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
1195       R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
1196       DEBUG(dbgs() << "  SU(" << Idx << ") in tree "
1197             << R.DFSNodeData[Idx].SubtreeID << '\n');
1198     }
1199     for (std::vector<std::pair<const SUnit*, const SUnit*> >::const_iterator
1200            I = ConnectionPairs.begin(), E = ConnectionPairs.end();
1201          I != E; ++I) {
1202       unsigned PredTree = SubtreeClasses[I->first->NodeNum];
1203       unsigned SuccTree = SubtreeClasses[I->second->NodeNum];
1204       if (PredTree == SuccTree)
1205         continue;
1206       unsigned Depth = I->first->getDepth();
1207       addConnection(PredTree, SuccTree, Depth);
1208       addConnection(SuccTree, PredTree, Depth);
1209     }
1210   }
1211
1212 protected:
1213   /// Join the predecessor subtree with the successor that is its DFS
1214   /// parent. Apply some heuristics before joining.
1215   bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
1216                        bool CheckLimit = true) {
1217     assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
1218
1219     // Check if the predecessor is already joined.
1220     const SUnit *PredSU = PredDep.getSUnit();
1221     unsigned PredNum = PredSU->NodeNum;
1222     if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
1223       return false;
1224
1225     // Four is the magic number of successors before a node is considered a
1226     // pinch point.
1227     unsigned NumDataSucs = 0;
1228     for (SUnit::const_succ_iterator SI = PredSU->Succs.begin(),
1229            SE = PredSU->Succs.end(); SI != SE; ++SI) {
1230       if (SI->getKind() == SDep::Data) {
1231         if (++NumDataSucs >= 4)
1232           return false;
1233       }
1234     }
1235     if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
1236       return false;
1237     R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
1238     SubtreeClasses.join(Succ->NodeNum, PredNum);
1239     return true;
1240   }
1241
1242   /// Called by finalize() to record a connection between trees.
1243   void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
1244     if (!Depth)
1245       return;
1246
1247     do {
1248       SmallVectorImpl<SchedDFSResult::Connection> &Connections =
1249         R.SubtreeConnections[FromTree];
1250       for (SmallVectorImpl<SchedDFSResult::Connection>::iterator
1251              I = Connections.begin(), E = Connections.end(); I != E; ++I) {
1252         if (I->TreeID == ToTree) {
1253           I->Level = std::max(I->Level, Depth);
1254           return;
1255         }
1256       }
1257       Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
1258       FromTree = R.DFSTreeData[FromTree].ParentTreeID;
1259     } while (FromTree != SchedDFSResult::InvalidSubtreeID);
1260   }
1261 };
1262 } // namespace llvm
1263
1264 namespace {
1265 /// \brief Manage the stack used by a reverse depth-first search over the DAG.
1266 class SchedDAGReverseDFS {
1267   std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
1268 public:
1269   bool isComplete() const { return DFSStack.empty(); }
1270
1271   void follow(const SUnit *SU) {
1272     DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
1273   }
1274   void advance() { ++DFSStack.back().second; }
1275
1276   const SDep *backtrack() {
1277     DFSStack.pop_back();
1278     return DFSStack.empty() ? 0 : llvm::prior(DFSStack.back().second);
1279   }
1280
1281   const SUnit *getCurr() const { return DFSStack.back().first; }
1282
1283   SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
1284
1285   SUnit::const_pred_iterator getPredEnd() const {
1286     return getCurr()->Preds.end();
1287   }
1288 };
1289 } // anonymous
1290
1291 static bool hasDataSucc(const SUnit *SU) {
1292   for (SUnit::const_succ_iterator
1293          SI = SU->Succs.begin(), SE = SU->Succs.end(); SI != SE; ++SI) {
1294     if (SI->getKind() == SDep::Data && !SI->getSUnit()->isBoundaryNode())
1295       return true;
1296   }
1297   return false;
1298 }
1299
1300 /// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
1301 /// search from this root.
1302 void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
1303   if (!IsBottomUp)
1304     llvm_unreachable("Top-down ILP metric is unimplemnted");
1305
1306   SchedDFSImpl Impl(*this);
1307   for (ArrayRef<SUnit>::const_iterator
1308          SI = SUnits.begin(), SE = SUnits.end(); SI != SE; ++SI) {
1309     const SUnit *SU = &*SI;
1310     if (Impl.isVisited(SU) || hasDataSucc(SU))
1311       continue;
1312
1313     SchedDAGReverseDFS DFS;
1314     Impl.visitPreorder(SU);
1315     DFS.follow(SU);
1316     for (;;) {
1317       // Traverse the leftmost path as far as possible.
1318       while (DFS.getPred() != DFS.getPredEnd()) {
1319         const SDep &PredDep = *DFS.getPred();
1320         DFS.advance();
1321         // Ignore non-data edges.
1322         if (PredDep.getKind() != SDep::Data
1323             || PredDep.getSUnit()->isBoundaryNode()) {
1324           continue;
1325         }
1326         // An already visited edge is a cross edge, assuming an acyclic DAG.
1327         if (Impl.isVisited(PredDep.getSUnit())) {
1328           Impl.visitCrossEdge(PredDep, DFS.getCurr());
1329           continue;
1330         }
1331         Impl.visitPreorder(PredDep.getSUnit());
1332         DFS.follow(PredDep.getSUnit());
1333       }
1334       // Visit the top of the stack in postorder and backtrack.
1335       const SUnit *Child = DFS.getCurr();
1336       const SDep *PredDep = DFS.backtrack();
1337       Impl.visitPostorderNode(Child);
1338       if (PredDep)
1339         Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
1340       if (DFS.isComplete())
1341         break;
1342     }
1343   }
1344   Impl.finalize();
1345 }
1346
1347 /// The root of the given SubtreeID was just scheduled. For all subtrees
1348 /// connected to this tree, record the depth of the connection so that the
1349 /// nearest connected subtrees can be prioritized.
1350 void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
1351   for (SmallVectorImpl<Connection>::const_iterator
1352          I = SubtreeConnections[SubtreeID].begin(),
1353          E = SubtreeConnections[SubtreeID].end(); I != E; ++I) {
1354     SubtreeConnectLevels[I->TreeID] =
1355       std::max(SubtreeConnectLevels[I->TreeID], I->Level);
1356     DEBUG(dbgs() << "  Tree: " << I->TreeID
1357           << " @" << SubtreeConnectLevels[I->TreeID] << '\n');
1358   }
1359 }
1360
1361 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1362 void ILPValue::print(raw_ostream &OS) const {
1363   OS << InstrCount << " / " << Length << " = ";
1364   if (!Length)
1365     OS << "BADILP";
1366   else
1367     OS << format("%g", ((double)InstrCount / Length));
1368 }
1369
1370 void ILPValue::dump() const {
1371   dbgs() << *this << '\n';
1372 }
1373
1374 namespace llvm {
1375
1376 raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1377   Val.print(OS);
1378   return OS;
1379 }
1380
1381 } // namespace llvm
1382 #endif // !NDEBUG || LLVM_ENABLE_DUMP