blob: 7eb5cf86ba5b66ed9b20dc3802b13619308a5338 [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"
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +000021#include "llvm/Target/TargetLowering.h"
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +000022#include "llvm/Target/TargetRegisterInfo.h"
23
24using namespace llvm;
25using namespace rdf;
26
27// Printing functions. Have them here first, so that the rest of the code
28// can use them.
Benjamin Kramer922efd72016-05-27 10:06:40 +000029namespace llvm {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +000030namespace rdf {
31
32template<>
33raw_ostream &operator<< (raw_ostream &OS, const Print<RegisterRef> &P) {
34 auto &TRI = P.G.getTRI();
35 if (P.Obj.Reg > 0 && P.Obj.Reg < TRI.getNumRegs())
36 OS << TRI.getName(P.Obj.Reg);
37 else
38 OS << '#' << P.Obj.Reg;
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +000039 if (P.Obj.Sub != 0) {
40 LaneBitmask LM = P.G.getLMI().getLaneMaskForIndex(P.Obj.Sub);
41 OS << ":L" << PrintLaneMask(LM);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +000042 }
43 return OS;
44}
45
46template<>
47raw_ostream &operator<< (raw_ostream &OS, const Print<NodeId> &P) {
48 auto NA = P.G.addr<NodeBase*>(P.Obj);
49 uint16_t Attrs = NA.Addr->getAttrs();
50 uint16_t Kind = NodeAttrs::kind(Attrs);
51 uint16_t Flags = NodeAttrs::flags(Attrs);
52 switch (NodeAttrs::type(Attrs)) {
53 case NodeAttrs::Code:
54 switch (Kind) {
55 case NodeAttrs::Func: OS << 'f'; break;
56 case NodeAttrs::Block: OS << 'b'; break;
57 case NodeAttrs::Stmt: OS << 's'; break;
58 case NodeAttrs::Phi: OS << 'p'; break;
59 default: OS << "c?"; break;
60 }
61 break;
62 case NodeAttrs::Ref:
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +000063 if (Flags & NodeAttrs::Undef)
64 OS << '/';
Krzysztof Parzyszek586fc122016-09-27 18:24:33 +000065 if (Flags & NodeAttrs::Dead)
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<>
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000306raw_ostream &operator<< (raw_ostream &OS, const Print<RegisterAggr> &P) {
307 P.Obj.print(OS);
308 return OS;
309}
310
311template<>
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000312raw_ostream &operator<< (raw_ostream &OS,
313 const Print<DataFlowGraph::DefStack> &P) {
314 for (auto I = P.Obj.top(), E = P.Obj.bottom(); I != E; ) {
315 OS << Print<NodeId>(I->Id, P.G)
316 << '<' << Print<RegisterRef>(I->Addr->getRegRef(), P.G) << '>';
317 I.down();
318 if (I != E)
319 OS << ' ';
320 }
321 return OS;
322}
323
324} // namespace rdf
Benjamin Kramer922efd72016-05-27 10:06:40 +0000325} // namespace llvm
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000326
327// Node allocation functions.
328//
329// Node allocator is like a slab memory allocator: it allocates blocks of
330// memory in sizes that are multiples of the size of a node. Each block has
331// the same size. Nodes are allocated from the currently active block, and
332// when it becomes full, a new one is created.
333// There is a mapping scheme between node id and its location in a block,
334// and within that block is described in the header file.
335//
336void NodeAllocator::startNewBlock() {
337 void *T = MemPool.Allocate(NodesPerBlock*NodeMemSize, NodeMemSize);
338 char *P = static_cast<char*>(T);
339 Blocks.push_back(P);
340 // Check if the block index is still within the allowed range, i.e. less
341 // than 2^N, where N is the number of bits in NodeId for the block index.
342 // BitsPerIndex is the number of bits per node index.
Simon Pilgrim99c6c292016-01-18 21:11:19 +0000343 assert((Blocks.size() < ((size_t)1 << (8*sizeof(NodeId)-BitsPerIndex))) &&
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000344 "Out of bits for block index");
345 ActiveEnd = P;
346}
347
348bool NodeAllocator::needNewBlock() {
349 if (Blocks.empty())
350 return true;
351
352 char *ActiveBegin = Blocks.back();
353 uint32_t Index = (ActiveEnd-ActiveBegin)/NodeMemSize;
354 return Index >= NodesPerBlock;
355}
356
357NodeAddr<NodeBase*> NodeAllocator::New() {
358 if (needNewBlock())
359 startNewBlock();
360
361 uint32_t ActiveB = Blocks.size()-1;
362 uint32_t Index = (ActiveEnd - Blocks[ActiveB])/NodeMemSize;
363 NodeAddr<NodeBase*> NA = { reinterpret_cast<NodeBase*>(ActiveEnd),
364 makeId(ActiveB, Index) };
365 ActiveEnd += NodeMemSize;
366 return NA;
367}
368
369NodeId NodeAllocator::id(const NodeBase *P) const {
370 uintptr_t A = reinterpret_cast<uintptr_t>(P);
371 for (unsigned i = 0, n = Blocks.size(); i != n; ++i) {
372 uintptr_t B = reinterpret_cast<uintptr_t>(Blocks[i]);
373 if (A < B || A >= B + NodesPerBlock*NodeMemSize)
374 continue;
375 uint32_t Idx = (A-B)/NodeMemSize;
376 return makeId(i, Idx);
377 }
378 llvm_unreachable("Invalid node address");
379}
380
381void NodeAllocator::clear() {
382 MemPool.Reset();
383 Blocks.clear();
384 ActiveEnd = nullptr;
385}
386
387
388// Insert node NA after "this" in the circular chain.
389void NodeBase::append(NodeAddr<NodeBase*> NA) {
390 NodeId Nx = Next;
391 // If NA is already "next", do nothing.
392 if (Next != NA.Id) {
393 Next = NA.Id;
394 NA.Addr->Next = Nx;
395 }
396}
397
398
399// Fundamental node manipulator functions.
400
401// Obtain the register reference from a reference node.
402RegisterRef RefNode::getRegRef() const {
403 assert(NodeAttrs::type(Attrs) == NodeAttrs::Ref);
404 if (NodeAttrs::flags(Attrs) & NodeAttrs::PhiRef)
405 return Ref.RR;
406 assert(Ref.Op != nullptr);
407 return { Ref.Op->getReg(), Ref.Op->getSubReg() };
408}
409
410// Set the register reference in the reference node directly (for references
411// in phi nodes).
412void RefNode::setRegRef(RegisterRef RR) {
413 assert(NodeAttrs::type(Attrs) == NodeAttrs::Ref);
414 assert(NodeAttrs::flags(Attrs) & NodeAttrs::PhiRef);
415 Ref.RR = RR;
416}
417
418// Set the register reference in the reference node based on a machine
419// operand (for references in statement nodes).
420void RefNode::setRegRef(MachineOperand *Op) {
421 assert(NodeAttrs::type(Attrs) == NodeAttrs::Ref);
422 assert(!(NodeAttrs::flags(Attrs) & NodeAttrs::PhiRef));
423 Ref.Op = Op;
424}
425
426// Get the owner of a given reference node.
427NodeAddr<NodeBase*> RefNode::getOwner(const DataFlowGraph &G) {
428 NodeAddr<NodeBase*> NA = G.addr<NodeBase*>(getNext());
429
430 while (NA.Addr != this) {
431 if (NA.Addr->getType() == NodeAttrs::Code)
432 return NA;
433 NA = G.addr<NodeBase*>(NA.Addr->getNext());
434 }
435 llvm_unreachable("No owner in circular list");
436}
437
438// Connect the def node to the reaching def node.
439void DefNode::linkToDef(NodeId Self, NodeAddr<DefNode*> DA) {
440 Ref.RD = DA.Id;
441 Ref.Sib = DA.Addr->getReachedDef();
442 DA.Addr->setReachedDef(Self);
443}
444
445// Connect the use node to the reaching def node.
446void UseNode::linkToDef(NodeId Self, NodeAddr<DefNode*> DA) {
447 Ref.RD = DA.Id;
448 Ref.Sib = DA.Addr->getReachedUse();
449 DA.Addr->setReachedUse(Self);
450}
451
452// Get the first member of the code node.
453NodeAddr<NodeBase*> CodeNode::getFirstMember(const DataFlowGraph &G) const {
454 if (Code.FirstM == 0)
455 return NodeAddr<NodeBase*>();
456 return G.addr<NodeBase*>(Code.FirstM);
457}
458
459// Get the last member of the code node.
460NodeAddr<NodeBase*> CodeNode::getLastMember(const DataFlowGraph &G) const {
461 if (Code.LastM == 0)
462 return NodeAddr<NodeBase*>();
463 return G.addr<NodeBase*>(Code.LastM);
464}
465
466// Add node NA at the end of the member list of the given code node.
467void CodeNode::addMember(NodeAddr<NodeBase*> NA, const DataFlowGraph &G) {
468 auto ML = getLastMember(G);
469 if (ML.Id != 0) {
470 ML.Addr->append(NA);
471 } else {
472 Code.FirstM = NA.Id;
473 NodeId Self = G.id(this);
474 NA.Addr->setNext(Self);
475 }
476 Code.LastM = NA.Id;
477}
478
479// Add node NA after member node MA in the given code node.
480void CodeNode::addMemberAfter(NodeAddr<NodeBase*> MA, NodeAddr<NodeBase*> NA,
481 const DataFlowGraph &G) {
482 MA.Addr->append(NA);
483 if (Code.LastM == MA.Id)
484 Code.LastM = NA.Id;
485}
486
487// Remove member node NA from the given code node.
488void CodeNode::removeMember(NodeAddr<NodeBase*> NA, const DataFlowGraph &G) {
489 auto MA = getFirstMember(G);
490 assert(MA.Id != 0);
491
492 // Special handling if the member to remove is the first member.
493 if (MA.Id == NA.Id) {
494 if (Code.LastM == MA.Id) {
495 // If it is the only member, set both first and last to 0.
496 Code.FirstM = Code.LastM = 0;
497 } else {
498 // Otherwise, advance the first member.
499 Code.FirstM = MA.Addr->getNext();
500 }
501 return;
502 }
503
504 while (MA.Addr != this) {
505 NodeId MX = MA.Addr->getNext();
506 if (MX == NA.Id) {
507 MA.Addr->setNext(NA.Addr->getNext());
508 // If the member to remove happens to be the last one, update the
509 // LastM indicator.
510 if (Code.LastM == NA.Id)
511 Code.LastM = MA.Id;
512 return;
513 }
514 MA = G.addr<NodeBase*>(MX);
515 }
516 llvm_unreachable("No such member");
517}
518
519// Return the list of all members of the code node.
520NodeList CodeNode::members(const DataFlowGraph &G) const {
521 static auto True = [] (NodeAddr<NodeBase*>) -> bool { return true; };
522 return members_if(True, G);
523}
524
525// Return the owner of the given instr node.
526NodeAddr<NodeBase*> InstrNode::getOwner(const DataFlowGraph &G) {
527 NodeAddr<NodeBase*> NA = G.addr<NodeBase*>(getNext());
528
529 while (NA.Addr != this) {
530 assert(NA.Addr->getType() == NodeAttrs::Code);
531 if (NA.Addr->getKind() == NodeAttrs::Block)
532 return NA;
533 NA = G.addr<NodeBase*>(NA.Addr->getNext());
534 }
535 llvm_unreachable("No owner in circular list");
536}
537
538// Add the phi node PA to the given block node.
539void BlockNode::addPhi(NodeAddr<PhiNode*> PA, const DataFlowGraph &G) {
540 auto M = getFirstMember(G);
541 if (M.Id == 0) {
542 addMember(PA, G);
543 return;
544 }
545
546 assert(M.Addr->getType() == NodeAttrs::Code);
547 if (M.Addr->getKind() == NodeAttrs::Stmt) {
548 // If the first member of the block is a statement, insert the phi as
549 // the first member.
550 Code.FirstM = PA.Id;
551 PA.Addr->setNext(M.Id);
552 } else {
553 // If the first member is a phi, find the last phi, and append PA to it.
554 assert(M.Addr->getKind() == NodeAttrs::Phi);
555 NodeAddr<NodeBase*> MN = M;
556 do {
557 M = MN;
558 MN = G.addr<NodeBase*>(M.Addr->getNext());
559 assert(MN.Addr->getType() == NodeAttrs::Code);
560 } while (MN.Addr->getKind() == NodeAttrs::Phi);
561
562 // M is the last phi.
563 addMemberAfter(M, PA, G);
564 }
565}
566
567// Find the block node corresponding to the machine basic block BB in the
568// given func node.
569NodeAddr<BlockNode*> FuncNode::findBlock(const MachineBasicBlock *BB,
570 const DataFlowGraph &G) const {
571 auto EqBB = [BB] (NodeAddr<NodeBase*> NA) -> bool {
572 return NodeAddr<BlockNode*>(NA).Addr->getCode() == BB;
573 };
574 NodeList Ms = members_if(EqBB, G);
575 if (!Ms.empty())
576 return Ms[0];
577 return NodeAddr<BlockNode*>();
578}
579
580// Get the block node for the entry block in the given function.
581NodeAddr<BlockNode*> FuncNode::getEntryBlock(const DataFlowGraph &G) {
582 MachineBasicBlock *EntryB = &getCode()->front();
583 return findBlock(EntryB, G);
584}
585
586
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000587// Target operand information.
588//
589
590// For a given instruction, check if there are any bits of RR that can remain
591// unchanged across this def.
592bool TargetOperandInfo::isPreserving(const MachineInstr &In, unsigned OpNum)
593 const {
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +0000594 return TII.isPredicated(In);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000595}
596
597// Check if the definition of RR produces an unspecified value.
598bool TargetOperandInfo::isClobbering(const MachineInstr &In, unsigned OpNum)
599 const {
600 if (In.isCall())
601 if (In.getOperand(OpNum).isImplicit())
602 return true;
603 return false;
604}
605
Krzysztof Parzyszekc5a4e262016-04-28 20:33:33 +0000606// Check if the given instruction specifically requires
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000607bool TargetOperandInfo::isFixedReg(const MachineInstr &In, unsigned OpNum)
608 const {
Krzysztof Parzyszekc5a4e262016-04-28 20:33:33 +0000609 if (In.isCall() || In.isReturn() || In.isInlineAsm())
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000610 return true;
Krzysztof Parzyszekbf90d5a2016-04-28 20:40:08 +0000611 // Check for a tail call.
612 if (In.isBranch())
613 for (auto &O : In.operands())
614 if (O.isGlobal() || O.isSymbol())
615 return true;
616
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000617 const MCInstrDesc &D = In.getDesc();
618 if (!D.getImplicitDefs() && !D.getImplicitUses())
619 return false;
620 const MachineOperand &Op = In.getOperand(OpNum);
621 // If there is a sub-register, treat the operand as non-fixed. Currently,
622 // fixed registers are those that are listed in the descriptor as implicit
623 // uses or defs, and those lists do not allow sub-registers.
624 if (Op.getSubReg() != 0)
625 return false;
Krzysztof Parzyszekc51f2392016-09-22 20:56:39 +0000626 uint32_t Reg = Op.getReg();
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000627 const MCPhysReg *ImpR = Op.isDef() ? D.getImplicitDefs()
628 : D.getImplicitUses();
629 if (!ImpR)
630 return false;
631 while (*ImpR)
632 if (*ImpR++ == Reg)
633 return true;
634 return false;
635}
636
637
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000638uint32_t RegisterAggr::getLargestSuperReg(uint32_t Reg) const {
639 uint32_t SuperReg = Reg;
640 while (true) {
641 MCSuperRegIterator SR(SuperReg, &TRI, false);
642 if (!SR.isValid())
643 return SuperReg;
644 SuperReg = *SR;
645 }
646 llvm_unreachable(nullptr);
647}
648
649LaneBitmask RegisterAggr::composeMaskForReg(uint32_t Reg, LaneBitmask LM,
650 uint32_t SuperR) const {
651 uint32_t SubR = TRI.getSubRegIndex(SuperR, Reg);
652 const TargetRegisterClass &RC = *TRI.getMinimalPhysRegClass(Reg);
653 return TRI.composeSubRegIndexLaneMask(SubR, LM & RC.LaneMask);
654}
655
656void RegisterAggr::setMaskRaw(uint32_t Reg, LaneBitmask LM) {
657 uint32_t SuperR = getLargestSuperReg(Reg);
658 LaneBitmask SuperM = composeMaskForReg(Reg, LM, SuperR);
659 auto F = Masks.find(SuperR);
660 if (F == Masks.end())
661 Masks.insert({SuperR, SuperM});
662 else
663 F->second |= SuperM;
664
665 // Visit all register units to see if there are any that were created
666 // by explicit aliases. Add those that were to the bit vector.
667 for (MCRegUnitIterator U(Reg, &TRI); U.isValid(); ++U) {
668 MCRegUnitRootIterator R(*U, &TRI);
669 ++R;
670 if (!R.isValid())
671 continue;
672 ExpAliasUnits.set(*U);
673 CheckUnits = true;
674 }
675}
676
677bool RegisterAggr::hasAliasOf(RegisterRef RR) const {
678 uint32_t SuperR = getLargestSuperReg(RR.Reg);
679 auto F = Masks.find(SuperR);
680 if (F != Masks.end()) {
681 LaneBitmask M = LMI.getLaneMaskForIndex(RR.Sub);
682 if (F->second & composeMaskForReg(RR.Reg, M, SuperR))
683 return true;
684 }
685 if (CheckUnits) {
686 for (MCRegUnitIterator U(RR.Reg, &TRI); U.isValid(); ++U)
687 if (ExpAliasUnits.test(*U))
688 return true;
689 }
690 return false;
691}
692
693bool RegisterAggr::hasCoverOf(RegisterRef RR) const {
694 uint32_t SuperR = getLargestSuperReg(RR.Reg);
695 auto F = Masks.find(SuperR);
696 if (F == Masks.end())
697 return false;
698 LaneBitmask M = LMI.getLaneMaskForIndex(RR.Sub);
699 LaneBitmask SuperM = composeMaskForReg(RR.Reg, M, SuperR);
700 return (SuperM & F->second) == SuperM;
701}
702
703RegisterAggr &RegisterAggr::insert(RegisterRef RR) {
704 setMaskRaw(RR.Reg, LMI.getLaneMaskForIndex(RR.Sub));
705 return *this;
706}
707
708RegisterAggr &RegisterAggr::insert(const RegisterAggr &RG) {
709 for (auto P : RG.Masks)
710 setMaskRaw(P.first, P.second);
711 return *this;
712}
713
714RegisterAggr &RegisterAggr::clear(RegisterRef RR) {
715 uint32_t SuperR = getLargestSuperReg(RR.Reg);
716 auto F = Masks.find(SuperR);
717 if (F == Masks.end())
718 return *this;
719 LaneBitmask M = LMI.getLaneMaskForIndex(RR.Sub);
720 LaneBitmask NewM = F->second & ~composeMaskForReg(RR.Reg, M, SuperR);
721 if (NewM == LaneBitmask(0))
722 Masks.erase(F);
723 else
724 F->second = NewM;
725 return *this;
726}
727
728void RegisterAggr::print(raw_ostream &OS) const {
729 OS << '{';
730 for (auto I : Masks)
731 OS << ' ' << PrintReg(I.first, &TRI) << ':' << PrintLaneMask(I.second);
732 OS << " }";
733}
734
735
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000736//
737// The data flow graph construction.
738//
739
740DataFlowGraph::DataFlowGraph(MachineFunction &mf, const TargetInstrInfo &tii,
741 const TargetRegisterInfo &tri, const MachineDominatorTree &mdt,
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000742 const MachineDominanceFrontier &mdf, const TargetOperandInfo &toi)
743 : TimeG("rdf"), MF(mf), TII(tii), TRI(tri), MDT(mdt), MDF(mdf), TOI(toi) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000744}
745
746
747// The implementation of the definition stack.
748// Each register reference has its own definition stack. In particular,
749// for a register references "Reg" and "Reg:subreg" will each have their
750// own definition stacks.
751
752// Construct a stack iterator.
753DataFlowGraph::DefStack::Iterator::Iterator(const DataFlowGraph::DefStack &S,
754 bool Top) : DS(S) {
755 if (!Top) {
756 // Initialize to bottom.
757 Pos = 0;
758 return;
759 }
760 // Initialize to the top, i.e. top-most non-delimiter (or 0, if empty).
761 Pos = DS.Stack.size();
762 while (Pos > 0 && DS.isDelimiter(DS.Stack[Pos-1]))
763 Pos--;
764}
765
766// Return the size of the stack, including block delimiters.
767unsigned DataFlowGraph::DefStack::size() const {
768 unsigned S = 0;
769 for (auto I = top(), E = bottom(); I != E; I.down())
770 S++;
771 return S;
772}
773
774// Remove the top entry from the stack. Remove all intervening delimiters
775// so that after this, the stack is either empty, or the top of the stack
776// is a non-delimiter.
777void DataFlowGraph::DefStack::pop() {
778 assert(!empty());
779 unsigned P = nextDown(Stack.size());
780 Stack.resize(P);
781}
782
783// Push a delimiter for block node N on the stack.
784void DataFlowGraph::DefStack::start_block(NodeId N) {
785 assert(N != 0);
786 Stack.push_back(NodeAddr<DefNode*>(nullptr, N));
787}
788
789// Remove all nodes from the top of the stack, until the delimited for
790// block node N is encountered. Remove the delimiter as well. In effect,
791// this will remove from the stack all definitions from block N.
792void DataFlowGraph::DefStack::clear_block(NodeId N) {
793 assert(N != 0);
794 unsigned P = Stack.size();
795 while (P > 0) {
796 bool Found = isDelimiter(Stack[P-1], N);
797 P--;
798 if (Found)
799 break;
800 }
801 // This will also remove the delimiter, if found.
802 Stack.resize(P);
803}
804
805// Move the stack iterator up by one.
806unsigned DataFlowGraph::DefStack::nextUp(unsigned P) const {
807 // Get the next valid position after P (skipping all delimiters).
808 // The input position P does not have to point to a non-delimiter.
809 unsigned SS = Stack.size();
810 bool IsDelim;
Krzysztof Parzyszek8dca45e2016-01-12 16:51:55 +0000811 assert(P < SS);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000812 do {
813 P++;
814 IsDelim = isDelimiter(Stack[P-1]);
815 } while (P < SS && IsDelim);
816 assert(!IsDelim);
817 return P;
818}
819
820// Move the stack iterator down by one.
821unsigned DataFlowGraph::DefStack::nextDown(unsigned P) const {
822 // Get the preceding valid position before P (skipping all delimiters).
823 // The input position P does not have to point to a non-delimiter.
824 assert(P > 0 && P <= Stack.size());
825 bool IsDelim = isDelimiter(Stack[P-1]);
826 do {
827 if (--P == 0)
828 break;
829 IsDelim = isDelimiter(Stack[P-1]);
830 } while (P > 0 && IsDelim);
831 assert(!IsDelim);
832 return P;
833}
834
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000835
836// Register information.
837
838// Get the list of references aliased to RR. Lane masks are ignored.
839RegisterSet DataFlowGraph::getAliasSet(uint32_t Reg) const {
840 // Do not include RR in the alias set. For virtual registers return an
841 // empty set.
842 RegisterSet AS;
843 if (TargetRegisterInfo::isVirtualRegister(Reg))
844 return AS;
845 assert(TargetRegisterInfo::isPhysicalRegister(Reg));
846
847 for (MCRegAliasIterator AI(Reg, &TRI, false); AI.isValid(); ++AI)
848 AS.insert({*AI,0});
849 return AS;
850}
851
852RegisterSet DataFlowGraph::getLandingPadLiveIns() const {
853 RegisterSet LR;
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +0000854 const Function &F = *MF.getFunction();
855 const Constant *PF = F.hasPersonalityFn() ? F.getPersonalityFn()
856 : nullptr;
857 const TargetLowering &TLI = *MF.getSubtarget().getTargetLowering();
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +0000858 if (uint32_t R = TLI.getExceptionPointerRegister(PF))
859 LR.insert({R,0});
860 if (uint32_t R = TLI.getExceptionSelectorRegister(PF))
861 LR.insert({R,0});
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +0000862 return LR;
863}
864
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000865// Node management functions.
866
867// Get the pointer to the node with the id N.
868NodeBase *DataFlowGraph::ptr(NodeId N) const {
869 if (N == 0)
870 return nullptr;
871 return Memory.ptr(N);
872}
873
874// Get the id of the node at the address P.
875NodeId DataFlowGraph::id(const NodeBase *P) const {
876 if (P == nullptr)
877 return 0;
878 return Memory.id(P);
879}
880
881// Allocate a new node and set the attributes to Attrs.
882NodeAddr<NodeBase*> DataFlowGraph::newNode(uint16_t Attrs) {
883 NodeAddr<NodeBase*> P = Memory.New();
884 P.Addr->init();
885 P.Addr->setAttrs(Attrs);
886 return P;
887}
888
889// Make a copy of the given node B, except for the data-flow links, which
890// are set to 0.
891NodeAddr<NodeBase*> DataFlowGraph::cloneNode(const NodeAddr<NodeBase*> B) {
892 NodeAddr<NodeBase*> NA = newNode(0);
893 memcpy(NA.Addr, B.Addr, sizeof(NodeBase));
894 // Ref nodes need to have the data-flow links reset.
895 if (NA.Addr->getType() == NodeAttrs::Ref) {
896 NodeAddr<RefNode*> RA = NA;
897 RA.Addr->setReachingDef(0);
898 RA.Addr->setSibling(0);
899 if (NA.Addr->getKind() == NodeAttrs::Def) {
900 NodeAddr<DefNode*> DA = NA;
901 DA.Addr->setReachedDef(0);
902 DA.Addr->setReachedUse(0);
903 }
904 }
905 return NA;
906}
907
908
909// Allocation routines for specific node types/kinds.
910
911NodeAddr<UseNode*> DataFlowGraph::newUse(NodeAddr<InstrNode*> Owner,
912 MachineOperand &Op, uint16_t Flags) {
913 NodeAddr<UseNode*> UA = newNode(NodeAttrs::Ref | NodeAttrs::Use | Flags);
914 UA.Addr->setRegRef(&Op);
915 return UA;
916}
917
918NodeAddr<PhiUseNode*> DataFlowGraph::newPhiUse(NodeAddr<PhiNode*> Owner,
919 RegisterRef RR, NodeAddr<BlockNode*> PredB, uint16_t Flags) {
920 NodeAddr<PhiUseNode*> PUA = newNode(NodeAttrs::Ref | NodeAttrs::Use | Flags);
921 assert(Flags & NodeAttrs::PhiRef);
922 PUA.Addr->setRegRef(RR);
923 PUA.Addr->setPredecessor(PredB.Id);
924 return PUA;
925}
926
927NodeAddr<DefNode*> DataFlowGraph::newDef(NodeAddr<InstrNode*> Owner,
928 MachineOperand &Op, uint16_t Flags) {
929 NodeAddr<DefNode*> DA = newNode(NodeAttrs::Ref | NodeAttrs::Def | Flags);
930 DA.Addr->setRegRef(&Op);
931 return DA;
932}
933
934NodeAddr<DefNode*> DataFlowGraph::newDef(NodeAddr<InstrNode*> Owner,
935 RegisterRef RR, uint16_t Flags) {
936 NodeAddr<DefNode*> DA = newNode(NodeAttrs::Ref | NodeAttrs::Def | Flags);
937 assert(Flags & NodeAttrs::PhiRef);
938 DA.Addr->setRegRef(RR);
939 return DA;
940}
941
942NodeAddr<PhiNode*> DataFlowGraph::newPhi(NodeAddr<BlockNode*> Owner) {
943 NodeAddr<PhiNode*> PA = newNode(NodeAttrs::Code | NodeAttrs::Phi);
944 Owner.Addr->addPhi(PA, *this);
945 return PA;
946}
947
948NodeAddr<StmtNode*> DataFlowGraph::newStmt(NodeAddr<BlockNode*> Owner,
949 MachineInstr *MI) {
950 NodeAddr<StmtNode*> SA = newNode(NodeAttrs::Code | NodeAttrs::Stmt);
951 SA.Addr->setCode(MI);
952 Owner.Addr->addMember(SA, *this);
953 return SA;
954}
955
956NodeAddr<BlockNode*> DataFlowGraph::newBlock(NodeAddr<FuncNode*> Owner,
957 MachineBasicBlock *BB) {
958 NodeAddr<BlockNode*> BA = newNode(NodeAttrs::Code | NodeAttrs::Block);
959 BA.Addr->setCode(BB);
960 Owner.Addr->addMember(BA, *this);
961 return BA;
962}
963
964NodeAddr<FuncNode*> DataFlowGraph::newFunc(MachineFunction *MF) {
965 NodeAddr<FuncNode*> FA = newNode(NodeAttrs::Code | NodeAttrs::Func);
966 FA.Addr->setCode(MF);
967 return FA;
968}
969
970// Build the data flow graph.
Krzysztof Parzyszek55874cf2016-04-28 20:17:06 +0000971void DataFlowGraph::build(unsigned Options) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000972 reset();
973 Func = newFunc(&MF);
974
975 if (MF.empty())
976 return;
977
978 for (auto &B : MF) {
979 auto BA = newBlock(Func, &B);
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +0000980 BlockNodes.insert(std::make_pair(&B, BA));
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000981 for (auto &I : B) {
982 if (I.isDebugValue())
983 continue;
984 buildStmt(BA, I);
985 }
986 }
987
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000988 NodeAddr<BlockNode*> EA = Func.Addr->getEntryBlock(*this);
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +0000989 NodeList Blocks = Func.Addr->members(*this);
990
991 // Collect information about block references.
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +0000992 BlockRefsMap RefM;
993 buildBlockRefs(EA, RefM);
994
995 // Add function-entry phi nodes.
996 MachineRegisterInfo &MRI = MF.getRegInfo();
997 for (auto I = MRI.livein_begin(), E = MRI.livein_end(); I != E; ++I) {
998 NodeAddr<PhiNode*> PA = newPhi(EA);
999 RegisterRef RR = { I->first, 0 };
1000 uint16_t PhiFlags = NodeAttrs::PhiRef | NodeAttrs::Preserving;
1001 NodeAddr<DefNode*> DA = newDef(PA, RR, PhiFlags);
1002 PA.Addr->addMember(DA, *this);
1003 }
1004
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001005 // Add phis for landing pads.
1006 // Landing pads, unlike usual backs blocks, are not entered through
1007 // branches in the program, or fall-throughs from other blocks. They
1008 // are entered from the exception handling runtime and target's ABI
1009 // may define certain registers as defined on entry to such a block.
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001010 RegisterSet EHRegs = getLandingPadLiveIns();
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001011 if (!EHRegs.empty()) {
1012 for (NodeAddr<BlockNode*> BA : Blocks) {
1013 const MachineBasicBlock &B = *BA.Addr->getCode();
1014 if (!B.isEHPad())
1015 continue;
1016
1017 // Prepare a list of NodeIds of the block's predecessors.
1018 NodeList Preds;
1019 for (MachineBasicBlock *PB : B.predecessors())
1020 Preds.push_back(findBlock(PB));
1021
1022 // Build phi nodes for each live-in.
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001023 for (RegisterRef RR : EHRegs) {
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001024 NodeAddr<PhiNode*> PA = newPhi(BA);
1025 uint16_t PhiFlags = NodeAttrs::PhiRef | NodeAttrs::Preserving;
1026 // Add def:
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001027 NodeAddr<DefNode*> DA = newDef(PA, RR, PhiFlags);
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001028 PA.Addr->addMember(DA, *this);
1029 // Add uses (no reaching defs for phi uses):
1030 for (NodeAddr<BlockNode*> PBA : Preds) {
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001031 NodeAddr<PhiUseNode*> PUA = newPhiUse(PA, RR, PBA);
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001032 PA.Addr->addMember(PUA, *this);
1033 }
1034 }
1035 }
1036 }
1037
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001038 // Build a map "PhiM" which will contain, for each block, the set
1039 // of references that will require phi definitions in that block.
1040 BlockRefsMap PhiM;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001041 for (NodeAddr<BlockNode*> BA : Blocks)
1042 recordDefsForDF(PhiM, RefM, BA);
1043 for (NodeAddr<BlockNode*> BA : Blocks)
1044 buildPhis(PhiM, RefM, BA);
1045
1046 // Link all the refs. This will recursively traverse the dominator tree.
1047 DefStackMap DM;
1048 linkBlockRefs(DM, EA);
1049
1050 // Finally, remove all unused phi nodes.
Krzysztof Parzyszek55874cf2016-04-28 20:17:06 +00001051 if (!(Options & BuildOptions::KeepDeadPhis))
1052 removeUnusedPhis();
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001053}
1054
1055// For each stack in the map DefM, push the delimiter for block B on it.
1056void DataFlowGraph::markBlock(NodeId B, DefStackMap &DefM) {
1057 // Push block delimiters.
1058 for (auto I = DefM.begin(), E = DefM.end(); I != E; ++I)
1059 I->second.start_block(B);
1060}
1061
1062// Remove all definitions coming from block B from each stack in DefM.
1063void DataFlowGraph::releaseBlock(NodeId B, DefStackMap &DefM) {
1064 // Pop all defs from this block from the definition stack. Defs that were
1065 // added to the map during the traversal of instructions will not have a
1066 // delimiter, but for those, the whole stack will be emptied.
1067 for (auto I = DefM.begin(), E = DefM.end(); I != E; ++I)
1068 I->second.clear_block(B);
1069
1070 // Finally, remove empty stacks from the map.
1071 for (auto I = DefM.begin(), E = DefM.end(), NextI = I; I != E; I = NextI) {
1072 NextI = std::next(I);
1073 // This preserves the validity of iterators other than I.
1074 if (I->second.empty())
1075 DefM.erase(I);
1076 }
1077}
1078
1079// Push all definitions from the instruction node IA to an appropriate
1080// stack in DefM.
1081void DataFlowGraph::pushDefs(NodeAddr<InstrNode*> IA, DefStackMap &DefM) {
1082 NodeList Defs = IA.Addr->members_if(IsDef, *this);
1083 NodeSet Visited;
1084#ifndef NDEBUG
1085 RegisterSet Defined;
1086#endif
1087
1088 // The important objectives of this function are:
1089 // - to be able to handle instructions both while the graph is being
1090 // constructed, and after the graph has been constructed, and
1091 // - maintain proper ordering of definitions on the stack for each
1092 // register reference:
1093 // - if there are two or more related defs in IA (i.e. coming from
1094 // the same machine operand), then only push one def on the stack,
1095 // - if there are multiple unrelated defs of non-overlapping
1096 // subregisters of S, then the stack for S will have both (in an
1097 // unspecified order), but the order does not matter from the data-
1098 // -flow perspective.
1099
1100 for (NodeAddr<DefNode*> DA : Defs) {
1101 if (Visited.count(DA.Id))
1102 continue;
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001103
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001104 NodeList Rel = getRelatedRefs(IA, DA);
1105 NodeAddr<DefNode*> PDA = Rel.front();
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001106 RegisterRef RR = PDA.Addr->getRegRef();
1107#ifndef NDEBUG
1108 // Assert if the register is defined in two or more unrelated defs.
1109 // This could happen if there are two or more def operands defining it.
1110 if (!Defined.insert(RR).second) {
1111 auto *MI = NodeAddr<StmtNode*>(IA).Addr->getCode();
1112 dbgs() << "Multiple definitions of register: "
1113 << Print<RegisterRef>(RR, *this) << " in\n " << *MI
1114 << "in BB#" << MI->getParent()->getNumber() << '\n';
1115 llvm_unreachable(nullptr);
1116 }
1117#endif
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001118 // Push the definition on the stack for the register and all aliases.
1119 // The def stack traversal in linkNodeUp will check the exact aliasing.
1120 DefM[RR.Reg].push(DA);
1121 for (RegisterRef A : getAliasSet(RR.Reg /*FIXME? use RegisterRef*/)) {
1122 // Check that we don't push the same def twice.
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001123 assert(A != RR);
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001124 DefM[A.Reg].push(DA);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001125 }
1126 // Mark all the related defs as visited.
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001127 for (NodeAddr<NodeBase*> T : Rel)
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001128 Visited.insert(T.Id);
1129 }
1130}
1131
1132// Return the list of all reference nodes related to RA, including RA itself.
1133// See "getNextRelated" for the meaning of a "related reference".
1134NodeList DataFlowGraph::getRelatedRefs(NodeAddr<InstrNode*> IA,
1135 NodeAddr<RefNode*> RA) const {
1136 assert(IA.Id != 0 && RA.Id != 0);
1137
1138 NodeList Refs;
1139 NodeId Start = RA.Id;
1140 do {
1141 Refs.push_back(RA);
1142 RA = getNextRelated(IA, RA);
1143 } while (RA.Id != 0 && RA.Id != Start);
1144 return Refs;
1145}
1146
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001147// Return true if RA and RB overlap, false otherwise.
1148bool DataFlowGraph::alias(RegisterRef RA, RegisterRef RB) const {
1149 // Handling of physical registers.
1150 bool IsPhysA = TargetRegisterInfo::isPhysicalRegister(RA.Reg);
1151 bool IsPhysB = TargetRegisterInfo::isPhysicalRegister(RB.Reg);
1152 if (IsPhysA != IsPhysB)
1153 return false;
1154 if (IsPhysA) {
1155 LaneBitmask LA = LMI.getLaneMaskForIndex(RA.Sub);
1156 LaneBitmask LB = LMI.getLaneMaskForIndex(RB.Sub);
1157
1158 MCRegUnitMaskIterator UMA(RA.Reg, &TRI);
1159 MCRegUnitMaskIterator UMB(RB.Reg, &TRI);
1160 // Reg units are returned in the numerical order.
1161 while (UMA.isValid() && UMB.isValid()) {
1162 std::pair<uint32_t,LaneBitmask> PA = *UMA;
1163 std::pair<uint32_t,LaneBitmask> PB = *UMB;
1164 // If the returned lane mask is 0, it should be treated as ~0
1165 // (or the lane mask from the given register ref should be ignored).
1166 // This can happen when a register has only one unit.
1167 if (PA.first < PB.first || (PA.second && !(PA.second & LA)))
1168 ++UMA;
1169 else if (PB.first < PA.first || (PB.second && !(PB.second & LB)))
1170 ++UMB;
1171 else
1172 return true;
1173 }
1174 return false;
1175 }
1176
1177 // Handling of virtual registers.
1178 bool IsVirtA = TargetRegisterInfo::isVirtualRegister(RA.Reg);
1179 bool IsVirtB = TargetRegisterInfo::isVirtualRegister(RB.Reg);
1180 if (IsVirtA != IsVirtB)
1181 return false;
1182 if (IsVirtA) {
1183 if (RA.Reg != RB.Reg)
1184 return false;
1185 // RA and RB refer to the same register. If any of them refer to the
1186 // whole register, they must be aliased.
1187 if (RA.Sub == 0 || RB.Sub == 0)
1188 return true;
1189 unsigned SA = TRI.getSubRegIdxSize(RA.Sub);
1190 unsigned OA = TRI.getSubRegIdxOffset(RA.Sub);
1191 unsigned SB = TRI.getSubRegIdxSize(RB.Sub);
1192 unsigned OB = TRI.getSubRegIdxOffset(RB.Sub);
1193 if (OA <= OB && OA+SA > OB)
1194 return true;
1195 if (OB <= OA && OB+SB > OA)
1196 return true;
1197 return false;
1198 }
1199
1200 return false;
1201}
1202
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001203
1204// Clear all information in the graph.
1205void DataFlowGraph::reset() {
1206 Memory.clear();
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +00001207 BlockNodes.clear();
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001208 Func = NodeAddr<FuncNode*>();
1209}
1210
1211
1212// Return the next reference node in the instruction node IA that is related
1213// to RA. Conceptually, two reference nodes are related if they refer to the
1214// same instance of a register access, but differ in flags or other minor
1215// characteristics. Specific examples of related nodes are shadow reference
1216// nodes.
1217// Return the equivalent of nullptr if there are no more related references.
1218NodeAddr<RefNode*> DataFlowGraph::getNextRelated(NodeAddr<InstrNode*> IA,
1219 NodeAddr<RefNode*> RA) const {
1220 assert(IA.Id != 0 && RA.Id != 0);
1221
1222 auto Related = [RA](NodeAddr<RefNode*> TA) -> bool {
1223 if (TA.Addr->getKind() != RA.Addr->getKind())
1224 return false;
1225 if (TA.Addr->getRegRef() != RA.Addr->getRegRef())
1226 return false;
1227 return true;
1228 };
1229 auto RelatedStmt = [&Related,RA](NodeAddr<RefNode*> TA) -> bool {
1230 return Related(TA) &&
1231 &RA.Addr->getOp() == &TA.Addr->getOp();
1232 };
1233 auto RelatedPhi = [&Related,RA](NodeAddr<RefNode*> TA) -> bool {
1234 if (!Related(TA))
1235 return false;
1236 if (TA.Addr->getKind() != NodeAttrs::Use)
1237 return true;
1238 // For phi uses, compare predecessor blocks.
1239 const NodeAddr<const PhiUseNode*> TUA = TA;
1240 const NodeAddr<const PhiUseNode*> RUA = RA;
1241 return TUA.Addr->getPredecessor() == RUA.Addr->getPredecessor();
1242 };
1243
1244 RegisterRef RR = RA.Addr->getRegRef();
1245 if (IA.Addr->getKind() == NodeAttrs::Stmt)
1246 return RA.Addr->getNextRef(RR, RelatedStmt, true, *this);
1247 return RA.Addr->getNextRef(RR, RelatedPhi, true, *this);
1248}
1249
1250// Find the next node related to RA in IA that satisfies condition P.
1251// If such a node was found, return a pair where the second element is the
1252// located node. If such a node does not exist, return a pair where the
1253// first element is the element after which such a node should be inserted,
1254// and the second element is a null-address.
1255template <typename Predicate>
1256std::pair<NodeAddr<RefNode*>,NodeAddr<RefNode*>>
1257DataFlowGraph::locateNextRef(NodeAddr<InstrNode*> IA, NodeAddr<RefNode*> RA,
1258 Predicate P) const {
1259 assert(IA.Id != 0 && RA.Id != 0);
1260
1261 NodeAddr<RefNode*> NA;
1262 NodeId Start = RA.Id;
1263 while (true) {
1264 NA = getNextRelated(IA, RA);
1265 if (NA.Id == 0 || NA.Id == Start)
1266 break;
1267 if (P(NA))
1268 break;
1269 RA = NA;
1270 }
1271
1272 if (NA.Id != 0 && NA.Id != Start)
1273 return std::make_pair(RA, NA);
1274 return std::make_pair(RA, NodeAddr<RefNode*>());
1275}
1276
1277// Get the next shadow node in IA corresponding to RA, and optionally create
1278// such a node if it does not exist.
1279NodeAddr<RefNode*> DataFlowGraph::getNextShadow(NodeAddr<InstrNode*> IA,
1280 NodeAddr<RefNode*> RA, bool Create) {
1281 assert(IA.Id != 0 && RA.Id != 0);
1282
1283 uint16_t Flags = RA.Addr->getFlags() | NodeAttrs::Shadow;
1284 auto IsShadow = [Flags] (NodeAddr<RefNode*> TA) -> bool {
1285 return TA.Addr->getFlags() == Flags;
1286 };
1287 auto Loc = locateNextRef(IA, RA, IsShadow);
1288 if (Loc.second.Id != 0 || !Create)
1289 return Loc.second;
1290
1291 // Create a copy of RA and mark is as shadow.
1292 NodeAddr<RefNode*> NA = cloneNode(RA);
1293 NA.Addr->setFlags(Flags | NodeAttrs::Shadow);
1294 IA.Addr->addMemberAfter(Loc.first, NA, *this);
1295 return NA;
1296}
1297
1298// Get the next shadow node in IA corresponding to RA. Return null-address
1299// if such a node does not exist.
1300NodeAddr<RefNode*> DataFlowGraph::getNextShadow(NodeAddr<InstrNode*> IA,
1301 NodeAddr<RefNode*> RA) const {
1302 assert(IA.Id != 0 && RA.Id != 0);
1303 uint16_t Flags = RA.Addr->getFlags() | NodeAttrs::Shadow;
1304 auto IsShadow = [Flags] (NodeAddr<RefNode*> TA) -> bool {
1305 return TA.Addr->getFlags() == Flags;
1306 };
1307 return locateNextRef(IA, RA, IsShadow).second;
1308}
1309
1310// Create a new statement node in the block node BA that corresponds to
1311// the machine instruction MI.
1312void DataFlowGraph::buildStmt(NodeAddr<BlockNode*> BA, MachineInstr &In) {
1313 auto SA = newStmt(BA, &In);
1314
Krzysztof Parzyszekbf90d5a2016-04-28 20:40:08 +00001315 auto isCall = [] (const MachineInstr &In) -> bool {
1316 if (In.isCall())
1317 return true;
1318 // Is tail call?
1319 if (In.isBranch())
1320 for (auto &Op : In.operands())
1321 if (Op.isGlobal() || Op.isSymbol())
1322 return true;
1323 return false;
1324 };
1325
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +00001326 auto isDefUndef = [this] (const MachineInstr &In, RegisterRef DR) -> bool {
1327 // This instruction defines DR. Check if there is a use operand that
1328 // would make DR live on entry to the instruction.
1329 for (const MachineOperand &UseOp : In.operands()) {
1330 if (!UseOp.isReg() || !UseOp.isUse() || UseOp.isUndef())
1331 continue;
1332 RegisterRef UR = { UseOp.getReg(), UseOp.getSubReg() };
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001333 if (alias(DR, UR))
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +00001334 return false;
1335 }
1336 return true;
1337 };
1338
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001339 // Collect a set of registers that this instruction implicitly uses
1340 // or defines. Implicit operands from an instruction will be ignored
1341 // unless they are listed here.
1342 RegisterSet ImpUses, ImpDefs;
1343 if (const uint16_t *ImpD = In.getDesc().getImplicitDefs())
1344 while (uint16_t R = *ImpD++)
1345 ImpDefs.insert({R, 0});
1346 if (const uint16_t *ImpU = In.getDesc().getImplicitUses())
1347 while (uint16_t R = *ImpU++)
1348 ImpUses.insert({R, 0});
1349
Krzysztof Parzyszek586fc122016-09-27 18:24:33 +00001350 bool IsCall = isCall(In);
1351 bool NeedsImplicit = IsCall || In.isInlineAsm() || In.isReturn();
Duncan P. N. Exon Smith6307eb52016-02-23 02:46:52 +00001352 bool IsPredicated = TII.isPredicated(In);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001353 unsigned NumOps = In.getNumOperands();
1354
1355 // Avoid duplicate implicit defs. This will not detect cases of implicit
1356 // defs that define registers that overlap, but it is not clear how to
1357 // interpret that in the absence of explicit defs. Overlapping explicit
1358 // defs are likely illegal already.
1359 RegisterSet DoneDefs;
1360 // Process explicit defs first.
1361 for (unsigned OpN = 0; OpN < NumOps; ++OpN) {
1362 MachineOperand &Op = In.getOperand(OpN);
1363 if (!Op.isReg() || !Op.isDef() || Op.isImplicit())
1364 continue;
1365 RegisterRef RR = { Op.getReg(), Op.getSubReg() };
1366 uint16_t Flags = NodeAttrs::None;
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +00001367 if (TOI.isPreserving(In, OpN)) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001368 Flags |= NodeAttrs::Preserving;
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +00001369 // If the def is preserving, check if it is also undefined.
1370 if (isDefUndef(In, RR))
1371 Flags |= NodeAttrs::Undef;
1372 }
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001373 if (TOI.isClobbering(In, OpN))
1374 Flags |= NodeAttrs::Clobbering;
1375 if (TOI.isFixedReg(In, OpN))
1376 Flags |= NodeAttrs::Fixed;
Krzysztof Parzyszek586fc122016-09-27 18:24:33 +00001377 if (IsCall && Op.isDead())
1378 Flags |= NodeAttrs::Dead;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001379 NodeAddr<DefNode*> DA = newDef(SA, Op, Flags);
1380 SA.Addr->addMember(DA, *this);
1381 DoneDefs.insert(RR);
1382 }
1383
1384 // Process implicit defs, skipping those that have already been added
1385 // as explicit.
1386 for (unsigned OpN = 0; OpN < NumOps; ++OpN) {
1387 MachineOperand &Op = In.getOperand(OpN);
1388 if (!Op.isReg() || !Op.isDef() || !Op.isImplicit())
1389 continue;
1390 RegisterRef RR = { Op.getReg(), Op.getSubReg() };
Krzysztof Parzyszekbf90d5a2016-04-28 20:40:08 +00001391 if (!NeedsImplicit && !ImpDefs.count(RR))
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001392 continue;
1393 if (DoneDefs.count(RR))
1394 continue;
1395 uint16_t Flags = NodeAttrs::None;
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +00001396 if (TOI.isPreserving(In, OpN)) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001397 Flags |= NodeAttrs::Preserving;
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +00001398 // If the def is preserving, check if it is also undefined.
1399 if (isDefUndef(In, RR))
1400 Flags |= NodeAttrs::Undef;
1401 }
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001402 if (TOI.isClobbering(In, OpN))
1403 Flags |= NodeAttrs::Clobbering;
1404 if (TOI.isFixedReg(In, OpN))
1405 Flags |= NodeAttrs::Fixed;
Krzysztof Parzyszek586fc122016-09-27 18:24:33 +00001406 if (IsCall && Op.isDead())
1407 Flags |= NodeAttrs::Dead;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001408 NodeAddr<DefNode*> DA = newDef(SA, Op, Flags);
1409 SA.Addr->addMember(DA, *this);
1410 DoneDefs.insert(RR);
1411 }
1412
1413 for (unsigned OpN = 0; OpN < NumOps; ++OpN) {
1414 MachineOperand &Op = In.getOperand(OpN);
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +00001415 if (!Op.isReg() || !Op.isUse())
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001416 continue;
1417 RegisterRef RR = { Op.getReg(), Op.getSubReg() };
1418 // Add implicit uses on return and call instructions, and on predicated
1419 // instructions regardless of whether or not they appear in the instruction
1420 // descriptor's list.
1421 bool Implicit = Op.isImplicit();
Krzysztof Parzyszekbf90d5a2016-04-28 20:40:08 +00001422 bool TakeImplicit = NeedsImplicit || IsPredicated;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001423 if (Implicit && !TakeImplicit && !ImpUses.count(RR))
1424 continue;
1425 uint16_t Flags = NodeAttrs::None;
Krzysztof Parzyszek1ff99522016-09-07 20:10:56 +00001426 if (Op.isUndef())
1427 Flags |= NodeAttrs::Undef;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001428 if (TOI.isFixedReg(In, OpN))
1429 Flags |= NodeAttrs::Fixed;
1430 NodeAddr<UseNode*> UA = newUse(SA, Op, Flags);
1431 SA.Addr->addMember(UA, *this);
1432 }
1433}
1434
1435// Build a map that for each block will have the set of all references from
1436// that block, and from all blocks dominated by it.
1437void DataFlowGraph::buildBlockRefs(NodeAddr<BlockNode*> BA,
1438 BlockRefsMap &RefM) {
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001439 RegisterSet &Refs = RefM[BA.Id];
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001440 MachineDomTreeNode *N = MDT.getNode(BA.Addr->getCode());
1441 assert(N);
1442 for (auto I : *N) {
1443 MachineBasicBlock *SB = I->getBlock();
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001444 NodeAddr<BlockNode*> SBA = findBlock(SB);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001445 buildBlockRefs(SBA, RefM);
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001446 const RegisterSet &RefsS = RefM[SBA.Id];
1447 Refs.insert(RefsS.begin(), RefsS.end());
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001448 }
1449
1450 for (NodeAddr<InstrNode*> IA : BA.Addr->members(*this))
1451 for (NodeAddr<RefNode*> RA : IA.Addr->members(*this))
1452 Refs.insert(RA.Addr->getRegRef());
1453}
1454
1455// Scan all defs in the block node BA and record in PhiM the locations of
1456// phi nodes corresponding to these defs.
1457void DataFlowGraph::recordDefsForDF(BlockRefsMap &PhiM, BlockRefsMap &RefM,
1458 NodeAddr<BlockNode*> BA) {
1459 // Check all defs from block BA and record them in each block in BA's
1460 // iterated dominance frontier. This information will later be used to
1461 // create phi nodes.
1462 MachineBasicBlock *BB = BA.Addr->getCode();
1463 assert(BB);
1464 auto DFLoc = MDF.find(BB);
1465 if (DFLoc == MDF.end() || DFLoc->second.empty())
1466 return;
1467
1468 // Traverse all instructions in the block and collect the set of all
1469 // defined references. For each reference there will be a phi created
1470 // in the block's iterated dominance frontier.
1471 // This is done to make sure that each defined reference gets only one
1472 // phi node, even if it is defined multiple times.
1473 RegisterSet Defs;
1474 for (auto I : BA.Addr->members(*this)) {
1475 assert(I.Addr->getType() == NodeAttrs::Code);
1476 assert(I.Addr->getKind() == NodeAttrs::Phi ||
1477 I.Addr->getKind() == NodeAttrs::Stmt);
1478 NodeAddr<InstrNode*> IA = I;
1479 for (NodeAddr<RefNode*> RA : IA.Addr->members_if(IsDef, *this))
1480 Defs.insert(RA.Addr->getRegRef());
1481 }
1482
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001483 // Calculate the iterated dominance frontier of BB.
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001484 const MachineDominanceFrontier::DomSetType &DF = DFLoc->second;
1485 SetVector<MachineBasicBlock*> IDF(DF.begin(), DF.end());
1486 for (unsigned i = 0; i < IDF.size(); ++i) {
1487 auto F = MDF.find(IDF[i]);
1488 if (F != MDF.end())
1489 IDF.insert(F->second.begin(), F->second.end());
1490 }
1491
1492 // Get the register references that are reachable from this block.
1493 RegisterSet &Refs = RefM[BA.Id];
1494 for (auto DB : IDF) {
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001495 NodeAddr<BlockNode*> DBA = findBlock(DB);
1496 const RegisterSet &RefsD = RefM[DBA.Id];
1497 Refs.insert(RefsD.begin(), RefsD.end());
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001498 }
1499
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001500 // Finally, add the set of defs to each block in the iterated dominance
1501 // frontier.
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001502 for (auto DB : IDF) {
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001503 NodeAddr<BlockNode*> DBA = findBlock(DB);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001504 PhiM[DBA.Id].insert(Defs.begin(), Defs.end());
1505 }
1506}
1507
1508// Given the locations of phi nodes in the map PhiM, create the phi nodes
1509// that are located in the block node BA.
1510void DataFlowGraph::buildPhis(BlockRefsMap &PhiM, BlockRefsMap &RefM,
1511 NodeAddr<BlockNode*> BA) {
1512 // Check if this blocks has any DF defs, i.e. if there are any defs
1513 // that this block is in the iterated dominance frontier of.
1514 auto HasDF = PhiM.find(BA.Id);
1515 if (HasDF == PhiM.end() || HasDF->second.empty())
1516 return;
1517
1518 // First, remove all R in Refs in such that there exists T in Refs
1519 // such that T covers R. In other words, only leave those refs that
1520 // are not covered by another ref (i.e. maximal with respect to covering).
1521
1522 auto MaxCoverIn = [this] (RegisterRef RR, RegisterSet &RRs) -> RegisterRef {
1523 for (auto I : RRs)
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001524 if (I != RR && RegisterAggr::isCoverOf(I, RR, LMI, TRI))
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001525 RR = I;
1526 return RR;
1527 };
1528
1529 RegisterSet MaxDF;
1530 for (auto I : HasDF->second)
1531 MaxDF.insert(MaxCoverIn(I, HasDF->second));
1532
1533 std::vector<RegisterRef> MaxRefs;
1534 auto &RefB = RefM[BA.Id];
1535 for (auto I : MaxDF)
1536 MaxRefs.push_back(MaxCoverIn(I, RefB));
1537
1538 // Now, for each R in MaxRefs, get the alias closure of R. If the closure
1539 // only has R in it, create a phi a def for R. Otherwise, create a phi,
1540 // and add a def for each S in the closure.
1541
1542 // Sort the refs so that the phis will be created in a deterministic order.
1543 std::sort(MaxRefs.begin(), MaxRefs.end());
1544 // Remove duplicates.
1545 auto NewEnd = std::unique(MaxRefs.begin(), MaxRefs.end());
1546 MaxRefs.erase(NewEnd, MaxRefs.end());
1547
1548 auto Aliased = [this,&MaxRefs](RegisterRef RR,
1549 std::vector<unsigned> &Closure) -> bool {
1550 for (auto I : Closure)
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001551 if (alias(RR, MaxRefs[I]))
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001552 return true;
1553 return false;
1554 };
1555
1556 // Prepare a list of NodeIds of the block's predecessors.
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001557 NodeList Preds;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001558 const MachineBasicBlock *MBB = BA.Addr->getCode();
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001559 for (auto PB : MBB->predecessors())
1560 Preds.push_back(findBlock(PB));
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001561
1562 while (!MaxRefs.empty()) {
1563 // Put the first element in the closure, and then add all subsequent
1564 // elements from MaxRefs to it, if they alias at least one element
1565 // already in the closure.
1566 // ClosureIdx: vector of indices in MaxRefs of members of the closure.
1567 std::vector<unsigned> ClosureIdx = { 0 };
1568 for (unsigned i = 1; i != MaxRefs.size(); ++i)
1569 if (Aliased(MaxRefs[i], ClosureIdx))
1570 ClosureIdx.push_back(i);
1571
1572 // Build a phi for the closure.
1573 unsigned CS = ClosureIdx.size();
1574 NodeAddr<PhiNode*> PA = newPhi(BA);
1575
1576 // Add defs.
1577 for (unsigned X = 0; X != CS; ++X) {
1578 RegisterRef RR = MaxRefs[ClosureIdx[X]];
1579 uint16_t PhiFlags = NodeAttrs::PhiRef | NodeAttrs::Preserving;
1580 NodeAddr<DefNode*> DA = newDef(PA, RR, PhiFlags);
1581 PA.Addr->addMember(DA, *this);
1582 }
1583 // Add phi uses.
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001584 for (NodeAddr<BlockNode*> PBA : Preds) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001585 for (unsigned X = 0; X != CS; ++X) {
1586 RegisterRef RR = MaxRefs[ClosureIdx[X]];
1587 NodeAddr<PhiUseNode*> PUA = newPhiUse(PA, RR, PBA);
1588 PA.Addr->addMember(PUA, *this);
1589 }
1590 }
1591
1592 // Erase from MaxRefs all elements in the closure.
1593 auto Begin = MaxRefs.begin();
1594 for (unsigned i = ClosureIdx.size(); i != 0; --i)
1595 MaxRefs.erase(Begin + ClosureIdx[i-1]);
1596 }
1597}
1598
1599// Remove any unneeded phi nodes that were created during the build process.
1600void DataFlowGraph::removeUnusedPhis() {
1601 // This will remove unused phis, i.e. phis where each def does not reach
1602 // any uses or other defs. This will not detect or remove circular phi
1603 // chains that are otherwise dead. Unused/dead phis are created during
1604 // the build process and this function is intended to remove these cases
1605 // that are easily determinable to be unnecessary.
1606
1607 SetVector<NodeId> PhiQ;
1608 for (NodeAddr<BlockNode*> BA : Func.Addr->members(*this)) {
1609 for (auto P : BA.Addr->members_if(IsPhi, *this))
1610 PhiQ.insert(P.Id);
1611 }
1612
1613 static auto HasUsedDef = [](NodeList &Ms) -> bool {
1614 for (auto M : Ms) {
1615 if (M.Addr->getKind() != NodeAttrs::Def)
1616 continue;
1617 NodeAddr<DefNode*> DA = M;
1618 if (DA.Addr->getReachedDef() != 0 || DA.Addr->getReachedUse() != 0)
1619 return true;
1620 }
1621 return false;
1622 };
1623
1624 // Any phi, if it is removed, may affect other phis (make them dead).
1625 // For each removed phi, collect the potentially affected phis and add
1626 // them back to the queue.
1627 while (!PhiQ.empty()) {
1628 auto PA = addr<PhiNode*>(PhiQ[0]);
1629 PhiQ.remove(PA.Id);
1630 NodeList Refs = PA.Addr->members(*this);
1631 if (HasUsedDef(Refs))
1632 continue;
1633 for (NodeAddr<RefNode*> RA : Refs) {
1634 if (NodeId RD = RA.Addr->getReachingDef()) {
1635 auto RDA = addr<DefNode*>(RD);
1636 NodeAddr<InstrNode*> OA = RDA.Addr->getOwner(*this);
1637 if (IsPhi(OA))
1638 PhiQ.insert(OA.Id);
1639 }
1640 if (RA.Addr->isDef())
Krzysztof Parzyszek69e670d52016-01-18 20:41:34 +00001641 unlinkDef(RA, true);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001642 else
Krzysztof Parzyszek69e670d52016-01-18 20:41:34 +00001643 unlinkUse(RA, true);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001644 }
1645 NodeAddr<BlockNode*> BA = PA.Addr->getOwner(*this);
1646 BA.Addr->removeMember(PA, *this);
1647 }
1648}
1649
1650// For a given reference node TA in an instruction node IA, connect the
1651// reaching def of TA to the appropriate def node. Create any shadow nodes
1652// as appropriate.
1653template <typename T>
1654void DataFlowGraph::linkRefUp(NodeAddr<InstrNode*> IA, NodeAddr<T> TA,
1655 DefStack &DS) {
1656 if (DS.empty())
1657 return;
1658 RegisterRef RR = TA.Addr->getRegRef();
1659 NodeAddr<T> TAP;
1660
1661 // References from the def stack that have been examined so far.
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001662 RegisterAggr Defs(LMI, TRI);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001663
1664 for (auto I = DS.top(), E = DS.bottom(); I != E; I.down()) {
1665 RegisterRef QR = I->Addr->getRegRef();
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001666
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001667 // Skip all defs that are aliased to any of the defs that we have already
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001668 // seen. If this completes a cover of RR, stop the stack traversal.
1669 bool Alias = Defs.hasAliasOf(QR);
1670 bool Cover = Defs.insert(QR).hasCoverOf(RR);
1671 if (Alias) {
1672 if (Cover)
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001673 break;
1674 continue;
1675 }
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001676
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001677 // The reaching def.
1678 NodeAddr<DefNode*> RDA = *I;
1679
1680 // Pick the reached node.
1681 if (TAP.Id == 0) {
1682 TAP = TA;
1683 } else {
1684 // Mark the existing ref as "shadow" and create a new shadow.
1685 TAP.Addr->setFlags(TAP.Addr->getFlags() | NodeAttrs::Shadow);
1686 TAP = getNextShadow(IA, TAP, true);
1687 }
1688
1689 // Create the link.
1690 TAP.Addr->linkToDef(TAP.Id, RDA);
1691
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001692 if (Cover)
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001693 break;
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001694 }
1695}
1696
1697// Create data-flow links for all reference nodes in the statement node SA.
1698void DataFlowGraph::linkStmtRefs(DefStackMap &DefM, NodeAddr<StmtNode*> SA) {
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001699#ifndef NDEBUG
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001700 RegisterSet Defs;
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001701#endif
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001702
1703 // Link all nodes (upwards in the data-flow) with their reaching defs.
1704 for (NodeAddr<RefNode*> RA : SA.Addr->members(*this)) {
1705 uint16_t Kind = RA.Addr->getKind();
1706 assert(Kind == NodeAttrs::Def || Kind == NodeAttrs::Use);
1707 RegisterRef RR = RA.Addr->getRegRef();
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001708#ifndef NDEBUG
1709 // Do not expect multiple defs of the same reference.
1710 assert(Kind != NodeAttrs::Def || !Defs.count(RR));
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001711 Defs.insert(RR);
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001712#endif
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001713
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001714 auto F = DefM.find(RR.Reg);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001715 if (F == DefM.end())
1716 continue;
1717 DefStack &DS = F->second;
1718 if (Kind == NodeAttrs::Use)
1719 linkRefUp<UseNode*>(SA, RA, DS);
1720 else if (Kind == NodeAttrs::Def)
1721 linkRefUp<DefNode*>(SA, RA, DS);
1722 else
1723 llvm_unreachable("Unexpected node in instruction");
1724 }
1725}
1726
1727// Create data-flow links for all instructions in the block node BA. This
1728// will include updating any phi nodes in BA.
1729void DataFlowGraph::linkBlockRefs(DefStackMap &DefM, NodeAddr<BlockNode*> BA) {
1730 // Push block delimiters.
1731 markBlock(BA.Id, DefM);
1732
Krzysztof Parzyszek89757432016-05-05 22:00:44 +00001733 assert(BA.Addr && "block node address is needed to create a data-flow link");
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001734 // For each non-phi instruction in the block, link all the defs and uses
1735 // to their reaching defs. For any member of the block (including phis),
1736 // push the defs on the corresponding stacks.
1737 for (NodeAddr<InstrNode*> IA : BA.Addr->members(*this)) {
1738 // Ignore phi nodes here. They will be linked part by part from the
1739 // predecessors.
1740 if (IA.Addr->getKind() == NodeAttrs::Stmt)
1741 linkStmtRefs(DefM, IA);
1742
1743 // Push the definitions on the stack.
1744 pushDefs(IA, DefM);
1745 }
1746
1747 // Recursively process all children in the dominator tree.
1748 MachineDomTreeNode *N = MDT.getNode(BA.Addr->getCode());
1749 for (auto I : *N) {
1750 MachineBasicBlock *SB = I->getBlock();
Krzysztof Parzyszek047149f2016-07-22 16:09:47 +00001751 auto SBA = findBlock(SB);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001752 linkBlockRefs(DefM, SBA);
1753 }
1754
1755 // Link the phi uses from the successor blocks.
1756 auto IsUseForBA = [BA](NodeAddr<NodeBase*> NA) -> bool {
1757 if (NA.Addr->getKind() != NodeAttrs::Use)
1758 return false;
1759 assert(NA.Addr->getFlags() & NodeAttrs::PhiRef);
1760 NodeAddr<PhiUseNode*> PUA = NA;
1761 return PUA.Addr->getPredecessor() == BA.Id;
1762 };
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001763
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001764 RegisterSet EHLiveIns = getLandingPadLiveIns();
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001765 MachineBasicBlock *MBB = BA.Addr->getCode();
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001766
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001767 for (auto SB : MBB->successors()) {
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001768 bool IsEHPad = SB->isEHPad();
1769 NodeAddr<BlockNode*> SBA = findBlock(SB);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001770 for (NodeAddr<InstrNode*> IA : SBA.Addr->members_if(IsPhi, *this)) {
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001771 // Do not link phi uses for landing pad live-ins.
1772 if (IsEHPad) {
1773 // Find what register this phi is for.
1774 NodeAddr<RefNode*> RA = IA.Addr->getFirstMember(*this);
1775 assert(RA.Id != 0);
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001776 if (EHLiveIns.count(RA.Addr->getRegRef()))
Krzysztof Parzyszek1d322202016-09-27 18:18:44 +00001777 continue;
1778 }
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001779 // Go over each phi use associated with MBB, and link it.
1780 for (auto U : IA.Addr->members_if(IsUseForBA, *this)) {
1781 NodeAddr<PhiUseNode*> PUA = U;
1782 RegisterRef RR = PUA.Addr->getRegRef();
Krzysztof Parzyszeka77fe4e2016-10-03 17:14:48 +00001783 linkRefUp<UseNode*>(IA, PUA, DefM[RR.Reg]);
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001784 }
1785 }
1786 }
1787
1788 // Pop all defs from this block from the definition stacks.
1789 releaseBlock(BA.Id, DefM);
1790}
1791
1792// Remove the use node UA from any data-flow and structural links.
Krzysztof Parzyszek69e670d52016-01-18 20:41:34 +00001793void DataFlowGraph::unlinkUseDF(NodeAddr<UseNode*> UA) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001794 NodeId RD = UA.Addr->getReachingDef();
1795 NodeId Sib = UA.Addr->getSibling();
1796
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001797 if (RD == 0) {
1798 assert(Sib == 0);
1799 return;
1800 }
1801
1802 auto RDA = addr<DefNode*>(RD);
1803 auto TA = addr<UseNode*>(RDA.Addr->getReachedUse());
1804 if (TA.Id == UA.Id) {
1805 RDA.Addr->setReachedUse(Sib);
1806 return;
1807 }
1808
1809 while (TA.Id != 0) {
1810 NodeId S = TA.Addr->getSibling();
1811 if (S == UA.Id) {
1812 TA.Addr->setSibling(UA.Addr->getSibling());
1813 return;
1814 }
1815 TA = addr<UseNode*>(S);
1816 }
1817}
1818
1819// Remove the def node DA from any data-flow and structural links.
Krzysztof Parzyszek69e670d52016-01-18 20:41:34 +00001820void DataFlowGraph::unlinkDefDF(NodeAddr<DefNode*> DA) {
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001821 //
1822 // RD
1823 // | reached
1824 // | def
1825 // :
1826 // .
1827 // +----+
1828 // ... -- | DA | -- ... -- 0 : sibling chain of DA
1829 // +----+
1830 // | | reached
1831 // | : def
1832 // | .
1833 // | ... : Siblings (defs)
1834 // |
1835 // : reached
1836 // . use
1837 // ... : sibling chain of reached uses
1838
1839 NodeId RD = DA.Addr->getReachingDef();
1840
1841 // Visit all siblings of the reached def and reset their reaching defs.
1842 // Also, defs reached by DA are now "promoted" to being reached by RD,
1843 // so all of them will need to be spliced into the sibling chain where
1844 // DA belongs.
1845 auto getAllNodes = [this] (NodeId N) -> NodeList {
1846 NodeList Res;
1847 while (N) {
1848 auto RA = addr<RefNode*>(N);
1849 // Keep the nodes in the exact sibling order.
1850 Res.push_back(RA);
1851 N = RA.Addr->getSibling();
1852 }
1853 return Res;
1854 };
1855 NodeList ReachedDefs = getAllNodes(DA.Addr->getReachedDef());
1856 NodeList ReachedUses = getAllNodes(DA.Addr->getReachedUse());
1857
1858 if (RD == 0) {
1859 for (NodeAddr<RefNode*> I : ReachedDefs)
1860 I.Addr->setSibling(0);
1861 for (NodeAddr<RefNode*> I : ReachedUses)
1862 I.Addr->setSibling(0);
1863 }
1864 for (NodeAddr<DefNode*> I : ReachedDefs)
1865 I.Addr->setReachingDef(RD);
1866 for (NodeAddr<UseNode*> I : ReachedUses)
1867 I.Addr->setReachingDef(RD);
1868
1869 NodeId Sib = DA.Addr->getSibling();
1870 if (RD == 0) {
1871 assert(Sib == 0);
1872 return;
1873 }
1874
1875 // Update the reaching def node and remove DA from the sibling list.
1876 auto RDA = addr<DefNode*>(RD);
1877 auto TA = addr<DefNode*>(RDA.Addr->getReachedDef());
1878 if (TA.Id == DA.Id) {
1879 // If DA is the first reached def, just update the RD's reached def
1880 // to the DA's sibling.
1881 RDA.Addr->setReachedDef(Sib);
1882 } else {
1883 // Otherwise, traverse the sibling list of the reached defs and remove
1884 // DA from it.
1885 while (TA.Id != 0) {
1886 NodeId S = TA.Addr->getSibling();
1887 if (S == DA.Id) {
1888 TA.Addr->setSibling(Sib);
1889 break;
1890 }
1891 TA = addr<DefNode*>(S);
1892 }
1893 }
1894
1895 // Splice the DA's reached defs into the RDA's reached def chain.
1896 if (!ReachedDefs.empty()) {
1897 auto Last = NodeAddr<DefNode*>(ReachedDefs.back());
1898 Last.Addr->setSibling(RDA.Addr->getReachedDef());
1899 RDA.Addr->setReachedDef(ReachedDefs.front().Id);
1900 }
1901 // Splice the DA's reached uses into the RDA's reached use chain.
1902 if (!ReachedUses.empty()) {
1903 auto Last = NodeAddr<UseNode*>(ReachedUses.back());
1904 Last.Addr->setSibling(RDA.Addr->getReachedUse());
1905 RDA.Addr->setReachedUse(ReachedUses.front().Id);
1906 }
Krzysztof Parzyszekb5b5a1d2016-01-12 15:09:49 +00001907}