1 //===- ExtractFunction.cpp - Extract a function from Program --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
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"
37 #define DEBUG_TYPE "bugpoint"
40 bool DisableSimplifyCFG = false;
41 extern cl::opt<std::string> OutputPrefix;
42 } // End llvm namespace
45 cl::opt<bool> NoDCE("disable-dce",
46 cl::desc("Do not use the -dce pass to reduce testcases"));
48 NoSCFG("disable-simplifycfg", cl::location(DisableSimplifyCFG),
49 cl::desc("Do not use the -simplifycfg pass to reduce testcases"));
51 Function *globalInitUsesExternalBA(GlobalVariable *GV) {
52 if (!GV->hasInitializer())
55 Constant *I = GV->getInitializer();
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;
63 while (!Todo.empty()) {
64 Constant *V = Todo.back();
68 if (BlockAddress *BA = dyn_cast<BlockAddress>(V)) {
69 Function *F = BA->getFunction();
70 if (F->isDeclaration())
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))
82 } // end anonymous namespace
84 std::unique_ptr<Module>
85 BugDriver::deleteInstructionFromProgram(const Instruction *I,
86 unsigned Simplification) {
88 Module *Clone = CloneModule(Program).release();
90 const BasicBlock *PBB = I->getParent();
91 const Function *PF = PBB->getParent();
93 Module::iterator RFI = Clone->begin(); // Get iterator to corresponding fn
95 RFI, std::distance(PF->getParent()->begin(), Module::const_iterator(PF)));
97 Function::iterator RBI = RFI->begin(); // Get iterator to corresponding BB
98 std::advance(RBI, std::distance(PF->begin(), Function::const_iterator(PBB)));
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!
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()));
108 // Remove the instruction from the program.
109 TheInst->getParent()->getInstList().erase(TheInst);
111 // Spiff up the output a little bit.
112 std::vector<std::string> Passes;
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
120 Passes.push_back("verify");
121 std::unique_ptr<Module> New = runPassesOn(Clone, Passes);
124 errs() << "Instruction removal failed. Sorry. :( Please report a bug!\n";
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);
136 std::vector<std::string> CleanupPasses;
137 CleanupPasses.push_back("globaldce");
139 if (MayModifySemantics)
140 CleanupPasses.push_back("deadarghaX0r");
142 CleanupPasses.push_back("deadargelim");
144 std::unique_ptr<Module> New = runPassesOn(M, CleanupPasses);
146 errs() << "Final cleanups failed. Sorry. :( Please report a bug!\n";
153 std::unique_ptr<Module> BugDriver::extractLoop(Module *M) {
154 std::vector<std::string> LoopExtractPasses;
155 LoopExtractPasses.push_back("loop-extract-single");
157 std::unique_ptr<Module> NewM = runPassesOn(M, LoopExtractPasses);
159 outs() << "*** Loop extraction failed: ";
160 EmitProgressBitcode(M, "loopextraction", true);
161 outs() << "*** Sorry. :( Please report a bug!\n";
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) {
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)
181 static void eliminateAliases(GlobalValue *GV) {
182 // First, check whether a GlobalAlias references this definition.
183 // GlobalAlias MAY NOT reference declarations.
186 SmallVector<GlobalAlias *, 1> aliases;
187 Module *M = GV->getParent();
188 for (Module::alias_iterator I = M->alias_begin(), E = M->alias_end();
190 if (I->getAliasee()->stripPointerCasts() == GV)
191 aliases.push_back(&*I);
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();
199 // 3. Repeat until no more aliases found; there might
200 // be an alias to an alias...
205 // DeleteGlobalInitializer - "Remove" the global variable by deleting its
207 // making it external.
209 void llvm::DeleteGlobalInitializer(GlobalVariable *GV) {
210 eliminateAliases(GV);
211 GV->setInitializer(nullptr);
212 GV->setComdat(nullptr);
215 // DeleteFunctionBody - "Remove" the function by deleting all of its basic
216 // blocks, making it external.
218 void llvm::DeleteFunctionBody(Function *F) {
220 // Function declarations can't have comdats.
221 F->setComdat(nullptr);
223 // delete the body of the function...
225 assert(F->isDeclaration() && "This didn't make the function external!");
228 /// GetTorInit - Given a list of entries for static ctors/dtors, return them
229 /// as a constant array.
230 static Constant *GetTorInit(std::vector<std::pair<Function *, int>> &TorList) {
231 assert(!TorList.empty() && "Don't create empty tor list!");
232 std::vector<Constant *> ArrayElts;
233 Type *Int32Ty = Type::getInt32Ty(TorList[0].first->getContext());
236 StructType::get(Int32Ty, TorList[0].first->getType(), nullptr);
237 for (unsigned i = 0, e = TorList.size(); i != e; ++i) {
238 Constant *Elts[] = {ConstantInt::get(Int32Ty, TorList[i].second),
240 ArrayElts.push_back(ConstantStruct::get(STy, Elts));
242 return ConstantArray::get(
243 ArrayType::get(ArrayElts[0]->getType(), ArrayElts.size()), ArrayElts);
246 /// SplitStaticCtorDtor - A module was recently split into two parts, M1/M2, and
247 /// M1 has all of the global variables. If M2 contains any functions that are
248 /// static ctors/dtors, we need to add an llvm.global_[cd]tors global to M2, and
249 /// prune appropriate entries out of M1s list.
250 static void SplitStaticCtorDtor(const char *GlobalName, Module *M1, Module *M2,
251 ValueToValueMapTy &VMap) {
252 GlobalVariable *GV = M1->getNamedGlobal(GlobalName);
253 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage() || !GV->use_empty())
256 std::vector<std::pair<Function *, int>> M1Tors, M2Tors;
257 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
261 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
262 if (ConstantStruct *CS =
263 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
264 if (CS->getNumOperands() != 2)
265 return; // Not array of 2-element structs.
267 if (CS->getOperand(1)->isNullValue())
268 break; // Found a null terminator, stop here.
270 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
271 int Priority = CI ? CI->getSExtValue() : 0;
273 Constant *FP = CS->getOperand(1);
274 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
276 FP = CE->getOperand(0);
277 if (Function *F = dyn_cast<Function>(FP)) {
278 if (!F->isDeclaration())
279 M1Tors.push_back(std::make_pair(F, Priority));
281 // Map to M2's version of the function.
282 F = cast<Function>(VMap[F]);
283 M2Tors.push_back(std::make_pair(F, Priority));
289 GV->eraseFromParent();
290 if (!M1Tors.empty()) {
291 Constant *M1Init = GetTorInit(M1Tors);
292 new GlobalVariable(*M1, M1Init->getType(), false,
293 GlobalValue::AppendingLinkage, M1Init, GlobalName);
296 GV = M2->getNamedGlobal(GlobalName);
297 assert(GV && "Not a clone of M1?");
298 assert(GV->use_empty() && "llvm.ctors shouldn't have uses!");
300 GV->eraseFromParent();
301 if (!M2Tors.empty()) {
302 Constant *M2Init = GetTorInit(M2Tors);
303 new GlobalVariable(*M2, M2Init->getType(), false,
304 GlobalValue::AppendingLinkage, M2Init, GlobalName);
308 std::unique_ptr<Module>
309 llvm::SplitFunctionsOutOfModule(Module *M, const std::vector<Function *> &F,
310 ValueToValueMapTy &VMap) {
311 // Make sure functions & globals are all external so that linkage
312 // between the two modules will work.
313 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
314 I->setLinkage(GlobalValue::ExternalLinkage);
315 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
317 if (I->hasName() && I->getName()[0] == '\01')
318 I->setName(I->getName().substr(1));
319 I->setLinkage(GlobalValue::ExternalLinkage);
322 ValueToValueMapTy NewVMap;
323 std::unique_ptr<Module> New = CloneModule(M, NewVMap);
325 // Remove the Test functions from the Safe module
326 std::set<Function *> TestFunctions;
327 for (unsigned i = 0, e = F.size(); i != e; ++i) {
328 Function *TNOF = cast<Function>(VMap[F[i]]);
329 DEBUG(errs() << "Removing function ");
330 DEBUG(TNOF->printAsOperand(errs(), false));
331 DEBUG(errs() << "\n");
332 TestFunctions.insert(cast<Function>(NewVMap[TNOF]));
333 DeleteFunctionBody(TNOF); // Function is now external in this module!
336 // Remove the Safe functions from the Test module
337 for (Function &I : *New)
338 if (!TestFunctions.count(&I))
339 DeleteFunctionBody(&I);
341 // Try to split the global initializers evenly
342 for (GlobalVariable &I : M->globals()) {
343 GlobalVariable *GV = cast<GlobalVariable>(NewVMap[&I]);
344 if (Function *TestFn = globalInitUsesExternalBA(&I)) {
345 if (Function *SafeFn = globalInitUsesExternalBA(GV)) {
346 errs() << "*** Error: when reducing functions, encountered "
348 GV->printAsOperand(errs(), false);
349 errs() << "' with an initializer that references blockaddresses "
350 "from safe function '"
351 << SafeFn->getName() << "' and from test function '"
352 << TestFn->getName() << "'.\n";
355 DeleteGlobalInitializer(&I); // Delete the initializer to make it external
357 // If we keep it in the safe module, then delete it in the test module
358 DeleteGlobalInitializer(GV);
362 // Make sure that there is a global ctor/dtor array in both halves of the
363 // module if they both have static ctor/dtor functions.
364 SplitStaticCtorDtor("llvm.global_ctors", M, New.get(), NewVMap);
365 SplitStaticCtorDtor("llvm.global_dtors", M, New.get(), NewVMap);
370 //===----------------------------------------------------------------------===//
371 // Basic Block Extraction Code
372 //===----------------------------------------------------------------------===//
374 std::unique_ptr<Module>
375 BugDriver::extractMappedBlocksFromModule(const std::vector<BasicBlock *> &BBs,
377 SmallString<128> Filename;
379 std::error_code EC = sys::fs::createUniqueFile(
380 OutputPrefix + "-extractblocks%%%%%%%", FD, Filename);
382 outs() << "*** Basic Block extraction failed!\n";
383 errs() << "Error creating temporary file: " << EC.message() << "\n";
384 EmitProgressBitcode(M, "basicblockextractfail", true);
387 sys::RemoveFileOnSignal(Filename);
389 tool_output_file BlocksToNotExtractFile(Filename.c_str(), FD);
390 for (std::vector<BasicBlock *>::const_iterator I = BBs.begin(), E = BBs.end();
393 // If the BB doesn't have a name, give it one so we have something to key
396 BB->setName("tmpbb");
397 BlocksToNotExtractFile.os() << BB->getParent()->getName() << " "
398 << BB->getName() << "\n";
400 BlocksToNotExtractFile.os().close();
401 if (BlocksToNotExtractFile.os().has_error()) {
402 errs() << "Error writing list of blocks to not extract\n";
403 EmitProgressBitcode(M, "basicblockextractfail", true);
404 BlocksToNotExtractFile.os().clear_error();
407 BlocksToNotExtractFile.keep();
409 std::string uniqueFN = "--extract-blocks-file=";
410 uniqueFN += Filename.str();
411 const char *ExtraArg = uniqueFN.c_str();
413 std::vector<std::string> PI;
414 PI.push_back("extract-blocks");
415 std::unique_ptr<Module> Ret = runPassesOn(M, PI, 1, &ExtraArg);
417 sys::fs::remove(Filename.c_str());
420 outs() << "*** Basic Block extraction failed, please report a bug!\n";
421 EmitProgressBitcode(M, "basicblockextractfail", true);