Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:44:43

0001 //===- FunctionComparator.h - Function Comparator ---------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 //
0009 // This file defines the FunctionComparator and GlobalNumberState classes which
0010 // are used by the MergeFunctions pass for comparing functions.
0011 //
0012 //===----------------------------------------------------------------------===//
0013 
0014 #ifndef LLVM_TRANSFORMS_UTILS_FUNCTIONCOMPARATOR_H
0015 #define LLVM_TRANSFORMS_UTILS_FUNCTIONCOMPARATOR_H
0016 
0017 #include "llvm/ADT/DenseMap.h"
0018 #include "llvm/ADT/StringRef.h"
0019 #include "llvm/IR/Instructions.h"
0020 #include "llvm/IR/Operator.h"
0021 #include "llvm/IR/ValueMap.h"
0022 #include "llvm/Support/AtomicOrdering.h"
0023 #include "llvm/Support/Casting.h"
0024 #include <cstdint>
0025 #include <tuple>
0026 
0027 namespace llvm {
0028 
0029 class APFloat;
0030 class AttributeList;
0031 class APInt;
0032 class BasicBlock;
0033 class Constant;
0034 class Function;
0035 class GlobalValue;
0036 class InlineAsm;
0037 class Instruction;
0038 class MDNode;
0039 class Type;
0040 class Value;
0041 
0042 /// GlobalNumberState assigns an integer to each global value in the program,
0043 /// which is used by the comparison routine to order references to globals. This
0044 /// state must be preserved throughout the pass, because Functions and other
0045 /// globals need to maintain their relative order. Globals are assigned a number
0046 /// when they are first visited. This order is deterministic, and so the
0047 /// assigned numbers are as well. When two functions are merged, neither number
0048 /// is updated. If the symbols are weak, this would be incorrect. If they are
0049 /// strong, then one will be replaced at all references to the other, and so
0050 /// direct callsites will now see one or the other symbol, and no update is
0051 /// necessary. Note that if we were guaranteed unique names, we could just
0052 /// compare those, but this would not work for stripped bitcodes or for those
0053 /// few symbols without a name.
0054 class GlobalNumberState {
0055   struct Config : ValueMapConfig<GlobalValue *> {
0056     enum { FollowRAUW = false };
0057   };
0058 
0059   // Each GlobalValue is mapped to an identifier. The Config ensures when RAUW
0060   // occurs, the mapping does not change. Tracking changes is unnecessary, and
0061   // also problematic for weak symbols (which may be overwritten).
0062   using ValueNumberMap = ValueMap<GlobalValue *, uint64_t, Config>;
0063   ValueNumberMap GlobalNumbers;
0064 
0065   // The next unused serial number to assign to a global.
0066   uint64_t NextNumber = 0;
0067 
0068 public:
0069   GlobalNumberState() = default;
0070 
0071   uint64_t getNumber(GlobalValue* Global) {
0072     ValueNumberMap::iterator MapIter;
0073     bool Inserted;
0074     std::tie(MapIter, Inserted) = GlobalNumbers.insert({Global, NextNumber});
0075     if (Inserted)
0076       NextNumber++;
0077     return MapIter->second;
0078   }
0079 
0080   void erase(GlobalValue *Global) {
0081     GlobalNumbers.erase(Global);
0082   }
0083 
0084   void clear() {
0085     GlobalNumbers.clear();
0086   }
0087 };
0088 
0089 /// FunctionComparator - Compares two functions to determine whether or not
0090 /// they will generate machine code with the same behaviour. DataLayout is
0091 /// used if available. The comparator always fails conservatively (erring on the
0092 /// side of claiming that two functions are different).
0093 class FunctionComparator {
0094 public:
0095   FunctionComparator(const Function *F1, const Function *F2,
0096                      GlobalNumberState* GN)
0097       : FnL(F1), FnR(F2), GlobalNumbers(GN) {}
0098 
0099   /// Test whether the two functions have equivalent behaviour.
0100   int compare();
0101 
0102 protected:
0103   /// Start the comparison.
0104   void beginCompare() {
0105     sn_mapL.clear();
0106     sn_mapR.clear();
0107   }
0108 
0109   /// Compares the signature and other general attributes of the two functions.
0110   int compareSignature() const;
0111 
0112   /// Test whether two basic blocks have equivalent behaviour.
0113   int cmpBasicBlocks(const BasicBlock *BBL, const BasicBlock *BBR) const;
0114 
0115   /// Constants comparison.
0116   /// Its analog to lexicographical comparison between hypothetical numbers
0117   /// of next format:
0118   /// <bitcastability-trait><raw-bit-contents>
0119   ///
0120   /// 1. Bitcastability.
0121   /// Check whether L's type could be losslessly bitcasted to R's type.
0122   /// On this stage method, in case when lossless bitcast is not possible
0123   /// method returns -1 or 1, thus also defining which type is greater in
0124   /// context of bitcastability.
0125   /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
0126   ///          to the contents comparison.
0127   ///          If types differ, remember types comparison result and check
0128   ///          whether we still can bitcast types.
0129   /// Stage 1: Types that satisfies isFirstClassType conditions are always
0130   ///          greater then others.
0131   /// Stage 2: Vector is greater then non-vector.
0132   ///          If both types are vectors, then vector with greater bitwidth is
0133   ///          greater.
0134   ///          If both types are vectors with the same bitwidth, then types
0135   ///          are bitcastable, and we can skip other stages, and go to contents
0136   ///          comparison.
0137   /// Stage 3: Pointer types are greater than non-pointers. If both types are
0138   ///          pointers of the same address space - go to contents comparison.
0139   ///          Different address spaces: pointer with greater address space is
0140   ///          greater.
0141   /// Stage 4: Types are neither vectors, nor pointers. And they differ.
0142   ///          We don't know how to bitcast them. So, we better don't do it,
0143   ///          and return types comparison result (so it determines the
0144   ///          relationship among constants we don't know how to bitcast).
0145   ///
0146   /// Just for clearance, let's see how the set of constants could look
0147   /// on single dimension axis:
0148   ///
0149   /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
0150   /// Where: NFCT - Not a FirstClassType
0151   ///        FCT - FirstClassTyp:
0152   ///
0153   /// 2. Compare raw contents.
0154   /// It ignores types on this stage and only compares bits from L and R.
0155   /// Returns 0, if L and R has equivalent contents.
0156   /// -1 or 1 if values are different.
0157   /// Pretty trivial:
0158   /// 2.1. If contents are numbers, compare numbers.
0159   ///    Ints with greater bitwidth are greater. Ints with same bitwidths
0160   ///    compared by their contents.
0161   /// 2.2. "And so on". Just to avoid discrepancies with comments
0162   /// perhaps it would be better to read the implementation itself.
0163   /// 3. And again about overall picture. Let's look back at how the ordered set
0164   /// of constants will look like:
0165   /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
0166   ///
0167   /// Now look, what could be inside [FCT, "others"], for example:
0168   /// [FCT, "others"] =
0169   /// [
0170   ///   [double 0.1], [double 1.23],
0171   ///   [i32 1], [i32 2],
0172   ///   { double 1.0 },       ; StructTyID, NumElements = 1
0173   ///   { i32 1 },            ; StructTyID, NumElements = 1
0174   ///   { double 1, i32 1 },  ; StructTyID, NumElements = 2
0175   ///   { i32 1, double 1 }   ; StructTyID, NumElements = 2
0176   /// ]
0177   ///
0178   /// Let's explain the order. Float numbers will be less than integers, just
0179   /// because of cmpType terms: FloatTyID < IntegerTyID.
0180   /// Floats (with same fltSemantics) are sorted according to their value.
0181   /// Then you can see integers, and they are, like a floats,
0182   /// could be easy sorted among each others.
0183   /// The structures. Structures are grouped at the tail, again because of their
0184   /// TypeID: StructTyID > IntegerTyID > FloatTyID.
0185   /// Structures with greater number of elements are greater. Structures with
0186   /// greater elements going first are greater.
0187   /// The same logic with vectors, arrays and other possible complex types.
0188   ///
0189   /// Bitcastable constants.
0190   /// Let's assume, that some constant, belongs to some group of
0191   /// "so-called-equal" values with different types, and at the same time
0192   /// belongs to another group of constants with equal types
0193   /// and "really" equal values.
0194   ///
0195   /// Now, prove that this is impossible:
0196   ///
0197   /// If constant A with type TyA is bitcastable to B with type TyB, then:
0198   /// 1. All constants with equal types to TyA, are bitcastable to B. Since
0199   ///    those should be vectors (if TyA is vector), pointers
0200   ///    (if TyA is pointer), or else (if TyA equal to TyB), those types should
0201   ///    be equal to TyB.
0202   /// 2. All constants with non-equal, but bitcastable types to TyA, are
0203   ///    bitcastable to B.
0204   ///    Once again, just because we allow it to vectors and pointers only.
0205   ///    This statement could be expanded as below:
0206   /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
0207   ///      vector B, and thus bitcastable to B as well.
0208   /// 2.2. All pointers of the same address space, no matter what they point to,
0209   ///      bitcastable. So if C is pointer, it could be bitcasted to A and to B.
0210   /// So any constant equal or bitcastable to A is equal or bitcastable to B.
0211   /// QED.
0212   ///
0213   /// In another words, for pointers and vectors, we ignore top-level type and
0214   /// look at their particular properties (bit-width for vectors, and
0215   /// address space for pointers).
0216   /// If these properties are equal - compare their contents.
0217   int cmpConstants(const Constant *L, const Constant *R) const;
0218 
0219   /// Compares two global values by number. Uses the GlobalNumbersState to
0220   /// identify the same gobals across function calls.
0221   int cmpGlobalValues(GlobalValue *L, GlobalValue *R) const;
0222 
0223   /// Assign or look up previously assigned numbers for the two values, and
0224   /// return whether the numbers are equal. Numbers are assigned in the order
0225   /// visited.
0226   /// Comparison order:
0227   /// Stage 0: Value that is function itself is always greater then others.
0228   ///          If left and right values are references to their functions, then
0229   ///          they are equal.
0230   /// Stage 1: Constants are greater than non-constants.
0231   ///          If both left and right are constants, then the result of
0232   ///          cmpConstants is used as cmpValues result.
0233   /// Stage 2: InlineAsm instances are greater than others. If both left and
0234   ///          right are InlineAsm instances, InlineAsm* pointers casted to
0235   ///          integers and compared as numbers.
0236   /// Stage 3: For all other cases we compare order we meet these values in
0237   ///          their functions. If right value was met first during scanning,
0238   ///          then left value is greater.
0239   ///          In another words, we compare serial numbers, for more details
0240   ///          see comments for sn_mapL and sn_mapR.
0241   int cmpValues(const Value *L, const Value *R) const;
0242 
0243   /// Compare two Instructions for equivalence, similar to
0244   /// Instruction::isSameOperationAs.
0245   ///
0246   /// Stages are listed in "most significant stage first" order:
0247   /// On each stage below, we do comparison between some left and right
0248   /// operation parts. If parts are non-equal, we assign parts comparison
0249   /// result to the operation comparison result and exit from method.
0250   /// Otherwise we proceed to the next stage.
0251   /// Stages:
0252   /// 1. Operations opcodes. Compared as numbers.
0253   /// 2. Number of operands.
0254   /// 3. Operation types. Compared with cmpType method.
0255   /// 4. Compare operation subclass optional data as stream of bytes:
0256   /// just convert it to integers and call cmpNumbers.
0257   /// 5. Compare in operation operand types with cmpType in
0258   /// most significant operand first order.
0259   /// 6. Last stage. Check operations for some specific attributes.
0260   /// For example, for Load it would be:
0261   /// 6.1.Load: volatile (as boolean flag)
0262   /// 6.2.Load: alignment (as integer numbers)
0263   /// 6.3.Load: ordering (as underlying enum class value)
0264   /// 6.4.Load: synch-scope (as integer numbers)
0265   /// 6.5.Load: range metadata (as integer ranges)
0266   /// On this stage its better to see the code, since its not more than 10-15
0267   /// strings for particular instruction, and could change sometimes.
0268   ///
0269   /// Sets \p needToCmpOperands to true if the operands of the instructions
0270   /// still must be compared afterwards. In this case it's already guaranteed
0271   /// that both instructions have the same number of operands.
0272   int cmpOperations(const Instruction *L, const Instruction *R,
0273                     bool &needToCmpOperands) const;
0274 
0275   /// cmpType - compares two types,
0276   /// defines total ordering among the types set.
0277   ///
0278   /// Return values:
0279   /// 0 if types are equal,
0280   /// -1 if Left is less than Right,
0281   /// +1 if Left is greater than Right.
0282   ///
0283   /// Description:
0284   /// Comparison is broken onto stages. Like in lexicographical comparison
0285   /// stage coming first has higher priority.
0286   /// On each explanation stage keep in mind total ordering properties.
0287   ///
0288   /// 0. Before comparison we coerce pointer types of 0 address space to
0289   /// integer.
0290   /// We also don't bother with same type at left and right, so
0291   /// just return 0 in this case.
0292   ///
0293   /// 1. If types are of different kind (different type IDs).
0294   ///    Return result of type IDs comparison, treating them as numbers.
0295   /// 2. If types are integers, check that they have the same width. If they
0296   /// are vectors, check that they have the same count and subtype.
0297   /// 3. Types have the same ID, so check whether they are one of:
0298   /// * Void
0299   /// * Float
0300   /// * Double
0301   /// * X86_FP80
0302   /// * FP128
0303   /// * PPC_FP128
0304   /// * Label
0305   /// * Metadata
0306   /// We can treat these types as equal whenever their IDs are same.
0307   /// 4. If Left and Right are pointers, return result of address space
0308   /// comparison (numbers comparison). We can treat pointer types of same
0309   /// address space as equal.
0310   /// 5. If types are complex.
0311   /// Then both Left and Right are to be expanded and their element types will
0312   /// be checked with the same way. If we get Res != 0 on some stage, return it.
0313   /// Otherwise return 0.
0314   /// 6. For all other cases put llvm_unreachable.
0315   int cmpTypes(Type *TyL, Type *TyR) const;
0316 
0317   int cmpNumbers(uint64_t L, uint64_t R) const;
0318   int cmpAligns(Align L, Align R) const;
0319   int cmpAPInts(const APInt &L, const APInt &R) const;
0320   int cmpConstantRanges(const ConstantRange &L, const ConstantRange &R) const;
0321   int cmpAPFloats(const APFloat &L, const APFloat &R) const;
0322   int cmpMem(StringRef L, StringRef R) const;
0323 
0324   // The two functions undergoing comparison.
0325   const Function *FnL, *FnR;
0326 
0327 private:
0328   int cmpOrderings(AtomicOrdering L, AtomicOrdering R) const;
0329   int cmpInlineAsm(const InlineAsm *L, const InlineAsm *R) const;
0330   int cmpAttrs(const AttributeList L, const AttributeList R) const;
0331   int cmpMDNode(const MDNode *L, const MDNode *R) const;
0332   int cmpMetadata(const Metadata *L, const Metadata *R) const;
0333   int cmpInstMetadata(Instruction const *L, Instruction const *R) const;
0334   int cmpOperandBundlesSchema(const CallBase &LCS, const CallBase &RCS) const;
0335 
0336   /// Compare two GEPs for equivalent pointer arithmetic.
0337   /// Parts to be compared for each comparison stage,
0338   /// most significant stage first:
0339   /// 1. Address space. As numbers.
0340   /// 2. Constant offset, (using GEPOperator::accumulateConstantOffset method).
0341   /// 3. Pointer operand type (using cmpType method).
0342   /// 4. Number of operands.
0343   /// 5. Compare operands, using cmpValues method.
0344   int cmpGEPs(const GEPOperator *GEPL, const GEPOperator *GEPR) const;
0345   int cmpGEPs(const GetElementPtrInst *GEPL,
0346               const GetElementPtrInst *GEPR) const {
0347     return cmpGEPs(cast<GEPOperator>(GEPL), cast<GEPOperator>(GEPR));
0348   }
0349 
0350   /// Assign serial numbers to values from left function, and values from
0351   /// right function.
0352   /// Explanation:
0353   /// Being comparing functions we need to compare values we meet at left and
0354   /// right sides.
0355   /// Its easy to sort things out for external values. It just should be
0356   /// the same value at left and right.
0357   /// But for local values (those were introduced inside function body)
0358   /// we have to ensure they were introduced at exactly the same place,
0359   /// and plays the same role.
0360   /// Let's assign serial number to each value when we meet it first time.
0361   /// Values that were met at same place will be with same serial numbers.
0362   /// In this case it would be good to explain few points about values assigned
0363   /// to BBs and other ways of implementation (see below).
0364   ///
0365   /// 1. Safety of BB reordering.
0366   /// It's safe to change the order of BasicBlocks in function.
0367   /// Relationship with other functions and serial numbering will not be
0368   /// changed in this case.
0369   /// As follows from FunctionComparator::compare(), we do CFG walk: we start
0370   /// from the entry, and then take each terminator. So it doesn't matter how in
0371   /// fact BBs are ordered in function. And since cmpValues are called during
0372   /// this walk, the numbering depends only on how BBs located inside the CFG.
0373   /// So the answer is - yes. We will get the same numbering.
0374   ///
0375   /// 2. Impossibility to use dominance properties of values.
0376   /// If we compare two instruction operands: first is usage of local
0377   /// variable AL from function FL, and second is usage of local variable AR
0378   /// from FR, we could compare their origins and check whether they are
0379   /// defined at the same place.
0380   /// But, we are still not able to compare operands of PHI nodes, since those
0381   /// could be operands from further BBs we didn't scan yet.
0382   /// So it's impossible to use dominance properties in general.
0383   mutable DenseMap<const Value*, int> sn_mapL, sn_mapR;
0384 
0385   // The global state we will use
0386   GlobalNumberState* GlobalNumbers;
0387 };
0388 
0389 } // end namespace llvm
0390 
0391 #endif // LLVM_TRANSFORMS_UTILS_FUNCTIONCOMPARATOR_H