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