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