blob: 48f1575c25eb863ee073bc4d8569154d13fd9800 [file] [log] [blame]
Chris Lattnerafade922002-11-20 22:28:10 +00001//===- ExtractFunction.cpp - Extract a function from Program --------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
John Criswell7c0e0222003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner21c62da2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
John Criswell7c0e0222003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerafade922002-11-20 22:28:10 +00009//
Chris Lattnerefdc0b52004-03-14 20:50:42 +000010// This file implements several methods that are used to extract functions,
11// loops, or portions of a module from the rest of the module.
Chris Lattnerafade922002-11-20 22:28:10 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "BugDriver.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000016#include "llvm/IR/Constants.h"
17#include "llvm/IR/DataLayout.h"
18#include "llvm/IR/DerivedTypes.h"
19#include "llvm/IR/LLVMContext.h"
Chandler Carruth417c5c12015-02-13 10:01:29 +000020#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000021#include "llvm/IR/Module.h"
Chandler Carruth56e13942014-01-13 09:26:24 +000022#include "llvm/IR/Verifier.h"
Brian Gaeked1a85a72003-09-10 21:11:42 +000023#include "llvm/Pass.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000024#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"
Chris Lattnerafade922002-11-20 22:28:10 +000030#include "llvm/Transforms/IPO.h"
Chris Lattner65207852003-01-23 02:48:33 +000031#include "llvm/Transforms/Scalar.h"
Chris Lattnerafade922002-11-20 22:28:10 +000032#include "llvm/Transforms/Utils/Cloning.h"
Chandler Carruth99650c92012-05-04 10:18:49 +000033#include "llvm/Transforms/Utils/CodeExtractor.h"
Chris Lattnerfb4b96e2004-04-02 16:28:32 +000034#include <set>
Chris Lattnerc6b519d2003-11-23 04:51:05 +000035using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000036
Chandler Carruth283b3992014-04-21 22:55:11 +000037#define DEBUG_TYPE "bugpoint"
38
Brian Gaeked0fde302003-11-11 22:41:34 +000039namespace llvm {
Justin Bogner388e8b92016-09-02 01:21:37 +000040bool DisableSimplifyCFG = false;
41extern cl::opt<std::string> OutputPrefix;
Brian Gaeked0fde302003-11-11 22:41:34 +000042} // End llvm namespace
43
Chris Lattner6db70ef2003-04-25 22:08:12 +000044namespace {
Justin Bogner388e8b92016-09-02 01:21:37 +000045cl::opt<bool> NoDCE("disable-dce",
46 cl::desc("Do not use the -dce pass to reduce testcases"));
47cl::opt<bool, true>
48 NoSCFG("disable-simplifycfg", cl::location(DisableSimplifyCFG),
49 cl::desc("Do not use the -simplifycfg pass to reduce testcases"));
Eli Friedman967570f2012-02-22 01:43:47 +000050
Justin Bogner388e8b92016-09-02 01:21:37 +000051Function *globalInitUsesExternalBA(GlobalVariable *GV) {
52 if (!GV->hasInitializer())
Craig Topper573faec2014-04-25 04:24:47 +000053 return nullptr;
Justin Bogner388e8b92016-09-02 01:21:37 +000054
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 }
Eli Friedman967570f2012-02-22 01:43:47 +000079 }
Justin Bogner388e8b92016-09-02 01:21:37 +000080 return nullptr;
81}
82} // end anonymous namespace
Chris Lattnerafade922002-11-20 22:28:10 +000083
Rafael Espindola1bfd87a2014-08-26 17:19:03 +000084std::unique_ptr<Module>
85BugDriver::deleteInstructionFromProgram(const Instruction *I,
86 unsigned Simplification) {
Rafael Espindola866aa0d2010-08-10 15:46:11 +000087 // FIXME, use vmap?
Rafael Espindola22b77242018-02-14 19:50:40 +000088 std::unique_ptr<Module> Clone = CloneModule(*Program);
Chris Lattner65207852003-01-23 02:48:33 +000089
Chris Lattner0cc88072004-02-18 21:50:26 +000090 const BasicBlock *PBB = I->getParent();
91 const Function *PF = PBB->getParent();
Chris Lattner65207852003-01-23 02:48:33 +000092
Rafael Espindola866aa0d2010-08-10 15:46:11 +000093 Module::iterator RFI = Clone->begin(); // Get iterator to corresponding fn
Justin Bogner388e8b92016-09-02 01:21:37 +000094 std::advance(
95 RFI, std::distance(PF->getParent()->begin(), Module::const_iterator(PF)));
Chris Lattner65207852003-01-23 02:48:33 +000096
Justin Bogner388e8b92016-09-02 01:21:37 +000097 Function::iterator RBI = RFI->begin(); // Get iterator to corresponding BB
Chris Lattner0cc88072004-02-18 21:50:26 +000098 std::advance(RBI, std::distance(PF->begin(), Function::const_iterator(PBB)));
Chris Lattner65207852003-01-23 02:48:33 +000099
100 BasicBlock::iterator RI = RBI->begin(); // Get iterator to corresponding inst
Chris Lattner0cc88072004-02-18 21:50:26 +0000101 std::advance(RI, std::distance(PBB->begin(), BasicBlock::const_iterator(I)));
Duncan P. N. Exon Smith1e221d52015-10-20 19:36:39 +0000102 Instruction *TheInst = &*RI; // Got the corresponding instruction!
Chris Lattner65207852003-01-23 02:48:33 +0000103
104 // If this instruction produces a value, replace any users with null values
Dan Gohmane49a13e2010-06-07 20:19:26 +0000105 if (!TheInst->getType()->isVoidTy())
Owen Andersona7235ea2009-07-31 20:28:14 +0000106 TheInst->replaceAllUsesWith(Constant::getNullValue(TheInst->getType()));
Chris Lattner65207852003-01-23 02:48:33 +0000107
108 // Remove the instruction from the program.
Chris Lattner0cc88072004-02-18 21:50:26 +0000109 TheInst->getParent()->getInstList().erase(TheInst);
Chris Lattner65207852003-01-23 02:48:33 +0000110
Chris Lattner44be2572003-04-24 22:53:24 +0000111 // Spiff up the output a little bit.
Rafael Espindola866aa0d2010-08-10 15:46:11 +0000112 std::vector<std::string> Passes;
Chris Lattner5da69c72003-10-23 15:42:55 +0000113
Rafael Espindola866aa0d2010-08-10 15:46:11 +0000114 /// Can we get rid of the -disable-* options?
Chris Lattner6db70ef2003-04-25 22:08:12 +0000115 if (Simplification > 1 && !NoDCE)
Rafael Espindola866aa0d2010-08-10 15:46:11 +0000116 Passes.push_back("dce");
Chris Lattner47ae4a12003-08-05 15:51:05 +0000117 if (Simplification && !DisableSimplifyCFG)
Justin Bogner388e8b92016-09-02 01:21:37 +0000118 Passes.push_back("simplifycfg"); // Delete dead control flow
Chris Lattner10f22cb2003-03-07 18:17:13 +0000119
Rafael Espindola866aa0d2010-08-10 15:46:11 +0000120 Passes.push_back("verify");
Vedant Kumar00088b82018-02-09 05:09:50 +0000121 std::unique_ptr<Module> New = runPassesOn(Clone.get(), Passes);
Rafael Espindola866aa0d2010-08-10 15:46:11 +0000122 if (!New) {
123 errs() << "Instruction removal failed. Sorry. :( Please report a bug!\n";
124 exit(1);
125 }
126 return New;
Chris Lattner65207852003-01-23 02:48:33 +0000127}
Chris Lattnerba386d92003-02-28 16:13:20 +0000128
Rafael Espindola1bfd87a2014-08-26 17:19:03 +0000129std::unique_ptr<Module>
Rafael Espindola46e55022018-04-24 20:15:27 +0000130BugDriver::performFinalCleanups(std::unique_ptr<Module> M,
131 bool MayModifySemantics) {
Chris Lattner28b8ed92003-05-21 19:41:31 +0000132 // 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);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000135
Rafael Espindola8261dfe2010-08-08 03:55:08 +0000136 std::vector<std::string> CleanupPasses;
137 CleanupPasses.push_back("globaldce");
Chris Lattnerfcb6ec02003-11-05 21:45:35 +0000138
Chris Lattnerc6b519d2003-11-23 04:51:05 +0000139 if (MayModifySemantics)
Rafael Espindola8261dfe2010-08-08 03:55:08 +0000140 CleanupPasses.push_back("deadarghaX0r");
Chris Lattnerc6b519d2003-11-23 04:51:05 +0000141 else
Rafael Espindola8261dfe2010-08-08 03:55:08 +0000142 CleanupPasses.push_back("deadargelim");
Chris Lattnerfcb6ec02003-11-05 21:45:35 +0000143
Rafael Espindola46e55022018-04-24 20:15:27 +0000144 std::unique_ptr<Module> New = runPassesOn(M.get(), CleanupPasses);
Craig Topper573faec2014-04-25 04:24:47 +0000145 if (!New) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000146 errs() << "Final cleanups failed. Sorry. :( Please report a bug!\n";
Rafael Espindola1bfd87a2014-08-26 17:19:03 +0000147 return nullptr;
Chris Lattnerfcb6ec02003-11-05 21:45:35 +0000148 }
Chris Lattnera75766a2004-03-14 21:17:22 +0000149 return New;
Chris Lattnerba386d92003-02-28 16:13:20 +0000150}
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000151
Rafael Espindola1bfd87a2014-08-26 17:19:03 +0000152std::unique_ptr<Module> BugDriver::extractLoop(Module *M) {
Rafael Espindola8261dfe2010-08-08 03:55:08 +0000153 std::vector<std::string> LoopExtractPasses;
154 LoopExtractPasses.push_back("loop-extract-single");
Chris Lattner7546c382004-03-14 20:02:07 +0000155
Rafael Espindola1bfd87a2014-08-26 17:19:03 +0000156 std::unique_ptr<Module> NewM = runPassesOn(M, LoopExtractPasses);
Craig Topper573faec2014-04-25 04:24:47 +0000157 if (!NewM) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000158 outs() << "*** Loop extraction failed: ";
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000159 EmitProgressBitcode(*M, "loopextraction", true);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000160 outs() << "*** Sorry. :( Please report a bug!\n";
Craig Topper573faec2014-04-25 04:24:47 +0000161 return nullptr;
Chris Lattner7546c382004-03-14 20:02:07 +0000162 }
Chris Lattnera75766a2004-03-14 21:17:22 +0000163
164 // Check to see if we created any new functions. If not, no loops were
Chris Lattnera269ec72004-11-18 19:40:13 +0000165 // extracted and we should return null. Limit the number of loops we extract
166 // to avoid taking forever.
167 static unsigned NumExtracted = 32;
Chris Lattner90c18c52004-11-16 06:31:38 +0000168 if (M->size() == NewM->size() || --NumExtracted == 0) {
Craig Topper573faec2014-04-25 04:24:47 +0000169 return nullptr;
Chris Lattner90c18c52004-11-16 06:31:38 +0000170 } else {
171 assert(M->size() < NewM->size() && "Loop extract removed functions?");
172 Module::iterator MI = NewM->begin();
173 for (unsigned i = 0, e = M->size(); i != e; ++i)
174 ++MI;
Chris Lattnera75766a2004-03-14 21:17:22 +0000175 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000176
Chris Lattnera75766a2004-03-14 21:17:22 +0000177 return NewM;
Chris Lattner7546c382004-03-14 20:02:07 +0000178}
179
Hal Finkelc818be02015-11-26 19:23:49 +0000180static void eliminateAliases(GlobalValue *GV) {
181 // First, check whether a GlobalAlias references this definition.
182 // GlobalAlias MAY NOT reference declarations.
183 for (;;) {
184 // 1. Find aliases
Justin Bogner388e8b92016-09-02 01:21:37 +0000185 SmallVector<GlobalAlias *, 1> aliases;
Hal Finkelc818be02015-11-26 19:23:49 +0000186 Module *M = GV->getParent();
Justin Bogner388e8b92016-09-02 01:21:37 +0000187 for (Module::alias_iterator I = M->alias_begin(), E = M->alias_end();
188 I != E; ++I)
Hal Finkelc818be02015-11-26 19:23:49 +0000189 if (I->getAliasee()->stripPointerCasts() == GV)
190 aliases.push_back(&*I);
191 if (aliases.empty())
192 break;
193 // 2. Resolve aliases
Justin Bogner388e8b92016-09-02 01:21:37 +0000194 for (unsigned i = 0, e = aliases.size(); i < e; ++i) {
Hal Finkelc818be02015-11-26 19:23:49 +0000195 aliases[i]->replaceAllUsesWith(aliases[i]->getAliasee());
196 aliases[i]->eraseFromParent();
197 }
198 // 3. Repeat until no more aliases found; there might
199 // be an alias to an alias...
200 }
201}
202
203//
Justin Bogner388e8b92016-09-02 01:21:37 +0000204// DeleteGlobalInitializer - "Remove" the global variable by deleting its
205// initializer,
Hal Finkelc818be02015-11-26 19:23:49 +0000206// making it external.
207//
208void llvm::DeleteGlobalInitializer(GlobalVariable *GV) {
209 eliminateAliases(GV);
210 GV->setInitializer(nullptr);
Hal Finkela65ac0d2017-04-11 00:18:42 +0000211 GV->setComdat(nullptr);
Hal Finkelc818be02015-11-26 19:23:49 +0000212}
Chris Lattner7546c382004-03-14 20:02:07 +0000213
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000214// DeleteFunctionBody - "Remove" the function by deleting all of its basic
215// blocks, making it external.
216//
217void llvm::DeleteFunctionBody(Function *F) {
Hal Finkelc818be02015-11-26 19:23:49 +0000218 eliminateAliases(F);
Justin Lebarb570d712016-06-15 23:20:12 +0000219 // Function declarations can't have comdats.
220 F->setComdat(nullptr);
Hal Finkelc818be02015-11-26 19:23:49 +0000221
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000222 // delete the body of the function...
223 F->deleteBody();
Reid Spencer5cbf9852007-01-30 20:08:39 +0000224 assert(F->isDeclaration() && "This didn't make the function external!");
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000225}
226
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000227/// GetTorInit - Given a list of entries for static ctors/dtors, return them
228/// as a constant array.
Justin Bogner388e8b92016-09-02 01:21:37 +0000229static Constant *GetTorInit(std::vector<std::pair<Function *, int>> &TorList) {
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000230 assert(!TorList.empty() && "Don't create empty tor list!");
Justin Bogner388e8b92016-09-02 01:21:37 +0000231 std::vector<Constant *> ArrayElts;
Jay Foad5fdd6c82011-07-12 14:06:48 +0000232 Type *Int32Ty = Type::getInt32Ty(TorList[0].first->getContext());
David Majnemer3bd9ff32015-02-26 01:10:49 +0000233
Serge Gueltond35f86e2017-05-09 19:31:13 +0000234 StructType *STy = StructType::get(Int32Ty, TorList[0].first->getType());
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000235 for (unsigned i = 0, e = TorList.size(); i != e; ++i) {
Justin Bogner388e8b92016-09-02 01:21:37 +0000236 Constant *Elts[] = {ConstantInt::get(Int32Ty, TorList[i].second),
237 TorList[i].first};
Chris Lattnerb065b062011-06-20 04:01:31 +0000238 ArrayElts.push_back(ConstantStruct::get(STy, Elts));
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000239 }
Justin Bogner388e8b92016-09-02 01:21:37 +0000240 return ConstantArray::get(
241 ArrayType::get(ArrayElts[0]->getType(), ArrayElts.size()), ArrayElts);
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000242}
243
244/// SplitStaticCtorDtor - A module was recently split into two parts, M1/M2, and
245/// M1 has all of the global variables. If M2 contains any functions that are
246/// static ctors/dtors, we need to add an llvm.global_[cd]tors global to M2, and
247/// prune appropriate entries out of M1s list.
Dan Gohmand50330c2009-04-22 15:57:18 +0000248static void SplitStaticCtorDtor(const char *GlobalName, Module *M1, Module *M2,
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000249 ValueToValueMapTy &VMap) {
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000250 GlobalVariable *GV = M1->getNamedGlobal(GlobalName);
Justin Bogner388e8b92016-09-02 01:21:37 +0000251 if (!GV || GV->isDeclaration() || GV->hasLocalLinkage() || !GV->use_empty())
252 return;
253
254 std::vector<std::pair<Function *, int>> M1Tors, M2Tors;
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000255 ConstantArray *InitList = dyn_cast<ConstantArray>(GV->getInitializer());
Justin Bogner388e8b92016-09-02 01:21:37 +0000256 if (!InitList)
257 return;
258
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000259 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i) {
Justin Bogner388e8b92016-09-02 01:21:37 +0000260 if (ConstantStruct *CS =
261 dyn_cast<ConstantStruct>(InitList->getOperand(i))) {
262 if (CS->getNumOperands() != 2)
263 return; // Not array of 2-element structs.
264
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000265 if (CS->getOperand(1)->isNullValue())
Justin Bogner388e8b92016-09-02 01:21:37 +0000266 break; // Found a null terminator, stop here.
267
Reid Spencerb83eb642006-10-20 07:07:24 +0000268 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
269 int Priority = CI ? CI->getSExtValue() : 0;
Justin Bogner388e8b92016-09-02 01:21:37 +0000270
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000271 Constant *FP = CS->getOperand(1);
272 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(FP))
Reid Spencer3da59db2006-11-27 01:05:10 +0000273 if (CE->isCast())
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000274 FP = CE->getOperand(0);
275 if (Function *F = dyn_cast<Function>(FP)) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000276 if (!F->isDeclaration())
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000277 M1Tors.push_back(std::make_pair(F, Priority));
278 else {
279 // Map to M2's version of the function.
Devang Patele9916a32010-06-24 00:33:28 +0000280 F = cast<Function>(VMap[F]);
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000281 M2Tors.push_back(std::make_pair(F, Priority));
282 }
283 }
284 }
285 }
Justin Bogner388e8b92016-09-02 01:21:37 +0000286
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000287 GV->eraseFromParent();
288 if (!M1Tors.empty()) {
289 Constant *M1Init = GetTorInit(M1Tors);
Owen Andersone9b11b42009-07-08 19:03:57 +0000290 new GlobalVariable(*M1, M1Init->getType(), false,
Justin Bogner388e8b92016-09-02 01:21:37 +0000291 GlobalValue::AppendingLinkage, M1Init, GlobalName);
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000292 }
293
294 GV = M2->getNamedGlobal(GlobalName);
295 assert(GV && "Not a clone of M1?");
296 assert(GV->use_empty() && "llvm.ctors shouldn't have uses!");
297
298 GV->eraseFromParent();
299 if (!M2Tors.empty()) {
300 Constant *M2Init = GetTorInit(M2Tors);
Owen Andersone9b11b42009-07-08 19:03:57 +0000301 new GlobalVariable(*M2, M2Init->getType(), false,
Justin Bogner388e8b92016-09-02 01:21:37 +0000302 GlobalValue::AppendingLinkage, M2Init, GlobalName);
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000303 }
304}
305
Rafael Espindola18d70502015-12-09 00:34:10 +0000306std::unique_ptr<Module>
307llvm::SplitFunctionsOutOfModule(Module *M, const std::vector<Function *> &F,
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000308 ValueToValueMapTy &VMap) {
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000309 // Make sure functions & globals are all external so that linkage
310 // between the two modules will work.
311 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
312 I->setLinkage(GlobalValue::ExternalLinkage);
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000313 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
Owen Anderson7220b812008-07-08 16:38:42 +0000314 I != E; ++I) {
Daniel Dunbar3f53fa92009-07-26 00:34:27 +0000315 if (I->hasName() && I->getName()[0] == '\01')
316 I->setName(I->getName().substr(1));
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000317 I->setLinkage(GlobalValue::ExternalLinkage);
Owen Anderson7220b812008-07-08 16:38:42 +0000318 }
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000319
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000320 ValueToValueMapTy NewVMap;
Rafael Espindola22b77242018-02-14 19:50:40 +0000321 std::unique_ptr<Module> New = CloneModule(*M, NewVMap);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000322
Chris Lattnerfef02422006-11-09 06:24:56 +0000323 // Remove the Test functions from the Safe module
Dan Gohmand50330c2009-04-22 15:57:18 +0000324 std::set<Function *> TestFunctions;
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000325 for (unsigned i = 0, e = F.size(); i != e; ++i) {
Devang Patele9916a32010-06-24 00:33:28 +0000326 Function *TNOF = cast<Function>(VMap[F[i]]);
Nicola Zaghen0818e782018-05-14 12:53:11 +0000327 LLVM_DEBUG(errs() << "Removing function ");
328 LLVM_DEBUG(TNOF->printAsOperand(errs(), false));
329 LLVM_DEBUG(errs() << "\n");
Devang Patele9916a32010-06-24 00:33:28 +0000330 TestFunctions.insert(cast<Function>(NewVMap[TNOF]));
Justin Bogner388e8b92016-09-02 01:21:37 +0000331 DeleteFunctionBody(TNOF); // Function is now external in this module!
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000332 }
333
Chris Lattnerfef02422006-11-09 06:24:56 +0000334 // Remove the Safe functions from the Test module
Duncan P. N. Exon Smith1e221d52015-10-20 19:36:39 +0000335 for (Function &I : *New)
336 if (!TestFunctions.count(&I))
337 DeleteFunctionBody(&I);
Patrick Jenkinse47863e2006-07-28 01:19:28 +0000338
Eli Friedman967570f2012-02-22 01:43:47 +0000339 // Try to split the global initializers evenly
Duncan P. N. Exon Smith1e221d52015-10-20 19:36:39 +0000340 for (GlobalVariable &I : M->globals()) {
341 GlobalVariable *GV = cast<GlobalVariable>(NewVMap[&I]);
342 if (Function *TestFn = globalInitUsesExternalBA(&I)) {
Eli Friedman967570f2012-02-22 01:43:47 +0000343 if (Function *SafeFn = globalInitUsesExternalBA(GV)) {
344 errs() << "*** Error: when reducing functions, encountered "
345 "the global '";
Chandler Carruth560e3952014-01-09 02:29:41 +0000346 GV->printAsOperand(errs(), false);
Eli Friedman967570f2012-02-22 01:43:47 +0000347 errs() << "' with an initializer that references blockaddresses "
Justin Bogner388e8b92016-09-02 01:21:37 +0000348 "from safe function '"
349 << SafeFn->getName() << "' and from test function '"
350 << TestFn->getName() << "'.\n";
Eli Friedman967570f2012-02-22 01:43:47 +0000351 exit(1);
352 }
Hal Finkelc818be02015-11-26 19:23:49 +0000353 DeleteGlobalInitializer(&I); // Delete the initializer to make it external
Eli Friedman967570f2012-02-22 01:43:47 +0000354 } else {
355 // If we keep it in the safe module, then delete it in the test module
Hal Finkelc818be02015-11-26 19:23:49 +0000356 DeleteGlobalInitializer(GV);
Eli Friedman967570f2012-02-22 01:43:47 +0000357 }
358 }
359
Chris Lattner5a7a9e52006-03-08 23:55:38 +0000360 // Make sure that there is a global ctor/dtor array in both halves of the
361 // module if they both have static ctor/dtor functions.
Rafael Espindola18d70502015-12-09 00:34:10 +0000362 SplitStaticCtorDtor("llvm.global_ctors", M, New.get(), NewVMap);
363 SplitStaticCtorDtor("llvm.global_dtors", M, New.get(), NewVMap);
364
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000365 return New;
366}
Chris Lattner5e783ab2004-05-11 21:54:13 +0000367
368//===----------------------------------------------------------------------===//
369// Basic Block Extraction Code
370//===----------------------------------------------------------------------===//
371
Rafael Espindola1bfd87a2014-08-26 17:19:03 +0000372std::unique_ptr<Module>
373BugDriver::extractMappedBlocksFromModule(const std::vector<BasicBlock *> &BBs,
374 Module *M) {
Rafael Espindola324f1412017-11-16 17:35:50 +0000375 auto Temp = sys::fs::TempFile::create(OutputPrefix + "-extractblocks%%%%%%%");
376 if (!Temp) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000377 outs() << "*** Basic Block extraction failed!\n";
Rafael Espindola324f1412017-11-16 17:35:50 +0000378 errs() << "Error creating temporary file: " << toString(Temp.takeError())
379 << "\n";
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000380 EmitProgressBitcode(*M, "basicblockextractfail", true);
Craig Topper573faec2014-04-25 04:24:47 +0000381 return nullptr;
Nick Lewycky6fa98b12007-11-14 06:47:06 +0000382 }
Rafael Espindola324f1412017-11-16 17:35:50 +0000383 DiscardTemp Discard{*Temp};
Nick Lewycky6fa98b12007-11-14 06:47:06 +0000384
Volkan Keles22b25642018-01-23 21:51:34 +0000385 // Extract all of the blocks except the ones in BBs.
386 SmallVector<BasicBlock *, 32> BlocksToExtract;
387 for (Function &F : *M)
388 for (BasicBlock &BB : F)
389 // Check if this block is going to be extracted.
390 if (std::find(BBs.begin(), BBs.end(), &BB) == BBs.end())
391 BlocksToExtract.push_back(&BB);
392
Rafael Espindola324f1412017-11-16 17:35:50 +0000393 raw_fd_ostream OS(Temp->FD, /*shouldClose*/ false);
Volkan Keles22b25642018-01-23 21:51:34 +0000394 for (BasicBlock *BB : BBs) {
Chris Lattner4a6a6f22008-01-08 04:26:20 +0000395 // If the BB doesn't have a name, give it one so we have something to key
396 // off of.
Justin Bogner388e8b92016-09-02 01:21:37 +0000397 if (!BB->hasName())
398 BB->setName("tmpbb");
Rafael Espindola324f1412017-11-16 17:35:50 +0000399 OS << BB->getParent()->getName() << " " << BB->getName() << "\n";
Nick Lewycky6fa98b12007-11-14 06:47:06 +0000400 }
Rafael Espindola324f1412017-11-16 17:35:50 +0000401 OS.flush();
402 if (OS.has_error()) {
Rafael Espindolab81784f2013-06-17 18:48:59 +0000403 errs() << "Error writing list of blocks to not extract\n";
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000404 EmitProgressBitcode(*M, "basicblockextractfail", true);
Rafael Espindola324f1412017-11-16 17:35:50 +0000405 OS.clear_error();
Craig Topper573faec2014-04-25 04:24:47 +0000406 return nullptr;
Dan Gohmanf2914012010-08-20 16:59:15 +0000407 }
Nick Lewycky6fa98b12007-11-14 06:47:06 +0000408
Rafael Espindolab81784f2013-06-17 18:48:59 +0000409 std::string uniqueFN = "--extract-blocks-file=";
Rafael Espindola324f1412017-11-16 17:35:50 +0000410 uniqueFN += Temp->TmpName;
Benjamin Kramer12ea66a2010-01-28 18:04:38 +0000411 const char *ExtraArg = uniqueFN.c_str();
Nick Lewycky6fa98b12007-11-14 06:47:06 +0000412
Rafael Espindola8261dfe2010-08-08 03:55:08 +0000413 std::vector<std::string> PI;
414 PI.push_back("extract-blocks");
Philip Reames34618d92016-06-29 00:26:21 +0000415 std::unique_ptr<Module> Ret = runPassesOn(M, PI, 1, &ExtraArg);
Nick Lewycky6fa98b12007-11-14 06:47:06 +0000416
Craig Topper573faec2014-04-25 04:24:47 +0000417 if (!Ret) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000418 outs() << "*** Basic Block extraction failed, please report a bug!\n";
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000419 EmitProgressBitcode(*M, "basicblockextractfail", true);
Chris Lattner891150f2004-08-12 02:36:50 +0000420 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000421 return Ret;
422}