1 //===- MergeFunctions.cpp - Merge identical functions ---------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass looks for equivalent functions that are mergable and folds them. 11 // 12 // Order relation is defined on set of functions. It was made through 13 // special function comparison procedure that returns 14 // 0 when functions are equal, 15 // -1 when Left function is less than right function, and 16 // 1 for opposite case. We need total-ordering, so we need to maintain 17 // four properties on the functions set: 18 // a <= a (reflexivity) 19 // if a <= b and b <= a then a = b (antisymmetry) 20 // if a <= b and b <= c then a <= c (transitivity). 21 // for all a and b: a <= b or b <= a (totality). 22 // 23 // Comparison iterates through each instruction in each basic block. 24 // Functions are kept on binary tree. For each new function F we perform 25 // lookup in binary tree. 26 // In practice it works the following way: 27 // -- We define Function* container class with custom "operator<" (FunctionPtr). 28 // -- "FunctionPtr" instances are stored in std::set collection, so every 29 // std::set::insert operation will give you result in log(N) time. 30 // 31 // As an optimization, a hash of the function structure is calculated first, and 32 // two functions are only compared if they have the same hash. This hash is 33 // cheap to compute, and has the property that if function F == G according to 34 // the comparison function, then hash(F) == hash(G). This consistency property 35 // is critical to ensuring all possible merging opportunities are exploited. 36 // Collisions in the hash affect the speed of the pass but not the correctness 37 // or determinism of the resulting transformation. 38 // 39 // When a match is found the functions are folded. If both functions are 40 // overridable, we move the functionality into a new internal function and 41 // leave two overridable thunks to it. 42 // 43 //===----------------------------------------------------------------------===// 44 // 45 // Future work: 46 // 47 // * virtual functions. 48 // 49 // Many functions have their address taken by the virtual function table for 50 // the object they belong to. However, as long as it's only used for a lookup 51 // and call, this is irrelevant, and we'd like to fold such functions. 52 // 53 // * be smarter about bitcasts. 54 // 55 // In order to fold functions, we will sometimes add either bitcast instructions 56 // or bitcast constant expressions. Unfortunately, this can confound further 57 // analysis since the two functions differ where one has a bitcast and the 58 // other doesn't. We should learn to look through bitcasts. 59 // 60 // * Compare complex types with pointer types inside. 61 // * Compare cross-reference cases. 62 // * Compare complex expressions. 63 // 64 // All the three issues above could be described as ability to prove that 65 // fA == fB == fC == fE == fF == fG in example below: 66 // 67 // void fA() { 68 // fB(); 69 // } 70 // void fB() { 71 // fA(); 72 // } 73 // 74 // void fE() { 75 // fF(); 76 // } 77 // void fF() { 78 // fG(); 79 // } 80 // void fG() { 81 // fE(); 82 // } 83 // 84 // Simplest cross-reference case (fA <--> fB) was implemented in previous 85 // versions of MergeFunctions, though it presented only in two function pairs 86 // in test-suite (that counts >50k functions) 87 // Though possibility to detect complex cross-referencing (e.g.: A->B->C->D->A) 88 // could cover much more cases. 89 // 90 //===----------------------------------------------------------------------===// 91 92 #include "llvm/Transforms/IPO.h" 93 #include "llvm/ADT/DenseSet.h" 94 #include "llvm/ADT/FoldingSet.h" 95 #include "llvm/ADT/STLExtras.h" 96 #include "llvm/ADT/SmallSet.h" 97 #include "llvm/ADT/Statistic.h" 98 #include "llvm/ADT/Hashing.h" 99 #include "llvm/IR/CallSite.h" 100 #include "llvm/IR/Constants.h" 101 #include "llvm/IR/DataLayout.h" 102 #include "llvm/IR/IRBuilder.h" 103 #include "llvm/IR/InlineAsm.h" 104 #include "llvm/IR/Instructions.h" 105 #include "llvm/IR/LLVMContext.h" 106 #include "llvm/IR/Module.h" 107 #include "llvm/IR/Operator.h" 108 #include "llvm/IR/ValueHandle.h" 109 #include "llvm/IR/ValueMap.h" 110 #include "llvm/Pass.h" 111 #include "llvm/Support/CommandLine.h" 112 #include "llvm/Support/Debug.h" 113 #include "llvm/Support/ErrorHandling.h" 114 #include "llvm/Support/raw_ostream.h" 115 #include <vector> 116 117 using namespace llvm; 118 119 #define DEBUG_TYPE "mergefunc" 120 121 STATISTIC(NumFunctionsMerged, "Number of functions merged"); 122 STATISTIC(NumThunksWritten, "Number of thunks generated"); 123 STATISTIC(NumAliasesWritten, "Number of aliases generated"); 124 STATISTIC(NumDoubleWeak, "Number of new functions created"); 125 126 static cl::opt<unsigned> NumFunctionsForSanityCheck( 127 "mergefunc-sanity", 128 cl::desc("How many functions in module could be used for " 129 "MergeFunctions pass sanity check. " 130 "'0' disables this check. Works only with '-debug' key."), 131 cl::init(0), cl::Hidden); 132 133 namespace { 134 135 /// GlobalNumberState assigns an integer to each global value in the program, 136 /// which is used by the comparison routine to order references to globals. This 137 /// state must be preserved throughout the pass, because Functions and other 138 /// globals need to maintain their relative order. Globals are assigned a number 139 /// when they are first visited. This order is deterministic, and so the 140 /// assigned numbers are as well. When two functions are merged, neither number 141 /// is updated. If the symbols are weak, this would be incorrect. If they are 142 /// strong, then one will be replaced at all references to the other, and so 143 /// direct callsites will now see one or the other symbol, and no update is 144 /// necessary. Note that if we were guaranteed unique names, we could just 145 /// compare those, but this would not work for stripped bitcodes or for those 146 /// few symbols without a name. 147 class GlobalNumberState { 148 struct Config : ValueMapConfig<GlobalValue*> { 149 enum { FollowRAUW = false }; 150 }; 151 // Each GlobalValue is mapped to an identifier. The Config ensures when RAUW 152 // occurs, the mapping does not change. Tracking changes is unnecessary, and 153 // also problematic for weak symbols (which may be overwritten). 154 typedef ValueMap<GlobalValue *, uint64_t, Config> ValueNumberMap; 155 ValueNumberMap GlobalNumbers; 156 // The next unused serial number to assign to a global. 157 uint64_t NextNumber; 158 public: 159 GlobalNumberState() : GlobalNumbers(), NextNumber(0) {} 160 uint64_t getNumber(GlobalValue* Global) { 161 ValueNumberMap::iterator MapIter; 162 bool Inserted; 163 std::tie(MapIter, Inserted) = GlobalNumbers.insert({Global, NextNumber}); 164 if (Inserted) 165 NextNumber++; 166 return MapIter->second; 167 } 168 void clear() { 169 GlobalNumbers.clear(); 170 } 171 }; 172 173 /// FunctionComparator - Compares two functions to determine whether or not 174 /// they will generate machine code with the same behaviour. DataLayout is 175 /// used if available. The comparator always fails conservatively (erring on the 176 /// side of claiming that two functions are different). 177 class FunctionComparator { 178 public: 179 FunctionComparator(const Function *F1, const Function *F2, 180 GlobalNumberState* GN) 181 : FnL(F1), FnR(F2), GlobalNumbers(GN) {} 182 183 /// Test whether the two functions have equivalent behaviour. 184 int compare(); 185 /// Hash a function. Equivalent functions will have the same hash, and unequal 186 /// functions will have different hashes with high probability. 187 typedef uint64_t FunctionHash; 188 static FunctionHash functionHash(Function &); 189 190 private: 191 /// Test whether two basic blocks have equivalent behaviour. 192 int cmpBasicBlocks(const BasicBlock *BBL, const BasicBlock *BBR); 193 194 /// Constants comparison. 195 /// Its analog to lexicographical comparison between hypothetical numbers 196 /// of next format: 197 /// <bitcastability-trait><raw-bit-contents> 198 /// 199 /// 1. Bitcastability. 200 /// Check whether L's type could be losslessly bitcasted to R's type. 201 /// On this stage method, in case when lossless bitcast is not possible 202 /// method returns -1 or 1, thus also defining which type is greater in 203 /// context of bitcastability. 204 /// Stage 0: If types are equal in terms of cmpTypes, then we can go straight 205 /// to the contents comparison. 206 /// If types differ, remember types comparison result and check 207 /// whether we still can bitcast types. 208 /// Stage 1: Types that satisfies isFirstClassType conditions are always 209 /// greater then others. 210 /// Stage 2: Vector is greater then non-vector. 211 /// If both types are vectors, then vector with greater bitwidth is 212 /// greater. 213 /// If both types are vectors with the same bitwidth, then types 214 /// are bitcastable, and we can skip other stages, and go to contents 215 /// comparison. 216 /// Stage 3: Pointer types are greater than non-pointers. If both types are 217 /// pointers of the same address space - go to contents comparison. 218 /// Different address spaces: pointer with greater address space is 219 /// greater. 220 /// Stage 4: Types are neither vectors, nor pointers. And they differ. 221 /// We don't know how to bitcast them. So, we better don't do it, 222 /// and return types comparison result (so it determines the 223 /// relationship among constants we don't know how to bitcast). 224 /// 225 /// Just for clearance, let's see how the set of constants could look 226 /// on single dimension axis: 227 /// 228 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors] 229 /// Where: NFCT - Not a FirstClassType 230 /// FCT - FirstClassTyp: 231 /// 232 /// 2. Compare raw contents. 233 /// It ignores types on this stage and only compares bits from L and R. 234 /// Returns 0, if L and R has equivalent contents. 235 /// -1 or 1 if values are different. 236 /// Pretty trivial: 237 /// 2.1. If contents are numbers, compare numbers. 238 /// Ints with greater bitwidth are greater. Ints with same bitwidths 239 /// compared by their contents. 240 /// 2.2. "And so on". Just to avoid discrepancies with comments 241 /// perhaps it would be better to read the implementation itself. 242 /// 3. And again about overall picture. Let's look back at how the ordered set 243 /// of constants will look like: 244 /// [NFCT], [FCT, "others"], [FCT, pointers], [FCT, vectors] 245 /// 246 /// Now look, what could be inside [FCT, "others"], for example: 247 /// [FCT, "others"] = 248 /// [ 249 /// [double 0.1], [double 1.23], 250 /// [i32 1], [i32 2], 251 /// { double 1.0 }, ; StructTyID, NumElements = 1 252 /// { i32 1 }, ; StructTyID, NumElements = 1 253 /// { double 1, i32 1 }, ; StructTyID, NumElements = 2 254 /// { i32 1, double 1 } ; StructTyID, NumElements = 2 255 /// ] 256 /// 257 /// Let's explain the order. Float numbers will be less than integers, just 258 /// because of cmpType terms: FloatTyID < IntegerTyID. 259 /// Floats (with same fltSemantics) are sorted according to their value. 260 /// Then you can see integers, and they are, like a floats, 261 /// could be easy sorted among each others. 262 /// The structures. Structures are grouped at the tail, again because of their 263 /// TypeID: StructTyID > IntegerTyID > FloatTyID. 264 /// Structures with greater number of elements are greater. Structures with 265 /// greater elements going first are greater. 266 /// The same logic with vectors, arrays and other possible complex types. 267 /// 268 /// Bitcastable constants. 269 /// Let's assume, that some constant, belongs to some group of 270 /// "so-called-equal" values with different types, and at the same time 271 /// belongs to another group of constants with equal types 272 /// and "really" equal values. 273 /// 274 /// Now, prove that this is impossible: 275 /// 276 /// If constant A with type TyA is bitcastable to B with type TyB, then: 277 /// 1. All constants with equal types to TyA, are bitcastable to B. Since 278 /// those should be vectors (if TyA is vector), pointers 279 /// (if TyA is pointer), or else (if TyA equal to TyB), those types should 280 /// be equal to TyB. 281 /// 2. All constants with non-equal, but bitcastable types to TyA, are 282 /// bitcastable to B. 283 /// Once again, just because we allow it to vectors and pointers only. 284 /// This statement could be expanded as below: 285 /// 2.1. All vectors with equal bitwidth to vector A, has equal bitwidth to 286 /// vector B, and thus bitcastable to B as well. 287 /// 2.2. All pointers of the same address space, no matter what they point to, 288 /// bitcastable. So if C is pointer, it could be bitcasted to A and to B. 289 /// So any constant equal or bitcastable to A is equal or bitcastable to B. 290 /// QED. 291 /// 292 /// In another words, for pointers and vectors, we ignore top-level type and 293 /// look at their particular properties (bit-width for vectors, and 294 /// address space for pointers). 295 /// If these properties are equal - compare their contents. 296 int cmpConstants(const Constant *L, const Constant *R); 297 298 /// Compares two global values by number. Uses the GlobalNumbersState to 299 /// identify the same gobals across function calls. 300 int cmpGlobalValues(GlobalValue *L, GlobalValue *R); 301 302 /// Assign or look up previously assigned numbers for the two values, and 303 /// return whether the numbers are equal. Numbers are assigned in the order 304 /// visited. 305 /// Comparison order: 306 /// Stage 0: Value that is function itself is always greater then others. 307 /// If left and right values are references to their functions, then 308 /// they are equal. 309 /// Stage 1: Constants are greater than non-constants. 310 /// If both left and right are constants, then the result of 311 /// cmpConstants is used as cmpValues result. 312 /// Stage 2: InlineAsm instances are greater than others. If both left and 313 /// right are InlineAsm instances, InlineAsm* pointers casted to 314 /// integers and compared as numbers. 315 /// Stage 3: For all other cases we compare order we meet these values in 316 /// their functions. If right value was met first during scanning, 317 /// then left value is greater. 318 /// In another words, we compare serial numbers, for more details 319 /// see comments for sn_mapL and sn_mapR. 320 int cmpValues(const Value *L, const Value *R); 321 322 /// Compare two Instructions for equivalence, similar to 323 /// Instruction::isSameOperationAs but with modifications to the type 324 /// comparison. 325 /// Stages are listed in "most significant stage first" order: 326 /// On each stage below, we do comparison between some left and right 327 /// operation parts. If parts are non-equal, we assign parts comparison 328 /// result to the operation comparison result and exit from method. 329 /// Otherwise we proceed to the next stage. 330 /// Stages: 331 /// 1. Operations opcodes. Compared as numbers. 332 /// 2. Number of operands. 333 /// 3. Operation types. Compared with cmpType method. 334 /// 4. Compare operation subclass optional data as stream of bytes: 335 /// just convert it to integers and call cmpNumbers. 336 /// 5. Compare in operation operand types with cmpType in 337 /// most significant operand first order. 338 /// 6. Last stage. Check operations for some specific attributes. 339 /// For example, for Load it would be: 340 /// 6.1.Load: volatile (as boolean flag) 341 /// 6.2.Load: alignment (as integer numbers) 342 /// 6.3.Load: synch-scope (as integer numbers) 343 /// 6.4.Load: range metadata (as integer numbers) 344 /// On this stage its better to see the code, since its not more than 10-15 345 /// strings for particular instruction, and could change sometimes. 346 int cmpOperations(const Instruction *L, const Instruction *R) const; 347 348 /// Compare two GEPs for equivalent pointer arithmetic. 349 /// Parts to be compared for each comparison stage, 350 /// most significant stage first: 351 /// 1. Address space. As numbers. 352 /// 2. Constant offset, (using GEPOperator::accumulateConstantOffset method). 353 /// 3. Pointer operand type (using cmpType method). 354 /// 4. Number of operands. 355 /// 5. Compare operands, using cmpValues method. 356 int cmpGEPs(const GEPOperator *GEPL, const GEPOperator *GEPR); 357 int cmpGEPs(const GetElementPtrInst *GEPL, const GetElementPtrInst *GEPR) { 358 return cmpGEPs(cast<GEPOperator>(GEPL), cast<GEPOperator>(GEPR)); 359 } 360 361 /// cmpType - compares two types, 362 /// defines total ordering among the types set. 363 /// 364 /// Return values: 365 /// 0 if types are equal, 366 /// -1 if Left is less than Right, 367 /// +1 if Left is greater than Right. 368 /// 369 /// Description: 370 /// Comparison is broken onto stages. Like in lexicographical comparison 371 /// stage coming first has higher priority. 372 /// On each explanation stage keep in mind total ordering properties. 373 /// 374 /// 0. Before comparison we coerce pointer types of 0 address space to 375 /// integer. 376 /// We also don't bother with same type at left and right, so 377 /// just return 0 in this case. 378 /// 379 /// 1. If types are of different kind (different type IDs). 380 /// Return result of type IDs comparison, treating them as numbers. 381 /// 2. If types are integers, check that they have the same width. If they 382 /// are vectors, check that they have the same count and subtype. 383 /// 3. Types have the same ID, so check whether they are one of: 384 /// * Void 385 /// * Float 386 /// * Double 387 /// * X86_FP80 388 /// * FP128 389 /// * PPC_FP128 390 /// * Label 391 /// * Metadata 392 /// We can treat these types as equal whenever their IDs are same. 393 /// 4. If Left and Right are pointers, return result of address space 394 /// comparison (numbers comparison). We can treat pointer types of same 395 /// address space as equal. 396 /// 5. If types are complex. 397 /// Then both Left and Right are to be expanded and their element types will 398 /// be checked with the same way. If we get Res != 0 on some stage, return it. 399 /// Otherwise return 0. 400 /// 6. For all other cases put llvm_unreachable. 401 int cmpTypes(Type *TyL, Type *TyR) const; 402 403 int cmpNumbers(uint64_t L, uint64_t R) const; 404 int cmpAPInts(const APInt &L, const APInt &R) const; 405 int cmpAPFloats(const APFloat &L, const APFloat &R) const; 406 int cmpInlineAsm(const InlineAsm *L, const InlineAsm *R) const; 407 int cmpMem(StringRef L, StringRef R) const; 408 int cmpAttrs(const AttributeSet L, const AttributeSet R) const; 409 int cmpRangeMetadata(const MDNode* L, const MDNode* R) const; 410 411 // The two functions undergoing comparison. 412 const Function *FnL, *FnR; 413 414 /// Assign serial numbers to values from left function, and values from 415 /// right function. 416 /// Explanation: 417 /// Being comparing functions we need to compare values we meet at left and 418 /// right sides. 419 /// Its easy to sort things out for external values. It just should be 420 /// the same value at left and right. 421 /// But for local values (those were introduced inside function body) 422 /// we have to ensure they were introduced at exactly the same place, 423 /// and plays the same role. 424 /// Let's assign serial number to each value when we meet it first time. 425 /// Values that were met at same place will be with same serial numbers. 426 /// In this case it would be good to explain few points about values assigned 427 /// to BBs and other ways of implementation (see below). 428 /// 429 /// 1. Safety of BB reordering. 430 /// It's safe to change the order of BasicBlocks in function. 431 /// Relationship with other functions and serial numbering will not be 432 /// changed in this case. 433 /// As follows from FunctionComparator::compare(), we do CFG walk: we start 434 /// from the entry, and then take each terminator. So it doesn't matter how in 435 /// fact BBs are ordered in function. And since cmpValues are called during 436 /// this walk, the numbering depends only on how BBs located inside the CFG. 437 /// So the answer is - yes. We will get the same numbering. 438 /// 439 /// 2. Impossibility to use dominance properties of values. 440 /// If we compare two instruction operands: first is usage of local 441 /// variable AL from function FL, and second is usage of local variable AR 442 /// from FR, we could compare their origins and check whether they are 443 /// defined at the same place. 444 /// But, we are still not able to compare operands of PHI nodes, since those 445 /// could be operands from further BBs we didn't scan yet. 446 /// So it's impossible to use dominance properties in general. 447 DenseMap<const Value*, int> sn_mapL, sn_mapR; 448 449 // The global state we will use 450 GlobalNumberState* GlobalNumbers; 451 }; 452 453 class FunctionNode { 454 mutable AssertingVH<Function> F; 455 FunctionComparator::FunctionHash Hash; 456 public: 457 // Note the hash is recalculated potentially multiple times, but it is cheap. 458 FunctionNode(Function *F) 459 : F(F), Hash(FunctionComparator::functionHash(*F)) {} 460 Function *getFunc() const { return F; } 461 FunctionComparator::FunctionHash getHash() const { return Hash; } 462 463 /// Replace the reference to the function F by the function G, assuming their 464 /// implementations are equal. 465 void replaceBy(Function *G) const { 466 F = G; 467 } 468 469 void release() { F = nullptr; } 470 }; 471 } // end anonymous namespace 472 473 int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const { 474 if (L < R) return -1; 475 if (L > R) return 1; 476 return 0; 477 } 478 479 int FunctionComparator::cmpAPInts(const APInt &L, const APInt &R) const { 480 if (int Res = cmpNumbers(L.getBitWidth(), R.getBitWidth())) 481 return Res; 482 if (L.ugt(R)) return 1; 483 if (R.ugt(L)) return -1; 484 return 0; 485 } 486 487 int FunctionComparator::cmpAPFloats(const APFloat &L, const APFloat &R) const { 488 // Floats are ordered first by semantics (i.e. float, double, half, etc.), 489 // then by value interpreted as a bitstring (aka APInt). 490 const fltSemantics &SL = L.getSemantics(), &SR = R.getSemantics(); 491 if (int Res = cmpNumbers(APFloat::semanticsPrecision(SL), 492 APFloat::semanticsPrecision(SR))) 493 return Res; 494 if (int Res = cmpNumbers(APFloat::semanticsMaxExponent(SL), 495 APFloat::semanticsMaxExponent(SR))) 496 return Res; 497 if (int Res = cmpNumbers(APFloat::semanticsMinExponent(SL), 498 APFloat::semanticsMinExponent(SR))) 499 return Res; 500 if (int Res = cmpNumbers(APFloat::semanticsSizeInBits(SL), 501 APFloat::semanticsSizeInBits(SR))) 502 return Res; 503 return cmpAPInts(L.bitcastToAPInt(), R.bitcastToAPInt()); 504 } 505 506 int FunctionComparator::cmpMem(StringRef L, StringRef R) const { 507 // Prevent heavy comparison, compare sizes first. 508 if (int Res = cmpNumbers(L.size(), R.size())) 509 return Res; 510 511 // Compare strings lexicographically only when it is necessary: only when 512 // strings are equal in size. 513 return L.compare(R); 514 } 515 516 int FunctionComparator::cmpAttrs(const AttributeSet L, 517 const AttributeSet R) const { 518 if (int Res = cmpNumbers(L.getNumSlots(), R.getNumSlots())) 519 return Res; 520 521 for (unsigned i = 0, e = L.getNumSlots(); i != e; ++i) { 522 AttributeSet::iterator LI = L.begin(i), LE = L.end(i), RI = R.begin(i), 523 RE = R.end(i); 524 for (; LI != LE && RI != RE; ++LI, ++RI) { 525 Attribute LA = *LI; 526 Attribute RA = *RI; 527 if (LA < RA) 528 return -1; 529 if (RA < LA) 530 return 1; 531 } 532 if (LI != LE) 533 return 1; 534 if (RI != RE) 535 return -1; 536 } 537 return 0; 538 } 539 540 int FunctionComparator::cmpRangeMetadata(const MDNode* L, 541 const MDNode* R) const { 542 if (L == R) 543 return 0; 544 if (!L) 545 return -1; 546 if (!R) 547 return 1; 548 // Range metadata is a sequence of numbers. Make sure they are the same 549 // sequence. 550 // TODO: Note that as this is metadata, it is possible to drop and/or merge 551 // this data when considering functions to merge. Thus this comparison would 552 // return 0 (i.e. equivalent), but merging would become more complicated 553 // because the ranges would need to be unioned. It is not likely that 554 // functions differ ONLY in this metadata if they are actually the same 555 // function semantically. 556 if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands())) 557 return Res; 558 for (size_t I = 0; I < L->getNumOperands(); ++I) { 559 ConstantInt* LLow = mdconst::extract<ConstantInt>(L->getOperand(I)); 560 ConstantInt* RLow = mdconst::extract<ConstantInt>(R->getOperand(I)); 561 if (int Res = cmpAPInts(LLow->getValue(), RLow->getValue())) 562 return Res; 563 } 564 return 0; 565 } 566 567 /// Constants comparison: 568 /// 1. Check whether type of L constant could be losslessly bitcasted to R 569 /// type. 570 /// 2. Compare constant contents. 571 /// For more details see declaration comments. 572 int FunctionComparator::cmpConstants(const Constant *L, const Constant *R) { 573 574 Type *TyL = L->getType(); 575 Type *TyR = R->getType(); 576 577 // Check whether types are bitcastable. This part is just re-factored 578 // Type::canLosslesslyBitCastTo method, but instead of returning true/false, 579 // we also pack into result which type is "less" for us. 580 int TypesRes = cmpTypes(TyL, TyR); 581 if (TypesRes != 0) { 582 // Types are different, but check whether we can bitcast them. 583 if (!TyL->isFirstClassType()) { 584 if (TyR->isFirstClassType()) 585 return -1; 586 // Neither TyL nor TyR are values of first class type. Return the result 587 // of comparing the types 588 return TypesRes; 589 } 590 if (!TyR->isFirstClassType()) { 591 if (TyL->isFirstClassType()) 592 return 1; 593 return TypesRes; 594 } 595 596 // Vector -> Vector conversions are always lossless if the two vector types 597 // have the same size, otherwise not. 598 unsigned TyLWidth = 0; 599 unsigned TyRWidth = 0; 600 601 if (auto *VecTyL = dyn_cast<VectorType>(TyL)) 602 TyLWidth = VecTyL->getBitWidth(); 603 if (auto *VecTyR = dyn_cast<VectorType>(TyR)) 604 TyRWidth = VecTyR->getBitWidth(); 605 606 if (TyLWidth != TyRWidth) 607 return cmpNumbers(TyLWidth, TyRWidth); 608 609 // Zero bit-width means neither TyL nor TyR are vectors. 610 if (!TyLWidth) { 611 PointerType *PTyL = dyn_cast<PointerType>(TyL); 612 PointerType *PTyR = dyn_cast<PointerType>(TyR); 613 if (PTyL && PTyR) { 614 unsigned AddrSpaceL = PTyL->getAddressSpace(); 615 unsigned AddrSpaceR = PTyR->getAddressSpace(); 616 if (int Res = cmpNumbers(AddrSpaceL, AddrSpaceR)) 617 return Res; 618 } 619 if (PTyL) 620 return 1; 621 if (PTyR) 622 return -1; 623 624 // TyL and TyR aren't vectors, nor pointers. We don't know how to 625 // bitcast them. 626 return TypesRes; 627 } 628 } 629 630 // OK, types are bitcastable, now check constant contents. 631 632 if (L->isNullValue() && R->isNullValue()) 633 return TypesRes; 634 if (L->isNullValue() && !R->isNullValue()) 635 return 1; 636 if (!L->isNullValue() && R->isNullValue()) 637 return -1; 638 639 auto GlobalValueL = const_cast<GlobalValue*>(dyn_cast<GlobalValue>(L)); 640 auto GlobalValueR = const_cast<GlobalValue*>(dyn_cast<GlobalValue>(R)); 641 if (GlobalValueL && GlobalValueR) { 642 return cmpGlobalValues(GlobalValueL, GlobalValueR); 643 } 644 645 if (int Res = cmpNumbers(L->getValueID(), R->getValueID())) 646 return Res; 647 648 if (const auto *SeqL = dyn_cast<ConstantDataSequential>(L)) { 649 const auto *SeqR = cast<ConstantDataSequential>(R); 650 // This handles ConstantDataArray and ConstantDataVector. Note that we 651 // compare the two raw data arrays, which might differ depending on the host 652 // endianness. This isn't a problem though, because the endiness of a module 653 // will affect the order of the constants, but this order is the same 654 // for a given input module and host platform. 655 return cmpMem(SeqL->getRawDataValues(), SeqR->getRawDataValues()); 656 } 657 658 switch (L->getValueID()) { 659 case Value::UndefValueVal: return TypesRes; 660 case Value::ConstantIntVal: { 661 const APInt &LInt = cast<ConstantInt>(L)->getValue(); 662 const APInt &RInt = cast<ConstantInt>(R)->getValue(); 663 return cmpAPInts(LInt, RInt); 664 } 665 case Value::ConstantFPVal: { 666 const APFloat &LAPF = cast<ConstantFP>(L)->getValueAPF(); 667 const APFloat &RAPF = cast<ConstantFP>(R)->getValueAPF(); 668 return cmpAPFloats(LAPF, RAPF); 669 } 670 case Value::ConstantArrayVal: { 671 const ConstantArray *LA = cast<ConstantArray>(L); 672 const ConstantArray *RA = cast<ConstantArray>(R); 673 uint64_t NumElementsL = cast<ArrayType>(TyL)->getNumElements(); 674 uint64_t NumElementsR = cast<ArrayType>(TyR)->getNumElements(); 675 if (int Res = cmpNumbers(NumElementsL, NumElementsR)) 676 return Res; 677 for (uint64_t i = 0; i < NumElementsL; ++i) { 678 if (int Res = cmpConstants(cast<Constant>(LA->getOperand(i)), 679 cast<Constant>(RA->getOperand(i)))) 680 return Res; 681 } 682 return 0; 683 } 684 case Value::ConstantStructVal: { 685 const ConstantStruct *LS = cast<ConstantStruct>(L); 686 const ConstantStruct *RS = cast<ConstantStruct>(R); 687 unsigned NumElementsL = cast<StructType>(TyL)->getNumElements(); 688 unsigned NumElementsR = cast<StructType>(TyR)->getNumElements(); 689 if (int Res = cmpNumbers(NumElementsL, NumElementsR)) 690 return Res; 691 for (unsigned i = 0; i != NumElementsL; ++i) { 692 if (int Res = cmpConstants(cast<Constant>(LS->getOperand(i)), 693 cast<Constant>(RS->getOperand(i)))) 694 return Res; 695 } 696 return 0; 697 } 698 case Value::ConstantVectorVal: { 699 const ConstantVector *LV = cast<ConstantVector>(L); 700 const ConstantVector *RV = cast<ConstantVector>(R); 701 unsigned NumElementsL = cast<VectorType>(TyL)->getNumElements(); 702 unsigned NumElementsR = cast<VectorType>(TyR)->getNumElements(); 703 if (int Res = cmpNumbers(NumElementsL, NumElementsR)) 704 return Res; 705 for (uint64_t i = 0; i < NumElementsL; ++i) { 706 if (int Res = cmpConstants(cast<Constant>(LV->getOperand(i)), 707 cast<Constant>(RV->getOperand(i)))) 708 return Res; 709 } 710 return 0; 711 } 712 case Value::ConstantExprVal: { 713 const ConstantExpr *LE = cast<ConstantExpr>(L); 714 const ConstantExpr *RE = cast<ConstantExpr>(R); 715 unsigned NumOperandsL = LE->getNumOperands(); 716 unsigned NumOperandsR = RE->getNumOperands(); 717 if (int Res = cmpNumbers(NumOperandsL, NumOperandsR)) 718 return Res; 719 for (unsigned i = 0; i < NumOperandsL; ++i) { 720 if (int Res = cmpConstants(cast<Constant>(LE->getOperand(i)), 721 cast<Constant>(RE->getOperand(i)))) 722 return Res; 723 } 724 return 0; 725 } 726 case Value::BlockAddressVal: { 727 const BlockAddress *LBA = cast<BlockAddress>(L); 728 const BlockAddress *RBA = cast<BlockAddress>(R); 729 if (int Res = cmpValues(LBA->getFunction(), RBA->getFunction())) 730 return Res; 731 if (LBA->getFunction() == RBA->getFunction()) { 732 // They are BBs in the same function. Order by which comes first in the 733 // BB order of the function. This order is deterministic. 734 Function* F = LBA->getFunction(); 735 BasicBlock *LBB = LBA->getBasicBlock(); 736 BasicBlock *RBB = RBA->getBasicBlock(); 737 if (LBB == RBB) 738 return 0; 739 for(BasicBlock &BB : F->getBasicBlockList()) { 740 if (&BB == LBB) { 741 assert(&BB != RBB); 742 return -1; 743 } 744 if (&BB == RBB) 745 return 1; 746 } 747 llvm_unreachable("Basic Block Address does not point to a basic block in " 748 "its function."); 749 return -1; 750 } else { 751 // cmpValues said the functions are the same. So because they aren't 752 // literally the same pointer, they must respectively be the left and 753 // right functions. 754 assert(LBA->getFunction() == FnL && RBA->getFunction() == FnR); 755 // cmpValues will tell us if these are equivalent BasicBlocks, in the 756 // context of their respective functions. 757 return cmpValues(LBA->getBasicBlock(), RBA->getBasicBlock()); 758 } 759 } 760 default: // Unknown constant, abort. 761 DEBUG(dbgs() << "Looking at valueID " << L->getValueID() << "\n"); 762 llvm_unreachable("Constant ValueID not recognized."); 763 return -1; 764 } 765 } 766 767 int FunctionComparator::cmpGlobalValues(GlobalValue *L, GlobalValue* R) { 768 return cmpNumbers(GlobalNumbers->getNumber(L), GlobalNumbers->getNumber(R)); 769 } 770 771 /// cmpType - compares two types, 772 /// defines total ordering among the types set. 773 /// See method declaration comments for more details. 774 int FunctionComparator::cmpTypes(Type *TyL, Type *TyR) const { 775 PointerType *PTyL = dyn_cast<PointerType>(TyL); 776 PointerType *PTyR = dyn_cast<PointerType>(TyR); 777 778 const DataLayout &DL = FnL->getParent()->getDataLayout(); 779 if (PTyL && PTyL->getAddressSpace() == 0) 780 TyL = DL.getIntPtrType(TyL); 781 if (PTyR && PTyR->getAddressSpace() == 0) 782 TyR = DL.getIntPtrType(TyR); 783 784 if (TyL == TyR) 785 return 0; 786 787 if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID())) 788 return Res; 789 790 switch (TyL->getTypeID()) { 791 default: 792 llvm_unreachable("Unknown type!"); 793 // Fall through in Release mode. 794 case Type::IntegerTyID: 795 return cmpNumbers(cast<IntegerType>(TyL)->getBitWidth(), 796 cast<IntegerType>(TyR)->getBitWidth()); 797 case Type::VectorTyID: { 798 VectorType *VTyL = cast<VectorType>(TyL), *VTyR = cast<VectorType>(TyR); 799 if (int Res = cmpNumbers(VTyL->getNumElements(), VTyR->getNumElements())) 800 return Res; 801 return cmpTypes(VTyL->getElementType(), VTyR->getElementType()); 802 } 803 // TyL == TyR would have returned true earlier, because types are uniqued. 804 case Type::VoidTyID: 805 case Type::FloatTyID: 806 case Type::DoubleTyID: 807 case Type::X86_FP80TyID: 808 case Type::FP128TyID: 809 case Type::PPC_FP128TyID: 810 case Type::LabelTyID: 811 case Type::MetadataTyID: 812 case Type::TokenTyID: 813 return 0; 814 815 case Type::PointerTyID: { 816 assert(PTyL && PTyR && "Both types must be pointers here."); 817 return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace()); 818 } 819 820 case Type::StructTyID: { 821 StructType *STyL = cast<StructType>(TyL); 822 StructType *STyR = cast<StructType>(TyR); 823 if (STyL->getNumElements() != STyR->getNumElements()) 824 return cmpNumbers(STyL->getNumElements(), STyR->getNumElements()); 825 826 if (STyL->isPacked() != STyR->isPacked()) 827 return cmpNumbers(STyL->isPacked(), STyR->isPacked()); 828 829 for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) { 830 if (int Res = cmpTypes(STyL->getElementType(i), STyR->getElementType(i))) 831 return Res; 832 } 833 return 0; 834 } 835 836 case Type::FunctionTyID: { 837 FunctionType *FTyL = cast<FunctionType>(TyL); 838 FunctionType *FTyR = cast<FunctionType>(TyR); 839 if (FTyL->getNumParams() != FTyR->getNumParams()) 840 return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams()); 841 842 if (FTyL->isVarArg() != FTyR->isVarArg()) 843 return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg()); 844 845 if (int Res = cmpTypes(FTyL->getReturnType(), FTyR->getReturnType())) 846 return Res; 847 848 for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) { 849 if (int Res = cmpTypes(FTyL->getParamType(i), FTyR->getParamType(i))) 850 return Res; 851 } 852 return 0; 853 } 854 855 case Type::ArrayTyID: { 856 ArrayType *ATyL = cast<ArrayType>(TyL); 857 ArrayType *ATyR = cast<ArrayType>(TyR); 858 if (ATyL->getNumElements() != ATyR->getNumElements()) 859 return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements()); 860 return cmpTypes(ATyL->getElementType(), ATyR->getElementType()); 861 } 862 } 863 } 864 865 // Determine whether the two operations are the same except that pointer-to-A 866 // and pointer-to-B are equivalent. This should be kept in sync with 867 // Instruction::isSameOperationAs. 868 // Read method declaration comments for more details. 869 int FunctionComparator::cmpOperations(const Instruction *L, 870 const Instruction *R) const { 871 // Differences from Instruction::isSameOperationAs: 872 // * replace type comparison with calls to isEquivalentType. 873 // * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top 874 // * because of the above, we don't test for the tail bit on calls later on 875 if (int Res = cmpNumbers(L->getOpcode(), R->getOpcode())) 876 return Res; 877 878 if (int Res = cmpNumbers(L->getNumOperands(), R->getNumOperands())) 879 return Res; 880 881 if (int Res = cmpTypes(L->getType(), R->getType())) 882 return Res; 883 884 if (int Res = cmpNumbers(L->getRawSubclassOptionalData(), 885 R->getRawSubclassOptionalData())) 886 return Res; 887 888 if (const AllocaInst *AI = dyn_cast<AllocaInst>(L)) { 889 if (int Res = cmpTypes(AI->getAllocatedType(), 890 cast<AllocaInst>(R)->getAllocatedType())) 891 return Res; 892 if (int Res = 893 cmpNumbers(AI->getAlignment(), cast<AllocaInst>(R)->getAlignment())) 894 return Res; 895 } 896 897 // We have two instructions of identical opcode and #operands. Check to see 898 // if all operands are the same type 899 for (unsigned i = 0, e = L->getNumOperands(); i != e; ++i) { 900 if (int Res = 901 cmpTypes(L->getOperand(i)->getType(), R->getOperand(i)->getType())) 902 return Res; 903 } 904 905 // Check special state that is a part of some instructions. 906 if (const LoadInst *LI = dyn_cast<LoadInst>(L)) { 907 if (int Res = cmpNumbers(LI->isVolatile(), cast<LoadInst>(R)->isVolatile())) 908 return Res; 909 if (int Res = 910 cmpNumbers(LI->getAlignment(), cast<LoadInst>(R)->getAlignment())) 911 return Res; 912 if (int Res = 913 cmpNumbers(LI->getOrdering(), cast<LoadInst>(R)->getOrdering())) 914 return Res; 915 if (int Res = 916 cmpNumbers(LI->getSynchScope(), cast<LoadInst>(R)->getSynchScope())) 917 return Res; 918 return cmpRangeMetadata(LI->getMetadata(LLVMContext::MD_range), 919 cast<LoadInst>(R)->getMetadata(LLVMContext::MD_range)); 920 } 921 if (const StoreInst *SI = dyn_cast<StoreInst>(L)) { 922 if (int Res = 923 cmpNumbers(SI->isVolatile(), cast<StoreInst>(R)->isVolatile())) 924 return Res; 925 if (int Res = 926 cmpNumbers(SI->getAlignment(), cast<StoreInst>(R)->getAlignment())) 927 return Res; 928 if (int Res = 929 cmpNumbers(SI->getOrdering(), cast<StoreInst>(R)->getOrdering())) 930 return Res; 931 return cmpNumbers(SI->getSynchScope(), cast<StoreInst>(R)->getSynchScope()); 932 } 933 if (const CmpInst *CI = dyn_cast<CmpInst>(L)) 934 return cmpNumbers(CI->getPredicate(), cast<CmpInst>(R)->getPredicate()); 935 if (const CallInst *CI = dyn_cast<CallInst>(L)) { 936 if (int Res = cmpNumbers(CI->getCallingConv(), 937 cast<CallInst>(R)->getCallingConv())) 938 return Res; 939 if (int Res = 940 cmpAttrs(CI->getAttributes(), cast<CallInst>(R)->getAttributes())) 941 return Res; 942 return cmpRangeMetadata( 943 CI->getMetadata(LLVMContext::MD_range), 944 cast<CallInst>(R)->getMetadata(LLVMContext::MD_range)); 945 } 946 if (const InvokeInst *CI = dyn_cast<InvokeInst>(L)) { 947 if (int Res = cmpNumbers(CI->getCallingConv(), 948 cast<InvokeInst>(R)->getCallingConv())) 949 return Res; 950 if (int Res = 951 cmpAttrs(CI->getAttributes(), cast<InvokeInst>(R)->getAttributes())) 952 return Res; 953 return cmpRangeMetadata( 954 CI->getMetadata(LLVMContext::MD_range), 955 cast<InvokeInst>(R)->getMetadata(LLVMContext::MD_range)); 956 } 957 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(L)) { 958 ArrayRef<unsigned> LIndices = IVI->getIndices(); 959 ArrayRef<unsigned> RIndices = cast<InsertValueInst>(R)->getIndices(); 960 if (int Res = cmpNumbers(LIndices.size(), RIndices.size())) 961 return Res; 962 for (size_t i = 0, e = LIndices.size(); i != e; ++i) { 963 if (int Res = cmpNumbers(LIndices[i], RIndices[i])) 964 return Res; 965 } 966 } 967 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(L)) { 968 ArrayRef<unsigned> LIndices = EVI->getIndices(); 969 ArrayRef<unsigned> RIndices = cast<ExtractValueInst>(R)->getIndices(); 970 if (int Res = cmpNumbers(LIndices.size(), RIndices.size())) 971 return Res; 972 for (size_t i = 0, e = LIndices.size(); i != e; ++i) { 973 if (int Res = cmpNumbers(LIndices[i], RIndices[i])) 974 return Res; 975 } 976 } 977 if (const FenceInst *FI = dyn_cast<FenceInst>(L)) { 978 if (int Res = 979 cmpNumbers(FI->getOrdering(), cast<FenceInst>(R)->getOrdering())) 980 return Res; 981 return cmpNumbers(FI->getSynchScope(), cast<FenceInst>(R)->getSynchScope()); 982 } 983 984 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(L)) { 985 if (int Res = cmpNumbers(CXI->isVolatile(), 986 cast<AtomicCmpXchgInst>(R)->isVolatile())) 987 return Res; 988 if (int Res = cmpNumbers(CXI->isWeak(), 989 cast<AtomicCmpXchgInst>(R)->isWeak())) 990 return Res; 991 if (int Res = cmpNumbers(CXI->getSuccessOrdering(), 992 cast<AtomicCmpXchgInst>(R)->getSuccessOrdering())) 993 return Res; 994 if (int Res = cmpNumbers(CXI->getFailureOrdering(), 995 cast<AtomicCmpXchgInst>(R)->getFailureOrdering())) 996 return Res; 997 return cmpNumbers(CXI->getSynchScope(), 998 cast<AtomicCmpXchgInst>(R)->getSynchScope()); 999 } 1000 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(L)) { 1001 if (int Res = cmpNumbers(RMWI->getOperation(), 1002 cast<AtomicRMWInst>(R)->getOperation())) 1003 return Res; 1004 if (int Res = cmpNumbers(RMWI->isVolatile(), 1005 cast<AtomicRMWInst>(R)->isVolatile())) 1006 return Res; 1007 if (int Res = cmpNumbers(RMWI->getOrdering(), 1008 cast<AtomicRMWInst>(R)->getOrdering())) 1009 return Res; 1010 return cmpNumbers(RMWI->getSynchScope(), 1011 cast<AtomicRMWInst>(R)->getSynchScope()); 1012 } 1013 return 0; 1014 } 1015 1016 // Determine whether two GEP operations perform the same underlying arithmetic. 1017 // Read method declaration comments for more details. 1018 int FunctionComparator::cmpGEPs(const GEPOperator *GEPL, 1019 const GEPOperator *GEPR) { 1020 1021 unsigned int ASL = GEPL->getPointerAddressSpace(); 1022 unsigned int ASR = GEPR->getPointerAddressSpace(); 1023 1024 if (int Res = cmpNumbers(ASL, ASR)) 1025 return Res; 1026 1027 // When we have target data, we can reduce the GEP down to the value in bytes 1028 // added to the address. 1029 const DataLayout &DL = FnL->getParent()->getDataLayout(); 1030 unsigned BitWidth = DL.getPointerSizeInBits(ASL); 1031 APInt OffsetL(BitWidth, 0), OffsetR(BitWidth, 0); 1032 if (GEPL->accumulateConstantOffset(DL, OffsetL) && 1033 GEPR->accumulateConstantOffset(DL, OffsetR)) 1034 return cmpAPInts(OffsetL, OffsetR); 1035 if (int Res = cmpTypes(GEPL->getSourceElementType(), 1036 GEPR->getSourceElementType())) 1037 return Res; 1038 1039 if (int Res = cmpNumbers(GEPL->getNumOperands(), GEPR->getNumOperands())) 1040 return Res; 1041 1042 for (unsigned i = 0, e = GEPL->getNumOperands(); i != e; ++i) { 1043 if (int Res = cmpValues(GEPL->getOperand(i), GEPR->getOperand(i))) 1044 return Res; 1045 } 1046 1047 return 0; 1048 } 1049 1050 int FunctionComparator::cmpInlineAsm(const InlineAsm *L, 1051 const InlineAsm *R) const { 1052 // InlineAsm's are uniqued. If they are the same pointer, obviously they are 1053 // the same, otherwise compare the fields. 1054 if (L == R) 1055 return 0; 1056 if (int Res = cmpTypes(L->getFunctionType(), R->getFunctionType())) 1057 return Res; 1058 if (int Res = cmpMem(L->getAsmString(), R->getAsmString())) 1059 return Res; 1060 if (int Res = cmpMem(L->getConstraintString(), R->getConstraintString())) 1061 return Res; 1062 if (int Res = cmpNumbers(L->hasSideEffects(), R->hasSideEffects())) 1063 return Res; 1064 if (int Res = cmpNumbers(L->isAlignStack(), R->isAlignStack())) 1065 return Res; 1066 if (int Res = cmpNumbers(L->getDialect(), R->getDialect())) 1067 return Res; 1068 llvm_unreachable("InlineAsm blocks were not uniqued."); 1069 return 0; 1070 } 1071 1072 /// Compare two values used by the two functions under pair-wise comparison. If 1073 /// this is the first time the values are seen, they're added to the mapping so 1074 /// that we will detect mismatches on next use. 1075 /// See comments in declaration for more details. 1076 int FunctionComparator::cmpValues(const Value *L, const Value *R) { 1077 // Catch self-reference case. 1078 if (L == FnL) { 1079 if (R == FnR) 1080 return 0; 1081 return -1; 1082 } 1083 if (R == FnR) { 1084 if (L == FnL) 1085 return 0; 1086 return 1; 1087 } 1088 1089 const Constant *ConstL = dyn_cast<Constant>(L); 1090 const Constant *ConstR = dyn_cast<Constant>(R); 1091 if (ConstL && ConstR) { 1092 if (L == R) 1093 return 0; 1094 return cmpConstants(ConstL, ConstR); 1095 } 1096 1097 if (ConstL) 1098 return 1; 1099 if (ConstR) 1100 return -1; 1101 1102 const InlineAsm *InlineAsmL = dyn_cast<InlineAsm>(L); 1103 const InlineAsm *InlineAsmR = dyn_cast<InlineAsm>(R); 1104 1105 if (InlineAsmL && InlineAsmR) 1106 return cmpInlineAsm(InlineAsmL, InlineAsmR); 1107 if (InlineAsmL) 1108 return 1; 1109 if (InlineAsmR) 1110 return -1; 1111 1112 auto LeftSN = sn_mapL.insert(std::make_pair(L, sn_mapL.size())), 1113 RightSN = sn_mapR.insert(std::make_pair(R, sn_mapR.size())); 1114 1115 return cmpNumbers(LeftSN.first->second, RightSN.first->second); 1116 } 1117 // Test whether two basic blocks have equivalent behaviour. 1118 int FunctionComparator::cmpBasicBlocks(const BasicBlock *BBL, 1119 const BasicBlock *BBR) { 1120 BasicBlock::const_iterator InstL = BBL->begin(), InstLE = BBL->end(); 1121 BasicBlock::const_iterator InstR = BBR->begin(), InstRE = BBR->end(); 1122 1123 do { 1124 if (int Res = cmpValues(&*InstL, &*InstR)) 1125 return Res; 1126 1127 const GetElementPtrInst *GEPL = dyn_cast<GetElementPtrInst>(InstL); 1128 const GetElementPtrInst *GEPR = dyn_cast<GetElementPtrInst>(InstR); 1129 1130 if (GEPL && !GEPR) 1131 return 1; 1132 if (GEPR && !GEPL) 1133 return -1; 1134 1135 if (GEPL && GEPR) { 1136 if (int Res = 1137 cmpValues(GEPL->getPointerOperand(), GEPR->getPointerOperand())) 1138 return Res; 1139 if (int Res = cmpGEPs(GEPL, GEPR)) 1140 return Res; 1141 } else { 1142 if (int Res = cmpOperations(&*InstL, &*InstR)) 1143 return Res; 1144 assert(InstL->getNumOperands() == InstR->getNumOperands()); 1145 1146 for (unsigned i = 0, e = InstL->getNumOperands(); i != e; ++i) { 1147 Value *OpL = InstL->getOperand(i); 1148 Value *OpR = InstR->getOperand(i); 1149 if (int Res = cmpValues(OpL, OpR)) 1150 return Res; 1151 // cmpValues should ensure this is true. 1152 assert(cmpTypes(OpL->getType(), OpR->getType()) == 0); 1153 } 1154 } 1155 1156 ++InstL, ++InstR; 1157 } while (InstL != InstLE && InstR != InstRE); 1158 1159 if (InstL != InstLE && InstR == InstRE) 1160 return 1; 1161 if (InstL == InstLE && InstR != InstRE) 1162 return -1; 1163 return 0; 1164 } 1165 1166 // Test whether the two functions have equivalent behaviour. 1167 int FunctionComparator::compare() { 1168 sn_mapL.clear(); 1169 sn_mapR.clear(); 1170 1171 if (int Res = cmpAttrs(FnL->getAttributes(), FnR->getAttributes())) 1172 return Res; 1173 1174 if (int Res = cmpNumbers(FnL->hasGC(), FnR->hasGC())) 1175 return Res; 1176 1177 if (FnL->hasGC()) { 1178 if (int Res = cmpMem(FnL->getGC(), FnR->getGC())) 1179 return Res; 1180 } 1181 1182 if (int Res = cmpNumbers(FnL->hasSection(), FnR->hasSection())) 1183 return Res; 1184 1185 if (FnL->hasSection()) { 1186 if (int Res = cmpMem(FnL->getSection(), FnR->getSection())) 1187 return Res; 1188 } 1189 1190 if (int Res = cmpNumbers(FnL->isVarArg(), FnR->isVarArg())) 1191 return Res; 1192 1193 // TODO: if it's internal and only used in direct calls, we could handle this 1194 // case too. 1195 if (int Res = cmpNumbers(FnL->getCallingConv(), FnR->getCallingConv())) 1196 return Res; 1197 1198 if (int Res = cmpTypes(FnL->getFunctionType(), FnR->getFunctionType())) 1199 return Res; 1200 1201 assert(FnL->arg_size() == FnR->arg_size() && 1202 "Identically typed functions have different numbers of args!"); 1203 1204 // Visit the arguments so that they get enumerated in the order they're 1205 // passed in. 1206 for (Function::const_arg_iterator ArgLI = FnL->arg_begin(), 1207 ArgRI = FnR->arg_begin(), 1208 ArgLE = FnL->arg_end(); 1209 ArgLI != ArgLE; ++ArgLI, ++ArgRI) { 1210 if (cmpValues(&*ArgLI, &*ArgRI) != 0) 1211 llvm_unreachable("Arguments repeat!"); 1212 } 1213 1214 // We do a CFG-ordered walk since the actual ordering of the blocks in the 1215 // linked list is immaterial. Our walk starts at the entry block for both 1216 // functions, then takes each block from each terminator in order. As an 1217 // artifact, this also means that unreachable blocks are ignored. 1218 SmallVector<const BasicBlock *, 8> FnLBBs, FnRBBs; 1219 SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1. 1220 1221 FnLBBs.push_back(&FnL->getEntryBlock()); 1222 FnRBBs.push_back(&FnR->getEntryBlock()); 1223 1224 VisitedBBs.insert(FnLBBs[0]); 1225 while (!FnLBBs.empty()) { 1226 const BasicBlock *BBL = FnLBBs.pop_back_val(); 1227 const BasicBlock *BBR = FnRBBs.pop_back_val(); 1228 1229 if (int Res = cmpValues(BBL, BBR)) 1230 return Res; 1231 1232 if (int Res = cmpBasicBlocks(BBL, BBR)) 1233 return Res; 1234 1235 const TerminatorInst *TermL = BBL->getTerminator(); 1236 const TerminatorInst *TermR = BBR->getTerminator(); 1237 1238 assert(TermL->getNumSuccessors() == TermR->getNumSuccessors()); 1239 for (unsigned i = 0, e = TermL->getNumSuccessors(); i != e; ++i) { 1240 if (!VisitedBBs.insert(TermL->getSuccessor(i)).second) 1241 continue; 1242 1243 FnLBBs.push_back(TermL->getSuccessor(i)); 1244 FnRBBs.push_back(TermR->getSuccessor(i)); 1245 } 1246 } 1247 return 0; 1248 } 1249 1250 // Accumulate the hash of a sequence of 64-bit integers. This is similar to a 1251 // hash of a sequence of 64bit ints, but the entire input does not need to be 1252 // available at once. This interface is necessary for functionHash because it 1253 // needs to accumulate the hash as the structure of the function is traversed 1254 // without saving these values to an intermediate buffer. This form of hashing 1255 // is not often needed, as usually the object to hash is just read from a 1256 // buffer. 1257 class HashAccumulator64 { 1258 uint64_t Hash; 1259 public: 1260 // Initialize to random constant, so the state isn't zero. 1261 HashAccumulator64() { Hash = 0x6acaa36bef8325c5ULL; } 1262 void add(uint64_t V) { 1263 Hash = llvm::hashing::detail::hash_16_bytes(Hash, V); 1264 } 1265 // No finishing is required, because the entire hash value is used. 1266 uint64_t getHash() { return Hash; } 1267 }; 1268 1269 // A function hash is calculated by considering only the number of arguments and 1270 // whether a function is varargs, the order of basic blocks (given by the 1271 // successors of each basic block in depth first order), and the order of 1272 // opcodes of each instruction within each of these basic blocks. This mirrors 1273 // the strategy compare() uses to compare functions by walking the BBs in depth 1274 // first order and comparing each instruction in sequence. Because this hash 1275 // does not look at the operands, it is insensitive to things such as the 1276 // target of calls and the constants used in the function, which makes it useful 1277 // when possibly merging functions which are the same modulo constants and call 1278 // targets. 1279 FunctionComparator::FunctionHash FunctionComparator::functionHash(Function &F) { 1280 HashAccumulator64 H; 1281 H.add(F.isVarArg()); 1282 H.add(F.arg_size()); 1283 1284 SmallVector<const BasicBlock *, 8> BBs; 1285 SmallSet<const BasicBlock *, 16> VisitedBBs; 1286 1287 // Walk the blocks in the same order as FunctionComparator::cmpBasicBlocks(), 1288 // accumulating the hash of the function "structure." (BB and opcode sequence) 1289 BBs.push_back(&F.getEntryBlock()); 1290 VisitedBBs.insert(BBs[0]); 1291 while (!BBs.empty()) { 1292 const BasicBlock *BB = BBs.pop_back_val(); 1293 // This random value acts as a block header, as otherwise the partition of 1294 // opcodes into BBs wouldn't affect the hash, only the order of the opcodes 1295 H.add(45798); 1296 for (auto &Inst : *BB) { 1297 H.add(Inst.getOpcode()); 1298 } 1299 const TerminatorInst *Term = BB->getTerminator(); 1300 for (unsigned i = 0, e = Term->getNumSuccessors(); i != e; ++i) { 1301 if (!VisitedBBs.insert(Term->getSuccessor(i)).second) 1302 continue; 1303 BBs.push_back(Term->getSuccessor(i)); 1304 } 1305 } 1306 return H.getHash(); 1307 } 1308 1309 1310 namespace { 1311 1312 /// MergeFunctions finds functions which will generate identical machine code, 1313 /// by considering all pointer types to be equivalent. Once identified, 1314 /// MergeFunctions will fold them by replacing a call to one to a call to a 1315 /// bitcast of the other. 1316 /// 1317 class MergeFunctions : public ModulePass { 1318 public: 1319 static char ID; 1320 MergeFunctions() 1321 : ModulePass(ID), FnTree(FunctionNodeCmp(&GlobalNumbers)), FNodesInTree(), 1322 HasGlobalAliases(false) { 1323 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry()); 1324 } 1325 1326 bool runOnModule(Module &M) override; 1327 1328 private: 1329 // The function comparison operator is provided here so that FunctionNodes do 1330 // not need to become larger with another pointer. 1331 class FunctionNodeCmp { 1332 GlobalNumberState* GlobalNumbers; 1333 public: 1334 FunctionNodeCmp(GlobalNumberState* GN) : GlobalNumbers(GN) {} 1335 bool operator()(const FunctionNode &LHS, const FunctionNode &RHS) const { 1336 // Order first by hashes, then full function comparison. 1337 if (LHS.getHash() != RHS.getHash()) 1338 return LHS.getHash() < RHS.getHash(); 1339 FunctionComparator FCmp(LHS.getFunc(), RHS.getFunc(), GlobalNumbers); 1340 return FCmp.compare() == -1; 1341 } 1342 }; 1343 typedef std::set<FunctionNode, FunctionNodeCmp> FnTreeType; 1344 1345 GlobalNumberState GlobalNumbers; 1346 1347 /// A work queue of functions that may have been modified and should be 1348 /// analyzed again. 1349 std::vector<WeakVH> Deferred; 1350 1351 /// Checks the rules of order relation introduced among functions set. 1352 /// Returns true, if sanity check has been passed, and false if failed. 1353 bool doSanityCheck(std::vector<WeakVH> &Worklist); 1354 1355 /// Insert a ComparableFunction into the FnTree, or merge it away if it's 1356 /// equal to one that's already present. 1357 bool insert(Function *NewFunction); 1358 1359 /// Remove a Function from the FnTree and queue it up for a second sweep of 1360 /// analysis. 1361 void remove(Function *F); 1362 1363 /// Find the functions that use this Value and remove them from FnTree and 1364 /// queue the functions. 1365 void removeUsers(Value *V); 1366 1367 /// Replace all direct calls of Old with calls of New. Will bitcast New if 1368 /// necessary to make types match. 1369 void replaceDirectCallers(Function *Old, Function *New); 1370 1371 /// Merge two equivalent functions. Upon completion, G may be deleted, or may 1372 /// be converted into a thunk. In either case, it should never be visited 1373 /// again. 1374 void mergeTwoFunctions(Function *F, Function *G); 1375 1376 /// Replace G with a thunk or an alias to F. Deletes G. 1377 void writeThunkOrAlias(Function *F, Function *G); 1378 1379 /// Replace G with a simple tail call to bitcast(F). Also replace direct uses 1380 /// of G with bitcast(F). Deletes G. 1381 void writeThunk(Function *F, Function *G); 1382 1383 /// Replace G with an alias to F. Deletes G. 1384 void writeAlias(Function *F, Function *G); 1385 1386 /// Replace function F with function G in the function tree. 1387 void replaceFunctionInTree(const FunctionNode &FN, Function *G); 1388 1389 /// The set of all distinct functions. Use the insert() and remove() methods 1390 /// to modify it. The map allows efficient lookup and deferring of Functions. 1391 FnTreeType FnTree; 1392 // Map functions to the iterators of the FunctionNode which contains them 1393 // in the FnTree. This must be updated carefully whenever the FnTree is 1394 // modified, i.e. in insert(), remove(), and replaceFunctionInTree(), to avoid 1395 // dangling iterators into FnTree. The invariant that preserves this is that 1396 // there is exactly one mapping F -> FN for each FunctionNode FN in FnTree. 1397 ValueMap<Function*, FnTreeType::iterator> FNodesInTree; 1398 1399 /// Whether or not the target supports global aliases. 1400 bool HasGlobalAliases; 1401 }; 1402 1403 } // end anonymous namespace 1404 1405 char MergeFunctions::ID = 0; 1406 INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false) 1407 1408 ModulePass *llvm::createMergeFunctionsPass() { 1409 return new MergeFunctions(); 1410 } 1411 1412 bool MergeFunctions::doSanityCheck(std::vector<WeakVH> &Worklist) { 1413 if (const unsigned Max = NumFunctionsForSanityCheck) { 1414 unsigned TripleNumber = 0; 1415 bool Valid = true; 1416 1417 dbgs() << "MERGEFUNC-SANITY: Started for first " << Max << " functions.\n"; 1418 1419 unsigned i = 0; 1420 for (std::vector<WeakVH>::iterator I = Worklist.begin(), E = Worklist.end(); 1421 I != E && i < Max; ++I, ++i) { 1422 unsigned j = i; 1423 for (std::vector<WeakVH>::iterator J = I; J != E && j < Max; ++J, ++j) { 1424 Function *F1 = cast<Function>(*I); 1425 Function *F2 = cast<Function>(*J); 1426 int Res1 = FunctionComparator(F1, F2, &GlobalNumbers).compare(); 1427 int Res2 = FunctionComparator(F2, F1, &GlobalNumbers).compare(); 1428 1429 // If F1 <= F2, then F2 >= F1, otherwise report failure. 1430 if (Res1 != -Res2) { 1431 dbgs() << "MERGEFUNC-SANITY: Non-symmetric; triple: " << TripleNumber 1432 << "\n"; 1433 F1->dump(); 1434 F2->dump(); 1435 Valid = false; 1436 } 1437 1438 if (Res1 == 0) 1439 continue; 1440 1441 unsigned k = j; 1442 for (std::vector<WeakVH>::iterator K = J; K != E && k < Max; 1443 ++k, ++K, ++TripleNumber) { 1444 if (K == J) 1445 continue; 1446 1447 Function *F3 = cast<Function>(*K); 1448 int Res3 = FunctionComparator(F1, F3, &GlobalNumbers).compare(); 1449 int Res4 = FunctionComparator(F2, F3, &GlobalNumbers).compare(); 1450 1451 bool Transitive = true; 1452 1453 if (Res1 != 0 && Res1 == Res4) { 1454 // F1 > F2, F2 > F3 => F1 > F3 1455 Transitive = Res3 == Res1; 1456 } else if (Res3 != 0 && Res3 == -Res4) { 1457 // F1 > F3, F3 > F2 => F1 > F2 1458 Transitive = Res3 == Res1; 1459 } else if (Res4 != 0 && -Res3 == Res4) { 1460 // F2 > F3, F3 > F1 => F2 > F1 1461 Transitive = Res4 == -Res1; 1462 } 1463 1464 if (!Transitive) { 1465 dbgs() << "MERGEFUNC-SANITY: Non-transitive; triple: " 1466 << TripleNumber << "\n"; 1467 dbgs() << "Res1, Res3, Res4: " << Res1 << ", " << Res3 << ", " 1468 << Res4 << "\n"; 1469 F1->dump(); 1470 F2->dump(); 1471 F3->dump(); 1472 Valid = false; 1473 } 1474 } 1475 } 1476 } 1477 1478 dbgs() << "MERGEFUNC-SANITY: " << (Valid ? "Passed." : "Failed.") << "\n"; 1479 return Valid; 1480 } 1481 return true; 1482 } 1483 1484 bool MergeFunctions::runOnModule(Module &M) { 1485 bool Changed = false; 1486 1487 // All functions in the module, ordered by hash. Functions with a unique 1488 // hash value are easily eliminated. 1489 std::vector<std::pair<FunctionComparator::FunctionHash, Function *>> 1490 HashedFuncs; 1491 for (Function &Func : M) { 1492 if (!Func.isDeclaration() && !Func.hasAvailableExternallyLinkage()) { 1493 HashedFuncs.push_back({FunctionComparator::functionHash(Func), &Func}); 1494 } 1495 } 1496 1497 std::stable_sort( 1498 HashedFuncs.begin(), HashedFuncs.end(), 1499 [](const std::pair<FunctionComparator::FunctionHash, Function *> &a, 1500 const std::pair<FunctionComparator::FunctionHash, Function *> &b) { 1501 return a.first < b.first; 1502 }); 1503 1504 auto S = HashedFuncs.begin(); 1505 for (auto I = HashedFuncs.begin(), IE = HashedFuncs.end(); I != IE; ++I) { 1506 // If the hash value matches the previous value or the next one, we must 1507 // consider merging it. Otherwise it is dropped and never considered again. 1508 if ((I != S && std::prev(I)->first == I->first) || 1509 (std::next(I) != IE && std::next(I)->first == I->first) ) { 1510 Deferred.push_back(WeakVH(I->second)); 1511 } 1512 } 1513 1514 do { 1515 std::vector<WeakVH> Worklist; 1516 Deferred.swap(Worklist); 1517 1518 DEBUG(doSanityCheck(Worklist)); 1519 1520 DEBUG(dbgs() << "size of module: " << M.size() << '\n'); 1521 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n'); 1522 1523 // Insert only strong functions and merge them. Strong function merging 1524 // always deletes one of them. 1525 for (std::vector<WeakVH>::iterator I = Worklist.begin(), 1526 E = Worklist.end(); I != E; ++I) { 1527 if (!*I) continue; 1528 Function *F = cast<Function>(*I); 1529 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() && 1530 !F->mayBeOverridden()) { 1531 Changed |= insert(F); 1532 } 1533 } 1534 1535 // Insert only weak functions and merge them. By doing these second we 1536 // create thunks to the strong function when possible. When two weak 1537 // functions are identical, we create a new strong function with two weak 1538 // weak thunks to it which are identical but not mergable. 1539 for (std::vector<WeakVH>::iterator I = Worklist.begin(), 1540 E = Worklist.end(); I != E; ++I) { 1541 if (!*I) continue; 1542 Function *F = cast<Function>(*I); 1543 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() && 1544 F->mayBeOverridden()) { 1545 Changed |= insert(F); 1546 } 1547 } 1548 DEBUG(dbgs() << "size of FnTree: " << FnTree.size() << '\n'); 1549 } while (!Deferred.empty()); 1550 1551 FnTree.clear(); 1552 GlobalNumbers.clear(); 1553 1554 return Changed; 1555 } 1556 1557 // Replace direct callers of Old with New. 1558 void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) { 1559 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType()); 1560 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) { 1561 Use *U = &*UI; 1562 ++UI; 1563 CallSite CS(U->getUser()); 1564 if (CS && CS.isCallee(U)) { 1565 // Transfer the called function's attributes to the call site. Due to the 1566 // bitcast we will 'lose' ABI changing attributes because the 'called 1567 // function' is no longer a Function* but the bitcast. Code that looks up 1568 // the attributes from the called function will fail. 1569 1570 // FIXME: This is not actually true, at least not anymore. The callsite 1571 // will always have the same ABI affecting attributes as the callee, 1572 // because otherwise the original input has UB. Note that Old and New 1573 // always have matching ABI, so no attributes need to be changed. 1574 // Transferring other attributes may help other optimizations, but that 1575 // should be done uniformly and not in this ad-hoc way. 1576 auto &Context = New->getContext(); 1577 auto NewFuncAttrs = New->getAttributes(); 1578 auto CallSiteAttrs = CS.getAttributes(); 1579 1580 CallSiteAttrs = CallSiteAttrs.addAttributes( 1581 Context, AttributeSet::ReturnIndex, NewFuncAttrs.getRetAttributes()); 1582 1583 for (unsigned argIdx = 0; argIdx < CS.arg_size(); argIdx++) { 1584 AttributeSet Attrs = NewFuncAttrs.getParamAttributes(argIdx); 1585 if (Attrs.getNumSlots()) 1586 CallSiteAttrs = CallSiteAttrs.addAttributes(Context, argIdx, Attrs); 1587 } 1588 1589 CS.setAttributes(CallSiteAttrs); 1590 1591 remove(CS.getInstruction()->getParent()->getParent()); 1592 U->set(BitcastNew); 1593 } 1594 } 1595 } 1596 1597 // Replace G with an alias to F if possible, or else a thunk to F. Deletes G. 1598 void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) { 1599 if (HasGlobalAliases && G->hasUnnamedAddr()) { 1600 if (G->hasExternalLinkage() || G->hasLocalLinkage() || 1601 G->hasWeakLinkage()) { 1602 writeAlias(F, G); 1603 return; 1604 } 1605 } 1606 1607 writeThunk(F, G); 1608 } 1609 1610 // Helper for writeThunk, 1611 // Selects proper bitcast operation, 1612 // but a bit simpler then CastInst::getCastOpcode. 1613 static Value *createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) { 1614 Type *SrcTy = V->getType(); 1615 if (SrcTy->isStructTy()) { 1616 assert(DestTy->isStructTy()); 1617 assert(SrcTy->getStructNumElements() == DestTy->getStructNumElements()); 1618 Value *Result = UndefValue::get(DestTy); 1619 for (unsigned int I = 0, E = SrcTy->getStructNumElements(); I < E; ++I) { 1620 Value *Element = createCast( 1621 Builder, Builder.CreateExtractValue(V, makeArrayRef(I)), 1622 DestTy->getStructElementType(I)); 1623 1624 Result = 1625 Builder.CreateInsertValue(Result, Element, makeArrayRef(I)); 1626 } 1627 return Result; 1628 } 1629 assert(!DestTy->isStructTy()); 1630 if (SrcTy->isIntegerTy() && DestTy->isPointerTy()) 1631 return Builder.CreateIntToPtr(V, DestTy); 1632 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy()) 1633 return Builder.CreatePtrToInt(V, DestTy); 1634 else 1635 return Builder.CreateBitCast(V, DestTy); 1636 } 1637 1638 // Replace G with a simple tail call to bitcast(F). Also replace direct uses 1639 // of G with bitcast(F). Deletes G. 1640 void MergeFunctions::writeThunk(Function *F, Function *G) { 1641 if (!G->mayBeOverridden()) { 1642 // Redirect direct callers of G to F. 1643 replaceDirectCallers(G, F); 1644 } 1645 1646 // If G was internal then we may have replaced all uses of G with F. If so, 1647 // stop here and delete G. There's no need for a thunk. 1648 if (G->hasLocalLinkage() && G->use_empty()) { 1649 G->eraseFromParent(); 1650 return; 1651 } 1652 1653 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "", 1654 G->getParent()); 1655 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG); 1656 IRBuilder<false> Builder(BB); 1657 1658 SmallVector<Value *, 16> Args; 1659 unsigned i = 0; 1660 FunctionType *FFTy = F->getFunctionType(); 1661 for (Argument & AI : NewG->args()) { 1662 Args.push_back(createCast(Builder, &AI, FFTy->getParamType(i))); 1663 ++i; 1664 } 1665 1666 CallInst *CI = Builder.CreateCall(F, Args); 1667 CI->setTailCall(); 1668 CI->setCallingConv(F->getCallingConv()); 1669 CI->setAttributes(F->getAttributes()); 1670 if (NewG->getReturnType()->isVoidTy()) { 1671 Builder.CreateRetVoid(); 1672 } else { 1673 Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType())); 1674 } 1675 1676 NewG->copyAttributesFrom(G); 1677 NewG->takeName(G); 1678 removeUsers(G); 1679 G->replaceAllUsesWith(NewG); 1680 G->eraseFromParent(); 1681 1682 DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n'); 1683 ++NumThunksWritten; 1684 } 1685 1686 // Replace G with an alias to F and delete G. 1687 void MergeFunctions::writeAlias(Function *F, Function *G) { 1688 auto *GA = GlobalAlias::create(G->getLinkage(), "", F); 1689 F->setAlignment(std::max(F->getAlignment(), G->getAlignment())); 1690 GA->takeName(G); 1691 GA->setVisibility(G->getVisibility()); 1692 removeUsers(G); 1693 G->replaceAllUsesWith(GA); 1694 G->eraseFromParent(); 1695 1696 DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n'); 1697 ++NumAliasesWritten; 1698 } 1699 1700 // Merge two equivalent functions. Upon completion, Function G is deleted. 1701 void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) { 1702 if (F->mayBeOverridden()) { 1703 assert(G->mayBeOverridden()); 1704 1705 // Make them both thunks to the same internal function. 1706 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "", 1707 F->getParent()); 1708 H->copyAttributesFrom(F); 1709 H->takeName(F); 1710 removeUsers(F); 1711 F->replaceAllUsesWith(H); 1712 1713 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment()); 1714 1715 if (HasGlobalAliases) { 1716 writeAlias(F, G); 1717 writeAlias(F, H); 1718 } else { 1719 writeThunk(F, G); 1720 writeThunk(F, H); 1721 } 1722 1723 F->setAlignment(MaxAlignment); 1724 F->setLinkage(GlobalValue::PrivateLinkage); 1725 ++NumDoubleWeak; 1726 } else { 1727 writeThunkOrAlias(F, G); 1728 } 1729 1730 ++NumFunctionsMerged; 1731 } 1732 1733 /// Replace function F by function G. 1734 void MergeFunctions::replaceFunctionInTree(const FunctionNode &FN, 1735 Function *G) { 1736 Function *F = FN.getFunc(); 1737 assert(FunctionComparator(F, G, &GlobalNumbers).compare() == 0 && 1738 "The two functions must be equal"); 1739 1740 auto I = FNodesInTree.find(F); 1741 assert(I != FNodesInTree.end() && "F should be in FNodesInTree"); 1742 assert(FNodesInTree.count(G) == 0 && "FNodesInTree should not contain G"); 1743 1744 FnTreeType::iterator IterToFNInFnTree = I->second; 1745 assert(&(*IterToFNInFnTree) == &FN && "F should map to FN in FNodesInTree."); 1746 // Remove F -> FN and insert G -> FN 1747 FNodesInTree.erase(I); 1748 FNodesInTree.insert({G, IterToFNInFnTree}); 1749 // Replace F with G in FN, which is stored inside the FnTree. 1750 FN.replaceBy(G); 1751 } 1752 1753 // Insert a ComparableFunction into the FnTree, or merge it away if equal to one 1754 // that was already inserted. 1755 bool MergeFunctions::insert(Function *NewFunction) { 1756 std::pair<FnTreeType::iterator, bool> Result = 1757 FnTree.insert(FunctionNode(NewFunction)); 1758 1759 if (Result.second) { 1760 assert(FNodesInTree.count(NewFunction) == 0); 1761 FNodesInTree.insert({NewFunction, Result.first}); 1762 DEBUG(dbgs() << "Inserting as unique: " << NewFunction->getName() << '\n'); 1763 return false; 1764 } 1765 1766 const FunctionNode &OldF = *Result.first; 1767 1768 // Don't merge tiny functions, since it can just end up making the function 1769 // larger. 1770 // FIXME: Should still merge them if they are unnamed_addr and produce an 1771 // alias. 1772 if (NewFunction->size() == 1) { 1773 if (NewFunction->front().size() <= 2) { 1774 DEBUG(dbgs() << NewFunction->getName() 1775 << " is to small to bother merging\n"); 1776 return false; 1777 } 1778 } 1779 1780 // Impose a total order (by name) on the replacement of functions. This is 1781 // important when operating on more than one module independently to prevent 1782 // cycles of thunks calling each other when the modules are linked together. 1783 // 1784 // When one function is weak and the other is strong there is an order imposed 1785 // already. We process strong functions before weak functions. 1786 if ((OldF.getFunc()->mayBeOverridden() && NewFunction->mayBeOverridden()) || 1787 (!OldF.getFunc()->mayBeOverridden() && !NewFunction->mayBeOverridden())) 1788 if (OldF.getFunc()->getName() > NewFunction->getName()) { 1789 // Swap the two functions. 1790 Function *F = OldF.getFunc(); 1791 replaceFunctionInTree(*Result.first, NewFunction); 1792 NewFunction = F; 1793 assert(OldF.getFunc() != F && "Must have swapped the functions."); 1794 } 1795 1796 // Never thunk a strong function to a weak function. 1797 assert(!OldF.getFunc()->mayBeOverridden() || NewFunction->mayBeOverridden()); 1798 1799 DEBUG(dbgs() << " " << OldF.getFunc()->getName() 1800 << " == " << NewFunction->getName() << '\n'); 1801 1802 Function *DeleteF = NewFunction; 1803 mergeTwoFunctions(OldF.getFunc(), DeleteF); 1804 return true; 1805 } 1806 1807 // Remove a function from FnTree. If it was already in FnTree, add 1808 // it to Deferred so that we'll look at it in the next round. 1809 void MergeFunctions::remove(Function *F) { 1810 auto I = FNodesInTree.find(F); 1811 if (I != FNodesInTree.end()) { 1812 DEBUG(dbgs() << "Deferred " << F->getName()<< ".\n"); 1813 FnTree.erase(I->second); 1814 // I->second has been invalidated, remove it from the FNodesInTree map to 1815 // preserve the invariant. 1816 FNodesInTree.erase(I); 1817 Deferred.emplace_back(F); 1818 } 1819 } 1820 1821 // For each instruction used by the value, remove() the function that contains 1822 // the instruction. This should happen right before a call to RAUW. 1823 void MergeFunctions::removeUsers(Value *V) { 1824 std::vector<Value *> Worklist; 1825 Worklist.push_back(V); 1826 SmallSet<Value*, 8> Visited; 1827 Visited.insert(V); 1828 while (!Worklist.empty()) { 1829 Value *V = Worklist.back(); 1830 Worklist.pop_back(); 1831 1832 for (User *U : V->users()) { 1833 if (Instruction *I = dyn_cast<Instruction>(U)) { 1834 remove(I->getParent()->getParent()); 1835 } else if (isa<GlobalValue>(U)) { 1836 // do nothing 1837 } else if (Constant *C = dyn_cast<Constant>(U)) { 1838 for (User *UU : C->users()) { 1839 if (!Visited.insert(UU).second) 1840 Worklist.push_back(UU); 1841 } 1842 } 1843 } 1844 } 1845 } 1846