1 //===- ExtractFunction.cpp - Extract a function from Program --------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements several methods that are used to extract functions,
10 // loops, or portions of a module from the rest of the module.
12 //===----------------------------------------------------------------------===//
14 #include "BugDriver.h"
15 #include "llvm/IR/Constants.h"
16 #include "llvm/IR/DataLayout.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/IR/LegacyPassManager.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IR/Verifier.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/FileUtilities.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/Signals.h"
28 #include "llvm/Support/ToolOutputFile.h"
29 #include "llvm/Transforms/IPO.h"
30 #include "llvm/Transforms/Scalar.h"
31 #include "llvm/Transforms/Utils/Cloning.h"
32 #include "llvm/Transforms/Utils/CodeExtractor.h"
36 #define DEBUG_TYPE "bugpoint"
39 bool DisableSimplifyCFG
= false;
40 extern cl::opt
<std::string
> OutputPrefix
;
41 } // End llvm namespace
44 cl::opt
<bool> NoDCE("disable-dce",
45 cl::desc("Do not use the -dce pass to reduce testcases"));
47 NoSCFG("disable-simplifycfg", cl::location(DisableSimplifyCFG
),
48 cl::desc("Do not use the -simplifycfg pass to reduce testcases"));
50 Function
*globalInitUsesExternalBA(GlobalVariable
*GV
) {
51 if (!GV
->hasInitializer())
54 Constant
*I
= GV
->getInitializer();
56 // walk the values used by the initializer
57 // (and recurse into things like ConstantExpr)
58 std::vector
<Constant
*> Todo
;
59 std::set
<Constant
*> Done
;
62 while (!Todo
.empty()) {
63 Constant
*V
= Todo
.back();
67 if (BlockAddress
*BA
= dyn_cast
<BlockAddress
>(V
)) {
68 Function
*F
= BA
->getFunction();
69 if (F
->isDeclaration())
73 for (User::op_iterator i
= V
->op_begin(), e
= V
->op_end(); i
!= e
; ++i
) {
74 Constant
*C
= dyn_cast
<Constant
>(*i
);
75 if (C
&& !isa
<GlobalValue
>(C
) && !Done
.count(C
))
81 } // end anonymous namespace
83 std::unique_ptr
<Module
>
84 BugDriver::deleteInstructionFromProgram(const Instruction
*I
,
85 unsigned Simplification
) {
87 std::unique_ptr
<Module
> Clone
= CloneModule(*Program
);
89 const BasicBlock
*PBB
= I
->getParent();
90 const Function
*PF
= PBB
->getParent();
92 Module::iterator RFI
= Clone
->begin(); // Get iterator to corresponding fn
94 RFI
, std::distance(PF
->getParent()->begin(), Module::const_iterator(PF
)));
96 Function::iterator RBI
= RFI
->begin(); // Get iterator to corresponding BB
97 std::advance(RBI
, std::distance(PF
->begin(), Function::const_iterator(PBB
)));
99 BasicBlock::iterator RI
= RBI
->begin(); // Get iterator to corresponding inst
100 std::advance(RI
, std::distance(PBB
->begin(), BasicBlock::const_iterator(I
)));
101 Instruction
*TheInst
= &*RI
; // Got the corresponding instruction!
103 // If this instruction produces a value, replace any users with null values
104 if (!TheInst
->getType()->isVoidTy())
105 TheInst
->replaceAllUsesWith(Constant::getNullValue(TheInst
->getType()));
107 // Remove the instruction from the program.
108 TheInst
->eraseFromParent();
110 // Spiff up the output a little bit.
111 std::vector
<std::string
> Passes
;
113 /// Can we get rid of the -disable-* options?
114 if (Simplification
> 1 && !NoDCE
)
115 Passes
.push_back("dce");
116 if (Simplification
&& !DisableSimplifyCFG
)
117 Passes
.push_back("simplifycfg"); // Delete dead control flow
119 Passes
.push_back("verify");
120 std::unique_ptr
<Module
> New
= runPassesOn(Clone
.get(), Passes
);
122 errs() << "Instruction removal failed. Sorry. :( Please report a bug!\n";
128 std::unique_ptr
<Module
>
129 BugDriver::performFinalCleanups(std::unique_ptr
<Module
> M
,
130 bool MayModifySemantics
) {
131 // Make all functions external, so GlobalDCE doesn't delete them...
132 for (Module::iterator I
= M
->begin(), E
= M
->end(); I
!= E
; ++I
)
133 I
->setLinkage(GlobalValue::ExternalLinkage
);
135 std::vector
<std::string
> CleanupPasses
;
137 if (MayModifySemantics
)
138 CleanupPasses
.push_back("deadarghaX0r");
140 CleanupPasses
.push_back("deadargelim");
142 std::unique_ptr
<Module
> New
= runPassesOn(M
.get(), CleanupPasses
);
144 errs() << "Final cleanups failed. Sorry. :( Please report a bug!\n";
150 std::unique_ptr
<Module
> BugDriver::extractLoop(Module
*M
) {
151 std::vector
<std::string
> LoopExtractPasses
;
152 LoopExtractPasses
.push_back("loop-extract-single");
154 std::unique_ptr
<Module
> NewM
= runPassesOn(M
, LoopExtractPasses
);
156 outs() << "*** Loop extraction failed: ";
157 EmitProgressBitcode(*M
, "loopextraction", true);
158 outs() << "*** Sorry. :( Please report a bug!\n";
162 // Check to see if we created any new functions. If not, no loops were
163 // extracted and we should return null. Limit the number of loops we extract
164 // to avoid taking forever.
165 static unsigned NumExtracted
= 32;
166 if (M
->size() == NewM
->size() || --NumExtracted
== 0) {
169 assert(M
->size() < NewM
->size() && "Loop extract removed functions?");
170 Module::iterator MI
= NewM
->begin();
171 for (unsigned i
= 0, e
= M
->size(); i
!= e
; ++i
)
178 static void eliminateAliases(GlobalValue
*GV
) {
179 // First, check whether a GlobalAlias references this definition.
180 // GlobalAlias MAY NOT reference declarations.
183 SmallVector
<GlobalAlias
*, 1> aliases
;
184 Module
*M
= GV
->getParent();
185 for (Module::alias_iterator I
= M
->alias_begin(), E
= M
->alias_end();
187 if (I
->getAliasee()->stripPointerCasts() == GV
)
188 aliases
.push_back(&*I
);
191 // 2. Resolve aliases
192 for (unsigned i
= 0, e
= aliases
.size(); i
< e
; ++i
) {
193 aliases
[i
]->replaceAllUsesWith(aliases
[i
]->getAliasee());
194 aliases
[i
]->eraseFromParent();
196 // 3. Repeat until no more aliases found; there might
197 // be an alias to an alias...
202 // DeleteGlobalInitializer - "Remove" the global variable by deleting its
204 // making it external.
206 void llvm::DeleteGlobalInitializer(GlobalVariable
*GV
) {
207 eliminateAliases(GV
);
208 GV
->setInitializer(nullptr);
209 GV
->setComdat(nullptr);
212 // DeleteFunctionBody - "Remove" the function by deleting all of its basic
213 // blocks, making it external.
215 void llvm::DeleteFunctionBody(Function
*F
) {
217 // Function declarations can't have comdats.
218 F
->setComdat(nullptr);
220 // delete the body of the function...
222 assert(F
->isDeclaration() && "This didn't make the function external!");
225 /// GetTorInit - Given a list of entries for static ctors/dtors, return them
226 /// as a constant array.
227 static Constant
*GetTorInit(std::vector
<std::pair
<Function
*, int>> &TorList
) {
228 assert(!TorList
.empty() && "Don't create empty tor list!");
229 std::vector
<Constant
*> ArrayElts
;
230 Type
*Int32Ty
= Type::getInt32Ty(TorList
[0].first
->getContext());
232 StructType
*STy
= StructType::get(Int32Ty
, TorList
[0].first
->getType());
233 for (unsigned i
= 0, e
= TorList
.size(); i
!= e
; ++i
) {
234 Constant
*Elts
[] = {ConstantInt::get(Int32Ty
, TorList
[i
].second
),
236 ArrayElts
.push_back(ConstantStruct::get(STy
, Elts
));
238 return ConstantArray::get(
239 ArrayType::get(ArrayElts
[0]->getType(), ArrayElts
.size()), ArrayElts
);
242 /// SplitStaticCtorDtor - A module was recently split into two parts, M1/M2, and
243 /// M1 has all of the global variables. If M2 contains any functions that are
244 /// static ctors/dtors, we need to add an llvm.global_[cd]tors global to M2, and
245 /// prune appropriate entries out of M1s list.
246 static void SplitStaticCtorDtor(const char *GlobalName
, Module
*M1
, Module
*M2
,
247 ValueToValueMapTy
&VMap
) {
248 GlobalVariable
*GV
= M1
->getNamedGlobal(GlobalName
);
249 if (!GV
|| GV
->isDeclaration() || GV
->hasLocalLinkage() || !GV
->use_empty())
252 std::vector
<std::pair
<Function
*, int>> M1Tors
, M2Tors
;
253 ConstantArray
*InitList
= dyn_cast
<ConstantArray
>(GV
->getInitializer());
257 for (unsigned i
= 0, e
= InitList
->getNumOperands(); i
!= e
; ++i
) {
258 if (ConstantStruct
*CS
=
259 dyn_cast
<ConstantStruct
>(InitList
->getOperand(i
))) {
260 if (CS
->getNumOperands() != 2)
261 return; // Not array of 2-element structs.
263 if (CS
->getOperand(1)->isNullValue())
264 break; // Found a null terminator, stop here.
266 ConstantInt
*CI
= dyn_cast
<ConstantInt
>(CS
->getOperand(0));
267 int Priority
= CI
? CI
->getSExtValue() : 0;
269 Constant
*FP
= CS
->getOperand(1);
270 if (ConstantExpr
*CE
= dyn_cast
<ConstantExpr
>(FP
))
272 FP
= CE
->getOperand(0);
273 if (Function
*F
= dyn_cast
<Function
>(FP
)) {
274 if (!F
->isDeclaration())
275 M1Tors
.push_back(std::make_pair(F
, Priority
));
277 // Map to M2's version of the function.
278 F
= cast
<Function
>(VMap
[F
]);
279 M2Tors
.push_back(std::make_pair(F
, Priority
));
285 GV
->eraseFromParent();
286 if (!M1Tors
.empty()) {
287 Constant
*M1Init
= GetTorInit(M1Tors
);
288 new GlobalVariable(*M1
, M1Init
->getType(), false,
289 GlobalValue::AppendingLinkage
, M1Init
, GlobalName
);
292 GV
= M2
->getNamedGlobal(GlobalName
);
293 assert(GV
&& "Not a clone of M1?");
294 assert(GV
->use_empty() && "llvm.ctors shouldn't have uses!");
296 GV
->eraseFromParent();
297 if (!M2Tors
.empty()) {
298 Constant
*M2Init
= GetTorInit(M2Tors
);
299 new GlobalVariable(*M2
, M2Init
->getType(), false,
300 GlobalValue::AppendingLinkage
, M2Init
, GlobalName
);
304 std::unique_ptr
<Module
>
305 llvm::SplitFunctionsOutOfModule(Module
*M
, const std::vector
<Function
*> &F
,
306 ValueToValueMapTy
&VMap
) {
307 // Make sure functions & globals are all external so that linkage
308 // between the two modules will work.
309 for (Module::iterator I
= M
->begin(), E
= M
->end(); I
!= E
; ++I
)
310 I
->setLinkage(GlobalValue::ExternalLinkage
);
311 for (Module::global_iterator I
= M
->global_begin(), E
= M
->global_end();
313 if (I
->hasName() && I
->getName()[0] == '\01')
314 I
->setName(I
->getName().substr(1));
315 I
->setLinkage(GlobalValue::ExternalLinkage
);
318 ValueToValueMapTy NewVMap
;
319 std::unique_ptr
<Module
> New
= CloneModule(*M
, NewVMap
);
321 // Remove the Test functions from the Safe module
322 std::set
<Function
*> TestFunctions
;
323 for (unsigned i
= 0, e
= F
.size(); i
!= e
; ++i
) {
324 Function
*TNOF
= cast
<Function
>(VMap
[F
[i
]]);
325 LLVM_DEBUG(errs() << "Removing function ");
326 LLVM_DEBUG(TNOF
->printAsOperand(errs(), false));
327 LLVM_DEBUG(errs() << "\n");
328 TestFunctions
.insert(cast
<Function
>(NewVMap
[TNOF
]));
329 DeleteFunctionBody(TNOF
); // Function is now external in this module!
332 // Remove the Safe functions from the Test module
333 for (Function
&I
: *New
)
334 if (!TestFunctions
.count(&I
))
335 DeleteFunctionBody(&I
);
337 // Try to split the global initializers evenly
338 for (GlobalVariable
&I
: M
->globals()) {
339 GlobalVariable
*GV
= cast
<GlobalVariable
>(NewVMap
[&I
]);
340 if (Function
*TestFn
= globalInitUsesExternalBA(&I
)) {
341 if (Function
*SafeFn
= globalInitUsesExternalBA(GV
)) {
342 errs() << "*** Error: when reducing functions, encountered "
344 GV
->printAsOperand(errs(), false);
345 errs() << "' with an initializer that references blockaddresses "
346 "from safe function '"
347 << SafeFn
->getName() << "' and from test function '"
348 << TestFn
->getName() << "'.\n";
351 DeleteGlobalInitializer(&I
); // Delete the initializer to make it external
353 // If we keep it in the safe module, then delete it in the test module
354 DeleteGlobalInitializer(GV
);
358 // Make sure that there is a global ctor/dtor array in both halves of the
359 // module if they both have static ctor/dtor functions.
360 SplitStaticCtorDtor("llvm.global_ctors", M
, New
.get(), NewVMap
);
361 SplitStaticCtorDtor("llvm.global_dtors", M
, New
.get(), NewVMap
);
366 //===----------------------------------------------------------------------===//
367 // Basic Block Extraction Code
368 //===----------------------------------------------------------------------===//
370 std::unique_ptr
<Module
>
371 BugDriver::extractMappedBlocksFromModule(const std::vector
<BasicBlock
*> &BBs
,
373 auto Temp
= sys::fs::TempFile::create(OutputPrefix
+ "-extractblocks%%%%%%%");
375 outs() << "*** Basic Block extraction failed!\n";
376 errs() << "Error creating temporary file: " << toString(Temp
.takeError())
378 EmitProgressBitcode(*M
, "basicblockextractfail", true);
381 DiscardTemp Discard
{*Temp
};
383 // Extract all of the blocks except the ones in BBs.
384 SmallVector
<BasicBlock
*, 32> BlocksToExtract
;
385 for (Function
&F
: *M
)
386 for (BasicBlock
&BB
: F
)
387 // Check if this block is going to be extracted.
388 if (!llvm::is_contained(BBs
, &BB
))
389 BlocksToExtract
.push_back(&BB
);
391 raw_fd_ostream
OS(Temp
->FD
, /*shouldClose*/ false);
392 for (BasicBlock
*BB
: BBs
) {
393 // If the BB doesn't have a name, give it one so we have something to key
396 BB
->setName("tmpbb");
397 OS
<< BB
->getParent()->getName() << " " << BB
->getName() << "\n";
400 if (OS
.has_error()) {
401 errs() << "Error writing list of blocks to not extract\n";
402 EmitProgressBitcode(*M
, "basicblockextractfail", true);
407 std::string uniqueFN
= "--extract-blocks-file=";
408 uniqueFN
+= Temp
->TmpName
;
410 std::vector
<std::string
> PI
;
411 PI
.push_back("extract-blocks");
412 std::unique_ptr
<Module
> Ret
= runPassesOn(M
, PI
, {uniqueFN
});
415 outs() << "*** Basic Block extraction failed, please report a bug!\n";
416 EmitProgressBitcode(*M
, "basicblockextractfail", true);