blob: e62ed3094651e9113271b2ca10c661c00c54c515 [file] [log] [blame]
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +00001//===- lib/CodeGen/MachineTraceMetrics.cpp --------------------------------===//
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00002//
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
Chandler Carruthe3e43d92017-06-06 11:49:48 +000010#include "llvm/CodeGen/MachineTraceMetrics.h"
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000011#include "llvm/ADT/ArrayRef.h"
12#include "llvm/ADT/DenseMap.h"
13#include "llvm/ADT/Optional.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000014#include "llvm/ADT/PostOrderIterator.h"
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000015#include "llvm/ADT/SmallPtrSet.h"
16#include "llvm/ADT/SmallVector.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000017#include "llvm/ADT/SparseSet.h"
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000018#include "llvm/CodeGen/MachineBasicBlock.h"
19#include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000020#include "llvm/CodeGen/MachineFunction.h"
21#include "llvm/CodeGen/MachineInstr.h"
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000022#include "llvm/CodeGen/MachineLoopInfo.h"
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000023#include "llvm/CodeGen/MachineOperand.h"
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000024#include "llvm/CodeGen/MachineRegisterInfo.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000025#include "llvm/CodeGen/TargetRegisterInfo.h"
Eugene Zelenko8fd05042017-09-11 23:00:48 +000026#include "llvm/CodeGen/TargetSchedule.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000027#include "llvm/CodeGen/TargetSubtargetInfo.h"
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000028#include "llvm/MC/MCRegisterInfo.h"
29#include "llvm/Pass.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000030#include "llvm/Support/Debug.h"
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000031#include "llvm/Support/ErrorHandling.h"
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +000032#include "llvm/Support/Format.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000033#include "llvm/Support/raw_ostream.h"
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000034#include <algorithm>
35#include <cassert>
36#include <iterator>
37#include <tuple>
38#include <utility>
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000039
40using namespace llvm;
41
Chandler Carruth8677f2f2014-04-22 02:02:50 +000042#define DEBUG_TYPE "machine-trace-metrics"
43
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000044char MachineTraceMetrics::ID = 0;
Eugene Zelenko8fd05042017-09-11 23:00:48 +000045
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000046char &llvm::MachineTraceMetricsID = MachineTraceMetrics::ID;
47
Matthias Braun94c49042017-05-25 21:26:32 +000048INITIALIZE_PASS_BEGIN(MachineTraceMetrics, DEBUG_TYPE,
49 "Machine Trace Metrics", false, true)
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000050INITIALIZE_PASS_DEPENDENCY(MachineBranchProbabilityInfo)
51INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
Matthias Braun94c49042017-05-25 21:26:32 +000052INITIALIZE_PASS_END(MachineTraceMetrics, DEBUG_TYPE,
53 "Machine Trace Metrics", false, true)
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000054
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +000055MachineTraceMetrics::MachineTraceMetrics() : MachineFunctionPass(ID) {
Benjamin Kramer15c435a2014-04-12 16:15:53 +000056 std::fill(std::begin(Ensembles), std::end(Ensembles), nullptr);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000057}
58
59void MachineTraceMetrics::getAnalysisUsage(AnalysisUsage &AU) const {
60 AU.setPreservesAll();
61 AU.addRequired<MachineBranchProbabilityInfo>();
62 AU.addRequired<MachineLoopInfo>();
63 MachineFunctionPass::getAnalysisUsage(AU);
64}
65
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +000066bool MachineTraceMetrics::runOnMachineFunction(MachineFunction &Func) {
67 MF = &Func;
Eric Christopher72e75862015-01-27 07:31:29 +000068 const TargetSubtargetInfo &ST = MF->getSubtarget();
69 TII = ST.getInstrInfo();
70 TRI = ST.getRegisterInfo();
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +000071 MRI = &MF->getRegInfo();
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000072 Loops = &getAnalysis<MachineLoopInfo>();
Sanjay Patele599cea2018-04-08 19:56:04 +000073 SchedModel.init(&ST);
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +000074 BlockInfo.resize(MF->getNumBlockIDs());
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +000075 ProcResourceCycles.resize(MF->getNumBlockIDs() *
76 SchedModel.getNumProcResourceKinds());
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000077 return false;
78}
79
80void MachineTraceMetrics::releaseMemory() {
Craig Topper4ba84432014-04-14 00:51:57 +000081 MF = nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000082 BlockInfo.clear();
83 for (unsigned i = 0; i != TS_NumStrategies; ++i) {
84 delete Ensembles[i];
Craig Topper4ba84432014-04-14 00:51:57 +000085 Ensembles[i] = nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000086 }
87}
88
89//===----------------------------------------------------------------------===//
90// Fixed block information
91//===----------------------------------------------------------------------===//
92//
93// The number of instructions in a basic block and the CPU resources used by
94// those instructions don't depend on any given trace strategy.
95
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +000096/// Compute the resource usage in basic block MBB.
97const MachineTraceMetrics::FixedBlockInfo*
98MachineTraceMetrics::getResources(const MachineBasicBlock *MBB) {
99 assert(MBB && "No basic block");
100 FixedBlockInfo *FBI = &BlockInfo[MBB->getNumber()];
101 if (FBI->hasResources())
102 return FBI;
103
104 // Compute resource usage in the block.
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000105 FBI->HasCalls = false;
106 unsigned InstrCount = 0;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000107
108 // Add up per-processor resource cycles as well.
109 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
110 SmallVector<unsigned, 32> PRCycles(PRKinds);
111
Alexey Samsonov84678122014-04-30 22:17:38 +0000112 for (const auto &MI : *MBB) {
113 if (MI.isTransient())
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000114 continue;
115 ++InstrCount;
Alexey Samsonov84678122014-04-30 22:17:38 +0000116 if (MI.isCall())
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000117 FBI->HasCalls = true;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000118
119 // Count processor resources used.
Jakob Stoklund Olesen2ccdbc62013-04-02 22:27:45 +0000120 if (!SchedModel.hasInstrSchedModel())
121 continue;
Alexey Samsonov84678122014-04-30 22:17:38 +0000122 const MCSchedClassDesc *SC = SchedModel.resolveSchedClass(&MI);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000123 if (!SC->isValid())
124 continue;
125
126 for (TargetSchedModel::ProcResIter
127 PI = SchedModel.getWriteProcResBegin(SC),
128 PE = SchedModel.getWriteProcResEnd(SC); PI != PE; ++PI) {
129 assert(PI->ProcResourceIdx < PRKinds && "Bad processor resource kind");
130 PRCycles[PI->ProcResourceIdx] += PI->Cycles;
131 }
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000132 }
133 FBI->InstrCount = InstrCount;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000134
135 // Scale the resource cycles so they are comparable.
136 unsigned PROffset = MBB->getNumber() * PRKinds;
137 for (unsigned K = 0; K != PRKinds; ++K)
138 ProcResourceCycles[PROffset + K] =
139 PRCycles[K] * SchedModel.getResourceFactor(K);
140
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000141 return FBI;
142}
143
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000144ArrayRef<unsigned>
145MachineTraceMetrics::getProcResourceCycles(unsigned MBBNum) const {
146 assert(BlockInfo[MBBNum].hasResources() &&
147 "getResources() must be called before getProcResourceCycles()");
148 unsigned PRKinds = SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesen2ccdbc62013-04-02 22:27:45 +0000149 assert((MBBNum+1) * PRKinds <= ProcResourceCycles.size());
Craig Topper35120342014-08-27 05:25:25 +0000150 return makeArrayRef(ProcResourceCycles.data() + MBBNum * PRKinds, PRKinds);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000151}
152
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000153//===----------------------------------------------------------------------===//
154// Ensemble utility functions
155//===----------------------------------------------------------------------===//
156
157MachineTraceMetrics::Ensemble::Ensemble(MachineTraceMetrics *ct)
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000158 : MTM(*ct) {
159 BlockInfo.resize(MTM.BlockInfo.size());
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000160 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
161 ProcResourceDepths.resize(MTM.BlockInfo.size() * PRKinds);
162 ProcResourceHeights.resize(MTM.BlockInfo.size() * PRKinds);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000163}
164
165// Virtual destructor serves as an anchor.
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +0000166MachineTraceMetrics::Ensemble::~Ensemble() = default;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000167
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000168const MachineLoop*
169MachineTraceMetrics::Ensemble::getLoopFor(const MachineBasicBlock *MBB) const {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000170 return MTM.Loops->getLoopFor(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000171}
172
173// Update resource-related information in the TraceBlockInfo for MBB.
174// Only update resources related to the trace above MBB.
175void MachineTraceMetrics::Ensemble::
176computeDepthResources(const MachineBasicBlock *MBB) {
177 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000178 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
179 unsigned PROffset = MBB->getNumber() * PRKinds;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000180
181 // Compute resources from trace above. The top block is simple.
182 if (!TBI->Pred) {
183 TBI->InstrDepth = 0;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000184 TBI->Head = MBB->getNumber();
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000185 std::fill(ProcResourceDepths.begin() + PROffset,
186 ProcResourceDepths.begin() + PROffset + PRKinds, 0);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000187 return;
188 }
189
190 // Compute from the block above. A post-order traversal ensures the
191 // predecessor is always computed first.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000192 unsigned PredNum = TBI->Pred->getNumber();
193 TraceBlockInfo *PredTBI = &BlockInfo[PredNum];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000194 assert(PredTBI->hasValidDepth() && "Trace above has not been computed yet");
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000195 const FixedBlockInfo *PredFBI = MTM.getResources(TBI->Pred);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000196 TBI->InstrDepth = PredTBI->InstrDepth + PredFBI->InstrCount;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000197 TBI->Head = PredTBI->Head;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000198
199 // Compute per-resource depths.
200 ArrayRef<unsigned> PredPRDepths = getProcResourceDepths(PredNum);
201 ArrayRef<unsigned> PredPRCycles = MTM.getProcResourceCycles(PredNum);
202 for (unsigned K = 0; K != PRKinds; ++K)
203 ProcResourceDepths[PROffset + K] = PredPRDepths[K] + PredPRCycles[K];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000204}
205
206// Update resource-related information in the TraceBlockInfo for MBB.
207// Only update resources related to the trace below MBB.
208void MachineTraceMetrics::Ensemble::
209computeHeightResources(const MachineBasicBlock *MBB) {
210 TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000211 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
212 unsigned PROffset = MBB->getNumber() * PRKinds;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000213
214 // Compute resources for the current block.
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000215 TBI->InstrHeight = MTM.getResources(MBB)->InstrCount;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000216 ArrayRef<unsigned> PRCycles = MTM.getProcResourceCycles(MBB->getNumber());
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000217
218 // The trace tail is done.
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000219 if (!TBI->Succ) {
220 TBI->Tail = MBB->getNumber();
Fangrui Song53a62242018-11-17 01:44:25 +0000221 llvm::copy(PRCycles, ProcResourceHeights.begin() + PROffset);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000222 return;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000223 }
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000224
225 // Compute from the block below. A post-order traversal ensures the
226 // predecessor is always computed first.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000227 unsigned SuccNum = TBI->Succ->getNumber();
228 TraceBlockInfo *SuccTBI = &BlockInfo[SuccNum];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000229 assert(SuccTBI->hasValidHeight() && "Trace below has not been computed yet");
230 TBI->InstrHeight += SuccTBI->InstrHeight;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +0000231 TBI->Tail = SuccTBI->Tail;
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000232
233 // Compute per-resource heights.
234 ArrayRef<unsigned> SuccPRHeights = getProcResourceHeights(SuccNum);
235 for (unsigned K = 0; K != PRKinds; ++K)
236 ProcResourceHeights[PROffset + K] = SuccPRHeights[K] + PRCycles[K];
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000237}
238
239// Check if depth resources for MBB are valid and return the TBI.
240// Return NULL if the resources have been invalidated.
241const MachineTraceMetrics::TraceBlockInfo*
242MachineTraceMetrics::Ensemble::
243getDepthResources(const MachineBasicBlock *MBB) const {
244 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Craig Topper4ba84432014-04-14 00:51:57 +0000245 return TBI->hasValidDepth() ? TBI : nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000246}
247
248// Check if height resources for MBB are valid and return the TBI.
249// Return NULL if the resources have been invalidated.
250const MachineTraceMetrics::TraceBlockInfo*
251MachineTraceMetrics::Ensemble::
252getHeightResources(const MachineBasicBlock *MBB) const {
253 const TraceBlockInfo *TBI = &BlockInfo[MBB->getNumber()];
Craig Topper4ba84432014-04-14 00:51:57 +0000254 return TBI->hasValidHeight() ? TBI : nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000255}
256
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000257/// Get an array of processor resource depths for MBB. Indexed by processor
258/// resource kind, this array contains the scaled processor resources consumed
259/// by all blocks preceding MBB in its trace. It does not include instructions
260/// in MBB.
261///
262/// Compare TraceBlockInfo::InstrDepth.
263ArrayRef<unsigned>
264MachineTraceMetrics::Ensemble::
265getProcResourceDepths(unsigned MBBNum) const {
266 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesen2ccdbc62013-04-02 22:27:45 +0000267 assert((MBBNum+1) * PRKinds <= ProcResourceDepths.size());
Craig Topper35120342014-08-27 05:25:25 +0000268 return makeArrayRef(ProcResourceDepths.data() + MBBNum * PRKinds, PRKinds);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000269}
270
271/// Get an array of processor resource heights for MBB. Indexed by processor
272/// resource kind, this array contains the scaled processor resources consumed
273/// by this block and all blocks following it in its trace.
274///
275/// Compare TraceBlockInfo::InstrHeight.
276ArrayRef<unsigned>
277MachineTraceMetrics::Ensemble::
278getProcResourceHeights(unsigned MBBNum) const {
279 unsigned PRKinds = MTM.SchedModel.getNumProcResourceKinds();
Jakob Stoklund Olesen2ccdbc62013-04-02 22:27:45 +0000280 assert((MBBNum+1) * PRKinds <= ProcResourceHeights.size());
Craig Topper35120342014-08-27 05:25:25 +0000281 return makeArrayRef(ProcResourceHeights.data() + MBBNum * PRKinds, PRKinds);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000282}
283
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000284//===----------------------------------------------------------------------===//
285// Trace Selection Strategies
286//===----------------------------------------------------------------------===//
287//
288// A trace selection strategy is implemented as a sub-class of Ensemble. The
289// trace through a block B is computed by two DFS traversals of the CFG
290// starting from B. One upwards, and one downwards. During the upwards DFS,
291// pickTracePred() is called on the post-ordered blocks. During the downwards
292// DFS, pickTraceSucc() is called in a post-order.
293//
294
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000295// We never allow traces that leave loops, but we do allow traces to enter
296// nested loops. We also never allow traces to contain back-edges.
297//
298// This means that a loop header can never appear above the center block of a
299// trace, except as the trace head. Below the center block, loop exiting edges
300// are banned.
301//
302// Return true if an edge from the From loop to the To loop is leaving a loop.
303// Either of To and From can be null.
304static bool isExitingLoop(const MachineLoop *From, const MachineLoop *To) {
305 return From && !From->contains(To);
306}
307
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000308// MinInstrCountEnsemble - Pick the trace that executes the least number of
309// instructions.
310namespace {
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +0000311
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000312class MinInstrCountEnsemble : public MachineTraceMetrics::Ensemble {
Craig Topper9f998de2014-03-07 09:26:03 +0000313 const char *getName() const override { return "MinInstr"; }
314 const MachineBasicBlock *pickTracePred(const MachineBasicBlock*) override;
315 const MachineBasicBlock *pickTraceSucc(const MachineBasicBlock*) override;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000316
317public:
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000318 MinInstrCountEnsemble(MachineTraceMetrics *mtm)
319 : MachineTraceMetrics::Ensemble(mtm) {}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000320};
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +0000321
322} // end anonymous namespace
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000323
324// Select the preferred predecessor for MBB.
325const MachineBasicBlock*
326MinInstrCountEnsemble::pickTracePred(const MachineBasicBlock *MBB) {
327 if (MBB->pred_empty())
Craig Topper4ba84432014-04-14 00:51:57 +0000328 return nullptr;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000329 const MachineLoop *CurLoop = getLoopFor(MBB);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000330 // Don't leave loops, and never follow back-edges.
331 if (CurLoop && MBB == CurLoop->getHeader())
Craig Topper4ba84432014-04-14 00:51:57 +0000332 return nullptr;
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000333 unsigned CurCount = MTM.getResources(MBB)->InstrCount;
Craig Topper4ba84432014-04-14 00:51:57 +0000334 const MachineBasicBlock *Best = nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000335 unsigned BestDepth = 0;
Sanjay Patel090f1de2015-05-21 17:22:45 +0000336 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
Jakob Stoklund Olesen8e54ab52012-07-30 21:10:27 +0000337 const MachineTraceMetrics::TraceBlockInfo *PredTBI =
338 getDepthResources(Pred);
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000339 // Ignore cycles that aren't natural loops.
340 if (!PredTBI)
341 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000342 // Pick the predecessor that would give this block the smallest InstrDepth.
343 unsigned Depth = PredTBI->InstrDepth + CurCount;
Richard Trieu1b96cbe2016-02-18 22:09:30 +0000344 if (!Best || Depth < BestDepth) {
345 Best = Pred;
346 BestDepth = Depth;
347 }
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000348 }
349 return Best;
350}
351
352// Select the preferred successor for MBB.
353const MachineBasicBlock*
354MinInstrCountEnsemble::pickTraceSucc(const MachineBasicBlock *MBB) {
355 if (MBB->pred_empty())
Craig Topper4ba84432014-04-14 00:51:57 +0000356 return nullptr;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000357 const MachineLoop *CurLoop = getLoopFor(MBB);
Craig Topper4ba84432014-04-14 00:51:57 +0000358 const MachineBasicBlock *Best = nullptr;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000359 unsigned BestHeight = 0;
Sanjay Patel090f1de2015-05-21 17:22:45 +0000360 for (const MachineBasicBlock *Succ : MBB->successors()) {
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000361 // Don't consider back-edges.
362 if (CurLoop && Succ == CurLoop->getHeader())
363 continue;
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000364 // Don't consider successors exiting CurLoop.
365 if (isExitingLoop(CurLoop, getLoopFor(Succ)))
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000366 continue;
Jakob Stoklund Olesen8e54ab52012-07-30 21:10:27 +0000367 const MachineTraceMetrics::TraceBlockInfo *SuccTBI =
368 getHeightResources(Succ);
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000369 // Ignore cycles that aren't natural loops.
370 if (!SuccTBI)
371 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000372 // Pick the successor that would give this block the smallest InstrHeight.
373 unsigned Height = SuccTBI->InstrHeight;
Richard Trieu1b96cbe2016-02-18 22:09:30 +0000374 if (!Best || Height < BestHeight) {
375 Best = Succ;
376 BestHeight = Height;
377 }
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000378 }
379 return Best;
380}
381
382// Get an Ensemble sub-class for the requested trace strategy.
383MachineTraceMetrics::Ensemble *
384MachineTraceMetrics::getEnsemble(MachineTraceMetrics::Strategy strategy) {
385 assert(strategy < TS_NumStrategies && "Invalid trace strategy enum");
386 Ensemble *&E = Ensembles[strategy];
387 if (E)
388 return E;
389
390 // Allocate new Ensemble on demand.
391 switch (strategy) {
392 case TS_MinInstrCount: return (E = new MinInstrCountEnsemble(this));
393 default: llvm_unreachable("Invalid trace strategy enum");
394 }
395}
396
397void MachineTraceMetrics::invalidate(const MachineBasicBlock *MBB) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000398 LLVM_DEBUG(dbgs() << "Invalidate traces through " << printMBBReference(*MBB)
399 << '\n');
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000400 BlockInfo[MBB->getNumber()].invalidate();
401 for (unsigned i = 0; i != TS_NumStrategies; ++i)
402 if (Ensembles[i])
403 Ensembles[i]->invalidate(MBB);
404}
405
Jakob Stoklund Olesenef6c76c2012-07-30 20:57:50 +0000406void MachineTraceMetrics::verifyAnalysis() const {
Jakob Stoklund Olesen2f6b62b2012-07-30 23:15:12 +0000407 if (!MF)
408 return;
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000409#ifndef NDEBUG
410 assert(BlockInfo.size() == MF->getNumBlockIDs() && "Outdated BlockInfo size");
411 for (unsigned i = 0; i != TS_NumStrategies; ++i)
412 if (Ensembles[i])
413 Ensembles[i]->verify();
414#endif
415}
416
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000417//===----------------------------------------------------------------------===//
418// Trace building
419//===----------------------------------------------------------------------===//
420//
421// Traces are built by two CFG traversals. To avoid recomputing too much, use a
422// set abstraction that confines the search to the current loop, and doesn't
423// revisit blocks.
424
425namespace {
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +0000426
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000427struct LoopBounds {
428 MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> Blocks;
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000429 SmallPtrSet<const MachineBasicBlock*, 8> Visited;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000430 const MachineLoopInfo *Loops;
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +0000431 bool Downward = false;
432
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000433 LoopBounds(MutableArrayRef<MachineTraceMetrics::TraceBlockInfo> blocks,
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +0000434 const MachineLoopInfo *loops) : Blocks(blocks), Loops(loops) {}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000435};
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +0000436
437} // end anonymous namespace
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000438
439// Specialize po_iterator_storage in order to prune the post-order traversal so
440// it is limited to the current loop and doesn't traverse the loop back edges.
441namespace llvm {
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +0000442
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000443template<>
444class po_iterator_storage<LoopBounds, true> {
445 LoopBounds &LB;
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +0000446
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000447public:
448 po_iterator_storage(LoopBounds &lb) : LB(lb) {}
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +0000449
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000450 void finishPostorder(const MachineBasicBlock*) {}
451
Tim Shen36b7d782016-08-15 21:52:54 +0000452 bool insertEdge(Optional<const MachineBasicBlock *> From,
453 const MachineBasicBlock *To) {
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000454 // Skip already visited To blocks.
455 MachineTraceMetrics::TraceBlockInfo &TBI = LB.Blocks[To->getNumber()];
456 if (LB.Downward ? TBI.hasValidHeight() : TBI.hasValidDepth())
457 return false;
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000458 // From is null once when To is the trace center block.
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000459 if (From) {
Tim Shen36b7d782016-08-15 21:52:54 +0000460 if (const MachineLoop *FromLoop = LB.Loops->getLoopFor(*From)) {
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000461 // Don't follow backedges, don't leave FromLoop when going upwards.
Tim Shen36b7d782016-08-15 21:52:54 +0000462 if ((LB.Downward ? To : *From) == FromLoop->getHeader())
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000463 return false;
464 // Don't leave FromLoop.
465 if (isExitingLoop(FromLoop, LB.Loops->getLoopFor(To)))
466 return false;
467 }
468 }
469 // To is a new block. Mark the block as visited in case the CFG has cycles
470 // that MachineLoopInfo didn't recognize as a natural loop.
David Blaikie5401ba72014-11-19 07:49:26 +0000471 return LB.Visited.insert(To).second;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000472 }
473};
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +0000474
475} // end namespace llvm
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000476
477/// Compute the trace through MBB.
478void MachineTraceMetrics::Ensemble::computeTrace(const MachineBasicBlock *MBB) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000479 LLVM_DEBUG(dbgs() << "Computing " << getName() << " trace through "
480 << printMBBReference(*MBB) << '\n');
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000481 // Set up loop bounds for the backwards post-order traversal.
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000482 LoopBounds Bounds(BlockInfo, MTM.Loops);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000483
484 // Run an upwards post-order search for the trace start.
485 Bounds.Downward = false;
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000486 Bounds.Visited.clear();
Daniel Berlin7871b862015-04-15 17:41:42 +0000487 for (auto I : inverse_post_order_ext(MBB, Bounds)) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000488 LLVM_DEBUG(dbgs() << " pred for " << printMBBReference(*I) << ": ");
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000489 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
490 // All the predecessors have been visited, pick the preferred one.
Daniel Berlin7871b862015-04-15 17:41:42 +0000491 TBI.Pred = pickTracePred(I);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000492 LLVM_DEBUG({
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000493 if (TBI.Pred)
Francis Visoiu Mistrihca0df552017-12-04 17:18:51 +0000494 dbgs() << printMBBReference(*TBI.Pred) << '\n';
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000495 else
496 dbgs() << "null\n";
497 });
498 // The trace leading to I is now known, compute the depth resources.
Daniel Berlin7871b862015-04-15 17:41:42 +0000499 computeDepthResources(I);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000500 }
501
502 // Run a downwards post-order search for the trace end.
503 Bounds.Downward = true;
Jakob Stoklund Olesene7230072012-08-08 22:12:01 +0000504 Bounds.Visited.clear();
Daniel Berlin7871b862015-04-15 17:41:42 +0000505 for (auto I : post_order_ext(MBB, Bounds)) {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000506 LLVM_DEBUG(dbgs() << " succ for " << printMBBReference(*I) << ": ");
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000507 TraceBlockInfo &TBI = BlockInfo[I->getNumber()];
508 // All the successors have been visited, pick the preferred one.
Daniel Berlin7871b862015-04-15 17:41:42 +0000509 TBI.Succ = pickTraceSucc(I);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000510 LLVM_DEBUG({
Jakob Stoklund Olesen1c899cf2012-07-30 23:15:10 +0000511 if (TBI.Succ)
Francis Visoiu Mistrihca0df552017-12-04 17:18:51 +0000512 dbgs() << printMBBReference(*TBI.Succ) << '\n';
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000513 else
514 dbgs() << "null\n";
515 });
516 // The trace leaving I is now known, compute the height resources.
Daniel Berlin7871b862015-04-15 17:41:42 +0000517 computeHeightResources(I);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000518 }
519}
520
521/// Invalidate traces through BadMBB.
522void
523MachineTraceMetrics::Ensemble::invalidate(const MachineBasicBlock *BadMBB) {
524 SmallVector<const MachineBasicBlock*, 16> WorkList;
525 TraceBlockInfo &BadTBI = BlockInfo[BadMBB->getNumber()];
526
527 // Invalidate height resources of blocks above MBB.
528 if (BadTBI.hasValidHeight()) {
529 BadTBI.invalidateHeight();
530 WorkList.push_back(BadMBB);
531 do {
532 const MachineBasicBlock *MBB = WorkList.pop_back_val();
Nicola Zaghen0818e782018-05-14 12:53:11 +0000533 LLVM_DEBUG(dbgs() << "Invalidate " << printMBBReference(*MBB) << ' '
534 << getName() << " height.\n");
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000535 // Find any MBB predecessors that have MBB as their preferred successor.
536 // They are the only ones that need to be invalidated.
Sanjay Patela71390f2015-07-06 16:27:35 +0000537 for (const MachineBasicBlock *Pred : MBB->predecessors()) {
538 TraceBlockInfo &TBI = BlockInfo[Pred->getNumber()];
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000539 if (!TBI.hasValidHeight())
540 continue;
541 if (TBI.Succ == MBB) {
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000542 TBI.invalidateHeight();
Sanjay Patela71390f2015-07-06 16:27:35 +0000543 WorkList.push_back(Pred);
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000544 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000545 }
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000546 // Verify that TBI.Succ is actually a *I successor.
Sanjay Patela71390f2015-07-06 16:27:35 +0000547 assert((!TBI.Succ || Pred->isSuccessor(TBI.Succ)) && "CFG changed");
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000548 }
549 } while (!WorkList.empty());
550 }
551
552 // Invalidate depth resources of blocks below MBB.
553 if (BadTBI.hasValidDepth()) {
554 BadTBI.invalidateDepth();
555 WorkList.push_back(BadMBB);
556 do {
557 const MachineBasicBlock *MBB = WorkList.pop_back_val();
Nicola Zaghen0818e782018-05-14 12:53:11 +0000558 LLVM_DEBUG(dbgs() << "Invalidate " << printMBBReference(*MBB) << ' '
559 << getName() << " depth.\n");
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000560 // Find any MBB successors that have MBB as their preferred predecessor.
561 // They are the only ones that need to be invalidated.
Sanjay Patela71390f2015-07-06 16:27:35 +0000562 for (const MachineBasicBlock *Succ : MBB->successors()) {
563 TraceBlockInfo &TBI = BlockInfo[Succ->getNumber()];
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000564 if (!TBI.hasValidDepth())
565 continue;
566 if (TBI.Pred == MBB) {
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000567 TBI.invalidateDepth();
Sanjay Patela71390f2015-07-06 16:27:35 +0000568 WorkList.push_back(Succ);
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000569 continue;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000570 }
Jakob Stoklund Olesenee31ae12012-07-30 17:36:49 +0000571 // Verify that TBI.Pred is actually a *I predecessor.
Sanjay Patela71390f2015-07-06 16:27:35 +0000572 assert((!TBI.Pred || Succ->isPredecessor(TBI.Pred)) && "CFG changed");
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000573 }
574 } while (!WorkList.empty());
575 }
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000576
577 // Clear any per-instruction data. We only have to do this for BadMBB itself
578 // because the instructions in that block may change. Other blocks may be
579 // invalidated, but their instructions will stay the same, so there is no
580 // need to erase the Cycle entries. They will be overwritten when we
581 // recompute.
Alexey Samsonov84678122014-04-30 22:17:38 +0000582 for (const auto &I : *BadMBB)
583 Cycles.erase(&I);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000584}
585
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000586void MachineTraceMetrics::Ensemble::verify() const {
587#ifndef NDEBUG
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000588 assert(BlockInfo.size() == MTM.MF->getNumBlockIDs() &&
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000589 "Outdated BlockInfo size");
590 for (unsigned Num = 0, e = BlockInfo.size(); Num != e; ++Num) {
591 const TraceBlockInfo &TBI = BlockInfo[Num];
592 if (TBI.hasValidDepth() && TBI.Pred) {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000593 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000594 assert(MBB->isPredecessor(TBI.Pred) && "CFG doesn't match trace");
595 assert(BlockInfo[TBI.Pred->getNumber()].hasValidDepth() &&
596 "Trace is broken, depth should have been invalidated.");
597 const MachineLoop *Loop = getLoopFor(MBB);
598 assert(!(Loop && MBB == Loop->getHeader()) && "Trace contains backedge");
599 }
600 if (TBI.hasValidHeight() && TBI.Succ) {
Jakob Stoklund Olesen64e29732012-07-31 20:25:13 +0000601 const MachineBasicBlock *MBB = MTM.MF->getBlockNumbered(Num);
Jakob Stoklund Olesena1b2bf72012-07-30 18:34:11 +0000602 assert(MBB->isSuccessor(TBI.Succ) && "CFG doesn't match trace");
603 assert(BlockInfo[TBI.Succ->getNumber()].hasValidHeight() &&
604 "Trace is broken, height should have been invalidated.");
605 const MachineLoop *Loop = getLoopFor(MBB);
606 const MachineLoop *SuccLoop = getLoopFor(TBI.Succ);
607 assert(!(Loop && Loop == SuccLoop && TBI.Succ == Loop->getHeader()) &&
608 "Trace contains backedge");
609 }
610 }
611#endif
612}
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +0000613
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000614//===----------------------------------------------------------------------===//
615// Data Dependencies
616//===----------------------------------------------------------------------===//
617//
618// Compute the depth and height of each instruction based on data dependencies
619// and instruction latencies. These cycle numbers assume that the CPU can issue
620// an infinite number of instructions per cycle as long as their dependencies
621// are ready.
622
623// A data dependency is represented as a defining MI and operand numbers on the
624// defining and using MI.
625namespace {
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +0000626
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000627struct DataDep {
628 const MachineInstr *DefMI;
629 unsigned DefOp;
630 unsigned UseOp;
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000631
632 DataDep(const MachineInstr *DefMI, unsigned DefOp, unsigned UseOp)
633 : DefMI(DefMI), DefOp(DefOp), UseOp(UseOp) {}
634
635 /// Create a DataDep from an SSA form virtual register.
636 DataDep(const MachineRegisterInfo *MRI, unsigned VirtReg, unsigned UseOp)
637 : UseOp(UseOp) {
638 assert(TargetRegisterInfo::isVirtualRegister(VirtReg));
639 MachineRegisterInfo::def_iterator DefI = MRI->def_begin(VirtReg);
640 assert(!DefI.atEnd() && "Register has no defs");
Owen Andersonbf630222014-03-13 23:12:04 +0000641 DefMI = DefI->getParent();
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000642 DefOp = DefI.getOperandNo();
643 assert((++DefI).atEnd() && "Register has multiple defs");
644 }
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000645};
Eugene Zelenkoc688c0b2017-02-21 22:07:52 +0000646
647} // end anonymous namespace
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000648
649// Get the input data dependencies that must be ready before UseMI can issue.
650// Return true if UseMI has any physreg operands.
Duncan P. N. Exon Smithfdab22c2016-06-30 23:53:20 +0000651static bool getDataDeps(const MachineInstr &UseMI,
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000652 SmallVectorImpl<DataDep> &Deps,
653 const MachineRegisterInfo *MRI) {
Sanjay Patelc3bac702015-07-23 22:56:53 +0000654 // Debug values should not be included in any calculations.
Shiva Chen24abe712018-05-09 02:42:00 +0000655 if (UseMI.isDebugInstr())
Sanjay Patelc3bac702015-07-23 22:56:53 +0000656 return false;
Fangrui Songaf7b1832018-07-30 19:41:25 +0000657
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000658 bool HasPhysRegs = false;
Duncan P. N. Exon Smithfdab22c2016-06-30 23:53:20 +0000659 for (MachineInstr::const_mop_iterator I = UseMI.operands_begin(),
660 E = UseMI.operands_end(); I != E; ++I) {
Matthias Braune67bd6c2015-05-29 02:56:46 +0000661 const MachineOperand &MO = *I;
662 if (!MO.isReg())
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000663 continue;
Matthias Braune67bd6c2015-05-29 02:56:46 +0000664 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000665 if (!Reg)
666 continue;
667 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
668 HasPhysRegs = true;
669 continue;
670 }
671 // Collect virtual register reads.
Matthias Braune67bd6c2015-05-29 02:56:46 +0000672 if (MO.readsReg())
Duncan P. N. Exon Smithfdab22c2016-06-30 23:53:20 +0000673 Deps.push_back(DataDep(MRI, Reg, UseMI.getOperandNo(I)));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000674 }
675 return HasPhysRegs;
676}
677
678// Get the input data dependencies of a PHI instruction, using Pred as the
679// preferred predecessor.
680// This will add at most one dependency to Deps.
Duncan P. N. Exon Smith65b18dd2016-02-22 03:33:28 +0000681static void getPHIDeps(const MachineInstr &UseMI,
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000682 SmallVectorImpl<DataDep> &Deps,
683 const MachineBasicBlock *Pred,
684 const MachineRegisterInfo *MRI) {
685 // No predecessor at the beginning of a trace. Ignore dependencies.
686 if (!Pred)
687 return;
Duncan P. N. Exon Smith65b18dd2016-02-22 03:33:28 +0000688 assert(UseMI.isPHI() && UseMI.getNumOperands() % 2 && "Bad PHI");
689 for (unsigned i = 1; i != UseMI.getNumOperands(); i += 2) {
690 if (UseMI.getOperand(i + 1).getMBB() == Pred) {
691 unsigned Reg = UseMI.getOperand(i).getReg();
Jakob Stoklund Olesen9dae4572012-08-01 16:02:59 +0000692 Deps.push_back(DataDep(MRI, Reg, i));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000693 return;
694 }
695 }
696}
697
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000698// Identify physreg dependencies for UseMI, and update the live regunit
699// tracking set when scanning instructions downwards.
700static void updatePhysDepsDownwards(const MachineInstr *UseMI,
701 SmallVectorImpl<DataDep> &Deps,
702 SparseSet<LiveRegUnit> &RegUnits,
703 const TargetRegisterInfo *TRI) {
704 SmallVector<unsigned, 8> Kills;
705 SmallVector<unsigned, 8> LiveDefOps;
706
Matthias Braune67bd6c2015-05-29 02:56:46 +0000707 for (MachineInstr::const_mop_iterator MI = UseMI->operands_begin(),
708 ME = UseMI->operands_end(); MI != ME; ++MI) {
709 const MachineOperand &MO = *MI;
710 if (!MO.isReg())
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000711 continue;
Matthias Braune67bd6c2015-05-29 02:56:46 +0000712 unsigned Reg = MO.getReg();
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000713 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
714 continue;
715 // Track live defs and kills for updating RegUnits.
Matthias Braune67bd6c2015-05-29 02:56:46 +0000716 if (MO.isDef()) {
717 if (MO.isDead())
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000718 Kills.push_back(Reg);
719 else
Matthias Braune67bd6c2015-05-29 02:56:46 +0000720 LiveDefOps.push_back(UseMI->getOperandNo(MI));
721 } else if (MO.isKill())
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000722 Kills.push_back(Reg);
723 // Identify dependencies.
Matthias Braune67bd6c2015-05-29 02:56:46 +0000724 if (!MO.readsReg())
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000725 continue;
726 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
727 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
728 if (I == RegUnits.end())
729 continue;
Matthias Braune67bd6c2015-05-29 02:56:46 +0000730 Deps.push_back(DataDep(I->MI, I->Op, UseMI->getOperandNo(MI)));
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000731 break;
732 }
733 }
734
735 // Update RegUnits to reflect live registers after UseMI.
736 // First kills.
Sanjay Patel28e18e12015-12-09 22:45:45 +0000737 for (unsigned Kill : Kills)
738 for (MCRegUnitIterator Units(Kill, TRI); Units.isValid(); ++Units)
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000739 RegUnits.erase(*Units);
740
741 // Second, live defs.
Sanjay Patel28e18e12015-12-09 22:45:45 +0000742 for (unsigned DefOp : LiveDefOps) {
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000743 for (MCRegUnitIterator Units(UseMI->getOperand(DefOp).getReg(), TRI);
744 Units.isValid(); ++Units) {
745 LiveRegUnit &LRU = RegUnits[*Units];
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000746 LRU.MI = UseMI;
747 LRU.Op = DefOp;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000748 }
749 }
750}
751
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000752/// The length of the critical path through a trace is the maximum of two path
753/// lengths:
754///
755/// 1. The maximum height+depth over all instructions in the trace center block.
756///
757/// 2. The longest cross-block dependency chain. For small blocks, it is
758/// possible that the critical path through the trace doesn't include any
759/// instructions in the block.
760///
761/// This function computes the second number from the live-in list of the
762/// center block.
763unsigned MachineTraceMetrics::Ensemble::
764computeCrossBlockCriticalPath(const TraceBlockInfo &TBI) {
765 assert(TBI.HasValidInstrDepths && "Missing depth info");
766 assert(TBI.HasValidInstrHeights && "Missing height info");
767 unsigned MaxLen = 0;
Sanjay Patel28e18e12015-12-09 22:45:45 +0000768 for (const LiveInReg &LIR : TBI.LiveIns) {
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000769 if (!TargetRegisterInfo::isVirtualRegister(LIR.Reg))
770 continue;
771 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
772 // Ignore dependencies outside the current trace.
773 const TraceBlockInfo &DefTBI = BlockInfo[DefMI->getParent()->getNumber()];
Jakob Stoklund Olesen6ffcd5e2013-03-07 23:55:49 +0000774 if (!DefTBI.isUsefulDominator(TBI))
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000775 continue;
776 unsigned Len = LIR.Height + Cycles[DefMI].Depth;
777 MaxLen = std::max(MaxLen, Len);
778 }
779 return MaxLen;
780}
781
Florian Hahn4970c502017-09-07 11:51:30 +0000782void MachineTraceMetrics::Ensemble::
783updateDepth(MachineTraceMetrics::TraceBlockInfo &TBI, const MachineInstr &UseMI,
784 SparseSet<LiveRegUnit> &RegUnits) {
785 SmallVector<DataDep, 8> Deps;
786 // Collect all data dependencies.
787 if (UseMI.isPHI())
788 getPHIDeps(UseMI, Deps, TBI.Pred, MTM.MRI);
789 else if (getDataDeps(UseMI, Deps, MTM.MRI))
790 updatePhysDepsDownwards(&UseMI, Deps, RegUnits, MTM.TRI);
791
792 // Filter and process dependencies, computing the earliest issue cycle.
793 unsigned Cycle = 0;
794 for (const DataDep &Dep : Deps) {
795 const TraceBlockInfo&DepTBI =
796 BlockInfo[Dep.DefMI->getParent()->getNumber()];
797 // Ignore dependencies from outside the current trace.
798 if (!DepTBI.isUsefulDominator(TBI))
799 continue;
800 assert(DepTBI.HasValidInstrDepths && "Inconsistent dependency");
801 unsigned DepCycle = Cycles.lookup(Dep.DefMI).Depth;
802 // Add latency if DefMI is a real instruction. Transients get latency 0.
803 if (!Dep.DefMI->isTransient())
804 DepCycle += MTM.SchedModel
805 .computeOperandLatency(Dep.DefMI, Dep.DefOp, &UseMI, Dep.UseOp);
806 Cycle = std::max(Cycle, DepCycle);
807 }
808 // Remember the instruction depth.
809 InstrCycles &MICycles = Cycles[&UseMI];
810 MICycles.Depth = Cycle;
811
812 if (TBI.HasValidInstrHeights) {
813 // Update critical path length.
814 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Height);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000815 LLVM_DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << UseMI);
Florian Hahn4970c502017-09-07 11:51:30 +0000816 } else {
Nicola Zaghen0818e782018-05-14 12:53:11 +0000817 LLVM_DEBUG(dbgs() << Cycle << '\t' << UseMI);
Florian Hahn4970c502017-09-07 11:51:30 +0000818 }
819}
820
821void MachineTraceMetrics::Ensemble::
822updateDepth(const MachineBasicBlock *MBB, const MachineInstr &UseMI,
823 SparseSet<LiveRegUnit> &RegUnits) {
824 updateDepth(BlockInfo[MBB->getNumber()], UseMI, RegUnits);
825}
826
Florian Hahn6aed4212017-09-20 11:54:37 +0000827void MachineTraceMetrics::Ensemble::
828updateDepths(MachineBasicBlock::iterator Start,
829 MachineBasicBlock::iterator End,
830 SparseSet<LiveRegUnit> &RegUnits) {
831 for (; Start != End; Start++)
832 updateDepth(Start->getParent(), *Start, RegUnits);
833}
834
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000835/// Compute instruction depths for all instructions above or in MBB in its
836/// trace. This assumes that the trace through MBB has already been computed.
837void MachineTraceMetrics::Ensemble::
838computeInstrDepths(const MachineBasicBlock *MBB) {
839 // The top of the trace may already be computed, and HasValidInstrDepths
840 // implies Head->HasValidInstrDepths, so we only need to start from the first
841 // block in the trace that needs to be recomputed.
842 SmallVector<const MachineBasicBlock*, 8> Stack;
843 do {
844 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
845 assert(TBI.hasValidDepth() && "Incomplete trace");
846 if (TBI.HasValidInstrDepths)
847 break;
848 Stack.push_back(MBB);
849 MBB = TBI.Pred;
850 } while (MBB);
851
852 // FIXME: If MBB is non-null at this point, it is the last pre-computed block
853 // in the trace. We should track any live-out physregs that were defined in
854 // the trace. This is quite rare in SSA form, typically created by CSE
855 // hoisting a compare.
856 SparseSet<LiveRegUnit> RegUnits;
857 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
858
859 // Go through trace blocks in top-down order, stopping after the center block.
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000860 while (!Stack.empty()) {
861 MBB = Stack.pop_back_val();
Nicola Zaghen0818e782018-05-14 12:53:11 +0000862 LLVM_DEBUG(dbgs() << "\nDepths for " << printMBBReference(*MBB) << ":\n");
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000863 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
864 TBI.HasValidInstrDepths = true;
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000865 TBI.CriticalPath = 0;
866
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000867 // Print out resource depths here as well.
Nicola Zaghen0818e782018-05-14 12:53:11 +0000868 LLVM_DEBUG({
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +0000869 dbgs() << format("%7u Instructions\n", TBI.InstrDepth);
870 ArrayRef<unsigned> PRDepths = getProcResourceDepths(MBB->getNumber());
871 for (unsigned K = 0; K != PRDepths.size(); ++K)
872 if (PRDepths[K]) {
873 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
874 dbgs() << format("%6uc @ ", MTM.getCycles(PRDepths[K]))
875 << MTM.SchedModel.getProcResource(K)->Name << " ("
876 << PRDepths[K]/Factor << " ops x" << Factor << ")\n";
877 }
878 });
879
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +0000880 // Also compute the critical path length through MBB when possible.
881 if (TBI.HasValidInstrHeights)
882 TBI.CriticalPath = computeCrossBlockCriticalPath(TBI);
883
Alexey Samsonov84678122014-04-30 22:17:38 +0000884 for (const auto &UseMI : *MBB) {
Florian Hahn4970c502017-09-07 11:51:30 +0000885 updateDepth(TBI, UseMI, RegUnits);
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +0000886 }
887 }
888}
889
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000890// Identify physreg dependencies for MI when scanning instructions upwards.
891// Return the issue height of MI after considering any live regunits.
892// Height is the issue height computed from virtual register dependencies alone.
Duncan P. N. Exon Smith03941cc72016-07-01 00:05:40 +0000893static unsigned updatePhysDepsUpwards(const MachineInstr &MI, unsigned Height,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000894 SparseSet<LiveRegUnit> &RegUnits,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000895 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000896 const TargetInstrInfo *TII,
897 const TargetRegisterInfo *TRI) {
898 SmallVector<unsigned, 8> ReadOps;
Matthias Braune67bd6c2015-05-29 02:56:46 +0000899
Duncan P. N. Exon Smith03941cc72016-07-01 00:05:40 +0000900 for (MachineInstr::const_mop_iterator MOI = MI.operands_begin(),
901 MOE = MI.operands_end();
902 MOI != MOE; ++MOI) {
Matthias Braune67bd6c2015-05-29 02:56:46 +0000903 const MachineOperand &MO = *MOI;
904 if (!MO.isReg())
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000905 continue;
Matthias Braune67bd6c2015-05-29 02:56:46 +0000906 unsigned Reg = MO.getReg();
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000907 if (!TargetRegisterInfo::isPhysicalRegister(Reg))
908 continue;
Matthias Braune67bd6c2015-05-29 02:56:46 +0000909 if (MO.readsReg())
Duncan P. N. Exon Smith03941cc72016-07-01 00:05:40 +0000910 ReadOps.push_back(MI.getOperandNo(MOI));
Matthias Braune67bd6c2015-05-29 02:56:46 +0000911 if (!MO.isDef())
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000912 continue;
913 // This is a def of Reg. Remove corresponding entries from RegUnits, and
914 // update MI Height to consider the physreg dependencies.
915 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
916 SparseSet<LiveRegUnit>::iterator I = RegUnits.find(*Units);
917 if (I == RegUnits.end())
918 continue;
919 unsigned DepHeight = I->Cycle;
Duncan P. N. Exon Smith03941cc72016-07-01 00:05:40 +0000920 if (!MI.isTransient()) {
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000921 // We may not know the UseMI of this dependency, if it came from the
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000922 // live-in list. SchedModel can handle a NULL UseMI.
Duncan P. N. Exon Smith03941cc72016-07-01 00:05:40 +0000923 DepHeight += SchedModel.computeOperandLatency(&MI, MI.getOperandNo(MOI),
924 I->MI, I->Op);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000925 }
926 Height = std::max(Height, DepHeight);
927 // This regunit is dead above MI.
928 RegUnits.erase(I);
929 }
930 }
931
932 // Now we know the height of MI. Update any regunits read.
933 for (unsigned i = 0, e = ReadOps.size(); i != e; ++i) {
Duncan P. N. Exon Smith03941cc72016-07-01 00:05:40 +0000934 unsigned Reg = MI.getOperand(ReadOps[i]).getReg();
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000935 for (MCRegUnitIterator Units(Reg, TRI); Units.isValid(); ++Units) {
936 LiveRegUnit &LRU = RegUnits[*Units];
937 // Set the height to the highest reader of the unit.
Duncan P. N. Exon Smith03941cc72016-07-01 00:05:40 +0000938 if (LRU.Cycle <= Height && LRU.MI != &MI) {
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000939 LRU.Cycle = Height;
Duncan P. N. Exon Smith03941cc72016-07-01 00:05:40 +0000940 LRU.MI = &MI;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000941 LRU.Op = ReadOps[i];
942 }
943 }
944 }
945
946 return Height;
947}
948
Eugene Zelenko8fd05042017-09-11 23:00:48 +0000949using MIHeightMap = DenseMap<const MachineInstr *, unsigned>;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000950
951// Push the height of DefMI upwards if required to match UseMI.
952// Return true if this is the first time DefMI was seen.
Duncan P. N. Exon Smith03941cc72016-07-01 00:05:40 +0000953static bool pushDepHeight(const DataDep &Dep, const MachineInstr &UseMI,
954 unsigned UseHeight, MIHeightMap &Heights,
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +0000955 const TargetSchedModel &SchedModel,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000956 const TargetInstrInfo *TII) {
957 // Adjust height by Dep.DefMI latency.
958 if (!Dep.DefMI->isTransient())
Duncan P. N. Exon Smith03941cc72016-07-01 00:05:40 +0000959 UseHeight += SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp, &UseMI,
960 Dep.UseOp);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000961
962 // Update Heights[DefMI] to be the maximum height seen.
963 MIHeightMap::iterator I;
964 bool New;
Benjamin Kramera4f0aad2014-03-02 13:30:33 +0000965 std::tie(I, New) = Heights.insert(std::make_pair(Dep.DefMI, UseHeight));
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000966 if (New)
967 return true;
968
969 // DefMI has been pushed before. Give it the max height.
970 if (I->second < UseHeight)
971 I->second = UseHeight;
972 return false;
973}
974
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000975/// Assuming that the virtual register defined by DefMI:DefOp was used by
976/// Trace.back(), add it to the live-in lists of all the blocks in Trace. Stop
977/// when reaching the block that contains DefMI.
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000978void MachineTraceMetrics::Ensemble::
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000979addLiveIns(const MachineInstr *DefMI, unsigned DefOp,
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000980 ArrayRef<const MachineBasicBlock*> Trace) {
981 assert(!Trace.empty() && "Trace should contain at least one block");
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +0000982 unsigned Reg = DefMI->getOperand(DefOp).getReg();
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +0000983 assert(TargetRegisterInfo::isVirtualRegister(Reg));
984 const MachineBasicBlock *DefMBB = DefMI->getParent();
985
986 // Reg is live-in to all blocks in Trace that follow DefMBB.
987 for (unsigned i = Trace.size(); i; --i) {
988 const MachineBasicBlock *MBB = Trace[i-1];
989 if (MBB == DefMBB)
990 return;
991 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
992 // Just add the register. The height will be updated later.
993 TBI.LiveIns.push_back(Reg);
994 }
995}
996
997/// Compute instruction heights in the trace through MBB. This updates MBB and
998/// the blocks below it in the trace. It is assumed that the trace has already
999/// been computed.
1000void MachineTraceMetrics::Ensemble::
1001computeInstrHeights(const MachineBasicBlock *MBB) {
1002 // The bottom of the trace may already be computed.
1003 // Find the blocks that need updating.
1004 SmallVector<const MachineBasicBlock*, 8> Stack;
1005 do {
1006 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1007 assert(TBI.hasValidHeight() && "Incomplete trace");
1008 if (TBI.HasValidInstrHeights)
1009 break;
1010 Stack.push_back(MBB);
1011 TBI.LiveIns.clear();
1012 MBB = TBI.Succ;
1013 } while (MBB);
1014
1015 // As we move upwards in the trace, keep track of instructions that are
1016 // required by deeper trace instructions. Map MI -> height required so far.
1017 MIHeightMap Heights;
1018
1019 // For physregs, the def isn't known when we see the use.
1020 // Instead, keep track of the highest use of each regunit.
1021 SparseSet<LiveRegUnit> RegUnits;
1022 RegUnits.setUniverse(MTM.TRI->getNumRegUnits());
1023
1024 // If the bottom of the trace was already precomputed, initialize heights
1025 // from its live-in list.
1026 // MBB is the highest precomputed block in the trace.
1027 if (MBB) {
1028 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
Sanjay Patel98d447c2015-07-06 16:19:14 +00001029 for (LiveInReg &LI : TBI.LiveIns) {
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001030 if (TargetRegisterInfo::isVirtualRegister(LI.Reg)) {
1031 // For virtual registers, the def latency is included.
1032 unsigned &Height = Heights[MTM.MRI->getVRegDef(LI.Reg)];
1033 if (Height < LI.Height)
1034 Height = LI.Height;
1035 } else {
1036 // For register units, the def latency is not included because we don't
1037 // know the def yet.
1038 RegUnits[LI.Reg].Cycle = LI.Height;
1039 }
1040 }
1041 }
1042
1043 // Go through the trace blocks in bottom-up order.
1044 SmallVector<DataDep, 8> Deps;
1045 for (;!Stack.empty(); Stack.pop_back()) {
1046 MBB = Stack.back();
Nicola Zaghen0818e782018-05-14 12:53:11 +00001047 LLVM_DEBUG(dbgs() << "Heights for " << printMBBReference(*MBB) << ":\n");
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001048 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1049 TBI.HasValidInstrHeights = true;
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001050 TBI.CriticalPath = 0;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001051
Nicola Zaghen0818e782018-05-14 12:53:11 +00001052 LLVM_DEBUG({
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001053 dbgs() << format("%7u Instructions\n", TBI.InstrHeight);
1054 ArrayRef<unsigned> PRHeights = getProcResourceHeights(MBB->getNumber());
1055 for (unsigned K = 0; K != PRHeights.size(); ++K)
1056 if (PRHeights[K]) {
1057 unsigned Factor = MTM.SchedModel.getResourceFactor(K);
1058 dbgs() << format("%6uc @ ", MTM.getCycles(PRHeights[K]))
1059 << MTM.SchedModel.getProcResource(K)->Name << " ("
1060 << PRHeights[K]/Factor << " ops x" << Factor << ")\n";
1061 }
1062 });
1063
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001064 // Get dependencies from PHIs in the trace successor.
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001065 const MachineBasicBlock *Succ = TBI.Succ;
1066 // If MBB is the last block in the trace, and it has a back-edge to the
1067 // loop header, get loop-carried dependencies from PHIs in the header. For
1068 // that purpose, pretend that all the loop header PHIs have height 0.
1069 if (!Succ)
1070 if (const MachineLoop *Loop = getLoopFor(MBB))
1071 if (MBB->isSuccessor(Loop->getHeader()))
1072 Succ = Loop->getHeader();
1073
1074 if (Succ) {
Alexey Samsonov84678122014-04-30 22:17:38 +00001075 for (const auto &PHI : *Succ) {
1076 if (!PHI.isPHI())
1077 break;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001078 Deps.clear();
Duncan P. N. Exon Smith65b18dd2016-02-22 03:33:28 +00001079 getPHIDeps(PHI, Deps, MBB, MTM.MRI);
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001080 if (!Deps.empty()) {
1081 // Loop header PHI heights are all 0.
Alexey Samsonov84678122014-04-30 22:17:38 +00001082 unsigned Height = TBI.Succ ? Cycles.lookup(&PHI).Height : 0;
Nicola Zaghen0818e782018-05-14 12:53:11 +00001083 LLVM_DEBUG(dbgs() << "pred\t" << Height << '\t' << PHI);
Duncan P. N. Exon Smith03941cc72016-07-01 00:05:40 +00001084 if (pushDepHeight(Deps.front(), PHI, Height, Heights, MTM.SchedModel,
1085 MTM.TII))
Jakob Stoklund Olesenebba4932012-10-11 16:46:07 +00001086 addLiveIns(Deps.front().DefMI, Deps.front().DefOp, Stack);
Jakob Stoklund Olesen8828c4c2012-08-10 20:11:38 +00001087 }
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001088 }
1089 }
1090
1091 // Go through the block backwards.
1092 for (MachineBasicBlock::const_iterator BI = MBB->end(), BB = MBB->begin();
1093 BI != BB;) {
Duncan P. N. Exon Smithfdab22c2016-06-30 23:53:20 +00001094 const MachineInstr &MI = *--BI;
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001095
1096 // Find the MI height as determined by virtual register uses in the
1097 // trace below.
1098 unsigned Cycle = 0;
Duncan P. N. Exon Smithfdab22c2016-06-30 23:53:20 +00001099 MIHeightMap::iterator HeightI = Heights.find(&MI);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001100 if (HeightI != Heights.end()) {
1101 Cycle = HeightI->second;
1102 // We won't be seeing any more MI uses.
1103 Heights.erase(HeightI);
1104 }
1105
1106 // Don't process PHI deps. They depend on the specific predecessor, and
1107 // we'll get them when visiting the predecessor.
1108 Deps.clear();
Duncan P. N. Exon Smithfdab22c2016-06-30 23:53:20 +00001109 bool HasPhysRegs = !MI.isPHI() && getDataDeps(MI, Deps, MTM.MRI);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001110
1111 // There may also be regunit dependencies to include in the height.
1112 if (HasPhysRegs)
Duncan P. N. Exon Smith03941cc72016-07-01 00:05:40 +00001113 Cycle = updatePhysDepsUpwards(MI, Cycle, RegUnits, MTM.SchedModel,
1114 MTM.TII, MTM.TRI);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001115
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001116 // Update the required height of any virtual registers read by MI.
Sanjay Patel5601e302015-06-30 16:30:22 +00001117 for (const DataDep &Dep : Deps)
Duncan P. N. Exon Smith03941cc72016-07-01 00:05:40 +00001118 if (pushDepHeight(Dep, MI, Cycle, Heights, MTM.SchedModel, MTM.TII))
Sanjay Patel5601e302015-06-30 16:30:22 +00001119 addLiveIns(Dep.DefMI, Dep.DefOp, Stack);
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001120
Duncan P. N. Exon Smithfdab22c2016-06-30 23:53:20 +00001121 InstrCycles &MICycles = Cycles[&MI];
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001122 MICycles.Height = Cycle;
1123 if (!TBI.HasValidInstrDepths) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00001124 LLVM_DEBUG(dbgs() << Cycle << '\t' << MI);
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001125 continue;
1126 }
1127 // Update critical path length.
1128 TBI.CriticalPath = std::max(TBI.CriticalPath, Cycle + MICycles.Depth);
Nicola Zaghen0818e782018-05-14 12:53:11 +00001129 LLVM_DEBUG(dbgs() << TBI.CriticalPath << '\t' << Cycle << '\t' << MI);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001130 }
1131
1132 // Update virtual live-in heights. They were added by addLiveIns() with a 0
1133 // height because the final height isn't known until now.
Nicola Zaghen0818e782018-05-14 12:53:11 +00001134 LLVM_DEBUG(dbgs() << printMBBReference(*MBB) << " Live-ins:");
Sanjay Patel5601e302015-06-30 16:30:22 +00001135 for (LiveInReg &LIR : TBI.LiveIns) {
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001136 const MachineInstr *DefMI = MTM.MRI->getVRegDef(LIR.Reg);
1137 LIR.Height = Heights.lookup(DefMI);
Nicola Zaghen0818e782018-05-14 12:53:11 +00001138 LLVM_DEBUG(dbgs() << ' ' << printReg(LIR.Reg) << '@' << LIR.Height);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001139 }
1140
1141 // Transfer the live regunits to the live-in list.
1142 for (SparseSet<LiveRegUnit>::const_iterator
1143 RI = RegUnits.begin(), RE = RegUnits.end(); RI != RE; ++RI) {
1144 TBI.LiveIns.push_back(LiveInReg(RI->RegUnit, RI->Cycle));
Nicola Zaghen0818e782018-05-14 12:53:11 +00001145 LLVM_DEBUG(dbgs() << ' ' << printRegUnit(RI->RegUnit, MTM.TRI) << '@'
1146 << RI->Cycle);
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001147 }
Nicola Zaghen0818e782018-05-14 12:53:11 +00001148 LLVM_DEBUG(dbgs() << '\n');
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001149
1150 if (!TBI.HasValidInstrDepths)
1151 continue;
1152 // Add live-ins to the critical path length.
1153 TBI.CriticalPath = std::max(TBI.CriticalPath,
1154 computeCrossBlockCriticalPath(TBI));
Nicola Zaghen0818e782018-05-14 12:53:11 +00001155 LLVM_DEBUG(dbgs() << "Critical path: " << TBI.CriticalPath << '\n');
Jakob Stoklund Olesenc7f44b82012-08-01 22:36:00 +00001156 }
1157}
1158
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001159MachineTraceMetrics::Trace
1160MachineTraceMetrics::Ensemble::getTrace(const MachineBasicBlock *MBB) {
Sanjay Patel2244d522015-07-04 15:00:28 +00001161 TraceBlockInfo &TBI = BlockInfo[MBB->getNumber()];
1162
1163 if (!TBI.hasValidDepth() || !TBI.hasValidHeight())
1164 computeTrace(MBB);
1165 if (!TBI.HasValidInstrDepths)
1166 computeInstrDepths(MBB);
1167 if (!TBI.HasValidInstrHeights)
1168 computeInstrHeights(MBB);
Fangrui Songaf7b1832018-07-30 19:41:25 +00001169
Sanjay Patel2244d522015-07-04 15:00:28 +00001170 return Trace(*this, TBI);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001171}
1172
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001173unsigned
Duncan P. N. Exon Smith65b18dd2016-02-22 03:33:28 +00001174MachineTraceMetrics::Trace::getInstrSlack(const MachineInstr &MI) const {
1175 assert(getBlockNum() == unsigned(MI.getParent()->getNumber()) &&
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001176 "MI must be in the trace center block");
1177 InstrCycles Cyc = getInstrCycles(MI);
1178 return getCriticalPath() - (Cyc.Depth + Cyc.Height);
1179}
1180
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001181unsigned
Duncan P. N. Exon Smith65b18dd2016-02-22 03:33:28 +00001182MachineTraceMetrics::Trace::getPHIDepth(const MachineInstr &PHI) const {
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001183 const MachineBasicBlock *MBB = TE.MTM.MF->getBlockNumbered(getBlockNum());
1184 SmallVector<DataDep, 1> Deps;
1185 getPHIDeps(PHI, Deps, MBB, TE.MTM.MRI);
1186 assert(Deps.size() == 1 && "PHI doesn't have MBB as a predecessor");
1187 DataDep &Dep = Deps.front();
Duncan P. N. Exon Smith65b18dd2016-02-22 03:33:28 +00001188 unsigned DepCycle = getInstrCycles(*Dep.DefMI).Depth;
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001189 // Add latency if DefMI is a real instruction. Transients get latency 0.
1190 if (!Dep.DefMI->isTransient())
Duncan P. N. Exon Smith65b18dd2016-02-22 03:33:28 +00001191 DepCycle += TE.MTM.SchedModel.computeOperandLatency(Dep.DefMI, Dep.DefOp,
1192 &PHI, Dep.UseOp);
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001193 return DepCycle;
1194}
1195
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +00001196/// When bottom is set include instructions in current block in estimate.
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001197unsigned MachineTraceMetrics::Trace::getResourceDepth(bool Bottom) const {
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001198 // Find the limiting processor resource.
1199 // Numbers have been pre-scaled to be comparable.
1200 unsigned PRMax = 0;
1201 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1202 if (Bottom) {
1203 ArrayRef<unsigned> PRCycles = TE.MTM.getProcResourceCycles(getBlockNum());
1204 for (unsigned K = 0; K != PRDepths.size(); ++K)
1205 PRMax = std::max(PRMax, PRDepths[K] + PRCycles[K]);
1206 } else {
1207 for (unsigned K = 0; K != PRDepths.size(); ++K)
1208 PRMax = std::max(PRMax, PRDepths[K]);
1209 }
1210 // Convert to cycle count.
1211 PRMax = TE.MTM.getCycles(PRMax);
1212
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +00001213 /// All instructions before current block
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001214 unsigned Instrs = TBI.InstrDepth;
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +00001215 // plus instructions in current block
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001216 if (Bottom)
1217 Instrs += TE.MTM.BlockInfo[getBlockNum()].InstrCount;
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001218 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1219 Instrs /= IW;
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001220 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001221 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen84ef6ba2012-08-07 18:02:19 +00001222}
1223
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +00001224unsigned MachineTraceMetrics::Trace::getResourceLength(
1225 ArrayRef<const MachineBasicBlock *> Extrablocks,
1226 ArrayRef<const MCSchedClassDesc *> ExtraInstrs,
1227 ArrayRef<const MCSchedClassDesc *> RemoveInstrs) const {
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001228 // Add up resources above and below the center block.
1229 ArrayRef<unsigned> PRDepths = TE.getProcResourceDepths(getBlockNum());
1230 ArrayRef<unsigned> PRHeights = TE.getProcResourceHeights(getBlockNum());
1231 unsigned PRMax = 0;
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +00001232
1233 // Capture computing cycles from extra instructions
1234 auto extraCycles = [this](ArrayRef<const MCSchedClassDesc *> Instrs,
1235 unsigned ResourceIdx)
1236 ->unsigned {
1237 unsigned Cycles = 0;
Sanjay Patel98d447c2015-07-06 16:19:14 +00001238 for (const MCSchedClassDesc *SC : Instrs) {
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +00001239 if (!SC->isValid())
1240 continue;
1241 for (TargetSchedModel::ProcResIter
1242 PI = TE.MTM.SchedModel.getWriteProcResBegin(SC),
1243 PE = TE.MTM.SchedModel.getWriteProcResEnd(SC);
1244 PI != PE; ++PI) {
1245 if (PI->ProcResourceIdx != ResourceIdx)
1246 continue;
1247 Cycles +=
1248 (PI->Cycles * TE.MTM.SchedModel.getResourceFactor(ResourceIdx));
1249 }
1250 }
1251 return Cycles;
1252 };
1253
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001254 for (unsigned K = 0; K != PRDepths.size(); ++K) {
1255 unsigned PRCycles = PRDepths[K] + PRHeights[K];
Sanjay Patel98d447c2015-07-06 16:19:14 +00001256 for (const MachineBasicBlock *MBB : Extrablocks)
1257 PRCycles += TE.MTM.getProcResourceCycles(MBB->getNumber())[K];
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +00001258 PRCycles += extraCycles(ExtraInstrs, K);
1259 PRCycles -= extraCycles(RemoveInstrs, K);
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001260 PRMax = std::max(PRMax, PRCycles);
1261 }
1262 // Convert to cycle count.
1263 PRMax = TE.MTM.getCycles(PRMax);
1264
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +00001265 // Instrs: #instructions in current trace outside current block.
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001266 unsigned Instrs = TBI.InstrDepth + TBI.InstrHeight;
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +00001267 // Add instruction count from the extra blocks.
Sanjay Patel98d447c2015-07-06 16:19:14 +00001268 for (const MachineBasicBlock *MBB : Extrablocks)
1269 Instrs += TE.MTM.getResources(MBB)->InstrCount;
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +00001270 Instrs += ExtraInstrs.size();
1271 Instrs -= RemoveInstrs.size();
Jakob Stoklund Olesenf43fe1d2012-10-04 17:30:40 +00001272 if (unsigned IW = TE.MTM.SchedModel.getIssueWidth())
1273 Instrs /= IW;
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001274 // Assume issue width 1 without a schedule model.
Jakob Stoklund Olesen8396e132013-04-02 17:49:51 +00001275 return std::max(Instrs, PRMax);
Jakob Stoklund Olesen5413b682012-08-10 22:27:27 +00001276}
1277
Duncan P. N. Exon Smith65b18dd2016-02-22 03:33:28 +00001278bool MachineTraceMetrics::Trace::isDepInTrace(const MachineInstr &DefMI,
1279 const MachineInstr &UseMI) const {
1280 if (DefMI.getParent() == UseMI.getParent())
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +00001281 return true;
1282
Duncan P. N. Exon Smith65b18dd2016-02-22 03:33:28 +00001283 const TraceBlockInfo &DepTBI = TE.BlockInfo[DefMI.getParent()->getNumber()];
1284 const TraceBlockInfo &TBI = TE.BlockInfo[UseMI.getParent()->getNumber()];
Gerolf Hoflehnerb0b70882014-08-03 21:35:39 +00001285
1286 return DepTBI.isUsefulDominator(TBI);
1287}
1288
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001289void MachineTraceMetrics::Ensemble::print(raw_ostream &OS) const {
1290 OS << getName() << " ensemble:\n";
1291 for (unsigned i = 0, e = BlockInfo.size(); i != e; ++i) {
Francis Visoiu Mistrihca0df552017-12-04 17:18:51 +00001292 OS << " %bb." << i << '\t';
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001293 BlockInfo[i].print(OS);
1294 OS << '\n';
1295 }
1296}
1297
1298void MachineTraceMetrics::TraceBlockInfo::print(raw_ostream &OS) const {
1299 if (hasValidDepth()) {
1300 OS << "depth=" << InstrDepth;
1301 if (Pred)
Francis Visoiu Mistrihca0df552017-12-04 17:18:51 +00001302 OS << " pred=" << printMBBReference(*Pred);
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001303 else
1304 OS << " pred=null";
Francis Visoiu Mistrihca0df552017-12-04 17:18:51 +00001305 OS << " head=%bb." << Head;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +00001306 if (HasValidInstrDepths)
1307 OS << " +instrs";
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001308 } else
1309 OS << "depth invalid";
1310 OS << ", ";
1311 if (hasValidHeight()) {
1312 OS << "height=" << InstrHeight;
1313 if (Succ)
Francis Visoiu Mistrihca0df552017-12-04 17:18:51 +00001314 OS << " succ=" << printMBBReference(*Succ);
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001315 else
1316 OS << " succ=null";
Francis Visoiu Mistrihca0df552017-12-04 17:18:51 +00001317 OS << " tail=%bb." << Tail;
Jakob Stoklund Olesen5f8e8bd2012-07-31 20:44:38 +00001318 if (HasValidInstrHeights)
1319 OS << " +instrs";
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001320 } else
1321 OS << "height invalid";
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001322 if (HasValidInstrDepths && HasValidInstrHeights)
1323 OS << ", crit=" << CriticalPath;
Jakob Stoklund Olesen08f6ef62012-07-27 23:58:38 +00001324}
1325
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001326void MachineTraceMetrics::Trace::print(raw_ostream &OS) const {
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001327 unsigned MBBNum = &TBI - &TE.BlockInfo[0];
1328
Francis Visoiu Mistrihca0df552017-12-04 17:18:51 +00001329 OS << TE.getName() << " trace %bb." << TBI.Head << " --> %bb." << MBBNum
1330 << " --> %bb." << TBI.Tail << ':';
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001331 if (TBI.hasValidHeight() && TBI.hasValidDepth())
1332 OS << ' ' << getInstrCount() << " instrs.";
Jakob Stoklund Olesen79a20ce2012-08-02 18:45:54 +00001333 if (TBI.HasValidInstrDepths && TBI.HasValidInstrHeights)
1334 OS << ' ' << TBI.CriticalPath << " cycles.";
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001335
1336 const MachineTraceMetrics::TraceBlockInfo *Block = &TBI;
Francis Visoiu Mistrihca0df552017-12-04 17:18:51 +00001337 OS << "\n%bb." << MBBNum;
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001338 while (Block->hasValidDepth() && Block->Pred) {
1339 unsigned Num = Block->Pred->getNumber();
Francis Visoiu Mistrihca0df552017-12-04 17:18:51 +00001340 OS << " <- " << printMBBReference(*Block->Pred);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001341 Block = &TE.BlockInfo[Num];
1342 }
1343
1344 Block = &TBI;
Jakob Stoklund Olesen0271a5f2012-07-27 23:58:36 +00001345 OS << "\n ";
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001346 while (Block->hasValidHeight() && Block->Succ) {
1347 unsigned Num = Block->Succ->getNumber();
Francis Visoiu Mistrihca0df552017-12-04 17:18:51 +00001348 OS << " -> " << printMBBReference(*Block->Succ);
Jakob Stoklund Olesen9f63e102012-07-26 18:38:11 +00001349 Block = &TE.BlockInfo[Num];
1350 }
1351 OS << '\n';
1352}