blob: 8aacd1f31bb6f85717cb247d1ae3d334324e8752 [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 Hinesebe69fe2015-03-23 12:10:34 -070055 const TargetSubtargetInfo &ST = MF->getSubtarget();
56 TII = ST.getInstrInfo();
57 TRI = ST.getRegisterInfo();
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +000058 MRI = &MF->getRegInfo();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000059 Loops = &getAnalysis<MachineLoopInfo>();
Stephen Hines37ed9c12014-12-01 14:51:49 -080060 SchedModel.init(ST.getSchedModel(), &ST, TII);
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +000061 BlockInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +000062 ProcResourceCycles.resize(MF->getNumBlockIDs() *
63 SchedModel.getNumProcResourceKinds());
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000064 return false;
65}
66
67void MachineTraceMetrics::releaseMemory() {
Stephen Hinesdce4a402014-05-29 02:49:00 -070068 MF = nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000069 BlockInfo.clear();
70 for (unsigned i = 0; i != TS_NumStrategies; ++i) {
71 delete Ensembles[i];
Stephen Hinesdce4a402014-05-29 02:49:00 -070072 Ensembles[i] = nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000073 }
74}
75
76//===----------------------------------------------------------------------===//
77// Fixed block information
78//===----------------------------------------------------------------------===//
79//
80// The number of instructions in a basic block and the CPU resources used by
81// those instructions don't depend on any given trace strategy.
82
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000083/// Compute the resource usage in basic block MBB.
84const MachineTraceMetrics::FixedBlockInfo*
85MachineTraceMetrics::getResources(const MachineBasicBlock *MBB) {
86 assert(MBB && "No basic block");
87 FixedBlockInfo *FBI = &BlockInfo[MBB->getNumber()];
88 if (FBI->hasResources())
89 return FBI;
90
91 // Compute resource usage in the block.
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000092 FBI->HasCalls = false;
93 unsigned InstrCount = 0;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +000094
95 // Add up per-processor resource cycles as well.
96 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
97 SmallVector<unsigned, 32> PRCycles(PRKinds);
98
Stephen Hinesdce4a402014-05-29 02:49:00 -070099 for (const auto &MI : *MBB) {
100 if (MI.isTransient())
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000101 continue;
102 ++InstrCount;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700103 if (MI.isCall())
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000104 FBI->HasCalls = true;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000105
106 // Count processor resources used.
Jakob Stoklund Olesen2ccdbc62013-04-02 22:27:45 +0000107 if (!SchedModel.hasInstrSchedModel())
108 continue;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700109 const MCSchedClassDesc *SC = SchedModel.resolveSchedClass(&MI);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000110 if (!SC->isValid())
111 continue;
112
113 for (TargetSchedModel::ProcResIter
114 PI = SchedModel.getWriteProcResBegin(SC),
115 PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
116 assert(PI->ProcResourceIdx < PRKinds && "Bad processor resource kind");
117 PRCycles[PI->ProcResourceIdx] += PI->Cycles;
118 }
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000119 }
120 FBI->InstrCount = InstrCount;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000121
122 // Scale the resource cycles so they are comparable.
123 unsigned PROffset = MBB->getNumber() * PRKinds;
124 for (unsigned K = 0; K != PRKinds; ++K)
125 ProcResourceCycles[PROffset + K] =
126 PRCycles[K] * SchedModel.getResourceFactor(K);
127
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000128 return FBI;
129}
130
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000131ArrayRef<unsigned>
132MachineTraceMetrics::getProcResourceCycles(unsigned MBBNum) const {
133 assert(BlockInfo[MBBNum].hasResources() &&
134 "getResources() must be called before getProcResourceCycles()");
135 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesen2ccdbc62013-04-02 22:27:45 +0000136 assert((MBBNum+1) * PRKinds <= ProcResourceCycles.size());
Stephen Hines37ed9c12014-12-01 14:51:49 -0800137 return makeArrayRef(ProcResourceCycles.data() + MBBNum * PRKinds, PRKinds);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000138}
139
140
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000141//===----------------------------------------------------------------------===//
142// Ensemble utility functions
143//===----------------------------------------------------------------------===//
144
145MachineTraceMetrics::Ensemble::Ensemble(MachineTraceMetrics *ct)
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000146 : MTM(*ct) {
147 BlockInfo.resize(MTM.BlockInfo.size());
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000148 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
149 ProcResourceDepths.resize(MTM.BlockInfo.size() * PRKinds);
150 ProcResourceHeights.resize(MTM.BlockInfo.size() * PRKinds);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000151}
152
153// Virtual destructor serves as an anchor.
154MachineTraceMetrics::Ensemble::~Ensemble() {}
155
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000156const MachineLoop*
157MachineTraceMetrics::Ensemble::getLoopFor(const MachineBasicBlock *MBB) const {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000158 return MTM.Loops->getLoopFor(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000159}
160
161// Update resource-related information in the TraceBlockInfo for MBB.
162// Only update resources related to the trace above MBB.
163void MachineTraceMetrics::Ensemble::
164computeDepthResources(const MachineBasicBlock *MBB) {
165 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000166 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
167 unsigned PROffset = MBB->getNumber() * PRKinds;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000168
169 // Compute resources from trace above. The top block is simple.
170 if (!TBI->Pred) {
171 TBI->InstrDepth = 0;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000172 TBI->Head = MBB->getNumber();
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000173 std::fill(ProcResourceDepths.begin() + PROffset,
174 ProcResourceDepths.begin() + PROffset + PRKinds, 0);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000175 return;
176 }
177
178 // Compute from the block above. A post-order traversal ensures the
179 // predecessor is always computed first.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000180 unsigned PredNum = TBI->Pred->getNumber();
181 TraceBlockInfo *PredTBI = &BlockInfo[PredNum];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000182 assert(PredTBI->hasValidDepth() && "Trace above has not been computed yet");
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000183 const FixedBlockInfo *PredFBI = MTM.getResources(TBI->Pred);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000184 TBI->InstrDepth = PredTBI->InstrDepth + PredFBI->InstrCount;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000185 TBI->Head = PredTBI->Head;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000186
187 // Compute per-resource depths.
188 ArrayRef<unsigned> PredPRDepths = getProcResourceDepths(PredNum);
189 ArrayRef<unsigned> PredPRCycles = MTM.getProcResourceCycles(PredNum);
190 for (unsigned K = 0; K != PRKinds; ++K)
191 ProcResourceDepths[PROffset + K] = PredPRDepths[K] + PredPRCycles[K];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000192}
193
194// Update resource-related information in the TraceBlockInfo for MBB.
195// Only update resources related to the trace below MBB.
196void MachineTraceMetrics::Ensemble::
197computeHeightResources(const MachineBasicBlock *MBB) {
198 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000199 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
200 unsigned PROffset = MBB->getNumber() * PRKinds;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000201
202 // Compute resources for the current block.
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000203 TBI->InstrHeight = MTM.getResources(MBB)->InstrCount;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000204 ArrayRef<unsigned> PRCycles = MTM.getProcResourceCycles(MBB->getNumber());
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000205
206 // The trace tail is done.
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000207 if (!TBI->Succ) {
208 TBI->Tail = MBB->getNumber();
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000209 std::copy(PRCycles.begin(), PRCycles.end(),
210 ProcResourceHeights.begin() + PROffset);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000211 return;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000212 }
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000213
214 // Compute from the block below. A post-order traversal ensures the
215 // predecessor is always computed first.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000216 unsigned SuccNum = TBI->Succ->getNumber();
217 TraceBlockInfo *SuccTBI = &BlockInfo[SuccNum];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000218 assert(SuccTBI->hasValidHeight() && "Trace below has not been computed yet");
219 TBI->InstrHeight += SuccTBI->InstrHeight;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000220 TBI->Tail = SuccTBI->Tail;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000221
222 // Compute per-resource heights.
223 ArrayRef<unsigned> SuccPRHeights = getProcResourceHeights(SuccNum);
224 for (unsigned K = 0; K != PRKinds; ++K)
225 ProcResourceHeights[PROffset + K] = SuccPRHeights[K] + PRCycles[K];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000226}
227
228// Check if depth resources for MBB are valid and return the TBI.
229// Return NULL if the resources have been invalidated.
230const MachineTraceMetrics::TraceBlockInfo*
231MachineTraceMetrics::Ensemble::
232getDepthResources(const MachineBasicBlock *MBB) const {
233 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Stephen Hinesdce4a402014-05-29 02:49:00 -0700234 return TBI->hasValidDepth() ? TBI : nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000235}
236
237// Check if height resources for MBB are valid and return the TBI.
238// Return NULL if the resources have been invalidated.
239const MachineTraceMetrics::TraceBlockInfo*
240MachineTraceMetrics::Ensemble::
241getHeightResources(const MachineBasicBlock *MBB) const {
242 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Stephen Hinesdce4a402014-05-29 02:49:00 -0700243 return TBI->hasValidHeight() ? TBI : nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000244}
245
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000246/// Get an array of processor resource depths for MBB. Indexed by processor
247/// resource kind, this array contains the scaled processor resources consumed
248/// by all blocks preceding MBB in its trace. It does not include instructions
249/// in MBB.
250///
251/// Compare TraceBlockInfo::InstrDepth.
252ArrayRef<unsigned>
253MachineTraceMetrics::Ensemble::
254getProcResourceDepths(unsigned MBBNum) const {
255 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesen2ccdbc62013-04-02 22:27:45 +0000256 assert((MBBNum+1) * PRKinds <= ProcResourceDepths.size());
Stephen Hines37ed9c12014-12-01 14:51:49 -0800257 return makeArrayRef(ProcResourceDepths.data() + MBBNum * PRKinds, PRKinds);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000258}
259
260/// Get an array of processor resource heights for MBB. Indexed by processor
261/// resource kind, this array contains the scaled processor resources consumed
262/// by this block and all blocks following it in its trace.
263///
264/// Compare TraceBlockInfo::InstrHeight.
265ArrayRef<unsigned>
266MachineTraceMetrics::Ensemble::
267getProcResourceHeights(unsigned MBBNum) const {
268 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesen2ccdbc62013-04-02 22:27:45 +0000269 assert((MBBNum+1) * PRKinds <= ProcResourceHeights.size());
Stephen Hines37ed9c12014-12-01 14:51:49 -0800270 return makeArrayRef(ProcResourceHeights.data() + MBBNum * PRKinds, PRKinds);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000271}
272
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000273//===----------------------------------------------------------------------===//
274// Trace Selection Strategies
275//===----------------------------------------------------------------------===//
276//
277// A trace selection strategy is implemented as a sub-class of Ensemble. The
278// trace through a block B is computed by two DFS traversals of the CFG
279// starting from B. One upwards, and one downwards. During the upwards DFS,
280// pickTracePred() is called on the post-ordered blocks. During the downwards
281// DFS, pickTraceSucc() is called in a post-order.
282//
283
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000284// We never allow traces that leave loops, but we do allow traces to enter
285// nested loops. We also never allow traces to contain back-edges.
286//
287// This means that a loop header can never appear above the center block of a
288// trace, except as the trace head. Below the center block, loop exiting edges
289// are banned.
290//
291// Return true if an edge from the From loop to the To loop is leaving a loop.
292// Either of To and From can be null.
293static bool isExitingLoop(const MachineLoop *From, const MachineLoop *To) {
294 return From && !From->contains(To);
295}
296
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000297// MinInstrCountEnsemble - Pick the trace that executes the least number of
298// instructions.
299namespace {
300class MinInstrCountEnsemble : public MachineTraceMetrics::Ensemble {
Stephen Hines36b56882014-04-23 16:57:46 -0700301 const char *getName() const override { return "MinInstr"; }
302 const MachineBasicBlock *pickTracePred(const MachineBasicBlock*) override;
303 const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*) override;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000304
305public:
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000306 MinInstrCountEnsemble(MachineTraceMetrics *mtm)
307 : MachineTraceMetrics::Ensemble(mtm) {}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000308};
309}
310
311// Select the preferred predecessor for MBB.
312const MachineBasicBlock*
313MinInstrCountEnsemble::pickTracePred(const MachineBasicBlock *MBB) {
314 if (MBB->pred_empty())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700315 return nullptr;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000316 const MachineLoop *CurLoop = getLoopFor(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000317 // Don't leave loops, and never follow back-edges.
318 if (CurLoop && MBB == CurLoop->getHeader())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700319 return nullptr;
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000320 unsigned CurCount = MTM.getResources(MBB)->InstrCount;
Stephen Hinesdce4a402014-05-29 02:49:00 -0700321 const MachineBasicBlock *Best = nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000322 unsigned BestDepth = 0;
323 for (MachineBasicBlock::const_pred_iterator
324 I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
325 const MachineBasicBlock *Pred = *I;
Jakob Stoklund Olesen8e54ab52012-07-30 21:10:27 +0000326 const MachineTraceMetrics::TraceBlockInfo *PredTBI =
327 getDepthResources(Pred);
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000328 // Ignore cycles that aren't natural loops.
329 if (!PredTBI)
330 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000331 // Pick the predecessor that would give this block the smallest InstrDepth.
332 unsigned Depth = PredTBI->InstrDepth + CurCount;
333 if (!Best || Depth < BestDepth)
334 Best = Pred, BestDepth = Depth;
335 }
336 return Best;
337}
338
339// Select the preferred successor for MBB.
340const MachineBasicBlock*
341MinInstrCountEnsemble::pickTraceSucc(const MachineBasicBlock *MBB) {
342 if (MBB->pred_empty())
Stephen Hinesdce4a402014-05-29 02:49:00 -0700343 return nullptr;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000344 const MachineLoop *CurLoop = getLoopFor(MBB);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700345 const MachineBasicBlock *Best = nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000346 unsigned BestHeight = 0;
347 for (MachineBasicBlock::const_succ_iterator
348 I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
349 const MachineBasicBlock *Succ = *I;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000350 // Don't consider back-edges.
351 if (CurLoop && Succ == CurLoop->getHeader())
352 continue;
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000353 // Don't consider successors exiting CurLoop.
354 if (isExitingLoop(CurLoop, getLoopFor(Succ)))
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000355 continue;
Jakob Stoklund Olesen8e54ab52012-07-30 21:10:27 +0000356 const MachineTraceMetrics::TraceBlockInfo *SuccTBI =
357 getHeightResources(Succ);
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000358 // Ignore cycles that aren't natural loops.
359 if (!SuccTBI)
360 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000361 // Pick the successor that would give this block the smallest InstrHeight.
362 unsigned Height = SuccTBI->InstrHeight;
363 if (!Best || Height < BestHeight)
364 Best = Succ, BestHeight = Height;
365 }
366 return Best;
367}
368
369// Get an Ensemble sub-class for the requested trace strategy.
370MachineTraceMetrics::Ensemble *
371MachineTraceMetrics::getEnsemble(MachineTraceMetrics::Strategy strategy) {
372 assert(strategy < TS_NumStrategies && "Invalid trace strategy enum");
373 Ensemble *&E = Ensembles[strategy];
374 if (E)
375 return E;
376
377 // Allocate new Ensemble on demand.
378 switch (strategy) {
379 case TS_MinInstrCount: return (E = new MinInstrCountEnsemble(this));
380 default: llvm_unreachable("Invalid trace strategy enum");
381 }
382}
383
384void MachineTraceMetrics::invalidate(const MachineBasicBlock *MBB) {
385 DEBUG(dbgs() << "Invalidate traces through BB#" << MBB->getNumber() << '\n');
386 BlockInfo[MBB->getNumber()].invalidate();
387 for (unsigned i = 0; i != TS_NumStrategies; ++i)
388 if (Ensembles[i])
389 Ensembles[i]->invalidate(MBB);
390}
391
Jakob Stoklund Olesenef6c76c2012-07-30 20:57:50 +0000392void MachineTraceMetrics::verifyAnalysis() const {
Jakob Stoklund Olesen2f6b62b2012-07-30 23:15:12 +0000393 if (!MF)
394 return;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000395#ifndef NDEBUG
396 assert(BlockInfo.size() == MF->getNumBlockIDs() && "Outdated BlockInfo size");
397 for (unsigned i = 0; i != TS_NumStrategies; ++i)
398 if (Ensembles[i])
399 Ensembles[i]->verify();
400#endif
401}
402
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000403//===----------------------------------------------------------------------===//
404// Trace building
405//===----------------------------------------------------------------------===//
406//
407// Traces are built by two CFG traversals. To avoid recomputing too much, use a
408// set abstraction that confines the search to the current loop, and doesn't
409// revisit blocks.
410
411namespace {
412struct LoopBounds {
413 MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> Blocks;
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000414 SmallPtrSet<const MachineBasicBlock*, 8> Visited;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000415 const MachineLoopInfo *Loops;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000416 bool Downward;
417 LoopBounds(MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> blocks,
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000418 const MachineLoopInfo *loops)
419 : Blocks(blocks), Loops(loops), Downward(false) {}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000420};
421}
422
423// Specialize po_iterator_storage in order to prune the post-order traversal so
424// it is limited to the current loop and doesn't traverse the loop back edges.
425namespace llvm {
426template<>
427class po_iterator_storage<LoopBounds, true> {
428 LoopBounds &LB;
429public:
430 po_iterator_storage(LoopBounds &lb) : LB(lb) {}
431 void finishPostorder(const MachineBasicBlock*) {}
432
433 bool insertEdge(const MachineBasicBlock *From, const MachineBasicBlock *To) {
434 // Skip already visited To blocks.
435 MachineTraceMetrics::TraceBlockInfo &TBI = LB.Blocks[To->getNumber()];
436 if (LB.Downward ? TBI.hasValidHeight() : TBI.hasValidDepth())
437 return false;
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000438 // From is null once when To is the trace center block.
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000439 if (From) {
440 if (const MachineLoop *FromLoop = LB.Loops->getLoopFor(From)) {
441 // Don't follow backedges, don't leave FromLoop when going upwards.
442 if ((LB.Downward ? To : From) == FromLoop->getHeader())
443 return false;
444 // Don't leave FromLoop.
445 if (isExitingLoop(FromLoop, LB.Loops->getLoopFor(To)))
446 return false;
447 }
448 }
449 // To is a new block. Mark the block as visited in case the CFG has cycles
450 // that MachineLoopInfo didn't recognize as a natural loop.
Stephen Hines37ed9c12014-12-01 14:51:49 -0800451 return LB.Visited.insert(To).second;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000452 }
453};
454}
455
456/// Compute the trace through MBB.
457void MachineTraceMetrics::Ensemble::computeTrace(const MachineBasicBlock *MBB) {
458 DEBUG(dbgs() << "Computing " << getName() << " trace through BB#"
459 << MBB->getNumber() << '\n');
460 // Set up loop bounds for the backwards post-order traversal.
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000461 LoopBounds Bounds(BlockInfo, MTM.Loops);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000462
463 // Run an upwards post-order search for the trace start.
464 Bounds.Downward = false;
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000465 Bounds.Visited.clear();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000466 typedef ipo_ext_iterator<const MachineBasicBlock*, LoopBounds> UpwardPO;
467 for (UpwardPO I = ipo_ext_begin(MBB, Bounds), E = ipo_ext_end(MBB, Bounds);
468 I != E; ++I) {
469 DEBUG(dbgs() << " pred for BB#" << I->getNumber() << ": ");
470 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
471 // All the predecessors have been visited, pick the preferred one.
472 TBI.Pred = pickTracePred(*I);
473 DEBUG({
474 if (TBI.Pred)
475 dbgs() << "BB#" << TBI.Pred->getNumber() << '\n';
476 else
477 dbgs() << "null\n";
478 });
479 // The trace leading to I is now known, compute the depth resources.
480 computeDepthResources(*I);
481 }
482
483 // Run a downwards post-order search for the trace end.
484 Bounds.Downward = true;
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000485 Bounds.Visited.clear();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000486 typedef po_ext_iterator<const MachineBasicBlock*, LoopBounds> DownwardPO;
487 for (DownwardPO I = po_ext_begin(MBB, Bounds), E = po_ext_end(MBB, Bounds);
488 I != E; ++I) {
489 DEBUG(dbgs() << " succ for BB#" << I->getNumber() << ": ");
490 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
491 // All the successors have been visited, pick the preferred one.
Jakob Stoklund Olesen0fc44862012-07-26 19:42:56 +0000492 TBI.Succ = pickTraceSucc(*I);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000493 DEBUG({
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000494 if (TBI.Succ)
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000495 dbgs() << "BB#" << TBI.Succ->getNumber() << '\n';
496 else
497 dbgs() << "null\n";
498 });
499 // The trace leaving I is now known, compute the height resources.
500 computeHeightResources(*I);
501 }
502}
503
504/// Invalidate traces through BadMBB.
505void
506MachineTraceMetrics::Ensemble::invalidate(const MachineBasicBlock *BadMBB) {
507 SmallVector<const MachineBasicBlock*, 16> WorkList;
508 TraceBlockInfo &BadTBI = BlockInfo[BadMBB->getNumber()];
509
510 // Invalidate height resources of blocks above MBB.
511 if (BadTBI.hasValidHeight()) {
512 BadTBI.invalidateHeight();
513 WorkList.push_back(BadMBB);
514 do {
515 const MachineBasicBlock *MBB = WorkList.pop_back_val();
516 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
517 << " height.\n");
518 // Find any MBB predecessors that have MBB as their preferred successor.
519 // They are the only ones that need to be invalidated.
520 for (MachineBasicBlock::const_pred_iterator
521 I = MBB->pred_begin(), E = MBB->pred_end(); I != E; ++I) {
522 TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000523 if (!TBI.hasValidHeight())
524 continue;
525 if (TBI.Succ == MBB) {
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000526 TBI.invalidateHeight();
527 WorkList.push_back(*I);
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000528 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000529 }
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000530 // Verify that TBI.Succ is actually a *I successor.
531 assert((!TBI.Succ || (*I)->isSuccessor(TBI.Succ)) && "CFG changed");
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000532 }
533 } while (!WorkList.empty());
534 }
535
536 // Invalidate depth resources of blocks below MBB.
537 if (BadTBI.hasValidDepth()) {
538 BadTBI.invalidateDepth();
539 WorkList.push_back(BadMBB);
540 do {
541 const MachineBasicBlock *MBB = WorkList.pop_back_val();
542 DEBUG(dbgs() << "Invalidate BB#" << MBB->getNumber() << ' ' << getName()
543 << " depth.\n");
544 // Find any MBB successors that have MBB as their preferred predecessor.
545 // They are the only ones that need to be invalidated.
546 for (MachineBasicBlock::const_succ_iterator
547 I = MBB->succ_begin(), E = MBB->succ_end(); I != E; ++I) {
548 TraceBlockInfo &TBI = BlockInfo[(*I)->getNumber()];
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000549 if (!TBI.hasValidDepth())
550 continue;
551 if (TBI.Pred == MBB) {
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000552 TBI.invalidateDepth();
553 WorkList.push_back(*I);
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000554 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000555 }
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000556 // Verify that TBI.Pred is actually a *I predecessor.
557 assert((!TBI.Pred || (*I)->isPredecessor(TBI.Pred)) && "CFG changed");
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000558 }
559 } while (!WorkList.empty());
560 }
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000561
562 // Clear any per-instruction data. We only have to do this for BadMBB itself
563 // because the instructions in that block may change. Other blocks may be
564 // invalidated, but their instructions will stay the same, so there is no
565 // need to erase the Cycle entries. They will be overwritten when we
566 // recompute.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700567 for (const auto &I : *BadMBB)
568 Cycles.erase(&I);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000569}
570
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000571void MachineTraceMetrics::Ensemble::verify() const {
572#ifndef NDEBUG
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000573 assert(BlockInfo.size() == MTM.MF->getNumBlockIDs() &&
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000574 "Outdated BlockInfo size");
575 for (unsigned Num = 0, e = BlockInfo.size(); Num != e; ++Num) {
576 const TraceBlockInfo &TBI = BlockInfo[Num];
577 if (TBI.hasValidDepth() && TBI.Pred) {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000578 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000579 assert(MBB->isPredecessor(TBI.Pred) && "CFG doesn't match trace");
580 assert(BlockInfo[TBI.Pred->getNumber()].hasValidDepth() &&
581 "Trace is broken, depth should have been invalidated.");
582 const MachineLoop *Loop = getLoopFor(MBB);
583 assert(!(Loop && MBB == Loop->getHeader()) && "Trace contains backedge");
584 }
585 if (TBI.hasValidHeight() && TBI.Succ) {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000586 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000587 assert(MBB->isSuccessor(TBI.Succ) && "CFG doesn't match trace");
588 assert(BlockInfo[TBI.Succ->getNumber()].hasValidHeight() &&
589 "Trace is broken, height should have been invalidated.");
590 const MachineLoop *Loop = getLoopFor(MBB);
591 const MachineLoop *SuccLoop = getLoopFor(TBI.Succ);
592 assert(!(Loop && Loop == SuccLoop && TBI.Succ == Loop->getHeader()) &&
593 "Trace contains backedge");
594 }
595 }
596#endif
597}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000598
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000599//===----------------------------------------------------------------------===//
600// Data Dependencies
601//===----------------------------------------------------------------------===//
602//
603// Compute the depth and height of each instruction based on data dependencies
604// and instruction latencies. These cycle numbers assume that the CPU can issue
605// an infinite number of instructions per cycle as long as their dependencies
606// are ready.
607
608// A data dependency is represented as a defining MI and operand numbers on the
609// defining and using MI.
610namespace {
611struct DataDep {
612 const MachineInstr *DefMI;
613 unsigned DefOp;
614 unsigned UseOp;
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000615
616 DataDep(const MachineInstr *DefMI, unsigned DefOp, unsigned UseOp)
617 : DefMI(DefMI), DefOp(DefOp), UseOp(UseOp) {}
618
619 /// Create a DataDep from an SSA form virtual register.
620 DataDep(const MachineRegisterInfo *MRI, unsigned VirtReg, unsigned UseOp)
621 : UseOp(UseOp) {
622 assert(TargetRegisterInfo::isVirtualRegister(VirtReg));
623 MachineRegisterInfo::def_iterator DefI = MRI->def_begin(VirtReg);
624 assert(!DefI.atEnd() && "Register has no defs");
Stephen Hines36b56882014-04-23 16:57:46 -0700625 DefMI = DefI->getParent();
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000626 DefOp = DefI.getOperandNo();
627 assert((++DefI).atEnd() && "Register has multiple defs");
628 }
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000629};
630}
631
632// Get the input data dependencies that must be ready before UseMI can issue.
633// Return true if UseMI has any physreg operands.
634static bool getDataDeps(const MachineInstr *UseMI,
635 SmallVectorImpl<DataDep> &Deps,
636 const MachineRegisterInfo *MRI) {
637 bool HasPhysRegs = false;
638 for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
639 if (!MO->isReg())
640 continue;
641 unsigned Reg = MO->getReg();
642 if (!Reg)
643 continue;
644 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
645 HasPhysRegs = true;
646 continue;
647 }
648 // Collect virtual register reads.
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000649 if (MO->readsReg())
650 Deps.push_back(DataDep(MRI, Reg, MO.getOperandNo()));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000651 }
652 return HasPhysRegs;
653}
654
655// Get the input data dependencies of a PHI instruction, using Pred as the
656// preferred predecessor.
657// This will add at most one dependency to Deps.
658static void getPHIDeps(const MachineInstr *UseMI,
659 SmallVectorImpl<DataDep> &Deps,
660 const MachineBasicBlock *Pred,
661 const MachineRegisterInfo *MRI) {
662 // No predecessor at the beginning of a trace. Ignore dependencies.
663 if (!Pred)
664 return;
665 assert(UseMI->isPHI() && UseMI->getNumOperands() % 2 && "Bad PHI");
666 for (unsigned i = 1; i != UseMI->getNumOperands(); i += 2) {
667 if (UseMI->getOperand(i + 1).getMBB() == Pred) {
668 unsigned Reg = UseMI->getOperand(i).getReg();
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000669 Deps.push_back(DataDep(MRI, Reg, i));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000670 return;
671 }
672 }
673}
674
675// Keep track of physreg data dependencies by recording each live register unit.
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000676// Associate each regunit with an instruction operand. Depending on the
677// direction instructions are scanned, it could be the operand that defined the
678// regunit, or the highest operand to read the regunit.
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000679namespace {
680struct LiveRegUnit {
681 unsigned RegUnit;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000682 unsigned Cycle;
683 const MachineInstr *MI;
684 unsigned Op;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000685
686 unsigned getSparseSetIndex() const { return RegUnit; }
687
Stephen Hinesdce4a402014-05-29 02:49:00 -0700688 LiveRegUnit(unsigned RU) : RegUnit(RU), Cycle(0), MI(nullptr), Op(0) {}
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000689};
690}
691
692// Identify physreg dependencies for UseMI, and update the live regunit
693// tracking set when scanning instructions downwards.
694static void updatePhysDepsDownwards(const MachineInstr *UseMI,
695 SmallVectorImpl<DataDep> &Deps,
696 SparseSet<LiveRegUnit> &RegUnits,
697 const TargetRegisterInfo *TRI) {
698 SmallVector<unsigned, 8> Kills;
699 SmallVector<unsigned, 8> LiveDefOps;
700
701 for (ConstMIOperands MO(UseMI); MO.isValid(); ++MO) {
702 if (!MO->isReg())
703 continue;
704 unsigned Reg = MO->getReg();
705 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
706 continue;
707 // Track live defs and kills for updating RegUnits.
708 if (MO->isDef()) {
709 if (MO->isDead())
710 Kills.push_back(Reg);
711 else
712 LiveDefOps.push_back(MO.getOperandNo());
713 } else if (MO->isKill())
714 Kills.push_back(Reg);
715 // Identify dependencies.
716 if (!MO->readsReg())
717 continue;
718 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
719 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
720 if (I == RegUnits.end())
721 continue;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000722 Deps.push_back(DataDep(I->MI, I->Op, MO.getOperandNo()));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000723 break;
724 }
725 }
726
727 // Update RegUnits to reflect live registers after UseMI.
728 // First kills.
729 for (unsigned i = 0, e = Kills.size(); i != e; ++i)
730 for (MCRegUnitIterator Units(Kills[i], TRI); Units.isValid(); ++Units)
731 RegUnits.erase(*Units);
732
733 // Second, live defs.
734 for (unsigned i = 0, e = LiveDefOps.size(); i != e; ++i) {
735 unsigned DefOp = LiveDefOps[i];
736 for (MCRegUnitIterator Units(UseMI->getOperand(DefOp).getReg(), TRI);
737 Units.isValid(); ++Units) {
738 LiveRegUnit &LRU = RegUnits[*Units];
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000739 LRU.MI = UseMI;
740 LRU.Op = DefOp;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000741 }
742 }
743}
744
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000745/// The length of the critical path through a trace is the maximum of two path
746/// lengths:
747///
748/// 1. The maximum height+depth over all instructions in the trace center block.
749///
750/// 2. The longest cross-block dependency chain. For small blocks, it is
751/// possible that the critical path through the trace doesn't include any
752/// instructions in the block.
753///
754/// This function computes the second number from the live-in list of the
755/// center block.
756unsigned MachineTraceMetrics::Ensemble::
757computeCrossBlockCriticalPath(const TraceBlockInfo &TBI) {
758 assert(TBI.HasValidInstrDepths && "Missing depth info");
759 assert(TBI.HasValidInstrHeights && "Missing height info");
760 unsigned MaxLen = 0;
761 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
762 const LiveInReg &LIR = TBI.LiveIns[i];
763 if (!TargetRegisterInfo::isVirtualRegister(LIR.Reg))
764 continue;
765 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
766 // Ignore dependencies outside the current trace.
767 const TraceBlockInfo &DefTBI = BlockInfo[DefMI->getParent()->getNumber()];
Jakob Stoklund Olesen6ffcd5e2013-03-07 23:55:49 +0000768 if (!DefTBI.isUsefulDominator(TBI))
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000769 continue;
770 unsigned Len = LIR.Height + Cycles[DefMI].Depth;
771 MaxLen = std::max(MaxLen, Len);
772 }
773 return MaxLen;
774}
775
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000776/// Compute instruction depths for all instructions above or in MBB in its
777/// trace. This assumes that the trace through MBB has already been computed.
778void MachineTraceMetrics::Ensemble::
779computeInstrDepths(const MachineBasicBlock *MBB) {
780 // The top of the trace may already be computed, and HasValidInstrDepths
781 // implies Head->HasValidInstrDepths, so we only need to start from the first
782 // block in the trace that needs to be recomputed.
783 SmallVector<const MachineBasicBlock*, 8> Stack;
784 do {
785 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
786 assert(TBI.hasValidDepth() && "Incomplete trace");
787 if (TBI.HasValidInstrDepths)
788 break;
789 Stack.push_back(MBB);
790 MBB = TBI.Pred;
791 } while (MBB);
792
793 // FIXME: If MBB is non-null at this point, it is the last pre-computed block
794 // in the trace. We should track any live-out physregs that were defined in
795 // the trace. This is quite rare in SSA form, typically created by CSE
796 // hoisting a compare.
797 SparseSet<LiveRegUnit> RegUnits;
798 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
799
800 // Go through trace blocks in top-down order, stopping after the center block.
801 SmallVector<DataDep, 8> Deps;
802 while (!Stack.empty()) {
803 MBB = Stack.pop_back_val();
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000804 DEBUG(dbgs() << "\nDepths for BB#" << MBB->getNumber() << ":\n");
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000805 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
806 TBI.HasValidInstrDepths = true;
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000807 TBI.CriticalPath = 0;
808
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000809 // Print out resource depths here as well.
810 DEBUG({
811 dbgs() << format("%7u Instructions\n", TBI.InstrDepth);
812 ArrayRef<unsigned> PRDepths = getProcResourceDepths(MBB->getNumber());
813 for (unsigned K = 0; K != PRDepths.size(); ++K)
814 if (PRDepths[K]) {
815 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
816 dbgs() << format("%6uc @ ", MTM.getCycles(PRDepths[K]))
817 << MTM.SchedModel.getProcResource(K)->Name << " ("
818 << PRDepths[K]/Factor << " ops x" << Factor << ")\n";
819 }
820 });
821
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000822 // Also compute the critical path length through MBB when possible.
823 if (TBI.HasValidInstrHeights)
824 TBI.CriticalPath = computeCrossBlockCriticalPath(TBI);
825
Stephen Hinesdce4a402014-05-29 02:49:00 -0700826 for (const auto &UseMI : *MBB) {
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000827 // Collect all data dependencies.
828 Deps.clear();
Stephen Hinesdce4a402014-05-29 02:49:00 -0700829 if (UseMI.isPHI())
830 getPHIDeps(&UseMI, Deps, TBI.Pred, MTM.MRI);
831 else if (getDataDeps(&UseMI, Deps, MTM.MRI))
832 updatePhysDepsDownwards(&UseMI, Deps, RegUnits, MTM.TRI);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000833
834 // Filter and process dependencies, computing the earliest issue cycle.
835 unsigned Cycle = 0;
836 for (unsigned i = 0, e = Deps.size(); i != e; ++i) {
837 const DataDep &Dep = Deps[i];
838 const TraceBlockInfo&DepTBI =
839 BlockInfo[Dep.DefMI->getParent()->getNumber()];
840 // Ignore dependencies from outside the current trace.
Jakob Stoklund Olesen6ffcd5e2013-03-07 23:55:49 +0000841 if (!DepTBI.isUsefulDominator(TBI))
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000842 continue;
843 assert(DepTBI.HasValidInstrDepths && "Inconsistent dependency");
844 unsigned DepCycle = Cycles.lookup(Dep.DefMI).Depth;
845 // Add latency if DefMI is a real instruction. Transients get latency 0.
846 if (!Dep.DefMI->isTransient())
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000847 DepCycle += MTM.SchedModel
Stephen Hinesdce4a402014-05-29 02:49:00 -0700848 .computeOperandLatency(Dep.DefMI, Dep.DefOp, &UseMI, Dep.UseOp);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000849 Cycle = std::max(Cycle, DepCycle);
850 }
851 // Remember the instruction depth.
Stephen Hinesdce4a402014-05-29 02:49:00 -0700852 InstrCycles &MICycles = Cycles[&UseMI];
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000853 MICycles.Depth = Cycle;
854
855 if (!TBI.HasValidInstrHeights) {
Stephen Hinesdce4a402014-05-29 02:49:00 -0700856 DEBUG(dbgs() << Cycle << '\t' << UseMI);
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000857 continue;
858 }
859 // Update critical path length.
860 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Height);
Stephen Hinesdce4a402014-05-29 02:49:00 -0700861 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << UseMI);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000862 }
863 }
864}
865
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000866// Identify physreg dependencies for MI when scanning instructions upwards.
867// Return the issue height of MI after considering any live regunits.
868// Height is the issue height computed from virtual register dependencies alone.
869static unsigned updatePhysDepsUpwards(const MachineInstr *MI, unsigned Height,
870 SparseSet<LiveRegUnit> &RegUnits,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000871 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000872 const TargetInstrInfo *TII,
873 const TargetRegisterInfo *TRI) {
874 SmallVector<unsigned, 8> ReadOps;
875 for (ConstMIOperands MO(MI); MO.isValid(); ++MO) {
876 if (!MO->isReg())
877 continue;
878 unsigned Reg = MO->getReg();
879 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
880 continue;
881 if (MO->readsReg())
882 ReadOps.push_back(MO.getOperandNo());
883 if (!MO->isDef())
884 continue;
885 // This is a def of Reg. Remove corresponding entries from RegUnits, and
886 // update MI Height to consider the physreg dependencies.
887 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
888 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
889 if (I == RegUnits.end())
890 continue;
891 unsigned DepHeight = I->Cycle;
892 if (!MI->isTransient()) {
893 // We may not know the UseMI of this dependency, if it came from the
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000894 // live-in list. SchedModel can handle a NULL UseMI.
895 DepHeight += SchedModel
Andrew Trickb86a0cd2013-06-15 04:49:57 +0000896 .computeOperandLatency(MI, MO.getOperandNo(), I->MI, I->Op);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000897 }
898 Height = std::max(Height, DepHeight);
899 // This regunit is dead above MI.
900 RegUnits.erase(I);
901 }
902 }
903
904 // Now we know the height of MI. Update any regunits read.
905 for (unsigned i = 0, e = ReadOps.size(); i != e; ++i) {
906 unsigned Reg = MI->getOperand(ReadOps[i]).getReg();
907 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
908 LiveRegUnit &LRU = RegUnits[*Units];
909 // Set the height to the highest reader of the unit.
910 if (LRU.Cycle <= Height && LRU.MI != MI) {
911 LRU.Cycle = Height;
912 LRU.MI = MI;
913 LRU.Op = ReadOps[i];
914 }
915 }
916 }
917
918 return Height;
919}
920
921
922typedef DenseMap<const MachineInstr *, unsigned> MIHeightMap;
923
924// Push the height of DefMI upwards if required to match UseMI.
925// Return true if this is the first time DefMI was seen.
926static bool pushDepHeight(const DataDep &Dep,
927 const MachineInstr *UseMI, unsigned UseHeight,
928 MIHeightMap &Heights,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000929 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000930 const TargetInstrInfo *TII) {
931 // Adjust height by Dep.DefMI latency.
932 if (!Dep.DefMI->isTransient())
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000933 UseHeight += SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp,
Andrew Trickb86a0cd2013-06-15 04:49:57 +0000934 UseMI, Dep.UseOp);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000935
936 // Update Heights[DefMI] to be the maximum height seen.
937 MIHeightMap::iterator I;
938 bool New;
Stephen Hines36b56882014-04-23 16:57:46 -0700939 std::tie(I, New) = Heights.insert(std::make_pair(Dep.DefMI, UseHeight));
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000940 if (New)
941 return true;
942
943 // DefMI has been pushed before. Give it the max height.
944 if (I->second < UseHeight)
945 I->second = UseHeight;
946 return false;
947}
948
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000949/// Assuming that the virtual register defined by DefMI:DefOp was used by
950/// Trace.back(), add it to the live-in lists of all the blocks in Trace. Stop
951/// when reaching the block that contains DefMI.
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000952void MachineTraceMetrics::Ensemble::
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000953addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000954 ArrayRef<const MachineBasicBlock*> Trace) {
955 assert(!Trace.empty() && "Trace should contain at least one block");
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000956 unsigned Reg = DefMI->getOperand(DefOp).getReg();
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000957 assert(TargetRegisterInfo::isVirtualRegister(Reg));
958 const MachineBasicBlock *DefMBB = DefMI->getParent();
959
960 // Reg is live-in to all blocks in Trace that follow DefMBB.
961 for (unsigned i = Trace.size(); i; --i) {
962 const MachineBasicBlock *MBB = Trace[i-1];
963 if (MBB == DefMBB)
964 return;
965 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
966 // Just add the register. The height will be updated later.
967 TBI.LiveIns.push_back(Reg);
968 }
969}
970
971/// Compute instruction heights in the trace through MBB. This updates MBB and
972/// the blocks below it in the trace. It is assumed that the trace has already
973/// been computed.
974void MachineTraceMetrics::Ensemble::
975computeInstrHeights(const MachineBasicBlock *MBB) {
976 // The bottom of the trace may already be computed.
977 // Find the blocks that need updating.
978 SmallVector<const MachineBasicBlock*, 8> Stack;
979 do {
980 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
981 assert(TBI.hasValidHeight() && "Incomplete trace");
982 if (TBI.HasValidInstrHeights)
983 break;
984 Stack.push_back(MBB);
985 TBI.LiveIns.clear();
986 MBB = TBI.Succ;
987 } while (MBB);
988
989 // As we move upwards in the trace, keep track of instructions that are
990 // required by deeper trace instructions. Map MI -> height required so far.
991 MIHeightMap Heights;
992
993 // For physregs, the def isn't known when we see the use.
994 // Instead, keep track of the highest use of each regunit.
995 SparseSet<LiveRegUnit> RegUnits;
996 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
997
998 // If the bottom of the trace was already precomputed, initialize heights
999 // from its live-in list.
1000 // MBB is the highest precomputed block in the trace.
1001 if (MBB) {
1002 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1003 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
1004 LiveInReg LI = TBI.LiveIns[i];
1005 if (TargetRegisterInfo::isVirtualRegister(LI.Reg)) {
1006 // For virtual registers, the def latency is included.
1007 unsigned &Height = Heights[MTM.MRI->getVRegDef(LI.Reg)];
1008 if (Height < LI.Height)
1009 Height = LI.Height;
1010 } else {
1011 // For register units, the def latency is not included because we don't
1012 // know the def yet.
1013 RegUnits[LI.Reg].Cycle = LI.Height;
1014 }
1015 }
1016 }
1017
1018 // Go through the trace blocks in bottom-up order.
1019 SmallVector<DataDep, 8> Deps;
1020 for (;!Stack.empty(); Stack.pop_back()) {
1021 MBB = Stack.back();
1022 DEBUG(dbgs() << "Heights for BB#" << MBB->getNumber() << ":\n");
1023 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1024 TBI.HasValidInstrHeights = true;
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001025 TBI.CriticalPath = 0;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001026
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001027 DEBUG({
1028 dbgs() << format("%7u Instructions\n", TBI.InstrHeight);
1029 ArrayRef<unsigned> PRHeights = getProcResourceHeights(MBB->getNumber());
1030 for (unsigned K = 0; K != PRHeights.size(); ++K)
1031 if (PRHeights[K]) {
1032 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
1033 dbgs() << format("%6uc @ ", MTM.getCycles(PRHeights[K]))
1034 << MTM.SchedModel.getProcResource(K)->Name << " ("
1035 << PRHeights[K]/Factor << " ops x" << Factor << ")\n";
1036 }
1037 });
1038
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001039 // Get dependencies from PHIs in the trace successor.
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001040 const MachineBasicBlock *Succ = TBI.Succ;
1041 // If MBB is the last block in the trace, and it has a back-edge to the
1042 // loop header, get loop-carried dependencies from PHIs in the header. For
1043 // that purpose, pretend that all the loop header PHIs have height 0.
1044 if (!Succ)
1045 if (const MachineLoop *Loop = getLoopFor(MBB))
1046 if (MBB->isSuccessor(Loop->getHeader()))
1047 Succ = Loop->getHeader();
1048
1049 if (Succ) {
Stephen Hinesdce4a402014-05-29 02:49:00 -07001050 for (const auto &PHI : *Succ) {
1051 if (!PHI.isPHI())
1052 break;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001053 Deps.clear();
Stephen Hinesdce4a402014-05-29 02:49:00 -07001054 getPHIDeps(&PHI, Deps, MBB, MTM.MRI);
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001055 if (!Deps.empty()) {
1056 // Loop header PHI heights are all 0.
Stephen Hinesdce4a402014-05-29 02:49:00 -07001057 unsigned Height = TBI.Succ ? Cycles.lookup(&PHI).Height : 0;
1058 DEBUG(dbgs() << "pred\t" << Height << '\t' << PHI);
1059 if (pushDepHeight(Deps.front(), &PHI, Height,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001060 Heights, MTM.SchedModel, MTM.TII))
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +00001061 addLiveIns(Deps.front().DefMI, Deps.front().DefOp, Stack);
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001062 }
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001063 }
1064 }
1065
1066 // Go through the block backwards.
1067 for (MachineBasicBlock::const_iterator BI = MBB->end(), BB = MBB->begin();
1068 BI != BB;) {
1069 const MachineInstr *MI = --BI;
1070
1071 // Find the MI height as determined by virtual register uses in the
1072 // trace below.
1073 unsigned Cycle = 0;
1074 MIHeightMap::iterator HeightI = Heights.find(MI);
1075 if (HeightI != Heights.end()) {
1076 Cycle = HeightI->second;
1077 // We won't be seeing any more MI uses.
1078 Heights.erase(HeightI);
1079 }
1080
1081 // Don't process PHI deps. They depend on the specific predecessor, and
1082 // we'll get them when visiting the predecessor.
1083 Deps.clear();
1084 bool HasPhysRegs = !MI->isPHI() && getDataDeps(MI, Deps, MTM.MRI);
1085
1086 // There may also be regunit dependencies to include in the height.
1087 if (HasPhysRegs)
1088 Cycle = updatePhysDepsUpwards(MI, Cycle, RegUnits,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001089 MTM.SchedModel, MTM.TII, MTM.TRI);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001090
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001091 // Update the required height of any virtual registers read by MI.
1092 for (unsigned i = 0, e = Deps.size(); i != e; ++i)
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001093 if (pushDepHeight(Deps[i], MI, Cycle, Heights, MTM.SchedModel, MTM.TII))
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +00001094 addLiveIns(Deps[i].DefMI, Deps[i].DefOp, Stack);
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001095
1096 InstrCycles &MICycles = Cycles[MI];
1097 MICycles.Height = Cycle;
1098 if (!TBI.HasValidInstrDepths) {
1099 DEBUG(dbgs() << Cycle << '\t' << *MI);
1100 continue;
1101 }
1102 // Update critical path length.
1103 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Depth);
1104 DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << *MI);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001105 }
1106
1107 // Update virtual live-in heights. They were added by addLiveIns() with a 0
1108 // height because the final height isn't known until now.
1109 DEBUG(dbgs() << "BB#" << MBB->getNumber() << " Live-ins:");
1110 for (unsigned i = 0, e = TBI.LiveIns.size(); i != e; ++i) {
1111 LiveInReg &LIR = TBI.LiveIns[i];
1112 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
1113 LIR.Height = Heights.lookup(DefMI);
1114 DEBUG(dbgs() << ' ' << PrintReg(LIR.Reg) << '@' << LIR.Height);
1115 }
1116
1117 // Transfer the live regunits to the live-in list.
1118 for (SparseSet<LiveRegUnit>::const_iterator
1119 RI = RegUnits.begin(), RE = RegUnits.end(); RI != RE; ++RI) {
1120 TBI.LiveIns.push_back(LiveInReg(RI->RegUnit, RI->Cycle));
1121 DEBUG(dbgs() << ' ' << PrintRegUnit(RI->RegUnit, MTM.TRI)
1122 << '@' << RI->Cycle);
1123 }
1124 DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001125
1126 if (!TBI.HasValidInstrDepths)
1127 continue;
1128 // Add live-ins to the critical path length.
1129 TBI.CriticalPath = std::max(TBI.CriticalPath,
1130 computeCrossBlockCriticalPath(TBI));
1131 DEBUG(dbgs() << "Critical path: " << TBI.CriticalPath << '\n');
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001132 }
1133}
1134
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001135MachineTraceMetrics::Trace
1136MachineTraceMetrics::Ensemble::getTrace(const MachineBasicBlock *MBB) {
1137 // FIXME: Check cache tags, recompute as needed.
1138 computeTrace(MBB);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +00001139 computeInstrDepths(MBB);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001140 computeInstrHeights(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001141 return Trace(*this, BlockInfo[MBB->getNumber()]);
1142}
1143
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001144unsigned
1145MachineTraceMetrics::Trace::getInstrSlack(const MachineInstr *MI) const {
1146 assert(MI && "Not an instruction.");
1147 assert(getBlockNum() == unsigned(MI->getParent()->getNumber()) &&
1148 "MI must be in the trace center block");
1149 InstrCycles Cyc = getInstrCycles(MI);
1150 return getCriticalPath() - (Cyc.Depth + Cyc.Height);
1151}
1152
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001153unsigned
1154MachineTraceMetrics::Trace::getPHIDepth(const MachineInstr *PHI) const {
1155 const MachineBasicBlock *MBB = TE.MTM.MF->getBlockNumbered(getBlockNum());
1156 SmallVector<DataDep, 1> Deps;
1157 getPHIDeps(PHI, Deps, MBB, TE.MTM.MRI);
1158 assert(Deps.size() == 1 && "PHI doesn't have MBB as a predecessor");
1159 DataDep &Dep = Deps.front();
1160 unsigned DepCycle = getInstrCycles(Dep.DefMI).Depth;
1161 // Add latency if DefMI is a real instruction. Transients get latency 0.
1162 if (!Dep.DefMI->isTransient())
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001163 DepCycle += TE.MTM.SchedModel
Andrew Trickb86a0cd2013-06-15 04:49:57 +00001164 .computeOperandLatency(Dep.DefMI, Dep.DefOp, PHI, Dep.UseOp);
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001165 return DepCycle;
1166}
1167
Stephen Hines37ed9c12014-12-01 14:51:49 -08001168/// When bottom is set include instructions in current block in estimate.
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001169unsigned MachineTraceMetrics::Trace::getResourceDepth(bool Bottom) const {
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001170 // Find the limiting processor resource.
1171 // Numbers have been pre-scaled to be comparable.
1172 unsigned PRMax = 0;
1173 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1174 if (Bottom) {
1175 ArrayRef<unsigned> PRCycles = TE.MTM.getProcResourceCycles(getBlockNum());
1176 for (unsigned K = 0; K != PRDepths.size(); ++K)
1177 PRMax = std::max(PRMax, PRDepths[K] + PRCycles[K]);
1178 } else {
1179 for (unsigned K = 0; K != PRDepths.size(); ++K)
1180 PRMax = std::max(PRMax, PRDepths[K]);
1181 }
1182 // Convert to cycle count.
1183 PRMax = TE.MTM.getCycles(PRMax);
1184
Stephen Hines37ed9c12014-12-01 14:51:49 -08001185 /// All instructions before current block
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001186 unsigned Instrs = TBI.InstrDepth;
Stephen Hines37ed9c12014-12-01 14:51:49 -08001187 // plus instructions in current block
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001188 if (Bottom)
1189 Instrs += TE.MTM.BlockInfo[getBlockNum()].InstrCount;
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001190 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1191 Instrs /= IW;
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001192 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001193 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001194}
1195
Stephen Hines37ed9c12014-12-01 14:51:49 -08001196unsigned MachineTraceMetrics::Trace::getResourceLength(
1197 ArrayRef<const MachineBasicBlock *> Extrablocks,
1198 ArrayRef<const MCSchedClassDesc *> ExtraInstrs,
1199 ArrayRef<const MCSchedClassDesc *> RemoveInstrs) const {
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001200 // Add up resources above and below the center block.
1201 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1202 ArrayRef<unsigned> PRHeights = TE.getProcResourceHeights(getBlockNum());
1203 unsigned PRMax = 0;
Stephen Hines37ed9c12014-12-01 14:51:49 -08001204
1205 // Capture computing cycles from extra instructions
1206 auto extraCycles = [this](ArrayRef<const MCSchedClassDesc *> Instrs,
1207 unsigned ResourceIdx)
1208 ->unsigned {
1209 unsigned Cycles = 0;
1210 for (unsigned I = 0; I != Instrs.size(); ++I) {
1211 const MCSchedClassDesc *SC = Instrs[I];
1212 if (!SC->isValid())
1213 continue;
1214 for (TargetSchedModel::ProcResIter
1215 PI = TE.MTM.SchedModel.getWriteProcResBegin(SC),
1216 PE = TE.MTM.SchedModel.getWriteProcResEnd(SC);
1217 PI != PE; ++PI) {
1218 if (PI->ProcResourceIdx != ResourceIdx)
1219 continue;
1220 Cycles +=
1221 (PI->Cycles * TE.MTM.SchedModel.getResourceFactor(ResourceIdx));
1222 }
1223 }
1224 return Cycles;
1225 };
1226
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001227 for (unsigned K = 0; K != PRDepths.size(); ++K) {
1228 unsigned PRCycles = PRDepths[K] + PRHeights[K];
1229 for (unsigned I = 0; I != Extrablocks.size(); ++I)
1230 PRCycles += TE.MTM.getProcResourceCycles(Extrablocks[I]->getNumber())[K];
Stephen Hines37ed9c12014-12-01 14:51:49 -08001231 PRCycles += extraCycles(ExtraInstrs, K);
1232 PRCycles -= extraCycles(RemoveInstrs, K);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001233 PRMax = std::max(PRMax, PRCycles);
1234 }
1235 // Convert to cycle count.
1236 PRMax = TE.MTM.getCycles(PRMax);
1237
Stephen Hines37ed9c12014-12-01 14:51:49 -08001238 // Instrs: #instructions in current trace outside current block.
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001239 unsigned Instrs = TBI.InstrDepth + TBI.InstrHeight;
Stephen Hines37ed9c12014-12-01 14:51:49 -08001240 // Add instruction count from the extra blocks.
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001241 for (unsigned i = 0, e = Extrablocks.size(); i != e; ++i)
1242 Instrs += TE.MTM.getResources(Extrablocks[i])->InstrCount;
Stephen Hines37ed9c12014-12-01 14:51:49 -08001243 Instrs += ExtraInstrs.size();
1244 Instrs -= RemoveInstrs.size();
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001245 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1246 Instrs /= IW;
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001247 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001248 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001249}
1250
Stephen Hines37ed9c12014-12-01 14:51:49 -08001251bool MachineTraceMetrics::Trace::isDepInTrace(const MachineInstr *DefMI,
1252 const MachineInstr *UseMI) const {
1253 if (DefMI->getParent() == UseMI->getParent())
1254 return true;
1255
1256 const TraceBlockInfo &DepTBI = TE.BlockInfo[DefMI->getParent()->getNumber()];
1257 const TraceBlockInfo &TBI = TE.BlockInfo[UseMI->getParent()->getNumber()];
1258
1259 return DepTBI.isUsefulDominator(TBI);
1260}
1261
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001262void MachineTraceMetrics::Ensemble::print(raw_ostream &OS) const {
1263 OS << getName() << " ensemble:\n";
1264 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
1265 OS << " BB#" << i << '\t';
1266 BlockInfo[i].print(OS);
1267 OS << '\n';
1268 }
1269}
1270
1271void MachineTraceMetrics::TraceBlockInfo::print(raw_ostream &OS) const {
1272 if (hasValidDepth()) {
1273 OS << "depth=" << InstrDepth;
1274 if (Pred)
1275 OS << " pred=BB#" << Pred->getNumber();
1276 else
1277 OS << " pred=null";
1278 OS << " head=BB#" << Head;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +00001279 if (HasValidInstrDepths)
1280 OS << " +instrs";
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001281 } else
1282 OS << "depth invalid";
1283 OS << ", ";
1284 if (hasValidHeight()) {
1285 OS << "height=" << InstrHeight;
1286 if (Succ)
1287 OS << " succ=BB#" << Succ->getNumber();
1288 else
1289 OS << " succ=null";
1290 OS << " tail=BB#" << Tail;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +00001291 if (HasValidInstrHeights)
1292 OS << " +instrs";
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001293 } else
1294 OS << "height invalid";
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001295 if (HasValidInstrDepths && HasValidInstrHeights)
1296 OS << ", crit=" << CriticalPath;
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001297}
1298
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001299void MachineTraceMetrics::Trace::print(raw_ostream &OS) const {
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001300 unsigned MBBNum = &TBI - &TE.BlockInfo[0];
1301
1302 OS << TE.getName() << " trace BB#" << TBI.Head << " --> BB#" << MBBNum
1303 << " --> BB#" << TBI.Tail << ':';
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001304 if (TBI.hasValidHeight() && TBI.hasValidDepth())
1305 OS << ' ' << getInstrCount() << " instrs.";
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001306 if (TBI.HasValidInstrDepths && TBI.HasValidInstrHeights)
1307 OS << ' ' << TBI.CriticalPath << " cycles.";
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001308
1309 const MachineTraceMetrics::TraceBlockInfo *Block = &TBI;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001310 OS << "\nBB#" << MBBNum;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001311 while (Block->hasValidDepth() && Block->Pred) {
1312 unsigned Num = Block->Pred->getNumber();
1313 OS << " <- BB#" << Num;
1314 Block = &TE.BlockInfo[Num];
1315 }
1316
1317 Block = &TBI;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001318 OS << "\n ";
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001319 while (Block->hasValidHeight() && Block->Succ) {
1320 unsigned Num = Block->Succ->getNumber();
1321 OS << " -> BB#" << Num;
1322 Block = &TE.BlockInfo[Num];
1323 }
1324 OS << '\n';
1325}