xref: /src/contrib/llvm-project/llvm/tools/llvm-diff/lib/DifferenceEngine.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1d39c594dSDimitry Andric //===-- DifferenceEngine.cpp - Structural function/module comparison ------===//
2d39c594dSDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6d39c594dSDimitry Andric //
7d39c594dSDimitry Andric //===----------------------------------------------------------------------===//
8d39c594dSDimitry Andric //
9d39c594dSDimitry Andric // This header defines the implementation of the LLVM difference
10d39c594dSDimitry Andric // engine, which structurally compares global values within a module.
11d39c594dSDimitry Andric //
12d39c594dSDimitry Andric //===----------------------------------------------------------------------===//
13d39c594dSDimitry Andric 
14d39c594dSDimitry Andric #include "DifferenceEngine.h"
15d39c594dSDimitry Andric #include "llvm/ADT/DenseMap.h"
16d39c594dSDimitry Andric #include "llvm/ADT/DenseSet.h"
17cfca06d7SDimitry Andric #include "llvm/ADT/SmallString.h"
18d39c594dSDimitry Andric #include "llvm/ADT/SmallVector.h"
19d39c594dSDimitry Andric #include "llvm/ADT/StringSet.h"
20e3b55780SDimitry Andric #include "llvm/IR/BasicBlock.h"
215ca98fd9SDimitry Andric #include "llvm/IR/CFG.h"
224a16efa3SDimitry Andric #include "llvm/IR/Constants.h"
234a16efa3SDimitry Andric #include "llvm/IR/Function.h"
244a16efa3SDimitry Andric #include "llvm/IR/Instructions.h"
254a16efa3SDimitry Andric #include "llvm/IR/Module.h"
26d39c594dSDimitry Andric #include "llvm/Support/ErrorHandling.h"
27d39c594dSDimitry Andric #include "llvm/Support/raw_ostream.h"
28d39c594dSDimitry Andric #include "llvm/Support/type_traits.h"
29d39c594dSDimitry Andric #include <utility>
30d39c594dSDimitry Andric 
31d39c594dSDimitry Andric using namespace llvm;
32d39c594dSDimitry Andric 
33d39c594dSDimitry Andric namespace {
34d39c594dSDimitry Andric 
35d39c594dSDimitry Andric /// A priority queue, implemented as a heap.
36d39c594dSDimitry Andric template <class T, class Sorter, unsigned InlineCapacity>
37d39c594dSDimitry Andric class PriorityQueue {
38d39c594dSDimitry Andric   Sorter Precedes;
39d39c594dSDimitry Andric   llvm::SmallVector<T, InlineCapacity> Storage;
40d39c594dSDimitry Andric 
41d39c594dSDimitry Andric public:
PriorityQueue(const Sorter & Precedes)42d39c594dSDimitry Andric   PriorityQueue(const Sorter &Precedes) : Precedes(Precedes) {}
43d39c594dSDimitry Andric 
44d39c594dSDimitry Andric   /// Checks whether the heap is empty.
empty() const45d39c594dSDimitry Andric   bool empty() const { return Storage.empty(); }
46d39c594dSDimitry Andric 
47d39c594dSDimitry Andric   /// Insert a new value on the heap.
insert(const T & V)48d39c594dSDimitry Andric   void insert(const T &V) {
49d39c594dSDimitry Andric     unsigned Index = Storage.size();
50d39c594dSDimitry Andric     Storage.push_back(V);
51d39c594dSDimitry Andric     if (Index == 0) return;
52d39c594dSDimitry Andric 
53d39c594dSDimitry Andric     T *data = Storage.data();
54d39c594dSDimitry Andric     while (true) {
55d39c594dSDimitry Andric       unsigned Target = (Index + 1) / 2 - 1;
56d39c594dSDimitry Andric       if (!Precedes(data[Index], data[Target])) return;
57d39c594dSDimitry Andric       std::swap(data[Index], data[Target]);
58d39c594dSDimitry Andric       if (Target == 0) return;
59d39c594dSDimitry Andric       Index = Target;
60d39c594dSDimitry Andric     }
61d39c594dSDimitry Andric   }
62d39c594dSDimitry Andric 
63d39c594dSDimitry Andric   /// Remove the minimum value in the heap.  Only valid on a non-empty heap.
remove_min()64d39c594dSDimitry Andric   T remove_min() {
65d39c594dSDimitry Andric     assert(!empty());
66d39c594dSDimitry Andric     T tmp = Storage[0];
67d39c594dSDimitry Andric 
68d39c594dSDimitry Andric     unsigned NewSize = Storage.size() - 1;
69d39c594dSDimitry Andric     if (NewSize) {
70d39c594dSDimitry Andric       // Move the slot at the end to the beginning.
71b60736ecSDimitry Andric       if (std::is_trivially_copyable<T>::value)
72d39c594dSDimitry Andric         Storage[0] = Storage[NewSize];
73d39c594dSDimitry Andric       else
74d39c594dSDimitry Andric         std::swap(Storage[0], Storage[NewSize]);
75d39c594dSDimitry Andric 
76d39c594dSDimitry Andric       // Bubble the root up as necessary.
77d39c594dSDimitry Andric       unsigned Index = 0;
78d39c594dSDimitry Andric       while (true) {
79d39c594dSDimitry Andric         // With a 1-based index, the children would be Index*2 and Index*2+1.
80d39c594dSDimitry Andric         unsigned R = (Index + 1) * 2;
81d39c594dSDimitry Andric         unsigned L = R - 1;
82d39c594dSDimitry Andric 
83d39c594dSDimitry Andric         // If R is out of bounds, we're done after this in any case.
84d39c594dSDimitry Andric         if (R >= NewSize) {
85d39c594dSDimitry Andric           // If L is also out of bounds, we're done immediately.
86d39c594dSDimitry Andric           if (L >= NewSize) break;
87d39c594dSDimitry Andric 
88d39c594dSDimitry Andric           // Otherwise, test whether we should swap L and Index.
89d39c594dSDimitry Andric           if (Precedes(Storage[L], Storage[Index]))
90d39c594dSDimitry Andric             std::swap(Storage[L], Storage[Index]);
91d39c594dSDimitry Andric           break;
92d39c594dSDimitry Andric         }
93d39c594dSDimitry Andric 
94d39c594dSDimitry Andric         // Otherwise, we need to compare with the smaller of L and R.
95d39c594dSDimitry Andric         // Prefer R because it's closer to the end of the array.
96d39c594dSDimitry Andric         unsigned IndexToTest = (Precedes(Storage[L], Storage[R]) ? L : R);
97d39c594dSDimitry Andric 
98d39c594dSDimitry Andric         // If Index is >= the min of L and R, then heap ordering is restored.
99d39c594dSDimitry Andric         if (!Precedes(Storage[IndexToTest], Storage[Index]))
100d39c594dSDimitry Andric           break;
101d39c594dSDimitry Andric 
102d39c594dSDimitry Andric         // Otherwise, keep bubbling up.
103d39c594dSDimitry Andric         std::swap(Storage[IndexToTest], Storage[Index]);
104d39c594dSDimitry Andric         Index = IndexToTest;
105d39c594dSDimitry Andric       }
106d39c594dSDimitry Andric     }
107d39c594dSDimitry Andric     Storage.pop_back();
108d39c594dSDimitry Andric 
109d39c594dSDimitry Andric     return tmp;
110d39c594dSDimitry Andric   }
111d39c594dSDimitry Andric };
112d39c594dSDimitry Andric 
113d39c594dSDimitry Andric /// A function-scope difference engine.
114d39c594dSDimitry Andric class FunctionDifferenceEngine {
115d39c594dSDimitry Andric   DifferenceEngine &Engine;
116d39c594dSDimitry Andric 
117344a3780SDimitry Andric   // Some initializers may reference the variable we're currently checking. This
118344a3780SDimitry Andric   // can cause an infinite loop. The Saved[LR]HS ivars can be checked to prevent
119344a3780SDimitry Andric   // recursing.
120344a3780SDimitry Andric   const Value *SavedLHS;
121344a3780SDimitry Andric   const Value *SavedRHS;
122344a3780SDimitry Andric 
123e3b55780SDimitry Andric   // The current mapping from old local values to new local values.
124344a3780SDimitry Andric   DenseMap<const Value *, const Value *> Values;
125d39c594dSDimitry Andric 
126e3b55780SDimitry Andric   // The current mapping from old blocks to new blocks.
127344a3780SDimitry Andric   DenseMap<const BasicBlock *, const BasicBlock *> Blocks;
128d39c594dSDimitry Andric 
129e3b55780SDimitry Andric   // The tentative mapping from old local values while comparing a pair of
130e3b55780SDimitry Andric   // basic blocks. Once the pair has been processed, the tentative mapping is
131e3b55780SDimitry Andric   // committed to the Values map.
132344a3780SDimitry Andric   DenseSet<std::pair<const Value *, const Value *>> TentativeValues;
133d39c594dSDimitry Andric 
134e3b55780SDimitry Andric   // Equivalence Assumptions
135e3b55780SDimitry Andric   //
136e3b55780SDimitry Andric   // For basic blocks in loops, some values in phi nodes may depend on
137e3b55780SDimitry Andric   // values from not yet processed basic blocks in the loop. When encountering
138e3b55780SDimitry Andric   // such values, we optimistically asssume their equivalence and store this
139e3b55780SDimitry Andric   // assumption in a BlockDiffCandidate for the pair of compared BBs.
140e3b55780SDimitry Andric   //
141e3b55780SDimitry Andric   // Once we have diffed all BBs, for every BlockDiffCandidate, we check all
142e3b55780SDimitry Andric   // stored assumptions using the Values map that stores proven equivalences
143e3b55780SDimitry Andric   // between the old and new values, and report a diff if an assumption cannot
144e3b55780SDimitry Andric   // be proven to be true.
145e3b55780SDimitry Andric   //
146e3b55780SDimitry Andric   // Note that after having made an assumption, all further determined
147e3b55780SDimitry Andric   // equivalences implicitly depend on that assumption. These will not be
148e3b55780SDimitry Andric   // reverted or reported if the assumption proves to be false, because these
149e3b55780SDimitry Andric   // are considered indirect diffs caused by earlier direct diffs.
150e3b55780SDimitry Andric   //
151e3b55780SDimitry Andric   // We aim to avoid false negatives in llvm-diff, that is, ensure that
152e3b55780SDimitry Andric   // whenever no diff is reported, the functions are indeed equal. If
153e3b55780SDimitry Andric   // assumptions were made, this is not entirely clear, because in principle we
154e3b55780SDimitry Andric   // could end up with a circular proof where the proof of equivalence of two
155e3b55780SDimitry Andric   // nodes is depending on the assumption of their equivalence.
156e3b55780SDimitry Andric   //
157e3b55780SDimitry Andric   // To see that assumptions do not add false negatives, note that if we do not
158e3b55780SDimitry Andric   // report a diff, this means that there is an equivalence mapping between old
159e3b55780SDimitry Andric   // and new values that is consistent with all assumptions made. The circular
160e3b55780SDimitry Andric   // dependency that exists on an IR value level does not exist at run time,
161e3b55780SDimitry Andric   // because the values selected by the phi nodes must always already have been
162e3b55780SDimitry Andric   // computed. Hence, we can prove equivalence of the old and new functions by
163e3b55780SDimitry Andric   // considering step-wise parallel execution, and incrementally proving
164e3b55780SDimitry Andric   // equivalence of every new computed value. Another way to think about it is
165e3b55780SDimitry Andric   // to imagine cloning the loop BBs for every iteration, turning the loops
166e3b55780SDimitry Andric   // into (possibly infinite) DAGs, and proving equivalence by induction on the
167e3b55780SDimitry Andric   // iteration, using the computed value mapping.
168e3b55780SDimitry Andric 
169e3b55780SDimitry Andric   // The class BlockDiffCandidate stores pairs which either have already been
170e3b55780SDimitry Andric   // proven to differ, or pairs whose equivalence depends on assumptions to be
171e3b55780SDimitry Andric   // verified later.
172e3b55780SDimitry Andric   struct BlockDiffCandidate {
173e3b55780SDimitry Andric     const BasicBlock *LBB;
174e3b55780SDimitry Andric     const BasicBlock *RBB;
175e3b55780SDimitry Andric     // Maps old values to assumed-to-be-equivalent new values
176e3b55780SDimitry Andric     SmallDenseMap<const Value *, const Value *> EquivalenceAssumptions;
177e3b55780SDimitry Andric     // If set, we already know the blocks differ.
178e3b55780SDimitry Andric     bool KnownToDiffer;
179e3b55780SDimitry Andric   };
180e3b55780SDimitry Andric 
181e3b55780SDimitry Andric   // List of block diff candidates in the order found by processing.
182e3b55780SDimitry Andric   // We generate reports in this order.
183e3b55780SDimitry Andric   // For every LBB, there may only be one corresponding RBB.
184e3b55780SDimitry Andric   SmallVector<BlockDiffCandidate> BlockDiffCandidates;
185e3b55780SDimitry Andric   // Maps LBB to the index of its BlockDiffCandidate, if existing.
186e3b55780SDimitry Andric   DenseMap<const BasicBlock *, uint64_t> BlockDiffCandidateIndices;
187e3b55780SDimitry Andric 
188e3b55780SDimitry Andric   // Note: Every LBB must always be queried together with the same RBB.
189e3b55780SDimitry Andric   // The returned reference is not permanently valid and should not be stored.
getOrCreateBlockDiffCandidate(const BasicBlock * LBB,const BasicBlock * RBB)190e3b55780SDimitry Andric   BlockDiffCandidate &getOrCreateBlockDiffCandidate(const BasicBlock *LBB,
191e3b55780SDimitry Andric                                                     const BasicBlock *RBB) {
192e3b55780SDimitry Andric     auto It = BlockDiffCandidateIndices.find(LBB);
193e3b55780SDimitry Andric     // Check if LBB already has a diff candidate
194e3b55780SDimitry Andric     if (It == BlockDiffCandidateIndices.end()) {
195e3b55780SDimitry Andric       // Add new one
196e3b55780SDimitry Andric       BlockDiffCandidateIndices[LBB] = BlockDiffCandidates.size();
197e3b55780SDimitry Andric       BlockDiffCandidates.push_back(
198e3b55780SDimitry Andric           {LBB, RBB, SmallDenseMap<const Value *, const Value *>(), false});
199e3b55780SDimitry Andric       return BlockDiffCandidates.back();
200e3b55780SDimitry Andric     }
201e3b55780SDimitry Andric     // Use existing one
202e3b55780SDimitry Andric     BlockDiffCandidate &Result = BlockDiffCandidates[It->second];
203e3b55780SDimitry Andric     assert(Result.RBB == RBB && "Inconsistent basic block pairing!");
204e3b55780SDimitry Andric     return Result;
205e3b55780SDimitry Andric   }
206e3b55780SDimitry Andric 
207e3b55780SDimitry Andric   // Optionally passed to equivalence checker functions, so these can add
208e3b55780SDimitry Andric   // assumptions in BlockDiffCandidates. Its presence controls whether
209e3b55780SDimitry Andric   // assumptions are generated.
210e3b55780SDimitry Andric   struct AssumptionContext {
211e3b55780SDimitry Andric     // The two basic blocks that need the two compared values to be equivalent.
212e3b55780SDimitry Andric     const BasicBlock *LBB;
213e3b55780SDimitry Andric     const BasicBlock *RBB;
214e3b55780SDimitry Andric   };
215e3b55780SDimitry Andric 
getUnprocPredCount(const BasicBlock * Block) const216344a3780SDimitry Andric   unsigned getUnprocPredCount(const BasicBlock *Block) const {
2174df029ccSDimitry Andric     return llvm::count_if(predecessors(Block), [&](const BasicBlock *Pred) {
2184df029ccSDimitry Andric       return !Blocks.contains(Pred);
2194df029ccSDimitry Andric     });
220d39c594dSDimitry Andric   }
221d39c594dSDimitry Andric 
222344a3780SDimitry Andric   typedef std::pair<const BasicBlock *, const BasicBlock *> BlockPair;
223d39c594dSDimitry Andric 
224d39c594dSDimitry Andric   /// A type which sorts a priority queue by the number of unprocessed
225d39c594dSDimitry Andric   /// predecessor blocks it has remaining.
226d39c594dSDimitry Andric   ///
227d39c594dSDimitry Andric   /// This is actually really expensive to calculate.
228d39c594dSDimitry Andric   struct QueueSorter {
229d39c594dSDimitry Andric     const FunctionDifferenceEngine &fde;
QueueSorter__anon14d914b60111::FunctionDifferenceEngine::QueueSorter230d39c594dSDimitry Andric     explicit QueueSorter(const FunctionDifferenceEngine &fde) : fde(fde) {}
231d39c594dSDimitry Andric 
operator ()__anon14d914b60111::FunctionDifferenceEngine::QueueSorter232344a3780SDimitry Andric     bool operator()(BlockPair &Old, BlockPair &New) {
233d39c594dSDimitry Andric       return fde.getUnprocPredCount(Old.first)
234d39c594dSDimitry Andric            < fde.getUnprocPredCount(New.first);
235d39c594dSDimitry Andric     }
236d39c594dSDimitry Andric   };
237d39c594dSDimitry Andric 
238d39c594dSDimitry Andric   /// A queue of unified blocks to process.
239d39c594dSDimitry Andric   PriorityQueue<BlockPair, QueueSorter, 20> Queue;
240d39c594dSDimitry Andric 
241d39c594dSDimitry Andric   /// Try to unify the given two blocks.  Enqueues them for processing
242d39c594dSDimitry Andric   /// if they haven't already been processed.
243d39c594dSDimitry Andric   ///
244d39c594dSDimitry Andric   /// Returns true if there was a problem unifying them.
tryUnify(const BasicBlock * L,const BasicBlock * R)245344a3780SDimitry Andric   bool tryUnify(const BasicBlock *L, const BasicBlock *R) {
246344a3780SDimitry Andric     const BasicBlock *&Ref = Blocks[L];
247d39c594dSDimitry Andric 
248d39c594dSDimitry Andric     if (Ref) {
249d39c594dSDimitry Andric       if (Ref == R) return false;
250d39c594dSDimitry Andric 
251d39c594dSDimitry Andric       Engine.logf("successor %l cannot be equivalent to %r; "
252d39c594dSDimitry Andric                   "it's already equivalent to %r")
253d39c594dSDimitry Andric         << L << R << Ref;
254d39c594dSDimitry Andric       return true;
255d39c594dSDimitry Andric     }
256d39c594dSDimitry Andric 
257d39c594dSDimitry Andric     Ref = R;
258d39c594dSDimitry Andric     Queue.insert(BlockPair(L, R));
259d39c594dSDimitry Andric     return false;
260d39c594dSDimitry Andric   }
261d39c594dSDimitry Andric 
262d39c594dSDimitry Andric   /// Unifies two instructions, given that they're known not to have
263d39c594dSDimitry Andric   /// structural differences.
unify(const Instruction * L,const Instruction * R)264344a3780SDimitry Andric   void unify(const Instruction *L, const Instruction *R) {
265d39c594dSDimitry Andric     DifferenceEngine::Context C(Engine, L, R);
266d39c594dSDimitry Andric 
267e3b55780SDimitry Andric     bool Result = diff(L, R, true, true, true);
268d39c594dSDimitry Andric     assert(!Result && "structural differences second time around?");
269d39c594dSDimitry Andric     (void) Result;
270d39c594dSDimitry Andric     if (!L->use_empty())
271d39c594dSDimitry Andric       Values[L] = R;
272d39c594dSDimitry Andric   }
273d39c594dSDimitry Andric 
processQueue()274d39c594dSDimitry Andric   void processQueue() {
275d39c594dSDimitry Andric     while (!Queue.empty()) {
276d39c594dSDimitry Andric       BlockPair Pair = Queue.remove_min();
277d39c594dSDimitry Andric       diff(Pair.first, Pair.second);
278d39c594dSDimitry Andric     }
279d39c594dSDimitry Andric   }
280d39c594dSDimitry Andric 
checkAndReportDiffCandidates()281e3b55780SDimitry Andric   void checkAndReportDiffCandidates() {
282e3b55780SDimitry Andric     for (BlockDiffCandidate &BDC : BlockDiffCandidates) {
283e3b55780SDimitry Andric 
284e3b55780SDimitry Andric       // Check assumptions
285e3b55780SDimitry Andric       for (const auto &[L, R] : BDC.EquivalenceAssumptions) {
286e3b55780SDimitry Andric         auto It = Values.find(L);
287e3b55780SDimitry Andric         if (It == Values.end() || It->second != R) {
288e3b55780SDimitry Andric           BDC.KnownToDiffer = true;
289e3b55780SDimitry Andric           break;
290e3b55780SDimitry Andric         }
291e3b55780SDimitry Andric       }
292e3b55780SDimitry Andric 
293e3b55780SDimitry Andric       // Run block diff if the BBs differ
294e3b55780SDimitry Andric       if (BDC.KnownToDiffer) {
295e3b55780SDimitry Andric         DifferenceEngine::Context C(Engine, BDC.LBB, BDC.RBB);
296e3b55780SDimitry Andric         runBlockDiff(BDC.LBB->begin(), BDC.RBB->begin());
297e3b55780SDimitry Andric       }
298e3b55780SDimitry Andric     }
299e3b55780SDimitry Andric   }
300e3b55780SDimitry Andric 
diff(const BasicBlock * L,const BasicBlock * R)301344a3780SDimitry Andric   void diff(const BasicBlock *L, const BasicBlock *R) {
302d39c594dSDimitry Andric     DifferenceEngine::Context C(Engine, L, R);
303d39c594dSDimitry Andric 
304344a3780SDimitry Andric     BasicBlock::const_iterator LI = L->begin(), LE = L->end();
305344a3780SDimitry Andric     BasicBlock::const_iterator RI = R->begin();
306d39c594dSDimitry Andric 
307d39c594dSDimitry Andric     do {
30830815c53SDimitry Andric       assert(LI != LE && RI != R->end());
309344a3780SDimitry Andric       const Instruction *LeftI = &*LI, *RightI = &*RI;
310d39c594dSDimitry Andric 
311d39c594dSDimitry Andric       // If the instructions differ, start the more sophisticated diff
312d39c594dSDimitry Andric       // algorithm at the start of the block.
313e3b55780SDimitry Andric       if (diff(LeftI, RightI, false, false, true)) {
314d39c594dSDimitry Andric         TentativeValues.clear();
315e3b55780SDimitry Andric         // Register (L, R) as diffing pair. Note that we could directly emit a
316e3b55780SDimitry Andric         // block diff here, but this way we ensure all diffs are emitted in one
317e3b55780SDimitry Andric         // consistent order, independent of whether the diffs were detected
318e3b55780SDimitry Andric         // immediately or via invalid assumptions.
319e3b55780SDimitry Andric         getOrCreateBlockDiffCandidate(L, R).KnownToDiffer = true;
320e3b55780SDimitry Andric         return;
321d39c594dSDimitry Andric       }
322d39c594dSDimitry Andric 
323d39c594dSDimitry Andric       // Otherwise, tentatively unify them.
324d39c594dSDimitry Andric       if (!LeftI->use_empty())
325d39c594dSDimitry Andric         TentativeValues.insert(std::make_pair(LeftI, RightI));
326d39c594dSDimitry Andric 
32701095a5dSDimitry Andric       ++LI;
32801095a5dSDimitry Andric       ++RI;
329d39c594dSDimitry Andric     } while (LI != LE); // This is sufficient: we can't get equality of
330d39c594dSDimitry Andric                         // terminators if there are residual instructions.
331d39c594dSDimitry Andric 
332d39c594dSDimitry Andric     // Unify everything in the block, non-tentatively this time.
333d39c594dSDimitry Andric     TentativeValues.clear();
334d39c594dSDimitry Andric     for (LI = L->begin(), RI = R->begin(); LI != LE; ++LI, ++RI)
335d39c594dSDimitry Andric       unify(&*LI, &*RI);
336d39c594dSDimitry Andric   }
337d39c594dSDimitry Andric 
338344a3780SDimitry Andric   bool matchForBlockDiff(const Instruction *L, const Instruction *R);
339344a3780SDimitry Andric   void runBlockDiff(BasicBlock::const_iterator LI,
340344a3780SDimitry Andric                     BasicBlock::const_iterator RI);
341d39c594dSDimitry Andric 
diffCallSites(const CallBase & L,const CallBase & R,bool Complain)342344a3780SDimitry Andric   bool diffCallSites(const CallBase &L, const CallBase &R, bool Complain) {
343d39c594dSDimitry Andric     // FIXME: call attributes
344e3b55780SDimitry Andric     AssumptionContext AC = {L.getParent(), R.getParent()};
345e3b55780SDimitry Andric     if (!equivalentAsOperands(L.getCalledOperand(), R.getCalledOperand(),
346e3b55780SDimitry Andric                               &AC)) {
347d39c594dSDimitry Andric       if (Complain) Engine.log("called functions differ");
348d39c594dSDimitry Andric       return true;
349d39c594dSDimitry Andric     }
350d39c594dSDimitry Andric     if (L.arg_size() != R.arg_size()) {
351d39c594dSDimitry Andric       if (Complain) Engine.log("argument counts differ");
352d39c594dSDimitry Andric       return true;
353d39c594dSDimitry Andric     }
354d39c594dSDimitry Andric     for (unsigned I = 0, E = L.arg_size(); I != E; ++I)
355e3b55780SDimitry Andric       if (!equivalentAsOperands(L.getArgOperand(I), R.getArgOperand(I), &AC)) {
356d39c594dSDimitry Andric         if (Complain)
357d39c594dSDimitry Andric           Engine.logf("arguments %l and %r differ")
358cfca06d7SDimitry Andric               << L.getArgOperand(I) << R.getArgOperand(I);
359d39c594dSDimitry Andric         return true;
360d39c594dSDimitry Andric       }
361d39c594dSDimitry Andric     return false;
362d39c594dSDimitry Andric   }
363d39c594dSDimitry Andric 
364e3b55780SDimitry Andric   // If AllowAssumptions is enabled, whenever we encounter a pair of values
365e3b55780SDimitry Andric   // that we cannot prove to be equivalent, we assume equivalence and store that
366e3b55780SDimitry Andric   // assumption to be checked later in BlockDiffCandidates.
diff(const Instruction * L,const Instruction * R,bool Complain,bool TryUnify,bool AllowAssumptions)367344a3780SDimitry Andric   bool diff(const Instruction *L, const Instruction *R, bool Complain,
368e3b55780SDimitry Andric             bool TryUnify, bool AllowAssumptions) {
369d39c594dSDimitry Andric     // FIXME: metadata (if Complain is set)
370e3b55780SDimitry Andric     AssumptionContext ACValue = {L->getParent(), R->getParent()};
371e3b55780SDimitry Andric     // nullptr AssumptionContext disables assumption generation.
372e3b55780SDimitry Andric     const AssumptionContext *AC = AllowAssumptions ? &ACValue : nullptr;
373d39c594dSDimitry Andric 
374d39c594dSDimitry Andric     // Different opcodes always imply different operations.
375d39c594dSDimitry Andric     if (L->getOpcode() != R->getOpcode()) {
376d39c594dSDimitry Andric       if (Complain) Engine.log("different instruction types");
377d39c594dSDimitry Andric       return true;
378d39c594dSDimitry Andric     }
379d39c594dSDimitry Andric 
380d39c594dSDimitry Andric     if (isa<CmpInst>(L)) {
381d39c594dSDimitry Andric       if (cast<CmpInst>(L)->getPredicate()
382d39c594dSDimitry Andric             != cast<CmpInst>(R)->getPredicate()) {
383d39c594dSDimitry Andric         if (Complain) Engine.log("different predicates");
384d39c594dSDimitry Andric         return true;
385d39c594dSDimitry Andric       }
386d39c594dSDimitry Andric     } else if (isa<CallInst>(L)) {
387cfca06d7SDimitry Andric       return diffCallSites(cast<CallInst>(*L), cast<CallInst>(*R), Complain);
388d39c594dSDimitry Andric     } else if (isa<PHINode>(L)) {
389f65dcba8SDimitry Andric       const PHINode &LI = cast<PHINode>(*L);
390f65dcba8SDimitry Andric       const PHINode &RI = cast<PHINode>(*R);
391d39c594dSDimitry Andric 
3926b943ff3SDimitry Andric       // This is really weird;  type uniquing is broken?
393f65dcba8SDimitry Andric       if (LI.getType() != RI.getType()) {
394f65dcba8SDimitry Andric         if (!LI.getType()->isPointerTy() || !RI.getType()->isPointerTy()) {
395d39c594dSDimitry Andric           if (Complain) Engine.log("different phi types");
396d39c594dSDimitry Andric           return true;
397d39c594dSDimitry Andric         }
398d39c594dSDimitry Andric       }
399f65dcba8SDimitry Andric 
400f65dcba8SDimitry Andric       if (LI.getNumIncomingValues() != RI.getNumIncomingValues()) {
401f65dcba8SDimitry Andric         if (Complain)
402f65dcba8SDimitry Andric           Engine.log("PHI node # of incoming values differ");
403f65dcba8SDimitry Andric         return true;
404f65dcba8SDimitry Andric       }
405f65dcba8SDimitry Andric 
406f65dcba8SDimitry Andric       for (unsigned I = 0; I < LI.getNumIncomingValues(); ++I) {
407f65dcba8SDimitry Andric         if (TryUnify)
408f65dcba8SDimitry Andric           tryUnify(LI.getIncomingBlock(I), RI.getIncomingBlock(I));
409f65dcba8SDimitry Andric 
410f65dcba8SDimitry Andric         if (!equivalentAsOperands(LI.getIncomingValue(I),
411e3b55780SDimitry Andric                                   RI.getIncomingValue(I), AC)) {
412f65dcba8SDimitry Andric           if (Complain)
413f65dcba8SDimitry Andric             Engine.log("PHI node incoming values differ");
414f65dcba8SDimitry Andric           return true;
415f65dcba8SDimitry Andric         }
416f65dcba8SDimitry Andric       }
417f65dcba8SDimitry Andric 
418d39c594dSDimitry Andric       return false;
419d39c594dSDimitry Andric 
420d39c594dSDimitry Andric     // Terminators.
421d39c594dSDimitry Andric     } else if (isa<InvokeInst>(L)) {
422344a3780SDimitry Andric       const InvokeInst &LI = cast<InvokeInst>(*L);
423344a3780SDimitry Andric       const InvokeInst &RI = cast<InvokeInst>(*R);
424cfca06d7SDimitry Andric       if (diffCallSites(LI, RI, Complain))
425d39c594dSDimitry Andric         return true;
426d39c594dSDimitry Andric 
427d39c594dSDimitry Andric       if (TryUnify) {
428cfca06d7SDimitry Andric         tryUnify(LI.getNormalDest(), RI.getNormalDest());
429cfca06d7SDimitry Andric         tryUnify(LI.getUnwindDest(), RI.getUnwindDest());
430d39c594dSDimitry Andric       }
431d39c594dSDimitry Andric       return false;
432d39c594dSDimitry Andric 
433344a3780SDimitry Andric     } else if (isa<CallBrInst>(L)) {
434344a3780SDimitry Andric       const CallBrInst &LI = cast<CallBrInst>(*L);
435344a3780SDimitry Andric       const CallBrInst &RI = cast<CallBrInst>(*R);
436344a3780SDimitry Andric       if (LI.getNumIndirectDests() != RI.getNumIndirectDests()) {
437344a3780SDimitry Andric         if (Complain)
438344a3780SDimitry Andric           Engine.log("callbr # of indirect destinations differ");
439344a3780SDimitry Andric         return true;
440344a3780SDimitry Andric       }
441344a3780SDimitry Andric 
442344a3780SDimitry Andric       // Perform the "try unify" step so that we can equate the indirect
443344a3780SDimitry Andric       // destinations before checking the call site.
444344a3780SDimitry Andric       for (unsigned I = 0; I < LI.getNumIndirectDests(); I++)
445344a3780SDimitry Andric         tryUnify(LI.getIndirectDest(I), RI.getIndirectDest(I));
446344a3780SDimitry Andric 
447344a3780SDimitry Andric       if (diffCallSites(LI, RI, Complain))
448344a3780SDimitry Andric         return true;
449344a3780SDimitry Andric 
450344a3780SDimitry Andric       if (TryUnify)
451344a3780SDimitry Andric         tryUnify(LI.getDefaultDest(), RI.getDefaultDest());
452344a3780SDimitry Andric       return false;
453344a3780SDimitry Andric 
454d39c594dSDimitry Andric     } else if (isa<BranchInst>(L)) {
455344a3780SDimitry Andric       const BranchInst *LI = cast<BranchInst>(L);
456344a3780SDimitry Andric       const BranchInst *RI = cast<BranchInst>(R);
457d39c594dSDimitry Andric       if (LI->isConditional() != RI->isConditional()) {
458d39c594dSDimitry Andric         if (Complain) Engine.log("branch conditionality differs");
459d39c594dSDimitry Andric         return true;
460d39c594dSDimitry Andric       }
461d39c594dSDimitry Andric 
462d39c594dSDimitry Andric       if (LI->isConditional()) {
463e3b55780SDimitry Andric         if (!equivalentAsOperands(LI->getCondition(), RI->getCondition(), AC)) {
464d39c594dSDimitry Andric           if (Complain) Engine.log("branch conditions differ");
465d39c594dSDimitry Andric           return true;
466d39c594dSDimitry Andric         }
467d39c594dSDimitry Andric         if (TryUnify) tryUnify(LI->getSuccessor(1), RI->getSuccessor(1));
468d39c594dSDimitry Andric       }
469d39c594dSDimitry Andric       if (TryUnify) tryUnify(LI->getSuccessor(0), RI->getSuccessor(0));
470d39c594dSDimitry Andric       return false;
471d39c594dSDimitry Andric 
472eb11fae6SDimitry Andric     } else if (isa<IndirectBrInst>(L)) {
473344a3780SDimitry Andric       const IndirectBrInst *LI = cast<IndirectBrInst>(L);
474344a3780SDimitry Andric       const IndirectBrInst *RI = cast<IndirectBrInst>(R);
475eb11fae6SDimitry Andric       if (LI->getNumDestinations() != RI->getNumDestinations()) {
476eb11fae6SDimitry Andric         if (Complain) Engine.log("indirectbr # of destinations differ");
477eb11fae6SDimitry Andric         return true;
478eb11fae6SDimitry Andric       }
479eb11fae6SDimitry Andric 
480e3b55780SDimitry Andric       if (!equivalentAsOperands(LI->getAddress(), RI->getAddress(), AC)) {
481eb11fae6SDimitry Andric         if (Complain) Engine.log("indirectbr addresses differ");
482eb11fae6SDimitry Andric         return true;
483eb11fae6SDimitry Andric       }
484eb11fae6SDimitry Andric 
485eb11fae6SDimitry Andric       if (TryUnify) {
486eb11fae6SDimitry Andric         for (unsigned i = 0; i < LI->getNumDestinations(); i++) {
487eb11fae6SDimitry Andric           tryUnify(LI->getDestination(i), RI->getDestination(i));
488eb11fae6SDimitry Andric         }
489eb11fae6SDimitry Andric       }
490eb11fae6SDimitry Andric       return false;
491eb11fae6SDimitry Andric 
492d39c594dSDimitry Andric     } else if (isa<SwitchInst>(L)) {
493344a3780SDimitry Andric       const SwitchInst *LI = cast<SwitchInst>(L);
494344a3780SDimitry Andric       const SwitchInst *RI = cast<SwitchInst>(R);
495e3b55780SDimitry Andric       if (!equivalentAsOperands(LI->getCondition(), RI->getCondition(), AC)) {
496d39c594dSDimitry Andric         if (Complain) Engine.log("switch conditions differ");
497d39c594dSDimitry Andric         return true;
498d39c594dSDimitry Andric       }
499d39c594dSDimitry Andric       if (TryUnify) tryUnify(LI->getDefaultDest(), RI->getDefaultDest());
500d39c594dSDimitry Andric 
501d39c594dSDimitry Andric       bool Difference = false;
502d39c594dSDimitry Andric 
503344a3780SDimitry Andric       DenseMap<const ConstantInt *, const BasicBlock *> LCases;
50471d5a254SDimitry Andric       for (auto Case : LI->cases())
50571d5a254SDimitry Andric         LCases[Case.getCaseValue()] = Case.getCaseSuccessor();
50663faed5bSDimitry Andric 
50771d5a254SDimitry Andric       for (auto Case : RI->cases()) {
508344a3780SDimitry Andric         const ConstantInt *CaseValue = Case.getCaseValue();
509344a3780SDimitry Andric         const BasicBlock *LCase = LCases[CaseValue];
510d39c594dSDimitry Andric         if (LCase) {
51171d5a254SDimitry Andric           if (TryUnify)
51271d5a254SDimitry Andric             tryUnify(LCase, Case.getCaseSuccessor());
513d39c594dSDimitry Andric           LCases.erase(CaseValue);
51463faed5bSDimitry Andric         } else if (Complain || !Difference) {
515d39c594dSDimitry Andric           if (Complain)
516d39c594dSDimitry Andric             Engine.logf("right switch has extra case %r") << CaseValue;
517d39c594dSDimitry Andric           Difference = true;
518d39c594dSDimitry Andric         }
519d39c594dSDimitry Andric       }
520d39c594dSDimitry Andric       if (!Difference)
521344a3780SDimitry Andric         for (DenseMap<const ConstantInt *, const BasicBlock *>::iterator
522344a3780SDimitry Andric                  I = LCases.begin(),
523344a3780SDimitry Andric                  E = LCases.end();
524344a3780SDimitry Andric              I != E; ++I) {
525d39c594dSDimitry Andric           if (Complain)
526d39c594dSDimitry Andric             Engine.logf("left switch has extra case %l") << I->first;
527d39c594dSDimitry Andric           Difference = true;
528d39c594dSDimitry Andric         }
529d39c594dSDimitry Andric       return Difference;
530d39c594dSDimitry Andric     } else if (isa<UnreachableInst>(L)) {
531d39c594dSDimitry Andric       return false;
532d39c594dSDimitry Andric     }
533d39c594dSDimitry Andric 
534d39c594dSDimitry Andric     if (L->getNumOperands() != R->getNumOperands()) {
535d39c594dSDimitry Andric       if (Complain) Engine.log("instructions have different operand counts");
536d39c594dSDimitry Andric       return true;
537d39c594dSDimitry Andric     }
538d39c594dSDimitry Andric 
539d39c594dSDimitry Andric     for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I) {
540d39c594dSDimitry Andric       Value *LO = L->getOperand(I), *RO = R->getOperand(I);
541e3b55780SDimitry Andric       if (!equivalentAsOperands(LO, RO, AC)) {
542d39c594dSDimitry Andric         if (Complain) Engine.logf("operands %l and %r differ") << LO << RO;
543d39c594dSDimitry Andric         return true;
544d39c594dSDimitry Andric       }
545d39c594dSDimitry Andric     }
546d39c594dSDimitry Andric 
547d39c594dSDimitry Andric     return false;
548d39c594dSDimitry Andric   }
549d39c594dSDimitry Andric 
550344a3780SDimitry Andric public:
equivalentAsOperands(const Constant * L,const Constant * R,const AssumptionContext * AC)551e3b55780SDimitry Andric   bool equivalentAsOperands(const Constant *L, const Constant *R,
552e3b55780SDimitry Andric                             const AssumptionContext *AC) {
553d39c594dSDimitry Andric     // Use equality as a preliminary filter.
554d39c594dSDimitry Andric     if (L == R)
555d39c594dSDimitry Andric       return true;
556d39c594dSDimitry Andric 
557d39c594dSDimitry Andric     if (L->getValueID() != R->getValueID())
558d39c594dSDimitry Andric       return false;
559d39c594dSDimitry Andric 
560d39c594dSDimitry Andric     // Ask the engine about global values.
561d39c594dSDimitry Andric     if (isa<GlobalValue>(L))
562d39c594dSDimitry Andric       return Engine.equivalentAsOperands(cast<GlobalValue>(L),
563d39c594dSDimitry Andric                                          cast<GlobalValue>(R));
564d39c594dSDimitry Andric 
565d39c594dSDimitry Andric     // Compare constant expressions structurally.
566d39c594dSDimitry Andric     if (isa<ConstantExpr>(L))
567e3b55780SDimitry Andric       return equivalentAsOperands(cast<ConstantExpr>(L), cast<ConstantExpr>(R),
568e3b55780SDimitry Andric                                   AC);
569d39c594dSDimitry Andric 
570eb11fae6SDimitry Andric     // Constants of the "same type" don't always actually have the same
571d39c594dSDimitry Andric     // type; I don't know why.  Just white-list them.
572eb11fae6SDimitry Andric     if (isa<ConstantPointerNull>(L) || isa<UndefValue>(L) || isa<ConstantAggregateZero>(L))
573d39c594dSDimitry Andric       return true;
574d39c594dSDimitry Andric 
575d39c594dSDimitry Andric     // Block addresses only match if we've already encountered the
576d39c594dSDimitry Andric     // block.  FIXME: tentative matches?
577d39c594dSDimitry Andric     if (isa<BlockAddress>(L))
578d39c594dSDimitry Andric       return Blocks[cast<BlockAddress>(L)->getBasicBlock()]
579d39c594dSDimitry Andric                  == cast<BlockAddress>(R)->getBasicBlock();
580d39c594dSDimitry Andric 
581eb11fae6SDimitry Andric     // If L and R are ConstantVectors, compare each element
582eb11fae6SDimitry Andric     if (isa<ConstantVector>(L)) {
583344a3780SDimitry Andric       const ConstantVector *CVL = cast<ConstantVector>(L);
584344a3780SDimitry Andric       const ConstantVector *CVR = cast<ConstantVector>(R);
585eb11fae6SDimitry Andric       if (CVL->getType()->getNumElements() != CVR->getType()->getNumElements())
586eb11fae6SDimitry Andric         return false;
587eb11fae6SDimitry Andric       for (unsigned i = 0; i < CVL->getType()->getNumElements(); i++) {
588e3b55780SDimitry Andric         if (!equivalentAsOperands(CVL->getOperand(i), CVR->getOperand(i), AC))
589eb11fae6SDimitry Andric           return false;
590eb11fae6SDimitry Andric       }
591eb11fae6SDimitry Andric       return true;
592eb11fae6SDimitry Andric     }
593eb11fae6SDimitry Andric 
594344a3780SDimitry Andric     // If L and R are ConstantArrays, compare the element count and types.
595344a3780SDimitry Andric     if (isa<ConstantArray>(L)) {
596344a3780SDimitry Andric       const ConstantArray *CAL = cast<ConstantArray>(L);
597344a3780SDimitry Andric       const ConstantArray *CAR = cast<ConstantArray>(R);
598344a3780SDimitry Andric       // Sometimes a type may be equivalent, but not uniquified---e.g. it may
599344a3780SDimitry Andric       // contain a GEP instruction. Do a deeper comparison of the types.
600344a3780SDimitry Andric       if (CAL->getType()->getNumElements() != CAR->getType()->getNumElements())
601344a3780SDimitry Andric         return false;
602344a3780SDimitry Andric 
603344a3780SDimitry Andric       for (unsigned I = 0; I < CAL->getType()->getNumElements(); ++I) {
604344a3780SDimitry Andric         if (!equivalentAsOperands(CAL->getAggregateElement(I),
605e3b55780SDimitry Andric                                   CAR->getAggregateElement(I), AC))
606d39c594dSDimitry Andric           return false;
607d39c594dSDimitry Andric       }
608d39c594dSDimitry Andric 
609344a3780SDimitry Andric       return true;
610344a3780SDimitry Andric     }
611344a3780SDimitry Andric 
612344a3780SDimitry Andric     // If L and R are ConstantStructs, compare each field and type.
613344a3780SDimitry Andric     if (isa<ConstantStruct>(L)) {
614344a3780SDimitry Andric       const ConstantStruct *CSL = cast<ConstantStruct>(L);
615344a3780SDimitry Andric       const ConstantStruct *CSR = cast<ConstantStruct>(R);
616344a3780SDimitry Andric 
617344a3780SDimitry Andric       const StructType *LTy = cast<StructType>(CSL->getType());
618344a3780SDimitry Andric       const StructType *RTy = cast<StructType>(CSR->getType());
619344a3780SDimitry Andric 
620344a3780SDimitry Andric       // The StructTypes should have the same attributes. Don't use
621344a3780SDimitry Andric       // isLayoutIdentical(), because that just checks the element pointers,
622344a3780SDimitry Andric       // which may not work here.
623344a3780SDimitry Andric       if (LTy->getNumElements() != RTy->getNumElements() ||
624344a3780SDimitry Andric           LTy->isPacked() != RTy->isPacked())
625344a3780SDimitry Andric         return false;
626344a3780SDimitry Andric 
627344a3780SDimitry Andric       for (unsigned I = 0; I < LTy->getNumElements(); I++) {
628344a3780SDimitry Andric         const Value *LAgg = CSL->getAggregateElement(I);
629344a3780SDimitry Andric         const Value *RAgg = CSR->getAggregateElement(I);
630344a3780SDimitry Andric 
631344a3780SDimitry Andric         if (LAgg == SavedLHS || RAgg == SavedRHS) {
632344a3780SDimitry Andric           if (LAgg != SavedLHS || RAgg != SavedRHS)
633344a3780SDimitry Andric             // If the left and right operands aren't both re-analyzing the
634344a3780SDimitry Andric             // variable, then the initialiers don't match, so report "false".
635344a3780SDimitry Andric             // Otherwise, we skip these operands..
636344a3780SDimitry Andric             return false;
637344a3780SDimitry Andric 
638344a3780SDimitry Andric           continue;
639344a3780SDimitry Andric         }
640344a3780SDimitry Andric 
641e3b55780SDimitry Andric         if (!equivalentAsOperands(LAgg, RAgg, AC)) {
642344a3780SDimitry Andric           return false;
643344a3780SDimitry Andric         }
644344a3780SDimitry Andric       }
645344a3780SDimitry Andric 
646344a3780SDimitry Andric       return true;
647344a3780SDimitry Andric     }
648344a3780SDimitry Andric 
649344a3780SDimitry Andric     return false;
650344a3780SDimitry Andric   }
651344a3780SDimitry Andric 
equivalentAsOperands(const ConstantExpr * L,const ConstantExpr * R,const AssumptionContext * AC)652e3b55780SDimitry Andric   bool equivalentAsOperands(const ConstantExpr *L, const ConstantExpr *R,
653e3b55780SDimitry Andric                             const AssumptionContext *AC) {
654d39c594dSDimitry Andric     if (L == R)
655d39c594dSDimitry Andric       return true;
656344a3780SDimitry Andric 
657d39c594dSDimitry Andric     if (L->getOpcode() != R->getOpcode())
658d39c594dSDimitry Andric       return false;
659d39c594dSDimitry Andric 
660d39c594dSDimitry Andric     switch (L->getOpcode()) {
661d39c594dSDimitry Andric     case Instruction::GetElementPtr:
662d39c594dSDimitry Andric       // FIXME: inbounds?
663d39c594dSDimitry Andric       break;
664d39c594dSDimitry Andric 
665d39c594dSDimitry Andric     default:
666d39c594dSDimitry Andric       break;
667d39c594dSDimitry Andric     }
668d39c594dSDimitry Andric 
669d39c594dSDimitry Andric     if (L->getNumOperands() != R->getNumOperands())
670d39c594dSDimitry Andric       return false;
671d39c594dSDimitry Andric 
672344a3780SDimitry Andric     for (unsigned I = 0, E = L->getNumOperands(); I != E; ++I) {
673344a3780SDimitry Andric       const auto *LOp = L->getOperand(I);
674344a3780SDimitry Andric       const auto *ROp = R->getOperand(I);
675344a3780SDimitry Andric 
676344a3780SDimitry Andric       if (LOp == SavedLHS || ROp == SavedRHS) {
677344a3780SDimitry Andric         if (LOp != SavedLHS || ROp != SavedRHS)
678344a3780SDimitry Andric           // If the left and right operands aren't both re-analyzing the
679344a3780SDimitry Andric           // variable, then the initialiers don't match, so report "false".
680344a3780SDimitry Andric           // Otherwise, we skip these operands..
681d39c594dSDimitry Andric           return false;
682d39c594dSDimitry Andric 
683344a3780SDimitry Andric         continue;
684344a3780SDimitry Andric       }
685344a3780SDimitry Andric 
686e3b55780SDimitry Andric       if (!equivalentAsOperands(LOp, ROp, AC))
687344a3780SDimitry Andric         return false;
688344a3780SDimitry Andric     }
689344a3780SDimitry Andric 
690d39c594dSDimitry Andric     return true;
691d39c594dSDimitry Andric   }
692d39c594dSDimitry Andric 
693e3b55780SDimitry Andric   // There are cases where we cannot determine whether two values are
694e3b55780SDimitry Andric   // equivalent, because it depends on not yet processed basic blocks -- see the
695e3b55780SDimitry Andric   // documentation on assumptions.
696e3b55780SDimitry Andric   //
697e3b55780SDimitry Andric   // AC is the context in which we are currently performing a diff.
698e3b55780SDimitry Andric   // When we encounter a pair of values for which we can neither prove
699e3b55780SDimitry Andric   // equivalence nor the opposite, we do the following:
700e3b55780SDimitry Andric   //  * If AC is nullptr, we treat the pair as non-equivalent.
701e3b55780SDimitry Andric   //  * If AC is set, we add an assumption for the basic blocks given by AC,
702e3b55780SDimitry Andric   //    and treat the pair as equivalent. The assumption is checked later.
equivalentAsOperands(const Value * L,const Value * R,const AssumptionContext * AC)703e3b55780SDimitry Andric   bool equivalentAsOperands(const Value *L, const Value *R,
704e3b55780SDimitry Andric                             const AssumptionContext *AC) {
705d39c594dSDimitry Andric     // Fall out if the values have different kind.
706d39c594dSDimitry Andric     // This possibly shouldn't take priority over oracles.
707d39c594dSDimitry Andric     if (L->getValueID() != R->getValueID())
708d39c594dSDimitry Andric       return false;
709d39c594dSDimitry Andric 
710d39c594dSDimitry Andric     // Value subtypes:  Argument, Constant, Instruction, BasicBlock,
711d39c594dSDimitry Andric     //                  InlineAsm, MDNode, MDString, PseudoSourceValue
712d39c594dSDimitry Andric 
713d39c594dSDimitry Andric     if (isa<Constant>(L))
714e3b55780SDimitry Andric       return equivalentAsOperands(cast<Constant>(L), cast<Constant>(R), AC);
715d39c594dSDimitry Andric 
716e3b55780SDimitry Andric     if (isa<Instruction>(L)) {
717e3b55780SDimitry Andric       auto It = Values.find(L);
718e3b55780SDimitry Andric       if (It != Values.end())
719e3b55780SDimitry Andric         return It->second == R;
720e3b55780SDimitry Andric 
721e3b55780SDimitry Andric       if (TentativeValues.count(std::make_pair(L, R)))
722e3b55780SDimitry Andric         return true;
723e3b55780SDimitry Andric 
724e3b55780SDimitry Andric       // L and R might be equivalent, this could depend on not yet processed
725e3b55780SDimitry Andric       // basic blocks, so we cannot decide here.
726e3b55780SDimitry Andric       if (AC) {
727e3b55780SDimitry Andric         // Add an assumption, unless there is a conflict with an existing one
728e3b55780SDimitry Andric         BlockDiffCandidate &BDC =
729e3b55780SDimitry Andric             getOrCreateBlockDiffCandidate(AC->LBB, AC->RBB);
730e3b55780SDimitry Andric         auto InsertionResult = BDC.EquivalenceAssumptions.insert({L, R});
731e3b55780SDimitry Andric         if (!InsertionResult.second && InsertionResult.first->second != R) {
732e3b55780SDimitry Andric           // We already have a conflicting equivalence assumption for L, so at
733e3b55780SDimitry Andric           // least one must be wrong, and we know that there is a diff.
734e3b55780SDimitry Andric           BDC.KnownToDiffer = true;
735e3b55780SDimitry Andric           BDC.EquivalenceAssumptions.clear();
736e3b55780SDimitry Andric           return false;
737e3b55780SDimitry Andric         }
738e3b55780SDimitry Andric         // Optimistically assume equivalence, and check later once all BBs
739e3b55780SDimitry Andric         // have been processed.
740e3b55780SDimitry Andric         return true;
741e3b55780SDimitry Andric       }
742e3b55780SDimitry Andric 
743e3b55780SDimitry Andric       // Assumptions disabled, so pessimistically assume non-equivalence.
744e3b55780SDimitry Andric       return false;
745e3b55780SDimitry Andric     }
746d39c594dSDimitry Andric 
747d39c594dSDimitry Andric     if (isa<Argument>(L))
748d39c594dSDimitry Andric       return Values[L] == R;
749d39c594dSDimitry Andric 
750d39c594dSDimitry Andric     if (isa<BasicBlock>(L))
751d39c594dSDimitry Andric       return Blocks[cast<BasicBlock>(L)] != R;
752d39c594dSDimitry Andric 
753d39c594dSDimitry Andric     // Pretend everything else is identical.
754d39c594dSDimitry Andric     return true;
755d39c594dSDimitry Andric   }
756d39c594dSDimitry Andric 
757d39c594dSDimitry Andric   // Avoid a gcc warning about accessing 'this' in an initializer.
this_()758d39c594dSDimitry Andric   FunctionDifferenceEngine *this_() { return this; }
759d39c594dSDimitry Andric 
760d39c594dSDimitry Andric public:
FunctionDifferenceEngine(DifferenceEngine & Engine,const Value * SavedLHS=nullptr,const Value * SavedRHS=nullptr)761344a3780SDimitry Andric   FunctionDifferenceEngine(DifferenceEngine &Engine,
762344a3780SDimitry Andric                            const Value *SavedLHS = nullptr,
763344a3780SDimitry Andric                            const Value *SavedRHS = nullptr)
764344a3780SDimitry Andric       : Engine(Engine), SavedLHS(SavedLHS), SavedRHS(SavedRHS),
765344a3780SDimitry Andric         Queue(QueueSorter(*this_())) {}
766d39c594dSDimitry Andric 
diff(const Function * L,const Function * R)767344a3780SDimitry Andric   void diff(const Function *L, const Function *R) {
768e3b55780SDimitry Andric     assert(Values.empty() && "Multiple diffs per engine are not supported!");
769e3b55780SDimitry Andric 
770d39c594dSDimitry Andric     if (L->arg_size() != R->arg_size())
771d39c594dSDimitry Andric       Engine.log("different argument counts");
772d39c594dSDimitry Andric 
773d39c594dSDimitry Andric     // Map the arguments.
774344a3780SDimitry Andric     for (Function::const_arg_iterator LI = L->arg_begin(), LE = L->arg_end(),
775d39c594dSDimitry Andric                                       RI = R->arg_begin(), RE = R->arg_end();
776d39c594dSDimitry Andric          LI != LE && RI != RE; ++LI, ++RI)
777d39c594dSDimitry Andric       Values[&*LI] = &*RI;
778d39c594dSDimitry Andric 
779d39c594dSDimitry Andric     tryUnify(&*L->begin(), &*R->begin());
780d39c594dSDimitry Andric     processQueue();
781e3b55780SDimitry Andric     checkAndReportDiffCandidates();
782d39c594dSDimitry Andric   }
783d39c594dSDimitry Andric };
784d39c594dSDimitry Andric 
785d39c594dSDimitry Andric struct DiffEntry {
786b1c73532SDimitry Andric   DiffEntry() = default;
787d39c594dSDimitry Andric 
788b1c73532SDimitry Andric   unsigned Cost = 0;
789d39c594dSDimitry Andric   llvm::SmallVector<char, 8> Path; // actually of DifferenceEngine::DiffChange
790d39c594dSDimitry Andric };
791d39c594dSDimitry Andric 
matchForBlockDiff(const Instruction * L,const Instruction * R)792344a3780SDimitry Andric bool FunctionDifferenceEngine::matchForBlockDiff(const Instruction *L,
793344a3780SDimitry Andric                                                  const Instruction *R) {
794e3b55780SDimitry Andric   return !diff(L, R, false, false, false);
795d39c594dSDimitry Andric }
796d39c594dSDimitry Andric 
runBlockDiff(BasicBlock::const_iterator LStart,BasicBlock::const_iterator RStart)797344a3780SDimitry Andric void FunctionDifferenceEngine::runBlockDiff(BasicBlock::const_iterator LStart,
798344a3780SDimitry Andric                                             BasicBlock::const_iterator RStart) {
799344a3780SDimitry Andric   BasicBlock::const_iterator LE = LStart->getParent()->end();
800344a3780SDimitry Andric   BasicBlock::const_iterator RE = RStart->getParent()->end();
801d39c594dSDimitry Andric 
802d39c594dSDimitry Andric   unsigned NL = std::distance(LStart, LE);
803d39c594dSDimitry Andric 
804d39c594dSDimitry Andric   SmallVector<DiffEntry, 20> Paths1(NL+1);
805d39c594dSDimitry Andric   SmallVector<DiffEntry, 20> Paths2(NL+1);
806d39c594dSDimitry Andric 
807d39c594dSDimitry Andric   DiffEntry *Cur = Paths1.data();
808d39c594dSDimitry Andric   DiffEntry *Next = Paths2.data();
809d39c594dSDimitry Andric 
810d39c594dSDimitry Andric   const unsigned LeftCost = 2;
811d39c594dSDimitry Andric   const unsigned RightCost = 2;
812d39c594dSDimitry Andric   const unsigned MatchCost = 0;
813d39c594dSDimitry Andric 
814d39c594dSDimitry Andric   assert(TentativeValues.empty());
815d39c594dSDimitry Andric 
816d39c594dSDimitry Andric   // Initialize the first column.
817d39c594dSDimitry Andric   for (unsigned I = 0; I != NL+1; ++I) {
818d39c594dSDimitry Andric     Cur[I].Cost = I * LeftCost;
819d39c594dSDimitry Andric     for (unsigned J = 0; J != I; ++J)
8206b943ff3SDimitry Andric       Cur[I].Path.push_back(DC_left);
821d39c594dSDimitry Andric   }
822d39c594dSDimitry Andric 
823344a3780SDimitry Andric   for (BasicBlock::const_iterator RI = RStart; RI != RE; ++RI) {
824d39c594dSDimitry Andric     // Initialize the first row.
825d39c594dSDimitry Andric     Next[0] = Cur[0];
826d39c594dSDimitry Andric     Next[0].Cost += RightCost;
8276b943ff3SDimitry Andric     Next[0].Path.push_back(DC_right);
828d39c594dSDimitry Andric 
829d39c594dSDimitry Andric     unsigned Index = 1;
830344a3780SDimitry Andric     for (BasicBlock::const_iterator LI = LStart; LI != LE; ++LI, ++Index) {
831d39c594dSDimitry Andric       if (matchForBlockDiff(&*LI, &*RI)) {
832d39c594dSDimitry Andric         Next[Index] = Cur[Index-1];
833d39c594dSDimitry Andric         Next[Index].Cost += MatchCost;
8346b943ff3SDimitry Andric         Next[Index].Path.push_back(DC_match);
835d39c594dSDimitry Andric         TentativeValues.insert(std::make_pair(&*LI, &*RI));
836d39c594dSDimitry Andric       } else if (Next[Index-1].Cost <= Cur[Index].Cost) {
837d39c594dSDimitry Andric         Next[Index] = Next[Index-1];
838d39c594dSDimitry Andric         Next[Index].Cost += LeftCost;
8396b943ff3SDimitry Andric         Next[Index].Path.push_back(DC_left);
840d39c594dSDimitry Andric       } else {
841d39c594dSDimitry Andric         Next[Index] = Cur[Index];
842d39c594dSDimitry Andric         Next[Index].Cost += RightCost;
8436b943ff3SDimitry Andric         Next[Index].Path.push_back(DC_right);
844d39c594dSDimitry Andric       }
845d39c594dSDimitry Andric     }
846d39c594dSDimitry Andric 
847d39c594dSDimitry Andric     std::swap(Cur, Next);
848d39c594dSDimitry Andric   }
849d39c594dSDimitry Andric 
850d39c594dSDimitry Andric   // We don't need the tentative values anymore; everything from here
851d39c594dSDimitry Andric   // on out should be non-tentative.
852d39c594dSDimitry Andric   TentativeValues.clear();
853d39c594dSDimitry Andric 
854d39c594dSDimitry Andric   SmallVectorImpl<char> &Path = Cur[NL].Path;
855344a3780SDimitry Andric   BasicBlock::const_iterator LI = LStart, RI = RStart;
856d39c594dSDimitry Andric 
8576b943ff3SDimitry Andric   DiffLogBuilder Diff(Engine.getConsumer());
858d39c594dSDimitry Andric 
859d39c594dSDimitry Andric   // Drop trailing matches.
860cfca06d7SDimitry Andric   while (Path.size() && Path.back() == DC_match)
861d39c594dSDimitry Andric     Path.pop_back();
862d39c594dSDimitry Andric 
863d39c594dSDimitry Andric   // Skip leading matches.
864d39c594dSDimitry Andric   SmallVectorImpl<char>::iterator
865d39c594dSDimitry Andric     PI = Path.begin(), PE = Path.end();
8666b943ff3SDimitry Andric   while (PI != PE && *PI == DC_match) {
867d39c594dSDimitry Andric     unify(&*LI, &*RI);
86801095a5dSDimitry Andric     ++PI;
86901095a5dSDimitry Andric     ++LI;
87001095a5dSDimitry Andric     ++RI;
871d39c594dSDimitry Andric   }
872d39c594dSDimitry Andric 
873d39c594dSDimitry Andric   for (; PI != PE; ++PI) {
8746b943ff3SDimitry Andric     switch (static_cast<DiffChange>(*PI)) {
8756b943ff3SDimitry Andric     case DC_match:
876d39c594dSDimitry Andric       assert(LI != LE && RI != RE);
877d39c594dSDimitry Andric       {
878344a3780SDimitry Andric         const Instruction *L = &*LI, *R = &*RI;
879d39c594dSDimitry Andric         unify(L, R);
880d39c594dSDimitry Andric         Diff.addMatch(L, R);
881d39c594dSDimitry Andric       }
882d39c594dSDimitry Andric       ++LI; ++RI;
883d39c594dSDimitry Andric       break;
884d39c594dSDimitry Andric 
8856b943ff3SDimitry Andric     case DC_left:
886d39c594dSDimitry Andric       assert(LI != LE);
887d39c594dSDimitry Andric       Diff.addLeft(&*LI);
888d39c594dSDimitry Andric       ++LI;
889d39c594dSDimitry Andric       break;
890d39c594dSDimitry Andric 
8916b943ff3SDimitry Andric     case DC_right:
892d39c594dSDimitry Andric       assert(RI != RE);
893d39c594dSDimitry Andric       Diff.addRight(&*RI);
894d39c594dSDimitry Andric       ++RI;
895d39c594dSDimitry Andric       break;
896d39c594dSDimitry Andric     }
897d39c594dSDimitry Andric   }
898d39c594dSDimitry Andric 
899d39c594dSDimitry Andric   // Finishing unifying and complaining about the tails of the block,
900d39c594dSDimitry Andric   // which should be matches all the way through.
901d39c594dSDimitry Andric   while (LI != LE) {
902d39c594dSDimitry Andric     assert(RI != RE);
903d39c594dSDimitry Andric     unify(&*LI, &*RI);
90401095a5dSDimitry Andric     ++LI;
90501095a5dSDimitry Andric     ++RI;
906d39c594dSDimitry Andric   }
907d39c594dSDimitry Andric 
908d39c594dSDimitry Andric   // If the terminators have different kinds, but one is an invoke and the
909d39c594dSDimitry Andric   // other is an unconditional branch immediately following a call, unify
910d39c594dSDimitry Andric   // the results and the destinations.
911344a3780SDimitry Andric   const Instruction *LTerm = LStart->getParent()->getTerminator();
912344a3780SDimitry Andric   const Instruction *RTerm = RStart->getParent()->getTerminator();
913d39c594dSDimitry Andric   if (isa<BranchInst>(LTerm) && isa<InvokeInst>(RTerm)) {
914d39c594dSDimitry Andric     if (cast<BranchInst>(LTerm)->isConditional()) return;
915344a3780SDimitry Andric     BasicBlock::const_iterator I = LTerm->getIterator();
916d39c594dSDimitry Andric     if (I == LStart->getParent()->begin()) return;
917d39c594dSDimitry Andric     --I;
918d39c594dSDimitry Andric     if (!isa<CallInst>(*I)) return;
919344a3780SDimitry Andric     const CallInst *LCall = cast<CallInst>(&*I);
920344a3780SDimitry Andric     const InvokeInst *RInvoke = cast<InvokeInst>(RTerm);
921cfca06d7SDimitry Andric     if (!equivalentAsOperands(LCall->getCalledOperand(),
922e3b55780SDimitry Andric                               RInvoke->getCalledOperand(), nullptr))
923d39c594dSDimitry Andric       return;
924d39c594dSDimitry Andric     if (!LCall->use_empty())
925d39c594dSDimitry Andric       Values[LCall] = RInvoke;
926d39c594dSDimitry Andric     tryUnify(LTerm->getSuccessor(0), RInvoke->getNormalDest());
927d39c594dSDimitry Andric   } else if (isa<InvokeInst>(LTerm) && isa<BranchInst>(RTerm)) {
928d39c594dSDimitry Andric     if (cast<BranchInst>(RTerm)->isConditional()) return;
929344a3780SDimitry Andric     BasicBlock::const_iterator I = RTerm->getIterator();
930d39c594dSDimitry Andric     if (I == RStart->getParent()->begin()) return;
931d39c594dSDimitry Andric     --I;
932d39c594dSDimitry Andric     if (!isa<CallInst>(*I)) return;
933344a3780SDimitry Andric     const CallInst *RCall = cast<CallInst>(I);
934344a3780SDimitry Andric     const InvokeInst *LInvoke = cast<InvokeInst>(LTerm);
935cfca06d7SDimitry Andric     if (!equivalentAsOperands(LInvoke->getCalledOperand(),
936e3b55780SDimitry Andric                               RCall->getCalledOperand(), nullptr))
937d39c594dSDimitry Andric       return;
938d39c594dSDimitry Andric     if (!LInvoke->use_empty())
939d39c594dSDimitry Andric       Values[LInvoke] = RCall;
940d39c594dSDimitry Andric     tryUnify(LInvoke->getNormalDest(), RTerm->getSuccessor(0));
941d39c594dSDimitry Andric   }
942d39c594dSDimitry Andric }
943d39c594dSDimitry Andric }
944d39c594dSDimitry Andric 
anchor()94563faed5bSDimitry Andric void DifferenceEngine::Oracle::anchor() { }
94663faed5bSDimitry Andric 
diff(const Function * L,const Function * R)947344a3780SDimitry Andric void DifferenceEngine::diff(const Function *L, const Function *R) {
948d39c594dSDimitry Andric   Context C(*this, L, R);
949d39c594dSDimitry Andric 
950d39c594dSDimitry Andric   // FIXME: types
951d39c594dSDimitry Andric   // FIXME: attributes and CC
952d39c594dSDimitry Andric   // FIXME: parameter attributes
953d39c594dSDimitry Andric 
954d39c594dSDimitry Andric   // If both are declarations, we're done.
955d39c594dSDimitry Andric   if (L->empty() && R->empty())
956d39c594dSDimitry Andric     return;
957d39c594dSDimitry Andric   else if (L->empty())
958d39c594dSDimitry Andric     log("left function is declaration, right function is definition");
959d39c594dSDimitry Andric   else if (R->empty())
960d39c594dSDimitry Andric     log("right function is declaration, left function is definition");
961d39c594dSDimitry Andric   else
962d39c594dSDimitry Andric     FunctionDifferenceEngine(*this).diff(L, R);
963d39c594dSDimitry Andric }
964d39c594dSDimitry Andric 
diff(const Module * L,const Module * R)965344a3780SDimitry Andric void DifferenceEngine::diff(const Module *L, const Module *R) {
966d39c594dSDimitry Andric   StringSet<> LNames;
967344a3780SDimitry Andric   SmallVector<std::pair<const Function *, const Function *>, 20> Queue;
968d39c594dSDimitry Andric 
969d8e91e46SDimitry Andric   unsigned LeftAnonCount = 0;
970d8e91e46SDimitry Andric   unsigned RightAnonCount = 0;
971d8e91e46SDimitry Andric 
972344a3780SDimitry Andric   for (Module::const_iterator I = L->begin(), E = L->end(); I != E; ++I) {
973344a3780SDimitry Andric     const Function *LFn = &*I;
974d8e91e46SDimitry Andric     StringRef Name = LFn->getName();
975d8e91e46SDimitry Andric     if (Name.empty()) {
976d8e91e46SDimitry Andric       ++LeftAnonCount;
977d8e91e46SDimitry Andric       continue;
978d8e91e46SDimitry Andric     }
979d8e91e46SDimitry Andric 
980d8e91e46SDimitry Andric     LNames.insert(Name);
981d39c594dSDimitry Andric 
982d39c594dSDimitry Andric     if (Function *RFn = R->getFunction(LFn->getName()))
983d39c594dSDimitry Andric       Queue.push_back(std::make_pair(LFn, RFn));
984d39c594dSDimitry Andric     else
985d39c594dSDimitry Andric       logf("function %l exists only in left module") << LFn;
986d39c594dSDimitry Andric   }
987d39c594dSDimitry Andric 
988344a3780SDimitry Andric   for (Module::const_iterator I = R->begin(), E = R->end(); I != E; ++I) {
989344a3780SDimitry Andric     const Function *RFn = &*I;
990d8e91e46SDimitry Andric     StringRef Name = RFn->getName();
991d8e91e46SDimitry Andric     if (Name.empty()) {
992d8e91e46SDimitry Andric       ++RightAnonCount;
993d8e91e46SDimitry Andric       continue;
994d8e91e46SDimitry Andric     }
995d8e91e46SDimitry Andric 
996d8e91e46SDimitry Andric     if (!LNames.count(Name))
997d39c594dSDimitry Andric       logf("function %r exists only in right module") << RFn;
998d39c594dSDimitry Andric   }
999d39c594dSDimitry Andric 
1000d8e91e46SDimitry Andric   if (LeftAnonCount != 0 || RightAnonCount != 0) {
1001d8e91e46SDimitry Andric     SmallString<32> Tmp;
1002d8e91e46SDimitry Andric     logf(("not comparing " + Twine(LeftAnonCount) +
1003d8e91e46SDimitry Andric           " anonymous functions in the left module and " +
1004d8e91e46SDimitry Andric           Twine(RightAnonCount) + " in the right module")
1005d8e91e46SDimitry Andric              .toStringRef(Tmp));
1006d8e91e46SDimitry Andric   }
1007d8e91e46SDimitry Andric 
1008344a3780SDimitry Andric   for (SmallVectorImpl<std::pair<const Function *, const Function *>>::iterator
1009344a3780SDimitry Andric            I = Queue.begin(),
1010344a3780SDimitry Andric            E = Queue.end();
1011344a3780SDimitry Andric        I != E; ++I)
1012d39c594dSDimitry Andric     diff(I->first, I->second);
1013d39c594dSDimitry Andric }
1014d39c594dSDimitry Andric 
equivalentAsOperands(const GlobalValue * L,const GlobalValue * R)1015344a3780SDimitry Andric bool DifferenceEngine::equivalentAsOperands(const GlobalValue *L,
1016344a3780SDimitry Andric                                             const GlobalValue *R) {
1017d39c594dSDimitry Andric   if (globalValueOracle) return (*globalValueOracle)(L, R);
1018706b4fc4SDimitry Andric 
1019706b4fc4SDimitry Andric   if (isa<GlobalVariable>(L) && isa<GlobalVariable>(R)) {
1020344a3780SDimitry Andric     const GlobalVariable *GVL = cast<GlobalVariable>(L);
1021344a3780SDimitry Andric     const GlobalVariable *GVR = cast<GlobalVariable>(R);
1022706b4fc4SDimitry Andric     if (GVL->hasLocalLinkage() && GVL->hasUniqueInitializer() &&
1023706b4fc4SDimitry Andric         GVR->hasLocalLinkage() && GVR->hasUniqueInitializer())
1024344a3780SDimitry Andric       return FunctionDifferenceEngine(*this, GVL, GVR)
1025e3b55780SDimitry Andric           .equivalentAsOperands(GVL->getInitializer(), GVR->getInitializer(),
1026e3b55780SDimitry Andric                                 nullptr);
1027706b4fc4SDimitry Andric   }
1028706b4fc4SDimitry Andric 
1029d39c594dSDimitry Andric   return L->getName() == R->getName();
1030d39c594dSDimitry Andric }
1031