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