1de4aa4cfSChris Lattner //===- Miscompilation.cpp - Debug program miscompilations -----------------===//
2de4aa4cfSChris Lattner //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609344dcfSJohn Criswell //
709344dcfSJohn Criswell //===----------------------------------------------------------------------===//
809344dcfSJohn Criswell //
9bf791614SChris Lattner // This file implements optimizer and code generation miscompilation debugging
10bf791614SChris Lattner // support.
11de4aa4cfSChris Lattner //
12de4aa4cfSChris Lattner //===----------------------------------------------------------------------===//
13de4aa4cfSChris Lattner
14de4aa4cfSChris Lattner #include "BugDriver.h"
159f5a197eSChris Lattner #include "ListReducer.h"
168575a60dSDaniel Dunbar #include "ToolRunner.h"
174d88a1c2SChandler Carruth #include "llvm/Config/config.h" // for HAVE_LINK_R
189fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
199fb823bbSChandler Carruth #include "llvm/IR/DerivedTypes.h"
209fb823bbSChandler Carruth #include "llvm/IR/Instructions.h"
219fb823bbSChandler Carruth #include "llvm/IR/Module.h"
225ad5f15cSChandler Carruth #include "llvm/IR/Verifier.h"
236cc07df4SChandler Carruth #include "llvm/Linker/Linker.h"
240c2305b1SMisha Brukman #include "llvm/Pass.h"
257c16caa3SReid Spencer #include "llvm/Support/CommandLine.h"
267c16caa3SReid Spencer #include "llvm/Support/FileUtilities.h"
274d88a1c2SChandler Carruth #include "llvm/Transforms/Utils/Cloning.h"
28ecefe5a8SEugene Zelenko
292f1aa118SChris Lattner using namespace llvm;
30de4aa4cfSChris Lattner
31bf791614SChris Lattner namespace llvm {
32a53337f7SDaniel Dunbar extern cl::opt<std::string> OutputPrefix;
33bf791614SChris Lattner extern cl::list<std::string> InputArgv;
34ecefe5a8SEugene Zelenko } // end namespace llvm
35bf791614SChris Lattner
36fd72bed3SChris Lattner namespace {
378d0a0811SJustin Bogner static llvm::cl::opt<bool> DisableLoopExtraction(
388d0a0811SJustin Bogner "disable-loop-extraction",
39471bcb75SReid Spencer cl::desc("Don't extract loops when searching for miscompilations"),
40471bcb75SReid Spencer cl::init(false));
418d0a0811SJustin Bogner static llvm::cl::opt<bool> DisableBlockExtraction(
428d0a0811SJustin Bogner "disable-block-extraction",
432c04ff64SDavid Goodwin cl::desc("Don't extract blocks when searching for miscompilations"),
442c04ff64SDavid Goodwin cl::init(false));
45471bcb75SReid Spencer
4633e81a82SRafael Espindola class ReduceMiscompilingPasses : public ListReducer<std::string> {
4716a41310SChris Lattner BugDriver &BD;
488d0a0811SJustin Bogner
4916a41310SChris Lattner public:
ReduceMiscompilingPasses(BugDriver & bd)5024dac6afSJustin Bogner ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
5116a41310SChris Lattner
521c039155SJustin Bogner Expected<TestResult> doTest(std::vector<std::string> &Prefix,
531c039155SJustin Bogner std::vector<std::string> &Suffix) override;
5416a41310SChris Lattner };
55ecefe5a8SEugene Zelenko } // end anonymous namespace
5616a41310SChris Lattner
570784a601SMisha Brukman /// TestResult - After passes have been split into a test group and a control
580784a601SMisha Brukman /// group, see if they still break the program.
590784a601SMisha Brukman ///
601c039155SJustin Bogner Expected<ReduceMiscompilingPasses::TestResult>
doTest(std::vector<std::string> & Prefix,std::vector<std::string> & Suffix)6133e81a82SRafael Espindola ReduceMiscompilingPasses::doTest(std::vector<std::string> &Prefix,
621c039155SJustin Bogner std::vector<std::string> &Suffix) {
634a1a9d2cSChris Lattner // First, run the program with just the Suffix passes. If it is still broken
6416a41310SChris Lattner // with JUST the kept passes, discard the prefix passes.
65ee05152cSDan Gohman outs() << "Checking to see if '" << getPassesString(Suffix)
6673f4e3f4SDavid Goodwin << "' compiles correctly: ";
6716a41310SChris Lattner
680e535c3cSGabor Greif std::string BitcodeResult;
69315190b2SRafael Espindola if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false /*delete*/,
70315190b2SRafael Espindola true /*quiet*/)) {
71d8db3760SDan Gohman errs() << " Error running this sequence of passes"
7216a41310SChris Lattner << " on the input program!\n";
7392a9f7adSChris Lattner BD.setPassesToRun(Suffix);
74594994a3SRafael Espindola BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
751c039155SJustin Bogner // TODO: This should propagate the error instead of exiting.
761c039155SJustin Bogner if (Error E = BD.debugOptimizerCrash())
771c039155SJustin Bogner exit(1);
781c039155SJustin Bogner exit(0);
7916a41310SChris Lattner }
8016a41310SChris Lattner
8116a41310SChris Lattner // Check to see if the finished program matches the reference output...
821c039155SJustin Bogner Expected<bool> Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
831c039155SJustin Bogner true /*delete bitcode*/);
841c039155SJustin Bogner if (Error E = Diff.takeError())
85c55cf4afSBill Wendling return std::move(E);
861c039155SJustin Bogner if (*Diff) {
87ee05152cSDan Gohman outs() << " nope.\n";
88ea2fa46fSChris Lattner if (Suffix.empty()) {
89d8db3760SDan Gohman errs() << BD.getToolName() << ": I'm confused: the test fails when "
90ea2fa46fSChris Lattner << "no passes are run, nondeterministic program?\n";
91ea2fa46fSChris Lattner exit(1);
92ea2fa46fSChris Lattner }
9316a41310SChris Lattner return KeepSuffix; // Miscompilation detected!
9416a41310SChris Lattner }
95ee05152cSDan Gohman outs() << " yup.\n"; // No miscompilation!
9616a41310SChris Lattner
978d0a0811SJustin Bogner if (Prefix.empty())
988d0a0811SJustin Bogner return NoFailure;
9916a41310SChris Lattner
1004a1a9d2cSChris Lattner // Next, see if the program is broken if we run the "prefix" passes first,
1017fdaab4fSMisha Brukman // then separately run the "kept" passes.
102ee05152cSDan Gohman outs() << "Checking to see if '" << getPassesString(Prefix)
10373f4e3f4SDavid Goodwin << "' compiles correctly: ";
10416a41310SChris Lattner
10516a41310SChris Lattner // If it is not broken with the kept passes, it's possible that the prefix
10616a41310SChris Lattner // passes must be run before the kept passes to break it. If the program
10716a41310SChris Lattner // WORKS after the prefix passes, but then fails if running the prefix AND
1080e535c3cSGabor Greif // kept passes, we can update our bitcode file to include the result of the
10916a41310SChris Lattner // prefix passes, then discard the prefix passes.
11016a41310SChris Lattner //
111315190b2SRafael Espindola if (BD.runPasses(BD.getProgram(), Prefix, BitcodeResult, false /*delete*/,
112315190b2SRafael Espindola true /*quiet*/)) {
113d8db3760SDan Gohman errs() << " Error running this sequence of passes"
11416a41310SChris Lattner << " on the input program!\n";
1157d147aecSChris Lattner BD.setPassesToRun(Prefix);
116594994a3SRafael Espindola BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
1171c039155SJustin Bogner // TODO: This should propagate the error instead of exiting.
1181c039155SJustin Bogner if (Error E = BD.debugOptimizerCrash())
1191c039155SJustin Bogner exit(1);
1201c039155SJustin Bogner exit(0);
12116a41310SChris Lattner }
12216a41310SChris Lattner
12316a41310SChris Lattner // If the prefix maintains the predicate by itself, only keep the prefix!
1241c039155SJustin Bogner Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "", false);
1251c039155SJustin Bogner if (Error E = Diff.takeError())
126c55cf4afSBill Wendling return std::move(E);
1271c039155SJustin Bogner if (*Diff) {
128ee05152cSDan Gohman outs() << " nope.\n";
12918079586SRafael Espindola sys::fs::remove(BitcodeResult);
13016a41310SChris Lattner return KeepPrefix;
13116a41310SChris Lattner }
132ee05152cSDan Gohman outs() << " yup.\n"; // No miscompilation!
13316a41310SChris Lattner
13416a41310SChris Lattner // Ok, so now we know that the prefix passes work, try running the suffix
13516a41310SChris Lattner // passes on the result of the prefix passes.
13616a41310SChris Lattner //
13728b351a5SRafael Espindola std::unique_ptr<Module> PrefixOutput =
13828b351a5SRafael Espindola parseInputFile(BitcodeResult, BD.getContext());
139041f1aa3SDavid Blaikie if (!PrefixOutput) {
140d8db3760SDan Gohman errs() << BD.getToolName() << ": Error reading bitcode file '"
1410e535c3cSGabor Greif << BitcodeResult << "'!\n";
14216a41310SChris Lattner exit(1);
14316a41310SChris Lattner }
14418079586SRafael Espindola sys::fs::remove(BitcodeResult);
14516a41310SChris Lattner
14602cea4afSChris Lattner // Don't check if there are no passes in the suffix.
14702cea4afSChris Lattner if (Suffix.empty())
14802cea4afSChris Lattner return NoFailure;
14902cea4afSChris Lattner
150ee05152cSDan Gohman outs() << "Checking to see if '" << getPassesString(Suffix)
1518d0a0811SJustin Bogner << "' passes compile correctly after the '" << getPassesString(Prefix)
1528d0a0811SJustin Bogner << "' passes: ";
15316a41310SChris Lattner
154f6074ed9SRafael Espindola std::unique_ptr<Module> OriginalInput =
155f6074ed9SRafael Espindola BD.swapProgramIn(std::move(PrefixOutput));
156315190b2SRafael Espindola if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false /*delete*/,
157315190b2SRafael Espindola true /*quiet*/)) {
158d8db3760SDan Gohman errs() << " Error running this sequence of passes"
15916a41310SChris Lattner << " on the input program!\n";
16092a9f7adSChris Lattner BD.setPassesToRun(Suffix);
161594994a3SRafael Espindola BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
1621c039155SJustin Bogner // TODO: This should propagate the error instead of exiting.
1631c039155SJustin Bogner if (Error E = BD.debugOptimizerCrash())
1641c039155SJustin Bogner exit(1);
1651c039155SJustin Bogner exit(0);
16616a41310SChris Lattner }
16716a41310SChris Lattner
16816a41310SChris Lattner // Run the result...
169c89b1ef0SRafael Espindola Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
1701c039155SJustin Bogner true /*delete bitcode*/);
1711c039155SJustin Bogner if (Error E = Diff.takeError())
172c55cf4afSBill Wendling return std::move(E);
1731c039155SJustin Bogner if (*Diff) {
174ee05152cSDan Gohman outs() << " nope.\n";
1754a1a9d2cSChris Lattner return KeepSuffix;
17616a41310SChris Lattner }
17716a41310SChris Lattner
17816a41310SChris Lattner // Otherwise, we must not be running the bad pass anymore.
179ee05152cSDan Gohman outs() << " yup.\n"; // No miscompilation!
180e476fa0bSJeffrey Yasskin // Restore orig program & free test.
181f6074ed9SRafael Espindola BD.setNewProgram(std::move(OriginalInput));
18216a41310SChris Lattner return NoFailure;
18316a41310SChris Lattner }
18416a41310SChris Lattner
185fd72bed3SChris Lattner namespace {
18616a41310SChris Lattner class ReduceMiscompilingFunctions : public ListReducer<Function *> {
18716a41310SChris Lattner BugDriver &BD;
1881c039155SJustin Bogner Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
1891c039155SJustin Bogner std::unique_ptr<Module>);
190bc12cbc3SRafael Espindola
19116a41310SChris Lattner public:
ReduceMiscompilingFunctions(BugDriver & bd,Expected<bool> (* F)(BugDriver &,std::unique_ptr<Module>,std::unique_ptr<Module>))1920434ba3eSChris Lattner ReduceMiscompilingFunctions(BugDriver &bd,
1931c039155SJustin Bogner Expected<bool> (*F)(BugDriver &,
1941c039155SJustin Bogner std::unique_ptr<Module>,
1951c039155SJustin Bogner std::unique_ptr<Module>))
19624dac6afSJustin Bogner : BD(bd), TestFn(F) {}
19716a41310SChris Lattner
doTest(std::vector<Function * > & Prefix,std::vector<Function * > & Suffix)1981c039155SJustin Bogner Expected<TestResult> doTest(std::vector<Function *> &Prefix,
1991c039155SJustin Bogner std::vector<Function *> &Suffix) override {
2006ba630b0SNick Lewycky if (!Suffix.empty()) {
2011c039155SJustin Bogner Expected<bool> Ret = TestFuncs(Suffix);
2021c039155SJustin Bogner if (Error E = Ret.takeError())
203c55cf4afSBill Wendling return std::move(E);
2041c039155SJustin Bogner if (*Ret)
20516a41310SChris Lattner return KeepSuffix;
2066ba630b0SNick Lewycky }
2076ba630b0SNick Lewycky if (!Prefix.empty()) {
2081c039155SJustin Bogner Expected<bool> Ret = TestFuncs(Prefix);
2091c039155SJustin Bogner if (Error E = Ret.takeError())
210c55cf4afSBill Wendling return std::move(E);
2111c039155SJustin Bogner if (*Ret)
21216a41310SChris Lattner return KeepPrefix;
2136ba630b0SNick Lewycky }
21416a41310SChris Lattner return NoFailure;
21516a41310SChris Lattner }
21616a41310SChris Lattner
2171c039155SJustin Bogner Expected<bool> TestFuncs(const std::vector<Function *> &Prefix);
21816a41310SChris Lattner };
219ecefe5a8SEugene Zelenko } // end anonymous namespace
22016a41310SChris Lattner
2217471abd9SRafael Espindola /// Given two modules, link them together and run the program, checking to see
2227471abd9SRafael Espindola /// if the program matches the diff. If there is an error, return NULL. If not,
2237471abd9SRafael Espindola /// return the merged module. The Broken argument will be set to true if the
2247471abd9SRafael Espindola /// output is different. If the DeleteInputs argument is set to true then this
2257471abd9SRafael Espindola /// function deletes both input modules before it returns.
2260784a601SMisha Brukman ///
testMergedProgram(const BugDriver & BD,const Module & M1,const Module & M2,bool & Broken)22777b14505SBryant Wong static Expected<std::unique_ptr<Module>> testMergedProgram(const BugDriver &BD,
22877b14505SBryant Wong const Module &M1,
22977b14505SBryant Wong const Module &M2,
23077b14505SBryant Wong bool &Broken) {
23177b14505SBryant Wong // Resulting merge of M1 and M2.
23271867532SRafael Espindola auto Merged = CloneModule(M1);
23371867532SRafael Espindola if (Linker::linkModules(*Merged, CloneModule(M2)))
2341c039155SJustin Bogner // TODO: Shouldn't we thread the error up instead of exiting?
235fd72bed3SChris Lattner exit(1);
236fd72bed3SChris Lattner
237e490460fSRafael Espindola // Execute the program.
238f6074ed9SRafael Espindola Expected<bool> Diff = BD.diffProgram(*Merged, "", "", false);
2391c039155SJustin Bogner if (Error E = Diff.takeError())
240c55cf4afSBill Wendling return std::move(E);
2411c039155SJustin Bogner Broken = *Diff;
242c55cf4afSBill Wendling return std::move(Merged);
243fd72bed3SChris Lattner }
244fd72bed3SChris Lattner
245a7b07940SRafael Espindola /// split functions in a Module into two groups: those that are under
246a7b07940SRafael Espindola /// consideration for miscompilation vs. those that are not, and test
2470784a601SMisha Brukman /// accordingly. Each group of functions becomes a separate Module.
2481c039155SJustin Bogner Expected<bool>
TestFuncs(const std::vector<Function * > & Funcs)2491c039155SJustin Bogner ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function *> &Funcs) {
25016a41310SChris Lattner // Test to see if the function is misoptimized if we ONLY run it on the
25116a41310SChris Lattner // functions listed in Funcs.
252ee05152cSDan Gohman outs() << "Checking to see if the program is misoptimized when "
25369d47e73SChris Lattner << (Funcs.size() == 1 ? "this function is" : "these functions are")
25469d47e73SChris Lattner << " run through the pass"
255fd72bed3SChris Lattner << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
256fd72bed3SChris Lattner PrintFunctionList(Funcs);
257ee05152cSDan Gohman outs() << '\n';
25816a41310SChris Lattner
259235457caSRafael Espindola // Create a clone for two reasons:
260235457caSRafael Espindola // * If the optimization passes delete any function, the deleted function
261235457caSRafael Espindola // will be in the clone and Funcs will still point to valid memory
262235457caSRafael Espindola // * If the optimization passes use interprocedural information to break
263235457caSRafael Espindola // a function, we want to continue with the original function. Otherwise
264235457caSRafael Espindola // we can conclude that a function triggers the bug when in fact one
265235457caSRafael Espindola // needs a larger set of original functions to do so.
266229e38f0SRafael Espindola ValueToValueMapTy VMap;
267f6074ed9SRafael Espindola std::unique_ptr<Module> Clone = CloneModule(BD.getProgram(), VMap);
268f6074ed9SRafael Espindola std::unique_ptr<Module> Orig = BD.swapProgramIn(std::move(Clone));
269235457caSRafael Espindola
270235457caSRafael Espindola std::vector<Function *> FuncsOnClone;
271235457caSRafael Espindola for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
272235457caSRafael Espindola Function *F = cast<Function>(VMap[Funcs[i]]);
273235457caSRafael Espindola FuncsOnClone.push_back(F);
274235457caSRafael Espindola }
275235457caSRafael Espindola
276235457caSRafael Espindola // Split the module into the two halves of the program we want.
277235457caSRafael Espindola VMap.clear();
278f6074ed9SRafael Espindola std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
279bc12cbc3SRafael Espindola std::unique_ptr<Module> ToOptimize =
280bc12cbc3SRafael Espindola SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
28116a41310SChris Lattner
2821c039155SJustin Bogner Expected<bool> Broken =
2831c039155SJustin Bogner TestFn(BD, std::move(ToOptimize), std::move(ToNotOptimize));
284235457caSRafael Espindola
285f6074ed9SRafael Espindola BD.setNewProgram(std::move(Orig));
286235457caSRafael Espindola
287235457caSRafael Espindola return Broken;
28816a41310SChris Lattner }
28916a41310SChris Lattner
290f6074ed9SRafael Espindola /// Give anonymous global values names.
DisambiguateGlobalSymbols(Module & M)291f6074ed9SRafael Espindola static void DisambiguateGlobalSymbols(Module &M) {
292f6074ed9SRafael Espindola for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E;
293f6074ed9SRafael Espindola ++I)
294dc2cb5afSChris Lattner if (!I->hasName())
295dc2cb5afSChris Lattner I->setName("anon_global");
296f6074ed9SRafael Espindola for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
297dc2cb5afSChris Lattner if (!I->hasName())
298dc2cb5afSChris Lattner I->setName("anon_fn");
299dfbb1d1cSChris Lattner }
300dfbb1d1cSChris Lattner
301bc12cbc3SRafael Espindola /// Given a reduced list of functions that still exposed the bug, check to see
302bc12cbc3SRafael Espindola /// if we can extract the loops in the region without obscuring the bug. If so,
303bc12cbc3SRafael Espindola /// it reduces the amount of code identified.
3040784a601SMisha Brukman ///
3051c039155SJustin Bogner static Expected<bool>
ExtractLoops(BugDriver & BD,Expected<bool> (* TestFn)(BugDriver &,std::unique_ptr<Module>,std::unique_ptr<Module>),std::vector<Function * > & MiscompiledFunctions)3061c039155SJustin Bogner ExtractLoops(BugDriver &BD,
3071c039155SJustin Bogner Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
3081c039155SJustin Bogner std::unique_ptr<Module>),
3091c039155SJustin Bogner std::vector<Function *> &MiscompiledFunctions) {
310bcec7875SChris Lattner bool MadeChange = false;
311*2aed0813SKazu Hirata while (true) {
3128d0a0811SJustin Bogner if (BugpointIsInterrupted)
3138d0a0811SJustin Bogner return MadeChange;
314bd615f51SChris Lattner
315229e38f0SRafael Espindola ValueToValueMapTy VMap;
316f6074ed9SRafael Espindola std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
31754c64ed3SRafael Espindola std::unique_ptr<Module> ToOptimize = SplitFunctionsOutOfModule(
31854c64ed3SRafael Espindola ToNotOptimize.get(), MiscompiledFunctions, VMap);
31988a8f725SRafael Espindola std::unique_ptr<Module> ToOptimizeLoopExtracted =
32054c64ed3SRafael Espindola BD.extractLoop(ToOptimize.get());
32154c64ed3SRafael Espindola if (!ToOptimizeLoopExtracted)
322bcec7875SChris Lattner // If the loop extractor crashed or if there were no extractible loops,
323bcec7875SChris Lattner // then this chapter of our odyssey is over with.
324bcec7875SChris Lattner return MadeChange;
325bcec7875SChris Lattner
326d8db3760SDan Gohman errs() << "Extracted a loop from the breaking portion of the program.\n";
327bcec7875SChris Lattner
328bcec7875SChris Lattner // Bugpoint is intentionally not very trusting of LLVM transformations. In
329bcec7875SChris Lattner // particular, we're not going to assume that the loop extractor works, so
330bcec7875SChris Lattner // we're going to test the newly loop extracted program to make sure nothing
331bcec7875SChris Lattner // has broken. If something broke, then we'll inform the user and stop
332bcec7875SChris Lattner // extraction.
333414cf502SDan Gohman AbstractInterpreter *AI = BD.switchToSafeInterpreter();
334e490460fSRafael Espindola bool Failure;
33577b14505SBryant Wong Expected<std::unique_ptr<Module>> New = testMergedProgram(
33677b14505SBryant Wong BD, *ToOptimizeLoopExtracted, *ToNotOptimize, Failure);
3371c039155SJustin Bogner if (Error E = New.takeError())
338c55cf4afSBill Wendling return std::move(E);
3391c039155SJustin Bogner if (!*New)
3406ba630b0SNick Lewycky return false;
341e9efbf14SHal Finkel
342e490460fSRafael Espindola // Delete the original and set the new program.
343f6074ed9SRafael Espindola std::unique_ptr<Module> Old = BD.swapProgramIn(std::move(*New));
344e9efbf14SHal Finkel for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
345e9efbf14SHal Finkel MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
346e9efbf14SHal Finkel
3476ba630b0SNick Lewycky if (Failure) {
348bf791614SChris Lattner BD.switchToInterpreter(AI);
349bf791614SChris Lattner
350bcec7875SChris Lattner // Merged program doesn't work anymore!
351d8db3760SDan Gohman errs() << " *** ERROR: Loop extraction broke the program. :("
352bcec7875SChris Lattner << " Please report a bug!\n";
353d8db3760SDan Gohman errs() << " Continuing on with un-loop-extracted version.\n";
354257008beSChris Lattner
355a53337f7SDaniel Dunbar BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
356f6074ed9SRafael Espindola *ToNotOptimize);
357a53337f7SDaniel Dunbar BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
358f6074ed9SRafael Espindola *ToOptimize);
359a53337f7SDaniel Dunbar BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
360f6074ed9SRafael Espindola *ToOptimizeLoopExtracted);
361257008beSChris Lattner
3628d0a0811SJustin Bogner errs() << "Please submit the " << OutputPrefix
3638d0a0811SJustin Bogner << "-loop-extract-fail-*.bc files.\n";
364bcec7875SChris Lattner return MadeChange;
365bcec7875SChris Lattner }
366bf791614SChris Lattner BD.switchToInterpreter(AI);
367bcec7875SChris Lattner
368ee05152cSDan Gohman outs() << " Testing after loop extraction:\n";
3690434ba3eSChris Lattner // Clone modules, the tester function will free them.
37088a8f725SRafael Espindola std::unique_ptr<Module> TOLEBackup =
37171867532SRafael Espindola CloneModule(*ToOptimizeLoopExtracted, VMap);
37271867532SRafael Espindola std::unique_ptr<Module> TNOBackup = CloneModule(*ToNotOptimize, VMap);
373e9efbf14SHal Finkel
374e9efbf14SHal Finkel for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
375e9efbf14SHal Finkel MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
376e9efbf14SHal Finkel
3771c039155SJustin Bogner Expected<bool> Result = TestFn(BD, std::move(ToOptimizeLoopExtracted),
3781c039155SJustin Bogner std::move(ToNotOptimize));
3791c039155SJustin Bogner if (Error E = Result.takeError())
380c55cf4afSBill Wendling return std::move(E);
381e9efbf14SHal Finkel
38288a8f725SRafael Espindola ToOptimizeLoopExtracted = std::move(TOLEBackup);
383000bf49cSRafael Espindola ToNotOptimize = std::move(TNOBackup);
384e9efbf14SHal Finkel
3851c039155SJustin Bogner if (!*Result) {
386ee05152cSDan Gohman outs() << "*** Loop extraction masked the problem. Undoing.\n";
387bcec7875SChris Lattner // If the program is not still broken, then loop extraction did something
388bcec7875SChris Lattner // that masked the error. Stop loop extraction now.
389e9efbf14SHal Finkel
390e9efbf14SHal Finkel std::vector<std::pair<std::string, FunctionType *>> MisCompFunctions;
391f5e2fc47SBenjamin Kramer for (Function *F : MiscompiledFunctions) {
392cd87e207SBenjamin Kramer MisCompFunctions.emplace_back(std::string(F->getName()),
393cd87e207SBenjamin Kramer F->getFunctionType());
394e9efbf14SHal Finkel }
395e9efbf14SHal Finkel
396434e9561SRafael Espindola if (Linker::linkModules(*ToNotOptimize,
397434e9561SRafael Espindola std::move(ToOptimizeLoopExtracted)))
398e9efbf14SHal Finkel exit(1);
399e9efbf14SHal Finkel
400e9efbf14SHal Finkel MiscompiledFunctions.clear();
401e9efbf14SHal Finkel for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
402e9efbf14SHal Finkel Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
403e9efbf14SHal Finkel
404e9efbf14SHal Finkel assert(NewF && "Function not found??");
405e9efbf14SHal Finkel MiscompiledFunctions.push_back(NewF);
406e9efbf14SHal Finkel }
407e9efbf14SHal Finkel
408f6074ed9SRafael Espindola BD.setNewProgram(std::move(ToNotOptimize));
409bcec7875SChris Lattner return MadeChange;
410bcec7875SChris Lattner }
4110434ba3eSChris Lattner
412ee05152cSDan Gohman outs() << "*** Loop extraction successful!\n";
413bcec7875SChris Lattner
414229907cdSChris Lattner std::vector<std::pair<std::string, FunctionType *>> MisCompFunctions;
415d308797cSChris Lattner for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
4168d0a0811SJustin Bogner E = ToOptimizeLoopExtracted->end();
4178d0a0811SJustin Bogner I != E; ++I)
4185301e7c6SReid Spencer if (!I->isDeclaration())
419cd87e207SBenjamin Kramer MisCompFunctions.emplace_back(std::string(I->getName()),
420cd87e207SBenjamin Kramer I->getFunctionType());
421d308797cSChris Lattner
422bcec7875SChris Lattner // Okay, great! Now we know that we extracted a loop and that loop
423bcec7875SChris Lattner // extraction both didn't break the program, and didn't mask the problem.
424bcec7875SChris Lattner // Replace the current program with the loop extracted version, and try to
425bcec7875SChris Lattner // extract another loop.
426434e9561SRafael Espindola if (Linker::linkModules(*ToNotOptimize, std::move(ToOptimizeLoopExtracted)))
427bcec7875SChris Lattner exit(1);
428d12b4a33SRafael Espindola
429b38cc9c0SChris Lattner // All of the Function*'s in the MiscompiledFunctions list are in the old
430a413b085SChris Lattner // module. Update this list to include all of the functions in the
431a413b085SChris Lattner // optimized and loop extracted module.
432a413b085SChris Lattner MiscompiledFunctions.clear();
433d308797cSChris Lattner for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
4343aaaa0b2SReid Spencer Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
4353aaaa0b2SReid Spencer
436a413b085SChris Lattner assert(NewF && "Function not found??");
437a413b085SChris Lattner MiscompiledFunctions.push_back(NewF);
438b38cc9c0SChris Lattner }
439b38cc9c0SChris Lattner
440f6074ed9SRafael Espindola BD.setNewProgram(std::move(ToNotOptimize));
441bcec7875SChris Lattner MadeChange = true;
442bcec7875SChris Lattner }
443bcec7875SChris Lattner }
444bcec7875SChris Lattner
445a060b10eSChris Lattner namespace {
446a060b10eSChris Lattner class ReduceMiscompiledBlocks : public ListReducer<BasicBlock *> {
447a060b10eSChris Lattner BugDriver &BD;
4481c039155SJustin Bogner Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
4491c039155SJustin Bogner std::unique_ptr<Module>);
450a060b10eSChris Lattner std::vector<Function *> FunctionsBeingTested;
4518d0a0811SJustin Bogner
452a060b10eSChris Lattner public:
ReduceMiscompiledBlocks(BugDriver & bd,Expected<bool> (* F)(BugDriver &,std::unique_ptr<Module>,std::unique_ptr<Module>),const std::vector<Function * > & Fns)453a060b10eSChris Lattner ReduceMiscompiledBlocks(BugDriver &bd,
4541c039155SJustin Bogner Expected<bool> (*F)(BugDriver &,
4551c039155SJustin Bogner std::unique_ptr<Module>,
4561c039155SJustin Bogner std::unique_ptr<Module>),
45724dac6afSJustin Bogner const std::vector<Function *> &Fns)
45824dac6afSJustin Bogner : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
459a060b10eSChris Lattner
doTest(std::vector<BasicBlock * > & Prefix,std::vector<BasicBlock * > & Suffix)4601c039155SJustin Bogner Expected<TestResult> doTest(std::vector<BasicBlock *> &Prefix,
4611c039155SJustin Bogner std::vector<BasicBlock *> &Suffix) override {
4626ba630b0SNick Lewycky if (!Suffix.empty()) {
4631c039155SJustin Bogner Expected<bool> Ret = TestFuncs(Suffix);
4641c039155SJustin Bogner if (Error E = Ret.takeError())
465c55cf4afSBill Wendling return std::move(E);
4661c039155SJustin Bogner if (*Ret)
467a060b10eSChris Lattner return KeepSuffix;
4686ba630b0SNick Lewycky }
4696ba630b0SNick Lewycky if (!Prefix.empty()) {
4701c039155SJustin Bogner Expected<bool> Ret = TestFuncs(Prefix);
4711c039155SJustin Bogner if (Error E = Ret.takeError())
472c55cf4afSBill Wendling return std::move(E);
4731c039155SJustin Bogner if (*Ret)
474a060b10eSChris Lattner return KeepPrefix;
4756ba630b0SNick Lewycky }
476a060b10eSChris Lattner return NoFailure;
477a060b10eSChris Lattner }
478a060b10eSChris Lattner
4791c039155SJustin Bogner Expected<bool> TestFuncs(const std::vector<BasicBlock *> &BBs);
480a060b10eSChris Lattner };
481ecefe5a8SEugene Zelenko } // end anonymous namespace
482a060b10eSChris Lattner
483a060b10eSChris Lattner /// TestFuncs - Extract all blocks for the miscompiled functions except for the
484a060b10eSChris Lattner /// specified blocks. If the problem still exists, return true.
485a060b10eSChris Lattner ///
4861c039155SJustin Bogner Expected<bool>
TestFuncs(const std::vector<BasicBlock * > & BBs)4871c039155SJustin Bogner ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock *> &BBs) {
488a060b10eSChris Lattner // Test to see if the function is misoptimized if we ONLY run it on the
489a060b10eSChris Lattner // functions listed in Funcs.
490ee05152cSDan Gohman outs() << "Checking to see if the program is misoptimized when all ";
4916c0c313dSChris Lattner if (!BBs.empty()) {
492ee05152cSDan Gohman outs() << "but these " << BBs.size() << " blocks are extracted: ";
493a060b10eSChris Lattner for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
494ee05152cSDan Gohman outs() << BBs[i]->getName() << " ";
4958d0a0811SJustin Bogner if (BBs.size() > 10)
4968d0a0811SJustin Bogner outs() << "...";
4976c0c313dSChris Lattner } else {
498ee05152cSDan Gohman outs() << "blocks are extracted.";
4996c0c313dSChris Lattner }
500ee05152cSDan Gohman outs() << '\n';
501a060b10eSChris Lattner
502a060b10eSChris Lattner // Split the module into the two halves of the program we want.
503229e38f0SRafael Espindola ValueToValueMapTy VMap;
504f6074ed9SRafael Espindola std::unique_ptr<Module> Clone = CloneModule(BD.getProgram(), VMap);
505f6074ed9SRafael Espindola std::unique_ptr<Module> Orig = BD.swapProgramIn(std::move(Clone));
50607035e6aSRafael Espindola std::vector<Function *> FuncsOnClone;
50707035e6aSRafael Espindola std::vector<BasicBlock *> BBsOnClone;
50807035e6aSRafael Espindola for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
50907035e6aSRafael Espindola Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
51007035e6aSRafael Espindola FuncsOnClone.push_back(F);
51107035e6aSRafael Espindola }
51207035e6aSRafael Espindola for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
51307035e6aSRafael Espindola BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
51407035e6aSRafael Espindola BBsOnClone.push_back(BB);
51507035e6aSRafael Espindola }
51607035e6aSRafael Espindola VMap.clear();
51707035e6aSRafael Espindola
518f6074ed9SRafael Espindola std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
519bc12cbc3SRafael Espindola std::unique_ptr<Module> ToOptimize =
520bc12cbc3SRafael Espindola SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
521a060b10eSChris Lattner
522a060b10eSChris Lattner // Try the extraction. If it doesn't work, then the block extractor crashed
523a060b10eSChris Lattner // or something, in which case bugpoint can't chase down this possibility.
52428b351a5SRafael Espindola if (std::unique_ptr<Module> New =
525bc12cbc3SRafael Espindola BD.extractMappedBlocksFromModule(BBsOnClone, ToOptimize.get())) {
5261c039155SJustin Bogner Expected<bool> Ret = TestFn(BD, std::move(New), std::move(ToNotOptimize));
527f6074ed9SRafael Espindola BD.setNewProgram(std::move(Orig));
52807035e6aSRafael Espindola return Ret;
529a060b10eSChris Lattner }
530f6074ed9SRafael Espindola BD.setNewProgram(std::move(Orig));
531a060b10eSChris Lattner return false;
532a060b10eSChris Lattner }
533a060b10eSChris Lattner
534bc12cbc3SRafael Espindola /// Given a reduced list of functions that still expose the bug, extract as many
535bc12cbc3SRafael Espindola /// basic blocks from the region as possible without obscuring the bug.
536a060b10eSChris Lattner ///
5371c039155SJustin Bogner static Expected<bool>
ExtractBlocks(BugDriver & BD,Expected<bool> (* TestFn)(BugDriver &,std::unique_ptr<Module>,std::unique_ptr<Module>),std::vector<Function * > & MiscompiledFunctions)5381c039155SJustin Bogner ExtractBlocks(BugDriver &BD,
5391c039155SJustin Bogner Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
5401c039155SJustin Bogner std::unique_ptr<Module>),
5411c039155SJustin Bogner std::vector<Function *> &MiscompiledFunctions) {
5428d0a0811SJustin Bogner if (BugpointIsInterrupted)
5438d0a0811SJustin Bogner return false;
544beb01faeSChris Lattner
545a060b10eSChris Lattner std::vector<BasicBlock *> Blocks;
546a060b10eSChris Lattner for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
547306d16e0SDuncan P. N. Exon Smith for (BasicBlock &BB : *MiscompiledFunctions[i])
548306d16e0SDuncan P. N. Exon Smith Blocks.push_back(&BB);
549a060b10eSChris Lattner
550a060b10eSChris Lattner // Use the list reducer to identify blocks that can be extracted without
551a060b10eSChris Lattner // obscuring the bug. The Blocks list will end up containing blocks that must
552a060b10eSChris Lattner // be retained from the original program.
553a060b10eSChris Lattner unsigned OldSize = Blocks.size();
5546c0c313dSChris Lattner
5556c0c313dSChris Lattner // Check to see if all blocks are extractible first.
5561c039155SJustin Bogner Expected<bool> Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
5571c039155SJustin Bogner .TestFuncs(std::vector<BasicBlock *>());
5581c039155SJustin Bogner if (Error E = Ret.takeError())
559c55cf4afSBill Wendling return std::move(E);
5601c039155SJustin Bogner if (*Ret) {
5616c0c313dSChris Lattner Blocks.clear();
5626c0c313dSChris Lattner } else {
5631c039155SJustin Bogner Expected<bool> Ret =
56424dac6afSJustin Bogner ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
5651c039155SJustin Bogner .reduceList(Blocks);
5661c039155SJustin Bogner if (Error E = Ret.takeError())
567c55cf4afSBill Wendling return std::move(E);
568a060b10eSChris Lattner if (Blocks.size() == OldSize)
569a060b10eSChris Lattner return false;
5706c0c313dSChris Lattner }
571a060b10eSChris Lattner
572229e38f0SRafael Espindola ValueToValueMapTy VMap;
573f6074ed9SRafael Espindola std::unique_ptr<Module> ProgClone = CloneModule(BD.getProgram(), VMap);
5748b8d980bSRafael Espindola std::unique_ptr<Module> ToExtract =
5758b8d980bSRafael Espindola SplitFunctionsOutOfModule(ProgClone.get(), MiscompiledFunctions, VMap);
57628b351a5SRafael Espindola std::unique_ptr<Module> Extracted =
5778b8d980bSRafael Espindola BD.extractMappedBlocksFromModule(Blocks, ToExtract.get());
578e6cb63e4SCraig Topper if (!Extracted) {
5790ce80cd5SChris Lattner // Weird, extraction should have worked.
580d8db3760SDan Gohman errs() << "Nondeterministic problem extracting blocks??\n";
581a060b10eSChris Lattner return false;
582a060b10eSChris Lattner }
583a060b10eSChris Lattner
58449e4a33cSChris Lattner // Otherwise, block extraction succeeded. Link the two program fragments back
58549e4a33cSChris Lattner // together.
58649e4a33cSChris Lattner
587229907cdSChris Lattner std::vector<std::pair<std::string, FunctionType *>> MisCompFunctions;
5888d0a0811SJustin Bogner for (Module::iterator I = Extracted->begin(), E = Extracted->end(); I != E;
5898d0a0811SJustin Bogner ++I)
5905301e7c6SReid Spencer if (!I->isDeclaration())
59142a25e7fSBenjamin Kramer MisCompFunctions.emplace_back(std::string(I->getName()),
59242a25e7fSBenjamin Kramer I->getFunctionType());
593d308797cSChris Lattner
594434e9561SRafael Espindola if (Linker::linkModules(*ProgClone, std::move(Extracted)))
59549e4a33cSChris Lattner exit(1);
59649e4a33cSChris Lattner
59749e4a33cSChris Lattner // Update the list of miscompiled functions.
59849e4a33cSChris Lattner MiscompiledFunctions.clear();
59949e4a33cSChris Lattner
600d308797cSChris Lattner for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
6013aaaa0b2SReid Spencer Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
602d308797cSChris Lattner assert(NewF && "Function not found??");
603d308797cSChris Lattner MiscompiledFunctions.push_back(NewF);
60449e4a33cSChris Lattner }
60549e4a33cSChris Lattner
60692febc64SNick Desaulniers // Set the new program and delete the old one.
60792febc64SNick Desaulniers BD.setNewProgram(std::move(ProgClone));
60892febc64SNick Desaulniers
60949e4a33cSChris Lattner return true;
61049e4a33cSChris Lattner }
61149e4a33cSChris Lattner
612bc12cbc3SRafael Espindola /// This is a generic driver to narrow down miscompilations, either in an
613bc12cbc3SRafael Espindola /// optimization or a code generator.
6140784a601SMisha Brukman ///
DebugAMiscompilation(BugDriver & BD,Expected<bool> (* TestFn)(BugDriver &,std::unique_ptr<Module>,std::unique_ptr<Module>))6151c039155SJustin Bogner static Expected<std::vector<Function *>> DebugAMiscompilation(
6161c039155SJustin Bogner BugDriver &BD,
6171c039155SJustin Bogner Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
6181c039155SJustin Bogner std::unique_ptr<Module>)) {
6190434ba3eSChris Lattner // Okay, now that we have reduced the list of passes which are causing the
6200434ba3eSChris Lattner // failure, see if we can pin down which functions are being
6210434ba3eSChris Lattner // miscompiled... first build a list of all of the non-external functions in
6220434ba3eSChris Lattner // the program.
6230434ba3eSChris Lattner std::vector<Function *> MiscompiledFunctions;
624f6074ed9SRafael Espindola Module &Prog = BD.getProgram();
625f6074ed9SRafael Espindola for (Function &F : Prog)
626306d16e0SDuncan P. N. Exon Smith if (!F.isDeclaration())
627306d16e0SDuncan P. N. Exon Smith MiscompiledFunctions.push_back(&F);
6280434ba3eSChris Lattner
6290434ba3eSChris Lattner // Do the reduction...
6301c039155SJustin Bogner if (!BugpointIsInterrupted) {
6311c039155SJustin Bogner Expected<bool> Ret = ReduceMiscompilingFunctions(BD, TestFn)
6321c039155SJustin Bogner .reduceList(MiscompiledFunctions);
6331c039155SJustin Bogner if (Error E = Ret.takeError()) {
63455aeb55aSAndrew Trick errs() << "\n***Cannot reduce functions: ";
635c55cf4afSBill Wendling return std::move(E);
6361c039155SJustin Bogner }
63755aeb55aSAndrew Trick }
638ee05152cSDan Gohman outs() << "\n*** The following function"
6390434ba3eSChris Lattner << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
6400434ba3eSChris Lattner << " being miscompiled: ";
6410434ba3eSChris Lattner PrintFunctionList(MiscompiledFunctions);
642ee05152cSDan Gohman outs() << '\n';
6430434ba3eSChris Lattner
6440434ba3eSChris Lattner // See if we can rip any loops out of the miscompiled functions and still
6450434ba3eSChris Lattner // trigger the problem.
646471bcb75SReid Spencer
6476ba630b0SNick Lewycky if (!BugpointIsInterrupted && !DisableLoopExtraction) {
6481c039155SJustin Bogner Expected<bool> Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions);
6491c039155SJustin Bogner if (Error E = Ret.takeError())
650c55cf4afSBill Wendling return std::move(E);
6511c039155SJustin Bogner if (*Ret) {
6526ba630b0SNick Lewycky // Okay, we extracted some loops and the problem still appears. See if
6536ba630b0SNick Lewycky // we can eliminate some of the created functions from being candidates.
654dfbb1d1cSChris Lattner DisambiguateGlobalSymbols(BD.getProgram());
655dfbb1d1cSChris Lattner
6560434ba3eSChris Lattner // Do the reduction...
657beb01faeSChris Lattner if (!BugpointIsInterrupted)
6581c039155SJustin Bogner Ret = ReduceMiscompilingFunctions(BD, TestFn)
6591c039155SJustin Bogner .reduceList(MiscompiledFunctions);
6601c039155SJustin Bogner if (Error E = Ret.takeError())
661c55cf4afSBill Wendling return std::move(E);
6620434ba3eSChris Lattner
663ee05152cSDan Gohman outs() << "\n*** The following function"
6640434ba3eSChris Lattner << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
6650434ba3eSChris Lattner << " being miscompiled: ";
6660434ba3eSChris Lattner PrintFunctionList(MiscompiledFunctions);
667ee05152cSDan Gohman outs() << '\n';
6680434ba3eSChris Lattner }
6696ba630b0SNick Lewycky }
6700434ba3eSChris Lattner
6716ba630b0SNick Lewycky if (!BugpointIsInterrupted && !DisableBlockExtraction) {
6721c039155SJustin Bogner Expected<bool> Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions);
6731c039155SJustin Bogner if (Error E = Ret.takeError())
674c55cf4afSBill Wendling return std::move(E);
6751c039155SJustin Bogner if (*Ret) {
6766ba630b0SNick Lewycky // Okay, we extracted some blocks and the problem still appears. See if
6776ba630b0SNick Lewycky // we can eliminate some of the created functions from being candidates.
678a060b10eSChris Lattner DisambiguateGlobalSymbols(BD.getProgram());
679a060b10eSChris Lattner
680a060b10eSChris Lattner // Do the reduction...
6811c039155SJustin Bogner Ret = ReduceMiscompilingFunctions(BD, TestFn)
6821c039155SJustin Bogner .reduceList(MiscompiledFunctions);
6831c039155SJustin Bogner if (Error E = Ret.takeError())
684c55cf4afSBill Wendling return std::move(E);
685a060b10eSChris Lattner
686ee05152cSDan Gohman outs() << "\n*** The following function"
687a060b10eSChris Lattner << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
688a060b10eSChris Lattner << " being miscompiled: ";
689a060b10eSChris Lattner PrintFunctionList(MiscompiledFunctions);
690ee05152cSDan Gohman outs() << '\n';
691a060b10eSChris Lattner }
6926ba630b0SNick Lewycky }
693a060b10eSChris Lattner
6940434ba3eSChris Lattner return MiscompiledFunctions;
6950434ba3eSChris Lattner }
6960434ba3eSChris Lattner
697bc12cbc3SRafael Espindola /// This is the predicate function used to check to see if the "Test" portion of
698bc12cbc3SRafael Espindola /// the program is misoptimized. If so, return true. In any case, both module
699bc12cbc3SRafael Espindola /// arguments are deleted.
7000784a601SMisha Brukman ///
TestOptimizer(BugDriver & BD,std::unique_ptr<Module> Test,std::unique_ptr<Module> Safe)7011c039155SJustin Bogner static Expected<bool> TestOptimizer(BugDriver &BD, std::unique_ptr<Module> Test,
7021c039155SJustin Bogner std::unique_ptr<Module> Safe) {
7030434ba3eSChris Lattner // Run the optimization passes on ToOptimize, producing a transformed version
7040434ba3eSChris Lattner // of the functions being tested.
705ee05152cSDan Gohman outs() << " Optimizing functions being tested: ";
706bc12cbc3SRafael Espindola std::unique_ptr<Module> Optimized =
70778153a6dSPhilip Reames BD.runPassesOn(Test.get(), BD.getPassesToRun());
70878153a6dSPhilip Reames if (!Optimized) {
70978153a6dSPhilip Reames errs() << " Error running this sequence of passes"
71078153a6dSPhilip Reames << " on the input program!\n";
711f6074ed9SRafael Espindola BD.EmitProgressBitcode(*Test, "pass-error", false);
7128b1f64f6SNick Desaulniers BD.setNewProgram(std::move(Test));
7131c039155SJustin Bogner if (Error E = BD.debugOptimizerCrash())
714c55cf4afSBill Wendling return std::move(E);
7151c039155SJustin Bogner return false;
71678153a6dSPhilip Reames }
717ee05152cSDan Gohman outs() << "done.\n";
7180434ba3eSChris Lattner
719ee05152cSDan Gohman outs() << " Checking to see if the merged program executes correctly: ";
720e490460fSRafael Espindola bool Broken;
72177b14505SBryant Wong auto Result = testMergedProgram(BD, *Optimized, *Safe, Broken);
7221c039155SJustin Bogner if (Error E = Result.takeError())
723c55cf4afSBill Wendling return std::move(E);
7241c039155SJustin Bogner if (auto New = std::move(*Result)) {
725e490460fSRafael Espindola outs() << (Broken ? " nope.\n" : " yup.\n");
726e490460fSRafael Espindola // Delete the original and set the new program.
727f6074ed9SRafael Espindola BD.setNewProgram(std::move(New));
728e490460fSRafael Espindola }
7290434ba3eSChris Lattner return Broken;
7300434ba3eSChris Lattner }
7310434ba3eSChris Lattner
732de4aa4cfSChris Lattner /// debugMiscompilation - This method is used when the passes selected are not
733de4aa4cfSChris Lattner /// crashing, but the generated output is semantically different from the
734de4aa4cfSChris Lattner /// input.
735de4aa4cfSChris Lattner ///
debugMiscompilation()7361c039155SJustin Bogner Error BugDriver::debugMiscompilation() {
737de4aa4cfSChris Lattner // Make sure something was miscompiled...
7381c039155SJustin Bogner if (!BugpointIsInterrupted) {
7391c039155SJustin Bogner Expected<bool> Result =
7401c039155SJustin Bogner ReduceMiscompilingPasses(*this).reduceList(PassesToRun);
7411c039155SJustin Bogner if (Error E = Result.takeError())
7421c039155SJustin Bogner return E;
7431c039155SJustin Bogner if (!*Result)
7441c039155SJustin Bogner return make_error<StringError>(
7451c039155SJustin Bogner "*** Optimized program matches reference output! No problem"
7461c039155SJustin Bogner " detected...\nbugpoint can't help you with your problem!\n",
7471c039155SJustin Bogner inconvertibleErrorCode());
748de4aa4cfSChris Lattner }
749de4aa4cfSChris Lattner
750ee05152cSDan Gohman outs() << "\n*** Found miscompiling pass"
751fd72bed3SChris Lattner << (getPassesToRun().size() == 1 ? "" : "es") << ": "
7526aa3c83fSMisha Brukman << getPassesString(getPassesToRun()) << '\n';
753f6074ed9SRafael Espindola EmitProgressBitcode(*Program, "passinput");
754de4aa4cfSChris Lattner
7551c039155SJustin Bogner Expected<std::vector<Function *>> MiscompiledFunctions =
7561c039155SJustin Bogner DebugAMiscompilation(*this, TestOptimizer);
7571c039155SJustin Bogner if (Error E = MiscompiledFunctions.takeError())
7581c039155SJustin Bogner return E;
759bcec7875SChris Lattner
7600e535c3cSGabor Greif // Output a bunch of bitcode files for the user...
761ee05152cSDan Gohman outs() << "Outputting reduced bitcode files which expose the problem:\n";
762229e38f0SRafael Espindola ValueToValueMapTy VMap;
763f6074ed9SRafael Espindola Module *ToNotOptimize = CloneModule(getProgram(), VMap).release();
76450102c29SRafael Espindola Module *ToOptimize =
7651c039155SJustin Bogner SplitFunctionsOutOfModule(ToNotOptimize, *MiscompiledFunctions, VMap)
76650102c29SRafael Espindola .release();
767567543f0SChris Lattner
768ee05152cSDan Gohman outs() << " Non-optimized portion: ";
769f6074ed9SRafael Espindola EmitProgressBitcode(*ToNotOptimize, "tonotoptimize", true);
770594994a3SRafael Espindola delete ToNotOptimize; // Delete hacked module.
771567543f0SChris Lattner
772ee05152cSDan Gohman outs() << " Portion that is input to optimizer: ";
773f6074ed9SRafael Espindola EmitProgressBitcode(*ToOptimize, "tooptimize");
774594994a3SRafael Espindola delete ToOptimize; // Delete hacked module.
7751c039155SJustin Bogner
7761c039155SJustin Bogner return Error::success();
777de4aa4cfSChris Lattner }
778960707c3SBrian Gaeke
779bc12cbc3SRafael Espindola /// Get the specified modules ready for code generator testing.
7800784a601SMisha Brukman ///
781b71251caSRafael Espindola static std::unique_ptr<Module>
CleanupAndPrepareModules(BugDriver & BD,std::unique_ptr<Module> Test,Module * Safe)782b71251caSRafael Espindola CleanupAndPrepareModules(BugDriver &BD, std::unique_ptr<Module> Test,
783bf791614SChris Lattner Module *Safe) {
784bf791614SChris Lattner // Clean up the modules, removing extra cruft that we don't need anymore...
785b71251caSRafael Espindola Test = BD.performFinalCleanups(std::move(Test));
786bf791614SChris Lattner
787bf791614SChris Lattner // If we are executing the JIT, we have several nasty issues to take care of.
7888d0a0811SJustin Bogner if (!BD.isExecutingJIT())
789b71251caSRafael Espindola return Test;
790bf791614SChris Lattner
791bf791614SChris Lattner // First, if the main function is in the Safe module, we must add a stub to
792bf791614SChris Lattner // the Test module to call into it. Thus, we create a new function `main'
793bf791614SChris Lattner // which just calls the old one.
7941241d6d5SReid Spencer if (Function *oldMain = Safe->getFunction("main"))
7955301e7c6SReid Spencer if (!oldMain->isDeclaration()) {
796bf791614SChris Lattner // Rename it
797bf791614SChris Lattner oldMain->setName("llvm_bugpoint_old_main");
798bf791614SChris Lattner // Create a NEW `main' function with same type in the test module.
799bc12cbc3SRafael Espindola Function *newMain =
800bc12cbc3SRafael Espindola Function::Create(oldMain->getFunctionType(),
801bc12cbc3SRafael Espindola GlobalValue::ExternalLinkage, "main", Test.get());
802bf791614SChris Lattner // Create an `oldmain' prototype in the test module, which will
803bf791614SChris Lattner // corresponds to the real main function in the same module.
804e9ecc68dSGabor Greif Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
805bf791614SChris Lattner GlobalValue::ExternalLinkage,
806bc12cbc3SRafael Espindola oldMain->getName(), Test.get());
807bf791614SChris Lattner // Set up and remember the argument list for the main function.
808bf791614SChris Lattner std::vector<Value *> args;
8098d0a0811SJustin Bogner for (Function::arg_iterator I = newMain->arg_begin(),
8108d0a0811SJustin Bogner E = newMain->arg_end(),
8118d0a0811SJustin Bogner OI = oldMain->arg_begin();
8128d0a0811SJustin Bogner I != E; ++I, ++OI) {
8137629b71dSOwen Anderson I->setName(OI->getName()); // Copy argument names from oldMain
814306d16e0SDuncan P. N. Exon Smith args.push_back(&*I);
815bf791614SChris Lattner }
816bf791614SChris Lattner
817bf791614SChris Lattner // Call the old main function and return its result
81855f1c09eSOwen Anderson BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
8195bd375a6SJay Foad CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
820bf791614SChris Lattner
821bf791614SChris Lattner // If the type of old function wasn't void, return value of call
82255f1c09eSOwen Anderson ReturnInst::Create(Safe->getContext(), call, BB);
823bf791614SChris Lattner }
824bf791614SChris Lattner
825bf791614SChris Lattner // The second nasty issue we must deal with in the JIT is that the Safe
826bf791614SChris Lattner // module cannot directly reference any functions defined in the test
827bf791614SChris Lattner // module. Instead, we use a JIT API call to dynamically resolve the
828bf791614SChris Lattner // symbol.
829bf791614SChris Lattner
830bf791614SChris Lattner // Add the resolver to the Safe module.
831bf791614SChris Lattner // Prototype: void *getPointerToNamedFunction(const char* Name)
83213680223SJames Y Knight FunctionCallee resolverFunc = Safe->getOrInsertFunction(
8338d0a0811SJustin Bogner "getPointerToNamedFunction", Type::getInt8PtrTy(Safe->getContext()),
83459a2d7b9SSerge Guelton Type::getInt8PtrTy(Safe->getContext()));
835bf791614SChris Lattner
836bf791614SChris Lattner // Use the function we just added to get addresses of functions we need.
837bf791614SChris Lattner for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
83813680223SJames Y Knight if (F->isDeclaration() && !F->use_empty() &&
83913680223SJames Y Knight &*F != resolverFunc.getCallee() &&
84038ef3a8eSDuncan Sands !F->isIntrinsic() /* ignore intrinsics */) {
8411241d6d5SReid Spencer Function *TestFn = Test->getFunction(F->getName());
842bf791614SChris Lattner
843bf791614SChris Lattner // Don't forward functions which are external in the test module too.
8445301e7c6SReid Spencer if (TestFn && !TestFn->isDeclaration()) {
845bf791614SChris Lattner // 1. Add a string constant with its name to the global file
846cf9e8f69SChris Lattner Constant *InitArray =
847cf9e8f69SChris Lattner ConstantDataArray::getString(F->getContext(), F->getName());
8488d0a0811SJustin Bogner GlobalVariable *funcName = new GlobalVariable(
8498d0a0811SJustin Bogner *Safe, InitArray->getType(), true /*isConstant*/,
8508d0a0811SJustin Bogner GlobalValue::InternalLinkage, InitArray, F->getName() + "_name");
851bf791614SChris Lattner
852bf791614SChris Lattner // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
853bf791614SChris Lattner // sbyte* so it matches the signature of the resolver function.
854bf791614SChris Lattner
855bf791614SChris Lattner // GetElementPtr *funcName, ulong 0, ulong 0
8568d0a0811SJustin Bogner std::vector<Constant *> GEPargs(
8578d0a0811SJustin Bogner 2, Constant::getNullValue(Type::getInt32Ty(F->getContext())));
8584a2e73b0SDavid Blaikie Value *GEP = ConstantExpr::getGetElementPtr(InitArray->getType(),
8594a2e73b0SDavid Blaikie funcName, GEPargs);
860bf791614SChris Lattner std::vector<Value *> ResolverArgs;
861bf791614SChris Lattner ResolverArgs.push_back(GEP);
862bf791614SChris Lattner
863ce89b392SMisha Brukman // Rewrite uses of F in global initializers, etc. to uses of a wrapper
864ce89b392SMisha Brukman // function that dynamically resolves the calls to F via our JIT API
865986675cbSChris Lattner if (!F->use_empty()) {
866986675cbSChris Lattner // Create a new global to hold the cached function pointer.
867b292b8ceSOwen Anderson Constant *NullPtr = ConstantPointerNull::get(F->getType());
8688d0a0811SJustin Bogner GlobalVariable *Cache = new GlobalVariable(
8698d0a0811SJustin Bogner *F->getParent(), F->getType(), false,
8708d0a0811SJustin Bogner GlobalValue::InternalLinkage, NullPtr, F->getName() + ".fpcache");
871986675cbSChris Lattner
872ce89b392SMisha Brukman // Construct a new stub function that will re-route calls to F
873229907cdSChris Lattner FunctionType *FuncTy = F->getFunctionType();
8748d0a0811SJustin Bogner Function *FuncWrapper =
8758d0a0811SJustin Bogner Function::Create(FuncTy, GlobalValue::InternalLinkage,
8768d0a0811SJustin Bogner F->getName() + "_wrapper", F->getParent());
8778d0a0811SJustin Bogner BasicBlock *EntryBB =
8788d0a0811SJustin Bogner BasicBlock::Create(F->getContext(), "entry", FuncWrapper);
8798d0a0811SJustin Bogner BasicBlock *DoCallBB =
8808d0a0811SJustin Bogner BasicBlock::Create(F->getContext(), "usecache", FuncWrapper);
8818d0a0811SJustin Bogner BasicBlock *LookupBB =
8828d0a0811SJustin Bogner BasicBlock::Create(F->getContext(), "lookupfp", FuncWrapper);
883986675cbSChris Lattner
884986675cbSChris Lattner // Check to see if we already looked up the value.
88514359ef1SJames Y Knight Value *CachedVal =
88614359ef1SJames Y Knight new LoadInst(F->getType(), Cache, "fpcache", EntryBB);
8871e5f00e7SOwen Anderson Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
8881e5f00e7SOwen Anderson NullPtr, "isNull");
889e9ecc68dSGabor Greif BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
89083018642SMisha Brukman
891ce89b392SMisha Brukman // Resolve the call to function F via the JIT API:
892ce89b392SMisha Brukman //
893ce89b392SMisha Brukman // call resolver(GetElementPtr...)
8948d0a0811SJustin Bogner CallInst *Resolver = CallInst::Create(resolverFunc, ResolverArgs,
8958d0a0811SJustin Bogner "resolver", LookupBB);
896697e94ccSGabor Greif
897697e94ccSGabor Greif // Cast the result from the resolver to correctly-typed function.
8988d0a0811SJustin Bogner CastInst *CastedResolver = new BitCastInst(
8998d0a0811SJustin Bogner Resolver, PointerType::getUnqual(F->getFunctionType()),
900697e94ccSGabor Greif "resolverCast", LookupBB);
9016c38f0bbSReid Spencer
902986675cbSChris Lattner // Save the value in our cache.
903986675cbSChris Lattner new StoreInst(CastedResolver, Cache, LookupBB);
904e9ecc68dSGabor Greif BranchInst::Create(DoCallBB, LookupBB);
905ce89b392SMisha Brukman
9068d0a0811SJustin Bogner PHINode *FuncPtr =
9078d0a0811SJustin Bogner PHINode::Create(NullPtr->getType(), 2, "fp", DoCallBB);
908986675cbSChris Lattner FuncPtr->addIncoming(CastedResolver, LookupBB);
909986675cbSChris Lattner FuncPtr->addIncoming(CachedVal, EntryBB);
910986675cbSChris Lattner
911986675cbSChris Lattner // Save the argument list.
91283018642SMisha Brukman std::vector<Value *> Args;
913306d16e0SDuncan P. N. Exon Smith for (Argument &A : FuncWrapper->args())
914306d16e0SDuncan P. N. Exon Smith Args.push_back(&A);
91583018642SMisha Brukman
91683018642SMisha Brukman // Pass on the arguments to the real function, return its result
91734a2249fSDan Gohman if (F->getReturnType()->isVoidTy()) {
9187976eb58SJames Y Knight CallInst::Create(FuncTy, FuncPtr, Args, "", DoCallBB);
91955f1c09eSOwen Anderson ReturnInst::Create(F->getContext(), DoCallBB);
92083018642SMisha Brukman } else {
9218d0a0811SJustin Bogner CallInst *Call =
9227976eb58SJames Y Knight CallInst::Create(FuncTy, FuncPtr, Args, "retval", DoCallBB);
92355f1c09eSOwen Anderson ReturnInst::Create(F->getContext(), Call, DoCallBB);
92483018642SMisha Brukman }
92583018642SMisha Brukman
926ce89b392SMisha Brukman // Use the wrapper function instead of the old function
927ce89b392SMisha Brukman F->replaceAllUsesWith(FuncWrapper);
928bf791614SChris Lattner }
929bf791614SChris Lattner }
930bf791614SChris Lattner }
931bf791614SChris Lattner }
932bf791614SChris Lattner
933bf791614SChris Lattner if (verifyModule(*Test) || verifyModule(*Safe)) {
934d8db3760SDan Gohman errs() << "Bugpoint has a bug, which corrupted a module!!\n";
935bf791614SChris Lattner abort();
936bf791614SChris Lattner }
937b71251caSRafael Espindola
938b71251caSRafael Espindola return Test;
939bf791614SChris Lattner }
940bf791614SChris Lattner
941bc12cbc3SRafael Espindola /// This is the predicate function used to check to see if the "Test" portion of
942bc12cbc3SRafael Espindola /// the program is miscompiled by the code generator under test. If so, return
943bc12cbc3SRafael Espindola /// true. In any case, both module arguments are deleted.
9440784a601SMisha Brukman ///
TestCodeGenerator(BugDriver & BD,std::unique_ptr<Module> Test,std::unique_ptr<Module> Safe)9451c039155SJustin Bogner static Expected<bool> TestCodeGenerator(BugDriver &BD,
9461c039155SJustin Bogner std::unique_ptr<Module> Test,
9471c039155SJustin Bogner std::unique_ptr<Module> Safe) {
948b71251caSRafael Espindola Test = CleanupAndPrepareModules(BD, std::move(Test), Safe.get());
949bf791614SChris Lattner
950302c0da6SRafael Espindola SmallString<128> TestModuleBC;
951302c0da6SRafael Espindola int TestModuleFD;
9524453e429SRafael Espindola std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
953155cf0f3SRafael Espindola TestModuleFD, TestModuleBC);
954302c0da6SRafael Espindola if (EC) {
9558d0a0811SJustin Bogner errs() << BD.getToolName()
9568d0a0811SJustin Bogner << "Error making unique filename: " << EC.message() << "\n";
957e4ca7221SReid Spencer exit(1);
958e4ca7221SReid Spencer }
959adcd0268SBenjamin Kramer if (BD.writeProgramToFile(std::string(TestModuleBC.str()), TestModuleFD,
960adcd0268SBenjamin Kramer *Test)) {
961c521f541SChris Lattner errs() << "Error writing bitcode to `" << TestModuleBC.str()
962c521f541SChris Lattner << "'\nExiting.";
963bf791614SChris Lattner exit(1);
964bf791614SChris Lattner }
965bf791614SChris Lattner
966c60223efSMichael J. Spencer FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
967720f49edSRafael Espindola
968bf791614SChris Lattner // Make the shared library
969302c0da6SRafael Espindola SmallString<128> SafeModuleBC;
970302c0da6SRafael Espindola int SafeModuleFD;
971155cf0f3SRafael Espindola EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
972302c0da6SRafael Espindola SafeModuleBC);
973302c0da6SRafael Espindola if (EC) {
9748d0a0811SJustin Bogner errs() << BD.getToolName()
9758d0a0811SJustin Bogner << "Error making unique filename: " << EC.message() << "\n";
976e4ca7221SReid Spencer exit(1);
977e4ca7221SReid Spencer }
978bf791614SChris Lattner
979adcd0268SBenjamin Kramer if (BD.writeProgramToFile(std::string(SafeModuleBC.str()), SafeModuleFD,
980adcd0268SBenjamin Kramer *Safe)) {
9818d0a0811SJustin Bogner errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
982bf791614SChris Lattner exit(1);
983bf791614SChris Lattner }
984720f49edSRafael Espindola
985c60223efSMichael J. Spencer FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
986720f49edSRafael Espindola
9871c039155SJustin Bogner Expected<std::string> SharedObject =
988adcd0268SBenjamin Kramer BD.compileSharedObject(std::string(SafeModuleBC.str()));
9891c039155SJustin Bogner if (Error E = SharedObject.takeError())
990c55cf4afSBill Wendling return std::move(E);
991bf791614SChris Lattner
9921c039155SJustin Bogner FileRemover SharedObjectRemover(*SharedObject, !SaveTemps);
993720f49edSRafael Espindola
994bf791614SChris Lattner // Run the code generator on the `Test' code, loading the shared library.
995bf791614SChris Lattner // The function returns whether or not the new output differs from reference.
996adcd0268SBenjamin Kramer Expected<bool> Result = BD.diffProgram(
997adcd0268SBenjamin Kramer BD.getProgram(), std::string(TestModuleBC.str()), *SharedObject, false);
9981c039155SJustin Bogner if (Error E = Result.takeError())
999c55cf4afSBill Wendling return std::move(E);
1000bf791614SChris Lattner
10011c039155SJustin Bogner if (*Result)
1002d8db3760SDan Gohman errs() << ": still failing!\n";
1003bf791614SChris Lattner else
1004d8db3760SDan Gohman errs() << ": didn't fail.\n";
1005bf791614SChris Lattner
1006bf791614SChris Lattner return Result;
1007bf791614SChris Lattner }
1008bf791614SChris Lattner
10090784a601SMisha Brukman /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
10100784a601SMisha Brukman ///
debugCodeGenerator()10111c039155SJustin Bogner Error BugDriver::debugCodeGenerator() {
1012414cf502SDan Gohman if ((void *)SafeInterpreter == (void *)Interpreter) {
10131c039155SJustin Bogner Expected<std::string> Result =
1014f6074ed9SRafael Espindola executeProgramSafely(*Program, "bugpoint.safe.out");
10151c039155SJustin Bogner if (Result) {
1016ee05152cSDan Gohman outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
1017414cf502SDan Gohman << "the reference diff. This may be due to a\n front-end "
1018414cf502SDan Gohman << "bug or a bug in the original program, but this can also "
1019414cf502SDan Gohman << "happen if bugpoint isn't running the program with the "
1020414cf502SDan Gohman << "right flags or input.\n I left the result of executing "
1021414cf502SDan Gohman << "the program with the \"safe\" backend in this file for "
10221c039155SJustin Bogner << "you: '" << *Result << "'.\n";
10236ba630b0SNick Lewycky }
10241c039155SJustin Bogner return Error::success();
1025bf791614SChris Lattner }
1026bf791614SChris Lattner
1027f6074ed9SRafael Espindola DisambiguateGlobalSymbols(*Program);
1028bf791614SChris Lattner
10291c039155SJustin Bogner Expected<std::vector<Function *>> Funcs =
10301c039155SJustin Bogner DebugAMiscompilation(*this, TestCodeGenerator);
10311c039155SJustin Bogner if (Error E = Funcs.takeError())
10321c039155SJustin Bogner return E;
1033bf791614SChris Lattner
1034bf791614SChris Lattner // Split the module into the two halves of the program we want.
1035229e38f0SRafael Espindola ValueToValueMapTy VMap;
1036f6074ed9SRafael Espindola std::unique_ptr<Module> ToNotCodeGen = CloneModule(getProgram(), VMap);
1037bc12cbc3SRafael Espindola std::unique_ptr<Module> ToCodeGen =
10381c039155SJustin Bogner SplitFunctionsOutOfModule(ToNotCodeGen.get(), *Funcs, VMap);
1039bf791614SChris Lattner
1040bf791614SChris Lattner // Condition the modules
1041b71251caSRafael Espindola ToCodeGen =
1042b71251caSRafael Espindola CleanupAndPrepareModules(*this, std::move(ToCodeGen), ToNotCodeGen.get());
1043bf791614SChris Lattner
1044302c0da6SRafael Espindola SmallString<128> TestModuleBC;
1045302c0da6SRafael Espindola int TestModuleFD;
10464453e429SRafael Espindola std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
1047155cf0f3SRafael Espindola TestModuleFD, TestModuleBC);
1048302c0da6SRafael Espindola if (EC) {
10498d0a0811SJustin Bogner errs() << getToolName() << "Error making unique filename: " << EC.message()
10508d0a0811SJustin Bogner << "\n";
1051e4ca7221SReid Spencer exit(1);
1052e4ca7221SReid Spencer }
105330067f1eSReid Spencer
1054adcd0268SBenjamin Kramer if (writeProgramToFile(std::string(TestModuleBC.str()), TestModuleFD,
1055adcd0268SBenjamin Kramer *ToCodeGen)) {
10568d0a0811SJustin Bogner errs() << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
1057bf791614SChris Lattner exit(1);
1058bf791614SChris Lattner }
1059bf791614SChris Lattner
1060bf791614SChris Lattner // Make the shared library
1061302c0da6SRafael Espindola SmallString<128> SafeModuleBC;
1062302c0da6SRafael Espindola int SafeModuleFD;
1063155cf0f3SRafael Espindola EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
1064302c0da6SRafael Espindola SafeModuleBC);
1065302c0da6SRafael Espindola if (EC) {
10668d0a0811SJustin Bogner errs() << getToolName() << "Error making unique filename: " << EC.message()
10678d0a0811SJustin Bogner << "\n";
1068e4ca7221SReid Spencer exit(1);
1069e4ca7221SReid Spencer }
107030067f1eSReid Spencer
1071adcd0268SBenjamin Kramer if (writeProgramToFile(std::string(SafeModuleBC.str()), SafeModuleFD,
1072adcd0268SBenjamin Kramer *ToNotCodeGen)) {
10738d0a0811SJustin Bogner errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
1074bf791614SChris Lattner exit(1);
1075bf791614SChris Lattner }
1076adcd0268SBenjamin Kramer Expected<std::string> SharedObject =
1077adcd0268SBenjamin Kramer compileSharedObject(std::string(SafeModuleBC.str()));
10781c039155SJustin Bogner if (Error E = SharedObject.takeError())
10791c039155SJustin Bogner return E;
1080bf791614SChris Lattner
1081ee05152cSDan Gohman outs() << "You can reproduce the problem with the command line: \n";
1082bf791614SChris Lattner if (isExecutingJIT()) {
10831c039155SJustin Bogner outs() << " lli -load " << *SharedObject << " " << TestModuleBC;
1084bf791614SChris Lattner } else {
10858d0a0811SJustin Bogner outs() << " llc " << TestModuleBC << " -o " << TestModuleBC << ".s\n";
10861c039155SJustin Bogner outs() << " cc " << *SharedObject << " " << TestModuleBC.str() << ".s -o "
10878c4e4213SJoerg Sonnenberger << TestModuleBC << ".exe\n";
10888c4e4213SJoerg Sonnenberger outs() << " ./" << TestModuleBC << ".exe";
1089bf791614SChris Lattner }
1090bf791614SChris Lattner for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
1091ee05152cSDan Gohman outs() << " " << InputArgv[i];
1092ee05152cSDan Gohman outs() << '\n';
1093ee05152cSDan Gohman outs() << "The shared object was created with:\n llc -march=c "
1094c521f541SChris Lattner << SafeModuleBC.str() << " -o temporary.c\n"
10951c039155SJustin Bogner << " cc -xc temporary.c -O2 -o " << *SharedObject;
10968575a60dSDaniel Dunbar if (TargetTriple.getArch() == Triple::sparc)
10978575a60dSDaniel Dunbar outs() << " -G"; // Compile a shared library, `-G' for Sparc
10988575a60dSDaniel Dunbar else
10998575a60dSDaniel Dunbar outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
11008575a60dSDaniel Dunbar
11018575a60dSDaniel Dunbar outs() << " -fno-strict-aliasing\n";
1102bf791614SChris Lattner
11031c039155SJustin Bogner return Error::success();
1104bf791614SChris Lattner }
1105