blob: 2cf87eb9104fabf5f98e71a3212fd5bf620654d9 [file] [log] [blame]
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001//===- 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
Jakob Stoklund Olesen5ed625c2013-01-17 01:06:04 +000010#include "llvm/CodeGen/MachineTraceMetrics.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000011#include "llvm/ADT/PostOrderIterator.h"
12#include "llvm/ADT/SparseSet.h"
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000013#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"
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +000018#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000019#include "llvm/Support/Debug.h"
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +000020#include "llvm/Support/Format.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000021#include "llvm/Support/raw_ostream.h"
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000022#include "llvm/Target/TargetInstrInfo.h"
23#include "llvm/Target/TargetRegisterInfo.h"
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +000024#include "llvm/Target/TargetSubtargetInfo.h"
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000025
26using namespace llvm;
27
Stephen Hinesdce4a402014-05-29 02:49:00 -070028#define DEBUG_TYPE "machine-trace-metrics"
29
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000030char MachineTraceMetrics::ID = 0;
31char &llvm::MachineTraceMetricsID = MachineTraceMetrics::ID;
32
33INITIALIZE_PASS_BEGIN(MachineTraceMetrics,
34 "machine-trace-metrics", "Machine Trace Metrics", false, true)
35INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
36INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
37INITIALIZE_PASS_END(MachineTraceMetrics,
38 "machine-trace-metrics", "Machine Trace Metrics", false, true)
39
40MachineTraceMetrics::MachineTraceMetrics()
Stephen Hinesdce4a402014-05-29 02:49:00 -070041 : MachineFunctionPass(ID), MF(nullptr), TII(nullptr), TRI(nullptr),
42 MRI(nullptr), Loops(nullptr) {
43 std::fill(std::begin(Ensembles), std::end(Ensembles), nullptr);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000044}
45
46void MachineTraceMetrics::getAnalysisUsage(AnalysisUsage &AU) const {
47 AU.setPreservesAll();
48 AU.addRequired<MachineBranchProbabilityInfo>();
49 AU.addRequired<MachineLoopInfo>();
50 MachineFunctionPass::getAnalysisUsage(AU);
51}
52
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +000053bool MachineTraceMetrics::runOnMachineFunction(MachineFunction &Func) {
54 MF = &Func;
Stephen Hines37ed9c12014-12-01 14:51:49 -080055 TII = MF->getSubtarget().getInstrInfo();
56 TRI = MF->getSubtarget().getRegisterInfo();
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +000057 MRI = &MF->getRegInfo();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000058 Loops = &getAnalysis<MachineLoopInfo>();
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +000059 const TargetSubtargetInfo &ST =
60 MF->getTarget().getSubtarget<TargetSubtargetInfo>();
Stephen Hines37ed9c12014-12-01 14:51:49 -080061 SchedModel.init(ST.getSchedModel(), &ST, TII);
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +000062 BlockInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +000063 ProcResourceCycles.resize(MF->getNumBlockIDs() *
64 SchedModel.getNumProcResourceKinds());
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000065 return false;
66}
67
68void MachineTraceMetrics::releaseMemory() {
Stephen Hinesdce4a402014-05-29 02:49:00 -070069 MF = nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000070 BlockInfo.clear();
71 for (unsigned i = 0; i != TS_NumStrategies; ++i) {
72 delete Ensembles[i];
Stephen Hinesdce4a402014-05-29 02:49:00 -070073 Ensembles[i] = nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000074 }
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
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000084/// Compute the resource usage in basic block MBB.
85const MachineTraceMetrics::FixedBlockInfo*
86MachineTraceMetrics::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.
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000093 FBI->HasCalls = false;
94 unsigned InstrCount = 0;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +000095
96 // Add up per-processor resource cycles as well.
97 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
98 SmallVector<unsigned, 32> PRCycles(PRKinds);
99
Stephen Hinesdce4a402014-05-29 02:49:00 -0700100 for (const auto &MI : *MBB) {
101 if (MI.isTransient())
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000102 continue;
103 ++InstrCount;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700104 if (MI.isCall())
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000105 FBI->HasCalls = true;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000106
107 // Count processor resources used.
Jakob Stoklund Olesen2ccdbc62013-04-02 22:27:45 +0000108 if (!SchedModel.hasInstrSchedModel())
109 continue;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700110 const MCSchedClassDesc *SC = SchedModel.resolveSchedClass(&MI);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000111 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 }
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000120 }
121 FBI->InstrCount = InstrCount;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000122
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
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000129 return FBI;
130}
131
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000132ArrayRef<unsigned>
133MachineTraceMetrics::getProcResourceCycles(unsigned MBBNum) const {
134 assert(BlockInfo[MBBNum].hasResources() &&
135 "getResources() must be called before getProcResourceCycles()");
136 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesen2ccdbc62013-04-02 22:27:45 +0000137 assert((MBBNum+1) * PRKinds <= ProcResourceCycles.size());
Stephen Hines37ed9c12014-12-01 14:51:49 -0800138 return makeArrayRef(ProcResourceCycles.data() + MBBNum * PRKinds, PRKinds);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000139}
140
141
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000142//===----------------------------------------------------------------------===//
143// Ensemble utility functions
144//===----------------------------------------------------------------------===//
145
146MachineTraceMetrics::Ensemble::Ensemble(MachineTraceMetrics *ct)
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000147 : MTM(*ct) {
148 BlockInfo.resize(MTM.BlockInfo.size());
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000149 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
150 ProcResourceDepths.resize(MTM.BlockInfo.size() * PRKinds);
151 ProcResourceHeights.resize(MTM.BlockInfo.size() * PRKinds);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000152}
153
154// Virtual destructor serves as an anchor.
155MachineTraceMetrics::Ensemble::~Ensemble() {}
156
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000157const MachineLoop*
158MachineTraceMetrics::Ensemble::getLoopFor(const MachineBasicBlock *MBB) const {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000159 return MTM.Loops->getLoopFor(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000160}
161
162// Update resource-related information in the TraceBlockInfo for MBB.
163// Only update resources related to the trace above MBB.
164void MachineTraceMetrics::Ensemble::
165computeDepthResources(const MachineBasicBlock *MBB) {
166 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000167 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
168 unsigned PROffset = MBB->getNumber() * PRKinds;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000169
170 // Compute resources from trace above. The top block is simple.
171 if (!TBI->Pred) {
172 TBI->InstrDepth = 0;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000173 TBI->Head = MBB->getNumber();
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000174 std::fill(ProcResourceDepths.begin() + PROffset,
175 ProcResourceDepths.begin() + PROffset + PRKinds, 0);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000176 return;
177 }
178
179 // Compute from the block above. A post-order traversal ensures the
180 // predecessor is always computed first.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000181 unsigned PredNum = TBI->Pred->getNumber();
182 TraceBlockInfo *PredTBI = &BlockInfo[PredNum];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000183 assert(PredTBI->hasValidDepth() && "Trace above has not been computed yet");
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000184 const FixedBlockInfo *PredFBI = MTM.getResources(TBI->Pred);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000185 TBI->InstrDepth = PredTBI->InstrDepth + PredFBI->InstrCount;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000186 TBI->Head = PredTBI->Head;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000187
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];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000193}
194
195// Update resource-related information in the TraceBlockInfo for MBB.
196// Only update resources related to the trace below MBB.
197void MachineTraceMetrics::Ensemble::
198computeHeightResources(const MachineBasicBlock *MBB) {
199 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000200 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
201 unsigned PROffset = MBB->getNumber() * PRKinds;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000202
203 // Compute resources for the current block.
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000204 TBI->InstrHeight = MTM.getResources(MBB)->InstrCount;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000205 ArrayRef<unsigned> PRCycles = MTM.getProcResourceCycles(MBB->getNumber());
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000206
207 // The trace tail is done.
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000208 if (!TBI->Succ) {
209 TBI->Tail = MBB->getNumber();
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000210 std::copy(PRCycles.begin(), PRCycles.end(),
211 ProcResourceHeights.begin() + PROffset);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000212 return;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000213 }
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000214
215 // Compute from the block below. A post-order traversal ensures the
216 // predecessor is always computed first.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000217 unsigned SuccNum = TBI->Succ->getNumber();
218 TraceBlockInfo *SuccTBI = &BlockInfo[SuccNum];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000219 assert(SuccTBI->hasValidHeight() && "Trace below has not been computed yet");
220 TBI->InstrHeight += SuccTBI->InstrHeight;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000221 TBI->Tail = SuccTBI->Tail;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000222
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];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000227}
228
229// Check if depth resources for MBB are valid and return the TBI.
230// Return NULL if the resources have been invalidated.
231const MachineTraceMetrics::TraceBlockInfo*
232MachineTraceMetrics::Ensemble::
233getDepthResources(const MachineBasicBlock *MBB) const {
234 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Stephen Hinesdce4a402014-05-29 02:49:00 -0700235 return TBI->hasValidDepth() ? TBI : nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000236}
237
238// Check if height resources for MBB are valid and return the TBI.
239// Return NULL if the resources have been invalidated.
240const MachineTraceMetrics::TraceBlockInfo*
241MachineTraceMetrics::Ensemble::
242getHeightResources(const MachineBasicBlock *MBB) const {
243 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Stephen Hinesdce4a402014-05-29 02:49:00 -0700244 return TBI->hasValidHeight() ? TBI : nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000245}
246
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000247/// 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.
253ArrayRef<unsigned>
254MachineTraceMetrics::Ensemble::
255getProcResourceDepths(unsigned MBBNum) const {
256 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesen2ccdbc62013-04-02 22:27:45 +0000257 assert((MBBNum+1) * PRKinds <= ProcResourceDepths.size());
Stephen Hines37ed9c12014-12-01 14:51:49 -0800258 return makeArrayRef(ProcResourceDepths.data() + MBBNum * PRKinds, PRKinds);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000259}
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.
266ArrayRef<unsigned>
267MachineTraceMetrics::Ensemble::
268getProcResourceHeights(unsigned MBBNum) const {
269 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesen2ccdbc62013-04-02 22:27:45 +0000270 assert((MBBNum+1) * PRKinds <= ProcResourceHeights.size());
Stephen Hines37ed9c12014-12-01 14:51:49 -0800271 return makeArrayRef(ProcResourceHeights.data() + MBBNum * PRKinds, PRKinds);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000272}
273
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000274//===----------------------------------------------------------------------===//
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
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000285// 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.
294static bool isExitingLoop(const MachineLoop *From, const MachineLoop *To) {
295 return From && !From->contains(To);
296}
297
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000298// MinInstrCountEnsemble - Pick the trace that executes the least number of
299// instructions.
300namespace {
301class MinInstrCountEnsemble : public MachineTraceMetrics::Ensemble {
Stephen Hines36b56882014-04-23 16:57:46 -0700302 const char *getName() const override { return "MinInstr"; }
303 const MachineBasicBlock *pickTracePred(const MachineBasicBlock*) override;
304 const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*) override;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000305
306public:
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000307 MinInstrCountEnsemble(MachineTraceMetrics *mtm)
308 : MachineTraceMetrics::Ensemble(mtm) {}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000309};
310}
311
312// Select the preferred predecessor for MBB.
313const MachineBasicBlock*
314MinInstrCountEnsemble::pickTracePred(const MachineBasicBlock *MBB) {
315 if (MBB->pred_empty())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700316 return nullptr;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000317 const MachineLoop *CurLoop = getLoopFor(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000318 // Don't leave loops, and never follow back-edges.
319 if (CurLoop && MBB == CurLoop->getHeader())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700320 return nullptr;
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000321 unsigned CurCount = MTM.getResources(MBB)->InstrCount;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700322 const MachineBasicBlock *Best = nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000323 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;
Jakob Stoklund Olesen8e54ab52012-07-30 21:10:27 +0000327 const MachineTraceMetrics::TraceBlockInfo *PredTBI =
328 getDepthResources(Pred);
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000329 // Ignore cycles that aren't natural loops.
330 if (!PredTBI)
331 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000332 // 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.
341const MachineBasicBlock*
342MinInstrCountEnsemble::pickTraceSucc(const MachineBasicBlock *MBB) {
343 if (MBB->pred_empty())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700344 return nullptr;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000345 const MachineLoop *CurLoop = getLoopFor(MBB);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700346 const MachineBasicBlock *Best = nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000347 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;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000351 // Don't consider back-edges.
352 if (CurLoop && Succ == CurLoop->getHeader())
353 continue;
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000354 // Don't consider successors exiting CurLoop.
355 if (isExitingLoop(CurLoop, getLoopFor(Succ)))
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000356 continue;
Jakob Stoklund Olesen8e54ab52012-07-30 21:10:27 +0000357 const MachineTraceMetrics::TraceBlockInfo *SuccTBI =
358 getHeightResources(Succ);
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000359 // Ignore cycles that aren't natural loops.
360 if (!SuccTBI)
361 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000362 // 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.
371MachineTraceMetrics::Ensemble *
372MachineTraceMetrics::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
385void 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
Jakob Stoklund Olesenef6c76c2012-07-30 20:57:50 +0000393void MachineTraceMetrics::verifyAnalysis() const {
Jakob Stoklund Olesen2f6b62b2012-07-30 23:15:12 +0000394 if (!MF)
395 return;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000396#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
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000404//===----------------------------------------------------------------------===//
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
412namespace {
413struct LoopBounds {
414 MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> Blocks;
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000415 SmallPtrSet<const MachineBasicBlock*, 8> Visited;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000416 const MachineLoopInfo *Loops;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000417 bool Downward;
418 LoopBounds(MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> blocks,
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000419 const MachineLoopInfo *loops)
420 : Blocks(blocks), Loops(loops), Downward(false) {}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000421};
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.
426namespace llvm {
427template<>
428class po_iterator_storage<LoopBounds, true> {
429 LoopBounds &LB;
430public:
431 po_iterator_storage(LoopBounds &lb) : LB(lb) {}
432 void finishPostorder(const MachineBasicBlock*) {}
433
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;
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000439 // From is null once when To is the trace center block.
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000440 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.
Stephen Hines37ed9c12014-12-01 14:51:49 -0800452 return LB.Visited.insert(To).second;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000453 }
454};
455}
456
457/// Compute the trace through MBB.
458void 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.
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000462 LoopBounds Bounds(BlockInfo, MTM.Loops);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000463
464 // Run an upwards post-order search for the trace start.
465 Bounds.Downward = false;
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000466 Bounds.Visited.clear();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000467 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;
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000486 Bounds.Visited.clear();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000487 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.
Jakob Stoklund Olesen0fc44862012-07-26 19:42:56 +0000493 TBI.Succ = pickTraceSucc(*I);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000494 DEBUG({
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000495 if (TBI.Succ)
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000496 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.
506void
507MachineTraceMetrics::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()];
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000524 if (!TBI.hasValidHeight())
525 continue;
526 if (TBI.Succ == MBB) {
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000527 TBI.invalidateHeight();
528 WorkList.push_back(*I);
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000529 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000530 }
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000531 // Verify that TBI.Succ is actually a *I successor.
532 assert((!TBI.Succ || (*I)->isSuccessor(TBI.Succ)) && "CFG changed");
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000533 }
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()];
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000550 if (!TBI.hasValidDepth())
551 continue;
552 if (TBI.Pred == MBB) {
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000553 TBI.invalidateDepth();
554 WorkList.push_back(*I);
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000555 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000556 }
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000557 // Verify that TBI.Pred is actually a *I predecessor.
558 assert((!TBI.Pred || (*I)->isPredecessor(TBI.Pred)) && "CFG changed");
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000559 }
560 } while (!WorkList.empty());
561 }
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000562
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.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700568 for (const auto &I : *BadMBB)
569 Cycles.erase(&I);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000570}
571
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000572void MachineTraceMetrics::Ensemble::verify() const {
573#ifndef NDEBUG
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000574 assert(BlockInfo.size() == MTM.MF->getNumBlockIDs() &&
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000575 "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) {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000579 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000580 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) {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000587 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000588 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}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000599
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000600//===----------------------------------------------------------------------===//
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.
611namespace {
612struct DataDep {
613 const MachineInstr *DefMI;
614 unsigned DefOp;
615 unsigned UseOp;
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000616
617 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.
621 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");
Stephen Hines36b56882014-04-23 16:57:46 -0700626 DefMI = DefI->getParent();
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000627 DefOp = DefI.getOperandNo();
628 assert((++DefI).atEnd() && "Register has multiple defs");
629 }
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000630};
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.
635static 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.
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000650 if (MO->readsReg())
651 Deps.push_back(DataDep(MRI, Reg, MO.getOperandNo()));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000652 }
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.
659static 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();
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000670 Deps.push_back(DataDep(MRI, Reg, i));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000671 return;
672 }
673 }
674}
675
676// Keep track of physreg data dependencies by recording each live register unit.
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000677// 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.
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000680namespace {
681struct LiveRegUnit {
682 unsigned RegUnit;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000683 unsigned Cycle;
684 const MachineInstr *MI;
685 unsigned Op;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000686
687 unsigned getSparseSetIndex() const { return RegUnit; }
688
Stephen Hinesdce4a402014-05-29 02:49:00 -0700689 LiveRegUnit(unsigned RU) : RegUnit(RU), Cycle(0), MI(nullptr), Op(0) {}
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000690};
691}
692
693// Identify physreg dependencies for UseMI, and update the live regunit
694// tracking set when scanning instructions downwards.
695static 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;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000723 Deps.push_back(DataDep(I->MI, I->Op, MO.getOperandNo()));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000724 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];
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000740 LRU.MI = UseMI;
741 LRU.Op = DefOp;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000742 }
743 }
744}
745
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000746/// 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.
757unsigned MachineTraceMetrics::Ensemble::
758computeCrossBlockCriticalPath(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()];
Jakob Stoklund Olesen6ffcd5e2013-03-07 23:55:49 +0000769 if (!DefTBI.isUsefulDominator(TBI))
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000770 continue;
771 unsigned Len = LIR.Height + Cycles[DefMI].Depth;
772 MaxLen = std::max(MaxLen, Len);
773 }
774 return MaxLen;
775}
776
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000777/// 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.
779void MachineTraceMetrics::Ensemble::
780computeInstrDepths(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();
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000805 DEBUG(dbgs() << "\nDepths for BB#" << MBB->getNumber() << ":\n");
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000806 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
807 TBI.HasValidInstrDepths = true;
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000808 TBI.CriticalPath = 0;
809
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000810 // 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
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000823 // Also compute the critical path length through MBB when possible.
824 if (TBI.HasValidInstrHeights)
825 TBI.CriticalPath = computeCrossBlockCriticalPath(TBI);
826
Stephen Hinesdce4a402014-05-29 02:49:00 -0700827 for (const auto &UseMI : *MBB) {
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000828 // Collect all data dependencies.
829 Deps.clear();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700830 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);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000834
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.
Jakob Stoklund Olesen6ffcd5e2013-03-07 23:55:49 +0000842 if (!DepTBI.isUsefulDominator(TBI))
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000843 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())
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000848 DepCycle += MTM.SchedModel
Stephen Hinesdce4a402014-05-29 02:49:00 -0700849 .computeOperandLatency(Dep.DefMI, Dep.DefOp, &UseMI, Dep.UseOp);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000850 Cycle = std::max(Cycle, DepCycle);
851 }
852 // Remember the instruction depth.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700853 InstrCycles &MICycles = Cycles[&UseMI];
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000854 MICycles.Depth = Cycle;
855
856 if (!TBI.HasValidInstrHeights) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700857 DEBUG(dbgs() << Cycle << '\t' << UseMI);
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000858 continue;
859 }
860 // Update critical path length.
861 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Height);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700862 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << UseMI);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000863 }
864 }
865}
866
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000867// 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.
870static unsigned updatePhysDepsUpwards(const MachineInstr *MI, unsigned Height,
871 SparseSet<LiveRegUnit> &RegUnits,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000872 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000873 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
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000895 // live-in list. SchedModel can handle a NULL UseMI.
896 DepHeight += SchedModel
Andrew Trickb86a0cd2013-06-15 04:49:57 +0000897 .computeOperandLatency(MI, MO.getOperandNo(), I->MI, I->Op);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000898 }
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
923typedef 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.
927static bool pushDepHeight(const DataDep &Dep,
928 const MachineInstr *UseMI, unsigned UseHeight,
929 MIHeightMap &Heights,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000930 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000931 const TargetInstrInfo *TII) {
932 // Adjust height by Dep.DefMI latency.
933 if (!Dep.DefMI->isTransient())
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000934 UseHeight += SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp,
Andrew Trickb86a0cd2013-06-15 04:49:57 +0000935 UseMI, Dep.UseOp);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000936
937 // Update Heights[DefMI] to be the maximum height seen.
938 MIHeightMap::iterator I;
939 bool New;
Stephen Hines36b56882014-04-23 16:57:46 -0700940 std::tie(I, New) = Heights.insert(std::make_pair(Dep.DefMI, UseHeight));
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000941 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
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000950/// 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.
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000953void MachineTraceMetrics::Ensemble::
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000954addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000955 ArrayRef<const MachineBasicBlock*> Trace) {
956 assert(!Trace.empty() && "Trace should contain at least one block");
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000957 unsigned Reg = DefMI->getOperand(DefOp).getReg();
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000958 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.
975void MachineTraceMetrics::Ensemble::
976computeInstrHeights(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;
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001026 TBI.CriticalPath = 0;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001027
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001028 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
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001040 // Get dependencies from PHIs in the trace successor.
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001041 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) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07001051 for (const auto &PHI : *Succ) {
1052 if (!PHI.isPHI())
1053 break;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001054 Deps.clear();
Stephen Hinesdce4a402014-05-29 02:49:00 -07001055 getPHIDeps(&PHI, Deps, MBB, MTM.MRI);
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001056 if (!Deps.empty()) {
1057 // Loop header PHI heights are all 0.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001058 unsigned Height = TBI.Succ ? Cycles.lookup(&PHI).Height : 0;
1059 DEBUG(dbgs() << "pred\t" << Height << '\t' << PHI);
1060 if (pushDepHeight(Deps.front(), &PHI, Height,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001061 Heights, MTM.SchedModel, MTM.TII))
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +00001062 addLiveIns(Deps.front().DefMI, Deps.front().DefOp, Stack);
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001063 }
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001064 }
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,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001090 MTM.SchedModel, MTM.TII, MTM.TRI);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001091
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001092 // Update the required height of any virtual registers read by MI.
1093 for (unsigned i = 0, e = Deps.size(); i != e; ++i)
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001094 if (pushDepHeight(Deps[i], MI, Cycle, Heights, MTM.SchedModel, MTM.TII))
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +00001095 addLiveIns(Deps[i].DefMI, Deps[i].DefOp, Stack);
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001096
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);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001106 }
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');
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001126
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');
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001133 }
1134}
1135
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001136MachineTraceMetrics::Trace
1137MachineTraceMetrics::Ensemble::getTrace(const MachineBasicBlock *MBB) {
1138 // FIXME: Check cache tags, recompute as needed.
1139 computeTrace(MBB);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +00001140 computeInstrDepths(MBB);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001141 computeInstrHeights(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001142 return Trace(*this, BlockInfo[MBB->getNumber()]);
1143}
1144
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001145unsigned
1146MachineTraceMetrics::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
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001154unsigned
1155MachineTraceMetrics::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())
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001164 DepCycle += TE.MTM.SchedModel
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001165 .computeOperandLatency(Dep.DefMI, Dep.DefOp, PHI, Dep.UseOp);
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001166 return DepCycle;
1167}
1168
Stephen Hines37ed9c12014-12-01 14:51:49 -08001169/// When bottom is set include instructions in current block in estimate.
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001170unsigned MachineTraceMetrics::Trace::getResourceDepth(bool Bottom) const {
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001171 // 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
Stephen Hines37ed9c12014-12-01 14:51:49 -08001186 /// All instructions before current block
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001187 unsigned Instrs = TBI.InstrDepth;
Stephen Hines37ed9c12014-12-01 14:51:49 -08001188 // plus instructions in current block
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001189 if (Bottom)
1190 Instrs += TE.MTM.BlockInfo[getBlockNum()].InstrCount;
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001191 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1192 Instrs /= IW;
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001193 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001194 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001195}
1196
Stephen Hines37ed9c12014-12-01 14:51:49 -08001197unsigned MachineTraceMetrics::Trace::getResourceLength(
1198 ArrayRef<const MachineBasicBlock *> Extrablocks,
1199 ArrayRef<const MCSchedClassDesc *> ExtraInstrs,
1200 ArrayRef<const MCSchedClassDesc *> RemoveInstrs) const {
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001201 // 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;
Stephen Hines37ed9c12014-12-01 14:51:49 -08001205
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
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001228 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];
Stephen Hines37ed9c12014-12-01 14:51:49 -08001232 PRCycles += extraCycles(ExtraInstrs, K);
1233 PRCycles -= extraCycles(RemoveInstrs, K);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001234 PRMax = std::max(PRMax, PRCycles);
1235 }
1236 // Convert to cycle count.
1237 PRMax = TE.MTM.getCycles(PRMax);
1238
Stephen Hines37ed9c12014-12-01 14:51:49 -08001239 // Instrs: #instructions in current trace outside current block.
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001240 unsigned Instrs = TBI.InstrDepth + TBI.InstrHeight;
Stephen Hines37ed9c12014-12-01 14:51:49 -08001241 // Add instruction count from the extra blocks.
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001242 for (unsigned i = 0, e = Extrablocks.size(); i != e; ++i)
1243 Instrs += TE.MTM.getResources(Extrablocks[i])->InstrCount;
Stephen Hines37ed9c12014-12-01 14:51:49 -08001244 Instrs += ExtraInstrs.size();
1245 Instrs -= RemoveInstrs.size();
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001246 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1247 Instrs /= IW;
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001248 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001249 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001250}
1251
Stephen Hines37ed9c12014-12-01 14:51:49 -08001252bool 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
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001263void 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
1272void 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;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +00001280 if (HasValidInstrDepths)
1281 OS << " +instrs";
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001282 } 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;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +00001292 if (HasValidInstrHeights)
1293 OS << " +instrs";
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001294 } else
1295 OS << "height invalid";
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001296 if (HasValidInstrDepths && HasValidInstrHeights)
1297 OS << ", crit=" << CriticalPath;
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001298}
1299
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001300void MachineTraceMetrics::Trace::print(raw_ostream &OS) const {
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001301 unsigned MBBNum = &TBI - &TE.BlockInfo[0];
1302
1303 OS << TE.getName() << " trace BB#" << TBI.Head << " --> BB#" << MBBNum
1304 << " --> BB#" << TBI.Tail << ':';
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001305 if (TBI.hasValidHeight() && TBI.hasValidDepth())
1306 OS << ' ' << getInstrCount() << " instrs.";
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001307 if (TBI.HasValidInstrDepths && TBI.HasValidInstrHeights)
1308 OS << ' ' << TBI.CriticalPath << " cycles.";
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001309
1310 const MachineTraceMetrics::TraceBlockInfo *Block = &TBI;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001311 OS << "\nBB#" << MBBNum;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001312 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;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001319 OS << "\n ";
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001320 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}