xref: /llvm-project/llvm/lib/CodeGen/MachineTraceMetrics.cpp (revision 06e2a384c26dfc400470da13abdb29612aa5ef52)
1 //===- lib/CodeGen/MachineTraceMetrics.cpp --------------------------------===//
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 #include "llvm/CodeGen/MachineTraceMetrics.h"
11 #include "llvm/ADT/ArrayRef.h"
12 #include "llvm/ADT/DenseMap.h"
13 #include "llvm/ADT/Optional.h"
14 #include "llvm/ADT/PostOrderIterator.h"
15 #include "llvm/ADT/SmallPtrSet.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/SparseSet.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstr.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineOperand.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/TargetSchedule.h"
26 #include "llvm/MC/MCRegisterInfo.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/Format.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Target/TargetSubtargetInfo.h"
34 #include <algorithm>
35 #include <cassert>
36 #include <iterator>
37 #include <tuple>
38 #include <utility>
39 
40 using namespace llvm;
41 
42 #define DEBUG_TYPE "machine-trace-metrics"
43 
44 char MachineTraceMetrics::ID = 0;
45 
46 char &llvm::MachineTraceMetricsID = MachineTraceMetrics::ID;
47 
48 INITIALIZE_PASS_BEGIN(MachineTraceMetrics, DEBUG_TYPE,
49                       "Machine Trace Metrics", false, true)
50 INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
51 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
52 INITIALIZE_PASS_END(MachineTraceMetrics, DEBUG_TYPE,
53                     "Machine Trace Metrics", false, true)
54 
55 MachineTraceMetrics::MachineTraceMetrics() : MachineFunctionPass(ID) {
56   std::fill(std::begin(Ensembles), std::end(Ensembles), nullptr);
57 }
58 
59 void MachineTraceMetrics::getAnalysisUsage(AnalysisUsage &AU) const {
60   AU.setPreservesAll();
61   AU.addRequired<MachineBranchProbabilityInfo>();
62   AU.addRequired<MachineLoopInfo>();
63   MachineFunctionPass::getAnalysisUsage(AU);
64 }
65 
66 bool MachineTraceMetrics::runOnMachineFunction(MachineFunction &Func) {
67   MF = &Func;
68   const TargetSubtargetInfo &ST = MF->getSubtarget();
69   TII = ST.getInstrInfo();
70   TRI = ST.getRegisterInfo();
71   MRI = &MF->getRegInfo();
72   Loops = &getAnalysis<MachineLoopInfo>();
73   SchedModel.init(ST.getSchedModel(), &ST, TII);
74   BlockInfo.resize(MF->getNumBlockIDs());
75   ProcResourceCycles.resize(MF->getNumBlockIDs() *
76                             SchedModel.getNumProcResourceKinds());
77   return false;
78 }
79 
80 void MachineTraceMetrics::releaseMemory() {
81   MF = nullptr;
82   BlockInfo.clear();
83   for (unsigned i = 0; i != TS_NumStrategies; ++i) {
84     delete Ensembles[i];
85     Ensembles[i] = nullptr;
86   }
87 }
88 
89 //===----------------------------------------------------------------------===//
90 //                          Fixed block information
91 //===----------------------------------------------------------------------===//
92 //
93 // The number of instructions in a basic block and the CPU resources used by
94 // those instructions don't depend on any given trace strategy.
95 
96 /// Compute the resource usage in basic block MBB.
97 const MachineTraceMetrics::FixedBlockInfo*
98 MachineTraceMetrics::getResources(const MachineBasicBlock *MBB) {
99   assert(MBB && "No basic block");
100   FixedBlockInfo *FBI = &BlockInfo[MBB->getNumber()];
101   if (FBI->hasResources())
102     return FBI;
103 
104   // Compute resource usage in the block.
105   FBI->HasCalls = false;
106   unsigned InstrCount = 0;
107 
108   // Add up per-processor resource cycles as well.
109   unsigned PRKinds = SchedModel.getNumProcResourceKinds();
110   SmallVector<unsigned, 32> PRCycles(PRKinds);
111 
112   for (const auto &MI : *MBB) {
113     if (MI.isTransient())
114       continue;
115     ++InstrCount;
116     if (MI.isCall())
117       FBI->HasCalls = true;
118 
119     // Count processor resources used.
120     if (!SchedModel.hasInstrSchedModel())
121       continue;
122     const MCSchedClassDesc *SC = SchedModel.resolveSchedClass(&MI);
123     if (!SC->isValid())
124       continue;
125 
126     for (TargetSchedModel::ProcResIter
127          PI = SchedModel.getWriteProcResBegin(SC),
128          PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
129       assert(PI->ProcResourceIdx < PRKinds && "Bad processor resource kind");
130       PRCycles[PI->ProcResourceIdx] += PI->Cycles;
131     }
132   }
133   FBI->InstrCount = InstrCount;
134 
135   // Scale the resource cycles so they are comparable.
136   unsigned PROffset = MBB->getNumber() * PRKinds;
137   for (unsigned K = 0; K != PRKinds; ++K)
138     ProcResourceCycles[PROffset + K] =
139       PRCycles[K] * SchedModel.getResourceFactor(K);
140 
141   return FBI;
142 }
143 
144 ArrayRef<unsigned>
145 MachineTraceMetrics::getProcResourceCycles(unsigned MBBNum) const {
146   assert(BlockInfo[MBBNum].hasResources() &&
147          "getResources() must be called before getProcResourceCycles()");
148   unsigned PRKinds = SchedModel.getNumProcResourceKinds();
149   assert((MBBNum+1) * PRKinds <= ProcResourceCycles.size());
150   return makeArrayRef(ProcResourceCycles.data() + MBBNum * PRKinds, PRKinds);
151 }
152 
153 //===----------------------------------------------------------------------===//
154 //                         Ensemble utility functions
155 //===----------------------------------------------------------------------===//
156 
157 MachineTraceMetrics::Ensemble::Ensemble(MachineTraceMetrics *ct)
158   : MTM(*ct) {
159   BlockInfo.resize(MTM.BlockInfo.size());
160   unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
161   ProcResourceDepths.resize(MTM.BlockInfo.size() * PRKinds);
162   ProcResourceHeights.resize(MTM.BlockInfo.size() * PRKinds);
163 }
164 
165 // Virtual destructor serves as an anchor.
166 MachineTraceMetrics::Ensemble::~Ensemble() = default;
167 
168 const MachineLoop*
169 MachineTraceMetrics::Ensemble::getLoopFor(const MachineBasicBlock *MBB) const {
170   return MTM.Loops->getLoopFor(MBB);
171 }
172 
173 // Update resource-related information in the TraceBlockInfo for MBB.
174 // Only update resources related to the trace above MBB.
175 void MachineTraceMetrics::Ensemble::
176 computeDepthResources(const MachineBasicBlock *MBB) {
177   TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
178   unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
179   unsigned PROffset = MBB->getNumber() * PRKinds;
180 
181   // Compute resources from trace above. The top block is simple.
182   if (!TBI->Pred) {
183     TBI->InstrDepth = 0;
184     TBI->Head = MBB->getNumber();
185     std::fill(ProcResourceDepths.begin() + PROffset,
186               ProcResourceDepths.begin() + PROffset + PRKinds, 0);
187     return;
188   }
189 
190   // Compute from the block above. A post-order traversal ensures the
191   // predecessor is always computed first.
192   unsigned PredNum = TBI->Pred->getNumber();
193   TraceBlockInfo *PredTBI = &BlockInfo[PredNum];
194   assert(PredTBI->hasValidDepth() && "Trace above has not been computed yet");
195   const FixedBlockInfo *PredFBI = MTM.getResources(TBI->Pred);
196   TBI->InstrDepth = PredTBI->InstrDepth + PredFBI->InstrCount;
197   TBI->Head = PredTBI->Head;
198 
199   // Compute per-resource depths.
200   ArrayRef<unsigned> PredPRDepths = getProcResourceDepths(PredNum);
201   ArrayRef<unsigned> PredPRCycles = MTM.getProcResourceCycles(PredNum);
202   for (unsigned K = 0; K != PRKinds; ++K)
203     ProcResourceDepths[PROffset + K] = PredPRDepths[K] + PredPRCycles[K];
204 }
205 
206 // Update resource-related information in the TraceBlockInfo for MBB.
207 // Only update resources related to the trace below MBB.
208 void MachineTraceMetrics::Ensemble::
209 computeHeightResources(const MachineBasicBlock *MBB) {
210   TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
211   unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
212   unsigned PROffset = MBB->getNumber() * PRKinds;
213 
214   // Compute resources for the current block.
215   TBI->InstrHeight = MTM.getResources(MBB)->InstrCount;
216   ArrayRef<unsigned> PRCycles = MTM.getProcResourceCycles(MBB->getNumber());
217 
218   // The trace tail is done.
219   if (!TBI->Succ) {
220     TBI->Tail = MBB->getNumber();
221     std::copy(PRCycles.begin(), PRCycles.end(),
222               ProcResourceHeights.begin() + PROffset);
223     return;
224   }
225 
226   // Compute from the block below. A post-order traversal ensures the
227   // predecessor is always computed first.
228   unsigned SuccNum = TBI->Succ->getNumber();
229   TraceBlockInfo *SuccTBI = &BlockInfo[SuccNum];
230   assert(SuccTBI->hasValidHeight() && "Trace below has not been computed yet");
231   TBI->InstrHeight += SuccTBI->InstrHeight;
232   TBI->Tail = SuccTBI->Tail;
233 
234   // Compute per-resource heights.
235   ArrayRef<unsigned> SuccPRHeights = getProcResourceHeights(SuccNum);
236   for (unsigned K = 0; K != PRKinds; ++K)
237     ProcResourceHeights[PROffset + K] = SuccPRHeights[K] + PRCycles[K];
238 }
239 
240 // Check if depth resources for MBB are valid and return the TBI.
241 // Return NULL if the resources have been invalidated.
242 const MachineTraceMetrics::TraceBlockInfo*
243 MachineTraceMetrics::Ensemble::
244 getDepthResources(const MachineBasicBlock *MBB) const {
245   const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
246   return TBI->hasValidDepth() ? TBI : nullptr;
247 }
248 
249 // Check if height resources for MBB are valid and return the TBI.
250 // Return NULL if the resources have been invalidated.
251 const MachineTraceMetrics::TraceBlockInfo*
252 MachineTraceMetrics::Ensemble::
253 getHeightResources(const MachineBasicBlock *MBB) const {
254   const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
255   return TBI->hasValidHeight() ? TBI : nullptr;
256 }
257 
258 /// Get an array of processor resource depths for MBB. Indexed by processor
259 /// resource kind, this array contains the scaled processor resources consumed
260 /// by all blocks preceding MBB in its trace. It does not include instructions
261 /// in MBB.
262 ///
263 /// Compare TraceBlockInfo::InstrDepth.
264 ArrayRef<unsigned>
265 MachineTraceMetrics::Ensemble::
266 getProcResourceDepths(unsigned MBBNum) const {
267   unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
268   assert((MBBNum+1) * PRKinds <= ProcResourceDepths.size());
269   return makeArrayRef(ProcResourceDepths.data() + MBBNum * PRKinds, PRKinds);
270 }
271 
272 /// Get an array of processor resource heights for MBB. Indexed by processor
273 /// resource kind, this array contains the scaled processor resources consumed
274 /// by this block and all blocks following it in its trace.
275 ///
276 /// Compare TraceBlockInfo::InstrHeight.
277 ArrayRef<unsigned>
278 MachineTraceMetrics::Ensemble::
279 getProcResourceHeights(unsigned MBBNum) const {
280   unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
281   assert((MBBNum+1) * PRKinds <= ProcResourceHeights.size());
282   return makeArrayRef(ProcResourceHeights.data() + MBBNum * PRKinds, PRKinds);
283 }
284 
285 //===----------------------------------------------------------------------===//
286 //                         Trace Selection Strategies
287 //===----------------------------------------------------------------------===//
288 //
289 // A trace selection strategy is implemented as a sub-class of Ensemble. The
290 // trace through a block B is computed by two DFS traversals of the CFG
291 // starting from B. One upwards, and one downwards. During the upwards DFS,
292 // pickTracePred() is called on the post-ordered blocks. During the downwards
293 // DFS, pickTraceSucc() is called in a post-order.
294 //
295 
296 // We never allow traces that leave loops, but we do allow traces to enter
297 // nested loops. We also never allow traces to contain back-edges.
298 //
299 // This means that a loop header can never appear above the center block of a
300 // trace, except as the trace head. Below the center block, loop exiting edges
301 // are banned.
302 //
303 // Return true if an edge from the From loop to the To loop is leaving a loop.
304 // Either of To and From can be null.
305 static bool isExitingLoop(const MachineLoop *From, const MachineLoop *To) {
306   return From && !From->contains(To);
307 }
308 
309 // MinInstrCountEnsemble - Pick the trace that executes the least number of
310 // instructions.
311 namespace {
312 
313 class MinInstrCountEnsemble : public MachineTraceMetrics::Ensemble {
314   const char *getName() const override { return "MinInstr"; }
315   const MachineBasicBlock *pickTracePred(const MachineBasicBlock*) override;
316   const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*) override;
317 
318 public:
319   MinInstrCountEnsemble(MachineTraceMetrics *mtm)
320     : MachineTraceMetrics::Ensemble(mtm) {}
321 };
322 
323 } // end anonymous namespace
324 
325 // Select the preferred predecessor for MBB.
326 const MachineBasicBlock*
327 MinInstrCountEnsemble::pickTracePred(const MachineBasicBlock *MBB) {
328   if (MBB->pred_empty())
329     return nullptr;
330   const MachineLoop *CurLoop = getLoopFor(MBB);
331   // Don't leave loops, and never follow back-edges.
332   if (CurLoop && MBB == CurLoop->getHeader())
333     return nullptr;
334   unsigned CurCount = MTM.getResources(MBB)->InstrCount;
335   const MachineBasicBlock *Best = nullptr;
336   unsigned BestDepth = 0;
337   for (const MachineBasicBlock *Pred : MBB->predecessors()) {
338     const MachineTraceMetrics::TraceBlockInfo *PredTBI =
339       getDepthResources(Pred);
340     // Ignore cycles that aren't natural loops.
341     if (!PredTBI)
342       continue;
343     // Pick the predecessor that would give this block the smallest InstrDepth.
344     unsigned Depth = PredTBI->InstrDepth + CurCount;
345     if (!Best || Depth < BestDepth) {
346       Best = Pred;
347       BestDepth = Depth;
348     }
349   }
350   return Best;
351 }
352 
353 // Select the preferred successor for MBB.
354 const MachineBasicBlock*
355 MinInstrCountEnsemble::pickTraceSucc(const MachineBasicBlock *MBB) {
356   if (MBB->pred_empty())
357     return nullptr;
358   const MachineLoop *CurLoop = getLoopFor(MBB);
359   const MachineBasicBlock *Best = nullptr;
360   unsigned BestHeight = 0;
361   for (const MachineBasicBlock *Succ : MBB->successors()) {
362     // Don't consider back-edges.
363     if (CurLoop && Succ == CurLoop->getHeader())
364       continue;
365     // Don't consider successors exiting CurLoop.
366     if (isExitingLoop(CurLoop, getLoopFor(Succ)))
367       continue;
368     const MachineTraceMetrics::TraceBlockInfo *SuccTBI =
369       getHeightResources(Succ);
370     // Ignore cycles that aren't natural loops.
371     if (!SuccTBI)
372       continue;
373     // Pick the successor that would give this block the smallest InstrHeight.
374     unsigned Height = SuccTBI->InstrHeight;
375     if (!Best || Height < BestHeight) {
376       Best = Succ;
377       BestHeight = Height;
378     }
379   }
380   return Best;
381 }
382 
383 // Get an Ensemble sub-class for the requested trace strategy.
384 MachineTraceMetrics::Ensemble *
385 MachineTraceMetrics::getEnsemble(MachineTraceMetrics::Strategy strategy) {
386   assert(strategy < TS_NumStrategies && "Invalid trace strategy enum");
387   Ensemble *&E = Ensembles[strategy];
388   if (E)
389     return E;
390 
391   // Allocate new Ensemble on demand.
392   switch (strategy) {
393   case TS_MinInstrCount: return (E = new MinInstrCountEnsemble(this));
394   default: llvm_unreachable("Invalid trace strategy enum");
395   }
396 }
397 
398 void MachineTraceMetrics::invalidate(const MachineBasicBlock *MBB) {
399   DEBUG(dbgs() << "Invalidate traces through BB#" << MBB->getNumber() << '\n');
400   BlockInfo[MBB->getNumber()].invalidate();
401   for (unsigned i = 0; i != TS_NumStrategies; ++i)
402     if (Ensembles[i])
403       Ensembles[i]->invalidate(MBB);
404 }
405 
406 void MachineTraceMetrics::verifyAnalysis() const {
407   if (!MF)
408     return;
409 #ifndef NDEBUG
410   assert(BlockInfo.size() == MF->getNumBlockIDs() && "Outdated BlockInfo size");
411   for (unsigned i = 0; i != TS_NumStrategies; ++i)
412     if (Ensembles[i])
413       Ensembles[i]->verify();
414 #endif
415 }
416 
417 //===----------------------------------------------------------------------===//
418 //                               Trace building
419 //===----------------------------------------------------------------------===//
420 //
421 // Traces are built by two CFG traversals. To avoid recomputing too much, use a
422 // set abstraction that confines the search to the current loop, and doesn't
423 // revisit blocks.
424 
425 namespace {
426 
427 struct LoopBounds {
428   MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> Blocks;
429   SmallPtrSet<const MachineBasicBlock*, 8> Visited;
430   const MachineLoopInfo *Loops;
431   bool Downward = false;
432 
433   LoopBounds(MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> blocks,
434              const MachineLoopInfo *loops) : Blocks(blocks), Loops(loops) {}
435 };
436 
437 } // end anonymous namespace
438 
439 // Specialize po_iterator_storage in order to prune the post-order traversal so
440 // it is limited to the current loop and doesn't traverse the loop back edges.
441 namespace llvm {
442 
443 template<>
444 class po_iterator_storage<LoopBounds, true> {
445   LoopBounds &LB;
446 
447 public:
448   po_iterator_storage(LoopBounds &lb) : LB(lb) {}
449 
450   void finishPostorder(const MachineBasicBlock*) {}
451 
452   bool insertEdge(Optional<const MachineBasicBlock *> From,
453                   const MachineBasicBlock *To) {
454     // Skip already visited To blocks.
455     MachineTraceMetrics::TraceBlockInfo &TBI = LB.Blocks[To->getNumber()];
456     if (LB.Downward ? TBI.hasValidHeight() : TBI.hasValidDepth())
457       return false;
458     // From is null once when To is the trace center block.
459     if (From) {
460       if (const MachineLoop *FromLoop = LB.Loops->getLoopFor(*From)) {
461         // Don't follow backedges, don't leave FromLoop when going upwards.
462         if ((LB.Downward ? To : *From) == FromLoop->getHeader())
463           return false;
464         // Don't leave FromLoop.
465         if (isExitingLoop(FromLoop, LB.Loops->getLoopFor(To)))
466           return false;
467       }
468     }
469     // To is a new block. Mark the block as visited in case the CFG has cycles
470     // that MachineLoopInfo didn't recognize as a natural loop.
471     return LB.Visited.insert(To).second;
472   }
473 };
474 
475 } // end namespace llvm
476 
477 /// Compute the trace through MBB.
478 void MachineTraceMetrics::Ensemble::computeTrace(const MachineBasicBlock *MBB) {
479   DEBUG(dbgs() << "Computing " << getName() << " trace through BB#"
480                << MBB->getNumber() << '\n');
481   // Set up loop bounds for the backwards post-order traversal.
482   LoopBounds Bounds(BlockInfo, MTM.Loops);
483 
484   // Run an upwards post-order search for the trace start.
485   Bounds.Downward = false;
486   Bounds.Visited.clear();
487   for (auto I : inverse_post_order_ext(MBB, Bounds)) {
488     DEBUG(dbgs() << "  pred for BB#" << I->getNumber() << ": ");
489     TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
490     // All the predecessors have been visited, pick the preferred one.
491     TBI.Pred = pickTracePred(I);
492     DEBUG({
493       if (TBI.Pred)
494         dbgs() << "BB#" << TBI.Pred->getNumber() << '\n';
495       else
496         dbgs() << "null\n";
497     });
498     // The trace leading to I is now known, compute the depth resources.
499     computeDepthResources(I);
500   }
501 
502   // Run a downwards post-order search for the trace end.
503   Bounds.Downward = true;
504   Bounds.Visited.clear();
505   for (auto I : post_order_ext(MBB, Bounds)) {
506     DEBUG(dbgs() << "  succ for BB#" << I->getNumber() << ": ");
507     TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
508     // All the successors have been visited, pick the preferred one.
509     TBI.Succ = pickTraceSucc(I);
510     DEBUG({
511       if (TBI.Succ)
512         dbgs() << "BB#" << TBI.Succ->getNumber() << '\n';
513       else
514         dbgs() << "null\n";
515     });
516     // The trace leaving I is now known, compute the height resources.
517     computeHeightResources(I);
518   }
519 }
520 
521 /// Invalidate traces through BadMBB.
522 void
523 MachineTraceMetrics::Ensemble::invalidate(const MachineBasicBlock *BadMBB) {
524   SmallVector<const MachineBasicBlock*, 16> WorkList;
525   TraceBlockInfo &BadTBI = BlockInfo[BadMBB->getNumber()];
526 
527   // Invalidate height resources of blocks above MBB.
528   if (BadTBI.hasValidHeight()) {
529     BadTBI.invalidateHeight();
530     WorkList.push_back(BadMBB);
531     do {
532       const MachineBasicBlock *MBB = WorkList.pop_back_val();
533       DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
534             << " height.\n");
535       // Find any MBB predecessors that have MBB as their preferred successor.
536       // They are the only ones that need to be invalidated.
537       for (const MachineBasicBlock *Pred : MBB->predecessors()) {
538         TraceBlockInfo &TBI = BlockInfo[Pred->getNumber()];
539         if (!TBI.hasValidHeight())
540           continue;
541         if (TBI.Succ == MBB) {
542           TBI.invalidateHeight();
543           WorkList.push_back(Pred);
544           continue;
545         }
546         // Verify that TBI.Succ is actually a *I successor.
547         assert((!TBI.Succ || Pred->isSuccessor(TBI.Succ)) && "CFG changed");
548       }
549     } while (!WorkList.empty());
550   }
551 
552   // Invalidate depth resources of blocks below MBB.
553   if (BadTBI.hasValidDepth()) {
554     BadTBI.invalidateDepth();
555     WorkList.push_back(BadMBB);
556     do {
557       const MachineBasicBlock *MBB = WorkList.pop_back_val();
558       DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
559             << " depth.\n");
560       // Find any MBB successors that have MBB as their preferred predecessor.
561       // They are the only ones that need to be invalidated.
562       for (const MachineBasicBlock *Succ : MBB->successors()) {
563         TraceBlockInfo &TBI = BlockInfo[Succ->getNumber()];
564         if (!TBI.hasValidDepth())
565           continue;
566         if (TBI.Pred == MBB) {
567           TBI.invalidateDepth();
568           WorkList.push_back(Succ);
569           continue;
570         }
571         // Verify that TBI.Pred is actually a *I predecessor.
572         assert((!TBI.Pred || Succ->isPredecessor(TBI.Pred)) && "CFG changed");
573       }
574     } while (!WorkList.empty());
575   }
576 
577   // Clear any per-instruction data. We only have to do this for BadMBB itself
578   // because the instructions in that block may change. Other blocks may be
579   // invalidated, but their instructions will stay the same, so there is no
580   // need to erase the Cycle entries. They will be overwritten when we
581   // recompute.
582   for (const auto &I : *BadMBB)
583     Cycles.erase(&I);
584 }
585 
586 void MachineTraceMetrics::Ensemble::verify() const {
587 #ifndef NDEBUG
588   assert(BlockInfo.size() == MTM.MF->getNumBlockIDs() &&
589          "Outdated BlockInfo size");
590   for (unsigned Num = 0, e = BlockInfo.size(); Num != e; ++Num) {
591     const TraceBlockInfo &TBI = BlockInfo[Num];
592     if (TBI.hasValidDepth() && TBI.Pred) {
593       const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
594       assert(MBB->isPredecessor(TBI.Pred) && "CFG doesn't match trace");
595       assert(BlockInfo[TBI.Pred->getNumber()].hasValidDepth() &&
596              "Trace is broken, depth should have been invalidated.");
597       const MachineLoop *Loop = getLoopFor(MBB);
598       assert(!(Loop && MBB == Loop->getHeader()) && "Trace contains backedge");
599     }
600     if (TBI.hasValidHeight() && TBI.Succ) {
601       const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
602       assert(MBB->isSuccessor(TBI.Succ) && "CFG doesn't match trace");
603       assert(BlockInfo[TBI.Succ->getNumber()].hasValidHeight() &&
604              "Trace is broken, height should have been invalidated.");
605       const MachineLoop *Loop = getLoopFor(MBB);
606       const MachineLoop *SuccLoop = getLoopFor(TBI.Succ);
607       assert(!(Loop && Loop == SuccLoop && TBI.Succ == Loop->getHeader()) &&
608              "Trace contains backedge");
609     }
610   }
611 #endif
612 }
613 
614 //===----------------------------------------------------------------------===//
615 //                             Data Dependencies
616 //===----------------------------------------------------------------------===//
617 //
618 // Compute the depth and height of each instruction based on data dependencies
619 // and instruction latencies. These cycle numbers assume that the CPU can issue
620 // an infinite number of instructions per cycle as long as their dependencies
621 // are ready.
622 
623 // A data dependency is represented as a defining MI and operand numbers on the
624 // defining and using MI.
625 namespace {
626 
627 struct DataDep {
628   const MachineInstr *DefMI;
629   unsigned DefOp;
630   unsigned UseOp;
631 
632   DataDep(const MachineInstr *DefMI, unsigned DefOp, unsigned UseOp)
633     : DefMI(DefMI), DefOp(DefOp), UseOp(UseOp) {}
634 
635   /// Create a DataDep from an SSA form virtual register.
636   DataDep(const MachineRegisterInfo *MRI, unsigned VirtReg, unsigned UseOp)
637     : UseOp(UseOp) {
638     assert(TargetRegisterInfo::isVirtualRegister(VirtReg));
639     MachineRegisterInfo::def_iterator DefI = MRI->def_begin(VirtReg);
640     assert(!DefI.atEnd() && "Register has no defs");
641     DefMI = DefI->getParent();
642     DefOp = DefI.getOperandNo();
643     assert((++DefI).atEnd() && "Register has multiple defs");
644   }
645 };
646 
647 } // end anonymous namespace
648 
649 // Get the input data dependencies that must be ready before UseMI can issue.
650 // Return true if UseMI has any physreg operands.
651 static bool getDataDeps(const MachineInstr &UseMI,
652                         SmallVectorImpl<DataDep> &Deps,
653                         const MachineRegisterInfo *MRI) {
654   // Debug values should not be included in any calculations.
655   if (UseMI.isDebugValue())
656     return false;
657 
658   bool HasPhysRegs = false;
659   for (MachineInstr::const_mop_iterator I = UseMI.operands_begin(),
660        E = UseMI.operands_end(); I != E; ++I) {
661     const MachineOperand &MO = *I;
662     if (!MO.isReg())
663       continue;
664     unsigned Reg = MO.getReg();
665     if (!Reg)
666       continue;
667     if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
668       HasPhysRegs = true;
669       continue;
670     }
671     // Collect virtual register reads.
672     if (MO.readsReg())
673       Deps.push_back(DataDep(MRI, Reg, UseMI.getOperandNo(I)));
674   }
675   return HasPhysRegs;
676 }
677 
678 // Get the input data dependencies of a PHI instruction, using Pred as the
679 // preferred predecessor.
680 // This will add at most one dependency to Deps.
681 static void getPHIDeps(const MachineInstr &UseMI,
682                        SmallVectorImpl<DataDep> &Deps,
683                        const MachineBasicBlock *Pred,
684                        const MachineRegisterInfo *MRI) {
685   // No predecessor at the beginning of a trace. Ignore dependencies.
686   if (!Pred)
687     return;
688   assert(UseMI.isPHI() && UseMI.getNumOperands() % 2 && "Bad PHI");
689   for (unsigned i = 1; i != UseMI.getNumOperands(); i += 2) {
690     if (UseMI.getOperand(i + 1).getMBB() == Pred) {
691       unsigned Reg = UseMI.getOperand(i).getReg();
692       Deps.push_back(DataDep(MRI, Reg, i));
693       return;
694     }
695   }
696 }
697 
698 // Identify physreg dependencies for UseMI, and update the live regunit
699 // tracking set when scanning instructions downwards.
700 static void updatePhysDepsDownwards(const MachineInstr *UseMI,
701                                     SmallVectorImpl<DataDep> &Deps,
702                                     SparseSet<LiveRegUnit> &RegUnits,
703                                     const TargetRegisterInfo *TRI) {
704   SmallVector<unsigned, 8> Kills;
705   SmallVector<unsigned, 8> LiveDefOps;
706 
707   for (MachineInstr::const_mop_iterator MI = UseMI->operands_begin(),
708        ME = UseMI->operands_end(); MI != ME; ++MI) {
709     const MachineOperand &MO = *MI;
710     if (!MO.isReg())
711       continue;
712     unsigned Reg = MO.getReg();
713     if (!TargetRegisterInfo::isPhysicalRegister(Reg))
714       continue;
715     // Track live defs and kills for updating RegUnits.
716     if (MO.isDef()) {
717       if (MO.isDead())
718         Kills.push_back(Reg);
719       else
720         LiveDefOps.push_back(UseMI->getOperandNo(MI));
721     } else if (MO.isKill())
722       Kills.push_back(Reg);
723     // Identify dependencies.
724     if (!MO.readsReg())
725       continue;
726     for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
727       SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
728       if (I == RegUnits.end())
729         continue;
730       Deps.push_back(DataDep(I->MI, I->Op, UseMI->getOperandNo(MI)));
731       break;
732     }
733   }
734 
735   // Update RegUnits to reflect live registers after UseMI.
736   // First kills.
737   for (unsigned Kill : Kills)
738     for (MCRegUnitIterator Units(Kill, TRI); Units.isValid(); ++Units)
739       RegUnits.erase(*Units);
740 
741   // Second, live defs.
742   for (unsigned DefOp : LiveDefOps) {
743     for (MCRegUnitIterator Units(UseMI->getOperand(DefOp).getReg(), TRI);
744          Units.isValid(); ++Units) {
745       LiveRegUnit &LRU = RegUnits[*Units];
746       LRU.MI = UseMI;
747       LRU.Op = DefOp;
748     }
749   }
750 }
751 
752 /// The length of the critical path through a trace is the maximum of two path
753 /// lengths:
754 ///
755 /// 1. The maximum height+depth over all instructions in the trace center block.
756 ///
757 /// 2. The longest cross-block dependency chain. For small blocks, it is
758 ///    possible that the critical path through the trace doesn't include any
759 ///    instructions in the block.
760 ///
761 /// This function computes the second number from the live-in list of the
762 /// center block.
763 unsigned MachineTraceMetrics::Ensemble::
764 computeCrossBlockCriticalPath(const TraceBlockInfo &TBI) {
765   assert(TBI.HasValidInstrDepths && "Missing depth info");
766   assert(TBI.HasValidInstrHeights && "Missing height info");
767   unsigned MaxLen = 0;
768   for (const LiveInReg &LIR : TBI.LiveIns) {
769     if (!TargetRegisterInfo::isVirtualRegister(LIR.Reg))
770       continue;
771     const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
772     // Ignore dependencies outside the current trace.
773     const TraceBlockInfo &DefTBI = BlockInfo[DefMI->getParent()->getNumber()];
774     if (!DefTBI.isUsefulDominator(TBI))
775       continue;
776     unsigned Len = LIR.Height + Cycles[DefMI].Depth;
777     MaxLen = std::max(MaxLen, Len);
778   }
779   return MaxLen;
780 }
781 
782 void MachineTraceMetrics::Ensemble::
783 updateDepth(MachineTraceMetrics::TraceBlockInfo &TBI, const MachineInstr &UseMI,
784             SparseSet<LiveRegUnit> &RegUnits) {
785   SmallVector<DataDep, 8> Deps;
786   // Collect all data dependencies.
787   if (UseMI.isPHI())
788     getPHIDeps(UseMI, Deps, TBI.Pred, MTM.MRI);
789   else if (getDataDeps(UseMI, Deps, MTM.MRI))
790     updatePhysDepsDownwards(&UseMI, Deps, RegUnits, MTM.TRI);
791 
792   // Filter and process dependencies, computing the earliest issue cycle.
793   unsigned Cycle = 0;
794   for (const DataDep &Dep : Deps) {
795     const TraceBlockInfo&DepTBI =
796       BlockInfo[Dep.DefMI->getParent()->getNumber()];
797     // Ignore dependencies from outside the current trace.
798     if (!DepTBI.isUsefulDominator(TBI))
799       continue;
800     assert(DepTBI.HasValidInstrDepths && "Inconsistent dependency");
801     unsigned DepCycle = Cycles.lookup(Dep.DefMI).Depth;
802     // Add latency if DefMI is a real instruction. Transients get latency 0.
803     if (!Dep.DefMI->isTransient())
804       DepCycle += MTM.SchedModel
805         .computeOperandLatency(Dep.DefMI, Dep.DefOp, &UseMI, Dep.UseOp);
806     Cycle = std::max(Cycle, DepCycle);
807   }
808   // Remember the instruction depth.
809   InstrCycles &MICycles = Cycles[&UseMI];
810   MICycles.Depth = Cycle;
811 
812   if (TBI.HasValidInstrHeights) {
813     // Update critical path length.
814     TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Height);
815     DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << UseMI);
816   } else {
817     DEBUG(dbgs() << Cycle << '\t' << UseMI);
818   }
819 }
820 
821 void MachineTraceMetrics::Ensemble::
822 updateDepth(const MachineBasicBlock *MBB, const MachineInstr &UseMI,
823             SparseSet<LiveRegUnit> &RegUnits) {
824   updateDepth(BlockInfo[MBB->getNumber()], UseMI, RegUnits);
825 }
826 
827 /// Compute instruction depths for all instructions above or in MBB in its
828 /// trace. This assumes that the trace through MBB has already been computed.
829 void MachineTraceMetrics::Ensemble::
830 computeInstrDepths(const MachineBasicBlock *MBB) {
831   // The top of the trace may already be computed, and HasValidInstrDepths
832   // implies Head->HasValidInstrDepths, so we only need to start from the first
833   // block in the trace that needs to be recomputed.
834   SmallVector<const MachineBasicBlock*, 8> Stack;
835   do {
836     TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
837     assert(TBI.hasValidDepth() && "Incomplete trace");
838     if (TBI.HasValidInstrDepths)
839       break;
840     Stack.push_back(MBB);
841     MBB = TBI.Pred;
842   } while (MBB);
843 
844   // FIXME: If MBB is non-null at this point, it is the last pre-computed block
845   // in the trace. We should track any live-out physregs that were defined in
846   // the trace. This is quite rare in SSA form, typically created by CSE
847   // hoisting a compare.
848   SparseSet<LiveRegUnit> RegUnits;
849   RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
850 
851   // Go through trace blocks in top-down order, stopping after the center block.
852   while (!Stack.empty()) {
853     MBB = Stack.pop_back_val();
854     DEBUG(dbgs() << "\nDepths for BB#" << MBB->getNumber() << ":\n");
855     TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
856     TBI.HasValidInstrDepths = true;
857     TBI.CriticalPath = 0;
858 
859     // Print out resource depths here as well.
860     DEBUG({
861       dbgs() << format("%7u Instructions\n", TBI.InstrDepth);
862       ArrayRef<unsigned> PRDepths = getProcResourceDepths(MBB->getNumber());
863       for (unsigned K = 0; K != PRDepths.size(); ++K)
864         if (PRDepths[K]) {
865           unsigned Factor = MTM.SchedModel.getResourceFactor(K);
866           dbgs() << format("%6uc @ ", MTM.getCycles(PRDepths[K]))
867                  << MTM.SchedModel.getProcResource(K)->Name << " ("
868                  << PRDepths[K]/Factor << " ops x" << Factor << ")\n";
869         }
870     });
871 
872     // Also compute the critical path length through MBB when possible.
873     if (TBI.HasValidInstrHeights)
874       TBI.CriticalPath = computeCrossBlockCriticalPath(TBI);
875 
876     for (const auto &UseMI : *MBB) {
877       updateDepth(TBI, UseMI, RegUnits);
878     }
879   }
880 }
881 
882 // Identify physreg dependencies for MI when scanning instructions upwards.
883 // Return the issue height of MI after considering any live regunits.
884 // Height is the issue height computed from virtual register dependencies alone.
885 static unsigned updatePhysDepsUpwards(const MachineInstr &MI, unsigned Height,
886                                       SparseSet<LiveRegUnit> &RegUnits,
887                                       const TargetSchedModel &SchedModel,
888                                       const TargetInstrInfo *TII,
889                                       const TargetRegisterInfo *TRI) {
890   SmallVector<unsigned, 8> ReadOps;
891 
892   for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(),
893                                         MOE = MI.operands_end();
894        MOI != MOE; ++MOI) {
895     const MachineOperand &MO = *MOI;
896     if (!MO.isReg())
897       continue;
898     unsigned Reg = MO.getReg();
899     if (!TargetRegisterInfo::isPhysicalRegister(Reg))
900       continue;
901     if (MO.readsReg())
902       ReadOps.push_back(MI.getOperandNo(MOI));
903     if (!MO.isDef())
904       continue;
905     // This is a def of Reg. Remove corresponding entries from RegUnits, and
906     // update MI Height to consider the physreg dependencies.
907     for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
908       SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
909       if (I == RegUnits.end())
910         continue;
911       unsigned DepHeight = I->Cycle;
912       if (!MI.isTransient()) {
913         // We may not know the UseMI of this dependency, if it came from the
914         // live-in list. SchedModel can handle a NULL UseMI.
915         DepHeight += SchedModel.computeOperandLatency(&MI, MI.getOperandNo(MOI),
916                                                       I->MI, I->Op);
917       }
918       Height = std::max(Height, DepHeight);
919       // This regunit is dead above MI.
920       RegUnits.erase(I);
921     }
922   }
923 
924   // Now we know the height of MI. Update any regunits read.
925   for (unsigned i = 0, e = ReadOps.size(); i != e; ++i) {
926     unsigned Reg = MI.getOperand(ReadOps[i]).getReg();
927     for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
928       LiveRegUnit &LRU = RegUnits[*Units];
929       // Set the height to the highest reader of the unit.
930       if (LRU.Cycle <= Height && LRU.MI != &MI) {
931         LRU.Cycle = Height;
932         LRU.MI = &MI;
933         LRU.Op = ReadOps[i];
934       }
935     }
936   }
937 
938   return Height;
939 }
940 
941 using MIHeightMap = DenseMap<const MachineInstr *, unsigned>;
942 
943 // Push the height of DefMI upwards if required to match UseMI.
944 // Return true if this is the first time DefMI was seen.
945 static bool pushDepHeight(const DataDep &Dep, const MachineInstr &UseMI,
946                           unsigned UseHeight, MIHeightMap &Heights,
947                           const TargetSchedModel &SchedModel,
948                           const TargetInstrInfo *TII) {
949   // Adjust height by Dep.DefMI latency.
950   if (!Dep.DefMI->isTransient())
951     UseHeight += SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp, &UseMI,
952                                                   Dep.UseOp);
953 
954   // Update Heights[DefMI] to be the maximum height seen.
955   MIHeightMap::iterator I;
956   bool New;
957   std::tie(I, New) = Heights.insert(std::make_pair(Dep.DefMI, UseHeight));
958   if (New)
959     return true;
960 
961   // DefMI has been pushed before. Give it the max height.
962   if (I->second < UseHeight)
963     I->second = UseHeight;
964   return false;
965 }
966 
967 /// Assuming that the virtual register defined by DefMI:DefOp was used by
968 /// Trace.back(), add it to the live-in lists of all the blocks in Trace. Stop
969 /// when reaching the block that contains DefMI.
970 void MachineTraceMetrics::Ensemble::
971 addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
972            ArrayRef<const MachineBasicBlock*> Trace) {
973   assert(!Trace.empty() && "Trace should contain at least one block");
974   unsigned Reg = DefMI->getOperand(DefOp).getReg();
975   assert(TargetRegisterInfo::isVirtualRegister(Reg));
976   const MachineBasicBlock *DefMBB = DefMI->getParent();
977 
978   // Reg is live-in to all blocks in Trace that follow DefMBB.
979   for (unsigned i = Trace.size(); i; --i) {
980     const MachineBasicBlock *MBB = Trace[i-1];
981     if (MBB == DefMBB)
982       return;
983     TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
984     // Just add the register. The height will be updated later.
985     TBI.LiveIns.push_back(Reg);
986   }
987 }
988 
989 /// Compute instruction heights in the trace through MBB. This updates MBB and
990 /// the blocks below it in the trace. It is assumed that the trace has already
991 /// been computed.
992 void MachineTraceMetrics::Ensemble::
993 computeInstrHeights(const MachineBasicBlock *MBB) {
994   // The bottom of the trace may already be computed.
995   // Find the blocks that need updating.
996   SmallVector<const MachineBasicBlock*, 8> Stack;
997   do {
998     TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
999     assert(TBI.hasValidHeight() && "Incomplete trace");
1000     if (TBI.HasValidInstrHeights)
1001       break;
1002     Stack.push_back(MBB);
1003     TBI.LiveIns.clear();
1004     MBB = TBI.Succ;
1005   } while (MBB);
1006 
1007   // As we move upwards in the trace, keep track of instructions that are
1008   // required by deeper trace instructions. Map MI -> height required so far.
1009   MIHeightMap Heights;
1010 
1011   // For physregs, the def isn't known when we see the use.
1012   // Instead, keep track of the highest use of each regunit.
1013   SparseSet<LiveRegUnit> RegUnits;
1014   RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
1015 
1016   // If the bottom of the trace was already precomputed, initialize heights
1017   // from its live-in list.
1018   // MBB is the highest precomputed block in the trace.
1019   if (MBB) {
1020     TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1021     for (LiveInReg &LI : TBI.LiveIns) {
1022       if (TargetRegisterInfo::isVirtualRegister(LI.Reg)) {
1023         // For virtual registers, the def latency is included.
1024         unsigned &Height = Heights[MTM.MRI->getVRegDef(LI.Reg)];
1025         if (Height < LI.Height)
1026           Height = LI.Height;
1027       } else {
1028         // For register units, the def latency is not included because we don't
1029         // know the def yet.
1030         RegUnits[LI.Reg].Cycle = LI.Height;
1031       }
1032     }
1033   }
1034 
1035   // Go through the trace blocks in bottom-up order.
1036   SmallVector<DataDep, 8> Deps;
1037   for (;!Stack.empty(); Stack.pop_back()) {
1038     MBB = Stack.back();
1039     DEBUG(dbgs() << "Heights for BB#" << MBB->getNumber() << ":\n");
1040     TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1041     TBI.HasValidInstrHeights = true;
1042     TBI.CriticalPath = 0;
1043 
1044     DEBUG({
1045       dbgs() << format("%7u Instructions\n", TBI.InstrHeight);
1046       ArrayRef<unsigned> PRHeights = getProcResourceHeights(MBB->getNumber());
1047       for (unsigned K = 0; K != PRHeights.size(); ++K)
1048         if (PRHeights[K]) {
1049           unsigned Factor = MTM.SchedModel.getResourceFactor(K);
1050           dbgs() << format("%6uc @ ", MTM.getCycles(PRHeights[K]))
1051                  << MTM.SchedModel.getProcResource(K)->Name << " ("
1052                  << PRHeights[K]/Factor << " ops x" << Factor << ")\n";
1053         }
1054     });
1055 
1056     // Get dependencies from PHIs in the trace successor.
1057     const MachineBasicBlock *Succ = TBI.Succ;
1058     // If MBB is the last block in the trace, and it has a back-edge to the
1059     // loop header, get loop-carried dependencies from PHIs in the header. For
1060     // that purpose, pretend that all the loop header PHIs have height 0.
1061     if (!Succ)
1062       if (const MachineLoop *Loop = getLoopFor(MBB))
1063         if (MBB->isSuccessor(Loop->getHeader()))
1064           Succ = Loop->getHeader();
1065 
1066     if (Succ) {
1067       for (const auto &PHI : *Succ) {
1068         if (!PHI.isPHI())
1069           break;
1070         Deps.clear();
1071         getPHIDeps(PHI, Deps, MBB, MTM.MRI);
1072         if (!Deps.empty()) {
1073           // Loop header PHI heights are all 0.
1074           unsigned Height = TBI.Succ ? Cycles.lookup(&PHI).Height : 0;
1075           DEBUG(dbgs() << "pred\t" << Height << '\t' << PHI);
1076           if (pushDepHeight(Deps.front(), PHI, Height, Heights, MTM.SchedModel,
1077                             MTM.TII))
1078             addLiveIns(Deps.front().DefMI, Deps.front().DefOp, Stack);
1079         }
1080       }
1081     }
1082 
1083     // Go through the block backwards.
1084     for (MachineBasicBlock::const_iterator BI = MBB->end(), BB = MBB->begin();
1085          BI != BB;) {
1086       const MachineInstr &MI = *--BI;
1087 
1088       // Find the MI height as determined by virtual register uses in the
1089       // trace below.
1090       unsigned Cycle = 0;
1091       MIHeightMap::iterator HeightI = Heights.find(&MI);
1092       if (HeightI != Heights.end()) {
1093         Cycle = HeightI->second;
1094         // We won't be seeing any more MI uses.
1095         Heights.erase(HeightI);
1096       }
1097 
1098       // Don't process PHI deps. They depend on the specific predecessor, and
1099       // we'll get them when visiting the predecessor.
1100       Deps.clear();
1101       bool HasPhysRegs = !MI.isPHI() && getDataDeps(MI, Deps, MTM.MRI);
1102 
1103       // There may also be regunit dependencies to include in the height.
1104       if (HasPhysRegs)
1105         Cycle = updatePhysDepsUpwards(MI, Cycle, RegUnits, MTM.SchedModel,
1106                                       MTM.TII, MTM.TRI);
1107 
1108       // Update the required height of any virtual registers read by MI.
1109       for (const DataDep &Dep : Deps)
1110         if (pushDepHeight(Dep, MI, Cycle, Heights, MTM.SchedModel, MTM.TII))
1111           addLiveIns(Dep.DefMI, Dep.DefOp, Stack);
1112 
1113       InstrCycles &MICycles = Cycles[&MI];
1114       MICycles.Height = Cycle;
1115       if (!TBI.HasValidInstrDepths) {
1116         DEBUG(dbgs() << Cycle << '\t' << MI);
1117         continue;
1118       }
1119       // Update critical path length.
1120       TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Depth);
1121       DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << MI);
1122     }
1123 
1124     // Update virtual live-in heights. They were added by addLiveIns() with a 0
1125     // height because the final height isn't known until now.
1126     DEBUG(dbgs() << "BB#" << MBB->getNumber() <<  " Live-ins:");
1127     for (LiveInReg &LIR : TBI.LiveIns) {
1128       const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
1129       LIR.Height = Heights.lookup(DefMI);
1130       DEBUG(dbgs() << ' ' << PrintReg(LIR.Reg) << '@' << LIR.Height);
1131     }
1132 
1133     // Transfer the live regunits to the live-in list.
1134     for (SparseSet<LiveRegUnit>::const_iterator
1135          RI = RegUnits.begin(), RE = RegUnits.end(); RI != RE; ++RI) {
1136       TBI.LiveIns.push_back(LiveInReg(RI->RegUnit, RI->Cycle));
1137       DEBUG(dbgs() << ' ' << PrintRegUnit(RI->RegUnit, MTM.TRI)
1138                    << '@' << RI->Cycle);
1139     }
1140     DEBUG(dbgs() << '\n');
1141 
1142     if (!TBI.HasValidInstrDepths)
1143       continue;
1144     // Add live-ins to the critical path length.
1145     TBI.CriticalPath = std::max(TBI.CriticalPath,
1146                                 computeCrossBlockCriticalPath(TBI));
1147     DEBUG(dbgs() << "Critical path: " << TBI.CriticalPath << '\n');
1148   }
1149 }
1150 
1151 MachineTraceMetrics::Trace
1152 MachineTraceMetrics::Ensemble::getTrace(const MachineBasicBlock *MBB) {
1153   TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1154 
1155   if (!TBI.hasValidDepth() || !TBI.hasValidHeight())
1156     computeTrace(MBB);
1157   if (!TBI.HasValidInstrDepths)
1158     computeInstrDepths(MBB);
1159   if (!TBI.HasValidInstrHeights)
1160     computeInstrHeights(MBB);
1161 
1162   return Trace(*this, TBI);
1163 }
1164 
1165 unsigned
1166 MachineTraceMetrics::Trace::getInstrSlack(const MachineInstr &MI) const {
1167   assert(getBlockNum() == unsigned(MI.getParent()->getNumber()) &&
1168          "MI must be in the trace center block");
1169   InstrCycles Cyc = getInstrCycles(MI);
1170   return getCriticalPath() - (Cyc.Depth + Cyc.Height);
1171 }
1172 
1173 unsigned
1174 MachineTraceMetrics::Trace::getPHIDepth(const MachineInstr &PHI) const {
1175   const MachineBasicBlock *MBB = TE.MTM.MF->getBlockNumbered(getBlockNum());
1176   SmallVector<DataDep, 1> Deps;
1177   getPHIDeps(PHI, Deps, MBB, TE.MTM.MRI);
1178   assert(Deps.size() == 1 && "PHI doesn't have MBB as a predecessor");
1179   DataDep &Dep = Deps.front();
1180   unsigned DepCycle = getInstrCycles(*Dep.DefMI).Depth;
1181   // Add latency if DefMI is a real instruction. Transients get latency 0.
1182   if (!Dep.DefMI->isTransient())
1183     DepCycle += TE.MTM.SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp,
1184                                                         &PHI, Dep.UseOp);
1185   return DepCycle;
1186 }
1187 
1188 /// When bottom is set include instructions in current block in estimate.
1189 unsigned MachineTraceMetrics::Trace::getResourceDepth(bool Bottom) const {
1190   // Find the limiting processor resource.
1191   // Numbers have been pre-scaled to be comparable.
1192   unsigned PRMax = 0;
1193   ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1194   if (Bottom) {
1195     ArrayRef<unsigned> PRCycles = TE.MTM.getProcResourceCycles(getBlockNum());
1196     for (unsigned K = 0; K != PRDepths.size(); ++K)
1197       PRMax = std::max(PRMax, PRDepths[K] + PRCycles[K]);
1198   } else {
1199     for (unsigned K = 0; K != PRDepths.size(); ++K)
1200       PRMax = std::max(PRMax, PRDepths[K]);
1201   }
1202   // Convert to cycle count.
1203   PRMax = TE.MTM.getCycles(PRMax);
1204 
1205   /// All instructions before current block
1206   unsigned Instrs = TBI.InstrDepth;
1207   // plus instructions in current block
1208   if (Bottom)
1209     Instrs += TE.MTM.BlockInfo[getBlockNum()].InstrCount;
1210   if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1211     Instrs /= IW;
1212   // Assume issue width 1 without a schedule model.
1213   return std::max(Instrs, PRMax);
1214 }
1215 
1216 unsigned MachineTraceMetrics::Trace::getResourceLength(
1217     ArrayRef<const MachineBasicBlock *> Extrablocks,
1218     ArrayRef<const MCSchedClassDesc *> ExtraInstrs,
1219     ArrayRef<const MCSchedClassDesc *> RemoveInstrs) const {
1220   // Add up resources above and below the center block.
1221   ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1222   ArrayRef<unsigned> PRHeights = TE.getProcResourceHeights(getBlockNum());
1223   unsigned PRMax = 0;
1224 
1225   // Capture computing cycles from extra instructions
1226   auto extraCycles = [this](ArrayRef<const MCSchedClassDesc *> Instrs,
1227                             unsigned ResourceIdx)
1228                          ->unsigned {
1229     unsigned Cycles = 0;
1230     for (const MCSchedClassDesc *SC : Instrs) {
1231       if (!SC->isValid())
1232         continue;
1233       for (TargetSchedModel::ProcResIter
1234                PI = TE.MTM.SchedModel.getWriteProcResBegin(SC),
1235                PE = TE.MTM.SchedModel.getWriteProcResEnd(SC);
1236            PI != PE; ++PI) {
1237         if (PI->ProcResourceIdx != ResourceIdx)
1238           continue;
1239         Cycles +=
1240             (PI->Cycles * TE.MTM.SchedModel.getResourceFactor(ResourceIdx));
1241       }
1242     }
1243     return Cycles;
1244   };
1245 
1246   for (unsigned K = 0; K != PRDepths.size(); ++K) {
1247     unsigned PRCycles = PRDepths[K] + PRHeights[K];
1248     for (const MachineBasicBlock *MBB : Extrablocks)
1249       PRCycles += TE.MTM.getProcResourceCycles(MBB->getNumber())[K];
1250     PRCycles += extraCycles(ExtraInstrs, K);
1251     PRCycles -= extraCycles(RemoveInstrs, K);
1252     PRMax = std::max(PRMax, PRCycles);
1253   }
1254   // Convert to cycle count.
1255   PRMax = TE.MTM.getCycles(PRMax);
1256 
1257   // Instrs: #instructions in current trace outside current block.
1258   unsigned Instrs = TBI.InstrDepth + TBI.InstrHeight;
1259   // Add instruction count from the extra blocks.
1260   for (const MachineBasicBlock *MBB : Extrablocks)
1261     Instrs += TE.MTM.getResources(MBB)->InstrCount;
1262   Instrs += ExtraInstrs.size();
1263   Instrs -= RemoveInstrs.size();
1264   if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1265     Instrs /= IW;
1266   // Assume issue width 1 without a schedule model.
1267   return std::max(Instrs, PRMax);
1268 }
1269 
1270 bool MachineTraceMetrics::Trace::isDepInTrace(const MachineInstr &DefMI,
1271                                               const MachineInstr &UseMI) const {
1272   if (DefMI.getParent() == UseMI.getParent())
1273     return true;
1274 
1275   const TraceBlockInfo &DepTBI = TE.BlockInfo[DefMI.getParent()->getNumber()];
1276   const TraceBlockInfo &TBI = TE.BlockInfo[UseMI.getParent()->getNumber()];
1277 
1278   return DepTBI.isUsefulDominator(TBI);
1279 }
1280 
1281 void MachineTraceMetrics::Ensemble::print(raw_ostream &OS) const {
1282   OS << getName() << " ensemble:\n";
1283   for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
1284     OS << "  BB#" << i << '\t';
1285     BlockInfo[i].print(OS);
1286     OS << '\n';
1287   }
1288 }
1289 
1290 void MachineTraceMetrics::TraceBlockInfo::print(raw_ostream &OS) const {
1291   if (hasValidDepth()) {
1292     OS << "depth=" << InstrDepth;
1293     if (Pred)
1294       OS << " pred=BB#" << Pred->getNumber();
1295     else
1296       OS << " pred=null";
1297     OS << " head=BB#" << Head;
1298     if (HasValidInstrDepths)
1299       OS << " +instrs";
1300   } else
1301     OS << "depth invalid";
1302   OS << ", ";
1303   if (hasValidHeight()) {
1304     OS << "height=" << InstrHeight;
1305     if (Succ)
1306       OS << " succ=BB#" << Succ->getNumber();
1307     else
1308       OS << " succ=null";
1309     OS << " tail=BB#" << Tail;
1310     if (HasValidInstrHeights)
1311       OS << " +instrs";
1312   } else
1313     OS << "height invalid";
1314   if (HasValidInstrDepths && HasValidInstrHeights)
1315     OS << ", crit=" << CriticalPath;
1316 }
1317 
1318 void MachineTraceMetrics::Trace::print(raw_ostream &OS) const {
1319   unsigned MBBNum = &TBI - &TE.BlockInfo[0];
1320 
1321   OS << TE.getName() << " trace BB#" << TBI.Head << " --> BB#" << MBBNum
1322      << " --> BB#" << TBI.Tail << ':';
1323   if (TBI.hasValidHeight() && TBI.hasValidDepth())
1324     OS << ' ' << getInstrCount() << " instrs.";
1325   if (TBI.HasValidInstrDepths && TBI.HasValidInstrHeights)
1326     OS << ' ' << TBI.CriticalPath << " cycles.";
1327 
1328   const MachineTraceMetrics::TraceBlockInfo *Block = &TBI;
1329   OS << "\nBB#" << MBBNum;
1330   while (Block->hasValidDepth() && Block->Pred) {
1331     unsigned Num = Block->Pred->getNumber();
1332     OS << " <- BB#" << Num;
1333     Block = &TE.BlockInfo[Num];
1334   }
1335 
1336   Block = &TBI;
1337   OS << "\n    ";
1338   while (Block->hasValidHeight() && Block->Succ) {
1339     unsigned Num = Block->Succ->getNumber();
1340     OS << " -> BB#" << Num;
1341     Block = &TE.BlockInfo[Num];
1342   }
1343   OS << '\n';
1344 }
1345