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