MergeFunctions.cpp revision 61c70e98ac3c7504d31dd9bc81c4e9cb998e9984
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/DenseMap.h" 49#include "llvm/ADT/FoldingSet.h" 50#include "llvm/ADT/SmallSet.h" 51#include "llvm/ADT/Statistic.h" 52#include "llvm/Constants.h" 53#include "llvm/InlineAsm.h" 54#include "llvm/Instructions.h" 55#include "llvm/LLVMContext.h" 56#include "llvm/Module.h" 57#include "llvm/Pass.h" 58#include "llvm/Support/CallSite.h" 59#include "llvm/Support/Debug.h" 60#include "llvm/Support/ErrorHandling.h" 61#include "llvm/Support/IRBuilder.h" 62#include "llvm/Support/raw_ostream.h" 63#include "llvm/Target/TargetData.h" 64#include <map> 65#include <vector> 66using namespace llvm; 67 68STATISTIC(NumFunctionsMerged, "Number of functions merged"); 69 70namespace { 71 /// MergeFunctions finds functions which will generate identical machine code, 72 /// by considering all pointer types to be equivalent. Once identified, 73 /// MergeFunctions will fold them by replacing a call to one to a call to a 74 /// bitcast of the other. 75 /// 76 class MergeFunctions : public ModulePass { 77 public: 78 static char ID; 79 MergeFunctions() : ModulePass(ID) {} 80 81 bool runOnModule(Module &M); 82 83 private: 84 /// PairwiseCompareAndMerge - Given a list of functions, compare each pair 85 /// and merge the pairs of equivalent functions. 86 bool PairwiseCompareAndMerge(std::vector<Function *> &FnVec); 87 88 /// MergeTwoFunctions - Merge two equivalent functions. Upon completion, 89 /// FnVec[j] should never be visited again. 90 void MergeTwoFunctions(std::vector<Function *> &FnVec, 91 unsigned i, unsigned j) const; 92 93 /// WriteThunk - Replace G with a simple tail call to bitcast(F). Also 94 /// replace direct uses of G with bitcast(F). 95 void WriteThunk(Function *F, Function *G) const; 96 97 TargetData *TD; 98 }; 99} 100 101char MergeFunctions::ID = 0; 102INITIALIZE_PASS(MergeFunctions, "mergefunc", "Merge Functions", false, false); 103 104ModulePass *llvm::createMergeFunctionsPass() { 105 return new MergeFunctions(); 106} 107 108namespace { 109/// FunctionComparator - Compares two functions to determine whether or not 110/// they will generate machine code with the same behaviour. TargetData is 111/// used if available. The comparator always fails conservatively (erring on the 112/// side of claiming that two functions are different). 113class FunctionComparator { 114public: 115 FunctionComparator(TargetData *TD, Function *F1, Function *F2) 116 : F1(F1), F2(F2), TD(TD), IDMap1Count(0), IDMap2Count(0) {} 117 118 /// Compare - test whether the two functions have equivalent behaviour. 119 bool Compare(); 120 121private: 122 /// Compare - test whether two basic blocks have equivalent behaviour. 123 bool Compare(const BasicBlock *BB1, const BasicBlock *BB2); 124 125 /// Enumerate - Assign or look up previously assigned numbers for the two 126 /// values, and return whether the numbers are equal. Numbers are assigned in 127 /// the order visited. 128 bool Enumerate(const Value *V1, const Value *V2); 129 130 /// isEquivalentOperation - Compare two Instructions for equivalence, similar 131 /// to Instruction::isSameOperationAs but with modifications to the type 132 /// comparison. 133 bool isEquivalentOperation(const Instruction *I1, 134 const Instruction *I2) const; 135 136 /// isEquivalentGEP - Compare two GEPs for equivalent pointer arithmetic. 137 bool isEquivalentGEP(const GEPOperator *GEP1, const GEPOperator *GEP2); 138 bool isEquivalentGEP(const GetElementPtrInst *GEP1, 139 const GetElementPtrInst *GEP2) { 140 return isEquivalentGEP(cast<GEPOperator>(GEP1), cast<GEPOperator>(GEP2)); 141 } 142 143 /// isEquivalentType - Compare two Types, treating all pointer types as equal. 144 bool isEquivalentType(const Type *Ty1, const Type *Ty2) const; 145 146 // The two functions undergoing comparison. 147 Function *F1, *F2; 148 149 TargetData *TD; 150 151 typedef DenseMap<const Value *, unsigned long> IDMap; 152 IDMap Map1, Map2; 153 unsigned long IDMap1Count, IDMap2Count; 154}; 155} 156 157/// Compute a hash guaranteed to be equal for two equivalent functions, but 158/// very likely to be different for different functions. 159static unsigned long ProfileFunction(const Function *F) { 160 const FunctionType *FTy = F->getFunctionType(); 161 162 FoldingSetNodeID ID; 163 ID.AddInteger(F->size()); 164 ID.AddInteger(F->getCallingConv()); 165 ID.AddBoolean(F->hasGC()); 166 ID.AddBoolean(FTy->isVarArg()); 167 ID.AddInteger(FTy->getReturnType()->getTypeID()); 168 for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) 169 ID.AddInteger(FTy->getParamType(i)->getTypeID()); 170 return ID.ComputeHash(); 171} 172 173/// isEquivalentType - any two pointers in the same address space are 174/// equivalent. Otherwise, standard type equivalence rules apply. 175bool FunctionComparator::isEquivalentType(const Type *Ty1, 176 const Type *Ty2) const { 177 if (Ty1 == Ty2) 178 return true; 179 if (Ty1->getTypeID() != Ty2->getTypeID()) 180 return false; 181 182 switch(Ty1->getTypeID()) { 183 default: 184 llvm_unreachable("Unknown type!"); 185 // Fall through in Release mode. 186 case Type::IntegerTyID: 187 case Type::OpaqueTyID: 188 // Ty1 == Ty2 would have returned true earlier. 189 return false; 190 191 case Type::VoidTyID: 192 case Type::FloatTyID: 193 case Type::DoubleTyID: 194 case Type::X86_FP80TyID: 195 case Type::FP128TyID: 196 case Type::PPC_FP128TyID: 197 case Type::LabelTyID: 198 case Type::MetadataTyID: 199 return true; 200 201 case Type::PointerTyID: { 202 const PointerType *PTy1 = cast<PointerType>(Ty1); 203 const PointerType *PTy2 = cast<PointerType>(Ty2); 204 return PTy1->getAddressSpace() == PTy2->getAddressSpace(); 205 } 206 207 case Type::StructTyID: { 208 const StructType *STy1 = cast<StructType>(Ty1); 209 const StructType *STy2 = cast<StructType>(Ty2); 210 if (STy1->getNumElements() != STy2->getNumElements()) 211 return false; 212 213 if (STy1->isPacked() != STy2->isPacked()) 214 return false; 215 216 for (unsigned i = 0, e = STy1->getNumElements(); i != e; ++i) { 217 if (!isEquivalentType(STy1->getElementType(i), STy2->getElementType(i))) 218 return false; 219 } 220 return true; 221 } 222 223 case Type::FunctionTyID: { 224 const FunctionType *FTy1 = cast<FunctionType>(Ty1); 225 const FunctionType *FTy2 = cast<FunctionType>(Ty2); 226 if (FTy1->getNumParams() != FTy2->getNumParams() || 227 FTy1->isVarArg() != FTy2->isVarArg()) 228 return false; 229 230 if (!isEquivalentType(FTy1->getReturnType(), FTy2->getReturnType())) 231 return false; 232 233 for (unsigned i = 0, e = FTy1->getNumParams(); i != e; ++i) { 234 if (!isEquivalentType(FTy1->getParamType(i), FTy2->getParamType(i))) 235 return false; 236 } 237 return true; 238 } 239 240 case Type::ArrayTyID: { 241 const ArrayType *ATy1 = cast<ArrayType>(Ty1); 242 const ArrayType *ATy2 = cast<ArrayType>(Ty2); 243 return ATy1->getNumElements() == ATy2->getNumElements() && 244 isEquivalentType(ATy1->getElementType(), ATy2->getElementType()); 245 } 246 247 case Type::VectorTyID: { 248 const VectorType *VTy1 = cast<VectorType>(Ty1); 249 const VectorType *VTy2 = cast<VectorType>(Ty2); 250 return VTy1->getNumElements() == VTy2->getNumElements() && 251 isEquivalentType(VTy1->getElementType(), VTy2->getElementType()); 252 } 253 } 254} 255 256/// isEquivalentOperation - determine whether the two operations are the same 257/// except that pointer-to-A and pointer-to-B are equivalent. This should be 258/// kept in sync with Instruction::isSameOperationAs. 259bool FunctionComparator::isEquivalentOperation(const Instruction *I1, 260 const Instruction *I2) const { 261 if (I1->getOpcode() != I2->getOpcode() || 262 I1->getNumOperands() != I2->getNumOperands() || 263 !isEquivalentType(I1->getType(), I2->getType()) || 264 !I1->hasSameSubclassOptionalData(I2)) 265 return false; 266 267 // We have two instructions of identical opcode and #operands. Check to see 268 // if all operands are the same type 269 for (unsigned i = 0, e = I1->getNumOperands(); i != e; ++i) 270 if (!isEquivalentType(I1->getOperand(i)->getType(), 271 I2->getOperand(i)->getType())) 272 return false; 273 274 // Check special state that is a part of some instructions. 275 if (const LoadInst *LI = dyn_cast<LoadInst>(I1)) 276 return LI->isVolatile() == cast<LoadInst>(I2)->isVolatile() && 277 LI->getAlignment() == cast<LoadInst>(I2)->getAlignment(); 278 if (const StoreInst *SI = dyn_cast<StoreInst>(I1)) 279 return SI->isVolatile() == cast<StoreInst>(I2)->isVolatile() && 280 SI->getAlignment() == cast<StoreInst>(I2)->getAlignment(); 281 if (const CmpInst *CI = dyn_cast<CmpInst>(I1)) 282 return CI->getPredicate() == cast<CmpInst>(I2)->getPredicate(); 283 if (const CallInst *CI = dyn_cast<CallInst>(I1)) 284 return CI->isTailCall() == cast<CallInst>(I2)->isTailCall() && 285 CI->getCallingConv() == cast<CallInst>(I2)->getCallingConv() && 286 CI->getAttributes().getRawPointer() == 287 cast<CallInst>(I2)->getAttributes().getRawPointer(); 288 if (const InvokeInst *CI = dyn_cast<InvokeInst>(I1)) 289 return CI->getCallingConv() == cast<InvokeInst>(I2)->getCallingConv() && 290 CI->getAttributes().getRawPointer() == 291 cast<InvokeInst>(I2)->getAttributes().getRawPointer(); 292 if (const InsertValueInst *IVI = dyn_cast<InsertValueInst>(I1)) { 293 if (IVI->getNumIndices() != cast<InsertValueInst>(I2)->getNumIndices()) 294 return false; 295 for (unsigned i = 0, e = IVI->getNumIndices(); i != e; ++i) 296 if (IVI->idx_begin()[i] != cast<InsertValueInst>(I2)->idx_begin()[i]) 297 return false; 298 return true; 299 } 300 if (const ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I1)) { 301 if (EVI->getNumIndices() != cast<ExtractValueInst>(I2)->getNumIndices()) 302 return false; 303 for (unsigned i = 0, e = EVI->getNumIndices(); i != e; ++i) 304 if (EVI->idx_begin()[i] != cast<ExtractValueInst>(I2)->idx_begin()[i]) 305 return false; 306 return true; 307 } 308 309 return true; 310} 311 312/// isEquivalentGEP - determine whether two GEP operations perform the same 313/// underlying arithmetic. 314bool FunctionComparator::isEquivalentGEP(const GEPOperator *GEP1, 315 const GEPOperator *GEP2) { 316 // When we have target data, we can reduce the GEP down to the value in bytes 317 // added to the address. 318 if (TD && GEP1->hasAllConstantIndices() && GEP2->hasAllConstantIndices()) { 319 SmallVector<Value *, 8> Indices1(GEP1->idx_begin(), GEP1->idx_end()); 320 SmallVector<Value *, 8> Indices2(GEP2->idx_begin(), GEP2->idx_end()); 321 uint64_t Offset1 = TD->getIndexedOffset(GEP1->getPointerOperandType(), 322 Indices1.data(), Indices1.size()); 323 uint64_t Offset2 = TD->getIndexedOffset(GEP2->getPointerOperandType(), 324 Indices2.data(), Indices2.size()); 325 return Offset1 == Offset2; 326 } 327 328 if (GEP1->getPointerOperand()->getType() != 329 GEP2->getPointerOperand()->getType()) 330 return false; 331 332 if (GEP1->getNumOperands() != GEP2->getNumOperands()) 333 return false; 334 335 for (unsigned i = 0, e = GEP1->getNumOperands(); i != e; ++i) { 336 if (!Enumerate(GEP1->getOperand(i), GEP2->getOperand(i))) 337 return false; 338 } 339 340 return true; 341} 342 343/// Enumerate - Compare two values used by the two functions under pair-wise 344/// comparison. If this is the first time the values are seen, they're added to 345/// the mapping so that we will detect mismatches on next use. 346bool FunctionComparator::Enumerate(const Value *V1, const Value *V2) { 347 // Check for function @f1 referring to itself and function @f2 referring to 348 // itself, or referring to each other, or both referring to either of them. 349 // They're all equivalent if the two functions are otherwise equivalent. 350 if (V1 == F1 && V2 == F2) 351 return true; 352 if (V1 == F2 && V2 == F1) 353 return true; 354 355 // TODO: constant expressions with GEP or references to F1 or F2. 356 if (isa<Constant>(V1)) 357 return V1 == V2; 358 359 if (isa<InlineAsm>(V1) && isa<InlineAsm>(V2)) { 360 const InlineAsm *IA1 = cast<InlineAsm>(V1); 361 const InlineAsm *IA2 = cast<InlineAsm>(V2); 362 return IA1->getAsmString() == IA2->getAsmString() && 363 IA1->getConstraintString() == IA2->getConstraintString(); 364 } 365 366 unsigned long &ID1 = Map1[V1]; 367 if (!ID1) 368 ID1 = ++IDMap1Count; 369 370 unsigned long &ID2 = Map2[V2]; 371 if (!ID2) 372 ID2 = ++IDMap2Count; 373 374 return ID1 == ID2; 375} 376 377/// Compare - test whether two basic blocks have equivalent behaviour. 378bool FunctionComparator::Compare(const BasicBlock *BB1, const BasicBlock *BB2) { 379 BasicBlock::const_iterator F1I = BB1->begin(), F1E = BB1->end(); 380 BasicBlock::const_iterator F2I = BB2->begin(), F2E = BB2->end(); 381 382 do { 383 if (!Enumerate(F1I, F2I)) 384 return false; 385 386 if (const GetElementPtrInst *GEP1 = dyn_cast<GetElementPtrInst>(F1I)) { 387 const GetElementPtrInst *GEP2 = dyn_cast<GetElementPtrInst>(F2I); 388 if (!GEP2) 389 return false; 390 391 if (!Enumerate(GEP1->getPointerOperand(), GEP2->getPointerOperand())) 392 return false; 393 394 if (!isEquivalentGEP(GEP1, GEP2)) 395 return false; 396 } else { 397 if (!isEquivalentOperation(F1I, F2I)) 398 return false; 399 400 assert(F1I->getNumOperands() == F2I->getNumOperands()); 401 for (unsigned i = 0, e = F1I->getNumOperands(); i != e; ++i) { 402 Value *OpF1 = F1I->getOperand(i); 403 Value *OpF2 = F2I->getOperand(i); 404 405 if (!Enumerate(OpF1, OpF2)) 406 return false; 407 408 if (OpF1->getValueID() != OpF2->getValueID() || 409 !isEquivalentType(OpF1->getType(), OpF2->getType())) 410 return false; 411 } 412 } 413 414 ++F1I, ++F2I; 415 } while (F1I != F1E && F2I != F2E); 416 417 return F1I == F1E && F2I == F2E; 418} 419 420/// Compare - test whether the two functions have equivalent behaviour. 421bool FunctionComparator::Compare() { 422 // We need to recheck everything, but check the things that weren't included 423 // in the hash first. 424 425 if (F1->getAttributes() != F2->getAttributes()) 426 return false; 427 428 if (F1->hasGC() != F2->hasGC()) 429 return false; 430 431 if (F1->hasGC() && F1->getGC() != F2->getGC()) 432 return false; 433 434 if (F1->hasSection() != F2->hasSection()) 435 return false; 436 437 if (F1->hasSection() && F1->getSection() != F2->getSection()) 438 return false; 439 440 if (F1->isVarArg() != F2->isVarArg()) 441 return false; 442 443 // TODO: if it's internal and only used in direct calls, we could handle this 444 // case too. 445 if (F1->getCallingConv() != F2->getCallingConv()) 446 return false; 447 448 if (!isEquivalentType(F1->getFunctionType(), F2->getFunctionType())) 449 return false; 450 451 assert(F1->arg_size() == F2->arg_size() && 452 "Identical functions have a different number of args."); 453 454 // Visit the arguments so that they get enumerated in the order they're 455 // passed in. 456 for (Function::const_arg_iterator f1i = F1->arg_begin(), 457 f2i = F2->arg_begin(), f1e = F1->arg_end(); f1i != f1e; ++f1i, ++f2i) { 458 if (!Enumerate(f1i, f2i)) 459 llvm_unreachable("Arguments repeat"); 460 } 461 462 // We do a CFG-ordered walk since the actual ordering of the blocks in the 463 // linked list is immaterial. Our walk starts at the entry block for both 464 // functions, then takes each block from each terminator in order. As an 465 // artifact, this also means that unreachable blocks are ignored. 466 SmallVector<const BasicBlock *, 8> F1BBs, F2BBs; 467 SmallSet<const BasicBlock *, 128> VisitedBBs; // in terms of F1. 468 469 F1BBs.push_back(&F1->getEntryBlock()); 470 F2BBs.push_back(&F2->getEntryBlock()); 471 472 VisitedBBs.insert(F1BBs[0]); 473 while (!F1BBs.empty()) { 474 const BasicBlock *F1BB = F1BBs.pop_back_val(); 475 const BasicBlock *F2BB = F2BBs.pop_back_val(); 476 477 if (!Enumerate(F1BB, F2BB) || !Compare(F1BB, F2BB)) 478 return false; 479 480 const TerminatorInst *F1TI = F1BB->getTerminator(); 481 const TerminatorInst *F2TI = F2BB->getTerminator(); 482 483 assert(F1TI->getNumSuccessors() == F2TI->getNumSuccessors()); 484 for (unsigned i = 0, e = F1TI->getNumSuccessors(); i != e; ++i) { 485 if (!VisitedBBs.insert(F1TI->getSuccessor(i))) 486 continue; 487 488 F1BBs.push_back(F1TI->getSuccessor(i)); 489 F2BBs.push_back(F2TI->getSuccessor(i)); 490 } 491 } 492 return true; 493} 494 495/// WriteThunk - Replace G with a simple tail call to bitcast(F). Also replace 496/// direct uses of G with bitcast(F). 497void MergeFunctions::WriteThunk(Function *F, Function *G) const { 498 if (!G->mayBeOverridden()) { 499 // Redirect direct callers of G to F. 500 Constant *BitcastF = ConstantExpr::getBitCast(F, G->getType()); 501 for (Value::use_iterator UI = G->use_begin(), UE = G->use_end(); 502 UI != UE;) { 503 Value::use_iterator TheIter = UI; 504 ++UI; 505 CallSite CS(*TheIter); 506 if (CS && CS.isCallee(TheIter)) 507 TheIter.getUse().set(BitcastF); 508 } 509 } 510 511 // If G was internal then we may have replaced all uses if G with F. If so, 512 // stop here and delete G. There's no need for a thunk. 513 if (G->hasLocalLinkage() && G->use_empty()) { 514 G->eraseFromParent(); 515 return; 516 } 517 518 Function *NewG = Function::Create(G->getFunctionType(), G->getLinkage(), "", 519 G->getParent()); 520 BasicBlock *BB = BasicBlock::Create(F->getContext(), "", NewG); 521 IRBuilder<false> Builder(BB); 522 523 SmallVector<Value *, 16> Args; 524 unsigned i = 0; 525 const FunctionType *FFTy = F->getFunctionType(); 526 for (Function::arg_iterator AI = NewG->arg_begin(), AE = NewG->arg_end(); 527 AI != AE; ++AI) { 528 Args.push_back(Builder.CreateBitCast(AI, FFTy->getParamType(i))); 529 ++i; 530 } 531 532 CallInst *CI = Builder.CreateCall(F, Args.begin(), Args.end()); 533 CI->setTailCall(); 534 CI->setCallingConv(F->getCallingConv()); 535 if (NewG->getReturnType()->isVoidTy()) { 536 Builder.CreateRetVoid(); 537 } else { 538 Builder.CreateRet(Builder.CreateBitCast(CI, NewG->getReturnType())); 539 } 540 541 NewG->copyAttributesFrom(G); 542 NewG->takeName(G); 543 G->replaceAllUsesWith(NewG); 544 G->eraseFromParent(); 545} 546 547/// MergeTwoFunctions - Merge two equivalent functions. Upon completion, 548/// FnVec[j] is deleted but not removed from the vector. 549void MergeFunctions::MergeTwoFunctions(std::vector<Function *> &FnVec, 550 unsigned i, unsigned j) const { 551 Function *F = FnVec[i]; 552 Function *G = FnVec[j]; 553 554 if (F->isWeakForLinker() && !G->isWeakForLinker()) { 555 std::swap(FnVec[i], FnVec[j]); 556 std::swap(F, G); 557 } 558 559 if (F->isWeakForLinker()) { 560 assert(G->isWeakForLinker()); 561 562 // Make them both thunks to the same internal function. 563 Function *H = Function::Create(F->getFunctionType(), F->getLinkage(), "", 564 F->getParent()); 565 H->copyAttributesFrom(F); 566 H->takeName(F); 567 F->replaceAllUsesWith(H); 568 569 unsigned MaxAlignment = std::max(G->getAlignment(), H->getAlignment()); 570 571 WriteThunk(F, G); 572 WriteThunk(F, H); 573 574 F->setAlignment(MaxAlignment); 575 F->setLinkage(GlobalValue::InternalLinkage); 576 } else { 577 WriteThunk(F, G); 578 } 579 580 ++NumFunctionsMerged; 581} 582 583/// PairwiseCompareAndMerge - Given a list of functions, compare each pair and 584/// merge the pairs of equivalent functions. 585bool MergeFunctions::PairwiseCompareAndMerge(std::vector<Function *> &FnVec) { 586 bool Changed = false; 587 for (int i = 0, e = FnVec.size(); i != e; ++i) { 588 for (int j = i + 1; j != e; ++j) { 589 bool isEqual = FunctionComparator(TD, FnVec[i], FnVec[j]).Compare(); 590 591 DEBUG(dbgs() << " " << FnVec[i]->getName() 592 << (isEqual ? " == " : " != ") << FnVec[j]->getName() << "\n"); 593 594 if (isEqual) { 595 MergeTwoFunctions(FnVec, i, j); 596 Changed = true; 597 FnVec.erase(FnVec.begin() + j); 598 --j, --e; 599 } 600 } 601 } 602 return Changed; 603} 604 605bool MergeFunctions::runOnModule(Module &M) { 606 bool Changed = false; 607 608 std::map<unsigned long, std::vector<Function *> > FnMap; 609 610 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) { 611 if (F->isDeclaration() || F->hasAvailableExternallyLinkage()) 612 continue; 613 614 FnMap[ProfileFunction(F)].push_back(F); 615 } 616 617 TD = getAnalysisIfAvailable<TargetData>(); 618 619 bool LocalChanged; 620 do { 621 LocalChanged = false; 622 DEBUG(dbgs() << "size: " << FnMap.size() << "\n"); 623 for (std::map<unsigned long, std::vector<Function *> >::iterator 624 I = FnMap.begin(), E = FnMap.end(); I != E; ++I) { 625 std::vector<Function *> &FnVec = I->second; 626 DEBUG(dbgs() << "hash (" << I->first << "): " << FnVec.size() << "\n"); 627 LocalChanged |= PairwiseCompareAndMerge(FnVec); 628 } 629 Changed |= LocalChanged; 630 } while (LocalChanged); 631 632 return Changed; 633} 634