blob: 5070d9c6f4150f24b908f646d06ab386be8f585b [file] [log] [blame]
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001//===--- RDFGraph.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// Target-independent, SSA-based data flow graph for register data flow (RDF).
11//
12#include "RDFGraph.h"
13
14#include "llvm/ADT/SetVector.h"
15#include "llvm/CodeGen/MachineBasicBlock.h"
16#include "llvm/CodeGen/MachineDominanceFrontier.h"
17#include "llvm/CodeGen/MachineDominators.h"
18#include "llvm/CodeGen/MachineFunction.h"
19#include "llvm/CodeGen/MachineRegisterInfo.h"
20#include "llvm/Target/TargetInstrInfo.h"
21#include "llvm/Target/TargetRegisterInfo.h"
22
23using namespace llvm;
24using namespace rdf;
25
26// Printing functions. Have them here first, so that the rest of the code
27// can use them.
Benjamin Kramer922efd72016-05-27 10:06:40 +000028namespace llvm {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +000029namespace rdf {
30
31template<>
32raw_ostream &operator<< (raw_ostream &OS, const Print<RegisterRef> &P) {
33 auto &TRI = P.G.getTRI();
34 if (P.Obj.Reg > 0 && P.Obj.Reg < TRI.getNumRegs())
35 OS << TRI.getName(P.Obj.Reg);
36 else
37 OS << '#' << P.Obj.Reg;
38 if (P.Obj.Sub > 0) {
39 OS << ':';
40 if (P.Obj.Sub < TRI.getNumSubRegIndices())
41 OS << TRI.getSubRegIndexName(P.Obj.Sub);
42 else
43 OS << '#' << P.Obj.Sub;
44 }
45 return OS;
46}
47
48template<>
49raw_ostream &operator<< (raw_ostream &OS, const Print<NodeId> &P) {
50 auto NA = P.G.addr<NodeBase*>(P.Obj);
51 uint16_t Attrs = NA.Addr->getAttrs();
52 uint16_t Kind = NodeAttrs::kind(Attrs);
53 uint16_t Flags = NodeAttrs::flags(Attrs);
54 switch (NodeAttrs::type(Attrs)) {
55 case NodeAttrs::Code:
56 switch (Kind) {
57 case NodeAttrs::Func: OS << 'f'; break;
58 case NodeAttrs::Block: OS << 'b'; break;
59 case NodeAttrs::Stmt: OS << 's'; break;
60 case NodeAttrs::Phi: OS << 'p'; break;
61 default: OS << "c?"; break;
62 }
63 break;
64 case NodeAttrs::Ref:
65 if (Flags & NodeAttrs::Preserving)
66 OS << '+';
67 if (Flags & NodeAttrs::Clobbering)
68 OS << '~';
69 switch (Kind) {
70 case NodeAttrs::Use: OS << 'u'; break;
71 case NodeAttrs::Def: OS << 'd'; break;
72 case NodeAttrs::Block: OS << 'b'; break;
73 default: OS << "r?"; break;
74 }
75 break;
76 default:
77 OS << '?';
78 break;
79 }
80 OS << P.Obj;
81 if (Flags & NodeAttrs::Shadow)
82 OS << '"';
83 return OS;
84}
85
86namespace {
87 void printRefHeader(raw_ostream &OS, const NodeAddr<RefNode*> RA,
88 const DataFlowGraph &G) {
89 OS << Print<NodeId>(RA.Id, G) << '<'
90 << Print<RegisterRef>(RA.Addr->getRegRef(), G) << '>';
91 if (RA.Addr->getFlags() & NodeAttrs::Fixed)
92 OS << '!';
93 }
94}
95
96template<>
97raw_ostream &operator<< (raw_ostream &OS, const Print<NodeAddr<DefNode*>> &P) {
98 printRefHeader(OS, P.Obj, P.G);
99 OS << '(';
100 if (NodeId N = P.Obj.Addr->getReachingDef())
101 OS << Print<NodeId>(N, P.G);
102 OS << ',';
103 if (NodeId N = P.Obj.Addr->getReachedDef())
104 OS << Print<NodeId>(N, P.G);
105 OS << ',';
106 if (NodeId N = P.Obj.Addr->getReachedUse())
107 OS << Print<NodeId>(N, P.G);
108 OS << "):";
109 if (NodeId N = P.Obj.Addr->getSibling())
110 OS << Print<NodeId>(N, P.G);
111 return OS;
112}
113
114template<>
115raw_ostream &operator<< (raw_ostream &OS, const Print<NodeAddr<UseNode*>> &P) {
116 printRefHeader(OS, P.Obj, P.G);
117 OS << '(';
118 if (NodeId N = P.Obj.Addr->getReachingDef())
119 OS << Print<NodeId>(N, P.G);
120 OS << "):";
121 if (NodeId N = P.Obj.Addr->getSibling())
122 OS << Print<NodeId>(N, P.G);
123 return OS;
124}
125
126template<>
127raw_ostream &operator<< (raw_ostream &OS,
128 const Print<NodeAddr<PhiUseNode*>> &P) {
129 printRefHeader(OS, P.Obj, P.G);
130 OS << '(';
131 if (NodeId N = P.Obj.Addr->getReachingDef())
132 OS << Print<NodeId>(N, P.G);
133 OS << ',';
134 if (NodeId N = P.Obj.Addr->getPredecessor())
135 OS << Print<NodeId>(N, P.G);
136 OS << "):";
137 if (NodeId N = P.Obj.Addr->getSibling())
138 OS << Print<NodeId>(N, P.G);
139 return OS;
140}
141
142template<>
143raw_ostream &operator<< (raw_ostream &OS, const Print<NodeAddr<RefNode*>> &P) {
144 switch (P.Obj.Addr->getKind()) {
145 case NodeAttrs::Def:
146 OS << PrintNode<DefNode*>(P.Obj, P.G);
147 break;
148 case NodeAttrs::Use:
149 if (P.Obj.Addr->getFlags() & NodeAttrs::PhiRef)
150 OS << PrintNode<PhiUseNode*>(P.Obj, P.G);
151 else
152 OS << PrintNode<UseNode*>(P.Obj, P.G);
153 break;
154 }
155 return OS;
156}
157
158template<>
159raw_ostream &operator<< (raw_ostream &OS, const Print<NodeList> &P) {
160 unsigned N = P.Obj.size();
161 for (auto I : P.Obj) {
162 OS << Print<NodeId>(I.Id, P.G);
163 if (--N)
164 OS << ' ';
165 }
166 return OS;
167}
168
169template<>
170raw_ostream &operator<< (raw_ostream &OS, const Print<NodeSet> &P) {
171 unsigned N = P.Obj.size();
172 for (auto I : P.Obj) {
173 OS << Print<NodeId>(I, P.G);
174 if (--N)
175 OS << ' ';
176 }
177 return OS;
178}
179
180namespace {
181 template <typename T>
182 struct PrintListV {
183 PrintListV(const NodeList &L, const DataFlowGraph &G) : List(L), G(G) {}
184 typedef T Type;
185 const NodeList &List;
186 const DataFlowGraph &G;
187 };
188
189 template <typename T>
190 raw_ostream &operator<< (raw_ostream &OS, const PrintListV<T> &P) {
191 unsigned N = P.List.size();
192 for (NodeAddr<T> A : P.List) {
193 OS << PrintNode<T>(A, P.G);
194 if (--N)
195 OS << ", ";
196 }
197 return OS;
198 }
199}
200
201template<>
202raw_ostream &operator<< (raw_ostream &OS, const Print<NodeAddr<PhiNode*>> &P) {
203 OS << Print<NodeId>(P.Obj.Id, P.G) << ": phi ["
204 << PrintListV<RefNode*>(P.Obj.Addr->members(P.G), P.G) << ']';
205 return OS;
206}
207
208template<>
209raw_ostream &operator<< (raw_ostream &OS,
210 const Print<NodeAddr<StmtNode*>> &P) {
211 unsigned Opc = P.Obj.Addr->getCode()->getOpcode();
212 OS << Print<NodeId>(P.Obj.Id, P.G) << ": " << P.G.getTII().getName(Opc)
213 << " [" << PrintListV<RefNode*>(P.Obj.Addr->members(P.G), P.G) << ']';
214 return OS;
215}
216
217template<>
218raw_ostream &operator<< (raw_ostream &OS,
219 const Print<NodeAddr<InstrNode*>> &P) {
220 switch (P.Obj.Addr->getKind()) {
221 case NodeAttrs::Phi:
222 OS << PrintNode<PhiNode*>(P.Obj, P.G);
223 break;
224 case NodeAttrs::Stmt:
225 OS << PrintNode<StmtNode*>(P.Obj, P.G);
226 break;
227 default:
228 OS << "instr? " << Print<NodeId>(P.Obj.Id, P.G);
229 break;
230 }
231 return OS;
232}
233
234template<>
235raw_ostream &operator<< (raw_ostream &OS,
236 const Print<NodeAddr<BlockNode*>> &P) {
237 auto *BB = P.Obj.Addr->getCode();
238 unsigned NP = BB->pred_size();
239 std::vector<int> Ns;
240 auto PrintBBs = [&OS,&P] (std::vector<int> Ns) -> void {
241 unsigned N = Ns.size();
242 for (auto I : Ns) {
243 OS << "BB#" << I;
244 if (--N)
245 OS << ", ";
246 }
247 };
248
249 OS << Print<NodeId>(P.Obj.Id, P.G) << ": === BB#" << BB->getNumber()
250 << " === preds(" << NP << "): ";
251 for (auto I : BB->predecessors())
252 Ns.push_back(I->getNumber());
253 PrintBBs(Ns);
254
255 unsigned NS = BB->succ_size();
256 OS << " succs(" << NS << "): ";
257 Ns.clear();
258 for (auto I : BB->successors())
259 Ns.push_back(I->getNumber());
260 PrintBBs(Ns);
261 OS << '\n';
262
263 for (auto I : P.Obj.Addr->members(P.G))
264 OS << PrintNode<InstrNode*>(I, P.G) << '\n';
265 return OS;
266}
267
268template<>
269raw_ostream &operator<< (raw_ostream &OS,
270 const Print<NodeAddr<FuncNode*>> &P) {
271 OS << "DFG dump:[\n" << Print<NodeId>(P.Obj.Id, P.G) << ": Function: "
272 << P.Obj.Addr->getCode()->getName() << '\n';
273 for (auto I : P.Obj.Addr->members(P.G))
274 OS << PrintNode<BlockNode*>(I, P.G) << '\n';
275 OS << "]\n";
276 return OS;
277}
278
279template<>
280raw_ostream &operator<< (raw_ostream &OS, const Print<RegisterSet> &P) {
281 OS << '{';
282 for (auto I : P.Obj)
283 OS << ' ' << Print<RegisterRef>(I, P.G);
284 OS << " }";
285 return OS;
286}
287
288template<>
289raw_ostream &operator<< (raw_ostream &OS,
290 const Print<DataFlowGraph::DefStack> &P) {
291 for (auto I = P.Obj.top(), E = P.Obj.bottom(); I != E; ) {
292 OS << Print<NodeId>(I->Id, P.G)
293 << '<' << Print<RegisterRef>(I->Addr->getRegRef(), P.G) << '>';
294 I.down();
295 if (I != E)
296 OS << ' ';
297 }
298 return OS;
299}
300
301} // namespace rdf
Benjamin Kramer922efd72016-05-27 10:06:40 +0000302} // namespace llvm
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000303
304// Node allocation functions.
305//
306// Node allocator is like a slab memory allocator: it allocates blocks of
307// memory in sizes that are multiples of the size of a node. Each block has
308// the same size. Nodes are allocated from the currently active block, and
309// when it becomes full, a new one is created.
310// There is a mapping scheme between node id and its location in a block,
311// and within that block is described in the header file.
312//
313void NodeAllocator::startNewBlock() {
314 void *T = MemPool.Allocate(NodesPerBlock*NodeMemSize, NodeMemSize);
315 char *P = static_cast<char*>(T);
316 Blocks.push_back(P);
317 // Check if the block index is still within the allowed range, i.e. less
318 // than 2^N, where N is the number of bits in NodeId for the block index.
319 // BitsPerIndex is the number of bits per node index.
Simon Pilgrim99c6c292016-01-18 21:11:19 +0000320 assert((Blocks.size() < ((size_t)1 << (8*sizeof(NodeId)-BitsPerIndex))) &&
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000321 "Out of bits for block index");
322 ActiveEnd = P;
323}
324
325bool NodeAllocator::needNewBlock() {
326 if (Blocks.empty())
327 return true;
328
329 char *ActiveBegin = Blocks.back();
330 uint32_t Index = (ActiveEnd-ActiveBegin)/NodeMemSize;
331 return Index >= NodesPerBlock;
332}
333
334NodeAddr<NodeBase*> NodeAllocator::New() {
335 if (needNewBlock())
336 startNewBlock();
337
338 uint32_t ActiveB = Blocks.size()-1;
339 uint32_t Index = (ActiveEnd - Blocks[ActiveB])/NodeMemSize;
340 NodeAddr<NodeBase*> NA = { reinterpret_cast<NodeBase*>(ActiveEnd),
341 makeId(ActiveB, Index) };
342 ActiveEnd += NodeMemSize;
343 return NA;
344}
345
346NodeId NodeAllocator::id(const NodeBase *P) const {
347 uintptr_t A = reinterpret_cast<uintptr_t>(P);
348 for (unsigned i = 0, n = Blocks.size(); i != n; ++i) {
349 uintptr_t B = reinterpret_cast<uintptr_t>(Blocks[i]);
350 if (A < B || A >= B + NodesPerBlock*NodeMemSize)
351 continue;
352 uint32_t Idx = (A-B)/NodeMemSize;
353 return makeId(i, Idx);
354 }
355 llvm_unreachable("Invalid node address");
356}
357
358void NodeAllocator::clear() {
359 MemPool.Reset();
360 Blocks.clear();
361 ActiveEnd = nullptr;
362}
363
364
365// Insert node NA after "this" in the circular chain.
366void NodeBase::append(NodeAddr<NodeBase*> NA) {
367 NodeId Nx = Next;
368 // If NA is already "next", do nothing.
369 if (Next != NA.Id) {
370 Next = NA.Id;
371 NA.Addr->Next = Nx;
372 }
373}
374
375
376// Fundamental node manipulator functions.
377
378// Obtain the register reference from a reference node.
379RegisterRef RefNode::getRegRef() const {
380 assert(NodeAttrs::type(Attrs) == NodeAttrs::Ref);
381 if (NodeAttrs::flags(Attrs) & NodeAttrs::PhiRef)
382 return Ref.RR;
383 assert(Ref.Op != nullptr);
384 return { Ref.Op->getReg(), Ref.Op->getSubReg() };
385}
386
387// Set the register reference in the reference node directly (for references
388// in phi nodes).
389void RefNode::setRegRef(RegisterRef RR) {
390 assert(NodeAttrs::type(Attrs) == NodeAttrs::Ref);
391 assert(NodeAttrs::flags(Attrs) & NodeAttrs::PhiRef);
392 Ref.RR = RR;
393}
394
395// Set the register reference in the reference node based on a machine
396// operand (for references in statement nodes).
397void RefNode::setRegRef(MachineOperand *Op) {
398 assert(NodeAttrs::type(Attrs) == NodeAttrs::Ref);
399 assert(!(NodeAttrs::flags(Attrs) & NodeAttrs::PhiRef));
400 Ref.Op = Op;
401}
402
403// Get the owner of a given reference node.
404NodeAddr<NodeBase*> RefNode::getOwner(const DataFlowGraph &G) {
405 NodeAddr<NodeBase*> NA = G.addr<NodeBase*>(getNext());
406
407 while (NA.Addr != this) {
408 if (NA.Addr->getType() == NodeAttrs::Code)
409 return NA;
410 NA = G.addr<NodeBase*>(NA.Addr->getNext());
411 }
412 llvm_unreachable("No owner in circular list");
413}
414
415// Connect the def node to the reaching def node.
416void DefNode::linkToDef(NodeId Self, NodeAddr<DefNode*> DA) {
417 Ref.RD = DA.Id;
418 Ref.Sib = DA.Addr->getReachedDef();
419 DA.Addr->setReachedDef(Self);
420}
421
422// Connect the use node to the reaching def node.
423void UseNode::linkToDef(NodeId Self, NodeAddr<DefNode*> DA) {
424 Ref.RD = DA.Id;
425 Ref.Sib = DA.Addr->getReachedUse();
426 DA.Addr->setReachedUse(Self);
427}
428
429// Get the first member of the code node.
430NodeAddr<NodeBase*> CodeNode::getFirstMember(const DataFlowGraph &G) const {
431 if (Code.FirstM == 0)
432 return NodeAddr<NodeBase*>();
433 return G.addr<NodeBase*>(Code.FirstM);
434}
435
436// Get the last member of the code node.
437NodeAddr<NodeBase*> CodeNode::getLastMember(const DataFlowGraph &G) const {
438 if (Code.LastM == 0)
439 return NodeAddr<NodeBase*>();
440 return G.addr<NodeBase*>(Code.LastM);
441}
442
443// Add node NA at the end of the member list of the given code node.
444void CodeNode::addMember(NodeAddr<NodeBase*> NA, const DataFlowGraph &G) {
445 auto ML = getLastMember(G);
446 if (ML.Id != 0) {
447 ML.Addr->append(NA);
448 } else {
449 Code.FirstM = NA.Id;
450 NodeId Self = G.id(this);
451 NA.Addr->setNext(Self);
452 }
453 Code.LastM = NA.Id;
454}
455
456// Add node NA after member node MA in the given code node.
457void CodeNode::addMemberAfter(NodeAddr<NodeBase*> MA, NodeAddr<NodeBase*> NA,
458 const DataFlowGraph &G) {
459 MA.Addr->append(NA);
460 if (Code.LastM == MA.Id)
461 Code.LastM = NA.Id;
462}
463
464// Remove member node NA from the given code node.
465void CodeNode::removeMember(NodeAddr<NodeBase*> NA, const DataFlowGraph &G) {
466 auto MA = getFirstMember(G);
467 assert(MA.Id != 0);
468
469 // Special handling if the member to remove is the first member.
470 if (MA.Id == NA.Id) {
471 if (Code.LastM == MA.Id) {
472 // If it is the only member, set both first and last to 0.
473 Code.FirstM = Code.LastM = 0;
474 } else {
475 // Otherwise, advance the first member.
476 Code.FirstM = MA.Addr->getNext();
477 }
478 return;
479 }
480
481 while (MA.Addr != this) {
482 NodeId MX = MA.Addr->getNext();
483 if (MX == NA.Id) {
484 MA.Addr->setNext(NA.Addr->getNext());
485 // If the member to remove happens to be the last one, update the
486 // LastM indicator.
487 if (Code.LastM == NA.Id)
488 Code.LastM = MA.Id;
489 return;
490 }
491 MA = G.addr<NodeBase*>(MX);
492 }
493 llvm_unreachable("No such member");
494}
495
496// Return the list of all members of the code node.
497NodeList CodeNode::members(const DataFlowGraph &G) const {
498 static auto True = [] (NodeAddr<NodeBase*>) -> bool { return true; };
499 return members_if(True, G);
500}
501
502// Return the owner of the given instr node.
503NodeAddr<NodeBase*> InstrNode::getOwner(const DataFlowGraph &G) {
504 NodeAddr<NodeBase*> NA = G.addr<NodeBase*>(getNext());
505
506 while (NA.Addr != this) {
507 assert(NA.Addr->getType() == NodeAttrs::Code);
508 if (NA.Addr->getKind() == NodeAttrs::Block)
509 return NA;
510 NA = G.addr<NodeBase*>(NA.Addr->getNext());
511 }
512 llvm_unreachable("No owner in circular list");
513}
514
515// Add the phi node PA to the given block node.
516void BlockNode::addPhi(NodeAddr<PhiNode*> PA, const DataFlowGraph &G) {
517 auto M = getFirstMember(G);
518 if (M.Id == 0) {
519 addMember(PA, G);
520 return;
521 }
522
523 assert(M.Addr->getType() == NodeAttrs::Code);
524 if (M.Addr->getKind() == NodeAttrs::Stmt) {
525 // If the first member of the block is a statement, insert the phi as
526 // the first member.
527 Code.FirstM = PA.Id;
528 PA.Addr->setNext(M.Id);
529 } else {
530 // If the first member is a phi, find the last phi, and append PA to it.
531 assert(M.Addr->getKind() == NodeAttrs::Phi);
532 NodeAddr<NodeBase*> MN = M;
533 do {
534 M = MN;
535 MN = G.addr<NodeBase*>(M.Addr->getNext());
536 assert(MN.Addr->getType() == NodeAttrs::Code);
537 } while (MN.Addr->getKind() == NodeAttrs::Phi);
538
539 // M is the last phi.
540 addMemberAfter(M, PA, G);
541 }
542}
543
544// Find the block node corresponding to the machine basic block BB in the
545// given func node.
546NodeAddr<BlockNode*> FuncNode::findBlock(const MachineBasicBlock *BB,
547 const DataFlowGraph &G) const {
548 auto EqBB = [BB] (NodeAddr<NodeBase*> NA) -> bool {
549 return NodeAddr<BlockNode*>(NA).Addr->getCode() == BB;
550 };
551 NodeList Ms = members_if(EqBB, G);
552 if (!Ms.empty())
553 return Ms[0];
554 return NodeAddr<BlockNode*>();
555}
556
557// Get the block node for the entry block in the given function.
558NodeAddr<BlockNode*> FuncNode::getEntryBlock(const DataFlowGraph &G) {
559 MachineBasicBlock *EntryB = &getCode()->front();
560 return findBlock(EntryB, G);
561}
562
563
564// Register aliasing information.
565//
566// In theory, the lane information could be used to determine register
567// covering (and aliasing), but depending on the sub-register structure,
568// the lane mask information may be missing. The covering information
569// must be available for this framework to work, so relying solely on
570// the lane data is not sufficient.
571
572// Determine whether RA covers RB.
573bool RegisterAliasInfo::covers(RegisterRef RA, RegisterRef RB) const {
574 if (RA == RB)
575 return true;
576 if (TargetRegisterInfo::isVirtualRegister(RA.Reg)) {
577 assert(TargetRegisterInfo::isVirtualRegister(RB.Reg));
578 if (RA.Reg != RB.Reg)
579 return false;
580 if (RA.Sub == 0)
581 return true;
582 return TRI.composeSubRegIndices(RA.Sub, RB.Sub) == RA.Sub;
583 }
584
585 assert(TargetRegisterInfo::isPhysicalRegister(RA.Reg) &&
586 TargetRegisterInfo::isPhysicalRegister(RB.Reg));
587 unsigned A = RA.Sub != 0 ? TRI.getSubReg(RA.Reg, RA.Sub) : RA.Reg;
588 unsigned B = RB.Sub != 0 ? TRI.getSubReg(RB.Reg, RB.Sub) : RB.Reg;
589 return TRI.isSubRegister(A, B);
590}
591
592// Determine whether RR is covered by the set of references RRs.
593bool RegisterAliasInfo::covers(const RegisterSet &RRs, RegisterRef RR) const {
594 if (RRs.count(RR))
595 return true;
596
597 // For virtual registers, we cannot accurately determine covering based
598 // on subregisters. If RR itself is not present in RRs, but it has a sub-
599 // register reference, check for the super-register alone. Otherwise,
600 // assume non-covering.
601 if (TargetRegisterInfo::isVirtualRegister(RR.Reg)) {
602 if (RR.Sub != 0)
603 return RRs.count({RR.Reg, 0});
604 return false;
605 }
606
607 // If any super-register of RR is present, then RR is covered.
608 unsigned Reg = RR.Sub == 0 ? RR.Reg : TRI.getSubReg(RR.Reg, RR.Sub);
609 for (MCSuperRegIterator SR(Reg, &TRI); SR.isValid(); ++SR)
610 if (RRs.count({*SR, 0}))
611 return true;
612
613 return false;
614}
615
616// Get the list of references aliased to RR.
617std::vector<RegisterRef> RegisterAliasInfo::getAliasSet(RegisterRef RR) const {
618 // Do not include RR in the alias set. For virtual registers return an
619 // empty set.
620 std::vector<RegisterRef> AS;
621 if (TargetRegisterInfo::isVirtualRegister(RR.Reg))
622 return AS;
623 assert(TargetRegisterInfo::isPhysicalRegister(RR.Reg));
624 unsigned R = RR.Reg;
625 if (RR.Sub)
626 R = TRI.getSubReg(RR.Reg, RR.Sub);
627
628 for (MCRegAliasIterator AI(R, &TRI, false); AI.isValid(); ++AI)
629 AS.push_back(RegisterRef({*AI, 0}));
630 return AS;
631}
632
633// Check whether RA and RB are aliased.
634bool RegisterAliasInfo::alias(RegisterRef RA, RegisterRef RB) const {
635 bool VirtA = TargetRegisterInfo::isVirtualRegister(RA.Reg);
636 bool VirtB = TargetRegisterInfo::isVirtualRegister(RB.Reg);
637 bool PhysA = TargetRegisterInfo::isPhysicalRegister(RA.Reg);
638 bool PhysB = TargetRegisterInfo::isPhysicalRegister(RB.Reg);
639
640 if (VirtA != VirtB)
641 return false;
642
643 if (VirtA) {
644 if (RA.Reg != RB.Reg)
645 return false;
646 // RA and RB refer to the same register. If any of them refer to the
647 // whole register, they must be aliased.
648 if (RA.Sub == 0 || RB.Sub == 0)
649 return true;
650 unsigned SA = TRI.getSubRegIdxSize(RA.Sub);
651 unsigned OA = TRI.getSubRegIdxOffset(RA.Sub);
652 unsigned SB = TRI.getSubRegIdxSize(RB.Sub);
653 unsigned OB = TRI.getSubRegIdxOffset(RB.Sub);
654 if (OA <= OB && OA+SA > OB)
655 return true;
656 if (OB <= OA && OB+SB > OA)
657 return true;
658 return false;
659 }
660
661 assert(PhysA && PhysB);
662 (void)PhysA, (void)PhysB;
663 unsigned A = RA.Sub ? TRI.getSubReg(RA.Reg, RA.Sub) : RA.Reg;
664 unsigned B = RB.Sub ? TRI.getSubReg(RB.Reg, RB.Sub) : RB.Reg;
665 for (MCRegAliasIterator I(A, &TRI, true); I.isValid(); ++I)
666 if (B == *I)
667 return true;
668 return false;
669}
670
671
672// Target operand information.
673//
674
675// For a given instruction, check if there are any bits of RR that can remain
676// unchanged across this def.
677bool TargetOperandInfo::isPreserving(const MachineInstr &In, unsigned OpNum)
678 const {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000679 return TII.isPredicated(In);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000680}
681
682// Check if the definition of RR produces an unspecified value.
683bool TargetOperandInfo::isClobbering(const MachineInstr &In, unsigned OpNum)
684 const {
685 if (In.isCall())
686 if (In.getOperand(OpNum).isImplicit())
687 return true;
688 return false;
689}
690
Krzysztof Parzyszekc5a4e262016-04-28 20:33:33 +0000691// Check if the given instruction specifically requires
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000692bool TargetOperandInfo::isFixedReg(const MachineInstr &In, unsigned OpNum)
693 const {
Krzysztof Parzyszekc5a4e262016-04-28 20:33:33 +0000694 if (In.isCall() || In.isReturn() || In.isInlineAsm())
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000695 return true;
Krzysztof Parzyszekbf90d5a2016-04-28 20:40:08 +0000696 // Check for a tail call.
697 if (In.isBranch())
698 for (auto &O : In.operands())
699 if (O.isGlobal() || O.isSymbol())
700 return true;
701
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000702 const MCInstrDesc &D = In.getDesc();
703 if (!D.getImplicitDefs() && !D.getImplicitUses())
704 return false;
705 const MachineOperand &Op = In.getOperand(OpNum);
706 // If there is a sub-register, treat the operand as non-fixed. Currently,
707 // fixed registers are those that are listed in the descriptor as implicit
708 // uses or defs, and those lists do not allow sub-registers.
709 if (Op.getSubReg() != 0)
710 return false;
711 unsigned Reg = Op.getReg();
712 const MCPhysReg *ImpR = Op.isDef() ? D.getImplicitDefs()
713 : D.getImplicitUses();
714 if (!ImpR)
715 return false;
716 while (*ImpR)
717 if (*ImpR++ == Reg)
718 return true;
719 return false;
720}
721
722
723//
724// The data flow graph construction.
725//
726
727DataFlowGraph::DataFlowGraph(MachineFunction &mf, const TargetInstrInfo &tii,
728 const TargetRegisterInfo &tri, const MachineDominatorTree &mdt,
729 const MachineDominanceFrontier &mdf, const RegisterAliasInfo &rai,
730 const TargetOperandInfo &toi)
731 : TimeG("rdf"), MF(mf), TII(tii), TRI(tri), MDT(mdt), MDF(mdf), RAI(rai),
732 TOI(toi) {
733}
734
735
736// The implementation of the definition stack.
737// Each register reference has its own definition stack. In particular,
738// for a register references "Reg" and "Reg:subreg" will each have their
739// own definition stacks.
740
741// Construct a stack iterator.
742DataFlowGraph::DefStack::Iterator::Iterator(const DataFlowGraph::DefStack &S,
743 bool Top) : DS(S) {
744 if (!Top) {
745 // Initialize to bottom.
746 Pos = 0;
747 return;
748 }
749 // Initialize to the top, i.e. top-most non-delimiter (or 0, if empty).
750 Pos = DS.Stack.size();
751 while (Pos > 0 && DS.isDelimiter(DS.Stack[Pos-1]))
752 Pos--;
753}
754
755// Return the size of the stack, including block delimiters.
756unsigned DataFlowGraph::DefStack::size() const {
757 unsigned S = 0;
758 for (auto I = top(), E = bottom(); I != E; I.down())
759 S++;
760 return S;
761}
762
763// Remove the top entry from the stack. Remove all intervening delimiters
764// so that after this, the stack is either empty, or the top of the stack
765// is a non-delimiter.
766void DataFlowGraph::DefStack::pop() {
767 assert(!empty());
768 unsigned P = nextDown(Stack.size());
769 Stack.resize(P);
770}
771
772// Push a delimiter for block node N on the stack.
773void DataFlowGraph::DefStack::start_block(NodeId N) {
774 assert(N != 0);
775 Stack.push_back(NodeAddr<DefNode*>(nullptr, N));
776}
777
778// Remove all nodes from the top of the stack, until the delimited for
779// block node N is encountered. Remove the delimiter as well. In effect,
780// this will remove from the stack all definitions from block N.
781void DataFlowGraph::DefStack::clear_block(NodeId N) {
782 assert(N != 0);
783 unsigned P = Stack.size();
784 while (P > 0) {
785 bool Found = isDelimiter(Stack[P-1], N);
786 P--;
787 if (Found)
788 break;
789 }
790 // This will also remove the delimiter, if found.
791 Stack.resize(P);
792}
793
794// Move the stack iterator up by one.
795unsigned DataFlowGraph::DefStack::nextUp(unsigned P) const {
796 // Get the next valid position after P (skipping all delimiters).
797 // The input position P does not have to point to a non-delimiter.
798 unsigned SS = Stack.size();
799 bool IsDelim;
Krzysztof Parzyszek8dca45e2016-01-12 16:51:55 +0000800 assert(P < SS);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000801 do {
802 P++;
803 IsDelim = isDelimiter(Stack[P-1]);
804 } while (P < SS && IsDelim);
805 assert(!IsDelim);
806 return P;
807}
808
809// Move the stack iterator down by one.
810unsigned DataFlowGraph::DefStack::nextDown(unsigned P) const {
811 // Get the preceding valid position before P (skipping all delimiters).
812 // The input position P does not have to point to a non-delimiter.
813 assert(P > 0 && P <= Stack.size());
814 bool IsDelim = isDelimiter(Stack[P-1]);
815 do {
816 if (--P == 0)
817 break;
818 IsDelim = isDelimiter(Stack[P-1]);
819 } while (P > 0 && IsDelim);
820 assert(!IsDelim);
821 return P;
822}
823
824// Node management functions.
825
826// Get the pointer to the node with the id N.
827NodeBase *DataFlowGraph::ptr(NodeId N) const {
828 if (N == 0)
829 return nullptr;
830 return Memory.ptr(N);
831}
832
833// Get the id of the node at the address P.
834NodeId DataFlowGraph::id(const NodeBase *P) const {
835 if (P == nullptr)
836 return 0;
837 return Memory.id(P);
838}
839
840// Allocate a new node and set the attributes to Attrs.
841NodeAddr<NodeBase*> DataFlowGraph::newNode(uint16_t Attrs) {
842 NodeAddr<NodeBase*> P = Memory.New();
843 P.Addr->init();
844 P.Addr->setAttrs(Attrs);
845 return P;
846}
847
848// Make a copy of the given node B, except for the data-flow links, which
849// are set to 0.
850NodeAddr<NodeBase*> DataFlowGraph::cloneNode(const NodeAddr<NodeBase*> B) {
851 NodeAddr<NodeBase*> NA = newNode(0);
852 memcpy(NA.Addr, B.Addr, sizeof(NodeBase));
853 // Ref nodes need to have the data-flow links reset.
854 if (NA.Addr->getType() == NodeAttrs::Ref) {
855 NodeAddr<RefNode*> RA = NA;
856 RA.Addr->setReachingDef(0);
857 RA.Addr->setSibling(0);
858 if (NA.Addr->getKind() == NodeAttrs::Def) {
859 NodeAddr<DefNode*> DA = NA;
860 DA.Addr->setReachedDef(0);
861 DA.Addr->setReachedUse(0);
862 }
863 }
864 return NA;
865}
866
867
868// Allocation routines for specific node types/kinds.
869
870NodeAddr<UseNode*> DataFlowGraph::newUse(NodeAddr<InstrNode*> Owner,
871 MachineOperand &Op, uint16_t Flags) {
872 NodeAddr<UseNode*> UA = newNode(NodeAttrs::Ref | NodeAttrs::Use | Flags);
873 UA.Addr->setRegRef(&Op);
874 return UA;
875}
876
877NodeAddr<PhiUseNode*> DataFlowGraph::newPhiUse(NodeAddr<PhiNode*> Owner,
878 RegisterRef RR, NodeAddr<BlockNode*> PredB, uint16_t Flags) {
879 NodeAddr<PhiUseNode*> PUA = newNode(NodeAttrs::Ref | NodeAttrs::Use | Flags);
880 assert(Flags & NodeAttrs::PhiRef);
881 PUA.Addr->setRegRef(RR);
882 PUA.Addr->setPredecessor(PredB.Id);
883 return PUA;
884}
885
886NodeAddr<DefNode*> DataFlowGraph::newDef(NodeAddr<InstrNode*> Owner,
887 MachineOperand &Op, uint16_t Flags) {
888 NodeAddr<DefNode*> DA = newNode(NodeAttrs::Ref | NodeAttrs::Def | Flags);
889 DA.Addr->setRegRef(&Op);
890 return DA;
891}
892
893NodeAddr<DefNode*> DataFlowGraph::newDef(NodeAddr<InstrNode*> Owner,
894 RegisterRef RR, uint16_t Flags) {
895 NodeAddr<DefNode*> DA = newNode(NodeAttrs::Ref | NodeAttrs::Def | Flags);
896 assert(Flags & NodeAttrs::PhiRef);
897 DA.Addr->setRegRef(RR);
898 return DA;
899}
900
901NodeAddr<PhiNode*> DataFlowGraph::newPhi(NodeAddr<BlockNode*> Owner) {
902 NodeAddr<PhiNode*> PA = newNode(NodeAttrs::Code | NodeAttrs::Phi);
903 Owner.Addr->addPhi(PA, *this);
904 return PA;
905}
906
907NodeAddr<StmtNode*> DataFlowGraph::newStmt(NodeAddr<BlockNode*> Owner,
908 MachineInstr *MI) {
909 NodeAddr<StmtNode*> SA = newNode(NodeAttrs::Code | NodeAttrs::Stmt);
910 SA.Addr->setCode(MI);
911 Owner.Addr->addMember(SA, *this);
912 return SA;
913}
914
915NodeAddr<BlockNode*> DataFlowGraph::newBlock(NodeAddr<FuncNode*> Owner,
916 MachineBasicBlock *BB) {
917 NodeAddr<BlockNode*> BA = newNode(NodeAttrs::Code | NodeAttrs::Block);
918 BA.Addr->setCode(BB);
919 Owner.Addr->addMember(BA, *this);
920 return BA;
921}
922
923NodeAddr<FuncNode*> DataFlowGraph::newFunc(MachineFunction *MF) {
924 NodeAddr<FuncNode*> FA = newNode(NodeAttrs::Code | NodeAttrs::Func);
925 FA.Addr->setCode(MF);
926 return FA;
927}
928
929// Build the data flow graph.
Krzysztof Parzyszek55874cf2016-04-28 20:17:06 +0000930void DataFlowGraph::build(unsigned Options) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000931 reset();
932 Func = newFunc(&MF);
933
934 if (MF.empty())
935 return;
936
937 for (auto &B : MF) {
938 auto BA = newBlock(Func, &B);
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +0000939 BlockNodes.insert(std::make_pair(&B, BA));
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000940 for (auto &I : B) {
941 if (I.isDebugValue())
942 continue;
943 buildStmt(BA, I);
944 }
945 }
946
947 // Collect information about block references.
948 NodeAddr<BlockNode*> EA = Func.Addr->getEntryBlock(*this);
949 BlockRefsMap RefM;
950 buildBlockRefs(EA, RefM);
951
952 // Add function-entry phi nodes.
953 MachineRegisterInfo &MRI = MF.getRegInfo();
954 for (auto I = MRI.livein_begin(), E = MRI.livein_end(); I != E; ++I) {
955 NodeAddr<PhiNode*> PA = newPhi(EA);
956 RegisterRef RR = { I->first, 0 };
957 uint16_t PhiFlags = NodeAttrs::PhiRef | NodeAttrs::Preserving;
958 NodeAddr<DefNode*> DA = newDef(PA, RR, PhiFlags);
959 PA.Addr->addMember(DA, *this);
960 }
961
962 // Build a map "PhiM" which will contain, for each block, the set
963 // of references that will require phi definitions in that block.
964 BlockRefsMap PhiM;
965 auto Blocks = Func.Addr->members(*this);
966 for (NodeAddr<BlockNode*> BA : Blocks)
967 recordDefsForDF(PhiM, RefM, BA);
968 for (NodeAddr<BlockNode*> BA : Blocks)
969 buildPhis(PhiM, RefM, BA);
970
971 // Link all the refs. This will recursively traverse the dominator tree.
972 DefStackMap DM;
973 linkBlockRefs(DM, EA);
974
975 // Finally, remove all unused phi nodes.
Krzysztof Parzyszek55874cf2016-04-28 20:17:06 +0000976 if (!(Options & BuildOptions::KeepDeadPhis))
977 removeUnusedPhis();
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000978}
979
980// For each stack in the map DefM, push the delimiter for block B on it.
981void DataFlowGraph::markBlock(NodeId B, DefStackMap &DefM) {
982 // Push block delimiters.
983 for (auto I = DefM.begin(), E = DefM.end(); I != E; ++I)
984 I->second.start_block(B);
985}
986
987// Remove all definitions coming from block B from each stack in DefM.
988void DataFlowGraph::releaseBlock(NodeId B, DefStackMap &DefM) {
989 // Pop all defs from this block from the definition stack. Defs that were
990 // added to the map during the traversal of instructions will not have a
991 // delimiter, but for those, the whole stack will be emptied.
992 for (auto I = DefM.begin(), E = DefM.end(); I != E; ++I)
993 I->second.clear_block(B);
994
995 // Finally, remove empty stacks from the map.
996 for (auto I = DefM.begin(), E = DefM.end(), NextI = I; I != E; I = NextI) {
997 NextI = std::next(I);
998 // This preserves the validity of iterators other than I.
999 if (I->second.empty())
1000 DefM.erase(I);
1001 }
1002}
1003
1004// Push all definitions from the instruction node IA to an appropriate
1005// stack in DefM.
1006void DataFlowGraph::pushDefs(NodeAddr<InstrNode*> IA, DefStackMap &DefM) {
1007 NodeList Defs = IA.Addr->members_if(IsDef, *this);
1008 NodeSet Visited;
1009#ifndef NDEBUG
1010 RegisterSet Defined;
1011#endif
1012
1013 // The important objectives of this function are:
1014 // - to be able to handle instructions both while the graph is being
1015 // constructed, and after the graph has been constructed, and
1016 // - maintain proper ordering of definitions on the stack for each
1017 // register reference:
1018 // - if there are two or more related defs in IA (i.e. coming from
1019 // the same machine operand), then only push one def on the stack,
1020 // - if there are multiple unrelated defs of non-overlapping
1021 // subregisters of S, then the stack for S will have both (in an
1022 // unspecified order), but the order does not matter from the data-
1023 // -flow perspective.
1024
1025 for (NodeAddr<DefNode*> DA : Defs) {
1026 if (Visited.count(DA.Id))
1027 continue;
1028 NodeList Rel = getRelatedRefs(IA, DA);
1029 NodeAddr<DefNode*> PDA = Rel.front();
1030 // Push the definition on the stack for the register and all aliases.
1031 RegisterRef RR = PDA.Addr->getRegRef();
1032#ifndef NDEBUG
1033 // Assert if the register is defined in two or more unrelated defs.
1034 // This could happen if there are two or more def operands defining it.
1035 if (!Defined.insert(RR).second) {
1036 auto *MI = NodeAddr<StmtNode*>(IA).Addr->getCode();
1037 dbgs() << "Multiple definitions of register: "
1038 << Print<RegisterRef>(RR, *this) << " in\n " << *MI
1039 << "in BB#" << MI->getParent()->getNumber() << '\n';
1040 llvm_unreachable(nullptr);
1041 }
1042#endif
1043 DefM[RR].push(DA);
1044 for (auto A : RAI.getAliasSet(RR)) {
1045 assert(A != RR);
1046 DefM[A].push(DA);
1047 }
1048 // Mark all the related defs as visited.
1049 for (auto T : Rel)
1050 Visited.insert(T.Id);
1051 }
1052}
1053
1054// Return the list of all reference nodes related to RA, including RA itself.
1055// See "getNextRelated" for the meaning of a "related reference".
1056NodeList DataFlowGraph::getRelatedRefs(NodeAddr<InstrNode*> IA,
1057 NodeAddr<RefNode*> RA) const {
1058 assert(IA.Id != 0 && RA.Id != 0);
1059
1060 NodeList Refs;
1061 NodeId Start = RA.Id;
1062 do {
1063 Refs.push_back(RA);
1064 RA = getNextRelated(IA, RA);
1065 } while (RA.Id != 0 && RA.Id != Start);
1066 return Refs;
1067}
1068
1069
1070// Clear all information in the graph.
1071void DataFlowGraph::reset() {
1072 Memory.clear();
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +00001073 BlockNodes.clear();
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001074 Func = NodeAddr<FuncNode*>();
1075}
1076
1077
1078// Return the next reference node in the instruction node IA that is related
1079// to RA. Conceptually, two reference nodes are related if they refer to the
1080// same instance of a register access, but differ in flags or other minor
1081// characteristics. Specific examples of related nodes are shadow reference
1082// nodes.
1083// Return the equivalent of nullptr if there are no more related references.
1084NodeAddr<RefNode*> DataFlowGraph::getNextRelated(NodeAddr<InstrNode*> IA,
1085 NodeAddr<RefNode*> RA) const {
1086 assert(IA.Id != 0 && RA.Id != 0);
1087
1088 auto Related = [RA](NodeAddr<RefNode*> TA) -> bool {
1089 if (TA.Addr->getKind() != RA.Addr->getKind())
1090 return false;
1091 if (TA.Addr->getRegRef() != RA.Addr->getRegRef())
1092 return false;
1093 return true;
1094 };
1095 auto RelatedStmt = [&Related,RA](NodeAddr<RefNode*> TA) -> bool {
1096 return Related(TA) &&
1097 &RA.Addr->getOp() == &TA.Addr->getOp();
1098 };
1099 auto RelatedPhi = [&Related,RA](NodeAddr<RefNode*> TA) -> bool {
1100 if (!Related(TA))
1101 return false;
1102 if (TA.Addr->getKind() != NodeAttrs::Use)
1103 return true;
1104 // For phi uses, compare predecessor blocks.
1105 const NodeAddr<const PhiUseNode*> TUA = TA;
1106 const NodeAddr<const PhiUseNode*> RUA = RA;
1107 return TUA.Addr->getPredecessor() == RUA.Addr->getPredecessor();
1108 };
1109
1110 RegisterRef RR = RA.Addr->getRegRef();
1111 if (IA.Addr->getKind() == NodeAttrs::Stmt)
1112 return RA.Addr->getNextRef(RR, RelatedStmt, true, *this);
1113 return RA.Addr->getNextRef(RR, RelatedPhi, true, *this);
1114}
1115
1116// Find the next node related to RA in IA that satisfies condition P.
1117// If such a node was found, return a pair where the second element is the
1118// located node. If such a node does not exist, return a pair where the
1119// first element is the element after which such a node should be inserted,
1120// and the second element is a null-address.
1121template <typename Predicate>
1122std::pair<NodeAddr<RefNode*>,NodeAddr<RefNode*>>
1123DataFlowGraph::locateNextRef(NodeAddr<InstrNode*> IA, NodeAddr<RefNode*> RA,
1124 Predicate P) const {
1125 assert(IA.Id != 0 && RA.Id != 0);
1126
1127 NodeAddr<RefNode*> NA;
1128 NodeId Start = RA.Id;
1129 while (true) {
1130 NA = getNextRelated(IA, RA);
1131 if (NA.Id == 0 || NA.Id == Start)
1132 break;
1133 if (P(NA))
1134 break;
1135 RA = NA;
1136 }
1137
1138 if (NA.Id != 0 && NA.Id != Start)
1139 return std::make_pair(RA, NA);
1140 return std::make_pair(RA, NodeAddr<RefNode*>());
1141}
1142
1143// Get the next shadow node in IA corresponding to RA, and optionally create
1144// such a node if it does not exist.
1145NodeAddr<RefNode*> DataFlowGraph::getNextShadow(NodeAddr<InstrNode*> IA,
1146 NodeAddr<RefNode*> RA, bool Create) {
1147 assert(IA.Id != 0 && RA.Id != 0);
1148
1149 uint16_t Flags = RA.Addr->getFlags() | NodeAttrs::Shadow;
1150 auto IsShadow = [Flags] (NodeAddr<RefNode*> TA) -> bool {
1151 return TA.Addr->getFlags() == Flags;
1152 };
1153 auto Loc = locateNextRef(IA, RA, IsShadow);
1154 if (Loc.second.Id != 0 || !Create)
1155 return Loc.second;
1156
1157 // Create a copy of RA and mark is as shadow.
1158 NodeAddr<RefNode*> NA = cloneNode(RA);
1159 NA.Addr->setFlags(Flags | NodeAttrs::Shadow);
1160 IA.Addr->addMemberAfter(Loc.first, NA, *this);
1161 return NA;
1162}
1163
1164// Get the next shadow node in IA corresponding to RA. Return null-address
1165// if such a node does not exist.
1166NodeAddr<RefNode*> DataFlowGraph::getNextShadow(NodeAddr<InstrNode*> IA,
1167 NodeAddr<RefNode*> RA) const {
1168 assert(IA.Id != 0 && RA.Id != 0);
1169 uint16_t Flags = RA.Addr->getFlags() | NodeAttrs::Shadow;
1170 auto IsShadow = [Flags] (NodeAddr<RefNode*> TA) -> bool {
1171 return TA.Addr->getFlags() == Flags;
1172 };
1173 return locateNextRef(IA, RA, IsShadow).second;
1174}
1175
1176// Create a new statement node in the block node BA that corresponds to
1177// the machine instruction MI.
1178void DataFlowGraph::buildStmt(NodeAddr<BlockNode*> BA, MachineInstr &In) {
1179 auto SA = newStmt(BA, &In);
1180
Krzysztof Parzyszekbf90d5a2016-04-28 20:40:08 +00001181 auto isCall = [] (const MachineInstr &In) -> bool {
1182 if (In.isCall())
1183 return true;
1184 // Is tail call?
1185 if (In.isBranch())
1186 for (auto &Op : In.operands())
1187 if (Op.isGlobal() || Op.isSymbol())
1188 return true;
1189 return false;
1190 };
1191
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001192 // Collect a set of registers that this instruction implicitly uses
1193 // or defines. Implicit operands from an instruction will be ignored
1194 // unless they are listed here.
1195 RegisterSet ImpUses, ImpDefs;
1196 if (const uint16_t *ImpD = In.getDesc().getImplicitDefs())
1197 while (uint16_t R = *ImpD++)
1198 ImpDefs.insert({R, 0});
1199 if (const uint16_t *ImpU = In.getDesc().getImplicitUses())
1200 while (uint16_t R = *ImpU++)
1201 ImpUses.insert({R, 0});
1202
Krzysztof Parzyszekbf90d5a2016-04-28 20:40:08 +00001203 bool NeedsImplicit = isCall(In) || In.isInlineAsm() || In.isReturn();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001204 bool IsPredicated = TII.isPredicated(In);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001205 unsigned NumOps = In.getNumOperands();
1206
1207 // Avoid duplicate implicit defs. This will not detect cases of implicit
1208 // defs that define registers that overlap, but it is not clear how to
1209 // interpret that in the absence of explicit defs. Overlapping explicit
1210 // defs are likely illegal already.
1211 RegisterSet DoneDefs;
1212 // Process explicit defs first.
1213 for (unsigned OpN = 0; OpN < NumOps; ++OpN) {
1214 MachineOperand &Op = In.getOperand(OpN);
1215 if (!Op.isReg() || !Op.isDef() || Op.isImplicit())
1216 continue;
1217 RegisterRef RR = { Op.getReg(), Op.getSubReg() };
1218 uint16_t Flags = NodeAttrs::None;
1219 if (TOI.isPreserving(In, OpN))
1220 Flags |= NodeAttrs::Preserving;
1221 if (TOI.isClobbering(In, OpN))
1222 Flags |= NodeAttrs::Clobbering;
1223 if (TOI.isFixedReg(In, OpN))
1224 Flags |= NodeAttrs::Fixed;
1225 NodeAddr<DefNode*> DA = newDef(SA, Op, Flags);
1226 SA.Addr->addMember(DA, *this);
1227 DoneDefs.insert(RR);
1228 }
1229
1230 // Process implicit defs, skipping those that have already been added
1231 // as explicit.
1232 for (unsigned OpN = 0; OpN < NumOps; ++OpN) {
1233 MachineOperand &Op = In.getOperand(OpN);
1234 if (!Op.isReg() || !Op.isDef() || !Op.isImplicit())
1235 continue;
1236 RegisterRef RR = { Op.getReg(), Op.getSubReg() };
Krzysztof Parzyszekbf90d5a2016-04-28 20:40:08 +00001237 if (!NeedsImplicit && !ImpDefs.count(RR))
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001238 continue;
1239 if (DoneDefs.count(RR))
1240 continue;
1241 uint16_t Flags = NodeAttrs::None;
1242 if (TOI.isPreserving(In, OpN))
1243 Flags |= NodeAttrs::Preserving;
1244 if (TOI.isClobbering(In, OpN))
1245 Flags |= NodeAttrs::Clobbering;
1246 if (TOI.isFixedReg(In, OpN))
1247 Flags |= NodeAttrs::Fixed;
1248 NodeAddr<DefNode*> DA = newDef(SA, Op, Flags);
1249 SA.Addr->addMember(DA, *this);
1250 DoneDefs.insert(RR);
1251 }
1252
1253 for (unsigned OpN = 0; OpN < NumOps; ++OpN) {
1254 MachineOperand &Op = In.getOperand(OpN);
1255 if (!Op.isReg() || !Op.isUse())
1256 continue;
1257 RegisterRef RR = { Op.getReg(), Op.getSubReg() };
1258 // Add implicit uses on return and call instructions, and on predicated
1259 // instructions regardless of whether or not they appear in the instruction
1260 // descriptor's list.
1261 bool Implicit = Op.isImplicit();
Krzysztof Parzyszekbf90d5a2016-04-28 20:40:08 +00001262 bool TakeImplicit = NeedsImplicit || IsPredicated;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001263 if (Implicit && !TakeImplicit && !ImpUses.count(RR))
1264 continue;
1265 uint16_t Flags = NodeAttrs::None;
1266 if (TOI.isFixedReg(In, OpN))
1267 Flags |= NodeAttrs::Fixed;
1268 NodeAddr<UseNode*> UA = newUse(SA, Op, Flags);
1269 SA.Addr->addMember(UA, *this);
1270 }
1271}
1272
1273// Build a map that for each block will have the set of all references from
1274// that block, and from all blocks dominated by it.
1275void DataFlowGraph::buildBlockRefs(NodeAddr<BlockNode*> BA,
1276 BlockRefsMap &RefM) {
1277 auto &Refs = RefM[BA.Id];
1278 MachineDomTreeNode *N = MDT.getNode(BA.Addr->getCode());
1279 assert(N);
1280 for (auto I : *N) {
1281 MachineBasicBlock *SB = I->getBlock();
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +00001282 auto SBA = findBlock(SB);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001283 buildBlockRefs(SBA, RefM);
1284 const auto &SRs = RefM[SBA.Id];
1285 Refs.insert(SRs.begin(), SRs.end());
1286 }
1287
1288 for (NodeAddr<InstrNode*> IA : BA.Addr->members(*this))
1289 for (NodeAddr<RefNode*> RA : IA.Addr->members(*this))
1290 Refs.insert(RA.Addr->getRegRef());
1291}
1292
1293// Scan all defs in the block node BA and record in PhiM the locations of
1294// phi nodes corresponding to these defs.
1295void DataFlowGraph::recordDefsForDF(BlockRefsMap &PhiM, BlockRefsMap &RefM,
1296 NodeAddr<BlockNode*> BA) {
1297 // Check all defs from block BA and record them in each block in BA's
1298 // iterated dominance frontier. This information will later be used to
1299 // create phi nodes.
1300 MachineBasicBlock *BB = BA.Addr->getCode();
1301 assert(BB);
1302 auto DFLoc = MDF.find(BB);
1303 if (DFLoc == MDF.end() || DFLoc->second.empty())
1304 return;
1305
1306 // Traverse all instructions in the block and collect the set of all
1307 // defined references. For each reference there will be a phi created
1308 // in the block's iterated dominance frontier.
1309 // This is done to make sure that each defined reference gets only one
1310 // phi node, even if it is defined multiple times.
1311 RegisterSet Defs;
1312 for (auto I : BA.Addr->members(*this)) {
1313 assert(I.Addr->getType() == NodeAttrs::Code);
1314 assert(I.Addr->getKind() == NodeAttrs::Phi ||
1315 I.Addr->getKind() == NodeAttrs::Stmt);
1316 NodeAddr<InstrNode*> IA = I;
1317 for (NodeAddr<RefNode*> RA : IA.Addr->members_if(IsDef, *this))
1318 Defs.insert(RA.Addr->getRegRef());
1319 }
1320
1321 // Finally, add the set of defs to each block in the iterated dominance
1322 // frontier.
1323 const MachineDominanceFrontier::DomSetType &DF = DFLoc->second;
1324 SetVector<MachineBasicBlock*> IDF(DF.begin(), DF.end());
1325 for (unsigned i = 0; i < IDF.size(); ++i) {
1326 auto F = MDF.find(IDF[i]);
1327 if (F != MDF.end())
1328 IDF.insert(F->second.begin(), F->second.end());
1329 }
1330
1331 // Get the register references that are reachable from this block.
1332 RegisterSet &Refs = RefM[BA.Id];
1333 for (auto DB : IDF) {
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +00001334 auto DBA = findBlock(DB);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001335 const auto &Rs = RefM[DBA.Id];
1336 Refs.insert(Rs.begin(), Rs.end());
1337 }
1338
1339 for (auto DB : IDF) {
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +00001340 auto DBA = findBlock(DB);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001341 PhiM[DBA.Id].insert(Defs.begin(), Defs.end());
1342 }
1343}
1344
1345// Given the locations of phi nodes in the map PhiM, create the phi nodes
1346// that are located in the block node BA.
1347void DataFlowGraph::buildPhis(BlockRefsMap &PhiM, BlockRefsMap &RefM,
1348 NodeAddr<BlockNode*> BA) {
1349 // Check if this blocks has any DF defs, i.e. if there are any defs
1350 // that this block is in the iterated dominance frontier of.
1351 auto HasDF = PhiM.find(BA.Id);
1352 if (HasDF == PhiM.end() || HasDF->second.empty())
1353 return;
1354
1355 // First, remove all R in Refs in such that there exists T in Refs
1356 // such that T covers R. In other words, only leave those refs that
1357 // are not covered by another ref (i.e. maximal with respect to covering).
1358
1359 auto MaxCoverIn = [this] (RegisterRef RR, RegisterSet &RRs) -> RegisterRef {
1360 for (auto I : RRs)
1361 if (I != RR && RAI.covers(I, RR))
1362 RR = I;
1363 return RR;
1364 };
1365
1366 RegisterSet MaxDF;
1367 for (auto I : HasDF->second)
1368 MaxDF.insert(MaxCoverIn(I, HasDF->second));
1369
1370 std::vector<RegisterRef> MaxRefs;
1371 auto &RefB = RefM[BA.Id];
1372 for (auto I : MaxDF)
1373 MaxRefs.push_back(MaxCoverIn(I, RefB));
1374
1375 // Now, for each R in MaxRefs, get the alias closure of R. If the closure
1376 // only has R in it, create a phi a def for R. Otherwise, create a phi,
1377 // and add a def for each S in the closure.
1378
1379 // Sort the refs so that the phis will be created in a deterministic order.
1380 std::sort(MaxRefs.begin(), MaxRefs.end());
1381 // Remove duplicates.
1382 auto NewEnd = std::unique(MaxRefs.begin(), MaxRefs.end());
1383 MaxRefs.erase(NewEnd, MaxRefs.end());
1384
1385 auto Aliased = [this,&MaxRefs](RegisterRef RR,
1386 std::vector<unsigned> &Closure) -> bool {
1387 for (auto I : Closure)
1388 if (RAI.alias(RR, MaxRefs[I]))
1389 return true;
1390 return false;
1391 };
1392
1393 // Prepare a list of NodeIds of the block's predecessors.
1394 std::vector<NodeId> PredList;
1395 const MachineBasicBlock *MBB = BA.Addr->getCode();
1396 for (auto PB : MBB->predecessors()) {
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +00001397 auto B = findBlock(PB);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001398 PredList.push_back(B.Id);
1399 }
1400
1401 while (!MaxRefs.empty()) {
1402 // Put the first element in the closure, and then add all subsequent
1403 // elements from MaxRefs to it, if they alias at least one element
1404 // already in the closure.
1405 // ClosureIdx: vector of indices in MaxRefs of members of the closure.
1406 std::vector<unsigned> ClosureIdx = { 0 };
1407 for (unsigned i = 1; i != MaxRefs.size(); ++i)
1408 if (Aliased(MaxRefs[i], ClosureIdx))
1409 ClosureIdx.push_back(i);
1410
1411 // Build a phi for the closure.
1412 unsigned CS = ClosureIdx.size();
1413 NodeAddr<PhiNode*> PA = newPhi(BA);
1414
1415 // Add defs.
1416 for (unsigned X = 0; X != CS; ++X) {
1417 RegisterRef RR = MaxRefs[ClosureIdx[X]];
1418 uint16_t PhiFlags = NodeAttrs::PhiRef | NodeAttrs::Preserving;
1419 NodeAddr<DefNode*> DA = newDef(PA, RR, PhiFlags);
1420 PA.Addr->addMember(DA, *this);
1421 }
1422 // Add phi uses.
1423 for (auto P : PredList) {
1424 auto PBA = addr<BlockNode*>(P);
1425 for (unsigned X = 0; X != CS; ++X) {
1426 RegisterRef RR = MaxRefs[ClosureIdx[X]];
1427 NodeAddr<PhiUseNode*> PUA = newPhiUse(PA, RR, PBA);
1428 PA.Addr->addMember(PUA, *this);
1429 }
1430 }
1431
1432 // Erase from MaxRefs all elements in the closure.
1433 auto Begin = MaxRefs.begin();
1434 for (unsigned i = ClosureIdx.size(); i != 0; --i)
1435 MaxRefs.erase(Begin + ClosureIdx[i-1]);
1436 }
1437}
1438
1439// Remove any unneeded phi nodes that were created during the build process.
1440void DataFlowGraph::removeUnusedPhis() {
1441 // This will remove unused phis, i.e. phis where each def does not reach
1442 // any uses or other defs. This will not detect or remove circular phi
1443 // chains that are otherwise dead. Unused/dead phis are created during
1444 // the build process and this function is intended to remove these cases
1445 // that are easily determinable to be unnecessary.
1446
1447 SetVector<NodeId> PhiQ;
1448 for (NodeAddr<BlockNode*> BA : Func.Addr->members(*this)) {
1449 for (auto P : BA.Addr->members_if(IsPhi, *this))
1450 PhiQ.insert(P.Id);
1451 }
1452
1453 static auto HasUsedDef = [](NodeList &Ms) -> bool {
1454 for (auto M : Ms) {
1455 if (M.Addr->getKind() != NodeAttrs::Def)
1456 continue;
1457 NodeAddr<DefNode*> DA = M;
1458 if (DA.Addr->getReachedDef() != 0 || DA.Addr->getReachedUse() != 0)
1459 return true;
1460 }
1461 return false;
1462 };
1463
1464 // Any phi, if it is removed, may affect other phis (make them dead).
1465 // For each removed phi, collect the potentially affected phis and add
1466 // them back to the queue.
1467 while (!PhiQ.empty()) {
1468 auto PA = addr<PhiNode*>(PhiQ[0]);
1469 PhiQ.remove(PA.Id);
1470 NodeList Refs = PA.Addr->members(*this);
1471 if (HasUsedDef(Refs))
1472 continue;
1473 for (NodeAddr<RefNode*> RA : Refs) {
1474 if (NodeId RD = RA.Addr->getReachingDef()) {
1475 auto RDA = addr<DefNode*>(RD);
1476 NodeAddr<InstrNode*> OA = RDA.Addr->getOwner(*this);
1477 if (IsPhi(OA))
1478 PhiQ.insert(OA.Id);
1479 }
1480 if (RA.Addr->isDef())
Krzysztof Parzyszek69e670d52016-01-18 20:41:34 +00001481 unlinkDef(RA, true);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001482 else
Krzysztof Parzyszek69e670d52016-01-18 20:41:34 +00001483 unlinkUse(RA, true);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001484 }
1485 NodeAddr<BlockNode*> BA = PA.Addr->getOwner(*this);
1486 BA.Addr->removeMember(PA, *this);
1487 }
1488}
1489
1490// For a given reference node TA in an instruction node IA, connect the
1491// reaching def of TA to the appropriate def node. Create any shadow nodes
1492// as appropriate.
1493template <typename T>
1494void DataFlowGraph::linkRefUp(NodeAddr<InstrNode*> IA, NodeAddr<T> TA,
1495 DefStack &DS) {
1496 if (DS.empty())
1497 return;
1498 RegisterRef RR = TA.Addr->getRegRef();
1499 NodeAddr<T> TAP;
1500
1501 // References from the def stack that have been examined so far.
1502 RegisterSet Defs;
1503
1504 for (auto I = DS.top(), E = DS.bottom(); I != E; I.down()) {
1505 RegisterRef QR = I->Addr->getRegRef();
1506 auto AliasQR = [QR,this] (RegisterRef RR) -> bool {
1507 return RAI.alias(QR, RR);
1508 };
1509 bool PrecUp = RAI.covers(QR, RR);
1510 // Skip all defs that are aliased to any of the defs that we have already
1511 // seen. If we encounter a covering def, stop the stack traversal early.
1512 if (std::any_of(Defs.begin(), Defs.end(), AliasQR)) {
1513 if (PrecUp)
1514 break;
1515 continue;
1516 }
1517 // The reaching def.
1518 NodeAddr<DefNode*> RDA = *I;
1519
1520 // Pick the reached node.
1521 if (TAP.Id == 0) {
1522 TAP = TA;
1523 } else {
1524 // Mark the existing ref as "shadow" and create a new shadow.
1525 TAP.Addr->setFlags(TAP.Addr->getFlags() | NodeAttrs::Shadow);
1526 TAP = getNextShadow(IA, TAP, true);
1527 }
1528
1529 // Create the link.
1530 TAP.Addr->linkToDef(TAP.Id, RDA);
1531
1532 if (PrecUp)
1533 break;
1534 Defs.insert(QR);
1535 }
1536}
1537
1538// Create data-flow links for all reference nodes in the statement node SA.
1539void DataFlowGraph::linkStmtRefs(DefStackMap &DefM, NodeAddr<StmtNode*> SA) {
1540 RegisterSet Defs;
1541
1542 // Link all nodes (upwards in the data-flow) with their reaching defs.
1543 for (NodeAddr<RefNode*> RA : SA.Addr->members(*this)) {
1544 uint16_t Kind = RA.Addr->getKind();
1545 assert(Kind == NodeAttrs::Def || Kind == NodeAttrs::Use);
1546 RegisterRef RR = RA.Addr->getRegRef();
1547 // Do not process multiple defs of the same reference.
1548 if (Kind == NodeAttrs::Def && Defs.count(RR))
1549 continue;
1550 Defs.insert(RR);
1551
1552 auto F = DefM.find(RR);
1553 if (F == DefM.end())
1554 continue;
1555 DefStack &DS = F->second;
1556 if (Kind == NodeAttrs::Use)
1557 linkRefUp<UseNode*>(SA, RA, DS);
1558 else if (Kind == NodeAttrs::Def)
1559 linkRefUp<DefNode*>(SA, RA, DS);
1560 else
1561 llvm_unreachable("Unexpected node in instruction");
1562 }
1563}
1564
1565// Create data-flow links for all instructions in the block node BA. This
1566// will include updating any phi nodes in BA.
1567void DataFlowGraph::linkBlockRefs(DefStackMap &DefM, NodeAddr<BlockNode*> BA) {
1568 // Push block delimiters.
1569 markBlock(BA.Id, DefM);
1570
Krzysztof Parzyszek89757432016-05-05 22:00:44 +00001571 assert(BA.Addr && "block node address is needed to create a data-flow link");
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001572 // For each non-phi instruction in the block, link all the defs and uses
1573 // to their reaching defs. For any member of the block (including phis),
1574 // push the defs on the corresponding stacks.
1575 for (NodeAddr<InstrNode*> IA : BA.Addr->members(*this)) {
1576 // Ignore phi nodes here. They will be linked part by part from the
1577 // predecessors.
1578 if (IA.Addr->getKind() == NodeAttrs::Stmt)
1579 linkStmtRefs(DefM, IA);
1580
1581 // Push the definitions on the stack.
1582 pushDefs(IA, DefM);
1583 }
1584
1585 // Recursively process all children in the dominator tree.
1586 MachineDomTreeNode *N = MDT.getNode(BA.Addr->getCode());
1587 for (auto I : *N) {
1588 MachineBasicBlock *SB = I->getBlock();
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +00001589 auto SBA = findBlock(SB);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001590 linkBlockRefs(DefM, SBA);
1591 }
1592
1593 // Link the phi uses from the successor blocks.
1594 auto IsUseForBA = [BA](NodeAddr<NodeBase*> NA) -> bool {
1595 if (NA.Addr->getKind() != NodeAttrs::Use)
1596 return false;
1597 assert(NA.Addr->getFlags() & NodeAttrs::PhiRef);
1598 NodeAddr<PhiUseNode*> PUA = NA;
1599 return PUA.Addr->getPredecessor() == BA.Id;
1600 };
1601 MachineBasicBlock *MBB = BA.Addr->getCode();
1602 for (auto SB : MBB->successors()) {
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +00001603 auto SBA = findBlock(SB);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001604 for (NodeAddr<InstrNode*> IA : SBA.Addr->members_if(IsPhi, *this)) {
1605 // Go over each phi use associated with MBB, and link it.
1606 for (auto U : IA.Addr->members_if(IsUseForBA, *this)) {
1607 NodeAddr<PhiUseNode*> PUA = U;
1608 RegisterRef RR = PUA.Addr->getRegRef();
1609 linkRefUp<UseNode*>(IA, PUA, DefM[RR]);
1610 }
1611 }
1612 }
1613
1614 // Pop all defs from this block from the definition stacks.
1615 releaseBlock(BA.Id, DefM);
1616}
1617
1618// Remove the use node UA from any data-flow and structural links.
Krzysztof Parzyszek69e670d52016-01-18 20:41:34 +00001619void DataFlowGraph::unlinkUseDF(NodeAddr<UseNode*> UA) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001620 NodeId RD = UA.Addr->getReachingDef();
1621 NodeId Sib = UA.Addr->getSibling();
1622
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001623 if (RD == 0) {
1624 assert(Sib == 0);
1625 return;
1626 }
1627
1628 auto RDA = addr<DefNode*>(RD);
1629 auto TA = addr<UseNode*>(RDA.Addr->getReachedUse());
1630 if (TA.Id == UA.Id) {
1631 RDA.Addr->setReachedUse(Sib);
1632 return;
1633 }
1634
1635 while (TA.Id != 0) {
1636 NodeId S = TA.Addr->getSibling();
1637 if (S == UA.Id) {
1638 TA.Addr->setSibling(UA.Addr->getSibling());
1639 return;
1640 }
1641 TA = addr<UseNode*>(S);
1642 }
1643}
1644
1645// Remove the def node DA from any data-flow and structural links.
Krzysztof Parzyszek69e670d52016-01-18 20:41:34 +00001646void DataFlowGraph::unlinkDefDF(NodeAddr<DefNode*> DA) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001647 //
1648 // RD
1649 // | reached
1650 // | def
1651 // :
1652 // .
1653 // +----+
1654 // ... -- | DA | -- ... -- 0 : sibling chain of DA
1655 // +----+
1656 // | | reached
1657 // | : def
1658 // | .
1659 // | ... : Siblings (defs)
1660 // |
1661 // : reached
1662 // . use
1663 // ... : sibling chain of reached uses
1664
1665 NodeId RD = DA.Addr->getReachingDef();
1666
1667 // Visit all siblings of the reached def and reset their reaching defs.
1668 // Also, defs reached by DA are now "promoted" to being reached by RD,
1669 // so all of them will need to be spliced into the sibling chain where
1670 // DA belongs.
1671 auto getAllNodes = [this] (NodeId N) -> NodeList {
1672 NodeList Res;
1673 while (N) {
1674 auto RA = addr<RefNode*>(N);
1675 // Keep the nodes in the exact sibling order.
1676 Res.push_back(RA);
1677 N = RA.Addr->getSibling();
1678 }
1679 return Res;
1680 };
1681 NodeList ReachedDefs = getAllNodes(DA.Addr->getReachedDef());
1682 NodeList ReachedUses = getAllNodes(DA.Addr->getReachedUse());
1683
1684 if (RD == 0) {
1685 for (NodeAddr<RefNode*> I : ReachedDefs)
1686 I.Addr->setSibling(0);
1687 for (NodeAddr<RefNode*> I : ReachedUses)
1688 I.Addr->setSibling(0);
1689 }
1690 for (NodeAddr<DefNode*> I : ReachedDefs)
1691 I.Addr->setReachingDef(RD);
1692 for (NodeAddr<UseNode*> I : ReachedUses)
1693 I.Addr->setReachingDef(RD);
1694
1695 NodeId Sib = DA.Addr->getSibling();
1696 if (RD == 0) {
1697 assert(Sib == 0);
1698 return;
1699 }
1700
1701 // Update the reaching def node and remove DA from the sibling list.
1702 auto RDA = addr<DefNode*>(RD);
1703 auto TA = addr<DefNode*>(RDA.Addr->getReachedDef());
1704 if (TA.Id == DA.Id) {
1705 // If DA is the first reached def, just update the RD's reached def
1706 // to the DA's sibling.
1707 RDA.Addr->setReachedDef(Sib);
1708 } else {
1709 // Otherwise, traverse the sibling list of the reached defs and remove
1710 // DA from it.
1711 while (TA.Id != 0) {
1712 NodeId S = TA.Addr->getSibling();
1713 if (S == DA.Id) {
1714 TA.Addr->setSibling(Sib);
1715 break;
1716 }
1717 TA = addr<DefNode*>(S);
1718 }
1719 }
1720
1721 // Splice the DA's reached defs into the RDA's reached def chain.
1722 if (!ReachedDefs.empty()) {
1723 auto Last = NodeAddr<DefNode*>(ReachedDefs.back());
1724 Last.Addr->setSibling(RDA.Addr->getReachedDef());
1725 RDA.Addr->setReachedDef(ReachedDefs.front().Id);
1726 }
1727 // Splice the DA's reached uses into the RDA's reached use chain.
1728 if (!ReachedUses.empty()) {
1729 auto Last = NodeAddr<UseNode*>(ReachedUses.back());
1730 Last.Addr->setSibling(RDA.Addr->getReachedUse());
1731 RDA.Addr->setReachedUse(ReachedUses.front().Id);
1732 }
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001733}