1 //===- ExtractFunction.cpp - Extract a function from Program --------------===// 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 file implements several methods that are used to extract functions, 11 // loops, or portions of a module from the rest of the module. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "BugDriver.h" 16 #include "llvm/IR/Constants.h" 17 #include "llvm/IR/DataLayout.h" 18 #include "llvm/IR/DerivedTypes.h" 19 #include "llvm/IR/LLVMContext.h" 20 #include "llvm/IR/LegacyPassManager.h" 21 #include "llvm/IR/Module.h" 22 #include "llvm/IR/Verifier.h" 23 #include "llvm/Pass.h" 24 #include "llvm/Support/CommandLine.h" 25 #include "llvm/Support/Debug.h" 26 #include "llvm/Support/FileUtilities.h" 27 #include "llvm/Support/Path.h" 28 #include "llvm/Support/Signals.h" 29 #include "llvm/Support/ToolOutputFile.h" 30 #include "llvm/Transforms/IPO.h" 31 #include "llvm/Transforms/Scalar.h" 32 #include "llvm/Transforms/Utils/Cloning.h" 33 #include "llvm/Transforms/Utils/CodeExtractor.h" 34 #include <set> 35 using namespace llvm; 36 37 #define DEBUG_TYPE "bugpoint" 38 39 namespace llvm { 40 bool DisableSimplifyCFG = false; 41 extern cl::opt<std::string> OutputPrefix; 42 } // End llvm namespace 43 44 namespace { 45 cl::opt<bool> NoDCE("disable-dce", 46 cl::desc("Do not use the -dce pass to reduce testcases")); 47 cl::opt<bool, true> 48 NoSCFG("disable-simplifycfg", cl::location(DisableSimplifyCFG), 49 cl::desc("Do not use the -simplifycfg pass to reduce testcases")); 50 51 Function *globalInitUsesExternalBA(GlobalVariable *GV) { 52 if (!GV->hasInitializer()) 53 return nullptr; 54 55 Constant *I = GV->getInitializer(); 56 57 // walk the values used by the initializer 58 // (and recurse into things like ConstantExpr) 59 std::vector<Constant *> Todo; 60 std::set<Constant *> Done; 61 Todo.push_back(I); 62 63 while (!Todo.empty()) { 64 Constant *V = Todo.back(); 65 Todo.pop_back(); 66 Done.insert(V); 67 68 if (BlockAddress *BA = dyn_cast<BlockAddress>(V)) { 69 Function *F = BA->getFunction(); 70 if (F->isDeclaration()) 71 return F; 72 } 73 74 for (User::op_iterator i = V->op_begin(), e = V->op_end(); i != e; ++i) { 75 Constant *C = dyn_cast<Constant>(*i); 76 if (C && !isa<GlobalValue>(C) && !Done.count(C)) 77 Todo.push_back(C); 78 } 79 } 80 return nullptr; 81 } 82 } // end anonymous namespace 83 84 std::unique_ptr<Module> 85 BugDriver::deleteInstructionFromProgram(const Instruction *I, 86 unsigned Simplification) { 87 // FIXME, use vmap? 88 Module *Clone = CloneModule(Program).release(); 89 90 const BasicBlock *PBB = I->getParent(); 91 const Function *PF = PBB->getParent(); 92 93 Module::iterator RFI = Clone->begin(); // Get iterator to corresponding fn 94 std::advance( 95 RFI, std::distance(PF->getParent()->begin(), Module::const_iterator(PF))); 96 97 Function::iterator RBI = RFI->begin(); // Get iterator to corresponding BB 98 std::advance(RBI, std::distance(PF->begin(), Function::const_iterator(PBB))); 99 100 BasicBlock::iterator RI = RBI->begin(); // Get iterator to corresponding inst 101 std::advance(RI, std::distance(PBB->begin(), BasicBlock::const_iterator(I))); 102 Instruction *TheInst = &*RI; // Got the corresponding instruction! 103 104 // If this instruction produces a value, replace any users with null values 105 if (!TheInst->getType()->isVoidTy()) 106 TheInst->replaceAllUsesWith(Constant::getNullValue(TheInst->getType())); 107 108 // Remove the instruction from the program. 109 TheInst->getParent()->getInstList().erase(TheInst); 110 111 // Spiff up the output a little bit. 112 std::vector<std::string> Passes; 113 114 /// Can we get rid of the -disable-* options? 115 if (Simplification > 1 && !NoDCE) 116 Passes.push_back("dce"); 117 if (Simplification && !DisableSimplifyCFG) 118 Passes.push_back("simplifycfg"); // Delete dead control flow 119 120 Passes.push_back("verify"); 121 std::unique_ptr<Module> New = runPassesOn(Clone, Passes); 122 delete Clone; 123 if (!New) { 124 errs() << "Instruction removal failed. Sorry. :( Please report a bug!\n"; 125 exit(1); 126 } 127 return New; 128 } 129 130 std::unique_ptr<Module> 131 BugDriver::performFinalCleanups(Module *M, bool MayModifySemantics) { 132 // Make all functions external, so GlobalDCE doesn't delete them... 133 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) 134 I->setLinkage(GlobalValue::ExternalLinkage); 135 136 std::vector<std::string> CleanupPasses; 137 CleanupPasses.push_back("globaldce"); 138 139 if (MayModifySemantics) 140 CleanupPasses.push_back("deadarghaX0r"); 141 else 142 CleanupPasses.push_back("deadargelim"); 143 144 std::unique_ptr<Module> New = runPassesOn(M, CleanupPasses); 145 if (!New) { 146 errs() << "Final cleanups failed. Sorry. :( Please report a bug!\n"; 147 return nullptr; 148 } 149 delete M; 150 return New; 151 } 152 153 std::unique_ptr<Module> BugDriver::extractLoop(Module *M) { 154 std::vector<std::string> LoopExtractPasses; 155 LoopExtractPasses.push_back("loop-extract-single"); 156 157 std::unique_ptr<Module> NewM = runPassesOn(M, LoopExtractPasses); 158 if (!NewM) { 159 outs() << "*** Loop extraction failed: "; 160 EmitProgressBitcode(M, "loopextraction", true); 161 outs() << "*** Sorry. :( Please report a bug!\n"; 162 return nullptr; 163 } 164 165 // Check to see if we created any new functions. If not, no loops were 166 // extracted and we should return null. Limit the number of loops we extract 167 // to avoid taking forever. 168 static unsigned NumExtracted = 32; 169 if (M->size() == NewM->size() || --NumExtracted == 0) { 170 return nullptr; 171 } else { 172 assert(M->size() < NewM->size() && "Loop extract removed functions?"); 173 Module::iterator MI = NewM->begin(); 174 for (unsigned i = 0, e = M->size(); i != e; ++i) 175 ++MI; 176 } 177 178 return NewM; 179 } 180 181 static void eliminateAliases(GlobalValue *GV) { 182 // First, check whether a GlobalAlias references this definition. 183 // GlobalAlias MAY NOT reference declarations. 184 for (;;) { 185 // 1. Find aliases 186 SmallVector<GlobalAlias *, 1> aliases; 187 Module *M = GV->getParent(); 188 for (Module::alias_iterator I = M->alias_begin(), E = M->alias_end(); 189 I != E; ++I) 190 if (I->getAliasee()->stripPointerCasts() == GV) 191 aliases.push_back(&*I); 192 if (aliases.empty()) 193 break; 194 // 2. Resolve aliases 195 for (unsigned i = 0, e = aliases.size(); i < e; ++i) { 196 aliases[i]->replaceAllUsesWith(aliases[i]->getAliasee()); 197 aliases[i]->eraseFromParent(); 198 } 199 // 3. Repeat until no more aliases found; there might 200 // be an alias to an alias... 201 } 202 } 203 204 // 205 // DeleteGlobalInitializer - "Remove" the global variable by deleting its 206 // initializer, 207 // making it external. 208 // 209 void llvm::DeleteGlobalInitializer(GlobalVariable *GV) { 210 eliminateAliases(GV); 211 GV->setInitializer(nullptr); 212 } 213 214 // DeleteFunctionBody - "Remove" the function by deleting all of its basic 215 // blocks, making it external. 216 // 217 void llvm::DeleteFunctionBody(Function *F) { 218 eliminateAliases(F); 219 // Function declarations can't have comdats. 220 F->setComdat(nullptr); 221 222 // delete the body of the function... 223 F->deleteBody(); 224 assert(F->isDeclaration() && "This didn't make the function external!"); 225 } 226 227 /// GetTorInit - Given a list of entries for static ctors/dtors, return them 228 /// as a constant array. 229 static Constant *GetTorInit(std::vector<std::pair<Function *, int>> &TorList) { 230 assert(!TorList.empty() && "Don't create empty tor list!"); 231 std::vector<Constant *> ArrayElts; 232 Type *Int32Ty = Type::getInt32Ty(TorList[0].first->getContext()); 233 234 StructType *STy = 235 StructType::get(Int32Ty, TorList[0].first->getType(), nullptr); 236 for (unsigned i = 0, e = TorList.size(); i != e; ++i) { 237 Constant *Elts[] = {ConstantInt::get(Int32Ty, TorList[i].second), 238 TorList[i].first}; 239 ArrayElts.push_back(ConstantStruct::get(STy, Elts)); 240 } 241 return ConstantArray::get( 242 ArrayType::get(ArrayElts[0]->getType(), ArrayElts.size()), ArrayElts); 243 } 244 245 /// SplitStaticCtorDtor - A module was recently split into two parts, M1/M2, and 246 /// M1 has all of the global variables. If M2 contains any functions that are 247 /// static ctors/dtors, we need to add an llvm.global_[cd]tors global to M2, and 248 /// prune appropriate entries out of M1s list. 249 static void SplitStaticCtorDtor(const char *GlobalName, Module *M1, Module *M2, 250 ValueToValueMapTy &VMap) { 251 GlobalVariable *GV = M1->getNamedGlobal(GlobalName); 252 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage() || !GV->use_empty()) 253 return; 254 255 std::vector<std::pair<Function *, int>> M1Tors, M2Tors; 256 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer()); 257 if (!InitList) 258 return; 259 260 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) { 261 if (ConstantStruct *CS = 262 dyn_cast<ConstantStruct>(InitList->getOperand(i))) { 263 if (CS->getNumOperands() != 2) 264 return; // Not array of 2-element structs. 265 266 if (CS->getOperand(1)->isNullValue()) 267 break; // Found a null terminator, stop here. 268 269 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0)); 270 int Priority = CI ? CI->getSExtValue() : 0; 271 272 Constant *FP = CS->getOperand(1); 273 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP)) 274 if (CE->isCast()) 275 FP = CE->getOperand(0); 276 if (Function *F = dyn_cast<Function>(FP)) { 277 if (!F->isDeclaration()) 278 M1Tors.push_back(std::make_pair(F, Priority)); 279 else { 280 // Map to M2's version of the function. 281 F = cast<Function>(VMap[F]); 282 M2Tors.push_back(std::make_pair(F, Priority)); 283 } 284 } 285 } 286 } 287 288 GV->eraseFromParent(); 289 if (!M1Tors.empty()) { 290 Constant *M1Init = GetTorInit(M1Tors); 291 new GlobalVariable(*M1, M1Init->getType(), false, 292 GlobalValue::AppendingLinkage, M1Init, GlobalName); 293 } 294 295 GV = M2->getNamedGlobal(GlobalName); 296 assert(GV && "Not a clone of M1?"); 297 assert(GV->use_empty() && "llvm.ctors shouldn't have uses!"); 298 299 GV->eraseFromParent(); 300 if (!M2Tors.empty()) { 301 Constant *M2Init = GetTorInit(M2Tors); 302 new GlobalVariable(*M2, M2Init->getType(), false, 303 GlobalValue::AppendingLinkage, M2Init, GlobalName); 304 } 305 } 306 307 std::unique_ptr<Module> 308 llvm::SplitFunctionsOutOfModule(Module *M, const std::vector<Function *> &F, 309 ValueToValueMapTy &VMap) { 310 // Make sure functions & globals are all external so that linkage 311 // between the two modules will work. 312 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) 313 I->setLinkage(GlobalValue::ExternalLinkage); 314 for (Module::global_iterator I = M->global_begin(), E = M->global_end(); 315 I != E; ++I) { 316 if (I->hasName() && I->getName()[0] == '\01') 317 I->setName(I->getName().substr(1)); 318 I->setLinkage(GlobalValue::ExternalLinkage); 319 } 320 321 ValueToValueMapTy NewVMap; 322 std::unique_ptr<Module> New = CloneModule(M, NewVMap); 323 324 // Remove the Test functions from the Safe module 325 std::set<Function *> TestFunctions; 326 for (unsigned i = 0, e = F.size(); i != e; ++i) { 327 Function *TNOF = cast<Function>(VMap[F[i]]); 328 DEBUG(errs() << "Removing function "); 329 DEBUG(TNOF->printAsOperand(errs(), false)); 330 DEBUG(errs() << "\n"); 331 TestFunctions.insert(cast<Function>(NewVMap[TNOF])); 332 DeleteFunctionBody(TNOF); // Function is now external in this module! 333 } 334 335 // Remove the Safe functions from the Test module 336 for (Function &I : *New) 337 if (!TestFunctions.count(&I)) 338 DeleteFunctionBody(&I); 339 340 // Try to split the global initializers evenly 341 for (GlobalVariable &I : M->globals()) { 342 GlobalVariable *GV = cast<GlobalVariable>(NewVMap[&I]); 343 if (Function *TestFn = globalInitUsesExternalBA(&I)) { 344 if (Function *SafeFn = globalInitUsesExternalBA(GV)) { 345 errs() << "*** Error: when reducing functions, encountered " 346 "the global '"; 347 GV->printAsOperand(errs(), false); 348 errs() << "' with an initializer that references blockaddresses " 349 "from safe function '" 350 << SafeFn->getName() << "' and from test function '" 351 << TestFn->getName() << "'.\n"; 352 exit(1); 353 } 354 DeleteGlobalInitializer(&I); // Delete the initializer to make it external 355 } else { 356 // If we keep it in the safe module, then delete it in the test module 357 DeleteGlobalInitializer(GV); 358 } 359 } 360 361 // Make sure that there is a global ctor/dtor array in both halves of the 362 // module if they both have static ctor/dtor functions. 363 SplitStaticCtorDtor("llvm.global_ctors", M, New.get(), NewVMap); 364 SplitStaticCtorDtor("llvm.global_dtors", M, New.get(), NewVMap); 365 366 return New; 367 } 368 369 //===----------------------------------------------------------------------===// 370 // Basic Block Extraction Code 371 //===----------------------------------------------------------------------===// 372 373 std::unique_ptr<Module> 374 BugDriver::extractMappedBlocksFromModule(const std::vector<BasicBlock *> &BBs, 375 Module *M) { 376 SmallString<128> Filename; 377 int FD; 378 std::error_code EC = sys::fs::createUniqueFile( 379 OutputPrefix + "-extractblocks%%%%%%%", FD, Filename); 380 if (EC) { 381 outs() << "*** Basic Block extraction failed!\n"; 382 errs() << "Error creating temporary file: " << EC.message() << "\n"; 383 EmitProgressBitcode(M, "basicblockextractfail", true); 384 return nullptr; 385 } 386 sys::RemoveFileOnSignal(Filename); 387 388 tool_output_file BlocksToNotExtractFile(Filename.c_str(), FD); 389 for (std::vector<BasicBlock *>::const_iterator I = BBs.begin(), E = BBs.end(); 390 I != E; ++I) { 391 BasicBlock *BB = *I; 392 // If the BB doesn't have a name, give it one so we have something to key 393 // off of. 394 if (!BB->hasName()) 395 BB->setName("tmpbb"); 396 BlocksToNotExtractFile.os() << BB->getParent()->getName() << " " 397 << BB->getName() << "\n"; 398 } 399 BlocksToNotExtractFile.os().close(); 400 if (BlocksToNotExtractFile.os().has_error()) { 401 errs() << "Error writing list of blocks to not extract\n"; 402 EmitProgressBitcode(M, "basicblockextractfail", true); 403 BlocksToNotExtractFile.os().clear_error(); 404 return nullptr; 405 } 406 BlocksToNotExtractFile.keep(); 407 408 std::string uniqueFN = "--extract-blocks-file="; 409 uniqueFN += Filename.str(); 410 const char *ExtraArg = uniqueFN.c_str(); 411 412 std::vector<std::string> PI; 413 PI.push_back("extract-blocks"); 414 std::unique_ptr<Module> Ret = runPassesOn(M, PI, 1, &ExtraArg); 415 416 sys::fs::remove(Filename.c_str()); 417 418 if (!Ret) { 419 outs() << "*** Basic Block extraction failed, please report a bug!\n"; 420 EmitProgressBitcode(M, "basicblockextractfail", true); 421 } 422 return Ret; 423 } 424