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 // A hash is computed from the function, based on its type and number of 13 // basic blocks. 14 // 15 // Once all hashes are computed, we perform an expensive equality comparison 16 // on each function pair. This takes n^2/2 comparisons per bucket, so it's 17 // important that the hash function be high quality. The equality comparison 18 // iterates through each instruction in each basic block. 19 // 20 // When a match is found the functions are folded. If both functions are 21 // overridable, we move the functionality into a new internal function and 22 // leave two overridable thunks to it. 23 // 24 //===----------------------------------------------------------------------===// 25 // 26 // Future work: 27 // 28 // * virtual functions. 29 // 30 // Many functions have their address taken by the virtual function table for 31 // the object they belong to. However, as long as it's only used for a lookup 32 // and call, this is irrelevant, and we'd like to fold such functions. 33 // 34 // * switch from n^2 pair-wise comparisons to an n-way comparison for each 35 // bucket. 36 // 37 // * be smarter about bitcasts. 38 // 39 // In order to fold functions, we will sometimes add either bitcast instructions 40 // or bitcast constant expressions. Unfortunately, this can confound further 41 // analysis since the two functions differ where one has a bitcast and the 42 // other doesn't. We should learn to look through bitcasts. 43 // 44 //===----------------------------------------------------------------------===// 45 46 #define DEBUG_TYPE "mergefunc" 47 #include "llvm/Transforms/IPO.h" 48 #include "llvm/ADT/DenseSet.h" 49 #include "llvm/ADT/FoldingSet.h" 50 #include "llvm/ADT/STLExtras.h" 51 #include "llvm/ADT/SmallSet.h" 52 #include "llvm/ADT/Statistic.h" 53 #include "llvm/IR/CallSite.h" 54 #include "llvm/IR/Constants.h" 55 #include "llvm/IR/DataLayout.h" 56 #include "llvm/IR/IRBuilder.h" 57 #include "llvm/IR/InlineAsm.h" 58 #include "llvm/IR/Instructions.h" 59 #include "llvm/IR/LLVMContext.h" 60 #include "llvm/IR/Module.h" 61 #include "llvm/IR/Operator.h" 62 #include "llvm/IR/ValueHandle.h" 63 #include "llvm/Pass.h" 64 #include "llvm/Support/Debug.h" 65 #include "llvm/Support/ErrorHandling.h" 66 #include "llvm/Support/raw_ostream.h" 67 #include <vector> 68 using namespace llvm; 69 70 STATISTIC(NumFunctionsMerged, "Number of functions merged"); 71 STATISTIC(NumThunksWritten, "Number of thunks generated"); 72 STATISTIC(NumAliasesWritten, "Number of aliases generated"); 73 STATISTIC(NumDoubleWeak, "Number of new functions created"); 74 75 /// Returns the type id for a type to be hashed. We turn pointer types into 76 /// integers here because the actual compare logic below considers pointers and 77 /// integers of the same size as equal. 78 static Type::TypeID getTypeIDForHash(Type *Ty) { 79 if (Ty->isPointerTy()) 80 return Type::IntegerTyID; 81 return Ty->getTypeID(); 82 } 83 84 /// Creates a hash-code for the function which is the same for any two 85 /// functions that will compare equal, without looking at the instructions 86 /// inside the function. 87 static unsigned profileFunction(const Function *F) { 88 FunctionType *FTy = F->getFunctionType(); 89 90 FoldingSetNodeID ID; 91 ID.AddInteger(F->size()); 92 ID.AddInteger(F->getCallingConv()); 93 ID.AddBoolean(F->hasGC()); 94 ID.AddBoolean(FTy->isVarArg()); 95 ID.AddInteger(getTypeIDForHash(FTy->getReturnType())); 96 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 97 ID.AddInteger(getTypeIDForHash(FTy->getParamType(i))); 98 return ID.ComputeHash(); 99 } 100 101 namespace { 102 103 /// ComparableFunction - A struct that pairs together functions with a 104 /// DataLayout so that we can keep them together as elements in the DenseSet. 105 class ComparableFunction { 106 public: 107 static const ComparableFunction EmptyKey; 108 static const ComparableFunction TombstoneKey; 109 static DataLayout * const LookupOnly; 110 111 ComparableFunction(Function *Func, const DataLayout *DL) 112 : Func(Func), Hash(profileFunction(Func)), DL(DL) {} 113 114 Function *getFunc() const { return Func; } 115 unsigned getHash() const { return Hash; } 116 const DataLayout *getDataLayout() const { return DL; } 117 118 // Drops AssertingVH reference to the function. Outside of debug mode, this 119 // does nothing. 120 void release() { 121 assert(Func && 122 "Attempted to release function twice, or release empty/tombstone!"); 123 Func = NULL; 124 } 125 126 private: 127 explicit ComparableFunction(unsigned Hash) 128 : Func(NULL), Hash(Hash), DL(NULL) {} 129 130 AssertingVH<Function> Func; 131 unsigned Hash; 132 const DataLayout *DL; 133 }; 134 135 const ComparableFunction ComparableFunction::EmptyKey = ComparableFunction(0); 136 const ComparableFunction ComparableFunction::TombstoneKey = 137 ComparableFunction(1); 138 DataLayout *const ComparableFunction::LookupOnly = (DataLayout*)(-1); 139 140 } 141 142 namespace llvm { 143 template <> 144 struct DenseMapInfo<ComparableFunction> { 145 static ComparableFunction getEmptyKey() { 146 return ComparableFunction::EmptyKey; 147 } 148 static ComparableFunction getTombstoneKey() { 149 return ComparableFunction::TombstoneKey; 150 } 151 static unsigned getHashValue(const ComparableFunction &CF) { 152 return CF.getHash(); 153 } 154 static bool isEqual(const ComparableFunction &LHS, 155 const ComparableFunction &RHS); 156 }; 157 } 158 159 namespace { 160 161 /// FunctionComparator - Compares two functions to determine whether or not 162 /// they will generate machine code with the same behaviour. DataLayout is 163 /// used if available. The comparator always fails conservatively (erring on the 164 /// side of claiming that two functions are different). 165 class FunctionComparator { 166 public: 167 FunctionComparator(const DataLayout *DL, const Function *F1, 168 const Function *F2) 169 : F1(F1), F2(F2), DL(DL) {} 170 171 /// Test whether the two functions have equivalent behaviour. 172 bool compare(); 173 174 private: 175 /// Test whether two basic blocks have equivalent behaviour. 176 bool compare(const BasicBlock *BB1, const BasicBlock *BB2); 177 178 /// Assign or look up previously assigned numbers for the two values, and 179 /// return whether the numbers are equal. Numbers are assigned in the order 180 /// visited. 181 bool enumerate(const Value *V1, const Value *V2); 182 183 /// Compare two Instructions for equivalence, similar to 184 /// Instruction::isSameOperationAs but with modifications to the type 185 /// comparison. 186 bool isEquivalentOperation(const Instruction *I1, 187 const Instruction *I2) const; 188 189 /// Compare two GEPs for equivalent pointer arithmetic. 190 bool isEquivalentGEP(const GEPOperator *GEP1, const GEPOperator *GEP2); 191 bool isEquivalentGEP(const GetElementPtrInst *GEP1, 192 const GetElementPtrInst *GEP2) { 193 return isEquivalentGEP(cast<GEPOperator>(GEP1), cast<GEPOperator>(GEP2)); 194 } 195 196 /// cmpType - compares two types, 197 /// defines total ordering among the types set. 198 /// 199 /// Return values: 200 /// 0 if types are equal, 201 /// -1 if Left is less than Right, 202 /// +1 if Left is greater than Right. 203 /// 204 /// Description: 205 /// Comparison is broken onto stages. Like in lexicographical comparison 206 /// stage coming first has higher priority. 207 /// On each explanation stage keep in mind total ordering properties. 208 /// 209 /// 0. Before comparison we coerce pointer types of 0 address space to 210 /// integer. 211 /// We also don't bother with same type at left and right, so 212 /// just return 0 in this case. 213 /// 214 /// 1. If types are of different kind (different type IDs). 215 /// Return result of type IDs comparison, treating them as numbers. 216 /// 2. If types are vectors or integers, compare Type* values as numbers. 217 /// 3. Types has same ID, so check whether they belongs to the next group: 218 /// * Void 219 /// * Float 220 /// * Double 221 /// * X86_FP80 222 /// * FP128 223 /// * PPC_FP128 224 /// * Label 225 /// * Metadata 226 /// If so - return 0, yes - we can treat these types as equal only because 227 /// their IDs are same. 228 /// 4. If Left and Right are pointers, return result of address space 229 /// comparison (numbers comparison). We can treat pointer types of same 230 /// address space as equal. 231 /// 5. If types are complex. 232 /// Then both Left and Right are to be expanded and their element types will 233 /// be checked with the same way. If we get Res != 0 on some stage, return it. 234 /// Otherwise return 0. 235 /// 6. For all other cases put llvm_unreachable. 236 int cmpType(Type *TyL, Type *TyR) const; 237 238 bool isEquivalentType(Type *Ty1, Type *Ty2) const { 239 return cmpType(Ty1, Ty2) == 0; 240 } 241 242 int cmpNumbers(uint64_t L, uint64_t R) const; 243 244 // The two functions undergoing comparison. 245 const Function *F1, *F2; 246 247 const DataLayout *DL; 248 249 DenseMap<const Value *, const Value *> id_map; 250 DenseSet<const Value *> seen_values; 251 }; 252 253 } 254 255 int FunctionComparator::cmpNumbers(uint64_t L, uint64_t R) const { 256 if (L < R) return -1; 257 if (L > R) return 1; 258 return 0; 259 } 260 261 /// cmpType - compares two types, 262 /// defines total ordering among the types set. 263 /// See method declaration comments for more details. 264 int FunctionComparator::cmpType(Type *TyL, Type *TyR) const { 265 266 PointerType *PTyL = dyn_cast<PointerType>(TyL); 267 PointerType *PTyR = dyn_cast<PointerType>(TyR); 268 269 if (DL) { 270 if (PTyL && PTyL->getAddressSpace() == 0) TyL = DL->getIntPtrType(TyL); 271 if (PTyR && PTyR->getAddressSpace() == 0) TyR = DL->getIntPtrType(TyR); 272 } 273 274 if (TyL == TyR) 275 return 0; 276 277 if (int Res = cmpNumbers(TyL->getTypeID(), TyR->getTypeID())) 278 return Res; 279 280 switch (TyL->getTypeID()) { 281 default: 282 llvm_unreachable("Unknown type!"); 283 // Fall through in Release mode. 284 case Type::IntegerTyID: 285 case Type::VectorTyID: 286 // TyL == TyR would have returned true earlier. 287 return cmpNumbers((uint64_t)TyL, (uint64_t)TyR); 288 289 case Type::VoidTyID: 290 case Type::FloatTyID: 291 case Type::DoubleTyID: 292 case Type::X86_FP80TyID: 293 case Type::FP128TyID: 294 case Type::PPC_FP128TyID: 295 case Type::LabelTyID: 296 case Type::MetadataTyID: 297 return 0; 298 299 case Type::PointerTyID: { 300 assert(PTyL && PTyR && "Both types must be pointers here."); 301 return cmpNumbers(PTyL->getAddressSpace(), PTyR->getAddressSpace()); 302 } 303 304 case Type::StructTyID: { 305 StructType *STyL = cast<StructType>(TyL); 306 StructType *STyR = cast<StructType>(TyR); 307 if (STyL->getNumElements() != STyR->getNumElements()) 308 return cmpNumbers(STyL->getNumElements(), STyR->getNumElements()); 309 310 if (STyL->isPacked() != STyR->isPacked()) 311 return cmpNumbers(STyL->isPacked(), STyR->isPacked()); 312 313 for (unsigned i = 0, e = STyL->getNumElements(); i != e; ++i) { 314 if (int Res = cmpType(STyL->getElementType(i), 315 STyR->getElementType(i))) 316 return Res; 317 } 318 return 0; 319 } 320 321 case Type::FunctionTyID: { 322 FunctionType *FTyL = cast<FunctionType>(TyL); 323 FunctionType *FTyR = cast<FunctionType>(TyR); 324 if (FTyL->getNumParams() != FTyR->getNumParams()) 325 return cmpNumbers(FTyL->getNumParams(), FTyR->getNumParams()); 326 327 if (FTyL->isVarArg() != FTyR->isVarArg()) 328 return cmpNumbers(FTyL->isVarArg(), FTyR->isVarArg()); 329 330 if (int Res = cmpType(FTyL->getReturnType(), FTyR->getReturnType())) 331 return Res; 332 333 for (unsigned i = 0, e = FTyL->getNumParams(); i != e; ++i) { 334 if (int Res = cmpType(FTyL->getParamType(i), FTyR->getParamType(i))) 335 return Res; 336 } 337 return 0; 338 } 339 340 case Type::ArrayTyID: { 341 ArrayType *ATyL = cast<ArrayType>(TyL); 342 ArrayType *ATyR = cast<ArrayType>(TyR); 343 if (ATyL->getNumElements() != ATyR->getNumElements()) 344 return cmpNumbers(ATyL->getNumElements(), ATyR->getNumElements()); 345 return cmpType(ATyL->getElementType(), ATyR->getElementType()); 346 } 347 } 348 } 349 350 // Determine whether the two operations are the same except that pointer-to-A 351 // and pointer-to-B are equivalent. This should be kept in sync with 352 // Instruction::isSameOperationAs. 353 bool FunctionComparator::isEquivalentOperation(const Instruction *I1, 354 const Instruction *I2) const { 355 // Differences from Instruction::isSameOperationAs: 356 // * replace type comparison with calls to isEquivalentType. 357 // * we test for I->hasSameSubclassOptionalData (nuw/nsw/tail) at the top 358 // * because of the above, we don't test for the tail bit on calls later on 359 if (I1->getOpcode() != I2->getOpcode() || 360 I1->getNumOperands() != I2->getNumOperands() || 361 !isEquivalentType(I1->getType(), I2->getType()) || 362 !I1->hasSameSubclassOptionalData(I2)) 363 return false; 364 365 // We have two instructions of identical opcode and #operands. Check to see 366 // if all operands are the same type 367 for (unsigned i = 0, e = I1->getNumOperands(); i != e; ++i) 368 if (!isEquivalentType(I1->getOperand(i)->getType(), 369 I2->getOperand(i)->getType())) 370 return false; 371 372 // Check special state that is a part of some instructions. 373 if (const LoadInst *LI = dyn_cast<LoadInst>(I1)) 374 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() && 375 LI->getAlignment() == cast<LoadInst>(I2)->getAlignment() && 376 LI->getOrdering() == cast<LoadInst>(I2)->getOrdering() && 377 LI->getSynchScope() == cast<LoadInst>(I2)->getSynchScope(); 378 if (const StoreInst *SI = dyn_cast<StoreInst>(I1)) 379 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() && 380 SI->getAlignment() == cast<StoreInst>(I2)->getAlignment() && 381 SI->getOrdering() == cast<StoreInst>(I2)->getOrdering() && 382 SI->getSynchScope() == cast<StoreInst>(I2)->getSynchScope(); 383 if (const CmpInst *CI = dyn_cast<CmpInst>(I1)) 384 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate(); 385 if (const CallInst *CI = dyn_cast<CallInst>(I1)) 386 return CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() && 387 CI->getAttributes() == cast<CallInst>(I2)->getAttributes(); 388 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1)) 389 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() && 390 CI->getAttributes() == cast<InvokeInst>(I2)->getAttributes(); 391 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1)) 392 return IVI->getIndices() == cast<InsertValueInst>(I2)->getIndices(); 393 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1)) 394 return EVI->getIndices() == cast<ExtractValueInst>(I2)->getIndices(); 395 if (const FenceInst *FI = dyn_cast<FenceInst>(I1)) 396 return FI->getOrdering() == cast<FenceInst>(I2)->getOrdering() && 397 FI->getSynchScope() == cast<FenceInst>(I2)->getSynchScope(); 398 if (const AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(I1)) 399 return CXI->isVolatile() == cast<AtomicCmpXchgInst>(I2)->isVolatile() && 400 CXI->getSuccessOrdering() == 401 cast<AtomicCmpXchgInst>(I2)->getSuccessOrdering() && 402 CXI->getFailureOrdering() == 403 cast<AtomicCmpXchgInst>(I2)->getFailureOrdering() && 404 CXI->getSynchScope() == cast<AtomicCmpXchgInst>(I2)->getSynchScope(); 405 if (const AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(I1)) 406 return RMWI->getOperation() == cast<AtomicRMWInst>(I2)->getOperation() && 407 RMWI->isVolatile() == cast<AtomicRMWInst>(I2)->isVolatile() && 408 RMWI->getOrdering() == cast<AtomicRMWInst>(I2)->getOrdering() && 409 RMWI->getSynchScope() == cast<AtomicRMWInst>(I2)->getSynchScope(); 410 411 return true; 412 } 413 414 // Determine whether two GEP operations perform the same underlying arithmetic. 415 bool FunctionComparator::isEquivalentGEP(const GEPOperator *GEP1, 416 const GEPOperator *GEP2) { 417 unsigned AS = GEP1->getPointerAddressSpace(); 418 if (AS != GEP2->getPointerAddressSpace()) 419 return false; 420 421 if (DL) { 422 // When we have target data, we can reduce the GEP down to the value in bytes 423 // added to the address. 424 unsigned BitWidth = DL ? DL->getPointerSizeInBits(AS) : 1; 425 APInt Offset1(BitWidth, 0), Offset2(BitWidth, 0); 426 if (GEP1->accumulateConstantOffset(*DL, Offset1) && 427 GEP2->accumulateConstantOffset(*DL, Offset2)) { 428 return Offset1 == Offset2; 429 } 430 } 431 432 if (GEP1->getPointerOperand()->getType() != 433 GEP2->getPointerOperand()->getType()) 434 return false; 435 436 if (GEP1->getNumOperands() != GEP2->getNumOperands()) 437 return false; 438 439 for (unsigned i = 0, e = GEP1->getNumOperands(); i != e; ++i) { 440 if (!enumerate(GEP1->getOperand(i), GEP2->getOperand(i))) 441 return false; 442 } 443 444 return true; 445 } 446 447 // Compare two values used by the two functions under pair-wise comparison. If 448 // this is the first time the values are seen, they're added to the mapping so 449 // that we will detect mismatches on next use. 450 bool FunctionComparator::enumerate(const Value *V1, const Value *V2) { 451 // Check for function @f1 referring to itself and function @f2 referring to 452 // itself, or referring to each other, or both referring to either of them. 453 // They're all equivalent if the two functions are otherwise equivalent. 454 if (V1 == F1 && V2 == F2) 455 return true; 456 if (V1 == F2 && V2 == F1) 457 return true; 458 459 if (const Constant *C1 = dyn_cast<Constant>(V1)) { 460 if (V1 == V2) return true; 461 const Constant *C2 = dyn_cast<Constant>(V2); 462 if (!C2) return false; 463 // TODO: constant expressions with GEP or references to F1 or F2. 464 if (C1->isNullValue() && C2->isNullValue() && 465 isEquivalentType(C1->getType(), C2->getType())) 466 return true; 467 // Try bitcasting C2 to C1's type. If the bitcast is legal and returns C1 468 // then they must have equal bit patterns. 469 return C1->getType()->canLosslesslyBitCastTo(C2->getType()) && 470 C1 == ConstantExpr::getBitCast(const_cast<Constant*>(C2), C1->getType()); 471 } 472 473 if (isa<InlineAsm>(V1) || isa<InlineAsm>(V2)) 474 return V1 == V2; 475 476 // Check that V1 maps to V2. If we find a value that V1 maps to then we simply 477 // check whether it's equal to V2. When there is no mapping then we need to 478 // ensure that V2 isn't already equivalent to something else. For this 479 // purpose, we track the V2 values in a set. 480 481 const Value *&map_elem = id_map[V1]; 482 if (map_elem) 483 return map_elem == V2; 484 if (!seen_values.insert(V2).second) 485 return false; 486 map_elem = V2; 487 return true; 488 } 489 490 // Test whether two basic blocks have equivalent behaviour. 491 bool FunctionComparator::compare(const BasicBlock *BB1, const BasicBlock *BB2) { 492 BasicBlock::const_iterator F1I = BB1->begin(), F1E = BB1->end(); 493 BasicBlock::const_iterator F2I = BB2->begin(), F2E = BB2->end(); 494 495 do { 496 if (!enumerate(F1I, F2I)) 497 return false; 498 499 if (const GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(F1I)) { 500 const GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(F2I); 501 if (!GEP2) 502 return false; 503 504 if (!enumerate(GEP1->getPointerOperand(), GEP2->getPointerOperand())) 505 return false; 506 507 if (!isEquivalentGEP(GEP1, GEP2)) 508 return false; 509 } else { 510 if (!isEquivalentOperation(F1I, F2I)) 511 return false; 512 513 assert(F1I->getNumOperands() == F2I->getNumOperands()); 514 for (unsigned i = 0, e = F1I->getNumOperands(); i != e; ++i) { 515 Value *OpF1 = F1I->getOperand(i); 516 Value *OpF2 = F2I->getOperand(i); 517 518 if (!enumerate(OpF1, OpF2)) 519 return false; 520 521 if (OpF1->getValueID() != OpF2->getValueID() || 522 !isEquivalentType(OpF1->getType(), OpF2->getType())) 523 return false; 524 } 525 } 526 527 ++F1I, ++F2I; 528 } while (F1I != F1E && F2I != F2E); 529 530 return F1I == F1E && F2I == F2E; 531 } 532 533 // Test whether the two functions have equivalent behaviour. 534 bool FunctionComparator::compare() { 535 // We need to recheck everything, but check the things that weren't included 536 // in the hash first. 537 538 if (F1->getAttributes() != F2->getAttributes()) 539 return false; 540 541 if (F1->hasGC() != F2->hasGC()) 542 return false; 543 544 if (F1->hasGC() && F1->getGC() != F2->getGC()) 545 return false; 546 547 if (F1->hasSection() != F2->hasSection()) 548 return false; 549 550 if (F1->hasSection() && F1->getSection() != F2->getSection()) 551 return false; 552 553 if (F1->isVarArg() != F2->isVarArg()) 554 return false; 555 556 // TODO: if it's internal and only used in direct calls, we could handle this 557 // case too. 558 if (F1->getCallingConv() != F2->getCallingConv()) 559 return false; 560 561 if (!isEquivalentType(F1->getFunctionType(), F2->getFunctionType())) 562 return false; 563 564 assert(F1->arg_size() == F2->arg_size() && 565 "Identically typed functions have different numbers of args!"); 566 567 // Visit the arguments so that they get enumerated in the order they're 568 // passed in. 569 for (Function::const_arg_iterator f1i = F1->arg_begin(), 570 f2i = F2->arg_begin(), f1e = F1->arg_end(); f1i != f1e; ++f1i, ++f2i) { 571 if (!enumerate(f1i, f2i)) 572 llvm_unreachable("Arguments repeat!"); 573 } 574 575 // We do a CFG-ordered walk since the actual ordering of the blocks in the 576 // linked list is immaterial. Our walk starts at the entry block for both 577 // functions, then takes each block from each terminator in order. As an 578 // artifact, this also means that unreachable blocks are ignored. 579 SmallVector<const BasicBlock *, 8> F1BBs, F2BBs; 580 SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1. 581 582 F1BBs.push_back(&F1->getEntryBlock()); 583 F2BBs.push_back(&F2->getEntryBlock()); 584 585 VisitedBBs.insert(F1BBs[0]); 586 while (!F1BBs.empty()) { 587 const BasicBlock *F1BB = F1BBs.pop_back_val(); 588 const BasicBlock *F2BB = F2BBs.pop_back_val(); 589 590 if (!enumerate(F1BB, F2BB) || !compare(F1BB, F2BB)) 591 return false; 592 593 const TerminatorInst *F1TI = F1BB->getTerminator(); 594 const TerminatorInst *F2TI = F2BB->getTerminator(); 595 596 assert(F1TI->getNumSuccessors() == F2TI->getNumSuccessors()); 597 for (unsigned i = 0, e = F1TI->getNumSuccessors(); i != e; ++i) { 598 if (!VisitedBBs.insert(F1TI->getSuccessor(i))) 599 continue; 600 601 F1BBs.push_back(F1TI->getSuccessor(i)); 602 F2BBs.push_back(F2TI->getSuccessor(i)); 603 } 604 } 605 return true; 606 } 607 608 namespace { 609 610 /// MergeFunctions finds functions which will generate identical machine code, 611 /// by considering all pointer types to be equivalent. Once identified, 612 /// MergeFunctions will fold them by replacing a call to one to a call to a 613 /// bitcast of the other. 614 /// 615 class MergeFunctions : public ModulePass { 616 public: 617 static char ID; 618 MergeFunctions() 619 : ModulePass(ID), HasGlobalAliases(false) { 620 initializeMergeFunctionsPass(*PassRegistry::getPassRegistry()); 621 } 622 623 bool runOnModule(Module &M) override; 624 625 private: 626 typedef DenseSet<ComparableFunction> FnSetType; 627 628 /// A work queue of functions that may have been modified and should be 629 /// analyzed again. 630 std::vector<WeakVH> Deferred; 631 632 /// Insert a ComparableFunction into the FnSet, or merge it away if it's 633 /// equal to one that's already present. 634 bool insert(ComparableFunction &NewF); 635 636 /// Remove a Function from the FnSet and queue it up for a second sweep of 637 /// analysis. 638 void remove(Function *F); 639 640 /// Find the functions that use this Value and remove them from FnSet and 641 /// queue the functions. 642 void removeUsers(Value *V); 643 644 /// Replace all direct calls of Old with calls of New. Will bitcast New if 645 /// necessary to make types match. 646 void replaceDirectCallers(Function *Old, Function *New); 647 648 /// Merge two equivalent functions. Upon completion, G may be deleted, or may 649 /// be converted into a thunk. In either case, it should never be visited 650 /// again. 651 void mergeTwoFunctions(Function *F, Function *G); 652 653 /// Replace G with a thunk or an alias to F. Deletes G. 654 void writeThunkOrAlias(Function *F, Function *G); 655 656 /// Replace G with a simple tail call to bitcast(F). Also replace direct uses 657 /// of G with bitcast(F). Deletes G. 658 void writeThunk(Function *F, Function *G); 659 660 /// Replace G with an alias to F. Deletes G. 661 void writeAlias(Function *F, Function *G); 662 663 /// The set of all distinct functions. Use the insert() and remove() methods 664 /// to modify it. 665 FnSetType FnSet; 666 667 /// DataLayout for more accurate GEP comparisons. May be NULL. 668 const DataLayout *DL; 669 670 /// Whether or not the target supports global aliases. 671 bool HasGlobalAliases; 672 }; 673 674 } // end anonymous namespace 675 676 char MergeFunctions::ID = 0; 677 INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false) 678 679 ModulePass *llvm::createMergeFunctionsPass() { 680 return new MergeFunctions(); 681 } 682 683 bool MergeFunctions::runOnModule(Module &M) { 684 bool Changed = false; 685 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>(); 686 DL = DLP ? &DLP->getDataLayout() : 0; 687 688 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) { 689 if (!I->isDeclaration() && !I->hasAvailableExternallyLinkage()) 690 Deferred.push_back(WeakVH(I)); 691 } 692 FnSet.resize(Deferred.size()); 693 694 do { 695 std::vector<WeakVH> Worklist; 696 Deferred.swap(Worklist); 697 698 DEBUG(dbgs() << "size of module: " << M.size() << '\n'); 699 DEBUG(dbgs() << "size of worklist: " << Worklist.size() << '\n'); 700 701 // Insert only strong functions and merge them. Strong function merging 702 // always deletes one of them. 703 for (std::vector<WeakVH>::iterator I = Worklist.begin(), 704 E = Worklist.end(); I != E; ++I) { 705 if (!*I) continue; 706 Function *F = cast<Function>(*I); 707 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() && 708 !F->mayBeOverridden()) { 709 ComparableFunction CF = ComparableFunction(F, DL); 710 Changed |= insert(CF); 711 } 712 } 713 714 // Insert only weak functions and merge them. By doing these second we 715 // create thunks to the strong function when possible. When two weak 716 // functions are identical, we create a new strong function with two weak 717 // weak thunks to it which are identical but not mergable. 718 for (std::vector<WeakVH>::iterator I = Worklist.begin(), 719 E = Worklist.end(); I != E; ++I) { 720 if (!*I) continue; 721 Function *F = cast<Function>(*I); 722 if (!F->isDeclaration() && !F->hasAvailableExternallyLinkage() && 723 F->mayBeOverridden()) { 724 ComparableFunction CF = ComparableFunction(F, DL); 725 Changed |= insert(CF); 726 } 727 } 728 DEBUG(dbgs() << "size of FnSet: " << FnSet.size() << '\n'); 729 } while (!Deferred.empty()); 730 731 FnSet.clear(); 732 733 return Changed; 734 } 735 736 bool DenseMapInfo<ComparableFunction>::isEqual(const ComparableFunction &LHS, 737 const ComparableFunction &RHS) { 738 if (LHS.getFunc() == RHS.getFunc() && 739 LHS.getHash() == RHS.getHash()) 740 return true; 741 if (!LHS.getFunc() || !RHS.getFunc()) 742 return false; 743 744 // One of these is a special "underlying pointer comparison only" object. 745 if (LHS.getDataLayout() == ComparableFunction::LookupOnly || 746 RHS.getDataLayout() == ComparableFunction::LookupOnly) 747 return false; 748 749 assert(LHS.getDataLayout() == RHS.getDataLayout() && 750 "Comparing functions for different targets"); 751 752 return FunctionComparator(LHS.getDataLayout(), LHS.getFunc(), 753 RHS.getFunc()).compare(); 754 } 755 756 // Replace direct callers of Old with New. 757 void MergeFunctions::replaceDirectCallers(Function *Old, Function *New) { 758 Constant *BitcastNew = ConstantExpr::getBitCast(New, Old->getType()); 759 for (auto UI = Old->use_begin(), UE = Old->use_end(); UI != UE;) { 760 Use *U = &*UI; 761 ++UI; 762 CallSite CS(U->getUser()); 763 if (CS && CS.isCallee(U)) { 764 remove(CS.getInstruction()->getParent()->getParent()); 765 U->set(BitcastNew); 766 } 767 } 768 } 769 770 // Replace G with an alias to F if possible, or else a thunk to F. Deletes G. 771 void MergeFunctions::writeThunkOrAlias(Function *F, Function *G) { 772 if (HasGlobalAliases && G->hasUnnamedAddr()) { 773 if (G->hasExternalLinkage() || G->hasLocalLinkage() || 774 G->hasWeakLinkage()) { 775 writeAlias(F, G); 776 return; 777 } 778 } 779 780 writeThunk(F, G); 781 } 782 783 // Helper for writeThunk, 784 // Selects proper bitcast operation, 785 // but a bit simpler then CastInst::getCastOpcode. 786 static Value* createCast(IRBuilder<false> &Builder, Value *V, Type *DestTy) { 787 Type *SrcTy = V->getType(); 788 if (SrcTy->isIntegerTy() && DestTy->isPointerTy()) 789 return Builder.CreateIntToPtr(V, DestTy); 790 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy()) 791 return Builder.CreatePtrToInt(V, DestTy); 792 else 793 return Builder.CreateBitCast(V, DestTy); 794 } 795 796 // Replace G with a simple tail call to bitcast(F). Also replace direct uses 797 // of G with bitcast(F). Deletes G. 798 void MergeFunctions::writeThunk(Function *F, Function *G) { 799 if (!G->mayBeOverridden()) { 800 // Redirect direct callers of G to F. 801 replaceDirectCallers(G, F); 802 } 803 804 // If G was internal then we may have replaced all uses of G with F. If so, 805 // stop here and delete G. There's no need for a thunk. 806 if (G->hasLocalLinkage() && G->use_empty()) { 807 G->eraseFromParent(); 808 return; 809 } 810 811 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "", 812 G->getParent()); 813 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG); 814 IRBuilder<false> Builder(BB); 815 816 SmallVector<Value *, 16> Args; 817 unsigned i = 0; 818 FunctionType *FFTy = F->getFunctionType(); 819 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end(); 820 AI != AE; ++AI) { 821 Args.push_back(createCast(Builder, (Value*)AI, FFTy->getParamType(i))); 822 ++i; 823 } 824 825 CallInst *CI = Builder.CreateCall(F, Args); 826 CI->setTailCall(); 827 CI->setCallingConv(F->getCallingConv()); 828 if (NewG->getReturnType()->isVoidTy()) { 829 Builder.CreateRetVoid(); 830 } else { 831 Builder.CreateRet(createCast(Builder, CI, NewG->getReturnType())); 832 } 833 834 NewG->copyAttributesFrom(G); 835 NewG->takeName(G); 836 removeUsers(G); 837 G->replaceAllUsesWith(NewG); 838 G->eraseFromParent(); 839 840 DEBUG(dbgs() << "writeThunk: " << NewG->getName() << '\n'); 841 ++NumThunksWritten; 842 } 843 844 // Replace G with an alias to F and delete G. 845 void MergeFunctions::writeAlias(Function *F, Function *G) { 846 Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType()); 847 GlobalAlias *GA = new GlobalAlias(G->getType(), G->getLinkage(), "", 848 BitcastF, G->getParent()); 849 F->setAlignment(std::max(F->getAlignment(), G->getAlignment())); 850 GA->takeName(G); 851 GA->setVisibility(G->getVisibility()); 852 removeUsers(G); 853 G->replaceAllUsesWith(GA); 854 G->eraseFromParent(); 855 856 DEBUG(dbgs() << "writeAlias: " << GA->getName() << '\n'); 857 ++NumAliasesWritten; 858 } 859 860 // Merge two equivalent functions. Upon completion, Function G is deleted. 861 void MergeFunctions::mergeTwoFunctions(Function *F, Function *G) { 862 if (F->mayBeOverridden()) { 863 assert(G->mayBeOverridden()); 864 865 if (HasGlobalAliases) { 866 // Make them both thunks to the same internal function. 867 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "", 868 F->getParent()); 869 H->copyAttributesFrom(F); 870 H->takeName(F); 871 removeUsers(F); 872 F->replaceAllUsesWith(H); 873 874 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment()); 875 876 writeAlias(F, G); 877 writeAlias(F, H); 878 879 F->setAlignment(MaxAlignment); 880 F->setLinkage(GlobalValue::PrivateLinkage); 881 } else { 882 // We can't merge them. Instead, pick one and update all direct callers 883 // to call it and hope that we improve the instruction cache hit rate. 884 replaceDirectCallers(G, F); 885 } 886 887 ++NumDoubleWeak; 888 } else { 889 writeThunkOrAlias(F, G); 890 } 891 892 ++NumFunctionsMerged; 893 } 894 895 // Insert a ComparableFunction into the FnSet, or merge it away if equal to one 896 // that was already inserted. 897 bool MergeFunctions::insert(ComparableFunction &NewF) { 898 std::pair<FnSetType::iterator, bool> Result = FnSet.insert(NewF); 899 if (Result.second) { 900 DEBUG(dbgs() << "Inserting as unique: " << NewF.getFunc()->getName() << '\n'); 901 return false; 902 } 903 904 const ComparableFunction &OldF = *Result.first; 905 906 // Don't merge tiny functions, since it can just end up making the function 907 // larger. 908 // FIXME: Should still merge them if they are unnamed_addr and produce an 909 // alias. 910 if (NewF.getFunc()->size() == 1) { 911 if (NewF.getFunc()->front().size() <= 2) { 912 DEBUG(dbgs() << NewF.getFunc()->getName() 913 << " is to small to bother merging\n"); 914 return false; 915 } 916 } 917 918 // Never thunk a strong function to a weak function. 919 assert(!OldF.getFunc()->mayBeOverridden() || 920 NewF.getFunc()->mayBeOverridden()); 921 922 DEBUG(dbgs() << " " << OldF.getFunc()->getName() << " == " 923 << NewF.getFunc()->getName() << '\n'); 924 925 Function *DeleteF = NewF.getFunc(); 926 NewF.release(); 927 mergeTwoFunctions(OldF.getFunc(), DeleteF); 928 return true; 929 } 930 931 // Remove a function from FnSet. If it was already in FnSet, add it to Deferred 932 // so that we'll look at it in the next round. 933 void MergeFunctions::remove(Function *F) { 934 // We need to make sure we remove F, not a function "equal" to F per the 935 // function equality comparator. 936 // 937 // The special "lookup only" ComparableFunction bypasses the expensive 938 // function comparison in favour of a pointer comparison on the underlying 939 // Function*'s. 940 ComparableFunction CF = ComparableFunction(F, ComparableFunction::LookupOnly); 941 if (FnSet.erase(CF)) { 942 DEBUG(dbgs() << "Removed " << F->getName() << " from set and deferred it.\n"); 943 Deferred.push_back(F); 944 } 945 } 946 947 // For each instruction used by the value, remove() the function that contains 948 // the instruction. This should happen right before a call to RAUW. 949 void MergeFunctions::removeUsers(Value *V) { 950 std::vector<Value *> Worklist; 951 Worklist.push_back(V); 952 while (!Worklist.empty()) { 953 Value *V = Worklist.back(); 954 Worklist.pop_back(); 955 956 for (User *U : V->users()) { 957 if (Instruction *I = dyn_cast<Instruction>(U)) { 958 remove(I->getParent()->getParent()); 959 } else if (isa<GlobalValue>(U)) { 960 // do nothing 961 } else if (Constant *C = dyn_cast<Constant>(U)) { 962 for (User *UU : C->users()) 963 Worklist.push_back(UU); 964 } 965 } 966 } 967 } 968