1 //===---- ScheduleDAGInstrs.cpp - MachineInstr Rescheduling ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This implements the ScheduleDAGInstrs class, which implements re-scheduling
13 //===----------------------------------------------------------------------===//
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"
41 static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden,
42 cl::ZeroOrMore, cl::init(false),
43 cl::desc("Enable use of AA during MI GAD construction"));
45 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf,
46 const MachineLoopInfo &mli,
47 const MachineDominatorTree &mdt,
50 : ScheduleDAG(mf), MLI(mli), MDT(mdt), MFI(mf.getFrameInfo()), LIS(lis),
51 IsPostRA(IsPostRAFlag), CanHandleTerminators(false), FirstDbgValue(0) {
52 assert((IsPostRA || LIS) && "PreRA scheduling requires LiveIntervals");
54 assert(!(IsPostRA && MRI.getNumVirtRegs()) &&
55 "Virtual registers must be removed prior to PostRA scheduling");
57 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
58 SchedModel.init(*ST.getSchedModel(), &ST, TII);
61 /// getUnderlyingObjectFromInt - This is the function that does the work of
62 /// looking through basic ptrtoint+arithmetic+inttoptr sequences.
63 static const Value *getUnderlyingObjectFromInt(const Value *V) {
65 if (const Operator *U = dyn_cast<Operator>(V)) {
66 // If we find a ptrtoint, we can transfer control back to the
67 // regular getUnderlyingObjectFromInt.
68 if (U->getOpcode() == Instruction::PtrToInt)
69 return U->getOperand(0);
70 // If we find an add of a constant, a multiplied value, or a phi, it's
71 // likely that the other operand will lead us to the base
72 // object. We don't have to worry about the case where the
73 // object address is somehow being computed by the multiply,
74 // because our callers only care when the result is an
75 // identifiable object.
76 if (U->getOpcode() != Instruction::Add ||
77 (!isa<ConstantInt>(U->getOperand(1)) &&
78 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul &&
79 !isa<PHINode>(U->getOperand(1))))
85 assert(V->getType()->isIntegerTy() && "Unexpected operand type!");
89 /// getUnderlyingObjects - This is a wrapper around GetUnderlyingObjects
90 /// and adds support for basic ptrtoint+arithmetic+inttoptr sequences.
91 static void getUnderlyingObjects(const Value *V,
92 SmallVectorImpl<Value *> &Objects) {
93 SmallPtrSet<const Value*, 16> Visited;
94 SmallVector<const Value *, 4> Working(1, V);
96 V = Working.pop_back_val();
98 SmallVector<Value *, 4> Objs;
99 GetUnderlyingObjects(const_cast<Value *>(V), Objs);
101 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), IE = Objs.end();
104 if (!Visited.insert(V))
106 if (Operator::getOpcode(V) == Instruction::IntToPtr) {
108 getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0));
109 if (O->getType()->isPointerTy()) {
110 Working.push_back(O);
114 Objects.push_back(const_cast<Value *>(V));
116 } while (!Working.empty());
119 typedef SmallVector<PointerIntPair<const Value *, 1, bool>, 4>
120 UnderlyingObjectsVector;
122 /// getUnderlyingObjectsForInstr - If this machine instr has memory reference
123 /// information and it can be tracked to a normal reference to a known
124 /// object, return the Value for that object.
125 static void getUnderlyingObjectsForInstr(const MachineInstr *MI,
126 const MachineFrameInfo *MFI,
127 UnderlyingObjectsVector &Objects) {
128 if (!MI->hasOneMemOperand() ||
129 !(*MI->memoperands_begin())->getValue() ||
130 (*MI->memoperands_begin())->isVolatile())
133 const Value *V = (*MI->memoperands_begin())->getValue();
137 SmallVector<Value *, 4> Objs;
138 getUnderlyingObjects(V, Objs);
140 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(), IE = Objs.end();
142 bool MayAlias = true;
145 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
146 // For now, ignore PseudoSourceValues which may alias LLVM IR values
147 // because the code that uses this function has no way to cope with
150 if (PSV->isAliased(MFI)) {
155 MayAlias = PSV->mayAlias(MFI);
156 } else if (!isIdentifiedObject(V)) {
161 Objects.push_back(UnderlyingObjectsVector::value_type(V, MayAlias));
165 void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) {
169 void ScheduleDAGInstrs::finishBlock() {
170 // Subclasses should no longer refer to the old block.
174 /// Initialize the DAG and common scheduler state for the current scheduling
175 /// region. This does not actually create the DAG, only clears it. The
176 /// scheduling driver may call BuildSchedGraph multiple times per scheduling
178 void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb,
179 MachineBasicBlock::iterator begin,
180 MachineBasicBlock::iterator end,
181 unsigned regioninstrs) {
182 assert(bb == BB && "startBlock should set BB");
185 NumRegionInstrs = regioninstrs;
188 ScheduleDAG::clearDAG();
191 /// Close the current scheduling region. Don't clear any state in case the
192 /// driver wants to refer to the previous scheduling region.
193 void ScheduleDAGInstrs::exitRegion() {
197 /// addSchedBarrierDeps - Add dependencies from instructions in the current
198 /// list of instructions being scheduled to scheduling barrier by adding
199 /// the exit SU to the register defs and use list. This is because we want to
200 /// make sure instructions which define registers that are either used by
201 /// the terminator or are live-out are properly scheduled. This is
202 /// especially important when the definition latency of the return value(s)
203 /// are too high to be hidden by the branch or when the liveout registers
204 /// used by instructions in the fallthrough block.
205 void ScheduleDAGInstrs::addSchedBarrierDeps() {
206 MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : 0;
207 ExitSU.setInstr(ExitMI);
208 bool AllDepKnown = ExitMI &&
209 (ExitMI->isCall() || ExitMI->isBarrier());
210 if (ExitMI && AllDepKnown) {
211 // If it's a call or a barrier, add dependencies on the defs and uses of
213 for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) {
214 const MachineOperand &MO = ExitMI->getOperand(i);
215 if (!MO.isReg() || MO.isDef()) continue;
216 unsigned Reg = MO.getReg();
217 if (Reg == 0) continue;
219 if (TRI->isPhysicalRegister(Reg))
220 Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
222 assert(!IsPostRA && "Virtual register encountered after regalloc.");
223 if (MO.readsReg()) // ignore undef operands
224 addVRegUseDeps(&ExitSU, i);
228 // For others, e.g. fallthrough, conditional branch, assume the exit
229 // uses all the registers that are livein to the successor blocks.
230 assert(Uses.empty() && "Uses in set before adding deps?");
231 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
232 SE = BB->succ_end(); SI != SE; ++SI)
233 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(),
234 E = (*SI)->livein_end(); I != E; ++I) {
236 if (!Uses.contains(Reg))
237 Uses.insert(PhysRegSUOper(&ExitSU, -1, Reg));
242 /// MO is an operand of SU's instruction that defines a physical register. Add
243 /// data dependencies from SU to any uses of the physical register.
244 void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) {
245 const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx);
246 assert(MO.isDef() && "expect physreg def");
248 // Ask the target if address-backscheduling is desirable, and if so how much.
249 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
251 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
252 Alias.isValid(); ++Alias) {
253 if (!Uses.contains(*Alias))
255 for (Reg2SUnitsMap::iterator I = Uses.find(*Alias); I != Uses.end(); ++I) {
256 SUnit *UseSU = I->SU;
260 // Adjust the dependence latency using operand def/use information,
261 // then allow the target to perform its own adjustments.
262 int UseOp = I->OpIdx;
263 MachineInstr *RegUse = 0;
266 Dep = SDep(SU, SDep::Artificial);
268 // Set the hasPhysRegDefs only for physreg defs that have a use within
269 // the scheduling region.
270 SU->hasPhysRegDefs = true;
271 Dep = SDep(SU, SDep::Data, *Alias);
272 RegUse = UseSU->getInstr();
275 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, RegUse,
278 ST.adjustSchedDependency(SU, UseSU, Dep);
284 /// addPhysRegDeps - Add register dependencies (data, anti, and output) from
285 /// this SUnit to following instructions in the same scheduling region that
286 /// depend the physical register referenced at OperIdx.
287 void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) {
288 const MachineInstr *MI = SU->getInstr();
289 const MachineOperand &MO = MI->getOperand(OperIdx);
291 // Optionally add output and anti dependencies. For anti
292 // dependencies we use a latency of 0 because for a multi-issue
293 // target we want to allow the defining instruction to issue
294 // in the same cycle as the using instruction.
295 // TODO: Using a latency of 1 here for output dependencies assumes
296 // there's no cost for reusing registers.
297 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output;
298 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true);
299 Alias.isValid(); ++Alias) {
300 if (!Defs.contains(*Alias))
302 for (Reg2SUnitsMap::iterator I = Defs.find(*Alias); I != Defs.end(); ++I) {
303 SUnit *DefSU = I->SU;
304 if (DefSU == &ExitSU)
307 (Kind != SDep::Output || !MO.isDead() ||
308 !DefSU->getInstr()->registerDefIsDead(*Alias))) {
309 if (Kind == SDep::Anti)
310 DefSU->addPred(SDep(SU, Kind, /*Reg=*/*Alias));
312 SDep Dep(SU, Kind, /*Reg=*/*Alias);
314 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
322 SU->hasPhysRegUses = true;
323 // Either insert a new Reg2SUnits entry with an empty SUnits list, or
324 // retrieve the existing SUnits list for this register's uses.
325 // Push this SUnit on the use list.
326 Uses.insert(PhysRegSUOper(SU, OperIdx, MO.getReg()));
329 addPhysRegDataDeps(SU, OperIdx);
330 unsigned Reg = MO.getReg();
332 // clear this register's use list
333 if (Uses.contains(Reg))
338 } else if (SU->isCall) {
339 // Calls will not be reordered because of chain dependencies (see
340 // below). Since call operands are dead, calls may continue to be added
341 // to the DefList making dependence checking quadratic in the size of
342 // the block. Instead, we leave only one call at the back of the
344 Reg2SUnitsMap::RangePair P = Defs.equal_range(Reg);
345 Reg2SUnitsMap::iterator B = P.first;
346 Reg2SUnitsMap::iterator I = P.second;
347 for (bool isBegin = I == B; !isBegin; /* empty */) {
348 isBegin = (--I) == B;
355 // Defs are pushed in the order they are visited and never reordered.
356 Defs.insert(PhysRegSUOper(SU, OperIdx, Reg));
360 /// addVRegDefDeps - Add register output and data dependencies from this SUnit
361 /// to instructions that occur later in the same scheduling region if they read
362 /// from or write to the virtual register defined at OperIdx.
364 /// TODO: Hoist loop induction variable increments. This has to be
365 /// reevaluated. Generally, IV scheduling should be done before coalescing.
366 void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) {
367 const MachineInstr *MI = SU->getInstr();
368 unsigned Reg = MI->getOperand(OperIdx).getReg();
370 // Singly defined vregs do not have output/anti dependencies.
371 // The current operand is a def, so we have at least one.
372 // Check here if there are any others...
373 if (MRI.hasOneDef(Reg))
376 // Add output dependence to the next nearest def of this vreg.
378 // Unless this definition is dead, the output dependence should be
379 // transitively redundant with antidependencies from this definition's
380 // uses. We're conservative for now until we have a way to guarantee the uses
381 // are not eliminated sometime during scheduling. The output dependence edge
382 // is also useful if output latency exceeds def-use latency.
383 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
384 if (DefI == VRegDefs.end())
385 VRegDefs.insert(VReg2SUnit(Reg, SU));
387 SUnit *DefSU = DefI->SU;
388 if (DefSU != SU && DefSU != &ExitSU) {
389 SDep Dep(SU, SDep::Output, Reg);
391 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()));
398 /// addVRegUseDeps - Add a register data dependency if the instruction that
399 /// defines the virtual register used at OperIdx is mapped to an SUnit. Add a
400 /// register antidependency from this SUnit to instructions that occur later in
401 /// the same scheduling region if they write the virtual register.
403 /// TODO: Handle ExitSU "uses" properly.
404 void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) {
405 MachineInstr *MI = SU->getInstr();
406 unsigned Reg = MI->getOperand(OperIdx).getReg();
408 // Record this local VReg use.
409 VRegUses.insert(VReg2SUnit(Reg, SU));
411 // Lookup this operand's reaching definition.
412 assert(LIS && "vreg dependencies requires LiveIntervals");
413 LiveRangeQuery LRQ(LIS->getInterval(Reg), LIS->getInstructionIndex(MI));
414 VNInfo *VNI = LRQ.valueIn();
416 // VNI will be valid because MachineOperand::readsReg() is checked by caller.
417 assert(VNI && "No value to read by operand");
418 MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def);
419 // Phis and other noninstructions (after coalescing) have a NULL Def.
421 SUnit *DefSU = getSUnit(Def);
423 // The reaching Def lives within this scheduling region.
424 // Create a data dependence.
425 SDep dep(DefSU, SDep::Data, Reg);
426 // Adjust the dependence latency using operand def/use information, then
427 // allow the target to perform its own adjustments.
428 int DefOp = Def->findRegisterDefOperandIdx(Reg);
429 dep.setLatency(SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx));
431 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>();
432 ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep));
437 // Add antidependence to the following def of the vreg it uses.
438 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg);
439 if (DefI != VRegDefs.end() && DefI->SU != SU)
440 DefI->SU->addPred(SDep(SU, SDep::Anti, Reg));
443 /// Return true if MI is an instruction we are unable to reason about
444 /// (like a call or something with unmodeled side effects).
445 static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) {
446 if (MI->isCall() || MI->hasUnmodeledSideEffects() ||
447 (MI->hasOrderedMemoryRef() &&
448 (!MI->mayLoad() || !MI->isInvariantLoad(AA))))
453 // This MI might have either incomplete info, or known to be unsafe
454 // to deal with (i.e. volatile object).
455 static inline bool isUnsafeMemoryObject(MachineInstr *MI,
456 const MachineFrameInfo *MFI) {
457 if (!MI || MI->memoperands_empty())
459 // We purposefully do no check for hasOneMemOperand() here
460 // in hope to trigger an assert downstream in order to
461 // finish implementation.
462 if ((*MI->memoperands_begin())->isVolatile() ||
463 MI->hasUnmodeledSideEffects())
465 const Value *V = (*MI->memoperands_begin())->getValue();
469 SmallVector<Value *, 4> Objs;
470 getUnderlyingObjects(V, Objs);
471 for (SmallVectorImpl<Value *>::iterator I = Objs.begin(),
472 IE = Objs.end(); I != IE; ++I) {
475 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) {
476 // Similarly to getUnderlyingObjectForInstr:
477 // For now, ignore PseudoSourceValues which may alias LLVM IR values
478 // because the code that uses this function has no way to cope with
480 if (PSV->isAliased(MFI))
484 // Does this pointer refer to a distinct and identifiable object?
485 if (!isIdentifiedObject(V))
492 /// This returns true if the two MIs need a chain edge betwee them.
493 /// If these are not even memory operations, we still may need
494 /// chain deps between them. The question really is - could
495 /// these two MIs be reordered during scheduling from memory dependency
497 static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI,
500 // Cover a trivial case - no edge is need to itself.
504 if (isUnsafeMemoryObject(MIa, MFI) || isUnsafeMemoryObject(MIb, MFI))
507 // If we are dealing with two "normal" loads, we do not need an edge
508 // between them - they could be reordered.
509 if (!MIa->mayStore() && !MIb->mayStore())
512 // To this point analysis is generic. From here on we do need AA.
516 MachineMemOperand *MMOa = *MIa->memoperands_begin();
517 MachineMemOperand *MMOb = *MIb->memoperands_begin();
519 // FIXME: Need to handle multiple memory operands to support all targets.
520 if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand())
521 llvm_unreachable("Multiple memory operands.");
523 // The following interface to AA is fashioned after DAGCombiner::isAlias
524 // and operates with MachineMemOperand offset with some important
526 // - LLVM fundamentally assumes flat address spaces.
527 // - MachineOperand offset can *only* result from legalization and
528 // cannot affect queries other than the trivial case of overlap
530 // - These offsets never wrap and never step outside
531 // of allocated objects.
532 // - There should never be any negative offsets here.
534 // FIXME: Modify API to hide this math from "user"
535 // FIXME: Even before we go to AA we can reason locally about some
536 // memory objects. It can save compile time, and possibly catch some
537 // corner cases not currently covered.
539 assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset");
540 assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset");
542 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset());
543 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset;
544 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset;
546 AliasAnalysis::AliasResult AAResult = AA->alias(
547 AliasAnalysis::Location(MMOa->getValue(), Overlapa,
548 MMOa->getTBAAInfo()),
549 AliasAnalysis::Location(MMOb->getValue(), Overlapb,
550 MMOb->getTBAAInfo()));
552 return (AAResult != AliasAnalysis::NoAlias);
555 /// This recursive function iterates over chain deps of SUb looking for
556 /// "latest" node that needs a chain edge to SUa.
558 iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI,
559 SUnit *SUa, SUnit *SUb, SUnit *ExitSU, unsigned *Depth,
560 SmallPtrSet<const SUnit*, 16> &Visited) {
561 if (!SUa || !SUb || SUb == ExitSU)
564 // Remember visited nodes.
565 if (!Visited.insert(SUb))
567 // If there is _some_ dependency already in place, do not
568 // descend any further.
569 // TODO: Need to make sure that if that dependency got eliminated or ignored
570 // for any reason in the future, we would not violate DAG topology.
571 // Currently it does not happen, but makes an implicit assumption about
572 // future implementation.
574 // Independently, if we encounter node that is some sort of global
575 // object (like a call) we already have full set of dependencies to it
576 // and we can stop descending.
577 if (SUa->isSucc(SUb) ||
578 isGlobalMemoryObject(AA, SUb->getInstr()))
581 // If we do need an edge, or we have exceeded depth budget,
582 // add that edge to the predecessors chain of SUb,
583 // and stop descending.
585 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
586 SUb->addPred(SDep(SUa, SDep::MayAliasMem));
589 // Track current depth.
591 // Iterate over chain dependencies only.
592 for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end();
595 iterateChainSucc (AA, MFI, SUa, I->getSUnit(), ExitSU, Depth, Visited);
599 /// This function assumes that "downward" from SU there exist
600 /// tail/leaf of already constructed DAG. It iterates downward and
601 /// checks whether SU can be aliasing any node dominated
603 static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI,
604 SUnit *SU, SUnit *ExitSU, std::set<SUnit *> &CheckList,
605 unsigned LatencyToLoad) {
609 SmallPtrSet<const SUnit*, 16> Visited;
612 for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end();
616 if (MIsNeedChainEdge(AA, MFI, SU->getInstr(), (*I)->getInstr())) {
617 SDep Dep(SU, SDep::MayAliasMem);
618 Dep.setLatency(((*I)->getInstr()->mayLoad()) ? LatencyToLoad : 0);
621 // Now go through all the chain successors and iterate from them.
622 // Keep track of visited nodes.
623 for (SUnit::const_succ_iterator J = (*I)->Succs.begin(),
624 JE = (*I)->Succs.end(); J != JE; ++J)
626 iterateChainSucc (AA, MFI, SU, J->getSUnit(),
627 ExitSU, &Depth, Visited);
631 /// Check whether two objects need a chain edge, if so, add it
632 /// otherwise remember the rejected SU.
634 void addChainDependency (AliasAnalysis *AA, const MachineFrameInfo *MFI,
635 SUnit *SUa, SUnit *SUb,
636 std::set<SUnit *> &RejectList,
637 unsigned TrueMemOrderLatency = 0,
638 bool isNormalMemory = false) {
639 // If this is a false dependency,
640 // do not add the edge, but rememeber the rejected node.
641 if (!EnableAASchedMI ||
642 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) {
643 SDep Dep(SUa, isNormalMemory ? SDep::MayAliasMem : SDep::Barrier);
644 Dep.setLatency(TrueMemOrderLatency);
648 // Duplicate entries should be ignored.
649 RejectList.insert(SUb);
650 DEBUG(dbgs() << "\tReject chain dep between SU("
651 << SUa->NodeNum << ") and SU("
652 << SUb->NodeNum << ")\n");
656 /// Create an SUnit for each real instruction, numbered in top-down toplological
657 /// order. The instruction order A < B, implies that no edge exists from B to A.
659 /// Map each real instruction to its SUnit.
661 /// After initSUnits, the SUnits vector cannot be resized and the scheduler may
662 /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs
663 /// instead of pointers.
665 /// MachineScheduler relies on initSUnits numbering the nodes by their order in
666 /// the original instruction list.
667 void ScheduleDAGInstrs::initSUnits() {
668 // We'll be allocating one SUnit for each real instruction in the region,
669 // which is contained within a basic block.
670 SUnits.reserve(NumRegionInstrs);
672 for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) {
673 MachineInstr *MI = I;
674 if (MI->isDebugValue())
677 SUnit *SU = newSUnit(MI);
680 SU->isCall = MI->isCall();
681 SU->isCommutable = MI->isCommutable();
683 // Assign the Latency field of SU using target-provided information.
684 SU->Latency = SchedModel.computeInstrLatency(SU->getInstr());
688 /// If RegPressure is non null, compute register pressure as a side effect. The
689 /// DAG builder is an efficient place to do it because it already visits
691 void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA,
692 RegPressureTracker *RPTracker) {
693 // Create an SUnit for each real instruction.
696 // We build scheduling units by walking a block's instruction list from bottom
699 // Remember where a generic side-effecting instruction is as we procede.
700 SUnit *BarrierChain = 0, *AliasChain = 0;
702 // Memory references to specific known memory locations are tracked
703 // so that they can be given more precise dependencies. We track
704 // separately the known memory locations that may alias and those
705 // that are known not to alias
706 MapVector<const Value *, SUnit *> AliasMemDefs, NonAliasMemDefs;
707 MapVector<const Value *, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses;
708 std::set<SUnit*> RejectMemNodes;
710 // Remove any stale debug info; sometimes BuildSchedGraph is called again
711 // without emitting the info from the previous call.
713 FirstDbgValue = NULL;
715 assert(Defs.empty() && Uses.empty() &&
716 "Only BuildGraph should update Defs/Uses");
717 Defs.setUniverse(TRI->getNumRegs());
718 Uses.setUniverse(TRI->getNumRegs());
720 assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs");
722 VRegDefs.setUniverse(MRI.getNumVirtRegs());
723 VRegUses.setUniverse(MRI.getNumVirtRegs());
725 // Model data dependencies between instructions being scheduled and the
727 addSchedBarrierDeps();
729 // Walk the list of instructions, from bottom moving up.
730 MachineInstr *DbgMI = NULL;
731 for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin;
733 MachineInstr *MI = prior(MII);
735 DbgValues.push_back(std::make_pair(DbgMI, MI));
739 if (MI->isDebugValue()) {
745 assert(RPTracker->getPos() == prior(MII) && "RPTracker can't find MI");
748 assert((CanHandleTerminators || (!MI->isTerminator() && !MI->isLabel())) &&
749 "Cannot schedule terminators or labels!");
751 SUnit *SU = MISUnitMap[MI];
752 assert(SU && "No SUnit mapped to this MI");
754 // Add register-based dependencies (data, anti, and output).
755 bool HasVRegDef = false;
756 for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) {
757 const MachineOperand &MO = MI->getOperand(j);
758 if (!MO.isReg()) continue;
759 unsigned Reg = MO.getReg();
760 if (Reg == 0) continue;
762 if (TRI->isPhysicalRegister(Reg))
763 addPhysRegDeps(SU, j);
765 assert(!IsPostRA && "Virtual register encountered!");
768 addVRegDefDeps(SU, j);
770 else if (MO.readsReg()) // ignore undef operands
771 addVRegUseDeps(SU, j);
774 // If we haven't seen any uses in this scheduling region, create a
775 // dependence edge to ExitSU to model the live-out latency. This is required
776 // for vreg defs with no in-region use, and prefetches with no vreg def.
778 // FIXME: NumDataSuccs would be more precise than NumSuccs here. This
779 // check currently relies on being called before adding chain deps.
780 if (SU->NumSuccs == 0 && SU->Latency > 1
781 && (HasVRegDef || MI->mayLoad())) {
782 SDep Dep(SU, SDep::Artificial);
783 Dep.setLatency(SU->Latency - 1);
787 // Add chain dependencies.
788 // Chain dependencies used to enforce memory order should have
789 // latency of 0 (except for true dependency of Store followed by
790 // aliased Load... we estimate that with a single cycle of latency
791 // assuming the hardware will bypass)
792 // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable
793 // after stack slots are lowered to actual addresses.
794 // TODO: Use an AliasAnalysis and do real alias-analysis queries, and
795 // produce more precise dependence information.
796 unsigned TrueMemOrderLatency = MI->mayStore() ? 1 : 0;
797 if (isGlobalMemoryObject(AA, MI)) {
798 // Be conservative with these and add dependencies on all memory
799 // references, even those that are known to not alias.
800 for (MapVector<const Value *, SUnit *>::iterator I =
801 NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) {
802 I->second->addPred(SDep(SU, SDep::Barrier));
804 for (MapVector<const Value *, std::vector<SUnit *> >::iterator I =
805 NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) {
806 for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
807 SDep Dep(SU, SDep::Barrier);
808 Dep.setLatency(TrueMemOrderLatency);
809 I->second[i]->addPred(Dep);
812 // Add SU to the barrier chain.
814 BarrierChain->addPred(SDep(SU, SDep::Barrier));
816 // This is a barrier event that acts as a pivotal node in the DAG,
817 // so it is safe to clear list of exposed nodes.
818 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
819 TrueMemOrderLatency);
820 RejectMemNodes.clear();
821 NonAliasMemDefs.clear();
822 NonAliasMemUses.clear();
826 // Chain all possibly aliasing memory references though SU.
828 unsigned ChainLatency = 0;
829 if (AliasChain->getInstr()->mayLoad())
830 ChainLatency = TrueMemOrderLatency;
831 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes,
835 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
836 addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
837 TrueMemOrderLatency);
838 for (MapVector<const Value *, SUnit *>::iterator I = AliasMemDefs.begin(),
839 E = AliasMemDefs.end(); I != E; ++I)
840 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
841 for (MapVector<const Value *, std::vector<SUnit *> >::iterator I =
842 AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) {
843 for (unsigned i = 0, e = I->second.size(); i != e; ++i)
844 addChainDependency(AA, MFI, SU, I->second[i], RejectMemNodes,
845 TrueMemOrderLatency);
847 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
848 TrueMemOrderLatency);
849 PendingLoads.clear();
850 AliasMemDefs.clear();
851 AliasMemUses.clear();
852 } else if (MI->mayStore()) {
853 UnderlyingObjectsVector Objs;
854 getUnderlyingObjectsForInstr(MI, MFI, Objs);
857 // Treat all other stores conservatively.
858 goto new_alias_chain;
861 bool MayAlias = false;
862 for (UnderlyingObjectsVector::iterator K = Objs.begin(), KE = Objs.end();
864 const Value *V = K->getPointer();
865 bool ThisMayAlias = K->getInt();
869 // A store to a specific PseudoSourceValue. Add precise dependencies.
870 // Record the def in MemDefs, first adding a dep if there is
872 MapVector<const Value *, SUnit *>::iterator I =
873 ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
874 MapVector<const Value *, SUnit *>::iterator IE =
875 ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
877 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true);
881 AliasMemDefs[V] = SU;
883 NonAliasMemDefs[V] = SU;
885 // Handle the uses in MemUses, if there are any.
886 MapVector<const Value *, std::vector<SUnit *> >::iterator J =
887 ((ThisMayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V));
888 MapVector<const Value *, std::vector<SUnit *> >::iterator JE =
889 ((ThisMayAlias) ? AliasMemUses.end() : NonAliasMemUses.end());
891 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
892 addChainDependency(AA, MFI, SU, J->second[i], RejectMemNodes,
893 TrueMemOrderLatency, true);
898 // Add dependencies from all the PendingLoads, i.e. loads
899 // with no underlying object.
900 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k)
901 addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes,
902 TrueMemOrderLatency);
903 // Add dependence on alias chain, if needed.
905 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
906 // But we also should check dependent instructions for the
908 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes,
909 TrueMemOrderLatency);
911 // Add dependence on barrier chain, if needed.
912 // There is no point to check aliasing on barrier event. Even if
913 // SU and barrier _could_ be reordered, they should not. In addition,
914 // we have lost all RejectMemNodes below barrier.
916 BarrierChain->addPred(SDep(SU, SDep::Barrier));
918 if (!ExitSU.isPred(SU))
919 // Push store's up a bit to avoid them getting in between cmp
921 ExitSU.addPred(SDep(SU, SDep::Artificial));
922 } else if (MI->mayLoad()) {
923 bool MayAlias = true;
924 if (MI->isInvariantLoad(AA)) {
925 // Invariant load, no chain dependencies needed!
927 UnderlyingObjectsVector Objs;
928 getUnderlyingObjectsForInstr(MI, MFI, Objs);
931 // A load with no underlying object. Depend on all
932 // potentially aliasing stores.
933 for (MapVector<const Value *, SUnit *>::iterator I =
934 AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I)
935 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes);
937 PendingLoads.push_back(SU);
943 for (UnderlyingObjectsVector::iterator
944 J = Objs.begin(), JE = Objs.end(); J != JE; ++J) {
945 const Value *V = J->getPointer();
946 bool ThisMayAlias = J->getInt();
951 // A load from a specific PseudoSourceValue. Add precise dependencies.
952 MapVector<const Value *, SUnit *>::iterator I =
953 ((ThisMayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V));
954 MapVector<const Value *, SUnit *>::iterator IE =
955 ((ThisMayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end());
957 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true);
959 AliasMemUses[V].push_back(SU);
961 NonAliasMemUses[V].push_back(SU);
964 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, /*Latency=*/0);
965 // Add dependencies on alias and barrier chains, if needed.
966 if (MayAlias && AliasChain)
967 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes);
969 BarrierChain->addPred(SDep(SU, SDep::Barrier));
974 FirstDbgValue = DbgMI;
979 PendingLoads.clear();
982 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const {
983 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
984 SU->getInstr()->dump();
988 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const {
990 raw_string_ostream oss(s);
993 else if (SU == &ExitSU)
996 SU->getInstr()->print(oss, &TM, /*SkipOpers=*/true);
1000 /// Return the basic block label. It is not necessarilly unique because a block
1001 /// contains multiple scheduling regions. But it is fine for visualization.
1002 std::string ScheduleDAGInstrs::getDAGName() const {
1003 return "dag." + BB->getFullName();
1006 //===----------------------------------------------------------------------===//
1007 // SchedDFSResult Implementation
1008 //===----------------------------------------------------------------------===//
1011 /// \brief Internal state used to compute SchedDFSResult.
1012 class SchedDFSImpl {
1015 /// Join DAG nodes into equivalence classes by their subtree.
1016 IntEqClasses SubtreeClasses;
1017 /// List PredSU, SuccSU pairs that represent data edges between subtrees.
1018 std::vector<std::pair<const SUnit*, const SUnit*> > ConnectionPairs;
1022 unsigned ParentNodeID; // Parent node (member of the parent subtree).
1023 unsigned SubInstrCount; // Instr count in this tree only, not children.
1025 RootData(unsigned id): NodeID(id),
1026 ParentNodeID(SchedDFSResult::InvalidSubtreeID),
1029 unsigned getSparseSetIndex() const { return NodeID; }
1032 SparseSet<RootData> RootSet;
1035 SchedDFSImpl(SchedDFSResult &r): R(r), SubtreeClasses(R.DFSNodeData.size()) {
1036 RootSet.setUniverse(R.DFSNodeData.size());
1039 /// Return true if this node been visited by the DFS traversal.
1041 /// During visitPostorderNode the Node's SubtreeID is assigned to the Node
1042 /// ID. Later, SubtreeID is updated but remains valid.
1043 bool isVisited(const SUnit *SU) const {
1044 return R.DFSNodeData[SU->NodeNum].SubtreeID
1045 != SchedDFSResult::InvalidSubtreeID;
1048 /// Initialize this node's instruction count. We don't need to flag the node
1049 /// visited until visitPostorder because the DAG cannot have cycles.
1050 void visitPreorder(const SUnit *SU) {
1051 R.DFSNodeData[SU->NodeNum].InstrCount =
1052 SU->getInstr()->isTransient() ? 0 : 1;
1055 /// Called once for each node after all predecessors are visited. Revisit this
1056 /// node's predecessors and potentially join them now that we know the ILP of
1057 /// the other predecessors.
1058 void visitPostorderNode(const SUnit *SU) {
1059 // Mark this node as the root of a subtree. It may be joined with its
1060 // successors later.
1061 R.DFSNodeData[SU->NodeNum].SubtreeID = SU->NodeNum;
1062 RootData RData(SU->NodeNum);
1063 RData.SubInstrCount = SU->getInstr()->isTransient() ? 0 : 1;
1065 // If any predecessors are still in their own subtree, they either cannot be
1066 // joined or are large enough to remain separate. If this parent node's
1067 // total instruction count is not greater than a child subtree by at least
1068 // the subtree limit, then try to join it now since splitting subtrees is
1069 // only useful if multiple high-pressure paths are possible.
1070 unsigned InstrCount = R.DFSNodeData[SU->NodeNum].InstrCount;
1071 for (SUnit::const_pred_iterator
1072 PI = SU->Preds.begin(), PE = SU->Preds.end(); PI != PE; ++PI) {
1073 if (PI->getKind() != SDep::Data)
1075 unsigned PredNum = PI->getSUnit()->NodeNum;
1076 if ((InstrCount - R.DFSNodeData[PredNum].InstrCount) < R.SubtreeLimit)
1077 joinPredSubtree(*PI, SU, /*CheckLimit=*/false);
1079 // Either link or merge the TreeData entry from the child to the parent.
1080 if (R.DFSNodeData[PredNum].SubtreeID == PredNum) {
1081 // If the predecessor's parent is invalid, this is a tree edge and the
1082 // current node is the parent.
1083 if (RootSet[PredNum].ParentNodeID == SchedDFSResult::InvalidSubtreeID)
1084 RootSet[PredNum].ParentNodeID = SU->NodeNum;
1086 else if (RootSet.count(PredNum)) {
1087 // The predecessor is not a root, but is still in the root set. This
1088 // must be the new parent that it was just joined to. Note that
1089 // RootSet[PredNum].ParentNodeID may either be invalid or may still be
1090 // set to the original parent.
1091 RData.SubInstrCount += RootSet[PredNum].SubInstrCount;
1092 RootSet.erase(PredNum);
1095 RootSet[SU->NodeNum] = RData;
1098 /// Called once for each tree edge after calling visitPostOrderNode on the
1099 /// predecessor. Increment the parent node's instruction count and
1100 /// preemptively join this subtree to its parent's if it is small enough.
1101 void visitPostorderEdge(const SDep &PredDep, const SUnit *Succ) {
1102 R.DFSNodeData[Succ->NodeNum].InstrCount
1103 += R.DFSNodeData[PredDep.getSUnit()->NodeNum].InstrCount;
1104 joinPredSubtree(PredDep, Succ);
1107 /// Add a connection for cross edges.
1108 void visitCrossEdge(const SDep &PredDep, const SUnit *Succ) {
1109 ConnectionPairs.push_back(std::make_pair(PredDep.getSUnit(), Succ));
1112 /// Set each node's subtree ID to the representative ID and record connections
1115 SubtreeClasses.compress();
1116 R.DFSTreeData.resize(SubtreeClasses.getNumClasses());
1117 assert(SubtreeClasses.getNumClasses() == RootSet.size()
1118 && "number of roots should match trees");
1119 for (SparseSet<RootData>::const_iterator
1120 RI = RootSet.begin(), RE = RootSet.end(); RI != RE; ++RI) {
1121 unsigned TreeID = SubtreeClasses[RI->NodeID];
1122 if (RI->ParentNodeID != SchedDFSResult::InvalidSubtreeID)
1123 R.DFSTreeData[TreeID].ParentTreeID = SubtreeClasses[RI->ParentNodeID];
1124 R.DFSTreeData[TreeID].SubInstrCount = RI->SubInstrCount;
1125 // Note that SubInstrCount may be greater than InstrCount if we joined
1126 // subtrees across a cross edge. InstrCount will be attributed to the
1127 // original parent, while SubInstrCount will be attributed to the joined
1130 R.SubtreeConnections.resize(SubtreeClasses.getNumClasses());
1131 R.SubtreeConnectLevels.resize(SubtreeClasses.getNumClasses());
1132 DEBUG(dbgs() << R.getNumSubtrees() << " subtrees:\n");
1133 for (unsigned Idx = 0, End = R.DFSNodeData.size(); Idx != End; ++Idx) {
1134 R.DFSNodeData[Idx].SubtreeID = SubtreeClasses[Idx];
1135 DEBUG(dbgs() << " SU(" << Idx << ") in tree "
1136 << R.DFSNodeData[Idx].SubtreeID << '\n');
1138 for (std::vector<std::pair<const SUnit*, const SUnit*> >::const_iterator
1139 I = ConnectionPairs.begin(), E = ConnectionPairs.end();
1141 unsigned PredTree = SubtreeClasses[I->first->NodeNum];
1142 unsigned SuccTree = SubtreeClasses[I->second->NodeNum];
1143 if (PredTree == SuccTree)
1145 unsigned Depth = I->first->getDepth();
1146 addConnection(PredTree, SuccTree, Depth);
1147 addConnection(SuccTree, PredTree, Depth);
1152 /// Join the predecessor subtree with the successor that is its DFS
1153 /// parent. Apply some heuristics before joining.
1154 bool joinPredSubtree(const SDep &PredDep, const SUnit *Succ,
1155 bool CheckLimit = true) {
1156 assert(PredDep.getKind() == SDep::Data && "Subtrees are for data edges");
1158 // Check if the predecessor is already joined.
1159 const SUnit *PredSU = PredDep.getSUnit();
1160 unsigned PredNum = PredSU->NodeNum;
1161 if (R.DFSNodeData[PredNum].SubtreeID != PredNum)
1164 // Four is the magic number of successors before a node is considered a
1166 unsigned NumDataSucs = 0;
1167 for (SUnit::const_succ_iterator SI = PredSU->Succs.begin(),
1168 SE = PredSU->Succs.end(); SI != SE; ++SI) {
1169 if (SI->getKind() == SDep::Data) {
1170 if (++NumDataSucs >= 4)
1174 if (CheckLimit && R.DFSNodeData[PredNum].InstrCount > R.SubtreeLimit)
1176 R.DFSNodeData[PredNum].SubtreeID = Succ->NodeNum;
1177 SubtreeClasses.join(Succ->NodeNum, PredNum);
1181 /// Called by finalize() to record a connection between trees.
1182 void addConnection(unsigned FromTree, unsigned ToTree, unsigned Depth) {
1187 SmallVectorImpl<SchedDFSResult::Connection> &Connections =
1188 R.SubtreeConnections[FromTree];
1189 for (SmallVectorImpl<SchedDFSResult::Connection>::iterator
1190 I = Connections.begin(), E = Connections.end(); I != E; ++I) {
1191 if (I->TreeID == ToTree) {
1192 I->Level = std::max(I->Level, Depth);
1196 Connections.push_back(SchedDFSResult::Connection(ToTree, Depth));
1197 FromTree = R.DFSTreeData[FromTree].ParentTreeID;
1198 } while (FromTree != SchedDFSResult::InvalidSubtreeID);
1204 /// \brief Manage the stack used by a reverse depth-first search over the DAG.
1205 class SchedDAGReverseDFS {
1206 std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack;
1208 bool isComplete() const { return DFSStack.empty(); }
1210 void follow(const SUnit *SU) {
1211 DFSStack.push_back(std::make_pair(SU, SU->Preds.begin()));
1213 void advance() { ++DFSStack.back().second; }
1215 const SDep *backtrack() {
1216 DFSStack.pop_back();
1217 return DFSStack.empty() ? 0 : llvm::prior(DFSStack.back().second);
1220 const SUnit *getCurr() const { return DFSStack.back().first; }
1222 SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; }
1224 SUnit::const_pred_iterator getPredEnd() const {
1225 return getCurr()->Preds.end();
1230 static bool hasDataSucc(const SUnit *SU) {
1231 for (SUnit::const_succ_iterator
1232 SI = SU->Succs.begin(), SE = SU->Succs.end(); SI != SE; ++SI) {
1233 if (SI->getKind() == SDep::Data && !SI->getSUnit()->isBoundaryNode())
1239 /// Compute an ILP metric for all nodes in the subDAG reachable via depth-first
1240 /// search from this root.
1241 void SchedDFSResult::compute(ArrayRef<SUnit> SUnits) {
1243 llvm_unreachable("Top-down ILP metric is unimplemnted");
1245 SchedDFSImpl Impl(*this);
1246 for (ArrayRef<SUnit>::const_iterator
1247 SI = SUnits.begin(), SE = SUnits.end(); SI != SE; ++SI) {
1248 const SUnit *SU = &*SI;
1249 if (Impl.isVisited(SU) || hasDataSucc(SU))
1252 SchedDAGReverseDFS DFS;
1253 Impl.visitPreorder(SU);
1256 // Traverse the leftmost path as far as possible.
1257 while (DFS.getPred() != DFS.getPredEnd()) {
1258 const SDep &PredDep = *DFS.getPred();
1260 // Ignore non-data edges.
1261 if (PredDep.getKind() != SDep::Data
1262 || PredDep.getSUnit()->isBoundaryNode()) {
1265 // An already visited edge is a cross edge, assuming an acyclic DAG.
1266 if (Impl.isVisited(PredDep.getSUnit())) {
1267 Impl.visitCrossEdge(PredDep, DFS.getCurr());
1270 Impl.visitPreorder(PredDep.getSUnit());
1271 DFS.follow(PredDep.getSUnit());
1273 // Visit the top of the stack in postorder and backtrack.
1274 const SUnit *Child = DFS.getCurr();
1275 const SDep *PredDep = DFS.backtrack();
1276 Impl.visitPostorderNode(Child);
1278 Impl.visitPostorderEdge(*PredDep, DFS.getCurr());
1279 if (DFS.isComplete())
1286 /// The root of the given SubtreeID was just scheduled. For all subtrees
1287 /// connected to this tree, record the depth of the connection so that the
1288 /// nearest connected subtrees can be prioritized.
1289 void SchedDFSResult::scheduleTree(unsigned SubtreeID) {
1290 for (SmallVectorImpl<Connection>::const_iterator
1291 I = SubtreeConnections[SubtreeID].begin(),
1292 E = SubtreeConnections[SubtreeID].end(); I != E; ++I) {
1293 SubtreeConnectLevels[I->TreeID] =
1294 std::max(SubtreeConnectLevels[I->TreeID], I->Level);
1295 DEBUG(dbgs() << " Tree: " << I->TreeID
1296 << " @" << SubtreeConnectLevels[I->TreeID] << '\n');
1300 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1301 void ILPValue::print(raw_ostream &OS) const {
1302 OS << InstrCount << " / " << Length << " = ";
1306 OS << format("%g", ((double)InstrCount / Length));
1309 void ILPValue::dump() const {
1310 dbgs() << *this << '\n';
1315 raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) {
1321 #endif // !NDEBUG || LLVM_ENABLE_DUMP