LLVM API Documentation

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