blob: 863aaa24780afef1904ceb24235f57746ccc849b [file] [log] [blame]
Chris Lattnerde4aa4c2002-12-23 23:50:16 +00001//===- Miscompilation.cpp - Debug program miscompilations -----------------===//
Misha Brukman650ba8e2005-04-22 00:00:37 +00002//
John Criswell09344dc2003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner345353d2007-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 Brukman650ba8e2005-04-22 00:00:37 +00007//
John Criswell09344dc2003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerde4aa4c2002-12-23 23:50:16 +00009//
Chris Lattnerbf791612004-04-05 22:58:16 +000010// This file implements optimizer and code generation miscompilation debugging
11// support.
Chris Lattnerde4aa4c2002-12-23 23:50:16 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "BugDriver.h"
Chris Lattner9f5a1972003-04-24 20:16:29 +000016#include "ListReducer.h"
Daniel Dunbar8575a602009-08-18 03:35:57 +000017#include "ToolRunner.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000018#include "llvm/Config/config.h" // for HAVE_LINK_R
Chandler Carruth9fb823b2013-01-02 11:36:10 +000019#include "llvm/IR/Constants.h"
20#include "llvm/IR/DerivedTypes.h"
21#include "llvm/IR/Instructions.h"
22#include "llvm/IR/Module.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000023#include "llvm/IR/Verifier.h"
Chandler Carruth6cc07df2014-03-06 03:42:23 +000024#include "llvm/Linker/Linker.h"
Misha Brukman0c2305b2003-08-07 21:19:30 +000025#include "llvm/Pass.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/FileUtilities.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000028#include "llvm/Transforms/Utils/Cloning.h"
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +000029
Chris Lattner2f1aa112004-01-14 03:38:37 +000030using namespace llvm;
Chris Lattnerde4aa4c2002-12-23 23:50:16 +000031
Chris Lattnerbf791612004-04-05 22:58:16 +000032namespace llvm {
Daniel Dunbara53337f2009-09-07 19:26:11 +000033 extern cl::opt<std::string> OutputPrefix;
Chris Lattnerbf791612004-04-05 22:58:16 +000034 extern cl::list<std::string> InputArgv;
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +000035} // end namespace llvm
Chris Lattnerbf791612004-04-05 22:58:16 +000036
Chris Lattnerfd72bed2004-03-14 20:50:42 +000037namespace {
Michael J. Spencer3df5c042011-03-31 13:06:39 +000038 static llvm::cl::opt<bool>
39 DisableLoopExtraction("disable-loop-extraction",
Reid Spencer471bcb72006-11-11 19:05:02 +000040 cl::desc("Don't extract loops when searching for miscompilations"),
41 cl::init(false));
Michael J. Spencer3df5c042011-03-31 13:06:39 +000042 static llvm::cl::opt<bool>
43 DisableBlockExtraction("disable-block-extraction",
David Goodwin2c04ff62009-07-28 23:08:36 +000044 cl::desc("Don't extract blocks when searching for miscompilations"),
45 cl::init(false));
Reid Spencer471bcb72006-11-11 19:05:02 +000046
Rafael Espindola33e81a82010-08-08 03:55:08 +000047 class ReduceMiscompilingPasses : public ListReducer<std::string> {
Chris Lattner2f1aa112004-01-14 03:38:37 +000048 BugDriver &BD;
49 public:
50 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +000051
Craig Toppere56917c2014-03-08 08:27:28 +000052 TestResult doTest(std::vector<std::string> &Prefix,
53 std::vector<std::string> &Suffix,
54 std::string &Error) override;
Chris Lattner2f1aa112004-01-14 03:38:37 +000055 };
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +000056} // end anonymous namespace
Chris Lattner16a41312003-04-24 17:02:17 +000057
Misha Brukman0784a602004-04-21 18:36:43 +000058/// TestResult - After passes have been split into a test group and a control
59/// group, see if they still break the program.
60///
Chris Lattner16a41312003-04-24 17:02:17 +000061ReduceMiscompilingPasses::TestResult
Rafael Espindola33e81a82010-08-08 03:55:08 +000062ReduceMiscompilingPasses::doTest(std::vector<std::string> &Prefix,
63 std::vector<std::string> &Suffix,
Nick Lewycky6ba630b2010-04-12 05:08:25 +000064 std::string &Error) {
Chris Lattner4a1a9d22003-04-25 03:16:05 +000065 // First, run the program with just the Suffix passes. If it is still broken
Chris Lattner16a41312003-04-24 17:02:17 +000066 // with JUST the kept passes, discard the prefix passes.
Dan Gohmanee051522009-07-16 15:30:09 +000067 outs() << "Checking to see if '" << getPassesString(Suffix)
68 << "' compiles correctly: ";
Chris Lattner16a41312003-04-24 17:02:17 +000069
Gabor Greif0e535c3c2007-07-04 21:55:50 +000070 std::string BitcodeResult;
Rafael Espindola315190b2010-08-05 00:29:04 +000071 if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false/*delete*/,
72 true/*quiet*/)) {
Dan Gohmand8db3762009-07-15 16:35:29 +000073 errs() << " Error running this sequence of passes"
74 << " on the input program!\n";
Chris Lattner92a9f7a2003-10-17 23:07:47 +000075 BD.setPassesToRun(Suffix);
Rafael Espindola594994a2010-07-28 18:12:30 +000076 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
Chris Lattneread1dff2004-02-18 21:02:04 +000077 exit(BD.debugOptimizerCrash());
Chris Lattner16a41312003-04-24 17:02:17 +000078 }
Michael J. Spencer3df5c042011-03-31 13:06:39 +000079
Chris Lattner16a41312003-04-24 17:02:17 +000080 // Check to see if the finished program matches the reference output...
Rafael Espindolac89b1ef2010-07-30 14:19:00 +000081 bool Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
82 true /*delete bitcode*/, &Error);
Nick Lewycky6ba630b2010-04-12 05:08:25 +000083 if (!Error.empty())
84 return InternalError;
85 if (Diff) {
Dan Gohmanee051522009-07-16 15:30:09 +000086 outs() << " nope.\n";
Chris Lattnerea2fa462005-01-15 00:07:19 +000087 if (Suffix.empty()) {
Dan Gohmand8db3762009-07-15 16:35:29 +000088 errs() << BD.getToolName() << ": I'm confused: the test fails when "
89 << "no passes are run, nondeterministic program?\n";
Chris Lattnerea2fa462005-01-15 00:07:19 +000090 exit(1);
91 }
Misha Brukman324e9e02004-04-22 20:02:09 +000092 return KeepSuffix; // Miscompilation detected!
Chris Lattner16a41312003-04-24 17:02:17 +000093 }
Dan Gohmanee051522009-07-16 15:30:09 +000094 outs() << " yup.\n"; // No miscompilation!
Chris Lattner16a41312003-04-24 17:02:17 +000095
96 if (Prefix.empty()) return NoFailure;
97
Chris Lattner4a1a9d22003-04-25 03:16:05 +000098 // Next, see if the program is broken if we run the "prefix" passes first,
Misha Brukman7fdaab42003-07-14 17:20:40 +000099 // then separately run the "kept" passes.
Dan Gohmanee051522009-07-16 15:30:09 +0000100 outs() << "Checking to see if '" << getPassesString(Prefix)
101 << "' compiles correctly: ";
Chris Lattner16a41312003-04-24 17:02:17 +0000102
103 // If it is not broken with the kept passes, it's possible that the prefix
104 // passes must be run before the kept passes to break it. If the program
105 // WORKS after the prefix passes, but then fails if running the prefix AND
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000106 // kept passes, we can update our bitcode file to include the result of the
Chris Lattner16a41312003-04-24 17:02:17 +0000107 // prefix passes, then discard the prefix passes.
108 //
Rafael Espindola315190b2010-08-05 00:29:04 +0000109 if (BD.runPasses(BD.getProgram(), Prefix, BitcodeResult, false/*delete*/,
110 true/*quiet*/)) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000111 errs() << " Error running this sequence of passes"
112 << " on the input program!\n";
Chris Lattner7d147ae2003-10-17 23:03:16 +0000113 BD.setPassesToRun(Prefix);
Rafael Espindola594994a2010-07-28 18:12:30 +0000114 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
Chris Lattneread1dff2004-02-18 21:02:04 +0000115 exit(BD.debugOptimizerCrash());
Chris Lattner16a41312003-04-24 17:02:17 +0000116 }
117
118 // If the prefix maintains the predicate by itself, only keep the prefix!
Rafael Espindolac89b1ef2010-07-30 14:19:00 +0000119 Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "", false, &Error);
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000120 if (!Error.empty())
121 return InternalError;
122 if (Diff) {
Dan Gohmanee051522009-07-16 15:30:09 +0000123 outs() << " nope.\n";
Rafael Espindola18079582013-06-17 21:50:28 +0000124 sys::fs::remove(BitcodeResult);
Chris Lattner16a41312003-04-24 17:02:17 +0000125 return KeepPrefix;
126 }
Dan Gohmanee051522009-07-16 15:30:09 +0000127 outs() << " yup.\n"; // No miscompilation!
Chris Lattner16a41312003-04-24 17:02:17 +0000128
129 // Ok, so now we know that the prefix passes work, try running the suffix
130 // passes on the result of the prefix passes.
131 //
Rafael Espindola28b351a2014-08-26 17:19:03 +0000132 std::unique_ptr<Module> PrefixOutput =
133 parseInputFile(BitcodeResult, BD.getContext());
David Blaikie041f1aa2013-05-15 07:36:59 +0000134 if (!PrefixOutput) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000135 errs() << BD.getToolName() << ": Error reading bitcode file '"
136 << BitcodeResult << "'!\n";
Chris Lattner16a41312003-04-24 17:02:17 +0000137 exit(1);
138 }
Rafael Espindola18079582013-06-17 21:50:28 +0000139 sys::fs::remove(BitcodeResult);
Chris Lattner02cea4a2004-04-23 20:36:51 +0000140
141 // Don't check if there are no passes in the suffix.
142 if (Suffix.empty())
143 return NoFailure;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000144
Dan Gohmanee051522009-07-16 15:30:09 +0000145 outs() << "Checking to see if '" << getPassesString(Suffix)
Chris Lattner16a41312003-04-24 17:02:17 +0000146 << "' passes compile correctly after the '"
147 << getPassesString(Prefix) << "' passes: ";
148
Ahmed Charles56440fd2014-03-06 05:51:42 +0000149 std::unique_ptr<Module> OriginalInput(
150 BD.swapProgramIn(PrefixOutput.release()));
Rafael Espindola315190b2010-08-05 00:29:04 +0000151 if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false/*delete*/,
152 true/*quiet*/)) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000153 errs() << " Error running this sequence of passes"
154 << " on the input program!\n";
Chris Lattner92a9f7a2003-10-17 23:07:47 +0000155 BD.setPassesToRun(Suffix);
Rafael Espindola594994a2010-07-28 18:12:30 +0000156 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
Chris Lattneread1dff2004-02-18 21:02:04 +0000157 exit(BD.debugOptimizerCrash());
Chris Lattner16a41312003-04-24 17:02:17 +0000158 }
159
160 // Run the result...
Rafael Espindolac89b1ef2010-07-30 14:19:00 +0000161 Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
162 true /*delete bitcode*/, &Error);
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000163 if (!Error.empty())
164 return InternalError;
165 if (Diff) {
Dan Gohmanee051522009-07-16 15:30:09 +0000166 outs() << " nope.\n";
Chris Lattner4a1a9d22003-04-25 03:16:05 +0000167 return KeepSuffix;
Chris Lattner16a41312003-04-24 17:02:17 +0000168 }
169
170 // Otherwise, we must not be running the bad pass anymore.
Dan Gohmanee051522009-07-16 15:30:09 +0000171 outs() << " yup.\n"; // No miscompilation!
Jeffrey Yasskine476fa02010-05-11 23:25:16 +0000172 // Restore orig program & free test.
Ahmed Charles96c9d952014-03-05 10:19:29 +0000173 delete BD.swapProgramIn(OriginalInput.release());
Chris Lattner16a41312003-04-24 17:02:17 +0000174 return NoFailure;
175}
176
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000177namespace {
Chris Lattner2f1aa112004-01-14 03:38:37 +0000178 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
179 BugDriver &BD;
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000180 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
181 std::unique_ptr<Module>, std::string &);
182
Chris Lattner2f1aa112004-01-14 03:38:37 +0000183 public:
Chris Lattner0434ba32004-04-05 21:37:38 +0000184 ReduceMiscompilingFunctions(BugDriver &bd,
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000185 bool (*F)(BugDriver &, std::unique_ptr<Module>,
186 std::unique_ptr<Module>,
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000187 std::string &))
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000188 : BD(bd), TestFn(F) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000189
Craig Toppere56917c2014-03-08 08:27:28 +0000190 TestResult doTest(std::vector<Function*> &Prefix,
191 std::vector<Function*> &Suffix,
192 std::string &Error) override {
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000193 if (!Suffix.empty()) {
194 bool Ret = TestFuncs(Suffix, Error);
195 if (!Error.empty())
196 return InternalError;
197 if (Ret)
198 return KeepSuffix;
199 }
200 if (!Prefix.empty()) {
201 bool Ret = TestFuncs(Prefix, Error);
202 if (!Error.empty())
203 return InternalError;
204 if (Ret)
205 return KeepPrefix;
206 }
Chris Lattner2f1aa112004-01-14 03:38:37 +0000207 return NoFailure;
208 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000209
Rafael Espindola235457c2010-07-26 00:07:51 +0000210 bool TestFuncs(const std::vector<Function*> &Prefix, std::string &Error);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000211 };
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000212} // end anonymous namespace
Chris Lattner16a41312003-04-24 17:02:17 +0000213
Rafael Espindola7471abd2015-12-09 00:55:05 +0000214/// Given two modules, link them together and run the program, checking to see
215/// if the program matches the diff. If there is an error, return NULL. If not,
216/// return the merged module. The Broken argument will be set to true if the
217/// output is different. If the DeleteInputs argument is set to true then this
218/// function deletes both input modules before it returns.
Misha Brukman0784a602004-04-21 18:36:43 +0000219///
Rafael Espindola7471abd2015-12-09 00:55:05 +0000220static std::unique_ptr<Module> testMergedProgram(const BugDriver &BD,
221 std::unique_ptr<Module> M1,
222 std::unique_ptr<Module> M2,
223 std::string &Error,
224 bool &Broken) {
Rafael Espindola434e9562015-12-16 23:16:33 +0000225 if (Linker::linkModules(*M1, std::move(M2)))
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000226 exit(1);
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000227
Rafael Espindolae4904602010-07-31 14:34:49 +0000228 // Execute the program.
Rafael Espindola7471abd2015-12-09 00:55:05 +0000229 Broken = BD.diffProgram(M1.get(), "", "", false, &Error);
230 if (!Error.empty())
Craig Toppere6cb63e2014-04-25 04:24:47 +0000231 return nullptr;
Rafael Espindolae4904602010-07-31 14:34:49 +0000232 return M1;
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000233}
234
Misha Brukman0784a602004-04-21 18:36:43 +0000235/// TestFuncs - split functions in a Module into two groups: those that are
236/// under consideration for miscompilation vs. those that are not, and test
237/// accordingly. Each group of functions becomes a separate Module.
238///
Rafael Espindola235457c2010-07-26 00:07:51 +0000239bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*> &Funcs,
240 std::string &Error) {
Chris Lattner16a41312003-04-24 17:02:17 +0000241 // Test to see if the function is misoptimized if we ONLY run it on the
242 // functions listed in Funcs.
Dan Gohmanee051522009-07-16 15:30:09 +0000243 outs() << "Checking to see if the program is misoptimized when "
244 << (Funcs.size()==1 ? "this function is" : "these functions are")
245 << " run through the pass"
246 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000247 PrintFunctionList(Funcs);
Dan Gohmanee051522009-07-16 15:30:09 +0000248 outs() << '\n';
Chris Lattner16a41312003-04-24 17:02:17 +0000249
Rafael Espindola235457c2010-07-26 00:07:51 +0000250 // Create a clone for two reasons:
251 // * If the optimization passes delete any function, the deleted function
252 // will be in the clone and Funcs will still point to valid memory
253 // * If the optimization passes use interprocedural information to break
254 // a function, we want to continue with the original function. Otherwise
255 // we can conclude that a function triggers the bug when in fact one
256 // needs a larger set of original functions to do so.
Rafael Espindola229e38f2010-10-13 01:36:30 +0000257 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000258 Module *Clone = CloneModule(BD.getProgram(), VMap).release();
Rafael Espindola235457c2010-07-26 00:07:51 +0000259 Module *Orig = BD.swapProgramIn(Clone);
260
261 std::vector<Function*> FuncsOnClone;
262 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
263 Function *F = cast<Function>(VMap[Funcs[i]]);
264 FuncsOnClone.push_back(F);
265 }
266
267 // Split the module into the two halves of the program we want.
268 VMap.clear();
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000269 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
270 std::unique_ptr<Module> ToOptimize =
271 SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
Chris Lattner16a41312003-04-24 17:02:17 +0000272
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000273 bool Broken =
274 TestFn(BD, std::move(ToOptimize), std::move(ToNotOptimize), Error);
Rafael Espindola235457c2010-07-26 00:07:51 +0000275
276 delete BD.swapProgramIn(Orig);
277
278 return Broken;
Chris Lattner16a41312003-04-24 17:02:17 +0000279}
280
Chris Lattnerdc2cb5a2010-01-16 21:34:01 +0000281/// DisambiguateGlobalSymbols - Give anonymous global values names.
Misha Brukman0784a602004-04-21 18:36:43 +0000282///
Chris Lattnerdfbb1d12004-04-11 23:52:35 +0000283static void DisambiguateGlobalSymbols(Module *M) {
Chris Lattner34d26c32006-05-04 23:35:31 +0000284 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
Chris Lattner6a941f02010-01-16 21:34:51 +0000285 I != E; ++I)
Chris Lattnerdc2cb5a2010-01-16 21:34:01 +0000286 if (!I->hasName())
287 I->setName("anon_global");
Chris Lattner6a941f02010-01-16 21:34:51 +0000288 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattnerdc2cb5a2010-01-16 21:34:01 +0000289 if (!I->hasName())
290 I->setName("anon_fn");
Chris Lattnerdfbb1d12004-04-11 23:52:35 +0000291}
292
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000293/// Given a reduced list of functions that still exposed the bug, check to see
294/// if we can extract the loops in the region without obscuring the bug. If so,
295/// it reduces the amount of code identified.
Misha Brukman0784a602004-04-21 18:36:43 +0000296///
Chris Lattner0434ba32004-04-05 21:37:38 +0000297static bool ExtractLoops(BugDriver &BD,
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000298 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
299 std::unique_ptr<Module>, std::string &),
300 std::vector<Function *> &MiscompiledFunctions,
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000301 std::string &Error) {
Chris Lattnerbcec7872004-03-14 22:08:00 +0000302 bool MadeChange = false;
303 while (1) {
Chris Lattnerbd615f52005-08-02 23:25:56 +0000304 if (BugpointIsInterrupted) return MadeChange;
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000305
Rafael Espindola229e38f2010-10-13 01:36:30 +0000306 ValueToValueMapTy VMap;
Rafael Espindola000bf492015-12-09 00:18:41 +0000307 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
308 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize.get(),
Rafael Espindola50102c22015-12-09 00:34:10 +0000309 MiscompiledFunctions, VMap)
310 .release();
Rafael Espindola88a8f722015-12-09 00:08:22 +0000311 std::unique_ptr<Module> ToOptimizeLoopExtracted =
312 BD.extractLoop(ToOptimize);
Chris Lattnerbcec7872004-03-14 22:08:00 +0000313 if (!ToOptimizeLoopExtracted) {
314 // If the loop extractor crashed or if there were no extractible loops,
315 // then this chapter of our odyssey is over with.
Chris Lattnerbcec7872004-03-14 22:08:00 +0000316 delete ToOptimize;
317 return MadeChange;
318 }
319
Dan Gohmand8db3762009-07-15 16:35:29 +0000320 errs() << "Extracted a loop from the breaking portion of the program.\n";
Chris Lattnerbcec7872004-03-14 22:08:00 +0000321
322 // Bugpoint is intentionally not very trusting of LLVM transformations. In
323 // particular, we're not going to assume that the loop extractor works, so
324 // we're going to test the newly loop extracted program to make sure nothing
325 // has broken. If something broke, then we'll inform the user and stop
326 // extraction.
Dan Gohman414cf502008-12-08 04:02:47 +0000327 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
Rafael Espindolae4904602010-07-31 14:34:49 +0000328 bool Failure;
Rafael Espindola7471abd2015-12-09 00:55:05 +0000329 std::unique_ptr<Module> New =
330 testMergedProgram(BD, std::move(ToOptimizeLoopExtracted),
331 std::move(ToNotOptimize), Error, Failure);
Rafael Espindolae4904602010-07-31 14:34:49 +0000332 if (!New)
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000333 return false;
Hal Finkele9efbf12013-08-02 21:13:42 +0000334
Rafael Espindolae4904602010-07-31 14:34:49 +0000335 // Delete the original and set the new program.
Rafael Espindola7471abd2015-12-09 00:55:05 +0000336 Module *Old = BD.swapProgramIn(New.release());
Hal Finkele9efbf12013-08-02 21:13:42 +0000337 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
338 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
339 delete Old;
340
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000341 if (Failure) {
Chris Lattnerbf791612004-04-05 22:58:16 +0000342 BD.switchToInterpreter(AI);
343
Chris Lattnerbcec7872004-03-14 22:08:00 +0000344 // Merged program doesn't work anymore!
Dan Gohmand8db3762009-07-15 16:35:29 +0000345 errs() << " *** ERROR: Loop extraction broke the program. :("
346 << " Please report a bug!\n";
347 errs() << " Continuing on with un-loop-extracted version.\n";
Chris Lattner257008b2005-05-08 21:54:56 +0000348
Daniel Dunbara53337f2009-09-07 19:26:11 +0000349 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
Rafael Espindola000bf492015-12-09 00:18:41 +0000350 ToNotOptimize.get());
Daniel Dunbara53337f2009-09-07 19:26:11 +0000351 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
352 ToOptimize);
353 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
Rafael Espindola88a8f722015-12-09 00:08:22 +0000354 ToOptimizeLoopExtracted.get());
Chris Lattner257008b2005-05-08 21:54:56 +0000355
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000356 errs() << "Please submit the "
Daniel Dunbara53337f2009-09-07 19:26:11 +0000357 << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
Chris Lattner257008b2005-05-08 21:54:56 +0000358 delete ToOptimize;
Chris Lattnerbcec7872004-03-14 22:08:00 +0000359 return MadeChange;
360 }
Chris Lattner257008b2005-05-08 21:54:56 +0000361 delete ToOptimize;
Chris Lattnerbf791612004-04-05 22:58:16 +0000362 BD.switchToInterpreter(AI);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000363
Dan Gohmanee051522009-07-16 15:30:09 +0000364 outs() << " Testing after loop extraction:\n";
Chris Lattner0434ba32004-04-05 21:37:38 +0000365 // Clone modules, the tester function will free them.
Rafael Espindola88a8f722015-12-09 00:08:22 +0000366 std::unique_ptr<Module> TOLEBackup =
367 CloneModule(ToOptimizeLoopExtracted.get(), VMap);
Rafael Espindola000bf492015-12-09 00:18:41 +0000368 std::unique_ptr<Module> TNOBackup = CloneModule(ToNotOptimize.get(), VMap);
Hal Finkele9efbf12013-08-02 21:13:42 +0000369
370 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
371 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
372
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000373 Failure = TestFn(BD, std::move(ToOptimizeLoopExtracted),
374 std::move(ToNotOptimize), Error);
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000375 if (!Error.empty())
376 return false;
Hal Finkele9efbf12013-08-02 21:13:42 +0000377
Rafael Espindola88a8f722015-12-09 00:08:22 +0000378 ToOptimizeLoopExtracted = std::move(TOLEBackup);
Rafael Espindola000bf492015-12-09 00:18:41 +0000379 ToNotOptimize = std::move(TNOBackup);
Hal Finkele9efbf12013-08-02 21:13:42 +0000380
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000381 if (!Failure) {
Dan Gohmanee051522009-07-16 15:30:09 +0000382 outs() << "*** Loop extraction masked the problem. Undoing.\n";
Chris Lattnerbcec7872004-03-14 22:08:00 +0000383 // If the program is not still broken, then loop extraction did something
384 // that masked the error. Stop loop extraction now.
Hal Finkele9efbf12013-08-02 21:13:42 +0000385
386 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000387 for (Function *F : MiscompiledFunctions) {
388 MisCompFunctions.emplace_back(F->getName(), F->getFunctionType());
Hal Finkele9efbf12013-08-02 21:13:42 +0000389 }
390
Rafael Espindola434e9562015-12-16 23:16:33 +0000391 if (Linker::linkModules(*ToNotOptimize,
392 std::move(ToOptimizeLoopExtracted)))
Hal Finkele9efbf12013-08-02 21:13:42 +0000393 exit(1);
Hal Finkele9efbf12013-08-02 21:13:42 +0000394
395 MiscompiledFunctions.clear();
396 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
397 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
398
399 assert(NewF && "Function not found??");
400 MiscompiledFunctions.push_back(NewF);
401 }
402
Rafael Espindola000bf492015-12-09 00:18:41 +0000403 BD.setNewProgram(ToNotOptimize.release());
Chris Lattnerbcec7872004-03-14 22:08:00 +0000404 return MadeChange;
405 }
Chris Lattner0434ba32004-04-05 21:37:38 +0000406
Dan Gohmanee051522009-07-16 15:30:09 +0000407 outs() << "*** Loop extraction successful!\n";
Chris Lattnerbcec7872004-03-14 22:08:00 +0000408
Chris Lattner229907c2011-07-18 04:54:35 +0000409 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
Chris Lattnerd3087972004-11-16 06:31:38 +0000410 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
411 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
Reid Spencer5301e7c2007-01-30 20:08:39 +0000412 if (!I->isDeclaration())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000413 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
Chris Lattnerd3087972004-11-16 06:31:38 +0000414
Chris Lattnerbcec7872004-03-14 22:08:00 +0000415 // Okay, great! Now we know that we extracted a loop and that loop
416 // extraction both didn't break the program, and didn't mask the problem.
417 // Replace the current program with the loop extracted version, and try to
418 // extract another loop.
Rafael Espindola434e9562015-12-16 23:16:33 +0000419 if (Linker::linkModules(*ToNotOptimize, std::move(ToOptimizeLoopExtracted)))
Chris Lattnerbcec7872004-03-14 22:08:00 +0000420 exit(1);
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000421
Chris Lattnerb38cc9c2004-03-17 17:42:09 +0000422 // All of the Function*'s in the MiscompiledFunctions list are in the old
Chris Lattnera413b082004-04-02 06:32:17 +0000423 // module. Update this list to include all of the functions in the
424 // optimized and loop extracted module.
425 MiscompiledFunctions.clear();
Chris Lattnerd3087972004-11-16 06:31:38 +0000426 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000427 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000428
Chris Lattnerd3087972004-11-16 06:31:38 +0000429 assert(NewF && "Function not found??");
430 MiscompiledFunctions.push_back(NewF);
Chris Lattnerb38cc9c2004-03-17 17:42:09 +0000431 }
432
Rafael Espindola000bf492015-12-09 00:18:41 +0000433 BD.setNewProgram(ToNotOptimize.release());
Chris Lattnerbcec7872004-03-14 22:08:00 +0000434 MadeChange = true;
435 }
436}
437
Chris Lattnera060b102004-05-11 21:54:13 +0000438namespace {
439 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
440 BugDriver &BD;
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000441 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
442 std::unique_ptr<Module>, std::string &);
Chris Lattnera060b102004-05-11 21:54:13 +0000443 std::vector<Function*> FunctionsBeingTested;
444 public:
445 ReduceMiscompiledBlocks(BugDriver &bd,
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000446 bool (*F)(BugDriver &, std::unique_ptr<Module>,
447 std::unique_ptr<Module>, std::string &),
448 const std::vector<Function *> &Fns)
449 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000450
Craig Toppere56917c2014-03-08 08:27:28 +0000451 TestResult doTest(std::vector<BasicBlock*> &Prefix,
452 std::vector<BasicBlock*> &Suffix,
453 std::string &Error) override {
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000454 if (!Suffix.empty()) {
455 bool Ret = TestFuncs(Suffix, Error);
456 if (!Error.empty())
457 return InternalError;
458 if (Ret)
459 return KeepSuffix;
460 }
461 if (!Prefix.empty()) {
462 bool Ret = TestFuncs(Prefix, Error);
463 if (!Error.empty())
464 return InternalError;
465 if (Ret)
466 return KeepPrefix;
467 }
Chris Lattnera060b102004-05-11 21:54:13 +0000468 return NoFailure;
469 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000470
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000471 bool TestFuncs(const std::vector<BasicBlock*> &BBs, std::string &Error);
Chris Lattnera060b102004-05-11 21:54:13 +0000472 };
Eugene Zelenkoecefe5a2016-02-02 18:20:45 +0000473} // end anonymous namespace
Chris Lattnera060b102004-05-11 21:54:13 +0000474
475/// TestFuncs - Extract all blocks for the miscompiled functions except for the
476/// specified blocks. If the problem still exists, return true.
477///
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000478bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs,
479 std::string &Error) {
Chris Lattnera060b102004-05-11 21:54:13 +0000480 // Test to see if the function is misoptimized if we ONLY run it on the
481 // functions listed in Funcs.
Dan Gohmanee051522009-07-16 15:30:09 +0000482 outs() << "Checking to see if the program is misoptimized when all ";
Chris Lattner6c0c3132004-05-12 16:08:01 +0000483 if (!BBs.empty()) {
Dan Gohmanee051522009-07-16 15:30:09 +0000484 outs() << "but these " << BBs.size() << " blocks are extracted: ";
Chris Lattner6c0c3132004-05-12 16:08:01 +0000485 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
Dan Gohmanee051522009-07-16 15:30:09 +0000486 outs() << BBs[i]->getName() << " ";
487 if (BBs.size() > 10) outs() << "...";
Chris Lattner6c0c3132004-05-12 16:08:01 +0000488 } else {
Dan Gohmanee051522009-07-16 15:30:09 +0000489 outs() << "blocks are extracted.";
Chris Lattner6c0c3132004-05-12 16:08:01 +0000490 }
Dan Gohmanee051522009-07-16 15:30:09 +0000491 outs() << '\n';
Chris Lattnera060b102004-05-11 21:54:13 +0000492
493 // Split the module into the two halves of the program we want.
Rafael Espindola229e38f2010-10-13 01:36:30 +0000494 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000495 Module *Clone = CloneModule(BD.getProgram(), VMap).release();
Rafael Espindola07035e62010-07-29 14:20:59 +0000496 Module *Orig = BD.swapProgramIn(Clone);
497 std::vector<Function*> FuncsOnClone;
498 std::vector<BasicBlock*> BBsOnClone;
499 for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
500 Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
501 FuncsOnClone.push_back(F);
502 }
503 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
504 BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
505 BBsOnClone.push_back(BB);
506 }
507 VMap.clear();
508
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000509 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
510 std::unique_ptr<Module> ToOptimize =
511 SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
Chris Lattnera060b102004-05-11 21:54:13 +0000512
513 // Try the extraction. If it doesn't work, then the block extractor crashed
514 // or something, in which case bugpoint can't chase down this possibility.
Rafael Espindola28b351a2014-08-26 17:19:03 +0000515 if (std::unique_ptr<Module> New =
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000516 BD.extractMappedBlocksFromModule(BBsOnClone, ToOptimize.get())) {
517 bool Ret = TestFn(BD, std::move(New), std::move(ToNotOptimize), Error);
Rafael Espindola07035e62010-07-29 14:20:59 +0000518 delete BD.swapProgramIn(Orig);
519 return Ret;
Chris Lattnera060b102004-05-11 21:54:13 +0000520 }
Rafael Espindola07035e62010-07-29 14:20:59 +0000521 delete BD.swapProgramIn(Orig);
Chris Lattnera060b102004-05-11 21:54:13 +0000522 return false;
523}
524
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000525/// Given a reduced list of functions that still expose the bug, extract as many
526/// basic blocks from the region as possible without obscuring the bug.
Chris Lattnera060b102004-05-11 21:54:13 +0000527///
528static bool ExtractBlocks(BugDriver &BD,
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000529 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
530 std::unique_ptr<Module>,
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000531 std::string &),
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000532 std::vector<Function *> &MiscompiledFunctions,
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000533 std::string &Error) {
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000534 if (BugpointIsInterrupted) return false;
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000535
Chris Lattnera060b102004-05-11 21:54:13 +0000536 std::vector<BasicBlock*> Blocks;
537 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000538 for (BasicBlock &BB : *MiscompiledFunctions[i])
539 Blocks.push_back(&BB);
Chris Lattnera060b102004-05-11 21:54:13 +0000540
541 // Use the list reducer to identify blocks that can be extracted without
542 // obscuring the bug. The Blocks list will end up containing blocks that must
543 // be retained from the original program.
544 unsigned OldSize = Blocks.size();
Chris Lattner6c0c3132004-05-12 16:08:01 +0000545
546 // Check to see if all blocks are extractible first.
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000547 bool Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
548 .TestFuncs(std::vector<BasicBlock*>(), Error);
549 if (!Error.empty())
550 return false;
551 if (Ret) {
Chris Lattner6c0c3132004-05-12 16:08:01 +0000552 Blocks.clear();
553 } else {
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000554 ReduceMiscompiledBlocks(BD, TestFn,
555 MiscompiledFunctions).reduceList(Blocks, Error);
556 if (!Error.empty())
557 return false;
Chris Lattner6c0c3132004-05-12 16:08:01 +0000558 if (Blocks.size() == OldSize)
559 return false;
560 }
Chris Lattnera060b102004-05-11 21:54:13 +0000561
Rafael Espindola229e38f2010-10-13 01:36:30 +0000562 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000563 Module *ProgClone = CloneModule(BD.getProgram(), VMap).release();
Rafael Espindola50102c22015-12-09 00:34:10 +0000564 Module *ToExtract =
565 SplitFunctionsOutOfModule(ProgClone, MiscompiledFunctions, VMap)
566 .release();
Rafael Espindola28b351a2014-08-26 17:19:03 +0000567 std::unique_ptr<Module> Extracted =
568 BD.extractMappedBlocksFromModule(Blocks, ToExtract);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000569 if (!Extracted) {
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000570 // Weird, extraction should have worked.
Dan Gohmand8db3762009-07-15 16:35:29 +0000571 errs() << "Nondeterministic problem extracting blocks??\n";
Chris Lattner49e4a332004-05-12 02:43:24 +0000572 delete ProgClone;
573 delete ToExtract;
574 return false;
575 }
Chris Lattnera060b102004-05-11 21:54:13 +0000576
Chris Lattner49e4a332004-05-12 02:43:24 +0000577 // Otherwise, block extraction succeeded. Link the two program fragments back
578 // together.
579 delete ToExtract;
Chris Lattnera060b102004-05-11 21:54:13 +0000580
Chris Lattner229907c2011-07-18 04:54:35 +0000581 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
Chris Lattnerd3087972004-11-16 06:31:38 +0000582 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
583 I != E; ++I)
Reid Spencer5301e7c2007-01-30 20:08:39 +0000584 if (!I->isDeclaration())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000585 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
Chris Lattnerd3087972004-11-16 06:31:38 +0000586
Rafael Espindola434e9562015-12-16 23:16:33 +0000587 if (Linker::linkModules(*ProgClone, std::move(Extracted)))
Chris Lattner49e4a332004-05-12 02:43:24 +0000588 exit(1);
Chris Lattnera060b102004-05-11 21:54:13 +0000589
Chris Lattner49e4a332004-05-12 02:43:24 +0000590 // Set the new program and delete the old one.
591 BD.setNewProgram(ProgClone);
Chris Lattnera060b102004-05-11 21:54:13 +0000592
Chris Lattner49e4a332004-05-12 02:43:24 +0000593 // Update the list of miscompiled functions.
594 MiscompiledFunctions.clear();
Chris Lattnera060b102004-05-11 21:54:13 +0000595
Chris Lattnerd3087972004-11-16 06:31:38 +0000596 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000597 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
Chris Lattnerd3087972004-11-16 06:31:38 +0000598 assert(NewF && "Function not found??");
599 MiscompiledFunctions.push_back(NewF);
600 }
Chris Lattner49e4a332004-05-12 02:43:24 +0000601
602 return true;
Chris Lattnera060b102004-05-11 21:54:13 +0000603}
604
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000605/// This is a generic driver to narrow down miscompilations, either in an
606/// optimization or a code generator.
Misha Brukman0784a602004-04-21 18:36:43 +0000607///
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000608static std::vector<Function *>
Chris Lattner0434ba32004-04-05 21:37:38 +0000609DebugAMiscompilation(BugDriver &BD,
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000610 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
611 std::unique_ptr<Module>, std::string &),
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000612 std::string &Error) {
Chris Lattner0434ba32004-04-05 21:37:38 +0000613 // Okay, now that we have reduced the list of passes which are causing the
614 // failure, see if we can pin down which functions are being
615 // miscompiled... first build a list of all of the non-external functions in
616 // the program.
617 std::vector<Function*> MiscompiledFunctions;
618 Module *Prog = BD.getProgram();
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000619 for (Function &F : *Prog)
620 if (!F.isDeclaration())
621 MiscompiledFunctions.push_back(&F);
Chris Lattner0434ba32004-04-05 21:37:38 +0000622
623 // Do the reduction...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000624 if (!BugpointIsInterrupted)
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000625 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
626 Error);
Andrew Trick55aeb552011-05-11 16:31:24 +0000627 if (!Error.empty()) {
628 errs() << "\n***Cannot reduce functions: ";
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000629 return MiscompiledFunctions;
Andrew Trick55aeb552011-05-11 16:31:24 +0000630 }
Dan Gohmanee051522009-07-16 15:30:09 +0000631 outs() << "\n*** The following function"
632 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
633 << " being miscompiled: ";
Chris Lattner0434ba32004-04-05 21:37:38 +0000634 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanee051522009-07-16 15:30:09 +0000635 outs() << '\n';
Chris Lattner0434ba32004-04-05 21:37:38 +0000636
637 // See if we can rip any loops out of the miscompiled functions and still
638 // trigger the problem.
Reid Spencer471bcb72006-11-11 19:05:02 +0000639
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000640 if (!BugpointIsInterrupted && !DisableLoopExtraction) {
641 bool Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions, Error);
642 if (!Error.empty())
643 return MiscompiledFunctions;
644 if (Ret) {
645 // Okay, we extracted some loops and the problem still appears. See if
646 // we can eliminate some of the created functions from being candidates.
647 DisambiguateGlobalSymbols(BD.getProgram());
Chris Lattnerdfbb1d12004-04-11 23:52:35 +0000648
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000649 // Do the reduction...
650 if (!BugpointIsInterrupted)
651 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
652 Error);
653 if (!Error.empty())
654 return MiscompiledFunctions;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000655
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000656 outs() << "\n*** The following function"
657 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
658 << " being miscompiled: ";
659 PrintFunctionList(MiscompiledFunctions);
660 outs() << '\n';
661 }
Chris Lattner0434ba32004-04-05 21:37:38 +0000662 }
663
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000664 if (!BugpointIsInterrupted && !DisableBlockExtraction) {
665 bool Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions, Error);
666 if (!Error.empty())
667 return MiscompiledFunctions;
668 if (Ret) {
669 // Okay, we extracted some blocks and the problem still appears. See if
670 // we can eliminate some of the created functions from being candidates.
671 DisambiguateGlobalSymbols(BD.getProgram());
Chris Lattnera060b102004-05-11 21:54:13 +0000672
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000673 // Do the reduction...
674 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
675 Error);
676 if (!Error.empty())
677 return MiscompiledFunctions;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000678
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000679 outs() << "\n*** The following function"
680 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
681 << " being miscompiled: ";
682 PrintFunctionList(MiscompiledFunctions);
683 outs() << '\n';
684 }
Chris Lattnera060b102004-05-11 21:54:13 +0000685 }
686
Chris Lattner0434ba32004-04-05 21:37:38 +0000687 return MiscompiledFunctions;
688}
689
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000690/// This is the predicate function used to check to see if the "Test" portion of
691/// the program is misoptimized. If so, return true. In any case, both module
692/// arguments are deleted.
Misha Brukman0784a602004-04-21 18:36:43 +0000693///
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000694static bool TestOptimizer(BugDriver &BD, std::unique_ptr<Module> Test,
695 std::unique_ptr<Module> Safe, std::string &Error) {
Chris Lattner0434ba32004-04-05 21:37:38 +0000696 // Run the optimization passes on ToOptimize, producing a transformed version
697 // of the functions being tested.
Dan Gohmanee051522009-07-16 15:30:09 +0000698 outs() << " Optimizing functions being tested: ";
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000699 std::unique_ptr<Module> Optimized =
700 BD.runPassesOn(Test.get(), BD.getPassesToRun(),
701 /*AutoDebugCrashes*/ true);
Dan Gohmanee051522009-07-16 15:30:09 +0000702 outs() << "done.\n";
Chris Lattner0434ba32004-04-05 21:37:38 +0000703
Dan Gohmanee051522009-07-16 15:30:09 +0000704 outs() << " Checking to see if the merged program executes correctly: ";
Rafael Espindolae4904602010-07-31 14:34:49 +0000705 bool Broken;
Rafael Espindola7471abd2015-12-09 00:55:05 +0000706 std::unique_ptr<Module> New = testMergedProgram(
707 BD, std::move(Optimized), std::move(Safe), Error, Broken);
Rafael Espindolae4904602010-07-31 14:34:49 +0000708 if (New) {
709 outs() << (Broken ? " nope.\n" : " yup.\n");
710 // Delete the original and set the new program.
Rafael Espindola7471abd2015-12-09 00:55:05 +0000711 delete BD.swapProgramIn(New.release());
Rafael Espindolae4904602010-07-31 14:34:49 +0000712 }
Chris Lattner0434ba32004-04-05 21:37:38 +0000713 return Broken;
714}
715
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000716/// debugMiscompilation - This method is used when the passes selected are not
717/// crashing, but the generated output is semantically different from the
718/// input.
719///
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000720void BugDriver::debugMiscompilation(std::string *Error) {
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000721 // Make sure something was miscompiled...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000722 if (!BugpointIsInterrupted)
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000723 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun, *Error)) {
724 if (Error->empty())
725 errs() << "*** Optimized program matches reference output! No problem"
726 << " detected...\nbugpoint can't help you with your problem!\n";
727 return;
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000728 }
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000729
Dan Gohmanee051522009-07-16 15:30:09 +0000730 outs() << "\n*** Found miscompiling pass"
731 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
732 << getPassesString(getPassesToRun()) << '\n';
Rafael Espindola594994a2010-07-28 18:12:30 +0000733 EmitProgressBitcode(Program, "passinput");
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000734
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000735 std::vector<Function *> MiscompiledFunctions =
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000736 DebugAMiscompilation(*this, TestOptimizer, *Error);
737 if (!Error->empty())
738 return;
Chris Lattnerbcec7872004-03-14 22:08:00 +0000739
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000740 // Output a bunch of bitcode files for the user...
Dan Gohmanee051522009-07-16 15:30:09 +0000741 outs() << "Outputting reduced bitcode files which expose the problem:\n";
Rafael Espindola229e38f2010-10-13 01:36:30 +0000742 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000743 Module *ToNotOptimize = CloneModule(getProgram(), VMap).release();
Rafael Espindola50102c22015-12-09 00:34:10 +0000744 Module *ToOptimize =
745 SplitFunctionsOutOfModule(ToNotOptimize, MiscompiledFunctions, VMap)
746 .release();
Chris Lattner567543f2004-03-14 19:27:19 +0000747
Dan Gohmanee051522009-07-16 15:30:09 +0000748 outs() << " Non-optimized portion: ";
Rafael Espindola594994a2010-07-28 18:12:30 +0000749 EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true);
750 delete ToNotOptimize; // Delete hacked module.
Misha Brukman650ba8e2005-04-22 00:00:37 +0000751
Dan Gohmanee051522009-07-16 15:30:09 +0000752 outs() << " Portion that is input to optimizer: ";
Rafael Espindola594994a2010-07-28 18:12:30 +0000753 EmitProgressBitcode(ToOptimize, "tooptimize");
754 delete ToOptimize; // Delete hacked module.
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000755}
Brian Gaeke960707c2003-11-11 22:41:34 +0000756
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000757/// Get the specified modules ready for code generator testing.
Misha Brukman0784a602004-04-21 18:36:43 +0000758///
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000759static void CleanupAndPrepareModules(BugDriver &BD,
760 std::unique_ptr<Module> &Test,
Chris Lattnerbf791612004-04-05 22:58:16 +0000761 Module *Safe) {
762 // Clean up the modules, removing extra cruft that we don't need anymore...
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000763 Test = BD.performFinalCleanups(Test.get());
Chris Lattnerbf791612004-04-05 22:58:16 +0000764
765 // If we are executing the JIT, we have several nasty issues to take care of.
766 if (!BD.isExecutingJIT()) return;
767
768 // First, if the main function is in the Safe module, we must add a stub to
769 // the Test module to call into it. Thus, we create a new function `main'
770 // which just calls the old one.
Reid Spencer1241d6d2007-02-05 21:19:13 +0000771 if (Function *oldMain = Safe->getFunction("main"))
Reid Spencer5301e7c2007-01-30 20:08:39 +0000772 if (!oldMain->isDeclaration()) {
Chris Lattnerbf791612004-04-05 22:58:16 +0000773 // Rename it
774 oldMain->setName("llvm_bugpoint_old_main");
775 // Create a NEW `main' function with same type in the test module.
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000776 Function *newMain =
777 Function::Create(oldMain->getFunctionType(),
778 GlobalValue::ExternalLinkage, "main", Test.get());
Chris Lattnerbf791612004-04-05 22:58:16 +0000779 // Create an `oldmain' prototype in the test module, which will
780 // corresponds to the real main function in the same module.
Gabor Greife9ecc682008-04-06 20:25:17 +0000781 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
782 GlobalValue::ExternalLinkage,
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000783 oldMain->getName(), Test.get());
Chris Lattnerbf791612004-04-05 22:58:16 +0000784 // Set up and remember the argument list for the main function.
785 std::vector<Value*> args;
Alkis Evlogimenosa67bafa2005-03-15 07:02:26 +0000786 for (Function::arg_iterator
787 I = newMain->arg_begin(), E = newMain->arg_end(),
788 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
Owen Anderson7629b712008-04-14 17:38:21 +0000789 I->setName(OI->getName()); // Copy argument names from oldMain
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000790 args.push_back(&*I);
Chris Lattnerbf791612004-04-05 22:58:16 +0000791 }
792
793 // Call the old main function and return its result
Owen Anderson55f1c092009-08-13 21:58:54 +0000794 BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
Jay Foad5bd375a2011-07-15 08:37:34 +0000795 CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000796
Chris Lattnerbf791612004-04-05 22:58:16 +0000797 // If the type of old function wasn't void, return value of call
Owen Anderson55f1c092009-08-13 21:58:54 +0000798 ReturnInst::Create(Safe->getContext(), call, BB);
Chris Lattnerbf791612004-04-05 22:58:16 +0000799 }
800
801 // The second nasty issue we must deal with in the JIT is that the Safe
802 // module cannot directly reference any functions defined in the test
803 // module. Instead, we use a JIT API call to dynamically resolve the
804 // symbol.
Misha Brukman650ba8e2005-04-22 00:00:37 +0000805
Chris Lattnerbf791612004-04-05 22:58:16 +0000806 // Add the resolver to the Safe module.
807 // Prototype: void *getPointerToNamedFunction(const char* Name)
Chris Lattner7b864c02007-01-07 08:13:39 +0000808 Constant *resolverFunc =
Chris Lattnerbf791612004-04-05 22:58:16 +0000809 Safe->getOrInsertFunction("getPointerToNamedFunction",
Duncan Sands9ed7b162009-10-06 15:40:36 +0000810 Type::getInt8PtrTy(Safe->getContext()),
811 Type::getInt8PtrTy(Safe->getContext()),
Craig Toppere6cb63e2014-04-25 04:24:47 +0000812 (Type *)nullptr);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000813
Chris Lattnerbf791612004-04-05 22:58:16 +0000814 // Use the function we just added to get addresses of functions we need.
Misha Brukman83018642004-04-19 01:12:01 +0000815 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
Reid Spencer5301e7c2007-01-30 20:08:39 +0000816 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
Duncan Sands38ef3a82007-12-03 20:06:50 +0000817 !F->isIntrinsic() /* ignore intrinsics */) {
Reid Spencer1241d6d2007-02-05 21:19:13 +0000818 Function *TestFn = Test->getFunction(F->getName());
Chris Lattnerbf791612004-04-05 22:58:16 +0000819
820 // Don't forward functions which are external in the test module too.
Reid Spencer5301e7c2007-01-30 20:08:39 +0000821 if (TestFn && !TestFn->isDeclaration()) {
Chris Lattnerbf791612004-04-05 22:58:16 +0000822 // 1. Add a string constant with its name to the global file
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000823 Constant *InitArray =
824 ConstantDataArray::getString(F->getContext(), F->getName());
Chris Lattnerbf791612004-04-05 22:58:16 +0000825 GlobalVariable *funcName =
Owen Andersonb17f3292009-07-08 19:03:57 +0000826 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
Misha Brukman650ba8e2005-04-22 00:00:37 +0000827 GlobalValue::InternalLinkage, InitArray,
Owen Andersonb17f3292009-07-08 19:03:57 +0000828 F->getName() + "_name");
Chris Lattnerbf791612004-04-05 22:58:16 +0000829
830 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
831 // sbyte* so it matches the signature of the resolver function.
832
833 // GetElementPtr *funcName, ulong 0, ulong 0
Owen Anderson55f1c092009-08-13 21:58:54 +0000834 std::vector<Constant*> GEPargs(2,
835 Constant::getNullValue(Type::getInt32Ty(F->getContext())));
David Blaikie4a2e73b2015-04-02 18:55:32 +0000836 Value *GEP = ConstantExpr::getGetElementPtr(InitArray->getType(),
837 funcName, GEPargs);
Chris Lattnerbf791612004-04-05 22:58:16 +0000838 std::vector<Value*> ResolverArgs;
839 ResolverArgs.push_back(GEP);
840
Misha Brukmance89b392004-04-19 03:36:47 +0000841 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
842 // function that dynamically resolves the calls to F via our JIT API
Chris Lattner986675c2005-07-12 01:00:32 +0000843 if (!F->use_empty()) {
844 // Create a new global to hold the cached function pointer.
Owen Andersonb292b8c2009-07-30 23:03:37 +0000845 Constant *NullPtr = ConstantPointerNull::get(F->getType());
Chris Lattner986675c2005-07-12 01:00:32 +0000846 GlobalVariable *Cache =
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000847 new GlobalVariable(*F->getParent(), F->getType(),
Owen Andersonb17f3292009-07-08 19:03:57 +0000848 false, GlobalValue::InternalLinkage,
849 NullPtr,F->getName()+".fpcache");
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000850
Misha Brukmance89b392004-04-19 03:36:47 +0000851 // Construct a new stub function that will re-route calls to F
Chris Lattner229907c2011-07-18 04:54:35 +0000852 FunctionType *FuncTy = F->getFunctionType();
Gabor Greife9ecc682008-04-06 20:25:17 +0000853 Function *FuncWrapper = Function::Create(FuncTy,
854 GlobalValue::InternalLinkage,
855 F->getName() + "_wrapper",
856 F->getParent());
Owen Anderson55f1c092009-08-13 21:58:54 +0000857 BasicBlock *EntryBB = BasicBlock::Create(F->getContext(),
858 "entry", FuncWrapper);
859 BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
860 "usecache", FuncWrapper);
861 BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
862 "lookupfp", FuncWrapper);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000863
Chris Lattner986675c2005-07-12 01:00:32 +0000864 // Check to see if we already looked up the value.
865 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000866 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
867 NullPtr, "isNull");
Gabor Greife9ecc682008-04-06 20:25:17 +0000868 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000869
Misha Brukmance89b392004-04-19 03:36:47 +0000870 // Resolve the call to function F via the JIT API:
871 //
872 // call resolver(GetElementPtr...)
Gabor Greif697e94c2008-05-15 10:04:30 +0000873 CallInst *Resolver =
Jay Foad5bd375a2011-07-15 08:37:34 +0000874 CallInst::Create(resolverFunc, ResolverArgs, "resolver", LookupBB);
Gabor Greif697e94c2008-05-15 10:04:30 +0000875
876 // Cast the result from the resolver to correctly-typed function.
877 CastInst *CastedResolver =
878 new BitCastInst(Resolver,
Owen Anderson4056ca92009-07-29 22:17:13 +0000879 PointerType::getUnqual(F->getFunctionType()),
Gabor Greif697e94c2008-05-15 10:04:30 +0000880 "resolverCast", LookupBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000881
Chris Lattner986675c2005-07-12 01:00:32 +0000882 // Save the value in our cache.
883 new StoreInst(CastedResolver, Cache, LookupBB);
Gabor Greife9ecc682008-04-06 20:25:17 +0000884 BranchInst::Create(DoCallBB, LookupBB);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000885
Jay Foad52131342011-03-30 11:28:46 +0000886 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(), 2,
Gabor Greif697e94c2008-05-15 10:04:30 +0000887 "fp", DoCallBB);
Chris Lattner986675c2005-07-12 01:00:32 +0000888 FuncPtr->addIncoming(CastedResolver, LookupBB);
889 FuncPtr->addIncoming(CachedVal, EntryBB);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000890
Chris Lattner986675c2005-07-12 01:00:32 +0000891 // Save the argument list.
Misha Brukman83018642004-04-19 01:12:01 +0000892 std::vector<Value*> Args;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000893 for (Argument &A : FuncWrapper->args())
894 Args.push_back(&A);
Misha Brukman83018642004-04-19 01:12:01 +0000895
896 // Pass on the arguments to the real function, return its result
Dan Gohman34a22492010-06-07 20:19:26 +0000897 if (F->getReturnType()->isVoidTy()) {
Jay Foad5bd375a2011-07-15 08:37:34 +0000898 CallInst::Create(FuncPtr, Args, "", DoCallBB);
Owen Anderson55f1c092009-08-13 21:58:54 +0000899 ReturnInst::Create(F->getContext(), DoCallBB);
Misha Brukman83018642004-04-19 01:12:01 +0000900 } else {
Jay Foad5bd375a2011-07-15 08:37:34 +0000901 CallInst *Call = CallInst::Create(FuncPtr, Args,
Gabor Greife9ecc682008-04-06 20:25:17 +0000902 "retval", DoCallBB);
Owen Anderson55f1c092009-08-13 21:58:54 +0000903 ReturnInst::Create(F->getContext(),Call, DoCallBB);
Misha Brukman83018642004-04-19 01:12:01 +0000904 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000905
Misha Brukmance89b392004-04-19 03:36:47 +0000906 // Use the wrapper function instead of the old function
907 F->replaceAllUsesWith(FuncWrapper);
Misha Brukman83018642004-04-19 01:12:01 +0000908 }
Chris Lattnerbf791612004-04-05 22:58:16 +0000909 }
910 }
911 }
912
913 if (verifyModule(*Test) || verifyModule(*Safe)) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000914 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
Chris Lattnerbf791612004-04-05 22:58:16 +0000915 abort();
916 }
917}
918
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000919/// This is the predicate function used to check to see if the "Test" portion of
920/// the program is miscompiled by the code generator under test. If so, return
921/// true. In any case, both module arguments are deleted.
Misha Brukman0784a602004-04-21 18:36:43 +0000922///
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000923static bool TestCodeGenerator(BugDriver &BD, std::unique_ptr<Module> Test,
924 std::unique_ptr<Module> Safe,
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000925 std::string &Error) {
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000926 CleanupAndPrepareModules(BD, Test, Safe.get());
Chris Lattnerbf791612004-04-05 22:58:16 +0000927
Rafael Espindola302c0da2013-06-18 15:29:32 +0000928 SmallString<128> TestModuleBC;
929 int TestModuleFD;
Rafael Espindola4453e42942014-06-13 03:07:50 +0000930 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
931 TestModuleFD, TestModuleBC);
Rafael Espindola302c0da2013-06-18 15:29:32 +0000932 if (EC) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000933 errs() << BD.getToolName() << "Error making unique filename: "
Rafael Espindola302c0da2013-06-18 15:29:32 +0000934 << EC.message() << "\n";
Reid Spencere4ca7222006-08-23 20:34:57 +0000935 exit(1);
936 }
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000937 if (BD.writeProgramToFile(TestModuleBC.str(), TestModuleFD, Test.get())) {
Chris Lattnerc521f542009-08-23 22:45:37 +0000938 errs() << "Error writing bitcode to `" << TestModuleBC.str()
939 << "'\nExiting.";
Chris Lattnerbf791612004-04-05 22:58:16 +0000940 exit(1);
941 }
Chris Lattnerbf791612004-04-05 22:58:16 +0000942
Michael J. Spencerc60223e2011-03-31 13:04:19 +0000943 FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
Rafael Espindola720f49e2010-06-21 02:17:36 +0000944
Chris Lattnerbf791612004-04-05 22:58:16 +0000945 // Make the shared library
Rafael Espindola302c0da2013-06-18 15:29:32 +0000946 SmallString<128> SafeModuleBC;
947 int SafeModuleFD;
Rafael Espindola155cf0f2013-07-05 20:14:52 +0000948 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
949 SafeModuleBC);
Rafael Espindola302c0da2013-06-18 15:29:32 +0000950 if (EC) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000951 errs() << BD.getToolName() << "Error making unique filename: "
Rafael Espindola302c0da2013-06-18 15:29:32 +0000952 << EC.message() << "\n";
Reid Spencere4ca7222006-08-23 20:34:57 +0000953 exit(1);
954 }
Chris Lattnerbf791612004-04-05 22:58:16 +0000955
Rafael Espindolabc12cbc2015-12-09 00:51:06 +0000956 if (BD.writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, Safe.get())) {
Yaron Keren09fb7c62015-03-10 07:33:23 +0000957 errs() << "Error writing bitcode to `" << SafeModuleBC
Chris Lattnerc521f542009-08-23 22:45:37 +0000958 << "'\nExiting.";
Chris Lattnerbf791612004-04-05 22:58:16 +0000959 exit(1);
960 }
Rafael Espindola720f49e2010-06-21 02:17:36 +0000961
Michael J. Spencerc60223e2011-03-31 13:04:19 +0000962 FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
Rafael Espindola720f49e2010-06-21 02:17:36 +0000963
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000964 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str(), Error);
965 if (!Error.empty())
Benjamin Kramer1f336da2010-04-12 12:22:19 +0000966 return false;
Chris Lattnerbf791612004-04-05 22:58:16 +0000967
Michael J. Spencerc60223e2011-03-31 13:04:19 +0000968 FileRemover SharedObjectRemover(SharedObject, !SaveTemps);
Rafael Espindola720f49e2010-06-21 02:17:36 +0000969
Chris Lattnerbf791612004-04-05 22:58:16 +0000970 // Run the code generator on the `Test' code, loading the shared library.
971 // The function returns whether or not the new output differs from reference.
Rafael Espindolac89b1ef2010-07-30 14:19:00 +0000972 bool Result = BD.diffProgram(BD.getProgram(), TestModuleBC.str(),
973 SharedObject, false, &Error);
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000974 if (!Error.empty())
975 return false;
Chris Lattnerbf791612004-04-05 22:58:16 +0000976
977 if (Result)
Dan Gohmand8db3762009-07-15 16:35:29 +0000978 errs() << ": still failing!\n";
Chris Lattnerbf791612004-04-05 22:58:16 +0000979 else
Dan Gohmand8db3762009-07-15 16:35:29 +0000980 errs() << ": didn't fail.\n";
Chris Lattnerbf791612004-04-05 22:58:16 +0000981
982 return Result;
983}
984
Misha Brukman0784a602004-04-21 18:36:43 +0000985/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
986///
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000987bool BugDriver::debugCodeGenerator(std::string *Error) {
Dan Gohman414cf502008-12-08 04:02:47 +0000988 if ((void*)SafeInterpreter == (void*)Interpreter) {
Rafael Espindolac89b1ef2010-07-30 14:19:00 +0000989 std::string Result = executeProgramSafely(Program, "bugpoint.safe.out",
990 Error);
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000991 if (Error->empty()) {
992 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
993 << "the reference diff. This may be due to a\n front-end "
994 << "bug or a bug in the original program, but this can also "
995 << "happen if bugpoint isn't running the program with the "
996 << "right flags or input.\n I left the result of executing "
997 << "the program with the \"safe\" backend in this file for "
998 << "you: '"
999 << Result << "'.\n";
1000 }
Chris Lattnerbf791612004-04-05 22:58:16 +00001001 return true;
1002 }
1003
1004 DisambiguateGlobalSymbols(Program);
1005
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001006 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator,
1007 *Error);
1008 if (!Error->empty())
1009 return true;
Chris Lattnerbf791612004-04-05 22:58:16 +00001010
1011 // Split the module into the two halves of the program we want.
Rafael Espindola229e38f2010-10-13 01:36:30 +00001012 ValueToValueMapTy VMap;
Rafael Espindolabc12cbc2015-12-09 00:51:06 +00001013 std::unique_ptr<Module> ToNotCodeGen = CloneModule(getProgram(), VMap);
1014 std::unique_ptr<Module> ToCodeGen =
1015 SplitFunctionsOutOfModule(ToNotCodeGen.get(), Funcs, VMap);
Chris Lattnerbf791612004-04-05 22:58:16 +00001016
1017 // Condition the modules
Rafael Espindolabc12cbc2015-12-09 00:51:06 +00001018 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen.get());
Chris Lattnerbf791612004-04-05 22:58:16 +00001019
Rafael Espindola302c0da2013-06-18 15:29:32 +00001020 SmallString<128> TestModuleBC;
1021 int TestModuleFD;
Rafael Espindola4453e42942014-06-13 03:07:50 +00001022 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
1023 TestModuleFD, TestModuleBC);
Rafael Espindola302c0da2013-06-18 15:29:32 +00001024 if (EC) {
Dan Gohmand8db3762009-07-15 16:35:29 +00001025 errs() << getToolName() << "Error making unique filename: "
Rafael Espindola302c0da2013-06-18 15:29:32 +00001026 << EC.message() << "\n";
Reid Spencere4ca7222006-08-23 20:34:57 +00001027 exit(1);
1028 }
Reid Spencer30067f12004-12-15 01:53:08 +00001029
Rafael Espindolabc12cbc2015-12-09 00:51:06 +00001030 if (writeProgramToFile(TestModuleBC.str(), TestModuleFD, ToCodeGen.get())) {
Yaron Keren09fb7c62015-03-10 07:33:23 +00001031 errs() << "Error writing bitcode to `" << TestModuleBC
Chris Lattnerc521f542009-08-23 22:45:37 +00001032 << "'\nExiting.";
Chris Lattnerbf791612004-04-05 22:58:16 +00001033 exit(1);
1034 }
Chris Lattnerbf791612004-04-05 22:58:16 +00001035
1036 // Make the shared library
Rafael Espindola302c0da2013-06-18 15:29:32 +00001037 SmallString<128> SafeModuleBC;
1038 int SafeModuleFD;
Rafael Espindola155cf0f2013-07-05 20:14:52 +00001039 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
1040 SafeModuleBC);
Rafael Espindola302c0da2013-06-18 15:29:32 +00001041 if (EC) {
Dan Gohmand8db3762009-07-15 16:35:29 +00001042 errs() << getToolName() << "Error making unique filename: "
Rafael Espindola302c0da2013-06-18 15:29:32 +00001043 << EC.message() << "\n";
Reid Spencere4ca7222006-08-23 20:34:57 +00001044 exit(1);
1045 }
Reid Spencer30067f12004-12-15 01:53:08 +00001046
Rafael Espindolabc12cbc2015-12-09 00:51:06 +00001047 if (writeProgramToFile(SafeModuleBC.str(), SafeModuleFD,
1048 ToNotCodeGen.get())) {
Yaron Keren09fb7c62015-03-10 07:33:23 +00001049 errs() << "Error writing bitcode to `" << SafeModuleBC
Chris Lattnerc521f542009-08-23 22:45:37 +00001050 << "'\nExiting.";
Chris Lattnerbf791612004-04-05 22:58:16 +00001051 exit(1);
1052 }
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001053 std::string SharedObject = compileSharedObject(SafeModuleBC.str(), *Error);
1054 if (!Error->empty())
1055 return true;
Chris Lattnerbf791612004-04-05 22:58:16 +00001056
Dan Gohmanee051522009-07-16 15:30:09 +00001057 outs() << "You can reproduce the problem with the command line: \n";
Chris Lattnerbf791612004-04-05 22:58:16 +00001058 if (isExecutingJIT()) {
Yaron Keren09fb7c62015-03-10 07:33:23 +00001059 outs() << " lli -load " << SharedObject << " " << TestModuleBC;
Chris Lattnerbf791612004-04-05 22:58:16 +00001060 } else {
Yaron Keren09fb7c62015-03-10 07:33:23 +00001061 outs() << " llc " << TestModuleBC << " -o " << TestModuleBC
Chris Lattnerc521f542009-08-23 22:45:37 +00001062 << ".s\n";
Davide Italianoab256212015-10-14 20:29:54 +00001063 outs() << " cc " << SharedObject << " " << TestModuleBC.str()
Yaron Keren09fb7c62015-03-10 07:33:23 +00001064 << ".s -o " << TestModuleBC << ".exe";
Chris Lattnerea2fa462005-01-15 00:07:19 +00001065#if defined (HAVE_LINK_R)
Dan Gohmanee051522009-07-16 15:30:09 +00001066 outs() << " -Wl,-R.";
Chris Lattnerea2fa462005-01-15 00:07:19 +00001067#endif
Dan Gohmanee051522009-07-16 15:30:09 +00001068 outs() << "\n";
Yaron Keren09fb7c62015-03-10 07:33:23 +00001069 outs() << " " << TestModuleBC << ".exe";
Chris Lattnerbf791612004-04-05 22:58:16 +00001070 }
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001071 for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
Dan Gohmanee051522009-07-16 15:30:09 +00001072 outs() << " " << InputArgv[i];
1073 outs() << '\n';
1074 outs() << "The shared object was created with:\n llc -march=c "
Chris Lattnerc521f542009-08-23 22:45:37 +00001075 << SafeModuleBC.str() << " -o temporary.c\n"
Davide Italianoab256212015-10-14 20:29:54 +00001076 << " cc -xc temporary.c -O2 -o " << SharedObject;
Daniel Dunbar8575a602009-08-18 03:35:57 +00001077 if (TargetTriple.getArch() == Triple::sparc)
1078 outs() << " -G"; // Compile a shared library, `-G' for Sparc
1079 else
1080 outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
1081
1082 outs() << " -fno-strict-aliasing\n";
Chris Lattnerbf791612004-04-05 22:58:16 +00001083
1084 return false;
1085}