blob: 4e63e1698eb44a661983696cbe9dce62edd30067 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ExtractFunction.cpp - Extract a function from Program --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5f5a5732007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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/Constants.h"
17#include "llvm/DerivedTypes.h"
Owen Andersonea6230a2009-07-13 22:40:32 +000018#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000019#include "llvm/Module.h"
20#include "llvm/PassManager.h"
21#include "llvm/Pass.h"
22#include "llvm/Analysis/Verifier.h"
Dan Gohman92cc6932009-07-13 22:56:37 +000023#include "llvm/Assembly/Writer.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000024#include "llvm/Transforms/IPO.h"
25#include "llvm/Transforms/Scalar.h"
26#include "llvm/Transforms/Utils/Cloning.h"
27#include "llvm/Transforms/Utils/FunctionUtils.h"
28#include "llvm/Target/TargetData.h"
29#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/FileUtilities.h"
Chris Lattnerb1aa85b2009-08-23 22:45:37 +000032#include "llvm/Support/raw_ostream.h"
Nick Lewycky43e736d2007-11-14 06:47:06 +000033#include "llvm/System/Path.h"
34#include "llvm/System/Signals.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000035#include <set>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000036using namespace llvm;
37
38namespace llvm {
39 bool DisableSimplifyCFG = false;
Daniel Dunbar377b5a32009-09-07 19:26:11 +000040 extern cl::opt<std::string> OutputPrefix;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000041} // End llvm namespace
42
43namespace {
44 cl::opt<bool>
45 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
52/// deleteInstructionFromProgram - This method clones the current Program and
53/// deletes the specified instruction from the cloned module. It then runs a
54/// series of cleanup passes (ADCE and SimplifyCFG) to eliminate any code which
55/// depends on the value. The modified module is then returned.
56///
57Module *BugDriver::deleteInstructionFromProgram(const Instruction *I,
58 unsigned Simplification) const {
59 Module *Result = CloneModule(Program);
60
61 const BasicBlock *PBB = I->getParent();
62 const Function *PF = PBB->getParent();
63
64 Module::iterator RFI = Result->begin(); // Get iterator to corresponding fn
65 std::advance(RFI, std::distance(PF->getParent()->begin(),
66 Module::const_iterator(PF)));
67
68 Function::iterator RBI = RFI->begin(); // Get iterator to corresponding BB
69 std::advance(RBI, std::distance(PF->begin(), Function::const_iterator(PBB)));
70
71 BasicBlock::iterator RI = RBI->begin(); // Get iterator to corresponding inst
72 std::advance(RI, std::distance(PBB->begin(), BasicBlock::const_iterator(I)));
73 Instruction *TheInst = RI; // Got the corresponding instruction!
74
75 // If this instruction produces a value, replace any users with null values
Dan Gohman16b5f412010-06-07 20:19:26 +000076 if (!TheInst->getType()->isVoidTy())
Owen Andersonaac28372009-07-31 20:28:14 +000077 TheInst->replaceAllUsesWith(Constant::getNullValue(TheInst->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000078
79 // Remove the instruction from the program.
80 TheInst->getParent()->getInstList().erase(TheInst);
81
82
83 //writeProgramToFile("current.bc", Result);
84
85 // Spiff up the output a little bit.
86 PassManager Passes;
87 // Make sure that the appropriate target data is always used...
88 Passes.add(new TargetData(Result));
89
90 /// FIXME: If this used runPasses() like the methods below, we could get rid
91 /// of the -disable-* options!
92 if (Simplification > 1 && !NoDCE)
93 Passes.add(createDeadCodeEliminationPass());
94 if (Simplification && !DisableSimplifyCFG)
95 Passes.add(createCFGSimplificationPass()); // Delete dead control flow
96
97 Passes.add(createVerifierPass());
98 Passes.run(*Result);
99 return Result;
100}
101
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000102/// performFinalCleanups - This method clones the current Program and performs
103/// a series of cleanups intended to get rid of extra cruft on the module
104/// before handing it to the user.
105///
106Module *BugDriver::performFinalCleanups(Module *M, bool MayModifySemantics) {
107 // Make all functions external, so GlobalDCE doesn't delete them...
108 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
109 I->setLinkage(GlobalValue::ExternalLinkage);
110
Rafael Espindola3f1a8f02010-08-08 03:55:08 +0000111 std::vector<std::string> CleanupPasses;
112 CleanupPasses.push_back("globaldce");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000113
114 if (MayModifySemantics)
Rafael Espindola3f1a8f02010-08-08 03:55:08 +0000115 CleanupPasses.push_back("deadarghaX0r");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000116 else
Rafael Espindola3f1a8f02010-08-08 03:55:08 +0000117 CleanupPasses.push_back("deadargelim");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000118
Rafael Espindola3f1a8f02010-08-08 03:55:08 +0000119 CleanupPasses.push_back("deadtypeelim");
Dan Gohman4a8e3f12010-06-07 20:28:37 +0000120
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000121 Module *New = runPassesOn(M, CleanupPasses);
122 if (New == 0) {
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000123 errs() << "Final cleanups failed. Sorry. :( Please report a bug!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000124 return M;
125 }
126 delete M;
127 return New;
128}
129
130
131/// ExtractLoop - Given a module, extract up to one loop from it into a new
132/// function. This returns null if there are no extractable loops in the
133/// program or if the loop extractor crashes.
134Module *BugDriver::ExtractLoop(Module *M) {
Rafael Espindola3f1a8f02010-08-08 03:55:08 +0000135 std::vector<std::string> LoopExtractPasses;
136 LoopExtractPasses.push_back("loop-extract-single");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000137
138 Module *NewM = runPassesOn(M, LoopExtractPasses);
139 if (NewM == 0) {
Dan Gohmanb714fab2009-07-16 15:30:09 +0000140 outs() << "*** Loop extraction failed: ";
Rafael Espindola131d2602010-07-28 18:12:30 +0000141 EmitProgressBitcode(M, "loopextraction", true);
Dan Gohmanb714fab2009-07-16 15:30:09 +0000142 outs() << "*** Sorry. :( Please report a bug!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000143 return 0;
144 }
145
146 // Check to see if we created any new functions. If not, no loops were
147 // extracted and we should return null. Limit the number of loops we extract
148 // to avoid taking forever.
149 static unsigned NumExtracted = 32;
150 if (M->size() == NewM->size() || --NumExtracted == 0) {
151 delete NewM;
152 return 0;
153 } else {
154 assert(M->size() < NewM->size() && "Loop extract removed functions?");
155 Module::iterator MI = NewM->begin();
156 for (unsigned i = 0, e = M->size(); i != e; ++i)
157 ++MI;
158 }
159
160 return NewM;
161}
162
163
164// DeleteFunctionBody - "Remove" the function by deleting all of its basic
165// blocks, making it external.
166//
167void llvm::DeleteFunctionBody(Function *F) {
168 // delete the body of the function...
169 F->deleteBody();
170 assert(F->isDeclaration() && "This didn't make the function external!");
171}
172
173/// GetTorInit - Given a list of entries for static ctors/dtors, return them
174/// as a constant array.
175static Constant *GetTorInit(std::vector<std::pair<Function*, int> > &TorList) {
176 assert(!TorList.empty() && "Don't create empty tor list!");
177 std::vector<Constant*> ArrayElts;
178 for (unsigned i = 0, e = TorList.size(); i != e; ++i) {
179 std::vector<Constant*> Elts;
Owen Anderson35b47072009-08-13 21:58:54 +0000180 Elts.push_back(ConstantInt::get(
181 Type::getInt32Ty(TorList[i].first->getContext()), TorList[i].second));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000182 Elts.push_back(TorList[i].first);
Nick Lewycky9229fdb2009-09-19 20:30:26 +0000183 ArrayElts.push_back(ConstantStruct::get(TorList[i].first->getContext(),
184 Elts, false));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 }
Owen Anderson6b6e2d92009-07-29 22:17:13 +0000186 return ConstantArray::get(ArrayType::get(ArrayElts[0]->getType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187 ArrayElts.size()),
188 ArrayElts);
189}
190
191/// SplitStaticCtorDtor - A module was recently split into two parts, M1/M2, and
192/// M1 has all of the global variables. If M2 contains any functions that are
193/// static ctors/dtors, we need to add an llvm.global_[cd]tors global to M2, and
194/// prune appropriate entries out of M1s list.
Dan Gohman819b9562009-04-22 15:57:18 +0000195static void SplitStaticCtorDtor(const char *GlobalName, Module *M1, Module *M2,
Duncan Sands5c49ddb2010-07-30 05:50:45 +0000196 ValueMap<const Value*, Value*> &VMap) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000197 GlobalVariable *GV = M1->getNamedGlobal(GlobalName);
Rafael Espindolaa168fc92009-01-15 20:18:42 +0000198 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199 !GV->use_empty()) return;
200
201 std::vector<std::pair<Function*, int> > M1Tors, M2Tors;
202 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
203 if (!InitList) return;
204
205 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
206 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
207 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
208
209 if (CS->getOperand(1)->isNullValue())
210 break; // Found a null terminator, stop here.
211
212 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
213 int Priority = CI ? CI->getSExtValue() : 0;
214
215 Constant *FP = CS->getOperand(1);
216 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
217 if (CE->isCast())
218 FP = CE->getOperand(0);
219 if (Function *F = dyn_cast<Function>(FP)) {
220 if (!F->isDeclaration())
221 M1Tors.push_back(std::make_pair(F, Priority));
222 else {
223 // Map to M2's version of the function.
Devang Patel7098baf2010-06-24 00:33:28 +0000224 F = cast<Function>(VMap[F]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000225 M2Tors.push_back(std::make_pair(F, Priority));
226 }
227 }
228 }
229 }
230
231 GV->eraseFromParent();
232 if (!M1Tors.empty()) {
233 Constant *M1Init = GetTorInit(M1Tors);
Owen Andersone17fc1d2009-07-08 19:03:57 +0000234 new GlobalVariable(*M1, M1Init->getType(), false,
Owen Andersone0f136d2009-07-08 01:26:06 +0000235 GlobalValue::AppendingLinkage,
Owen Andersone17fc1d2009-07-08 19:03:57 +0000236 M1Init, GlobalName);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237 }
238
239 GV = M2->getNamedGlobal(GlobalName);
240 assert(GV && "Not a clone of M1?");
241 assert(GV->use_empty() && "llvm.ctors shouldn't have uses!");
242
243 GV->eraseFromParent();
244 if (!M2Tors.empty()) {
245 Constant *M2Init = GetTorInit(M2Tors);
Owen Andersone17fc1d2009-07-08 19:03:57 +0000246 new GlobalVariable(*M2, M2Init->getType(), false,
Owen Andersone0f136d2009-07-08 01:26:06 +0000247 GlobalValue::AppendingLinkage,
Owen Andersone17fc1d2009-07-08 19:03:57 +0000248 M2Init, GlobalName);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000249 }
250}
251
252
253/// SplitFunctionsOutOfModule - Given a module and a list of functions in the
254/// module, split the functions OUT of the specified module, and place them in
255/// the new module.
Dan Gohman819b9562009-04-22 15:57:18 +0000256Module *
257llvm::SplitFunctionsOutOfModule(Module *M,
258 const std::vector<Function*> &F,
Devang Patel7098baf2010-06-24 00:33:28 +0000259 ValueMap<const Value*, Value*> &VMap) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000260 // Make sure functions & globals are all external so that linkage
261 // between the two modules will work.
262 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
263 I->setLinkage(GlobalValue::ExternalLinkage);
264 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
Owen Anderson771a81d2008-07-08 16:38:42 +0000265 I != E; ++I) {
Daniel Dunbar1be13862009-07-26 00:34:27 +0000266 if (I->hasName() && I->getName()[0] == '\01')
267 I->setName(I->getName().substr(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000268 I->setLinkage(GlobalValue::ExternalLinkage);
Owen Anderson771a81d2008-07-08 16:38:42 +0000269 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000270
Devang Patel7098baf2010-06-24 00:33:28 +0000271 ValueMap<const Value*, Value*> NewVMap;
272 Module *New = CloneModule(M, NewVMap);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273
274 // Make sure global initializers exist only in the safe module (CBE->.so)
275 for (Module::global_iterator I = New->global_begin(), E = New->global_end();
276 I != E; ++I)
277 I->setInitializer(0); // Delete the initializer to make it external
278
279 // Remove the Test functions from the Safe module
Dan Gohman819b9562009-04-22 15:57:18 +0000280 std::set<Function *> TestFunctions;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000281 for (unsigned i = 0, e = F.size(); i != e; ++i) {
Devang Patel7098baf2010-06-24 00:33:28 +0000282 Function *TNOF = cast<Function>(VMap[F[i]]);
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000283 DEBUG(errs() << "Removing function ");
284 DEBUG(WriteAsOperand(errs(), TNOF, false));
285 DEBUG(errs() << "\n");
Devang Patel7098baf2010-06-24 00:33:28 +0000286 TestFunctions.insert(cast<Function>(NewVMap[TNOF]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000287 DeleteFunctionBody(TNOF); // Function is now external in this module!
288 }
289
290
291 // Remove the Safe functions from the Test module
292 for (Module::iterator I = New->begin(), E = New->end(); I != E; ++I)
Dan Gohman819b9562009-04-22 15:57:18 +0000293 if (!TestFunctions.count(I))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294 DeleteFunctionBody(I);
295
296
297 // Make sure that there is a global ctor/dtor array in both halves of the
298 // module if they both have static ctor/dtor functions.
Devang Patel7098baf2010-06-24 00:33:28 +0000299 SplitStaticCtorDtor("llvm.global_ctors", M, New, NewVMap);
300 SplitStaticCtorDtor("llvm.global_dtors", M, New, NewVMap);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000301
302 return New;
303}
304
305//===----------------------------------------------------------------------===//
306// Basic Block Extraction Code
307//===----------------------------------------------------------------------===//
308
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309/// ExtractMappedBlocksFromModule - Extract all but the specified basic blocks
310/// into their own functions. The only detail is that M is actually a module
311/// cloned from the one the BBs are in, so some mapping needs to be performed.
312/// If this operation fails for some reason (ie the implementation is buggy),
313/// this function should return null, otherwise it returns a new Module.
314Module *BugDriver::ExtractMappedBlocksFromModule(const
315 std::vector<BasicBlock*> &BBs,
316 Module *M) {
Daniel Dunbar377b5a32009-09-07 19:26:11 +0000317 sys::Path uniqueFilename(OutputPrefix + "-extractblocks");
Nick Lewycky43e736d2007-11-14 06:47:06 +0000318 std::string ErrMsg;
319 if (uniqueFilename.createTemporaryFileOnDisk(true, &ErrMsg)) {
Dan Gohmanb714fab2009-07-16 15:30:09 +0000320 outs() << "*** Basic Block extraction failed!\n";
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000321 errs() << "Error creating temporary file: " << ErrMsg << "\n";
Rafael Espindola131d2602010-07-28 18:12:30 +0000322 EmitProgressBitcode(M, "basicblockextractfail", true);
Nick Lewycky43e736d2007-11-14 06:47:06 +0000323 return 0;
324 }
325 sys::RemoveFileOnSignal(uniqueFilename);
326
Dan Gohmanb714fab2009-07-16 15:30:09 +0000327 std::string ErrorInfo;
Dan Gohman176426d2009-08-25 15:34:52 +0000328 raw_fd_ostream BlocksToNotExtractFile(uniqueFilename.c_str(), ErrorInfo);
Dan Gohmanb714fab2009-07-16 15:30:09 +0000329 if (!ErrorInfo.empty()) {
330 outs() << "*** Basic Block extraction failed!\n";
331 errs() << "Error writing list of blocks to not extract: " << ErrorInfo
Dan Gohmanf8b81bf2009-07-15 16:35:29 +0000332 << "\n";
Rafael Espindola131d2602010-07-28 18:12:30 +0000333 EmitProgressBitcode(M, "basicblockextractfail", true);
Nick Lewycky43e736d2007-11-14 06:47:06 +0000334 return 0;
335 }
336 for (std::vector<BasicBlock*>::const_iterator I = BBs.begin(), E = BBs.end();
337 I != E; ++I) {
338 BasicBlock *BB = *I;
Chris Lattner2dda3202008-01-08 04:26:20 +0000339 // If the BB doesn't have a name, give it one so we have something to key
340 // off of.
341 if (!BB->hasName()) BB->setName("tmpbb");
Daniel Dunbar1e13b972009-07-24 08:24:36 +0000342 BlocksToNotExtractFile << BB->getParent()->getNameStr() << " "
Nick Lewycky43e736d2007-11-14 06:47:06 +0000343 << BB->getName() << "\n";
344 }
345 BlocksToNotExtractFile.close();
346
Benjamin Kramerd65ad3c62010-01-28 18:04:38 +0000347 std::string uniqueFN = "--extract-blocks-file=" + uniqueFilename.str();
348 const char *ExtraArg = uniqueFN.c_str();
Nick Lewycky43e736d2007-11-14 06:47:06 +0000349
Rafael Espindola3f1a8f02010-08-08 03:55:08 +0000350 std::vector<std::string> PI;
351 PI.push_back("extract-blocks");
Nick Lewycky43e736d2007-11-14 06:47:06 +0000352 Module *Ret = runPassesOn(M, PI, false, 1, &ExtraArg);
353
Dan Gohman2e634222010-05-27 20:51:54 +0000354 uniqueFilename.eraseFromDisk(); // Free disk space
Nick Lewycky43e736d2007-11-14 06:47:06 +0000355
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000356 if (Ret == 0) {
Dan Gohmanb714fab2009-07-16 15:30:09 +0000357 outs() << "*** Basic Block extraction failed, please report a bug!\n";
Rafael Espindola131d2602010-07-28 18:12:30 +0000358 EmitProgressBitcode(M, "basicblockextractfail", true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000359 }
360 return Ret;
361}