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