FunctionComparator.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- FunctionComparator.h - Function Comparator ---------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the FunctionComparator and GlobalNumberState classes which
  15. // are used by the MergeFunctions pass for comparing functions.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_TRANSFORMS_UTILS_FUNCTIONCOMPARATOR_H
  19. #define LLVM_TRANSFORMS_UTILS_FUNCTIONCOMPARATOR_H
  20. #include "llvm/ADT/DenseMap.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/IR/Instructions.h"
  23. #include "llvm/IR/Operator.h"
  24. #include "llvm/IR/ValueMap.h"
  25. #include "llvm/Support/AtomicOrdering.h"
  26. #include "llvm/Support/Casting.h"
  27. #include <cstdint>
  28. #include <tuple>
  29. namespace llvm {
  30. class APFloat;
  31. class AttributeList;
  32. class APInt;
  33. class BasicBlock;
  34. class Constant;
  35. class Function;
  36. class GlobalValue;
  37. class InlineAsm;
  38. class Instruction;
  39. class MDNode;
  40. class Type;
  41. class Value;
  42. /// GlobalNumberState assigns an integer to each global value in the program,
  43. /// which is used by the comparison routine to order references to globals. This
  44. /// state must be preserved throughout the pass, because Functions and other
  45. /// globals need to maintain their relative order. Globals are assigned a number
  46. /// when they are first visited. This order is deterministic, and so the
  47. /// assigned numbers are as well. When two functions are merged, neither number
  48. /// is updated. If the symbols are weak, this would be incorrect. If they are
  49. /// strong, then one will be replaced at all references to the other, and so
  50. /// direct callsites will now see one or the other symbol, and no update is
  51. /// necessary. Note that if we were guaranteed unique names, we could just
  52. /// compare those, but this would not work for stripped bitcodes or for those
  53. /// few symbols without a name.
  54. class GlobalNumberState {
  55. struct Config : ValueMapConfig<GlobalValue *> {
  56. enum { FollowRAUW = false };
  57. };
  58. // Each GlobalValue is mapped to an identifier. The Config ensures when RAUW
  59. // occurs, the mapping does not change. Tracking changes is unnecessary, and
  60. // also problematic for weak symbols (which may be overwritten).
  61. using ValueNumberMap = ValueMap<GlobalValue *, uint64_t, Config>;
  62. ValueNumberMap GlobalNumbers;
  63. // The next unused serial number to assign to a global.
  64. uint64_t NextNumber = 0;
  65. public:
  66. GlobalNumberState() = default;
  67. uint64_t getNumber(GlobalValue* Global) {
  68. ValueNumberMap::iterator MapIter;
  69. bool Inserted;
  70. std::tie(MapIter, Inserted) = GlobalNumbers.insert({Global, NextNumber});
  71. if (Inserted)
  72. NextNumber++;
  73. return MapIter->second;
  74. }
  75. void erase(GlobalValue *Global) {
  76. GlobalNumbers.erase(Global);
  77. }
  78. void clear() {
  79. GlobalNumbers.clear();
  80. }
  81. };
  82. /// FunctionComparator - Compares two functions to determine whether or not
  83. /// they will generate machine code with the same behaviour. DataLayout is
  84. /// used if available. The comparator always fails conservatively (erring on the
  85. /// side of claiming that two functions are different).
  86. class FunctionComparator {
  87. public:
  88. FunctionComparator(const Function *F1, const Function *F2,
  89. GlobalNumberState* GN)
  90. : FnL(F1), FnR(F2), GlobalNumbers(GN) {}
  91. /// Test whether the two functions have equivalent behaviour.
  92. int compare();
  93. /// Hash a function. Equivalent functions will have the same hash, and unequal
  94. /// functions will have different hashes with high probability.
  95. using FunctionHash = uint64_t;
  96. static FunctionHash functionHash(Function &);
  97. protected:
  98. /// Start the comparison.
  99. void beginCompare() {
  100. sn_mapL.clear();
  101. sn_mapR.clear();
  102. }
  103. /// Compares the signature and other general attributes of the two functions.
  104. int compareSignature() const;
  105. /// Test whether two basic blocks have equivalent behaviour.
  106. int cmpBasicBlocks(const BasicBlock *BBL, const BasicBlock *BBR) const;
  107. /// Constants comparison.
  108. /// Its analog to lexicographical comparison between hypothetical numbers
  109. /// of next format:
  110. /// <bitcastability-trait><raw-bit-contents>
  111. ///
  112. /// 1. Bitcastability.
  113. /// Check whether L's type could be losslessly bitcasted to R's type.
  114. /// On this stage method, in case when lossless bitcast is not possible
  115. /// method returns -1 or 1, thus also defining which type is greater in
  116. /// context of bitcastability.
  117. /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight
  118. /// to the contents comparison.
  119. /// If types differ, remember types comparison result and check
  120. /// whether we still can bitcast types.
  121. /// Stage 1: Types that satisfies isFirstClassType conditions are always
  122. /// greater then others.
  123. /// Stage 2: Vector is greater then non-vector.
  124. /// If both types are vectors, then vector with greater bitwidth is
  125. /// greater.
  126. /// If both types are vectors with the same bitwidth, then types
  127. /// are bitcastable, and we can skip other stages, and go to contents
  128. /// comparison.
  129. /// Stage 3: Pointer types are greater than non-pointers. If both types are
  130. /// pointers of the same address space - go to contents comparison.
  131. /// Different address spaces: pointer with greater address space is
  132. /// greater.
  133. /// Stage 4: Types are neither vectors, nor pointers. And they differ.
  134. /// We don't know how to bitcast them. So, we better don't do it,
  135. /// and return types comparison result (so it determines the
  136. /// relationship among constants we don't know how to bitcast).
  137. ///
  138. /// Just for clearance, let's see how the set of constants could look
  139. /// on single dimension axis:
  140. ///
  141. /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
  142. /// Where: NFCT - Not a FirstClassType
  143. /// FCT - FirstClassTyp:
  144. ///
  145. /// 2. Compare raw contents.
  146. /// It ignores types on this stage and only compares bits from L and R.
  147. /// Returns 0, if L and R has equivalent contents.
  148. /// -1 or 1 if values are different.
  149. /// Pretty trivial:
  150. /// 2.1. If contents are numbers, compare numbers.
  151. /// Ints with greater bitwidth are greater. Ints with same bitwidths
  152. /// compared by their contents.
  153. /// 2.2. "And so on". Just to avoid discrepancies with comments
  154. /// perhaps it would be better to read the implementation itself.
  155. /// 3. And again about overall picture. Let's look back at how the ordered set
  156. /// of constants will look like:
  157. /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors]
  158. ///
  159. /// Now look, what could be inside [FCT, "others"], for example:
  160. /// [FCT, "others"] =
  161. /// [
  162. /// [double 0.1], [double 1.23],
  163. /// [i32 1], [i32 2],
  164. /// { double 1.0 }, ; StructTyID, NumElements = 1
  165. /// { i32 1 }, ; StructTyID, NumElements = 1
  166. /// { double 1, i32 1 }, ; StructTyID, NumElements = 2
  167. /// { i32 1, double 1 } ; StructTyID, NumElements = 2
  168. /// ]
  169. ///
  170. /// Let's explain the order. Float numbers will be less than integers, just
  171. /// because of cmpType terms: FloatTyID < IntegerTyID.
  172. /// Floats (with same fltSemantics) are sorted according to their value.
  173. /// Then you can see integers, and they are, like a floats,
  174. /// could be easy sorted among each others.
  175. /// The structures. Structures are grouped at the tail, again because of their
  176. /// TypeID: StructTyID > IntegerTyID > FloatTyID.
  177. /// Structures with greater number of elements are greater. Structures with
  178. /// greater elements going first are greater.
  179. /// The same logic with vectors, arrays and other possible complex types.
  180. ///
  181. /// Bitcastable constants.
  182. /// Let's assume, that some constant, belongs to some group of
  183. /// "so-called-equal" values with different types, and at the same time
  184. /// belongs to another group of constants with equal types
  185. /// and "really" equal values.
  186. ///
  187. /// Now, prove that this is impossible:
  188. ///
  189. /// If constant A with type TyA is bitcastable to B with type TyB, then:
  190. /// 1. All constants with equal types to TyA, are bitcastable to B. Since
  191. /// those should be vectors (if TyA is vector), pointers
  192. /// (if TyA is pointer), or else (if TyA equal to TyB), those types should
  193. /// be equal to TyB.
  194. /// 2. All constants with non-equal, but bitcastable types to TyA, are
  195. /// bitcastable to B.
  196. /// Once again, just because we allow it to vectors and pointers only.
  197. /// This statement could be expanded as below:
  198. /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to
  199. /// vector B, and thus bitcastable to B as well.
  200. /// 2.2. All pointers of the same address space, no matter what they point to,
  201. /// bitcastable. So if C is pointer, it could be bitcasted to A and to B.
  202. /// So any constant equal or bitcastable to A is equal or bitcastable to B.
  203. /// QED.
  204. ///
  205. /// In another words, for pointers and vectors, we ignore top-level type and
  206. /// look at their particular properties (bit-width for vectors, and
  207. /// address space for pointers).
  208. /// If these properties are equal - compare their contents.
  209. int cmpConstants(const Constant *L, const Constant *R) const;
  210. /// Compares two global values by number. Uses the GlobalNumbersState to
  211. /// identify the same gobals across function calls.
  212. int cmpGlobalValues(GlobalValue *L, GlobalValue *R) const;
  213. /// Assign or look up previously assigned numbers for the two values, and
  214. /// return whether the numbers are equal. Numbers are assigned in the order
  215. /// visited.
  216. /// Comparison order:
  217. /// Stage 0: Value that is function itself is always greater then others.
  218. /// If left and right values are references to their functions, then
  219. /// they are equal.
  220. /// Stage 1: Constants are greater than non-constants.
  221. /// If both left and right are constants, then the result of
  222. /// cmpConstants is used as cmpValues result.
  223. /// Stage 2: InlineAsm instances are greater than others. If both left and
  224. /// right are InlineAsm instances, InlineAsm* pointers casted to
  225. /// integers and compared as numbers.
  226. /// Stage 3: For all other cases we compare order we meet these values in
  227. /// their functions. If right value was met first during scanning,
  228. /// then left value is greater.
  229. /// In another words, we compare serial numbers, for more details
  230. /// see comments for sn_mapL and sn_mapR.
  231. int cmpValues(const Value *L, const Value *R) const;
  232. /// Compare two Instructions for equivalence, similar to
  233. /// Instruction::isSameOperationAs.
  234. ///
  235. /// Stages are listed in "most significant stage first" order:
  236. /// On each stage below, we do comparison between some left and right
  237. /// operation parts. If parts are non-equal, we assign parts comparison
  238. /// result to the operation comparison result and exit from method.
  239. /// Otherwise we proceed to the next stage.
  240. /// Stages:
  241. /// 1. Operations opcodes. Compared as numbers.
  242. /// 2. Number of operands.
  243. /// 3. Operation types. Compared with cmpType method.
  244. /// 4. Compare operation subclass optional data as stream of bytes:
  245. /// just convert it to integers and call cmpNumbers.
  246. /// 5. Compare in operation operand types with cmpType in
  247. /// most significant operand first order.
  248. /// 6. Last stage. Check operations for some specific attributes.
  249. /// For example, for Load it would be:
  250. /// 6.1.Load: volatile (as boolean flag)
  251. /// 6.2.Load: alignment (as integer numbers)
  252. /// 6.3.Load: ordering (as underlying enum class value)
  253. /// 6.4.Load: synch-scope (as integer numbers)
  254. /// 6.5.Load: range metadata (as integer ranges)
  255. /// On this stage its better to see the code, since its not more than 10-15
  256. /// strings for particular instruction, and could change sometimes.
  257. ///
  258. /// Sets \p needToCmpOperands to true if the operands of the instructions
  259. /// still must be compared afterwards. In this case it's already guaranteed
  260. /// that both instructions have the same number of operands.
  261. int cmpOperations(const Instruction *L, const Instruction *R,
  262. bool &needToCmpOperands) const;
  263. /// cmpType - compares two types,
  264. /// defines total ordering among the types set.
  265. ///
  266. /// Return values:
  267. /// 0 if types are equal,
  268. /// -1 if Left is less than Right,
  269. /// +1 if Left is greater than Right.
  270. ///
  271. /// Description:
  272. /// Comparison is broken onto stages. Like in lexicographical comparison
  273. /// stage coming first has higher priority.
  274. /// On each explanation stage keep in mind total ordering properties.
  275. ///
  276. /// 0. Before comparison we coerce pointer types of 0 address space to
  277. /// integer.
  278. /// We also don't bother with same type at left and right, so
  279. /// just return 0 in this case.
  280. ///
  281. /// 1. If types are of different kind (different type IDs).
  282. /// Return result of type IDs comparison, treating them as numbers.
  283. /// 2. If types are integers, check that they have the same width. If they
  284. /// are vectors, check that they have the same count and subtype.
  285. /// 3. Types have the same ID, so check whether they are one of:
  286. /// * Void
  287. /// * Float
  288. /// * Double
  289. /// * X86_FP80
  290. /// * FP128
  291. /// * PPC_FP128
  292. /// * Label
  293. /// * Metadata
  294. /// We can treat these types as equal whenever their IDs are same.
  295. /// 4. If Left and Right are pointers, return result of address space
  296. /// comparison (numbers comparison). We can treat pointer types of same
  297. /// address space as equal.
  298. /// 5. If types are complex.
  299. /// Then both Left and Right are to be expanded and their element types will
  300. /// be checked with the same way. If we get Res != 0 on some stage, return it.
  301. /// Otherwise return 0.
  302. /// 6. For all other cases put llvm_unreachable.
  303. int cmpTypes(Type *TyL, Type *TyR) const;
  304. int cmpNumbers(uint64_t L, uint64_t R) const;
  305. int cmpAligns(Align L, Align R) const;
  306. int cmpAPInts(const APInt &L, const APInt &R) const;
  307. int cmpAPFloats(const APFloat &L, const APFloat &R) const;
  308. int cmpMem(StringRef L, StringRef R) const;
  309. // The two functions undergoing comparison.
  310. const Function *FnL, *FnR;
  311. private:
  312. int cmpOrderings(AtomicOrdering L, AtomicOrdering R) const;
  313. int cmpInlineAsm(const InlineAsm *L, const InlineAsm *R) const;
  314. int cmpAttrs(const AttributeList L, const AttributeList R) const;
  315. int cmpRangeMetadata(const MDNode *L, const MDNode *R) const;
  316. int cmpOperandBundlesSchema(const CallBase &LCS, const CallBase &RCS) const;
  317. /// Compare two GEPs for equivalent pointer arithmetic.
  318. /// Parts to be compared for each comparison stage,
  319. /// most significant stage first:
  320. /// 1. Address space. As numbers.
  321. /// 2. Constant offset, (using GEPOperator::accumulateConstantOffset method).
  322. /// 3. Pointer operand type (using cmpType method).
  323. /// 4. Number of operands.
  324. /// 5. Compare operands, using cmpValues method.
  325. int cmpGEPs(const GEPOperator *GEPL, const GEPOperator *GEPR) const;
  326. int cmpGEPs(const GetElementPtrInst *GEPL,
  327. const GetElementPtrInst *GEPR) const {
  328. return cmpGEPs(cast<GEPOperator>(GEPL), cast<GEPOperator>(GEPR));
  329. }
  330. /// Assign serial numbers to values from left function, and values from
  331. /// right function.
  332. /// Explanation:
  333. /// Being comparing functions we need to compare values we meet at left and
  334. /// right sides.
  335. /// Its easy to sort things out for external values. It just should be
  336. /// the same value at left and right.
  337. /// But for local values (those were introduced inside function body)
  338. /// we have to ensure they were introduced at exactly the same place,
  339. /// and plays the same role.
  340. /// Let's assign serial number to each value when we meet it first time.
  341. /// Values that were met at same place will be with same serial numbers.
  342. /// In this case it would be good to explain few points about values assigned
  343. /// to BBs and other ways of implementation (see below).
  344. ///
  345. /// 1. Safety of BB reordering.
  346. /// It's safe to change the order of BasicBlocks in function.
  347. /// Relationship with other functions and serial numbering will not be
  348. /// changed in this case.
  349. /// As follows from FunctionComparator::compare(), we do CFG walk: we start
  350. /// from the entry, and then take each terminator. So it doesn't matter how in
  351. /// fact BBs are ordered in function. And since cmpValues are called during
  352. /// this walk, the numbering depends only on how BBs located inside the CFG.
  353. /// So the answer is - yes. We will get the same numbering.
  354. ///
  355. /// 2. Impossibility to use dominance properties of values.
  356. /// If we compare two instruction operands: first is usage of local
  357. /// variable AL from function FL, and second is usage of local variable AR
  358. /// from FR, we could compare their origins and check whether they are
  359. /// defined at the same place.
  360. /// But, we are still not able to compare operands of PHI nodes, since those
  361. /// could be operands from further BBs we didn't scan yet.
  362. /// So it's impossible to use dominance properties in general.
  363. mutable DenseMap<const Value*, int> sn_mapL, sn_mapR;
  364. // The global state we will use
  365. GlobalNumberState* GlobalNumbers;
  366. };
  367. } // end namespace llvm
  368. #endif // LLVM_TRANSFORMS_UTILS_FUNCTIONCOMPARATOR_H
  369. #ifdef __GNUC__
  370. #pragma GCC diagnostic pop
  371. #endif