blob: 3dfa7683c1c8e51fc78e961f320f4c5ce46c595e [file] [log] [blame]
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +00001//===--- RDFLiveness.cpp --------------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Computation of the liveness information from the data-flow graph.
11//
12// The main functionality of this code is to compute block live-in
13// information. With the live-in information in place, the placement
14// of kill flags can also be recalculated.
15//
16// The block live-in calculation is based on the ideas from the following
17// publication:
18//
19// Dibyendu Das, Ramakrishna Upadrasta, Benoit Dupont de Dinechin.
20// "Efficient Liveness Computation Using Merge Sets and DJ-Graphs."
21// ACM Transactions on Architecture and Code Optimization, Association for
22// Computing Machinery, 2012, ACM TACO Special Issue on "High-Performance
23// and Embedded Architectures and Compilers", 8 (4),
24// <10.1145/2086696.2086706>. <hal-00647369>
25//
26#include "RDFGraph.h"
27#include "RDFLiveness.h"
28#include "llvm/ADT/SetVector.h"
29#include "llvm/CodeGen/MachineBasicBlock.h"
30#include "llvm/CodeGen/MachineDominanceFrontier.h"
31#include "llvm/CodeGen/MachineDominators.h"
32#include "llvm/CodeGen/MachineFunction.h"
33#include "llvm/CodeGen/MachineRegisterInfo.h"
34#include "llvm/Target/TargetRegisterInfo.h"
35
36using namespace llvm;
37using namespace rdf;
38
Benjamin Kramer922efd72016-05-27 10:06:40 +000039namespace llvm {
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +000040namespace rdf {
41 template<>
42 raw_ostream &operator<< (raw_ostream &OS, const Print<Liveness::RefMap> &P) {
43 OS << '{';
44 for (auto I : P.Obj) {
45 OS << ' ' << Print<RegisterRef>(I.first, P.G) << '{';
46 for (auto J = I.second.begin(), E = I.second.end(); J != E; ) {
47 OS << Print<NodeId>(*J, P.G);
48 if (++J != E)
49 OS << ',';
50 }
51 OS << '}';
52 }
53 OS << " }";
54 return OS;
55 }
Benjamin Kramer922efd72016-05-27 10:06:40 +000056} // namespace rdf
57} // namespace llvm
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +000058
59// The order in the returned sequence is the order of reaching defs in the
60// upward traversal: the first def is the closest to the given reference RefA,
61// the next one is further up, and so on.
62// The list ends at a reaching phi def, or when the reference from RefA is
63// covered by the defs in the list (see FullChain).
64// This function provides two modes of operation:
65// (1) Returning the sequence of reaching defs for a particular reference
66// node. This sequence will terminate at the first phi node [1].
67// (2) Returning a partial sequence of reaching defs, where the final goal
68// is to traverse past phi nodes to the actual defs arising from the code
69// itself.
70// In mode (2), the register reference for which the search was started
71// may be different from the reference node RefA, for which this call was
72// made, hence the argument RefRR, which holds the original register.
73// Also, some definitions may have already been encountered in a previous
74// call that will influence register covering. The register references
75// already defined are passed in through DefRRs.
76// In mode (1), the "continuation" considerations do not apply, and the
77// RefRR is the same as the register in RefA, and the set DefRRs is empty.
78//
79// [1] It is possible for multiple phi nodes to be included in the returned
80// sequence:
81// SubA = phi ...
82// SubB = phi ...
83// ... = SuperAB(rdef:SubA), SuperAB"(rdef:SubB)
84// However, these phi nodes are independent from one another in terms of
85// the data-flow.
86
87NodeList Liveness::getAllReachingDefs(RegisterRef RefRR,
88 NodeAddr<RefNode*> RefA, bool FullChain, const RegisterSet &DefRRs) {
89 SetVector<NodeId> DefQ;
90 SetVector<NodeId> Owners;
91
92 // The initial queue should not have reaching defs for shadows. The
93 // whole point of a shadow is that it will have a reaching def that
94 // is not aliased to the reaching defs of the related shadows.
95 NodeId Start = RefA.Id;
96 auto SNA = DFG.addr<RefNode*>(Start);
97 if (NodeId RD = SNA.Addr->getReachingDef())
98 DefQ.insert(RD);
99
100 // Collect all the reaching defs, going up until a phi node is encountered,
101 // or there are no more reaching defs. From this set, the actual set of
102 // reaching defs will be selected.
103 // The traversal upwards must go on until a covering def is encountered.
104 // It is possible that a collection of non-covering (individually) defs
105 // will be sufficient, but keep going until a covering one is found.
106 for (unsigned i = 0; i < DefQ.size(); ++i) {
107 auto TA = DFG.addr<DefNode*>(DefQ[i]);
108 if (TA.Addr->getFlags() & NodeAttrs::PhiRef)
109 continue;
110 // Stop at the covering/overwriting def of the initial register reference.
111 RegisterRef RR = TA.Addr->getRegRef();
Krzysztof Parzyszeka1218722016-09-08 20:48:42 +0000112 if (!DFG.IsPreservingDef(TA) && RAI.covers(RR, RefRR))
113 continue;
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000114 // Get the next level of reaching defs. This will include multiple
115 // reaching defs for shadows.
116 for (auto S : DFG.getRelatedRefs(TA.Addr->getOwner(DFG), TA))
117 if (auto RD = NodeAddr<RefNode*>(S).Addr->getReachingDef())
118 DefQ.insert(RD);
119 }
120
121 // Remove all non-phi defs that are not aliased to RefRR, and collect
122 // the owners of the remaining defs.
123 SetVector<NodeId> Defs;
124 for (auto N : DefQ) {
125 auto TA = DFG.addr<DefNode*>(N);
126 bool IsPhi = TA.Addr->getFlags() & NodeAttrs::PhiRef;
127 if (!IsPhi && !RAI.alias(RefRR, TA.Addr->getRegRef()))
128 continue;
129 Defs.insert(TA.Id);
130 Owners.insert(TA.Addr->getOwner(DFG).Id);
131 }
132
133 // Return the MachineBasicBlock containing a given instruction.
134 auto Block = [this] (NodeAddr<InstrNode*> IA) -> MachineBasicBlock* {
135 if (IA.Addr->getKind() == NodeAttrs::Stmt)
136 return NodeAddr<StmtNode*>(IA).Addr->getCode()->getParent();
137 assert(IA.Addr->getKind() == NodeAttrs::Phi);
138 NodeAddr<PhiNode*> PA = IA;
139 NodeAddr<BlockNode*> BA = PA.Addr->getOwner(DFG);
140 return BA.Addr->getCode();
141 };
142 // Less(A,B) iff instruction A is further down in the dominator tree than B.
143 auto Less = [&Block,this] (NodeId A, NodeId B) -> bool {
144 if (A == B)
145 return false;
146 auto OA = DFG.addr<InstrNode*>(A), OB = DFG.addr<InstrNode*>(B);
147 MachineBasicBlock *BA = Block(OA), *BB = Block(OB);
148 if (BA != BB)
149 return MDT.dominates(BB, BA);
150 // They are in the same block.
151 bool StmtA = OA.Addr->getKind() == NodeAttrs::Stmt;
152 bool StmtB = OB.Addr->getKind() == NodeAttrs::Stmt;
153 if (StmtA) {
154 if (!StmtB) // OB is a phi and phis dominate statements.
155 return true;
156 auto CA = NodeAddr<StmtNode*>(OA).Addr->getCode();
157 auto CB = NodeAddr<StmtNode*>(OB).Addr->getCode();
158 // The order must be linear, so tie-break such equalities.
159 if (CA == CB)
160 return A < B;
161 return MDT.dominates(CB, CA);
162 } else {
163 // OA is a phi.
164 if (StmtB)
165 return false;
166 // Both are phis. There is no ordering between phis (in terms of
167 // the data-flow), so tie-break this via node id comparison.
168 return A < B;
169 }
170 };
171
172 std::vector<NodeId> Tmp(Owners.begin(), Owners.end());
173 std::sort(Tmp.begin(), Tmp.end(), Less);
174
175 // The vector is a list of instructions, so that defs coming from
176 // the same instruction don't need to be artificially ordered.
177 // Then, when computing the initial segment, and iterating over an
178 // instruction, pick the defs that contribute to the covering (i.e. is
179 // not covered by previously added defs). Check the defs individually,
180 // i.e. first check each def if is covered or not (without adding them
181 // to the tracking set), and then add all the selected ones.
182
183 // The reason for this is this example:
184 // *d1<A>, *d2<B>, ... Assume A and B are aliased (can happen in phi nodes).
185 // *d3<C> If A \incl BuC, and B \incl AuC, then *d2 would be
186 // covered if we added A first, and A would be covered
187 // if we added B first.
188
189 NodeList RDefs;
190 RegisterSet RRs = DefRRs;
191
192 auto DefInSet = [&Defs] (NodeAddr<RefNode*> TA) -> bool {
193 return TA.Addr->getKind() == NodeAttrs::Def &&
194 Defs.count(TA.Id);
195 };
196 for (auto T : Tmp) {
197 if (!FullChain && RAI.covers(RRs, RefRR))
198 break;
199 auto TA = DFG.addr<InstrNode*>(T);
200 bool IsPhi = DFG.IsCode<NodeAttrs::Phi>(TA);
201 NodeList Ds;
202 for (NodeAddr<DefNode*> DA : TA.Addr->members_if(DefInSet, DFG)) {
203 auto QR = DA.Addr->getRegRef();
204 // Add phi defs even if they are covered by subsequent defs. This is
205 // for cases where the reached use is not covered by any of the defs
206 // encountered so far: the phi def is needed to expose the liveness
207 // of that use to the entry of the block.
208 // Example:
209 // phi d1<R3>(,d2,), ... Phi def d1 is covered by d2.
210 // d2<R3>(d1,,u3), ...
211 // ..., u3<D1>(d2) This use needs to be live on entry.
212 if (FullChain || IsPhi || !RAI.covers(RRs, QR))
213 Ds.push_back(DA);
214 }
215 RDefs.insert(RDefs.end(), Ds.begin(), Ds.end());
216 for (NodeAddr<DefNode*> DA : Ds) {
217 // When collecting a full chain of definitions, do not consider phi
218 // defs to actually define a register.
219 uint16_t Flags = DA.Addr->getFlags();
220 if (!FullChain || !(Flags & NodeAttrs::PhiRef))
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +0000221 if (!(Flags & NodeAttrs::Preserving)) // Don't care about Undef here.
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000222 RRs.insert(DA.Addr->getRegRef());
223 }
224 }
225
226 return RDefs;
227}
228
229
230static const RegisterSet NoRegs;
231
232NodeList Liveness::getAllReachingDefs(NodeAddr<RefNode*> RefA) {
233 return getAllReachingDefs(RefA.Addr->getRegRef(), RefA, false, NoRegs);
234}
235
236
Krzysztof Parzyszekf5cbac92016-04-29 15:49:13 +0000237NodeSet Liveness::getAllReachingDefsRec(RegisterRef RefRR,
238 NodeAddr<RefNode*> RefA, NodeSet &Visited, const NodeSet &Defs) {
239 // Collect all defined registers. Do not consider phis to be defining
240 // anything, only collect "real" definitions.
241 RegisterSet DefRRs;
242 for (const auto D : Defs) {
243 const auto DA = DFG.addr<const DefNode*>(D);
244 if (!(DA.Addr->getFlags() & NodeAttrs::PhiRef))
245 DefRRs.insert(DA.Addr->getRegRef());
246 }
247
248 auto RDs = getAllReachingDefs(RefRR, RefA, true, DefRRs);
249 if (RDs.empty())
250 return Defs;
251
252 // Make a copy of the preexisting definitions and add the newly found ones.
253 NodeSet TmpDefs = Defs;
254 for (auto R : RDs)
255 TmpDefs.insert(R.Id);
256
257 NodeSet Result = Defs;
258
259 for (NodeAddr<DefNode*> DA : RDs) {
260 Result.insert(DA.Id);
261 if (!(DA.Addr->getFlags() & NodeAttrs::PhiRef))
262 continue;
263 NodeAddr<PhiNode*> PA = DA.Addr->getOwner(DFG);
264 if (Visited.count(PA.Id))
265 continue;
266 Visited.insert(PA.Id);
267 // Go over all phi uses and get the reaching defs for each use.
268 for (auto U : PA.Addr->members_if(DFG.IsRef<NodeAttrs::Use>, DFG)) {
269 const auto &T = getAllReachingDefsRec(RefRR, U, Visited, TmpDefs);
270 Result.insert(T.begin(), T.end());
271 }
272 }
273
274 return Result;
275}
276
277
278NodeSet Liveness::getAllReachedUses(RegisterRef RefRR,
279 NodeAddr<DefNode*> DefA, const RegisterSet &DefRRs) {
280 NodeSet Uses;
281
282 // If the original register is already covered by all the intervening
283 // defs, no more uses can be reached.
284 if (RAI.covers(DefRRs, RefRR))
285 return Uses;
286
287 // Add all directly reached uses.
288 NodeId U = DefA.Addr->getReachedUse();
289 while (U != 0) {
290 auto UA = DFG.addr<UseNode*>(U);
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +0000291 if (!(UA.Addr->getFlags() & NodeAttrs::Undef)) {
292 auto UR = UA.Addr->getRegRef();
293 if (RAI.alias(RefRR, UR) && !RAI.covers(DefRRs, UR))
294 Uses.insert(U);
295 }
Krzysztof Parzyszekf5cbac92016-04-29 15:49:13 +0000296 U = UA.Addr->getSibling();
297 }
298
299 // Traverse all reached defs.
300 for (NodeId D = DefA.Addr->getReachedDef(), NextD; D != 0; D = NextD) {
301 auto DA = DFG.addr<DefNode*>(D);
302 NextD = DA.Addr->getSibling();
303 auto DR = DA.Addr->getRegRef();
304 // If this def is already covered, it cannot reach anything new.
305 // Similarly, skip it if it is not aliased to the interesting register.
306 if (RAI.covers(DefRRs, DR) || !RAI.alias(RefRR, DR))
307 continue;
308 NodeSet T;
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +0000309 if (DFG.IsPreservingDef(DA)) {
Krzysztof Parzyszekf5cbac92016-04-29 15:49:13 +0000310 // If it is a preserving def, do not update the set of intervening defs.
311 T = getAllReachedUses(RefRR, DA, DefRRs);
312 } else {
313 RegisterSet NewDefRRs = DefRRs;
314 NewDefRRs.insert(DR);
315 T = getAllReachedUses(RefRR, DA, NewDefRRs);
316 }
317 Uses.insert(T.begin(), T.end());
318 }
319 return Uses;
320}
321
322
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000323void Liveness::computePhiInfo() {
Krzysztof Parzyszekf5cbac92016-04-29 15:49:13 +0000324 RealUseMap.clear();
325
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000326 NodeList Phis;
327 NodeAddr<FuncNode*> FA = DFG.getFunc();
328 auto Blocks = FA.Addr->members(DFG);
329 for (NodeAddr<BlockNode*> BA : Blocks) {
330 auto Ps = BA.Addr->members_if(DFG.IsCode<NodeAttrs::Phi>, DFG);
331 Phis.insert(Phis.end(), Ps.begin(), Ps.end());
332 }
333
334 // phi use -> (map: reaching phi -> set of registers defined in between)
335 std::map<NodeId,std::map<NodeId,RegisterSet>> PhiUp;
336 std::vector<NodeId> PhiUQ; // Work list of phis for upward propagation.
337
338 // Go over all phis.
339 for (NodeAddr<PhiNode*> PhiA : Phis) {
340 // Go over all defs and collect the reached uses that are non-phi uses
341 // (i.e. the "real uses").
342 auto &RealUses = RealUseMap[PhiA.Id];
343 auto PhiRefs = PhiA.Addr->members(DFG);
344
345 // Have a work queue of defs whose reached uses need to be found.
346 // For each def, add to the queue all reached (non-phi) defs.
347 SetVector<NodeId> DefQ;
348 NodeSet PhiDefs;
349 for (auto R : PhiRefs) {
350 if (!DFG.IsRef<NodeAttrs::Def>(R))
351 continue;
352 DefQ.insert(R.Id);
353 PhiDefs.insert(R.Id);
354 }
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000355
356 // Collect the super-set of all possible reached uses. This set will
357 // contain all uses reached from this phi, either directly from the
358 // phi defs, or (recursively) via non-phi defs reached by the phi defs.
359 // This set of uses will later be trimmed to only contain these uses that
360 // are actually reached by the phi defs.
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000361 for (unsigned i = 0; i < DefQ.size(); ++i) {
362 NodeAddr<DefNode*> DA = DFG.addr<DefNode*>(DefQ[i]);
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000363 // Visit all reached uses.
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000364 NodeId UN = DA.Addr->getReachedUse();
365 while (UN != 0) {
366 NodeAddr<UseNode*> A = DFG.addr<UseNode*>(UN);
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +0000367 uint16_t F = A.Addr->getFlags();
368 if ((F & (NodeAttrs::Undef | NodeAttrs::PhiRef)) == 0)
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000369 RealUses[getRestrictedRegRef(A)].insert(A.Id);
370 UN = A.Addr->getSibling();
371 }
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000372 // Visit all reached defs, and add them to the queue. These defs may
373 // override some of the uses collected here, but that will be handled
374 // later.
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000375 NodeId DN = DA.Addr->getReachedDef();
376 while (DN != 0) {
377 NodeAddr<DefNode*> A = DFG.addr<DefNode*>(DN);
378 for (auto T : DFG.getRelatedRefs(A.Addr->getOwner(DFG), A)) {
379 uint16_t Flags = NodeAddr<DefNode*>(T).Addr->getFlags();
380 // Must traverse the reached-def chain. Consider:
381 // def(D0) -> def(R0) -> def(R0) -> use(D0)
382 // The reachable use of D0 passes through a def of R0.
383 if (!(Flags & NodeAttrs::PhiRef))
384 DefQ.insert(T.Id);
385 }
386 DN = A.Addr->getSibling();
387 }
388 }
389 // Filter out these uses that appear to be reachable, but really
390 // are not. For example:
391 //
392 // R1:0 = d1
393 // = R1:0 u2 Reached by d1.
394 // R0 = d3
395 // = R1:0 u4 Still reached by d1: indirectly through
396 // the def d3.
397 // R1 = d5
398 // = R1:0 u6 Not reached by d1 (covered collectively
399 // by d3 and d5), but following reached
400 // defs and uses from d1 will lead here.
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000401 auto InPhiDefs = [&PhiDefs] (NodeAddr<DefNode*> DA) -> bool {
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000402 return PhiDefs.count(DA.Id);
403 };
404 for (auto UI = RealUses.begin(), UE = RealUses.end(); UI != UE; ) {
405 // For each reached register UI->first, there is a set UI->second, of
406 // uses of it. For each such use, check if it is reached by this phi,
407 // i.e. check if the set of its reaching uses intersects the set of
408 // this phi's defs.
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000409 NodeSet &Uses = UI->second;
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000410 for (auto I = Uses.begin(), E = Uses.end(); I != E; ) {
411 auto UA = DFG.addr<UseNode*>(*I);
412 NodeList RDs = getAllReachingDefs(UI->first, UA);
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000413 if (any_of(RDs, InPhiDefs))
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000414 ++I;
415 else
416 I = Uses.erase(I);
417 }
418 if (Uses.empty())
419 UI = RealUses.erase(UI);
420 else
421 ++UI;
422 }
423
424 // If this phi reaches some "real" uses, add it to the queue for upward
425 // propagation.
426 if (!RealUses.empty())
427 PhiUQ.push_back(PhiA.Id);
428
429 // Go over all phi uses and check if the reaching def is another phi.
430 // Collect the phis that are among the reaching defs of these uses.
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000431 // While traversing the list of reaching defs for each phi use, accumulate
432 // the set of registers defined between this phi (PhiA) and the owner phi
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000433 // of the reaching def.
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000434 NodeSet SeenUses;
Krzysztof Parzyszeka1218722016-09-08 20:48:42 +0000435
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000436 for (auto I : PhiRefs) {
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000437 if (!DFG.IsRef<NodeAttrs::Use>(I) || SeenUses.count(I.Id))
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000438 continue;
439 NodeAddr<UseNode*> UA = I;
Krzysztof Parzyszeka1218722016-09-08 20:48:42 +0000440
441 // Given a phi use UA, traverse all related phi uses (including UA).
442 // The related phi uses may reach different phi nodes or may reach the
443 // same phi node. If multiple uses reach the same phi P, the intervening
444 // defs must be accumulated for all such uses. To group all such uses
445 // into one set, map their node ids to the first use id that reaches P.
446 std::map<NodeId,NodeId> FirstUse; // Phi reached up -> first phi use.
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000447
448 for (NodeAddr<UseNode*> VA : DFG.getRelatedRefs(PhiA, UA)) {
449 SeenUses.insert(VA.Id);
Krzysztof Parzyszeka1218722016-09-08 20:48:42 +0000450 RegisterSet DefRRs;
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000451 for (NodeAddr<DefNode*> DA : getAllReachingDefs(VA)) {
452 if (DA.Addr->getFlags() & NodeAttrs::PhiRef) {
Krzysztof Parzyszeka1218722016-09-08 20:48:42 +0000453 NodeId RP = DA.Addr->getOwner(DFG).Id;
454 NodeId FU = FirstUse.insert({RP,VA.Id}).first->second;
455 PhiUp[FU][RP].insert(DefRRs.begin(), DefRRs.end());
456 }
457 DefRRs.insert(DA.Addr->getRegRef());
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000458 }
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000459 }
460 }
461 }
462
463 if (Trace) {
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000464 dbgs() << "Phi-up-to-phi map with intervening defs:\n";
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000465 for (auto I : PhiUp) {
466 dbgs() << "phi " << Print<NodeId>(I.first, DFG) << " -> {";
467 for (auto R : I.second)
468 dbgs() << ' ' << Print<NodeId>(R.first, DFG)
469 << Print<RegisterSet>(R.second, DFG);
470 dbgs() << " }\n";
471 }
472 }
473
474 // Propagate the reached registers up in the phi chain.
475 //
476 // The following type of situation needs careful handling:
477 //
478 // phi d1<R1:0> (1)
479 // |
480 // ... d2<R1>
481 // |
482 // phi u3<R1:0> (2)
483 // |
484 // ... u4<R1>
485 //
486 // The phi node (2) defines a register pair R1:0, and reaches a "real"
487 // use u4 of just R1. The same phi node is also known to reach (upwards)
488 // the phi node (1). However, the use u4 is not reached by phi (1),
489 // because of the intervening definition d2 of R1. The data flow between
490 // phis (1) and (2) is restricted to R1:0 minus R1, i.e. R0.
491 //
492 // When propagating uses up the phi chains, get the all reaching defs
493 // for a given phi use, and traverse the list until the propagated ref
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000494 // is covered, or until reaching the final phi. Only assume that the
495 // reference reaches the phi in the latter case.
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000496
497 for (unsigned i = 0; i < PhiUQ.size(); ++i) {
498 auto PA = DFG.addr<PhiNode*>(PhiUQ[i]);
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000499 NodeList PUs = PA.Addr->members_if(DFG.IsRef<NodeAttrs::Use>, DFG);
500 RefMap &RUM = RealUseMap[PA.Id];
501
502 for (auto U : PUs) {
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000503 NodeAddr<UseNode*> UA = U;
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000504 std::map<NodeId,RegisterSet> &PUM = PhiUp[UA.Id];
505 for (const std::pair<NodeId,RegisterSet> &P : PUM) {
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000506 bool Changed = false;
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000507 RegisterSet MidDefs = P.second;
508
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000509 // Collect the set UpReached of uses that are reached by the current
510 // phi PA, and are not covered by any intervening def between PA and
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000511 // the upward phi P.
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000512 RegisterSet UpReached;
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000513 for (const std::pair<RegisterRef,NodeSet> &T : RUM) {
514 RegisterRef R = T.first;
515 if (!isRestrictedToRef(PA, UA, R))
516 R = getRestrictedRegRef(UA);
517 if (!RAI.covers(MidDefs, R))
518 UpReached.insert(R);
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000519 }
520 if (UpReached.empty())
521 continue;
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000522 // Update the set PRUs of real uses reached by the upward phi P with
523 // the actual set of uses (UpReached) that the P phi reaches.
524 RefMap &PRUs = RealUseMap[P.first];
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000525 for (auto R : UpReached) {
526 unsigned Z = PRUs[R].size();
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000527 PRUs[R].insert(RUM[R].begin(), RUM[R].end());
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000528 Changed |= (PRUs[R].size() != Z);
529 }
530 if (Changed)
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000531 PhiUQ.push_back(P.first);
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000532 }
533 }
534 }
535
536 if (Trace) {
537 dbgs() << "Real use map:\n";
538 for (auto I : RealUseMap) {
539 dbgs() << "phi " << Print<NodeId>(I.first, DFG);
540 NodeAddr<PhiNode*> PA = DFG.addr<PhiNode*>(I.first);
541 NodeList Ds = PA.Addr->members_if(DFG.IsRef<NodeAttrs::Def>, DFG);
542 if (!Ds.empty()) {
543 RegisterRef RR = NodeAddr<DefNode*>(Ds[0]).Addr->getRegRef();
544 dbgs() << '<' << Print<RegisterRef>(RR, DFG) << '>';
545 } else {
546 dbgs() << "<noreg>";
547 }
548 dbgs() << " -> " << Print<RefMap>(I.second, DFG) << '\n';
549 }
550 }
551}
552
553
554void Liveness::computeLiveIns() {
555 // Populate the node-to-block map. This speeds up the calculations
556 // significantly.
557 NBMap.clear();
558 for (NodeAddr<BlockNode*> BA : DFG.getFunc().Addr->members(DFG)) {
559 MachineBasicBlock *BB = BA.Addr->getCode();
560 for (NodeAddr<InstrNode*> IA : BA.Addr->members(DFG)) {
561 for (NodeAddr<RefNode*> RA : IA.Addr->members(DFG))
562 NBMap.insert(std::make_pair(RA.Id, BB));
563 NBMap.insert(std::make_pair(IA.Id, BB));
564 }
565 }
566
567 MachineFunction &MF = DFG.getMF();
568
569 // Compute IDF first, then the inverse.
570 decltype(IIDF) IDF;
571 for (auto &B : MF) {
572 auto F1 = MDF.find(&B);
573 if (F1 == MDF.end())
574 continue;
575 SetVector<MachineBasicBlock*> IDFB(F1->second.begin(), F1->second.end());
576 for (unsigned i = 0; i < IDFB.size(); ++i) {
577 auto F2 = MDF.find(IDFB[i]);
578 if (F2 != MDF.end())
579 IDFB.insert(F2->second.begin(), F2->second.end());
580 }
581 // Add B to the IDF(B). This will put B in the IIDF(B).
582 IDFB.insert(&B);
583 IDF[&B].insert(IDFB.begin(), IDFB.end());
584 }
585
586 for (auto I : IDF)
587 for (auto S : I.second)
588 IIDF[S].insert(I.first);
589
590 computePhiInfo();
591
592 NodeAddr<FuncNode*> FA = DFG.getFunc();
593 auto Blocks = FA.Addr->members(DFG);
594
595 // Build the phi live-on-entry map.
596 for (NodeAddr<BlockNode*> BA : Blocks) {
597 MachineBasicBlock *MB = BA.Addr->getCode();
598 auto &LON = PhiLON[MB];
599 for (auto P : BA.Addr->members_if(DFG.IsCode<NodeAttrs::Phi>, DFG))
600 for (auto S : RealUseMap[P.Id])
601 LON[S.first].insert(S.second.begin(), S.second.end());
602 }
603
604 if (Trace) {
605 dbgs() << "Phi live-on-entry map:\n";
606 for (auto I : PhiLON)
607 dbgs() << "block #" << I.first->getNumber() << " -> "
608 << Print<RefMap>(I.second, DFG) << '\n';
609 }
610
611 // Build the phi live-on-exit map. Each phi node has some set of reached
612 // "real" uses. Propagate this set backwards into the block predecessors
613 // through the reaching defs of the corresponding phi uses.
614 for (NodeAddr<BlockNode*> BA : Blocks) {
615 auto Phis = BA.Addr->members_if(DFG.IsCode<NodeAttrs::Phi>, DFG);
616 for (NodeAddr<PhiNode*> PA : Phis) {
617 auto &RUs = RealUseMap[PA.Id];
618 if (RUs.empty())
619 continue;
620
621 for (auto U : PA.Addr->members_if(DFG.IsRef<NodeAttrs::Use>, DFG)) {
622 NodeAddr<PhiUseNode*> UA = U;
623 if (UA.Addr->getReachingDef() == 0)
624 continue;
625
626 // Mark all reached "real" uses of P as live on exit in the
627 // predecessor.
628 // Remap all the RUs so that they have a correct reaching def.
629 auto PrA = DFG.addr<BlockNode*>(UA.Addr->getPredecessor());
630 auto &LOX = PhiLOX[PrA.Addr->getCode()];
631 for (auto R : RUs) {
632 RegisterRef RR = R.first;
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000633 if (!isRestrictedToRef(PA, UA, RR))
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000634 RR = getRestrictedRegRef(UA);
635 // The restricted ref may be different from the ref that was
636 // accessed in the "real use". This means that this phi use
637 // is not the one that carries this reference, so skip it.
638 if (!RAI.alias(R.first, RR))
639 continue;
640 for (auto D : getAllReachingDefs(RR, UA))
641 LOX[RR].insert(D.Id);
642 }
643 } // for U : phi uses
644 } // for P : Phis
645 } // for B : Blocks
646
647 if (Trace) {
648 dbgs() << "Phi live-on-exit map:\n";
649 for (auto I : PhiLOX)
650 dbgs() << "block #" << I.first->getNumber() << " -> "
651 << Print<RefMap>(I.second, DFG) << '\n';
652 }
653
654 RefMap LiveIn;
655 traverse(&MF.front(), LiveIn);
656
657 // Add function live-ins to the live-in set of the function entry block.
658 auto &EntryIn = LiveMap[&MF.front()];
659 for (auto I = MRI.livein_begin(), E = MRI.livein_end(); I != E; ++I)
660 EntryIn.insert({I->first,0});
661
662 if (Trace) {
663 // Dump the liveness map
664 for (auto &B : MF) {
665 BitVector LV(TRI.getNumRegs());
666 for (auto I = B.livein_begin(), E = B.livein_end(); I != E; ++I)
667 LV.set(I->PhysReg);
668 dbgs() << "BB#" << B.getNumber() << "\t rec = {";
669 for (int x = LV.find_first(); x >= 0; x = LV.find_next(x))
670 dbgs() << ' ' << Print<RegisterRef>({unsigned(x),0}, DFG);
671 dbgs() << " }\n";
672 dbgs() << "\tcomp = " << Print<RegisterSet>(LiveMap[&B], DFG) << '\n';
673 }
674 }
675}
676
677
678void Liveness::resetLiveIns() {
679 for (auto &B : DFG.getMF()) {
680 // Remove all live-ins.
681 std::vector<unsigned> T;
682 for (auto I = B.livein_begin(), E = B.livein_end(); I != E; ++I)
683 T.push_back(I->PhysReg);
684 for (auto I : T)
685 B.removeLiveIn(I);
686 // Add the newly computed live-ins.
687 auto &LiveIns = LiveMap[&B];
688 for (auto I : LiveIns) {
689 assert(I.Sub == 0);
690 B.addLiveIn(I.Reg);
691 }
692 }
693}
694
695
696void Liveness::resetKills() {
697 for (auto &B : DFG.getMF())
698 resetKills(&B);
699}
700
701
702void Liveness::resetKills(MachineBasicBlock *B) {
703 auto CopyLiveIns = [] (MachineBasicBlock *B, BitVector &LV) -> void {
704 for (auto I = B->livein_begin(), E = B->livein_end(); I != E; ++I)
705 LV.set(I->PhysReg);
706 };
707
708 BitVector LiveIn(TRI.getNumRegs()), Live(TRI.getNumRegs());
709 CopyLiveIns(B, LiveIn);
710 for (auto SI : B->successors())
711 CopyLiveIns(SI, Live);
712
713 for (auto I = B->rbegin(), E = B->rend(); I != E; ++I) {
714 MachineInstr *MI = &*I;
715 if (MI->isDebugValue())
716 continue;
717
718 MI->clearKillInfo();
719 for (auto &Op : MI->operands()) {
Krzysztof Parzyszekf69ff712016-06-02 14:30:09 +0000720 // An implicit def of a super-register may not necessarily start a
721 // live range of it, since an implicit use could be used to keep parts
722 // of it live. Instead of analyzing the implicit operands, ignore
723 // implicit defs.
724 if (!Op.isReg() || !Op.isDef() || Op.isImplicit())
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000725 continue;
726 unsigned R = Op.getReg();
727 if (!TargetRegisterInfo::isPhysicalRegister(R))
728 continue;
729 for (MCSubRegIterator SR(R, &TRI, true); SR.isValid(); ++SR)
730 Live.reset(*SR);
731 }
732 for (auto &Op : MI->operands()) {
733 if (!Op.isReg() || !Op.isUse())
734 continue;
735 unsigned R = Op.getReg();
736 if (!TargetRegisterInfo::isPhysicalRegister(R))
737 continue;
738 bool IsLive = false;
Krzysztof Parzyszek16331f02016-04-20 14:33:23 +0000739 for (MCRegAliasIterator AR(R, &TRI, true); AR.isValid(); ++AR) {
740 if (!Live[*AR])
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000741 continue;
742 IsLive = true;
743 break;
744 }
745 if (IsLive)
746 continue;
747 Op.setIsKill(true);
748 for (MCSubRegIterator SR(R, &TRI, true); SR.isValid(); ++SR)
749 Live.set(*SR);
750 }
751 }
752}
753
754
755// For shadows, determine if RR is aliased to a reaching def of any other
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000756// shadow associated with RA. The register ref on RA will be "larger" than
757// each individual reaching def, and to determine the data-flow between defs
758// and uses of RR it may be necessary to visit all shadows. If RR is not
759// aliased to the reaching def of any other shadow, then visiting only RA
760// is sufficient. In that sense, the data flow of RR would be restricted to
761// the reference RA.
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000762// For non-shadows, this function returns "true".
Krzysztof Parzyszek2db0c8b2016-09-07 20:37:05 +0000763bool Liveness::isRestrictedToRef(NodeAddr<InstrNode*> IA, NodeAddr<RefNode*> RA,
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000764 RegisterRef RR) const {
765 NodeId Start = RA.Id;
766 for (NodeAddr<RefNode*> TA = DFG.getNextShadow(IA, RA);
767 TA.Id != 0 && TA.Id != Start; TA = DFG.getNextShadow(IA, TA)) {
768 NodeId RD = TA.Addr->getReachingDef();
769 if (RD == 0)
770 continue;
771 if (RAI.alias(RR, DFG.addr<DefNode*>(RD).Addr->getRegRef()))
772 return false;
773 }
774 return true;
775}
776
777
778RegisterRef Liveness::getRestrictedRegRef(NodeAddr<RefNode*> RA) const {
779 assert(DFG.IsRef<NodeAttrs::Use>(RA));
780 if (RA.Addr->getFlags() & NodeAttrs::Shadow) {
781 NodeId RD = RA.Addr->getReachingDef();
782 assert(RD);
783 RA = DFG.addr<DefNode*>(RD);
784 }
785 return RA.Addr->getRegRef();
786}
787
788
789unsigned Liveness::getPhysReg(RegisterRef RR) const {
790 if (!TargetRegisterInfo::isPhysicalRegister(RR.Reg))
791 return 0;
792 return RR.Sub ? TRI.getSubReg(RR.Reg, RR.Sub) : RR.Reg;
793}
794
795
796// Helper function to obtain the basic block containing the reaching def
797// of the given use.
798MachineBasicBlock *Liveness::getBlockWithRef(NodeId RN) const {
799 auto F = NBMap.find(RN);
800 if (F != NBMap.end())
801 return F->second;
802 llvm_unreachable("Node id not in map");
803}
804
805
806void Liveness::traverse(MachineBasicBlock *B, RefMap &LiveIn) {
807 // The LiveIn map, for each (physical) register, contains the set of live
808 // reaching defs of that register that are live on entry to the associated
809 // block.
810
811 // The summary of the traversal algorithm:
812 //
813 // R is live-in in B, if there exists a U(R), such that rdef(R) dom B
814 // and (U \in IDF(B) or B dom U).
815 //
816 // for (C : children) {
817 // LU = {}
818 // traverse(C, LU)
819 // LiveUses += LU
820 // }
821 //
822 // LiveUses -= Defs(B);
823 // LiveUses += UpwardExposedUses(B);
824 // for (C : IIDF[B])
825 // for (U : LiveUses)
826 // if (Rdef(U) dom C)
827 // C.addLiveIn(U)
828 //
829
830 // Go up the dominator tree (depth-first).
831 MachineDomTreeNode *N = MDT.getNode(B);
832 for (auto I : *N) {
833 RefMap L;
834 MachineBasicBlock *SB = I->getBlock();
835 traverse(SB, L);
836
837 for (auto S : L)
838 LiveIn[S.first].insert(S.second.begin(), S.second.end());
839 }
840
841 if (Trace) {
842 dbgs() << LLVM_FUNCTION_NAME << " in BB#" << B->getNumber()
843 << " after recursion into";
844 for (auto I : *N)
845 dbgs() << ' ' << I->getBlock()->getNumber();
846 dbgs() << "\n LiveIn: " << Print<RefMap>(LiveIn, DFG);
847 dbgs() << "\n Local: " << Print<RegisterSet>(LiveMap[B], DFG) << '\n';
848 }
849
850 // Add phi uses that are live on exit from this block.
851 RefMap &PUs = PhiLOX[B];
852 for (auto S : PUs)
853 LiveIn[S.first].insert(S.second.begin(), S.second.end());
854
855 if (Trace) {
856 dbgs() << "after LOX\n";
857 dbgs() << " LiveIn: " << Print<RefMap>(LiveIn, DFG) << '\n';
858 dbgs() << " Local: " << Print<RegisterSet>(LiveMap[B], DFG) << '\n';
859 }
860
861 // Stop tracking all uses defined in this block: erase those records
862 // where the reaching def is located in B and which cover all reached
863 // uses.
864 auto Copy = LiveIn;
865 LiveIn.clear();
866
867 for (auto I : Copy) {
868 auto &Defs = LiveIn[I.first];
869 NodeSet Rest;
870 for (auto R : I.second) {
871 auto DA = DFG.addr<DefNode*>(R);
872 RegisterRef DDR = DA.Addr->getRegRef();
873 NodeAddr<InstrNode*> IA = DA.Addr->getOwner(DFG);
874 NodeAddr<BlockNode*> BA = IA.Addr->getOwner(DFG);
875 // Defs from a different block need to be preserved. Defs from this
876 // block will need to be processed further, except for phi defs, the
877 // liveness of which is handled through the PhiLON/PhiLOX maps.
878 if (B != BA.Addr->getCode())
879 Defs.insert(R);
880 else {
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +0000881 bool IsPreserving = DFG.IsPreservingDef(DA);
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000882 if (IA.Addr->getKind() != NodeAttrs::Phi && !IsPreserving) {
883 bool Covering = RAI.covers(DDR, I.first);
884 NodeId U = DA.Addr->getReachedUse();
885 while (U && Covering) {
886 auto DUA = DFG.addr<UseNode*>(U);
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +0000887 if (!(DUA.Addr->getFlags() & NodeAttrs::Undef)) {
888 RegisterRef Q = DUA.Addr->getRegRef();
889 Covering = RAI.covers(DA.Addr->getRegRef(), Q);
890 }
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000891 U = DUA.Addr->getSibling();
892 }
893 if (!Covering)
894 Rest.insert(R);
895 }
896 }
897 }
898
899 // Non-covering defs from B.
900 for (auto R : Rest) {
901 auto DA = DFG.addr<DefNode*>(R);
902 RegisterRef DRR = DA.Addr->getRegRef();
903 RegisterSet RRs;
904 for (NodeAddr<DefNode*> TA : getAllReachingDefs(DA)) {
905 NodeAddr<InstrNode*> IA = TA.Addr->getOwner(DFG);
906 NodeAddr<BlockNode*> BA = IA.Addr->getOwner(DFG);
907 // Preserving defs do not count towards covering.
908 if (!(TA.Addr->getFlags() & NodeAttrs::Preserving))
909 RRs.insert(TA.Addr->getRegRef());
910 if (BA.Addr->getCode() == B)
911 continue;
912 if (RAI.covers(RRs, DRR))
913 break;
914 Defs.insert(TA.Id);
915 }
916 }
917 }
918
919 emptify(LiveIn);
920
921 if (Trace) {
922 dbgs() << "after defs in block\n";
923 dbgs() << " LiveIn: " << Print<RefMap>(LiveIn, DFG) << '\n';
924 dbgs() << " Local: " << Print<RegisterSet>(LiveMap[B], DFG) << '\n';
925 }
926
927 // Scan the block for upward-exposed uses and add them to the tracking set.
928 for (auto I : DFG.getFunc().Addr->findBlock(B, DFG).Addr->members(DFG)) {
929 NodeAddr<InstrNode*> IA = I;
930 if (IA.Addr->getKind() != NodeAttrs::Stmt)
931 continue;
932 for (NodeAddr<UseNode*> UA : IA.Addr->members_if(DFG.IsUse, DFG)) {
933 RegisterRef RR = UA.Addr->getRegRef();
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +0000934 if (UA.Addr->getFlags() & NodeAttrs::Undef)
935 continue;
Krzysztof Parzyszekacdff462016-01-12 15:56:33 +0000936 for (auto D : getAllReachingDefs(UA))
937 if (getBlockWithRef(D.Id) != B)
938 LiveIn[RR].insert(D.Id);
939 }
940 }
941
942 if (Trace) {
943 dbgs() << "after uses in block\n";
944 dbgs() << " LiveIn: " << Print<RefMap>(LiveIn, DFG) << '\n';
945 dbgs() << " Local: " << Print<RegisterSet>(LiveMap[B], DFG) << '\n';
946 }
947
948 // Phi uses should not be propagated up the dominator tree, since they
949 // are not dominated by their corresponding reaching defs.
950 auto &Local = LiveMap[B];
951 auto &LON = PhiLON[B];
952 for (auto R : LON)
953 Local.insert(R.first);
954
955 if (Trace) {
956 dbgs() << "after phi uses in block\n";
957 dbgs() << " LiveIn: " << Print<RefMap>(LiveIn, DFG) << '\n';
958 dbgs() << " Local: " << Print<RegisterSet>(Local, DFG) << '\n';
959 }
960
961 for (auto C : IIDF[B]) {
962 auto &LiveC = LiveMap[C];
963 for (auto S : LiveIn)
964 for (auto R : S.second)
965 if (MDT.properlyDominates(getBlockWithRef(R), C))
966 LiveC.insert(S.first);
967 }
968}
969
970
971void Liveness::emptify(RefMap &M) {
972 for (auto I = M.begin(), E = M.end(); I != E; )
973 I = I->second.empty() ? M.erase(I) : std::next(I);
974}
975