LLVM  8.0.1
PhiValues.cpp
Go to the documentation of this file.
1 //===- PhiValues.cpp - Phi Value Analysis ---------------------------------===//
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 
11 #include "llvm/ADT/SmallPtrSet.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/IR/Instructions.h"
14 
15 using namespace llvm;
16 
17 void PhiValues::PhiValuesCallbackVH::deleted() {
18  PV->invalidateValue(getValPtr());
19 }
20 
21 void PhiValues::PhiValuesCallbackVH::allUsesReplacedWith(Value *) {
22  // We could potentially update the cached values we have with the new value,
23  // but it's simpler to just treat the old value as invalidated.
24  PV->invalidateValue(getValPtr());
25 }
26 
29  // PhiValues is invalidated if it isn't preserved.
30  auto PAC = PA.getChecker<PhiValuesAnalysis>();
31  return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>());
32 }
33 
34 // The goal here is to find all of the non-phi values reachable from this phi,
35 // and to do the same for all of the phis reachable from this phi, as doing so
36 // is necessary anyway in order to get the values for this phi. We do this using
37 // Tarjan's algorithm with Nuutila's improvements to find the strongly connected
38 // components of the phi graph rooted in this phi:
39 // * All phis in a strongly connected component will have the same reachable
40 // non-phi values. The SCC may not be the maximal subgraph for that set of
41 // reachable values, but finding out that isn't really necessary (it would
42 // only reduce the amount of memory needed to store the values).
43 // * Tarjan's algorithm completes components in a bottom-up manner, i.e. it
44 // never completes a component before the components reachable from it have
45 // been completed. This means that when we complete a component we have
46 // everything we need to collect the values reachable from that component.
47 // * We collect both the non-phi values reachable from each SCC, as that's what
48 // we're ultimately interested in, and all of the reachable values, i.e.
49 // including phis, as that makes invalidateValue easier.
50 void PhiValues::processPhi(const PHINode *Phi,
52  // Initialize the phi with the next depth number.
53  assert(DepthMap.lookup(Phi) == 0);
54  assert(NextDepthNumber != UINT_MAX);
55  unsigned int DepthNumber = ++NextDepthNumber;
56  DepthMap[Phi] = DepthNumber;
57 
58  // Recursively process the incoming phis of this phi.
59  TrackedValues.insert(PhiValuesCallbackVH(const_cast<PHINode *>(Phi), this));
60  for (Value *PhiOp : Phi->incoming_values()) {
61  if (PHINode *PhiPhiOp = dyn_cast<PHINode>(PhiOp)) {
62  // Recurse if the phi has not yet been visited.
63  if (DepthMap.lookup(PhiPhiOp) == 0)
64  processPhi(PhiPhiOp, Stack);
65  assert(DepthMap.lookup(PhiPhiOp) != 0);
66  // If the phi did not become part of a component then this phi and that
67  // phi are part of the same component, so adjust the depth number.
68  if (!ReachableMap.count(DepthMap[PhiPhiOp]))
69  DepthMap[Phi] = std::min(DepthMap[Phi], DepthMap[PhiPhiOp]);
70  } else {
71  TrackedValues.insert(PhiValuesCallbackVH(PhiOp, this));
72  }
73  }
74 
75  // Now that incoming phis have been handled, push this phi to the stack.
76  Stack.push_back(Phi);
77 
78  // If the depth number has not changed then we've finished collecting the phis
79  // of a strongly connected component.
80  if (DepthMap[Phi] == DepthNumber) {
81  // Collect the reachable values for this component. The phis of this
82  // component will be those on top of the depth stach with the same or
83  // greater depth number.
84  ConstValueSet Reachable;
85  while (!Stack.empty() && DepthMap[Stack.back()] >= DepthNumber) {
86  const PHINode *ComponentPhi = Stack.pop_back_val();
87  Reachable.insert(ComponentPhi);
88  DepthMap[ComponentPhi] = DepthNumber;
89  for (Value *Op : ComponentPhi->incoming_values()) {
90  if (PHINode *PhiOp = dyn_cast<PHINode>(Op)) {
91  // If this phi is not part of the same component then that component
92  // is guaranteed to have been completed before this one. Therefore we
93  // can just add its reachable values to the reachable values of this
94  // component.
95  auto It = ReachableMap.find(DepthMap[PhiOp]);
96  if (It != ReachableMap.end())
97  Reachable.insert(It->second.begin(), It->second.end());
98  } else {
99  Reachable.insert(Op);
100  }
101  }
102  }
103  ReachableMap.insert({DepthNumber,Reachable});
104 
105  // Filter out phis to get the non-phi reachable values.
106  ValueSet NonPhi;
107  for (const Value *V : Reachable)
108  if (!isa<PHINode>(V))
109  NonPhi.insert(const_cast<Value*>(V));
110  NonPhiReachableMap.insert({DepthNumber,NonPhi});
111  }
112 }
113 
115  if (DepthMap.count(PN) == 0) {
117  processPhi(PN, Stack);
118  assert(Stack.empty());
119  }
120  assert(DepthMap.lookup(PN) != 0);
121  return NonPhiReachableMap[DepthMap[PN]];
122 }
123 
125  // Components that can reach V are invalid.
126  SmallVector<unsigned int, 8> InvalidComponents;
127  for (auto &Pair : ReachableMap)
128  if (Pair.second.count(V))
129  InvalidComponents.push_back(Pair.first);
130 
131  for (unsigned int N : InvalidComponents) {
132  for (const Value *V : ReachableMap[N])
133  if (const PHINode *PN = dyn_cast<PHINode>(V))
134  DepthMap.erase(PN);
135  NonPhiReachableMap.erase(N);
136  ReachableMap.erase(N);
137  }
138  // This value is no longer tracked
139  auto It = TrackedValues.find_as(V);
140  if (It != TrackedValues.end())
141  TrackedValues.erase(It);
142 }
143 
145  DepthMap.clear();
146  NonPhiReachableMap.clear();
147  ReachableMap.clear();
148 }
149 
150 void PhiValues::print(raw_ostream &OS) const {
151  // Iterate through the phi nodes of the function rather than iterating through
152  // DepthMap in order to get predictable ordering.
153  for (const BasicBlock &BB : F) {
154  for (const PHINode &PN : BB.phis()) {
155  OS << "PHI ";
156  PN.printAsOperand(OS, false);
157  OS << " has values:\n";
158  unsigned int N = DepthMap.lookup(&PN);
159  auto It = NonPhiReachableMap.find(N);
160  if (It == NonPhiReachableMap.end())
161  OS << " UNKNOWN\n";
162  else if (It->second.empty())
163  OS << " NONE\n";
164  else
165  for (Value *V : It->second)
166  // Printing of an instruction prints two spaces at the start, so
167  // handle instructions and everything else slightly differently in
168  // order to get consistent indenting.
169  if (Instruction *I = dyn_cast<Instruction>(V))
170  OS << *I << "\n";
171  else
172  OS << " " << *V << "\n";
173  }
174  }
175 }
176 
177 AnalysisKey PhiValuesAnalysis::Key;
179  return PhiValues(F);
180 }
181 
184  OS << "PHI Values for function: " << F.getName() << "\n";
186  for (const BasicBlock &BB : F)
187  for (const PHINode &PN : BB.phis())
188  PI.getValuesForPhi(&PN);
189  PI.print(OS);
190  return PreservedAnalyses::all();
191 }
192 
195 }
196 
198  Result.reset(new PhiValues(F));
199  return false;
200 }
201 
203  Result->releaseMemory();
204 }
205 
207  AU.setPreservesAll();
208 }
209 
210 char PhiValuesWrapperPass::ID = 0;
211 
212 INITIALIZE_PASS(PhiValuesWrapperPass, "phi-values", "Phi Values Analysis", false,
213  true)
void releaseMemory()
Free the memory used by this class.
Definition: PhiValues.cpp:144
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:770
This class represents lattice values for constants.
Definition: AllocatorList.h:24
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
Definition: PhiValues.cpp:202
F(f)
const ValueSet & getValuesForPhi(const PHINode *PN)
Get the underlying values of a phi.
Definition: PhiValues.cpp:114
The analysis pass which yields a PhiValues.
Definition: PhiValues.h:119
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition: PassManager.h:305
Wrapper pass for the legacy pass manager.
Definition: PhiValues.h:142
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition: PhiValues.cpp:206
bool invalidate(Function &, const PreservedAnalyses &, FunctionAnalysisManager::Invalidator &)
Handle invalidation events in the new pass manager.
Definition: PhiValues.cpp:27
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
LLVM Basic Block Representation.
Definition: BasicBlock.h:58
void invalidateValue(const Value *V)
Notify PhiValues that the cached information using V is no longer valid.
Definition: PhiValues.cpp:124
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:371
Represent the analysis usage information of a pass.
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:285
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:34
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:418
PhiValues run(Function &F, FunctionAnalysisManager &)
Definition: PhiValues.cpp:178
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
Definition: PhiValues.cpp:197
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:381
void setPreservesAll()
Set by analyses that do not transform their input at all.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Definition: PhiValues.cpp:182
void print(raw_ostream &OS) const
Print out the values currently in the cache.
Definition: PhiValues.cpp:150
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:56
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
Class for calculating and caching the underlying values of phis in a function.
Definition: PhiValues.h:43
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
API to communicate dependencies between analyses during invalidation.
Definition: PassManager.h:642
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This templated class represents "all analyses that operate over <a particular IR unit>" (e...
Definition: PassManager.h:92
LLVM Value Representation.
Definition: Value.h:73
void initializePhiValuesWrapperPassPass(PassRegistry &)
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
A container for analyses that lazily runs them and caches their results.
op_range incoming_values()
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition: PassManager.h:71
PhiValues(const Function &F)
Construct an empty PhiValues.
Definition: PhiValues.h:48