1 //===- ThreadSafetyTIL.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 in the llvm repository for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/Analysis/Analyses/ThreadSafetyTIL.h"
11 #include "clang/Basic/LLVM.h"
12 #include "llvm/Support/Casting.h"
13 #include <cassert>
14 #include <cstddef>
15 
16 using namespace clang;
17 using namespace threadSafety;
18 using namespace til;
19 
getUnaryOpcodeString(TIL_UnaryOpcode Op)20 StringRef til::getUnaryOpcodeString(TIL_UnaryOpcode Op) {
21   switch (Op) {
22     case UOP_Minus:    return "-";
23     case UOP_BitNot:   return "~";
24     case UOP_LogicNot: return "!";
25   }
26   return {};
27 }
28 
getBinaryOpcodeString(TIL_BinaryOpcode Op)29 StringRef til::getBinaryOpcodeString(TIL_BinaryOpcode Op) {
30   switch (Op) {
31     case BOP_Mul:      return "*";
32     case BOP_Div:      return "/";
33     case BOP_Rem:      return "%";
34     case BOP_Add:      return "+";
35     case BOP_Sub:      return "-";
36     case BOP_Shl:      return "<<";
37     case BOP_Shr:      return ">>";
38     case BOP_BitAnd:   return "&";
39     case BOP_BitXor:   return "^";
40     case BOP_BitOr:    return "|";
41     case BOP_Eq:       return "==";
42     case BOP_Neq:      return "!=";
43     case BOP_Lt:       return "<";
44     case BOP_Leq:      return "<=";
45     case BOP_Cmp:      return "<=>";
46     case BOP_LogicAnd: return "&&";
47     case BOP_LogicOr:  return "||";
48   }
49   return {};
50 }
51 
force()52 SExpr* Future::force() {
53   Status = FS_evaluating;
54   Result = compute();
55   Status = FS_done;
56   return Result;
57 }
58 
addPredecessor(BasicBlock * Pred)59 unsigned BasicBlock::addPredecessor(BasicBlock *Pred) {
60   unsigned Idx = Predecessors.size();
61   Predecessors.reserveCheck(1, Arena);
62   Predecessors.push_back(Pred);
63   for (auto *E : Args) {
64     if (auto *Ph = dyn_cast<Phi>(E)) {
65       Ph->values().reserveCheck(1, Arena);
66       Ph->values().push_back(nullptr);
67     }
68   }
69   return Idx;
70 }
71 
reservePredecessors(unsigned NumPreds)72 void BasicBlock::reservePredecessors(unsigned NumPreds) {
73   Predecessors.reserve(NumPreds, Arena);
74   for (auto *E : Args) {
75     if (auto *Ph = dyn_cast<Phi>(E)) {
76       Ph->values().reserve(NumPreds, Arena);
77     }
78   }
79 }
80 
81 // If E is a variable, then trace back through any aliases or redundant
82 // Phi nodes to find the canonical definition.
getCanonicalVal(const SExpr * E)83 const SExpr *til::getCanonicalVal(const SExpr *E) {
84   while (true) {
85     if (const auto *V = dyn_cast<Variable>(E)) {
86       if (V->kind() == Variable::VK_Let) {
87         E = V->definition();
88         continue;
89       }
90     }
91     if (const auto *Ph = dyn_cast<Phi>(E)) {
92       if (Ph->status() == Phi::PH_SingleVal) {
93         E = Ph->values()[0];
94         continue;
95       }
96     }
97     break;
98   }
99   return E;
100 }
101 
102 // If E is a variable, then trace back through any aliases or redundant
103 // Phi nodes to find the canonical definition.
104 // The non-const version will simplify incomplete Phi nodes.
simplifyToCanonicalVal(SExpr * E)105 SExpr *til::simplifyToCanonicalVal(SExpr *E) {
106   while (true) {
107     if (auto *V = dyn_cast<Variable>(E)) {
108       if (V->kind() != Variable::VK_Let)
109         return V;
110       // Eliminate redundant variables, e.g. x = y, or x = 5,
111       // but keep anything more complicated.
112       if (til::ThreadSafetyTIL::isTrivial(V->definition())) {
113         E = V->definition();
114         continue;
115       }
116       return V;
117     }
118     if (auto *Ph = dyn_cast<Phi>(E)) {
119       if (Ph->status() == Phi::PH_Incomplete)
120         simplifyIncompleteArg(Ph);
121       // Eliminate redundant Phi nodes.
122       if (Ph->status() == Phi::PH_SingleVal) {
123         E = Ph->values()[0];
124         continue;
125       }
126     }
127     return E;
128   }
129 }
130 
131 // Trace the arguments of an incomplete Phi node to see if they have the same
132 // canonical definition.  If so, mark the Phi node as redundant.
133 // getCanonicalVal() will recursively call simplifyIncompletePhi().
simplifyIncompleteArg(til::Phi * Ph)134 void til::simplifyIncompleteArg(til::Phi *Ph) {
135   assert(Ph && Ph->status() == Phi::PH_Incomplete);
136 
137   // eliminate infinite recursion -- assume that this node is not redundant.
138   Ph->setStatus(Phi::PH_MultiVal);
139 
140   SExpr *E0 = simplifyToCanonicalVal(Ph->values()[0]);
141   for (unsigned i = 1, n = Ph->values().size(); i < n; ++i) {
142     SExpr *Ei = simplifyToCanonicalVal(Ph->values()[i]);
143     if (Ei == Ph)
144       continue;  // Recursive reference to itself.  Don't count.
145     if (Ei != E0) {
146       return;    // Status is already set to MultiVal.
147     }
148   }
149   Ph->setStatus(Phi::PH_SingleVal);
150 }
151 
152 // Renumbers the arguments and instructions to have unique, sequential IDs.
renumberInstrs(int ID)153 int BasicBlock::renumberInstrs(int ID) {
154   for (auto *Arg : Args)
155     Arg->setID(this, ID++);
156   for (auto *Instr : Instrs)
157     Instr->setID(this, ID++);
158   TermInstr->setID(this, ID++);
159   return ID;
160 }
161 
162 // Sorts the CFGs blocks using a reverse post-order depth-first traversal.
163 // Each block will be written into the Blocks array in order, and its BlockID
164 // will be set to the index in the array.  Sorting should start from the entry
165 // block, and ID should be the total number of blocks.
topologicalSort(SimpleArray<BasicBlock * > & Blocks,int ID)166 int BasicBlock::topologicalSort(SimpleArray<BasicBlock *> &Blocks, int ID) {
167   if (Visited) return ID;
168   Visited = true;
169   for (auto *Block : successors())
170     ID = Block->topologicalSort(Blocks, ID);
171   // set ID and update block array in place.
172   // We may lose pointers to unreachable blocks.
173   assert(ID > 0);
174   BlockID = --ID;
175   Blocks[BlockID] = this;
176   return ID;
177 }
178 
179 // Performs a reverse topological traversal, starting from the exit block and
180 // following back-edges.  The dominator is serialized before any predecessors,
181 // which guarantees that all blocks are serialized after their dominator and
182 // before their post-dominator (because it's a reverse topological traversal).
183 // ID should be initially set to 0.
184 //
185 // This sort assumes that (1) dominators have been computed, (2) there are no
186 // critical edges, and (3) the entry block is reachable from the exit block
187 // and no blocks are accessible via traversal of back-edges from the exit that
188 // weren't accessible via forward edges from the entry.
topologicalFinalSort(SimpleArray<BasicBlock * > & Blocks,int ID)189 int BasicBlock::topologicalFinalSort(SimpleArray<BasicBlock*>& Blocks, int ID) {
190   // Visited is assumed to have been set by the topologicalSort.  This pass
191   // assumes !Visited means that we've visited this node before.
192   if (!Visited) return ID;
193   Visited = false;
194   if (DominatorNode.Parent)
195     ID = DominatorNode.Parent->topologicalFinalSort(Blocks, ID);
196   for (auto *Pred : Predecessors)
197     ID = Pred->topologicalFinalSort(Blocks, ID);
198   assert(static_cast<size_t>(ID) < Blocks.size());
199   BlockID = ID++;
200   Blocks[BlockID] = this;
201   return ID;
202 }
203 
204 // Computes the immediate dominator of the current block.  Assumes that all of
205 // its predecessors have already computed their dominators.  This is achieved
206 // by visiting the nodes in topological order.
computeDominator()207 void BasicBlock::computeDominator() {
208   BasicBlock *Candidate = nullptr;
209   // Walk backwards from each predecessor to find the common dominator node.
210   for (auto *Pred : Predecessors) {
211     // Skip back-edges
212     if (Pred->BlockID >= BlockID) continue;
213     // If we don't yet have a candidate for dominator yet, take this one.
214     if (Candidate == nullptr) {
215       Candidate = Pred;
216       continue;
217     }
218     // Walk the alternate and current candidate back to find a common ancestor.
219     auto *Alternate = Pred;
220     while (Alternate != Candidate) {
221       if (Candidate->BlockID > Alternate->BlockID)
222         Candidate = Candidate->DominatorNode.Parent;
223       else
224         Alternate = Alternate->DominatorNode.Parent;
225     }
226   }
227   DominatorNode.Parent = Candidate;
228   DominatorNode.SizeOfSubTree = 1;
229 }
230 
231 // Computes the immediate post-dominator of the current block.  Assumes that all
232 // of its successors have already computed their post-dominators.  This is
233 // achieved visiting the nodes in reverse topological order.
computePostDominator()234 void BasicBlock::computePostDominator() {
235   BasicBlock *Candidate = nullptr;
236   // Walk back from each predecessor to find the common post-dominator node.
237   for (auto *Succ : successors()) {
238     // Skip back-edges
239     if (Succ->BlockID <= BlockID) continue;
240     // If we don't yet have a candidate for post-dominator yet, take this one.
241     if (Candidate == nullptr) {
242       Candidate = Succ;
243       continue;
244     }
245     // Walk the alternate and current candidate back to find a common ancestor.
246     auto *Alternate = Succ;
247     while (Alternate != Candidate) {
248       if (Candidate->BlockID < Alternate->BlockID)
249         Candidate = Candidate->PostDominatorNode.Parent;
250       else
251         Alternate = Alternate->PostDominatorNode.Parent;
252     }
253   }
254   PostDominatorNode.Parent = Candidate;
255   PostDominatorNode.SizeOfSubTree = 1;
256 }
257 
258 // Renumber instructions in all blocks
renumberInstrs()259 void SCFG::renumberInstrs() {
260   int InstrID = 0;
261   for (auto *Block : Blocks)
262     InstrID = Block->renumberInstrs(InstrID);
263 }
264 
computeNodeSize(BasicBlock * B,BasicBlock::TopologyNode BasicBlock::* TN)265 static inline void computeNodeSize(BasicBlock *B,
266                                    BasicBlock::TopologyNode BasicBlock::*TN) {
267   BasicBlock::TopologyNode *N = &(B->*TN);
268   if (N->Parent) {
269     BasicBlock::TopologyNode *P = &(N->Parent->*TN);
270     // Initially set ID relative to the (as yet uncomputed) parent ID
271     N->NodeID = P->SizeOfSubTree;
272     P->SizeOfSubTree += N->SizeOfSubTree;
273   }
274 }
275 
computeNodeID(BasicBlock * B,BasicBlock::TopologyNode BasicBlock::* TN)276 static inline void computeNodeID(BasicBlock *B,
277                                  BasicBlock::TopologyNode BasicBlock::*TN) {
278   BasicBlock::TopologyNode *N = &(B->*TN);
279   if (N->Parent) {
280     BasicBlock::TopologyNode *P = &(N->Parent->*TN);
281     N->NodeID += P->NodeID;    // Fix NodeIDs relative to starting node.
282   }
283 }
284 
285 // Normalizes a CFG.  Normalization has a few major components:
286 // 1) Removing unreachable blocks.
287 // 2) Computing dominators and post-dominators
288 // 3) Topologically sorting the blocks into the "Blocks" array.
computeNormalForm()289 void SCFG::computeNormalForm() {
290   // Topologically sort the blocks starting from the entry block.
291   int NumUnreachableBlocks = Entry->topologicalSort(Blocks, Blocks.size());
292   if (NumUnreachableBlocks > 0) {
293     // If there were unreachable blocks shift everything down, and delete them.
294     for (size_t I = NumUnreachableBlocks, E = Blocks.size(); I < E; ++I) {
295       size_t NI = I - NumUnreachableBlocks;
296       Blocks[NI] = Blocks[I];
297       Blocks[NI]->BlockID = NI;
298       // FIXME: clean up predecessor pointers to unreachable blocks?
299     }
300     Blocks.drop(NumUnreachableBlocks);
301   }
302 
303   // Compute dominators.
304   for (auto *Block : Blocks)
305     Block->computeDominator();
306 
307   // Once dominators have been computed, the final sort may be performed.
308   int NumBlocks = Exit->topologicalFinalSort(Blocks, 0);
309   assert(static_cast<size_t>(NumBlocks) == Blocks.size());
310   (void) NumBlocks;
311 
312   // Renumber the instructions now that we have a final sort.
313   renumberInstrs();
314 
315   // Compute post-dominators and compute the sizes of each node in the
316   // dominator tree.
317   for (auto *Block : Blocks.reverse()) {
318     Block->computePostDominator();
319     computeNodeSize(Block, &BasicBlock::DominatorNode);
320   }
321   // Compute the sizes of each node in the post-dominator tree and assign IDs in
322   // the dominator tree.
323   for (auto *Block : Blocks) {
324     computeNodeID(Block, &BasicBlock::DominatorNode);
325     computeNodeSize(Block, &BasicBlock::PostDominatorNode);
326   }
327   // Assign IDs in the post-dominator tree.
328   for (auto *Block : Blocks.reverse()) {
329     computeNodeID(Block, &BasicBlock::PostDominatorNode);
330   }
331 }
332