xref: /freebsd-src/contrib/llvm-project/llvm/tools/llvm-diff/lib/DifferenceEngine.cpp (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
1349cc55cSDimitry Andric //===-- DifferenceEngine.cpp - Structural function/module comparison ------===//
2349cc55cSDimitry Andric //
3349cc55cSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4349cc55cSDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5349cc55cSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6349cc55cSDimitry Andric //
7349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
8349cc55cSDimitry Andric //
9349cc55cSDimitry Andric // This header defines the implementation of the LLVM difference
10349cc55cSDimitry Andric // engine, which structurally compares global values within a module.
11349cc55cSDimitry Andric //
12349cc55cSDimitry Andric //===----------------------------------------------------------------------===//
13349cc55cSDimitry Andric 
14349cc55cSDimitry Andric #include "DifferenceEngine.h"
15349cc55cSDimitry Andric #include "llvm/ADT/DenseMap.h"
16349cc55cSDimitry Andric #include "llvm/ADT/DenseSet.h"
17349cc55cSDimitry Andric #include "llvm/ADT/SmallString.h"
18349cc55cSDimitry Andric #include "llvm/ADT/SmallVector.h"
19349cc55cSDimitry Andric #include "llvm/ADT/StringSet.h"
20*bdd1243dSDimitry Andric #include "llvm/IR/BasicBlock.h"
21349cc55cSDimitry Andric #include "llvm/IR/CFG.h"
22349cc55cSDimitry Andric #include "llvm/IR/Constants.h"
23349cc55cSDimitry Andric #include "llvm/IR/Function.h"
24349cc55cSDimitry Andric #include "llvm/IR/Instructions.h"
25349cc55cSDimitry Andric #include "llvm/IR/Module.h"
26349cc55cSDimitry Andric #include "llvm/Support/ErrorHandling.h"
27349cc55cSDimitry Andric #include "llvm/Support/raw_ostream.h"
28349cc55cSDimitry Andric #include "llvm/Support/type_traits.h"
29349cc55cSDimitry Andric #include <utility>
30349cc55cSDimitry Andric 
31349cc55cSDimitry Andric using namespace llvm;
32349cc55cSDimitry Andric 
33349cc55cSDimitry Andric namespace {
34349cc55cSDimitry Andric 
35349cc55cSDimitry Andric /// A priority queue, implemented as a heap.
36349cc55cSDimitry Andric template <class T, class Sorter, unsigned InlineCapacity>
37349cc55cSDimitry Andric class PriorityQueue {
38349cc55cSDimitry Andric   Sorter Precedes;
39349cc55cSDimitry Andric   llvm::SmallVector<T, InlineCapacity> Storage;
40349cc55cSDimitry Andric 
41349cc55cSDimitry Andric public:
42349cc55cSDimitry Andric   PriorityQueue(const Sorter &Precedes) : Precedes(Precedes) {}
43349cc55cSDimitry Andric 
44349cc55cSDimitry Andric   /// Checks whether the heap is empty.
45349cc55cSDimitry Andric   bool empty() const { return Storage.empty(); }
46349cc55cSDimitry Andric 
47349cc55cSDimitry Andric   /// Insert a new value on the heap.
48349cc55cSDimitry Andric   void insert(const T &V) {
49349cc55cSDimitry Andric     unsigned Index = Storage.size();
50349cc55cSDimitry Andric     Storage.push_back(V);
51349cc55cSDimitry Andric     if (Index == 0) return;
52349cc55cSDimitry Andric 
53349cc55cSDimitry Andric     T *data = Storage.data();
54349cc55cSDimitry Andric     while (true) {
55349cc55cSDimitry Andric       unsigned Target = (Index + 1) / 2 - 1;
56349cc55cSDimitry Andric       if (!Precedes(data[Index], data[Target])) return;
57349cc55cSDimitry Andric       std::swap(data[Index], data[Target]);
58349cc55cSDimitry Andric       if (Target == 0) return;
59349cc55cSDimitry Andric       Index = Target;
60349cc55cSDimitry Andric     }
61349cc55cSDimitry Andric   }
62349cc55cSDimitry Andric 
63349cc55cSDimitry Andric   /// Remove the minimum value in the heap.  Only valid on a non-empty heap.
64349cc55cSDimitry Andric   T remove_min() {
65349cc55cSDimitry Andric     assert(!empty());
66349cc55cSDimitry Andric     T tmp = Storage[0];
67349cc55cSDimitry Andric 
68349cc55cSDimitry Andric     unsigned NewSize = Storage.size() - 1;
69349cc55cSDimitry Andric     if (NewSize) {
70349cc55cSDimitry Andric       // Move the slot at the end to the beginning.
71349cc55cSDimitry Andric       if (std::is_trivially_copyable<T>::value)
72349cc55cSDimitry Andric         Storage[0] = Storage[NewSize];
73349cc55cSDimitry Andric       else
74349cc55cSDimitry Andric         std::swap(Storage[0], Storage[NewSize]);
75349cc55cSDimitry Andric 
76349cc55cSDimitry Andric       // Bubble the root up as necessary.
77349cc55cSDimitry Andric       unsigned Index = 0;
78349cc55cSDimitry Andric       while (true) {
79349cc55cSDimitry Andric         // With a 1-based index, the children would be Index*2 and Index*2+1.
80349cc55cSDimitry Andric         unsigned R = (Index + 1) * 2;
81349cc55cSDimitry Andric         unsigned L = R - 1;
82349cc55cSDimitry Andric 
83349cc55cSDimitry Andric         // If R is out of bounds, we're done after this in any case.
84349cc55cSDimitry Andric         if (R >= NewSize) {
85349cc55cSDimitry Andric           // If L is also out of bounds, we're done immediately.
86349cc55cSDimitry Andric           if (L >= NewSize) break;
87349cc55cSDimitry Andric 
88349cc55cSDimitry Andric           // Otherwise, test whether we should swap L and Index.
89349cc55cSDimitry Andric           if (Precedes(Storage[L], Storage[Index]))
90349cc55cSDimitry Andric             std::swap(Storage[L], Storage[Index]);
91349cc55cSDimitry Andric           break;
92349cc55cSDimitry Andric         }
93349cc55cSDimitry Andric 
94349cc55cSDimitry Andric         // Otherwise, we need to compare with the smaller of L and R.
95349cc55cSDimitry Andric         // Prefer R because it's closer to the end of the array.
96349cc55cSDimitry Andric         unsigned IndexToTest = (Precedes(Storage[L], Storage[R]) ? L : R);
97349cc55cSDimitry Andric 
98349cc55cSDimitry Andric         // If Index is >= the min of L and R, then heap ordering is restored.
99349cc55cSDimitry Andric         if (!Precedes(Storage[IndexToTest], Storage[Index]))
100349cc55cSDimitry Andric           break;
101349cc55cSDimitry Andric 
102349cc55cSDimitry Andric         // Otherwise, keep bubbling up.
103349cc55cSDimitry Andric         std::swap(Storage[IndexToTest], Storage[Index]);
104349cc55cSDimitry Andric         Index = IndexToTest;
105349cc55cSDimitry Andric       }
106349cc55cSDimitry Andric     }
107349cc55cSDimitry Andric     Storage.pop_back();
108349cc55cSDimitry Andric 
109349cc55cSDimitry Andric     return tmp;
110349cc55cSDimitry Andric   }
111349cc55cSDimitry Andric };
112349cc55cSDimitry Andric 
113349cc55cSDimitry Andric /// A function-scope difference engine.
114349cc55cSDimitry Andric class FunctionDifferenceEngine {
115349cc55cSDimitry Andric   DifferenceEngine &Engine;
116349cc55cSDimitry Andric 
117349cc55cSDimitry Andric   // Some initializers may reference the variable we're currently checking. This
118349cc55cSDimitry Andric   // can cause an infinite loop. The Saved[LR]HS ivars can be checked to prevent
119349cc55cSDimitry Andric   // recursing.
120349cc55cSDimitry Andric   const Value *SavedLHS;
121349cc55cSDimitry Andric   const Value *SavedRHS;
122349cc55cSDimitry Andric 
123*bdd1243dSDimitry Andric   // The current mapping from old local values to new local values.
124349cc55cSDimitry Andric   DenseMap<const Value *, const Value *> Values;
125349cc55cSDimitry Andric 
126*bdd1243dSDimitry Andric   // The current mapping from old blocks to new blocks.
127349cc55cSDimitry Andric   DenseMap<const BasicBlock *, const BasicBlock *> Blocks;
128349cc55cSDimitry Andric 
129*bdd1243dSDimitry Andric   // The tentative mapping from old local values while comparing a pair of
130*bdd1243dSDimitry Andric   // basic blocks. Once the pair has been processed, the tentative mapping is
131*bdd1243dSDimitry Andric   // committed to the Values map.
132349cc55cSDimitry Andric   DenseSet<std::pair<const Value *, const Value *>> TentativeValues;
133349cc55cSDimitry Andric 
134*bdd1243dSDimitry Andric   // Equivalence Assumptions
135*bdd1243dSDimitry Andric   //
136*bdd1243dSDimitry Andric   // For basic blocks in loops, some values in phi nodes may depend on
137*bdd1243dSDimitry Andric   // values from not yet processed basic blocks in the loop. When encountering
138*bdd1243dSDimitry Andric   // such values, we optimistically asssume their equivalence and store this
139*bdd1243dSDimitry Andric   // assumption in a BlockDiffCandidate for the pair of compared BBs.
140*bdd1243dSDimitry Andric   //
141*bdd1243dSDimitry Andric   // Once we have diffed all BBs, for every BlockDiffCandidate, we check all
142*bdd1243dSDimitry Andric   // stored assumptions using the Values map that stores proven equivalences
143*bdd1243dSDimitry Andric   // between the old and new values, and report a diff if an assumption cannot
144*bdd1243dSDimitry Andric   // be proven to be true.
145*bdd1243dSDimitry Andric   //
146*bdd1243dSDimitry Andric   // Note that after having made an assumption, all further determined
147*bdd1243dSDimitry Andric   // equivalences implicitly depend on that assumption. These will not be
148*bdd1243dSDimitry Andric   // reverted or reported if the assumption proves to be false, because these
149*bdd1243dSDimitry Andric   // are considered indirect diffs caused by earlier direct diffs.
150*bdd1243dSDimitry Andric   //
151*bdd1243dSDimitry Andric   // We aim to avoid false negatives in llvm-diff, that is, ensure that
152*bdd1243dSDimitry Andric   // whenever no diff is reported, the functions are indeed equal. If
153*bdd1243dSDimitry Andric   // assumptions were made, this is not entirely clear, because in principle we
154*bdd1243dSDimitry Andric   // could end up with a circular proof where the proof of equivalence of two
155*bdd1243dSDimitry Andric   // nodes is depending on the assumption of their equivalence.
156*bdd1243dSDimitry Andric   //
157*bdd1243dSDimitry Andric   // To see that assumptions do not add false negatives, note that if we do not
158*bdd1243dSDimitry Andric   // report a diff, this means that there is an equivalence mapping between old
159*bdd1243dSDimitry Andric   // and new values that is consistent with all assumptions made. The circular
160*bdd1243dSDimitry Andric   // dependency that exists on an IR value level does not exist at run time,
161*bdd1243dSDimitry Andric   // because the values selected by the phi nodes must always already have been
162*bdd1243dSDimitry Andric   // computed. Hence, we can prove equivalence of the old and new functions by
163*bdd1243dSDimitry Andric   // considering step-wise parallel execution, and incrementally proving
164*bdd1243dSDimitry Andric   // equivalence of every new computed value. Another way to think about it is
165*bdd1243dSDimitry Andric   // to imagine cloning the loop BBs for every iteration, turning the loops
166*bdd1243dSDimitry Andric   // into (possibly infinite) DAGs, and proving equivalence by induction on the
167*bdd1243dSDimitry Andric   // iteration, using the computed value mapping.
168*bdd1243dSDimitry Andric 
169*bdd1243dSDimitry Andric   // The class BlockDiffCandidate stores pairs which either have already been
170*bdd1243dSDimitry Andric   // proven to differ, or pairs whose equivalence depends on assumptions to be
171*bdd1243dSDimitry Andric   // verified later.
172*bdd1243dSDimitry Andric   struct BlockDiffCandidate {
173*bdd1243dSDimitry Andric     const BasicBlock *LBB;
174*bdd1243dSDimitry Andric     const BasicBlock *RBB;
175*bdd1243dSDimitry Andric     // Maps old values to assumed-to-be-equivalent new values
176*bdd1243dSDimitry Andric     SmallDenseMap<const Value *, const Value *> EquivalenceAssumptions;
177*bdd1243dSDimitry Andric     // If set, we already know the blocks differ.
178*bdd1243dSDimitry Andric     bool KnownToDiffer;
179*bdd1243dSDimitry Andric   };
180*bdd1243dSDimitry Andric 
181*bdd1243dSDimitry Andric   // List of block diff candidates in the order found by processing.
182*bdd1243dSDimitry Andric   // We generate reports in this order.
183*bdd1243dSDimitry Andric   // For every LBB, there may only be one corresponding RBB.
184*bdd1243dSDimitry Andric   SmallVector<BlockDiffCandidate> BlockDiffCandidates;
185*bdd1243dSDimitry Andric   // Maps LBB to the index of its BlockDiffCandidate, if existing.
186*bdd1243dSDimitry Andric   DenseMap<const BasicBlock *, uint64_t> BlockDiffCandidateIndices;
187*bdd1243dSDimitry Andric 
188*bdd1243dSDimitry Andric   // Note: Every LBB must always be queried together with the same RBB.
189*bdd1243dSDimitry Andric   // The returned reference is not permanently valid and should not be stored.
190*bdd1243dSDimitry Andric   BlockDiffCandidate &getOrCreateBlockDiffCandidate(const BasicBlock *LBB,
191*bdd1243dSDimitry Andric                                                     const BasicBlock *RBB) {
192*bdd1243dSDimitry Andric     auto It = BlockDiffCandidateIndices.find(LBB);
193*bdd1243dSDimitry Andric     // Check if LBB already has a diff candidate
194*bdd1243dSDimitry Andric     if (It == BlockDiffCandidateIndices.end()) {
195*bdd1243dSDimitry Andric       // Add new one
196*bdd1243dSDimitry Andric       BlockDiffCandidateIndices[LBB] = BlockDiffCandidates.size();
197*bdd1243dSDimitry Andric       BlockDiffCandidates.push_back(
198*bdd1243dSDimitry Andric           {LBB, RBB, SmallDenseMap<const Value *, const Value *>(), false});
199*bdd1243dSDimitry Andric       return BlockDiffCandidates.back();
200*bdd1243dSDimitry Andric     }
201*bdd1243dSDimitry Andric     // Use existing one
202*bdd1243dSDimitry Andric     BlockDiffCandidate &Result = BlockDiffCandidates[It->second];
203*bdd1243dSDimitry Andric     assert(Result.RBB == RBB && "Inconsistent basic block pairing!");
204*bdd1243dSDimitry Andric     return Result;
205*bdd1243dSDimitry Andric   }
206*bdd1243dSDimitry Andric 
207*bdd1243dSDimitry Andric   // Optionally passed to equivalence checker functions, so these can add
208*bdd1243dSDimitry Andric   // assumptions in BlockDiffCandidates. Its presence controls whether
209*bdd1243dSDimitry Andric   // assumptions are generated.
210*bdd1243dSDimitry Andric   struct AssumptionContext {
211*bdd1243dSDimitry Andric     // The two basic blocks that need the two compared values to be equivalent.
212*bdd1243dSDimitry Andric     const BasicBlock *LBB;
213*bdd1243dSDimitry Andric     const BasicBlock *RBB;
214*bdd1243dSDimitry Andric   };
215*bdd1243dSDimitry Andric 
216349cc55cSDimitry Andric   unsigned getUnprocPredCount(const BasicBlock *Block) const {
217349cc55cSDimitry Andric     unsigned Count = 0;
218349cc55cSDimitry Andric     for (const_pred_iterator I = pred_begin(Block), E = pred_end(Block); I != E;
219349cc55cSDimitry Andric          ++I)
220349cc55cSDimitry Andric       if (!Blocks.count(*I)) Count++;
221349cc55cSDimitry Andric     return Count;
222349cc55cSDimitry Andric   }
223349cc55cSDimitry Andric 
224349cc55cSDimitry Andric   typedef std::pair<const BasicBlock *, const BasicBlock *> BlockPair;
225349cc55cSDimitry Andric 
226349cc55cSDimitry Andric   /// A type which sorts a priority queue by the number of unprocessed
227349cc55cSDimitry Andric   /// predecessor blocks it has remaining.
228349cc55cSDimitry Andric   ///
229349cc55cSDimitry Andric   /// This is actually really expensive to calculate.
230349cc55cSDimitry Andric   struct QueueSorter {
231349cc55cSDimitry Andric     const FunctionDifferenceEngine &fde;
232349cc55cSDimitry Andric     explicit QueueSorter(const FunctionDifferenceEngine &fde) : fde(fde) {}
233349cc55cSDimitry Andric 
234349cc55cSDimitry Andric     bool operator()(BlockPair &Old, BlockPair &New) {
235349cc55cSDimitry Andric       return fde.getUnprocPredCount(Old.first)
236349cc55cSDimitry Andric            < fde.getUnprocPredCount(New.first);
237349cc55cSDimitry Andric     }
238349cc55cSDimitry Andric   };
239349cc55cSDimitry Andric 
240349cc55cSDimitry Andric   /// A queue of unified blocks to process.
241349cc55cSDimitry Andric   PriorityQueue<BlockPair, QueueSorter, 20> Queue;
242349cc55cSDimitry Andric 
243349cc55cSDimitry Andric   /// Try to unify the given two blocks.  Enqueues them for processing
244349cc55cSDimitry Andric   /// if they haven't already been processed.
245349cc55cSDimitry Andric   ///
246349cc55cSDimitry Andric   /// Returns true if there was a problem unifying them.
247349cc55cSDimitry Andric   bool tryUnify(const BasicBlock *L, const BasicBlock *R) {
248349cc55cSDimitry Andric     const BasicBlock *&Ref = Blocks[L];
249349cc55cSDimitry Andric 
250349cc55cSDimitry Andric     if (Ref) {
251349cc55cSDimitry Andric       if (Ref == R) return false;
252349cc55cSDimitry Andric 
253349cc55cSDimitry Andric       Engine.logf("successor %l cannot be equivalent to %r; "
254349cc55cSDimitry Andric                   "it's already equivalent to %r")
255349cc55cSDimitry Andric         << L << R << Ref;
256349cc55cSDimitry Andric       return true;
257349cc55cSDimitry Andric     }
258349cc55cSDimitry Andric 
259349cc55cSDimitry Andric     Ref = R;
260349cc55cSDimitry Andric     Queue.insert(BlockPair(L, R));
261349cc55cSDimitry Andric     return false;
262349cc55cSDimitry Andric   }
263349cc55cSDimitry Andric 
264349cc55cSDimitry Andric   /// Unifies two instructions, given that they're known not to have
265349cc55cSDimitry Andric   /// structural differences.
266349cc55cSDimitry Andric   void unify(const Instruction *L, const Instruction *R) {
267349cc55cSDimitry Andric     DifferenceEngine::Context C(Engine, L, R);
268349cc55cSDimitry Andric 
269*bdd1243dSDimitry Andric     bool Result = diff(L, R, true, true, true);
270349cc55cSDimitry Andric     assert(!Result && "structural differences second time around?");
271349cc55cSDimitry Andric     (void) Result;
272349cc55cSDimitry Andric     if (!L->use_empty())
273349cc55cSDimitry Andric       Values[L] = R;
274349cc55cSDimitry Andric   }
275349cc55cSDimitry Andric 
276349cc55cSDimitry Andric   void processQueue() {
277349cc55cSDimitry Andric     while (!Queue.empty()) {
278349cc55cSDimitry Andric       BlockPair Pair = Queue.remove_min();
279349cc55cSDimitry Andric       diff(Pair.first, Pair.second);
280349cc55cSDimitry Andric     }
281349cc55cSDimitry Andric   }
282349cc55cSDimitry Andric 
283*bdd1243dSDimitry Andric   void checkAndReportDiffCandidates() {
284*bdd1243dSDimitry Andric     for (BlockDiffCandidate &BDC : BlockDiffCandidates) {
285*bdd1243dSDimitry Andric 
286*bdd1243dSDimitry Andric       // Check assumptions
287*bdd1243dSDimitry Andric       for (const auto &[L, R] : BDC.EquivalenceAssumptions) {
288*bdd1243dSDimitry Andric         auto It = Values.find(L);
289*bdd1243dSDimitry Andric         if (It == Values.end() || It->second != R) {
290*bdd1243dSDimitry Andric           BDC.KnownToDiffer = true;
291*bdd1243dSDimitry Andric           break;
292*bdd1243dSDimitry Andric         }
293*bdd1243dSDimitry Andric       }
294*bdd1243dSDimitry Andric 
295*bdd1243dSDimitry Andric       // Run block diff if the BBs differ
296*bdd1243dSDimitry Andric       if (BDC.KnownToDiffer) {
297*bdd1243dSDimitry Andric         DifferenceEngine::Context C(Engine, BDC.LBB, BDC.RBB);
298*bdd1243dSDimitry Andric         runBlockDiff(BDC.LBB->begin(), BDC.RBB->begin());
299*bdd1243dSDimitry Andric       }
300*bdd1243dSDimitry Andric     }
301*bdd1243dSDimitry Andric   }
302*bdd1243dSDimitry Andric 
303349cc55cSDimitry Andric   void diff(const BasicBlock *L, const BasicBlock *R) {
304349cc55cSDimitry Andric     DifferenceEngine::Context C(Engine, L, R);
305349cc55cSDimitry Andric 
306349cc55cSDimitry Andric     BasicBlock::const_iterator LI = L->begin(), LE = L->end();
307349cc55cSDimitry Andric     BasicBlock::const_iterator RI = R->begin();
308349cc55cSDimitry Andric 
309349cc55cSDimitry Andric     do {
310349cc55cSDimitry Andric       assert(LI != LE && RI != R->end());
311349cc55cSDimitry Andric       const Instruction *LeftI = &*LI, *RightI = &*RI;
312349cc55cSDimitry Andric 
313349cc55cSDimitry Andric       // If the instructions differ, start the more sophisticated diff
314349cc55cSDimitry Andric       // algorithm at the start of the block.
315*bdd1243dSDimitry Andric       if (diff(LeftI, RightI, false, false, true)) {
316349cc55cSDimitry Andric         TentativeValues.clear();
317*bdd1243dSDimitry Andric         // Register (L, R) as diffing pair. Note that we could directly emit a
318*bdd1243dSDimitry Andric         // block diff here, but this way we ensure all diffs are emitted in one
319*bdd1243dSDimitry Andric         // consistent order, independent of whether the diffs were detected
320*bdd1243dSDimitry Andric         // immediately or via invalid assumptions.
321*bdd1243dSDimitry Andric         getOrCreateBlockDiffCandidate(L, R).KnownToDiffer = true;
322*bdd1243dSDimitry Andric         return;
323349cc55cSDimitry Andric       }
324349cc55cSDimitry Andric 
325349cc55cSDimitry Andric       // Otherwise, tentatively unify them.
326349cc55cSDimitry Andric       if (!LeftI->use_empty())
327349cc55cSDimitry Andric         TentativeValues.insert(std::make_pair(LeftI, RightI));
328349cc55cSDimitry Andric 
329349cc55cSDimitry Andric       ++LI;
330349cc55cSDimitry Andric       ++RI;
331349cc55cSDimitry Andric     } while (LI != LE); // This is sufficient: we can't get equality of
332349cc55cSDimitry Andric                         // terminators if there are residual instructions.
333349cc55cSDimitry Andric 
334349cc55cSDimitry Andric     // Unify everything in the block, non-tentatively this time.
335349cc55cSDimitry Andric     TentativeValues.clear();
336349cc55cSDimitry Andric     for (LI = L->begin(), RI = R->begin(); LI != LE; ++LI, ++RI)
337349cc55cSDimitry Andric       unify(&*LI, &*RI);
338349cc55cSDimitry Andric   }
339349cc55cSDimitry Andric 
340349cc55cSDimitry Andric   bool matchForBlockDiff(const Instruction *L, const Instruction *R);
341349cc55cSDimitry Andric   void runBlockDiff(BasicBlock::const_iterator LI,
342349cc55cSDimitry Andric                     BasicBlock::const_iterator RI);
343349cc55cSDimitry Andric 
344349cc55cSDimitry Andric   bool diffCallSites(const CallBase &L, const CallBase &R, bool Complain) {
345349cc55cSDimitry Andric     // FIXME: call attributes
346*bdd1243dSDimitry Andric     AssumptionContext AC = {L.getParent(), R.getParent()};
347*bdd1243dSDimitry Andric     if (!equivalentAsOperands(L.getCalledOperand(), R.getCalledOperand(),
348*bdd1243dSDimitry Andric                               &AC)) {
349349cc55cSDimitry Andric       if (Complain) Engine.log("called functions differ");
350349cc55cSDimitry Andric       return true;
351349cc55cSDimitry Andric     }
352349cc55cSDimitry Andric     if (L.arg_size() != R.arg_size()) {
353349cc55cSDimitry Andric       if (Complain) Engine.log("argument counts differ");
354349cc55cSDimitry Andric       return true;
355349cc55cSDimitry Andric     }
356349cc55cSDimitry Andric     for (unsigned I = 0, E = L.arg_size(); I != E; ++I)
357*bdd1243dSDimitry Andric       if (!equivalentAsOperands(L.getArgOperand(I), R.getArgOperand(I), &AC)) {
358349cc55cSDimitry Andric         if (Complain)
359349cc55cSDimitry Andric           Engine.logf("arguments %l and %r differ")
360349cc55cSDimitry Andric               << L.getArgOperand(I) << R.getArgOperand(I);
361349cc55cSDimitry Andric         return true;
362349cc55cSDimitry Andric       }
363349cc55cSDimitry Andric     return false;
364349cc55cSDimitry Andric   }
365349cc55cSDimitry Andric 
366*bdd1243dSDimitry Andric   // If AllowAssumptions is enabled, whenever we encounter a pair of values
367*bdd1243dSDimitry Andric   // that we cannot prove to be equivalent, we assume equivalence and store that
368*bdd1243dSDimitry Andric   // assumption to be checked later in BlockDiffCandidates.
369349cc55cSDimitry Andric   bool diff(const Instruction *L, const Instruction *R, bool Complain,
370*bdd1243dSDimitry Andric             bool TryUnify, bool AllowAssumptions) {
371349cc55cSDimitry Andric     // FIXME: metadata (if Complain is set)
372*bdd1243dSDimitry Andric     AssumptionContext ACValue = {L->getParent(), R->getParent()};
373*bdd1243dSDimitry Andric     // nullptr AssumptionContext disables assumption generation.
374*bdd1243dSDimitry Andric     const AssumptionContext *AC = AllowAssumptions ? &ACValue : nullptr;
375349cc55cSDimitry Andric 
376349cc55cSDimitry Andric     // Different opcodes always imply different operations.
377349cc55cSDimitry Andric     if (L->getOpcode() != R->getOpcode()) {
378349cc55cSDimitry Andric       if (Complain) Engine.log("different instruction types");
379349cc55cSDimitry Andric       return true;
380349cc55cSDimitry Andric     }
381349cc55cSDimitry Andric 
382349cc55cSDimitry Andric     if (isa<CmpInst>(L)) {
383349cc55cSDimitry Andric       if (cast<CmpInst>(L)->getPredicate()
384349cc55cSDimitry Andric             != cast<CmpInst>(R)->getPredicate()) {
385349cc55cSDimitry Andric         if (Complain) Engine.log("different predicates");
386349cc55cSDimitry Andric         return true;
387349cc55cSDimitry Andric       }
388349cc55cSDimitry Andric     } else if (isa<CallInst>(L)) {
389349cc55cSDimitry Andric       return diffCallSites(cast<CallInst>(*L), cast<CallInst>(*R), Complain);
390349cc55cSDimitry Andric     } else if (isa<PHINode>(L)) {
3914824e7fdSDimitry Andric       const PHINode &LI = cast<PHINode>(*L);
3924824e7fdSDimitry Andric       const PHINode &RI = cast<PHINode>(*R);
393349cc55cSDimitry Andric 
394349cc55cSDimitry Andric       // This is really weird;  type uniquing is broken?
3954824e7fdSDimitry Andric       if (LI.getType() != RI.getType()) {
3964824e7fdSDimitry Andric         if (!LI.getType()->isPointerTy() || !RI.getType()->isPointerTy()) {
397349cc55cSDimitry Andric           if (Complain) Engine.log("different phi types");
398349cc55cSDimitry Andric           return true;
399349cc55cSDimitry Andric         }
400349cc55cSDimitry Andric       }
4014824e7fdSDimitry Andric 
4024824e7fdSDimitry Andric       if (LI.getNumIncomingValues() != RI.getNumIncomingValues()) {
4034824e7fdSDimitry Andric         if (Complain)
4044824e7fdSDimitry Andric           Engine.log("PHI node # of incoming values differ");
4054824e7fdSDimitry Andric         return true;
4064824e7fdSDimitry Andric       }
4074824e7fdSDimitry Andric 
4084824e7fdSDimitry Andric       for (unsigned I = 0; I < LI.getNumIncomingValues(); ++I) {
4094824e7fdSDimitry Andric         if (TryUnify)
4104824e7fdSDimitry Andric           tryUnify(LI.getIncomingBlock(I), RI.getIncomingBlock(I));
4114824e7fdSDimitry Andric 
4124824e7fdSDimitry Andric         if (!equivalentAsOperands(LI.getIncomingValue(I),
413*bdd1243dSDimitry Andric                                   RI.getIncomingValue(I), AC)) {
4144824e7fdSDimitry Andric           if (Complain)
4154824e7fdSDimitry Andric             Engine.log("PHI node incoming values differ");
4164824e7fdSDimitry Andric           return true;
4174824e7fdSDimitry Andric         }
4184824e7fdSDimitry Andric       }
4194824e7fdSDimitry Andric 
420349cc55cSDimitry Andric       return false;
421349cc55cSDimitry Andric 
422349cc55cSDimitry Andric     // Terminators.
423349cc55cSDimitry Andric     } else if (isa<InvokeInst>(L)) {
424349cc55cSDimitry Andric       const InvokeInst &LI = cast<InvokeInst>(*L);
425349cc55cSDimitry Andric       const InvokeInst &RI = cast<InvokeInst>(*R);
426349cc55cSDimitry Andric       if (diffCallSites(LI, RI, Complain))
427349cc55cSDimitry Andric         return true;
428349cc55cSDimitry Andric 
429349cc55cSDimitry Andric       if (TryUnify) {
430349cc55cSDimitry Andric         tryUnify(LI.getNormalDest(), RI.getNormalDest());
431349cc55cSDimitry Andric         tryUnify(LI.getUnwindDest(), RI.getUnwindDest());
432349cc55cSDimitry Andric       }
433349cc55cSDimitry Andric       return false;
434349cc55cSDimitry Andric 
435349cc55cSDimitry Andric     } else if (isa<CallBrInst>(L)) {
436349cc55cSDimitry Andric       const CallBrInst &LI = cast<CallBrInst>(*L);
437349cc55cSDimitry Andric       const CallBrInst &RI = cast<CallBrInst>(*R);
438349cc55cSDimitry Andric       if (LI.getNumIndirectDests() != RI.getNumIndirectDests()) {
439349cc55cSDimitry Andric         if (Complain)
440349cc55cSDimitry Andric           Engine.log("callbr # of indirect destinations differ");
441349cc55cSDimitry Andric         return true;
442349cc55cSDimitry Andric       }
443349cc55cSDimitry Andric 
444349cc55cSDimitry Andric       // Perform the "try unify" step so that we can equate the indirect
445349cc55cSDimitry Andric       // destinations before checking the call site.
446349cc55cSDimitry Andric       for (unsigned I = 0; I < LI.getNumIndirectDests(); I++)
447349cc55cSDimitry Andric         tryUnify(LI.getIndirectDest(I), RI.getIndirectDest(I));
448349cc55cSDimitry Andric 
449349cc55cSDimitry Andric       if (diffCallSites(LI, RI, Complain))
450349cc55cSDimitry Andric         return true;
451349cc55cSDimitry Andric 
452349cc55cSDimitry Andric       if (TryUnify)
453349cc55cSDimitry Andric         tryUnify(LI.getDefaultDest(), RI.getDefaultDest());
454349cc55cSDimitry Andric       return false;
455349cc55cSDimitry Andric 
456349cc55cSDimitry Andric     } else if (isa<BranchInst>(L)) {
457349cc55cSDimitry Andric       const BranchInst *LI = cast<BranchInst>(L);
458349cc55cSDimitry Andric       const BranchInst *RI = cast<BranchInst>(R);
459349cc55cSDimitry Andric       if (LI->isConditional() != RI->isConditional()) {
460349cc55cSDimitry Andric         if (Complain) Engine.log("branch conditionality differs");
461349cc55cSDimitry Andric         return true;
462349cc55cSDimitry Andric       }
463349cc55cSDimitry Andric 
464349cc55cSDimitry Andric       if (LI->isConditional()) {
465*bdd1243dSDimitry Andric         if (!equivalentAsOperands(LI->getCondition(), RI->getCondition(), AC)) {
466349cc55cSDimitry Andric           if (Complain) Engine.log("branch conditions differ");
467349cc55cSDimitry Andric           return true;
468349cc55cSDimitry Andric         }
469349cc55cSDimitry Andric         if (TryUnify) tryUnify(LI->getSuccessor(1), RI->getSuccessor(1));
470349cc55cSDimitry Andric       }
471349cc55cSDimitry Andric       if (TryUnify) tryUnify(LI->getSuccessor(0), RI->getSuccessor(0));
472349cc55cSDimitry Andric       return false;
473349cc55cSDimitry Andric 
474349cc55cSDimitry Andric     } else if (isa<IndirectBrInst>(L)) {
475349cc55cSDimitry Andric       const IndirectBrInst *LI = cast<IndirectBrInst>(L);
476349cc55cSDimitry Andric       const IndirectBrInst *RI = cast<IndirectBrInst>(R);
477349cc55cSDimitry Andric       if (LI->getNumDestinations() != RI->getNumDestinations()) {
478349cc55cSDimitry Andric         if (Complain) Engine.log("indirectbr # of destinations differ");
479349cc55cSDimitry Andric         return true;
480349cc55cSDimitry Andric       }
481349cc55cSDimitry Andric 
482*bdd1243dSDimitry Andric       if (!equivalentAsOperands(LI->getAddress(), RI->getAddress(), AC)) {
483349cc55cSDimitry Andric         if (Complain) Engine.log("indirectbr addresses differ");
484349cc55cSDimitry Andric         return true;
485349cc55cSDimitry Andric       }
486349cc55cSDimitry Andric 
487349cc55cSDimitry Andric       if (TryUnify) {
488349cc55cSDimitry Andric         for (unsigned i = 0; i < LI->getNumDestinations(); i++) {
489349cc55cSDimitry Andric           tryUnify(LI->getDestination(i), RI->getDestination(i));
490349cc55cSDimitry Andric         }
491349cc55cSDimitry Andric       }
492349cc55cSDimitry Andric       return false;
493349cc55cSDimitry Andric 
494349cc55cSDimitry Andric     } else if (isa<SwitchInst>(L)) {
495349cc55cSDimitry Andric       const SwitchInst *LI = cast<SwitchInst>(L);
496349cc55cSDimitry Andric       const SwitchInst *RI = cast<SwitchInst>(R);
497*bdd1243dSDimitry Andric       if (!equivalentAsOperands(LI->getCondition(), RI->getCondition(), AC)) {
498349cc55cSDimitry Andric         if (Complain) Engine.log("switch conditions differ");
499349cc55cSDimitry Andric         return true;
500349cc55cSDimitry Andric       }
501349cc55cSDimitry Andric       if (TryUnify) tryUnify(LI->getDefaultDest(), RI->getDefaultDest());
502349cc55cSDimitry Andric 
503349cc55cSDimitry Andric       bool Difference = false;
504349cc55cSDimitry Andric 
505349cc55cSDimitry Andric       DenseMap<const ConstantInt *, const BasicBlock *> LCases;
506349cc55cSDimitry Andric       for (auto Case : LI->cases())
507349cc55cSDimitry Andric         LCases[Case.getCaseValue()] = Case.getCaseSuccessor();
508349cc55cSDimitry Andric 
509349cc55cSDimitry Andric       for (auto Case : RI->cases()) {
510349cc55cSDimitry Andric         const ConstantInt *CaseValue = Case.getCaseValue();
511349cc55cSDimitry Andric         const BasicBlock *LCase = LCases[CaseValue];
512349cc55cSDimitry Andric         if (LCase) {
513349cc55cSDimitry Andric           if (TryUnify)
514349cc55cSDimitry Andric             tryUnify(LCase, Case.getCaseSuccessor());
515349cc55cSDimitry Andric           LCases.erase(CaseValue);
516349cc55cSDimitry Andric         } else if (Complain || !Difference) {
517349cc55cSDimitry Andric           if (Complain)
518349cc55cSDimitry Andric             Engine.logf("right switch has extra case %r") << CaseValue;
519349cc55cSDimitry Andric           Difference = true;
520349cc55cSDimitry Andric         }
521349cc55cSDimitry Andric       }
522349cc55cSDimitry Andric       if (!Difference)
523349cc55cSDimitry Andric         for (DenseMap<const ConstantInt *, const BasicBlock *>::iterator
524349cc55cSDimitry Andric                  I = LCases.begin(),
525349cc55cSDimitry Andric                  E = LCases.end();
526349cc55cSDimitry Andric              I != E; ++I) {
527349cc55cSDimitry Andric           if (Complain)
528349cc55cSDimitry Andric             Engine.logf("left switch has extra case %l") << I->first;
529349cc55cSDimitry Andric           Difference = true;
530349cc55cSDimitry Andric         }
531349cc55cSDimitry Andric       return Difference;
532349cc55cSDimitry Andric     } else if (isa<UnreachableInst>(L)) {
533349cc55cSDimitry Andric       return false;
534349cc55cSDimitry Andric     }
535349cc55cSDimitry Andric 
536349cc55cSDimitry Andric     if (L->getNumOperands() != R->getNumOperands()) {
537349cc55cSDimitry Andric       if (Complain) Engine.log("instructions have different operand counts");
538349cc55cSDimitry Andric       return true;
539349cc55cSDimitry Andric     }
540349cc55cSDimitry Andric 
541349cc55cSDimitry Andric     for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I) {
542349cc55cSDimitry Andric       Value *LO = L->getOperand(I), *RO = R->getOperand(I);
543*bdd1243dSDimitry Andric       if (!equivalentAsOperands(LO, RO, AC)) {
544349cc55cSDimitry Andric         if (Complain) Engine.logf("operands %l and %r differ") << LO << RO;
545349cc55cSDimitry Andric         return true;
546349cc55cSDimitry Andric       }
547349cc55cSDimitry Andric     }
548349cc55cSDimitry Andric 
549349cc55cSDimitry Andric     return false;
550349cc55cSDimitry Andric   }
551349cc55cSDimitry Andric 
552349cc55cSDimitry Andric public:
553*bdd1243dSDimitry Andric   bool equivalentAsOperands(const Constant *L, const Constant *R,
554*bdd1243dSDimitry Andric                             const AssumptionContext *AC) {
555349cc55cSDimitry Andric     // Use equality as a preliminary filter.
556349cc55cSDimitry Andric     if (L == R)
557349cc55cSDimitry Andric       return true;
558349cc55cSDimitry Andric 
559349cc55cSDimitry Andric     if (L->getValueID() != R->getValueID())
560349cc55cSDimitry Andric       return false;
561349cc55cSDimitry Andric 
562349cc55cSDimitry Andric     // Ask the engine about global values.
563349cc55cSDimitry Andric     if (isa<GlobalValue>(L))
564349cc55cSDimitry Andric       return Engine.equivalentAsOperands(cast<GlobalValue>(L),
565349cc55cSDimitry Andric                                          cast<GlobalValue>(R));
566349cc55cSDimitry Andric 
567349cc55cSDimitry Andric     // Compare constant expressions structurally.
568349cc55cSDimitry Andric     if (isa<ConstantExpr>(L))
569*bdd1243dSDimitry Andric       return equivalentAsOperands(cast<ConstantExpr>(L), cast<ConstantExpr>(R),
570*bdd1243dSDimitry Andric                                   AC);
571349cc55cSDimitry Andric 
572349cc55cSDimitry Andric     // Constants of the "same type" don't always actually have the same
573349cc55cSDimitry Andric     // type; I don't know why.  Just white-list them.
574349cc55cSDimitry Andric     if (isa<ConstantPointerNull>(L) || isa<UndefValue>(L) || isa<ConstantAggregateZero>(L))
575349cc55cSDimitry Andric       return true;
576349cc55cSDimitry Andric 
577349cc55cSDimitry Andric     // Block addresses only match if we've already encountered the
578349cc55cSDimitry Andric     // block.  FIXME: tentative matches?
579349cc55cSDimitry Andric     if (isa<BlockAddress>(L))
580349cc55cSDimitry Andric       return Blocks[cast<BlockAddress>(L)->getBasicBlock()]
581349cc55cSDimitry Andric                  == cast<BlockAddress>(R)->getBasicBlock();
582349cc55cSDimitry Andric 
583349cc55cSDimitry Andric     // If L and R are ConstantVectors, compare each element
584349cc55cSDimitry Andric     if (isa<ConstantVector>(L)) {
585349cc55cSDimitry Andric       const ConstantVector *CVL = cast<ConstantVector>(L);
586349cc55cSDimitry Andric       const ConstantVector *CVR = cast<ConstantVector>(R);
587349cc55cSDimitry Andric       if (CVL->getType()->getNumElements() != CVR->getType()->getNumElements())
588349cc55cSDimitry Andric         return false;
589349cc55cSDimitry Andric       for (unsigned i = 0; i < CVL->getType()->getNumElements(); i++) {
590*bdd1243dSDimitry Andric         if (!equivalentAsOperands(CVL->getOperand(i), CVR->getOperand(i), AC))
591349cc55cSDimitry Andric           return false;
592349cc55cSDimitry Andric       }
593349cc55cSDimitry Andric       return true;
594349cc55cSDimitry Andric     }
595349cc55cSDimitry Andric 
596349cc55cSDimitry Andric     // If L and R are ConstantArrays, compare the element count and types.
597349cc55cSDimitry Andric     if (isa<ConstantArray>(L)) {
598349cc55cSDimitry Andric       const ConstantArray *CAL = cast<ConstantArray>(L);
599349cc55cSDimitry Andric       const ConstantArray *CAR = cast<ConstantArray>(R);
600349cc55cSDimitry Andric       // Sometimes a type may be equivalent, but not uniquified---e.g. it may
601349cc55cSDimitry Andric       // contain a GEP instruction. Do a deeper comparison of the types.
602349cc55cSDimitry Andric       if (CAL->getType()->getNumElements() != CAR->getType()->getNumElements())
603349cc55cSDimitry Andric         return false;
604349cc55cSDimitry Andric 
605349cc55cSDimitry Andric       for (unsigned I = 0; I < CAL->getType()->getNumElements(); ++I) {
606349cc55cSDimitry Andric         if (!equivalentAsOperands(CAL->getAggregateElement(I),
607*bdd1243dSDimitry Andric                                   CAR->getAggregateElement(I), AC))
608349cc55cSDimitry Andric           return false;
609349cc55cSDimitry Andric       }
610349cc55cSDimitry Andric 
611349cc55cSDimitry Andric       return true;
612349cc55cSDimitry Andric     }
613349cc55cSDimitry Andric 
614349cc55cSDimitry Andric     // If L and R are ConstantStructs, compare each field and type.
615349cc55cSDimitry Andric     if (isa<ConstantStruct>(L)) {
616349cc55cSDimitry Andric       const ConstantStruct *CSL = cast<ConstantStruct>(L);
617349cc55cSDimitry Andric       const ConstantStruct *CSR = cast<ConstantStruct>(R);
618349cc55cSDimitry Andric 
619349cc55cSDimitry Andric       const StructType *LTy = cast<StructType>(CSL->getType());
620349cc55cSDimitry Andric       const StructType *RTy = cast<StructType>(CSR->getType());
621349cc55cSDimitry Andric 
622349cc55cSDimitry Andric       // The StructTypes should have the same attributes. Don't use
623349cc55cSDimitry Andric       // isLayoutIdentical(), because that just checks the element pointers,
624349cc55cSDimitry Andric       // which may not work here.
625349cc55cSDimitry Andric       if (LTy->getNumElements() != RTy->getNumElements() ||
626349cc55cSDimitry Andric           LTy->isPacked() != RTy->isPacked())
627349cc55cSDimitry Andric         return false;
628349cc55cSDimitry Andric 
629349cc55cSDimitry Andric       for (unsigned I = 0; I < LTy->getNumElements(); I++) {
630349cc55cSDimitry Andric         const Value *LAgg = CSL->getAggregateElement(I);
631349cc55cSDimitry Andric         const Value *RAgg = CSR->getAggregateElement(I);
632349cc55cSDimitry Andric 
633349cc55cSDimitry Andric         if (LAgg == SavedLHS || RAgg == SavedRHS) {
634349cc55cSDimitry Andric           if (LAgg != SavedLHS || RAgg != SavedRHS)
635349cc55cSDimitry Andric             // If the left and right operands aren't both re-analyzing the
636349cc55cSDimitry Andric             // variable, then the initialiers don't match, so report "false".
637349cc55cSDimitry Andric             // Otherwise, we skip these operands..
638349cc55cSDimitry Andric             return false;
639349cc55cSDimitry Andric 
640349cc55cSDimitry Andric           continue;
641349cc55cSDimitry Andric         }
642349cc55cSDimitry Andric 
643*bdd1243dSDimitry Andric         if (!equivalentAsOperands(LAgg, RAgg, AC)) {
644349cc55cSDimitry Andric           return false;
645349cc55cSDimitry Andric         }
646349cc55cSDimitry Andric       }
647349cc55cSDimitry Andric 
648349cc55cSDimitry Andric       return true;
649349cc55cSDimitry Andric     }
650349cc55cSDimitry Andric 
651349cc55cSDimitry Andric     return false;
652349cc55cSDimitry Andric   }
653349cc55cSDimitry Andric 
654*bdd1243dSDimitry Andric   bool equivalentAsOperands(const ConstantExpr *L, const ConstantExpr *R,
655*bdd1243dSDimitry Andric                             const AssumptionContext *AC) {
656349cc55cSDimitry Andric     if (L == R)
657349cc55cSDimitry Andric       return true;
658349cc55cSDimitry Andric 
659349cc55cSDimitry Andric     if (L->getOpcode() != R->getOpcode())
660349cc55cSDimitry Andric       return false;
661349cc55cSDimitry Andric 
662349cc55cSDimitry Andric     switch (L->getOpcode()) {
663349cc55cSDimitry Andric     case Instruction::ICmp:
664349cc55cSDimitry Andric     case Instruction::FCmp:
665349cc55cSDimitry Andric       if (L->getPredicate() != R->getPredicate())
666349cc55cSDimitry Andric         return false;
667349cc55cSDimitry Andric       break;
668349cc55cSDimitry Andric 
669349cc55cSDimitry Andric     case Instruction::GetElementPtr:
670349cc55cSDimitry Andric       // FIXME: inbounds?
671349cc55cSDimitry Andric       break;
672349cc55cSDimitry Andric 
673349cc55cSDimitry Andric     default:
674349cc55cSDimitry Andric       break;
675349cc55cSDimitry Andric     }
676349cc55cSDimitry Andric 
677349cc55cSDimitry Andric     if (L->getNumOperands() != R->getNumOperands())
678349cc55cSDimitry Andric       return false;
679349cc55cSDimitry Andric 
680349cc55cSDimitry Andric     for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I) {
681349cc55cSDimitry Andric       const auto *LOp = L->getOperand(I);
682349cc55cSDimitry Andric       const auto *ROp = R->getOperand(I);
683349cc55cSDimitry Andric 
684349cc55cSDimitry Andric       if (LOp == SavedLHS || ROp == SavedRHS) {
685349cc55cSDimitry Andric         if (LOp != SavedLHS || ROp != SavedRHS)
686349cc55cSDimitry Andric           // If the left and right operands aren't both re-analyzing the
687349cc55cSDimitry Andric           // variable, then the initialiers don't match, so report "false".
688349cc55cSDimitry Andric           // Otherwise, we skip these operands..
689349cc55cSDimitry Andric           return false;
690349cc55cSDimitry Andric 
691349cc55cSDimitry Andric         continue;
692349cc55cSDimitry Andric       }
693349cc55cSDimitry Andric 
694*bdd1243dSDimitry Andric       if (!equivalentAsOperands(LOp, ROp, AC))
695349cc55cSDimitry Andric         return false;
696349cc55cSDimitry Andric     }
697349cc55cSDimitry Andric 
698349cc55cSDimitry Andric     return true;
699349cc55cSDimitry Andric   }
700349cc55cSDimitry Andric 
701*bdd1243dSDimitry Andric   // There are cases where we cannot determine whether two values are
702*bdd1243dSDimitry Andric   // equivalent, because it depends on not yet processed basic blocks -- see the
703*bdd1243dSDimitry Andric   // documentation on assumptions.
704*bdd1243dSDimitry Andric   //
705*bdd1243dSDimitry Andric   // AC is the context in which we are currently performing a diff.
706*bdd1243dSDimitry Andric   // When we encounter a pair of values for which we can neither prove
707*bdd1243dSDimitry Andric   // equivalence nor the opposite, we do the following:
708*bdd1243dSDimitry Andric   //  * If AC is nullptr, we treat the pair as non-equivalent.
709*bdd1243dSDimitry Andric   //  * If AC is set, we add an assumption for the basic blocks given by AC,
710*bdd1243dSDimitry Andric   //    and treat the pair as equivalent. The assumption is checked later.
711*bdd1243dSDimitry Andric   bool equivalentAsOperands(const Value *L, const Value *R,
712*bdd1243dSDimitry Andric                             const AssumptionContext *AC) {
713349cc55cSDimitry Andric     // Fall out if the values have different kind.
714349cc55cSDimitry Andric     // This possibly shouldn't take priority over oracles.
715349cc55cSDimitry Andric     if (L->getValueID() != R->getValueID())
716349cc55cSDimitry Andric       return false;
717349cc55cSDimitry Andric 
718349cc55cSDimitry Andric     // Value subtypes:  Argument, Constant, Instruction, BasicBlock,
719349cc55cSDimitry Andric     //                  InlineAsm, MDNode, MDString, PseudoSourceValue
720349cc55cSDimitry Andric 
721349cc55cSDimitry Andric     if (isa<Constant>(L))
722*bdd1243dSDimitry Andric       return equivalentAsOperands(cast<Constant>(L), cast<Constant>(R), AC);
723349cc55cSDimitry Andric 
724*bdd1243dSDimitry Andric     if (isa<Instruction>(L)) {
725*bdd1243dSDimitry Andric       auto It = Values.find(L);
726*bdd1243dSDimitry Andric       if (It != Values.end())
727*bdd1243dSDimitry Andric         return It->second == R;
728*bdd1243dSDimitry Andric 
729*bdd1243dSDimitry Andric       if (TentativeValues.count(std::make_pair(L, R)))
730*bdd1243dSDimitry Andric         return true;
731*bdd1243dSDimitry Andric 
732*bdd1243dSDimitry Andric       // L and R might be equivalent, this could depend on not yet processed
733*bdd1243dSDimitry Andric       // basic blocks, so we cannot decide here.
734*bdd1243dSDimitry Andric       if (AC) {
735*bdd1243dSDimitry Andric         // Add an assumption, unless there is a conflict with an existing one
736*bdd1243dSDimitry Andric         BlockDiffCandidate &BDC =
737*bdd1243dSDimitry Andric             getOrCreateBlockDiffCandidate(AC->LBB, AC->RBB);
738*bdd1243dSDimitry Andric         auto InsertionResult = BDC.EquivalenceAssumptions.insert({L, R});
739*bdd1243dSDimitry Andric         if (!InsertionResult.second && InsertionResult.first->second != R) {
740*bdd1243dSDimitry Andric           // We already have a conflicting equivalence assumption for L, so at
741*bdd1243dSDimitry Andric           // least one must be wrong, and we know that there is a diff.
742*bdd1243dSDimitry Andric           BDC.KnownToDiffer = true;
743*bdd1243dSDimitry Andric           BDC.EquivalenceAssumptions.clear();
744*bdd1243dSDimitry Andric           return false;
745*bdd1243dSDimitry Andric         }
746*bdd1243dSDimitry Andric         // Optimistically assume equivalence, and check later once all BBs
747*bdd1243dSDimitry Andric         // have been processed.
748*bdd1243dSDimitry Andric         return true;
749*bdd1243dSDimitry Andric       }
750*bdd1243dSDimitry Andric 
751*bdd1243dSDimitry Andric       // Assumptions disabled, so pessimistically assume non-equivalence.
752*bdd1243dSDimitry Andric       return false;
753*bdd1243dSDimitry Andric     }
754349cc55cSDimitry Andric 
755349cc55cSDimitry Andric     if (isa<Argument>(L))
756349cc55cSDimitry Andric       return Values[L] == R;
757349cc55cSDimitry Andric 
758349cc55cSDimitry Andric     if (isa<BasicBlock>(L))
759349cc55cSDimitry Andric       return Blocks[cast<BasicBlock>(L)] != R;
760349cc55cSDimitry Andric 
761349cc55cSDimitry Andric     // Pretend everything else is identical.
762349cc55cSDimitry Andric     return true;
763349cc55cSDimitry Andric   }
764349cc55cSDimitry Andric 
765349cc55cSDimitry Andric   // Avoid a gcc warning about accessing 'this' in an initializer.
766349cc55cSDimitry Andric   FunctionDifferenceEngine *this_() { return this; }
767349cc55cSDimitry Andric 
768349cc55cSDimitry Andric public:
769349cc55cSDimitry Andric   FunctionDifferenceEngine(DifferenceEngine &Engine,
770349cc55cSDimitry Andric                            const Value *SavedLHS = nullptr,
771349cc55cSDimitry Andric                            const Value *SavedRHS = nullptr)
772349cc55cSDimitry Andric       : Engine(Engine), SavedLHS(SavedLHS), SavedRHS(SavedRHS),
773349cc55cSDimitry Andric         Queue(QueueSorter(*this_())) {}
774349cc55cSDimitry Andric 
775349cc55cSDimitry Andric   void diff(const Function *L, const Function *R) {
776*bdd1243dSDimitry Andric     assert(Values.empty() && "Multiple diffs per engine are not supported!");
777*bdd1243dSDimitry Andric 
778349cc55cSDimitry Andric     if (L->arg_size() != R->arg_size())
779349cc55cSDimitry Andric       Engine.log("different argument counts");
780349cc55cSDimitry Andric 
781349cc55cSDimitry Andric     // Map the arguments.
782349cc55cSDimitry Andric     for (Function::const_arg_iterator LI = L->arg_begin(), LE = L->arg_end(),
783349cc55cSDimitry Andric                                       RI = R->arg_begin(), RE = R->arg_end();
784349cc55cSDimitry Andric          LI != LE && RI != RE; ++LI, ++RI)
785349cc55cSDimitry Andric       Values[&*LI] = &*RI;
786349cc55cSDimitry Andric 
787349cc55cSDimitry Andric     tryUnify(&*L->begin(), &*R->begin());
788349cc55cSDimitry Andric     processQueue();
789*bdd1243dSDimitry Andric     checkAndReportDiffCandidates();
790349cc55cSDimitry Andric   }
791349cc55cSDimitry Andric };
792349cc55cSDimitry Andric 
793349cc55cSDimitry Andric struct DiffEntry {
794349cc55cSDimitry Andric   DiffEntry() : Cost(0) {}
795349cc55cSDimitry Andric 
796349cc55cSDimitry Andric   unsigned Cost;
797349cc55cSDimitry Andric   llvm::SmallVector<char, 8> Path; // actually of DifferenceEngine::DiffChange
798349cc55cSDimitry Andric };
799349cc55cSDimitry Andric 
800349cc55cSDimitry Andric bool FunctionDifferenceEngine::matchForBlockDiff(const Instruction *L,
801349cc55cSDimitry Andric                                                  const Instruction *R) {
802*bdd1243dSDimitry Andric   return !diff(L, R, false, false, false);
803349cc55cSDimitry Andric }
804349cc55cSDimitry Andric 
805349cc55cSDimitry Andric void FunctionDifferenceEngine::runBlockDiff(BasicBlock::const_iterator LStart,
806349cc55cSDimitry Andric                                             BasicBlock::const_iterator RStart) {
807349cc55cSDimitry Andric   BasicBlock::const_iterator LE = LStart->getParent()->end();
808349cc55cSDimitry Andric   BasicBlock::const_iterator RE = RStart->getParent()->end();
809349cc55cSDimitry Andric 
810349cc55cSDimitry Andric   unsigned NL = std::distance(LStart, LE);
811349cc55cSDimitry Andric 
812349cc55cSDimitry Andric   SmallVector<DiffEntry, 20> Paths1(NL+1);
813349cc55cSDimitry Andric   SmallVector<DiffEntry, 20> Paths2(NL+1);
814349cc55cSDimitry Andric 
815349cc55cSDimitry Andric   DiffEntry *Cur = Paths1.data();
816349cc55cSDimitry Andric   DiffEntry *Next = Paths2.data();
817349cc55cSDimitry Andric 
818349cc55cSDimitry Andric   const unsigned LeftCost = 2;
819349cc55cSDimitry Andric   const unsigned RightCost = 2;
820349cc55cSDimitry Andric   const unsigned MatchCost = 0;
821349cc55cSDimitry Andric 
822349cc55cSDimitry Andric   assert(TentativeValues.empty());
823349cc55cSDimitry Andric 
824349cc55cSDimitry Andric   // Initialize the first column.
825349cc55cSDimitry Andric   for (unsigned I = 0; I != NL+1; ++I) {
826349cc55cSDimitry Andric     Cur[I].Cost = I * LeftCost;
827349cc55cSDimitry Andric     for (unsigned J = 0; J != I; ++J)
828349cc55cSDimitry Andric       Cur[I].Path.push_back(DC_left);
829349cc55cSDimitry Andric   }
830349cc55cSDimitry Andric 
831349cc55cSDimitry Andric   for (BasicBlock::const_iterator RI = RStart; RI != RE; ++RI) {
832349cc55cSDimitry Andric     // Initialize the first row.
833349cc55cSDimitry Andric     Next[0] = Cur[0];
834349cc55cSDimitry Andric     Next[0].Cost += RightCost;
835349cc55cSDimitry Andric     Next[0].Path.push_back(DC_right);
836349cc55cSDimitry Andric 
837349cc55cSDimitry Andric     unsigned Index = 1;
838349cc55cSDimitry Andric     for (BasicBlock::const_iterator LI = LStart; LI != LE; ++LI, ++Index) {
839349cc55cSDimitry Andric       if (matchForBlockDiff(&*LI, &*RI)) {
840349cc55cSDimitry Andric         Next[Index] = Cur[Index-1];
841349cc55cSDimitry Andric         Next[Index].Cost += MatchCost;
842349cc55cSDimitry Andric         Next[Index].Path.push_back(DC_match);
843349cc55cSDimitry Andric         TentativeValues.insert(std::make_pair(&*LI, &*RI));
844349cc55cSDimitry Andric       } else if (Next[Index-1].Cost <= Cur[Index].Cost) {
845349cc55cSDimitry Andric         Next[Index] = Next[Index-1];
846349cc55cSDimitry Andric         Next[Index].Cost += LeftCost;
847349cc55cSDimitry Andric         Next[Index].Path.push_back(DC_left);
848349cc55cSDimitry Andric       } else {
849349cc55cSDimitry Andric         Next[Index] = Cur[Index];
850349cc55cSDimitry Andric         Next[Index].Cost += RightCost;
851349cc55cSDimitry Andric         Next[Index].Path.push_back(DC_right);
852349cc55cSDimitry Andric       }
853349cc55cSDimitry Andric     }
854349cc55cSDimitry Andric 
855349cc55cSDimitry Andric     std::swap(Cur, Next);
856349cc55cSDimitry Andric   }
857349cc55cSDimitry Andric 
858349cc55cSDimitry Andric   // We don't need the tentative values anymore; everything from here
859349cc55cSDimitry Andric   // on out should be non-tentative.
860349cc55cSDimitry Andric   TentativeValues.clear();
861349cc55cSDimitry Andric 
862349cc55cSDimitry Andric   SmallVectorImpl<char> &Path = Cur[NL].Path;
863349cc55cSDimitry Andric   BasicBlock::const_iterator LI = LStart, RI = RStart;
864349cc55cSDimitry Andric 
865349cc55cSDimitry Andric   DiffLogBuilder Diff(Engine.getConsumer());
866349cc55cSDimitry Andric 
867349cc55cSDimitry Andric   // Drop trailing matches.
868349cc55cSDimitry Andric   while (Path.size() && Path.back() == DC_match)
869349cc55cSDimitry Andric     Path.pop_back();
870349cc55cSDimitry Andric 
871349cc55cSDimitry Andric   // Skip leading matches.
872349cc55cSDimitry Andric   SmallVectorImpl<char>::iterator
873349cc55cSDimitry Andric     PI = Path.begin(), PE = Path.end();
874349cc55cSDimitry Andric   while (PI != PE && *PI == DC_match) {
875349cc55cSDimitry Andric     unify(&*LI, &*RI);
876349cc55cSDimitry Andric     ++PI;
877349cc55cSDimitry Andric     ++LI;
878349cc55cSDimitry Andric     ++RI;
879349cc55cSDimitry Andric   }
880349cc55cSDimitry Andric 
881349cc55cSDimitry Andric   for (; PI != PE; ++PI) {
882349cc55cSDimitry Andric     switch (static_cast<DiffChange>(*PI)) {
883349cc55cSDimitry Andric     case DC_match:
884349cc55cSDimitry Andric       assert(LI != LE && RI != RE);
885349cc55cSDimitry Andric       {
886349cc55cSDimitry Andric         const Instruction *L = &*LI, *R = &*RI;
887349cc55cSDimitry Andric         unify(L, R);
888349cc55cSDimitry Andric         Diff.addMatch(L, R);
889349cc55cSDimitry Andric       }
890349cc55cSDimitry Andric       ++LI; ++RI;
891349cc55cSDimitry Andric       break;
892349cc55cSDimitry Andric 
893349cc55cSDimitry Andric     case DC_left:
894349cc55cSDimitry Andric       assert(LI != LE);
895349cc55cSDimitry Andric       Diff.addLeft(&*LI);
896349cc55cSDimitry Andric       ++LI;
897349cc55cSDimitry Andric       break;
898349cc55cSDimitry Andric 
899349cc55cSDimitry Andric     case DC_right:
900349cc55cSDimitry Andric       assert(RI != RE);
901349cc55cSDimitry Andric       Diff.addRight(&*RI);
902349cc55cSDimitry Andric       ++RI;
903349cc55cSDimitry Andric       break;
904349cc55cSDimitry Andric     }
905349cc55cSDimitry Andric   }
906349cc55cSDimitry Andric 
907349cc55cSDimitry Andric   // Finishing unifying and complaining about the tails of the block,
908349cc55cSDimitry Andric   // which should be matches all the way through.
909349cc55cSDimitry Andric   while (LI != LE) {
910349cc55cSDimitry Andric     assert(RI != RE);
911349cc55cSDimitry Andric     unify(&*LI, &*RI);
912349cc55cSDimitry Andric     ++LI;
913349cc55cSDimitry Andric     ++RI;
914349cc55cSDimitry Andric   }
915349cc55cSDimitry Andric 
916349cc55cSDimitry Andric   // If the terminators have different kinds, but one is an invoke and the
917349cc55cSDimitry Andric   // other is an unconditional branch immediately following a call, unify
918349cc55cSDimitry Andric   // the results and the destinations.
919349cc55cSDimitry Andric   const Instruction *LTerm = LStart->getParent()->getTerminator();
920349cc55cSDimitry Andric   const Instruction *RTerm = RStart->getParent()->getTerminator();
921349cc55cSDimitry Andric   if (isa<BranchInst>(LTerm) && isa<InvokeInst>(RTerm)) {
922349cc55cSDimitry Andric     if (cast<BranchInst>(LTerm)->isConditional()) return;
923349cc55cSDimitry Andric     BasicBlock::const_iterator I = LTerm->getIterator();
924349cc55cSDimitry Andric     if (I == LStart->getParent()->begin()) return;
925349cc55cSDimitry Andric     --I;
926349cc55cSDimitry Andric     if (!isa<CallInst>(*I)) return;
927349cc55cSDimitry Andric     const CallInst *LCall = cast<CallInst>(&*I);
928349cc55cSDimitry Andric     const InvokeInst *RInvoke = cast<InvokeInst>(RTerm);
929349cc55cSDimitry Andric     if (!equivalentAsOperands(LCall->getCalledOperand(),
930*bdd1243dSDimitry Andric                               RInvoke->getCalledOperand(), nullptr))
931349cc55cSDimitry Andric       return;
932349cc55cSDimitry Andric     if (!LCall->use_empty())
933349cc55cSDimitry Andric       Values[LCall] = RInvoke;
934349cc55cSDimitry Andric     tryUnify(LTerm->getSuccessor(0), RInvoke->getNormalDest());
935349cc55cSDimitry Andric   } else if (isa<InvokeInst>(LTerm) && isa<BranchInst>(RTerm)) {
936349cc55cSDimitry Andric     if (cast<BranchInst>(RTerm)->isConditional()) return;
937349cc55cSDimitry Andric     BasicBlock::const_iterator I = RTerm->getIterator();
938349cc55cSDimitry Andric     if (I == RStart->getParent()->begin()) return;
939349cc55cSDimitry Andric     --I;
940349cc55cSDimitry Andric     if (!isa<CallInst>(*I)) return;
941349cc55cSDimitry Andric     const CallInst *RCall = cast<CallInst>(I);
942349cc55cSDimitry Andric     const InvokeInst *LInvoke = cast<InvokeInst>(LTerm);
943349cc55cSDimitry Andric     if (!equivalentAsOperands(LInvoke->getCalledOperand(),
944*bdd1243dSDimitry Andric                               RCall->getCalledOperand(), nullptr))
945349cc55cSDimitry Andric       return;
946349cc55cSDimitry Andric     if (!LInvoke->use_empty())
947349cc55cSDimitry Andric       Values[LInvoke] = RCall;
948349cc55cSDimitry Andric     tryUnify(LInvoke->getNormalDest(), RTerm->getSuccessor(0));
949349cc55cSDimitry Andric   }
950349cc55cSDimitry Andric }
951349cc55cSDimitry Andric }
952349cc55cSDimitry Andric 
953349cc55cSDimitry Andric void DifferenceEngine::Oracle::anchor() { }
954349cc55cSDimitry Andric 
955349cc55cSDimitry Andric void DifferenceEngine::diff(const Function *L, const Function *R) {
956349cc55cSDimitry Andric   Context C(*this, L, R);
957349cc55cSDimitry Andric 
958349cc55cSDimitry Andric   // FIXME: types
959349cc55cSDimitry Andric   // FIXME: attributes and CC
960349cc55cSDimitry Andric   // FIXME: parameter attributes
961349cc55cSDimitry Andric 
962349cc55cSDimitry Andric   // If both are declarations, we're done.
963349cc55cSDimitry Andric   if (L->empty() && R->empty())
964349cc55cSDimitry Andric     return;
965349cc55cSDimitry Andric   else if (L->empty())
966349cc55cSDimitry Andric     log("left function is declaration, right function is definition");
967349cc55cSDimitry Andric   else if (R->empty())
968349cc55cSDimitry Andric     log("right function is declaration, left function is definition");
969349cc55cSDimitry Andric   else
970349cc55cSDimitry Andric     FunctionDifferenceEngine(*this).diff(L, R);
971349cc55cSDimitry Andric }
972349cc55cSDimitry Andric 
973349cc55cSDimitry Andric void DifferenceEngine::diff(const Module *L, const Module *R) {
974349cc55cSDimitry Andric   StringSet<> LNames;
975349cc55cSDimitry Andric   SmallVector<std::pair<const Function *, const Function *>, 20> Queue;
976349cc55cSDimitry Andric 
977349cc55cSDimitry Andric   unsigned LeftAnonCount = 0;
978349cc55cSDimitry Andric   unsigned RightAnonCount = 0;
979349cc55cSDimitry Andric 
980349cc55cSDimitry Andric   for (Module::const_iterator I = L->begin(), E = L->end(); I != E; ++I) {
981349cc55cSDimitry Andric     const Function *LFn = &*I;
982349cc55cSDimitry Andric     StringRef Name = LFn->getName();
983349cc55cSDimitry Andric     if (Name.empty()) {
984349cc55cSDimitry Andric       ++LeftAnonCount;
985349cc55cSDimitry Andric       continue;
986349cc55cSDimitry Andric     }
987349cc55cSDimitry Andric 
988349cc55cSDimitry Andric     LNames.insert(Name);
989349cc55cSDimitry Andric 
990349cc55cSDimitry Andric     if (Function *RFn = R->getFunction(LFn->getName()))
991349cc55cSDimitry Andric       Queue.push_back(std::make_pair(LFn, RFn));
992349cc55cSDimitry Andric     else
993349cc55cSDimitry Andric       logf("function %l exists only in left module") << LFn;
994349cc55cSDimitry Andric   }
995349cc55cSDimitry Andric 
996349cc55cSDimitry Andric   for (Module::const_iterator I = R->begin(), E = R->end(); I != E; ++I) {
997349cc55cSDimitry Andric     const Function *RFn = &*I;
998349cc55cSDimitry Andric     StringRef Name = RFn->getName();
999349cc55cSDimitry Andric     if (Name.empty()) {
1000349cc55cSDimitry Andric       ++RightAnonCount;
1001349cc55cSDimitry Andric       continue;
1002349cc55cSDimitry Andric     }
1003349cc55cSDimitry Andric 
1004349cc55cSDimitry Andric     if (!LNames.count(Name))
1005349cc55cSDimitry Andric       logf("function %r exists only in right module") << RFn;
1006349cc55cSDimitry Andric   }
1007349cc55cSDimitry Andric 
1008349cc55cSDimitry Andric   if (LeftAnonCount != 0 || RightAnonCount != 0) {
1009349cc55cSDimitry Andric     SmallString<32> Tmp;
1010349cc55cSDimitry Andric     logf(("not comparing " + Twine(LeftAnonCount) +
1011349cc55cSDimitry Andric           " anonymous functions in the left module and " +
1012349cc55cSDimitry Andric           Twine(RightAnonCount) + " in the right module")
1013349cc55cSDimitry Andric              .toStringRef(Tmp));
1014349cc55cSDimitry Andric   }
1015349cc55cSDimitry Andric 
1016349cc55cSDimitry Andric   for (SmallVectorImpl<std::pair<const Function *, const Function *>>::iterator
1017349cc55cSDimitry Andric            I = Queue.begin(),
1018349cc55cSDimitry Andric            E = Queue.end();
1019349cc55cSDimitry Andric        I != E; ++I)
1020349cc55cSDimitry Andric     diff(I->first, I->second);
1021349cc55cSDimitry Andric }
1022349cc55cSDimitry Andric 
1023349cc55cSDimitry Andric bool DifferenceEngine::equivalentAsOperands(const GlobalValue *L,
1024349cc55cSDimitry Andric                                             const GlobalValue *R) {
1025349cc55cSDimitry Andric   if (globalValueOracle) return (*globalValueOracle)(L, R);
1026349cc55cSDimitry Andric 
1027349cc55cSDimitry Andric   if (isa<GlobalVariable>(L) && isa<GlobalVariable>(R)) {
1028349cc55cSDimitry Andric     const GlobalVariable *GVL = cast<GlobalVariable>(L);
1029349cc55cSDimitry Andric     const GlobalVariable *GVR = cast<GlobalVariable>(R);
1030349cc55cSDimitry Andric     if (GVL->hasLocalLinkage() && GVL->hasUniqueInitializer() &&
1031349cc55cSDimitry Andric         GVR->hasLocalLinkage() && GVR->hasUniqueInitializer())
1032349cc55cSDimitry Andric       return FunctionDifferenceEngine(*this, GVL, GVR)
1033*bdd1243dSDimitry Andric           .equivalentAsOperands(GVL->getInitializer(), GVR->getInitializer(),
1034*bdd1243dSDimitry Andric                                 nullptr);
1035349cc55cSDimitry Andric   }
1036349cc55cSDimitry Andric 
1037349cc55cSDimitry Andric   return L->getName() == R->getName();
1038349cc55cSDimitry Andric }
1039