blob: db6dd54a0879a0e0dc5e1bde8db8ffa8abf15682 [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"
Rafael Espindolaf49a38f2015-12-04 22:08:53 +000021#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/Instructions.h"
23#include "llvm/IR/Module.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000024#include "llvm/IR/Verifier.h"
Chandler Carruth6cc07df2014-03-06 03:42:23 +000025#include "llvm/Linker/Linker.h"
Misha Brukman0c2305b2003-08-07 21:19:30 +000026#include "llvm/Pass.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000027#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/FileUtilities.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000029#include "llvm/Transforms/Utils/Cloning.h"
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;
35}
36
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 };
56}
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;
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000180 bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000181 public:
Chris Lattner0434ba32004-04-05 21:37:38 +0000182 ReduceMiscompilingFunctions(BugDriver &bd,
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000183 bool (*F)(BugDriver &, Module *, Module *,
184 std::string &))
Chris Lattner0434ba32004-04-05 21:37:38 +0000185 : BD(bd), TestFn(F) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000186
Craig Toppere56917c2014-03-08 08:27:28 +0000187 TestResult doTest(std::vector<Function*> &Prefix,
188 std::vector<Function*> &Suffix,
189 std::string &Error) override {
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000190 if (!Suffix.empty()) {
191 bool Ret = TestFuncs(Suffix, Error);
192 if (!Error.empty())
193 return InternalError;
194 if (Ret)
195 return KeepSuffix;
196 }
197 if (!Prefix.empty()) {
198 bool Ret = TestFuncs(Prefix, Error);
199 if (!Error.empty())
200 return InternalError;
201 if (Ret)
202 return KeepPrefix;
203 }
Chris Lattner2f1aa112004-01-14 03:38:37 +0000204 return NoFailure;
205 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000206
Rafael Espindola235457c2010-07-26 00:07:51 +0000207 bool TestFuncs(const std::vector<Function*> &Prefix, std::string &Error);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000208 };
209}
Chris Lattner16a41312003-04-24 17:02:17 +0000210
Rafael Espindolaf49a38f2015-12-04 22:08:53 +0000211static void diagnosticHandler(const DiagnosticInfo &DI) {
212 DiagnosticPrinterRawOStream DP(errs());
213 DI.print(DP);
214 errs() << '\n';
215 if (DI.getSeverity() == DS_Error)
216 exit(1);
217}
218
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000219/// TestMergedProgram - Given two modules, link them together and run the
Rafael Espindolae4904602010-07-31 14:34:49 +0000220/// program, checking to see if the program matches the diff. If there is
221/// an error, return NULL. If not, return the merged module. The Broken argument
222/// will be set to true if the output is different. If the DeleteInputs
223/// argument is set to true then this function deletes both input
224/// modules before it returns.
Misha Brukman0784a602004-04-21 18:36:43 +0000225///
Rafael Espindolae4904602010-07-31 14:34:49 +0000226static Module *TestMergedProgram(const BugDriver &BD, Module *M1, Module *M2,
227 bool DeleteInputs, std::string &Error,
228 bool &Broken) {
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000229 // Link the two portions of the program back to together.
Chris Lattnerd3087972004-11-16 06:31:38 +0000230 if (!DeleteInputs) {
Rafael Espindolacab951d2015-12-08 23:57:17 +0000231 M1 = CloneModule(M1).release();
232 M2 = CloneModule(M2).release();
Chris Lattnerd3087972004-11-16 06:31:38 +0000233 }
Rafael Espindolaf49a38f2015-12-04 22:08:53 +0000234 if (Linker::linkModules(*M1, *M2, diagnosticHandler))
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000235 exit(1);
Chris Lattnerd3087972004-11-16 06:31:38 +0000236 delete M2; // We are done with this module.
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000237
Rafael Espindolae4904602010-07-31 14:34:49 +0000238 // Execute the program.
239 Broken = BD.diffProgram(M1, "", "", false, &Error);
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000240 if (!Error.empty()) {
Rafael Espindolac89b1ef2010-07-30 14:19:00 +0000241 // Delete the linked module
242 delete M1;
Craig Toppere6cb63e2014-04-25 04:24:47 +0000243 return nullptr;
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000244 }
Rafael Espindolae4904602010-07-31 14:34:49 +0000245 return M1;
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000246}
247
Misha Brukman0784a602004-04-21 18:36:43 +0000248/// TestFuncs - split functions in a Module into two groups: those that are
249/// under consideration for miscompilation vs. those that are not, and test
250/// accordingly. Each group of functions becomes a separate Module.
251///
Rafael Espindola235457c2010-07-26 00:07:51 +0000252bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*> &Funcs,
253 std::string &Error) {
Chris Lattner16a41312003-04-24 17:02:17 +0000254 // Test to see if the function is misoptimized if we ONLY run it on the
255 // functions listed in Funcs.
Dan Gohmanee051522009-07-16 15:30:09 +0000256 outs() << "Checking to see if the program is misoptimized when "
257 << (Funcs.size()==1 ? "this function is" : "these functions are")
258 << " run through the pass"
259 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000260 PrintFunctionList(Funcs);
Dan Gohmanee051522009-07-16 15:30:09 +0000261 outs() << '\n';
Chris Lattner16a41312003-04-24 17:02:17 +0000262
Rafael Espindola235457c2010-07-26 00:07:51 +0000263 // Create a clone for two reasons:
264 // * If the optimization passes delete any function, the deleted function
265 // will be in the clone and Funcs will still point to valid memory
266 // * If the optimization passes use interprocedural information to break
267 // a function, we want to continue with the original function. Otherwise
268 // we can conclude that a function triggers the bug when in fact one
269 // needs a larger set of original functions to do so.
Rafael Espindola229e38f2010-10-13 01:36:30 +0000270 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000271 Module *Clone = CloneModule(BD.getProgram(), VMap).release();
Rafael Espindola235457c2010-07-26 00:07:51 +0000272 Module *Orig = BD.swapProgramIn(Clone);
273
274 std::vector<Function*> FuncsOnClone;
275 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
276 Function *F = cast<Function>(VMap[Funcs[i]]);
277 FuncsOnClone.push_back(F);
278 }
279
280 // Split the module into the two halves of the program we want.
281 VMap.clear();
Rafael Espindolacab951d2015-12-08 23:57:17 +0000282 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap).release();
Rafael Espindola235457c2010-07-26 00:07:51 +0000283 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, FuncsOnClone,
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000284 VMap);
Chris Lattner16a41312003-04-24 17:02:17 +0000285
Nick Lewyckyc6243022007-11-14 06:47:06 +0000286 // Run the predicate, note that the predicate will delete both input modules.
Rafael Espindola235457c2010-07-26 00:07:51 +0000287 bool Broken = TestFn(BD, ToOptimize, ToNotOptimize, Error);
288
289 delete BD.swapProgramIn(Orig);
290
291 return Broken;
Chris Lattner16a41312003-04-24 17:02:17 +0000292}
293
Chris Lattnerdc2cb5a2010-01-16 21:34:01 +0000294/// DisambiguateGlobalSymbols - Give anonymous global values names.
Misha Brukman0784a602004-04-21 18:36:43 +0000295///
Chris Lattnerdfbb1d12004-04-11 23:52:35 +0000296static void DisambiguateGlobalSymbols(Module *M) {
Chris Lattner34d26c32006-05-04 23:35:31 +0000297 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
Chris Lattner6a941f02010-01-16 21:34:51 +0000298 I != E; ++I)
Chris Lattnerdc2cb5a2010-01-16 21:34:01 +0000299 if (!I->hasName())
300 I->setName("anon_global");
Chris Lattner6a941f02010-01-16 21:34:51 +0000301 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
Chris Lattnerdc2cb5a2010-01-16 21:34:01 +0000302 if (!I->hasName())
303 I->setName("anon_fn");
Chris Lattnerdfbb1d12004-04-11 23:52:35 +0000304}
305
Chris Lattnerbcec7872004-03-14 22:08:00 +0000306/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
307/// check to see if we can extract the loops in the region without obscuring the
308/// bug. If so, it reduces the amount of code identified.
Misha Brukman0784a602004-04-21 18:36:43 +0000309///
Chris Lattner0434ba32004-04-05 21:37:38 +0000310static bool ExtractLoops(BugDriver &BD,
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000311 bool (*TestFn)(BugDriver &, Module *, Module *,
312 std::string &),
313 std::vector<Function*> &MiscompiledFunctions,
314 std::string &Error) {
Chris Lattnerbcec7872004-03-14 22:08:00 +0000315 bool MadeChange = false;
316 while (1) {
Chris Lattnerbd615f52005-08-02 23:25:56 +0000317 if (BugpointIsInterrupted) return MadeChange;
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000318
Rafael Espindola229e38f2010-10-13 01:36:30 +0000319 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000320 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap).release();
Chris Lattnerbcec7872004-03-14 22:08:00 +0000321 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohman956ae9d2009-04-22 15:57:18 +0000322 MiscompiledFunctions,
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000323 VMap);
Rafael Espindola28b351a2014-08-26 17:19:03 +0000324 Module *ToOptimizeLoopExtracted = BD.extractLoop(ToOptimize).release();
Chris Lattnerbcec7872004-03-14 22:08:00 +0000325 if (!ToOptimizeLoopExtracted) {
326 // If the loop extractor crashed or if there were no extractible loops,
327 // then this chapter of our odyssey is over with.
328 delete ToNotOptimize;
329 delete ToOptimize;
330 return MadeChange;
331 }
332
Dan Gohmand8db3762009-07-15 16:35:29 +0000333 errs() << "Extracted a loop from the breaking portion of the program.\n";
Chris Lattnerbcec7872004-03-14 22:08:00 +0000334
335 // Bugpoint is intentionally not very trusting of LLVM transformations. In
336 // particular, we're not going to assume that the loop extractor works, so
337 // we're going to test the newly loop extracted program to make sure nothing
338 // has broken. If something broke, then we'll inform the user and stop
339 // extraction.
Dan Gohman414cf502008-12-08 04:02:47 +0000340 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
Rafael Espindolae4904602010-07-31 14:34:49 +0000341 bool Failure;
Rafael Espindola28b351a2014-08-26 17:19:03 +0000342 Module *New = TestMergedProgram(BD, ToOptimizeLoopExtracted,
343 ToNotOptimize, false, Error, Failure);
Rafael Espindolae4904602010-07-31 14:34:49 +0000344 if (!New)
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000345 return false;
Hal Finkele9efbf12013-08-02 21:13:42 +0000346
Rafael Espindolae4904602010-07-31 14:34:49 +0000347 // Delete the original and set the new program.
Hal Finkele9efbf12013-08-02 21:13:42 +0000348 Module *Old = BD.swapProgramIn(New);
349 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
350 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
351 delete Old;
352
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000353 if (Failure) {
Chris Lattnerbf791612004-04-05 22:58:16 +0000354 BD.switchToInterpreter(AI);
355
Chris Lattnerbcec7872004-03-14 22:08:00 +0000356 // Merged program doesn't work anymore!
Dan Gohmand8db3762009-07-15 16:35:29 +0000357 errs() << " *** ERROR: Loop extraction broke the program. :("
358 << " Please report a bug!\n";
359 errs() << " Continuing on with un-loop-extracted version.\n";
Chris Lattner257008b2005-05-08 21:54:56 +0000360
Daniel Dunbara53337f2009-09-07 19:26:11 +0000361 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
362 ToNotOptimize);
363 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
364 ToOptimize);
365 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
Chris Lattner257008b2005-05-08 21:54:56 +0000366 ToOptimizeLoopExtracted);
367
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000368 errs() << "Please submit the "
Daniel Dunbara53337f2009-09-07 19:26:11 +0000369 << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
Chris Lattner257008b2005-05-08 21:54:56 +0000370 delete ToOptimize;
Chris Lattnerbcec7872004-03-14 22:08:00 +0000371 delete ToNotOptimize;
Chris Lattnerbcec7872004-03-14 22:08:00 +0000372 return MadeChange;
373 }
Chris Lattner257008b2005-05-08 21:54:56 +0000374 delete ToOptimize;
Chris Lattnerbf791612004-04-05 22:58:16 +0000375 BD.switchToInterpreter(AI);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000376
Dan Gohmanee051522009-07-16 15:30:09 +0000377 outs() << " Testing after loop extraction:\n";
Chris Lattner0434ba32004-04-05 21:37:38 +0000378 // Clone modules, the tester function will free them.
Rafael Espindolacab951d2015-12-08 23:57:17 +0000379 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted, VMap).release();
380 Module *TNOBackup = CloneModule(ToNotOptimize, VMap).release();
Hal Finkele9efbf12013-08-02 21:13:42 +0000381
382 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
383 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
384
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000385 Failure = TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize, Error);
386 if (!Error.empty())
387 return false;
Hal Finkele9efbf12013-08-02 21:13:42 +0000388
389 ToOptimizeLoopExtracted = TOLEBackup;
390 ToNotOptimize = TNOBackup;
391
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000392 if (!Failure) {
Dan Gohmanee051522009-07-16 15:30:09 +0000393 outs() << "*** Loop extraction masked the problem. Undoing.\n";
Chris Lattnerbcec7872004-03-14 22:08:00 +0000394 // If the program is not still broken, then loop extraction did something
395 // that masked the error. Stop loop extraction now.
Hal Finkele9efbf12013-08-02 21:13:42 +0000396
397 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000398 for (Function *F : MiscompiledFunctions) {
399 MisCompFunctions.emplace_back(F->getName(), F->getFunctionType());
Hal Finkele9efbf12013-08-02 21:13:42 +0000400 }
401
Rafael Espindolaf49a38f2015-12-04 22:08:53 +0000402 if (Linker::linkModules(*ToNotOptimize, *ToOptimizeLoopExtracted,
403 diagnosticHandler))
Hal Finkele9efbf12013-08-02 21:13:42 +0000404 exit(1);
Hal Finkele9efbf12013-08-02 21:13:42 +0000405
406 MiscompiledFunctions.clear();
407 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
408 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
409
410 assert(NewF && "Function not found??");
411 MiscompiledFunctions.push_back(NewF);
412 }
413
414 delete ToOptimizeLoopExtracted;
415 BD.setNewProgram(ToNotOptimize);
Chris Lattnerbcec7872004-03-14 22:08:00 +0000416 return MadeChange;
417 }
Chris Lattner0434ba32004-04-05 21:37:38 +0000418
Dan Gohmanee051522009-07-16 15:30:09 +0000419 outs() << "*** Loop extraction successful!\n";
Chris Lattnerbcec7872004-03-14 22:08:00 +0000420
Chris Lattner229907c2011-07-18 04:54:35 +0000421 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
Chris Lattnerd3087972004-11-16 06:31:38 +0000422 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
423 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
Reid Spencer5301e7c2007-01-30 20:08:39 +0000424 if (!I->isDeclaration())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000425 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
Chris Lattnerd3087972004-11-16 06:31:38 +0000426
Chris Lattnerbcec7872004-03-14 22:08:00 +0000427 // Okay, great! Now we know that we extracted a loop and that loop
428 // extraction both didn't break the program, and didn't mask the problem.
429 // Replace the current program with the loop extracted version, and try to
430 // extract another loop.
Rafael Espindolaf49a38f2015-12-04 22:08:53 +0000431 if (Linker::linkModules(*ToNotOptimize, *ToOptimizeLoopExtracted,
432 diagnosticHandler))
Chris Lattnerbcec7872004-03-14 22:08:00 +0000433 exit(1);
Rafael Espindolad12b4a32014-10-25 04:06:10 +0000434
Chris Lattnerd3087972004-11-16 06:31:38 +0000435 delete ToOptimizeLoopExtracted;
Chris Lattnerb38cc9c2004-03-17 17:42:09 +0000436
437 // All of the Function*'s in the MiscompiledFunctions list are in the old
Chris Lattnera413b082004-04-02 06:32:17 +0000438 // module. Update this list to include all of the functions in the
439 // optimized and loop extracted module.
440 MiscompiledFunctions.clear();
Chris Lattnerd3087972004-11-16 06:31:38 +0000441 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000442 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000443
Chris Lattnerd3087972004-11-16 06:31:38 +0000444 assert(NewF && "Function not found??");
445 MiscompiledFunctions.push_back(NewF);
Chris Lattnerb38cc9c2004-03-17 17:42:09 +0000446 }
447
Chris Lattnerbcec7872004-03-14 22:08:00 +0000448 BD.setNewProgram(ToNotOptimize);
449 MadeChange = true;
450 }
451}
452
Chris Lattnera060b102004-05-11 21:54:13 +0000453namespace {
454 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
455 BugDriver &BD;
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000456 bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
Chris Lattnera060b102004-05-11 21:54:13 +0000457 std::vector<Function*> FunctionsBeingTested;
458 public:
459 ReduceMiscompiledBlocks(BugDriver &bd,
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000460 bool (*F)(BugDriver &, Module *, Module *,
461 std::string &),
Chris Lattnera060b102004-05-11 21:54:13 +0000462 const std::vector<Function*> &Fns)
463 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000464
Craig Toppere56917c2014-03-08 08:27:28 +0000465 TestResult doTest(std::vector<BasicBlock*> &Prefix,
466 std::vector<BasicBlock*> &Suffix,
467 std::string &Error) override {
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000468 if (!Suffix.empty()) {
469 bool Ret = TestFuncs(Suffix, Error);
470 if (!Error.empty())
471 return InternalError;
472 if (Ret)
473 return KeepSuffix;
474 }
475 if (!Prefix.empty()) {
476 bool Ret = TestFuncs(Prefix, Error);
477 if (!Error.empty())
478 return InternalError;
479 if (Ret)
480 return KeepPrefix;
481 }
Chris Lattnera060b102004-05-11 21:54:13 +0000482 return NoFailure;
483 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000484
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000485 bool TestFuncs(const std::vector<BasicBlock*> &BBs, std::string &Error);
Chris Lattnera060b102004-05-11 21:54:13 +0000486 };
487}
488
489/// TestFuncs - Extract all blocks for the miscompiled functions except for the
490/// specified blocks. If the problem still exists, return true.
491///
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000492bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs,
493 std::string &Error) {
Chris Lattnera060b102004-05-11 21:54:13 +0000494 // Test to see if the function is misoptimized if we ONLY run it on the
495 // functions listed in Funcs.
Dan Gohmanee051522009-07-16 15:30:09 +0000496 outs() << "Checking to see if the program is misoptimized when all ";
Chris Lattner6c0c3132004-05-12 16:08:01 +0000497 if (!BBs.empty()) {
Dan Gohmanee051522009-07-16 15:30:09 +0000498 outs() << "but these " << BBs.size() << " blocks are extracted: ";
Chris Lattner6c0c3132004-05-12 16:08:01 +0000499 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
Dan Gohmanee051522009-07-16 15:30:09 +0000500 outs() << BBs[i]->getName() << " ";
501 if (BBs.size() > 10) outs() << "...";
Chris Lattner6c0c3132004-05-12 16:08:01 +0000502 } else {
Dan Gohmanee051522009-07-16 15:30:09 +0000503 outs() << "blocks are extracted.";
Chris Lattner6c0c3132004-05-12 16:08:01 +0000504 }
Dan Gohmanee051522009-07-16 15:30:09 +0000505 outs() << '\n';
Chris Lattnera060b102004-05-11 21:54:13 +0000506
507 // Split the module into the two halves of the program we want.
Rafael Espindola229e38f2010-10-13 01:36:30 +0000508 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000509 Module *Clone = CloneModule(BD.getProgram(), VMap).release();
Rafael Espindola07035e62010-07-29 14:20:59 +0000510 Module *Orig = BD.swapProgramIn(Clone);
511 std::vector<Function*> FuncsOnClone;
512 std::vector<BasicBlock*> BBsOnClone;
513 for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
514 Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
515 FuncsOnClone.push_back(F);
516 }
517 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
518 BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
519 BBsOnClone.push_back(BB);
520 }
521 VMap.clear();
522
Rafael Espindolacab951d2015-12-08 23:57:17 +0000523 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap).release();
Chris Lattnera060b102004-05-11 21:54:13 +0000524 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Rafael Espindola07035e62010-07-29 14:20:59 +0000525 FuncsOnClone,
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000526 VMap);
Chris Lattnera060b102004-05-11 21:54:13 +0000527
528 // Try the extraction. If it doesn't work, then the block extractor crashed
529 // or something, in which case bugpoint can't chase down this possibility.
Rafael Espindola28b351a2014-08-26 17:19:03 +0000530 if (std::unique_ptr<Module> New =
531 BD.extractMappedBlocksFromModule(BBsOnClone, ToOptimize)) {
Chris Lattnera060b102004-05-11 21:54:13 +0000532 delete ToOptimize;
Rafael Espindola07035e62010-07-29 14:20:59 +0000533 // Run the predicate,
534 // note that the predicate will delete both input modules.
Rafael Espindola28b351a2014-08-26 17:19:03 +0000535 bool Ret = TestFn(BD, New.get(), ToNotOptimize, Error);
Rafael Espindola07035e62010-07-29 14:20:59 +0000536 delete BD.swapProgramIn(Orig);
537 return Ret;
Chris Lattnera060b102004-05-11 21:54:13 +0000538 }
Rafael Espindola07035e62010-07-29 14:20:59 +0000539 delete BD.swapProgramIn(Orig);
Chris Lattnera060b102004-05-11 21:54:13 +0000540 delete ToOptimize;
541 delete ToNotOptimize;
542 return false;
543}
544
545
546/// ExtractBlocks - Given a reduced list of functions that still expose the bug,
547/// extract as many basic blocks from the region as possible without obscuring
548/// the bug.
549///
550static bool ExtractBlocks(BugDriver &BD,
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000551 bool (*TestFn)(BugDriver &, Module *, Module *,
552 std::string &),
553 std::vector<Function*> &MiscompiledFunctions,
554 std::string &Error) {
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000555 if (BugpointIsInterrupted) return false;
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000556
Chris Lattnera060b102004-05-11 21:54:13 +0000557 std::vector<BasicBlock*> Blocks;
558 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000559 for (BasicBlock &BB : *MiscompiledFunctions[i])
560 Blocks.push_back(&BB);
Chris Lattnera060b102004-05-11 21:54:13 +0000561
562 // Use the list reducer to identify blocks that can be extracted without
563 // obscuring the bug. The Blocks list will end up containing blocks that must
564 // be retained from the original program.
565 unsigned OldSize = Blocks.size();
Chris Lattner6c0c3132004-05-12 16:08:01 +0000566
567 // Check to see if all blocks are extractible first.
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000568 bool Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
569 .TestFuncs(std::vector<BasicBlock*>(), Error);
570 if (!Error.empty())
571 return false;
572 if (Ret) {
Chris Lattner6c0c3132004-05-12 16:08:01 +0000573 Blocks.clear();
574 } else {
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000575 ReduceMiscompiledBlocks(BD, TestFn,
576 MiscompiledFunctions).reduceList(Blocks, Error);
577 if (!Error.empty())
578 return false;
Chris Lattner6c0c3132004-05-12 16:08:01 +0000579 if (Blocks.size() == OldSize)
580 return false;
581 }
Chris Lattnera060b102004-05-11 21:54:13 +0000582
Rafael Espindola229e38f2010-10-13 01:36:30 +0000583 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000584 Module *ProgClone = CloneModule(BD.getProgram(), VMap).release();
Chris Lattner49e4a332004-05-12 02:43:24 +0000585 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
Dan Gohman956ae9d2009-04-22 15:57:18 +0000586 MiscompiledFunctions,
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000587 VMap);
Rafael Espindola28b351a2014-08-26 17:19:03 +0000588 std::unique_ptr<Module> Extracted =
589 BD.extractMappedBlocksFromModule(Blocks, ToExtract);
Craig Toppere6cb63e2014-04-25 04:24:47 +0000590 if (!Extracted) {
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000591 // Weird, extraction should have worked.
Dan Gohmand8db3762009-07-15 16:35:29 +0000592 errs() << "Nondeterministic problem extracting blocks??\n";
Chris Lattner49e4a332004-05-12 02:43:24 +0000593 delete ProgClone;
594 delete ToExtract;
595 return false;
596 }
Chris Lattnera060b102004-05-11 21:54:13 +0000597
Chris Lattner49e4a332004-05-12 02:43:24 +0000598 // Otherwise, block extraction succeeded. Link the two program fragments back
599 // together.
600 delete ToExtract;
Chris Lattnera060b102004-05-11 21:54:13 +0000601
Chris Lattner229907c2011-07-18 04:54:35 +0000602 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
Chris Lattnerd3087972004-11-16 06:31:38 +0000603 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
604 I != E; ++I)
Reid Spencer5301e7c2007-01-30 20:08:39 +0000605 if (!I->isDeclaration())
Benjamin Kramerf5e2fc42015-05-29 19:43:39 +0000606 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
Chris Lattnerd3087972004-11-16 06:31:38 +0000607
Rafael Espindolaf49a38f2015-12-04 22:08:53 +0000608 if (Linker::linkModules(*ProgClone, *Extracted, diagnosticHandler))
Chris Lattner49e4a332004-05-12 02:43:24 +0000609 exit(1);
Chris Lattnera060b102004-05-11 21:54:13 +0000610
Chris Lattner49e4a332004-05-12 02:43:24 +0000611 // Set the new program and delete the old one.
612 BD.setNewProgram(ProgClone);
Chris Lattnera060b102004-05-11 21:54:13 +0000613
Chris Lattner49e4a332004-05-12 02:43:24 +0000614 // Update the list of miscompiled functions.
615 MiscompiledFunctions.clear();
Chris Lattnera060b102004-05-11 21:54:13 +0000616
Chris Lattnerd3087972004-11-16 06:31:38 +0000617 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000618 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
Chris Lattnerd3087972004-11-16 06:31:38 +0000619 assert(NewF && "Function not found??");
620 MiscompiledFunctions.push_back(NewF);
621 }
Chris Lattner49e4a332004-05-12 02:43:24 +0000622
623 return true;
Chris Lattnera060b102004-05-11 21:54:13 +0000624}
625
626
Chris Lattner0434ba32004-04-05 21:37:38 +0000627/// DebugAMiscompilation - This is a generic driver to narrow down
628/// miscompilations, either in an optimization or a code generator.
Misha Brukman0784a602004-04-21 18:36:43 +0000629///
Chris Lattner0434ba32004-04-05 21:37:38 +0000630static std::vector<Function*>
631DebugAMiscompilation(BugDriver &BD,
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000632 bool (*TestFn)(BugDriver &, Module *, Module *,
633 std::string &),
634 std::string &Error) {
Chris Lattner0434ba32004-04-05 21:37:38 +0000635 // Okay, now that we have reduced the list of passes which are causing the
636 // failure, see if we can pin down which functions are being
637 // miscompiled... first build a list of all of the non-external functions in
638 // the program.
639 std::vector<Function*> MiscompiledFunctions;
640 Module *Prog = BD.getProgram();
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000641 for (Function &F : *Prog)
642 if (!F.isDeclaration())
643 MiscompiledFunctions.push_back(&F);
Chris Lattner0434ba32004-04-05 21:37:38 +0000644
645 // Do the reduction...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000646 if (!BugpointIsInterrupted)
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000647 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
648 Error);
Andrew Trick55aeb552011-05-11 16:31:24 +0000649 if (!Error.empty()) {
650 errs() << "\n***Cannot reduce functions: ";
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000651 return MiscompiledFunctions;
Andrew Trick55aeb552011-05-11 16:31:24 +0000652 }
Dan Gohmanee051522009-07-16 15:30:09 +0000653 outs() << "\n*** The following function"
654 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
655 << " being miscompiled: ";
Chris Lattner0434ba32004-04-05 21:37:38 +0000656 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanee051522009-07-16 15:30:09 +0000657 outs() << '\n';
Chris Lattner0434ba32004-04-05 21:37:38 +0000658
659 // See if we can rip any loops out of the miscompiled functions and still
660 // trigger the problem.
Reid Spencer471bcb72006-11-11 19:05:02 +0000661
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000662 if (!BugpointIsInterrupted && !DisableLoopExtraction) {
663 bool Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions, Error);
664 if (!Error.empty())
665 return MiscompiledFunctions;
666 if (Ret) {
667 // Okay, we extracted some loops and the problem still appears. See if
668 // we can eliminate some of the created functions from being candidates.
669 DisambiguateGlobalSymbols(BD.getProgram());
Chris Lattnerdfbb1d12004-04-11 23:52:35 +0000670
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000671 // Do the reduction...
672 if (!BugpointIsInterrupted)
673 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
674 Error);
675 if (!Error.empty())
676 return MiscompiledFunctions;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000677
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000678 outs() << "\n*** The following function"
679 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
680 << " being miscompiled: ";
681 PrintFunctionList(MiscompiledFunctions);
682 outs() << '\n';
683 }
Chris Lattner0434ba32004-04-05 21:37:38 +0000684 }
685
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000686 if (!BugpointIsInterrupted && !DisableBlockExtraction) {
687 bool Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions, Error);
688 if (!Error.empty())
689 return MiscompiledFunctions;
690 if (Ret) {
691 // Okay, we extracted some blocks and the problem still appears. See if
692 // we can eliminate some of the created functions from being candidates.
693 DisambiguateGlobalSymbols(BD.getProgram());
Chris Lattnera060b102004-05-11 21:54:13 +0000694
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000695 // Do the reduction...
696 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
697 Error);
698 if (!Error.empty())
699 return MiscompiledFunctions;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000700
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000701 outs() << "\n*** The following function"
702 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
703 << " being miscompiled: ";
704 PrintFunctionList(MiscompiledFunctions);
705 outs() << '\n';
706 }
Chris Lattnera060b102004-05-11 21:54:13 +0000707 }
708
Chris Lattner0434ba32004-04-05 21:37:38 +0000709 return MiscompiledFunctions;
710}
711
Chris Lattnerbf791612004-04-05 22:58:16 +0000712/// TestOptimizer - This is the predicate function used to check to see if the
713/// "Test" portion of the program is misoptimized. If so, return true. In any
714/// case, both module arguments are deleted.
Misha Brukman0784a602004-04-21 18:36:43 +0000715///
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000716static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe,
717 std::string &Error) {
Chris Lattner0434ba32004-04-05 21:37:38 +0000718 // Run the optimization passes on ToOptimize, producing a transformed version
719 // of the functions being tested.
Dan Gohmanee051522009-07-16 15:30:09 +0000720 outs() << " Optimizing functions being tested: ";
Rafael Espindola28b351a2014-08-26 17:19:03 +0000721 std::unique_ptr<Module> Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
722 /*AutoDebugCrashes*/ true);
Dan Gohmanee051522009-07-16 15:30:09 +0000723 outs() << "done.\n";
Chris Lattner0434ba32004-04-05 21:37:38 +0000724 delete Test;
725
Dan Gohmanee051522009-07-16 15:30:09 +0000726 outs() << " Checking to see if the merged program executes correctly: ";
Rafael Espindolae4904602010-07-31 14:34:49 +0000727 bool Broken;
Rafael Espindola28b351a2014-08-26 17:19:03 +0000728 Module *New =
729 TestMergedProgram(BD, Optimized.get(), Safe, true, Error, Broken);
Rafael Espindolae4904602010-07-31 14:34:49 +0000730 if (New) {
731 outs() << (Broken ? " nope.\n" : " yup.\n");
732 // Delete the original and set the new program.
733 delete BD.swapProgramIn(New);
734 }
Chris Lattner0434ba32004-04-05 21:37:38 +0000735 return Broken;
736}
737
738
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000739/// debugMiscompilation - This method is used when the passes selected are not
740/// crashing, but the generated output is semantically different from the
741/// input.
742///
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000743void BugDriver::debugMiscompilation(std::string *Error) {
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000744 // Make sure something was miscompiled...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000745 if (!BugpointIsInterrupted)
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000746 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun, *Error)) {
747 if (Error->empty())
748 errs() << "*** Optimized program matches reference output! No problem"
749 << " detected...\nbugpoint can't help you with your problem!\n";
750 return;
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000751 }
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000752
Dan Gohmanee051522009-07-16 15:30:09 +0000753 outs() << "\n*** Found miscompiling pass"
754 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
755 << getPassesString(getPassesToRun()) << '\n';
Rafael Espindola594994a2010-07-28 18:12:30 +0000756 EmitProgressBitcode(Program, "passinput");
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000757
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000758 std::vector<Function *> MiscompiledFunctions =
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000759 DebugAMiscompilation(*this, TestOptimizer, *Error);
760 if (!Error->empty())
761 return;
Chris Lattnerbcec7872004-03-14 22:08:00 +0000762
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000763 // Output a bunch of bitcode files for the user...
Dan Gohmanee051522009-07-16 15:30:09 +0000764 outs() << "Outputting reduced bitcode files which expose the problem:\n";
Rafael Espindola229e38f2010-10-13 01:36:30 +0000765 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +0000766 Module *ToNotOptimize = CloneModule(getProgram(), VMap).release();
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000767 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohman956ae9d2009-04-22 15:57:18 +0000768 MiscompiledFunctions,
Devang Patel0dc3c2d2010-06-24 00:33:28 +0000769 VMap);
Chris Lattner567543f2004-03-14 19:27:19 +0000770
Dan Gohmanee051522009-07-16 15:30:09 +0000771 outs() << " Non-optimized portion: ";
Rafael Espindola594994a2010-07-28 18:12:30 +0000772 EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true);
773 delete ToNotOptimize; // Delete hacked module.
Misha Brukman650ba8e2005-04-22 00:00:37 +0000774
Dan Gohmanee051522009-07-16 15:30:09 +0000775 outs() << " Portion that is input to optimizer: ";
Rafael Espindola594994a2010-07-28 18:12:30 +0000776 EmitProgressBitcode(ToOptimize, "tooptimize");
777 delete ToOptimize; // Delete hacked module.
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000778
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000779 return;
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000780}
Brian Gaeke960707c2003-11-11 22:41:34 +0000781
Chris Lattnerbf791612004-04-05 22:58:16 +0000782/// CleanupAndPrepareModules - Get the specified modules ready for code
783/// generator testing.
Misha Brukman0784a602004-04-21 18:36:43 +0000784///
Chris Lattnerbf791612004-04-05 22:58:16 +0000785static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
786 Module *Safe) {
787 // Clean up the modules, removing extra cruft that we don't need anymore...
Rafael Espindola28b351a2014-08-26 17:19:03 +0000788 Test = BD.performFinalCleanups(Test).release();
Chris Lattnerbf791612004-04-05 22:58:16 +0000789
790 // If we are executing the JIT, we have several nasty issues to take care of.
791 if (!BD.isExecutingJIT()) return;
792
793 // First, if the main function is in the Safe module, we must add a stub to
794 // the Test module to call into it. Thus, we create a new function `main'
795 // which just calls the old one.
Reid Spencer1241d6d2007-02-05 21:19:13 +0000796 if (Function *oldMain = Safe->getFunction("main"))
Reid Spencer5301e7c2007-01-30 20:08:39 +0000797 if (!oldMain->isDeclaration()) {
Chris Lattnerbf791612004-04-05 22:58:16 +0000798 // Rename it
799 oldMain->setName("llvm_bugpoint_old_main");
800 // Create a NEW `main' function with same type in the test module.
Gabor Greife9ecc682008-04-06 20:25:17 +0000801 Function *newMain = Function::Create(oldMain->getFunctionType(),
802 GlobalValue::ExternalLinkage,
803 "main", Test);
Chris Lattnerbf791612004-04-05 22:58:16 +0000804 // Create an `oldmain' prototype in the test module, which will
805 // corresponds to the real main function in the same module.
Gabor Greife9ecc682008-04-06 20:25:17 +0000806 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
807 GlobalValue::ExternalLinkage,
808 oldMain->getName(), Test);
Chris Lattnerbf791612004-04-05 22:58:16 +0000809 // Set up and remember the argument list for the main function.
810 std::vector<Value*> args;
Alkis Evlogimenosa67bafa2005-03-15 07:02:26 +0000811 for (Function::arg_iterator
812 I = newMain->arg_begin(), E = newMain->arg_end(),
813 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
Owen Anderson7629b712008-04-14 17:38:21 +0000814 I->setName(OI->getName()); // Copy argument names from oldMain
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000815 args.push_back(&*I);
Chris Lattnerbf791612004-04-05 22:58:16 +0000816 }
817
818 // Call the old main function and return its result
Owen Anderson55f1c092009-08-13 21:58:54 +0000819 BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
Jay Foad5bd375a2011-07-15 08:37:34 +0000820 CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000821
Chris Lattnerbf791612004-04-05 22:58:16 +0000822 // If the type of old function wasn't void, return value of call
Owen Anderson55f1c092009-08-13 21:58:54 +0000823 ReturnInst::Create(Safe->getContext(), call, BB);
Chris Lattnerbf791612004-04-05 22:58:16 +0000824 }
825
826 // The second nasty issue we must deal with in the JIT is that the Safe
827 // module cannot directly reference any functions defined in the test
828 // module. Instead, we use a JIT API call to dynamically resolve the
829 // symbol.
Misha Brukman650ba8e2005-04-22 00:00:37 +0000830
Chris Lattnerbf791612004-04-05 22:58:16 +0000831 // Add the resolver to the Safe module.
832 // Prototype: void *getPointerToNamedFunction(const char* Name)
Chris Lattner7b864c02007-01-07 08:13:39 +0000833 Constant *resolverFunc =
Chris Lattnerbf791612004-04-05 22:58:16 +0000834 Safe->getOrInsertFunction("getPointerToNamedFunction",
Duncan Sands9ed7b162009-10-06 15:40:36 +0000835 Type::getInt8PtrTy(Safe->getContext()),
836 Type::getInt8PtrTy(Safe->getContext()),
Craig Toppere6cb63e2014-04-25 04:24:47 +0000837 (Type *)nullptr);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000838
Chris Lattnerbf791612004-04-05 22:58:16 +0000839 // Use the function we just added to get addresses of functions we need.
Misha Brukman83018642004-04-19 01:12:01 +0000840 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
Reid Spencer5301e7c2007-01-30 20:08:39 +0000841 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
Duncan Sands38ef3a82007-12-03 20:06:50 +0000842 !F->isIntrinsic() /* ignore intrinsics */) {
Reid Spencer1241d6d2007-02-05 21:19:13 +0000843 Function *TestFn = Test->getFunction(F->getName());
Chris Lattnerbf791612004-04-05 22:58:16 +0000844
845 // Don't forward functions which are external in the test module too.
Reid Spencer5301e7c2007-01-30 20:08:39 +0000846 if (TestFn && !TestFn->isDeclaration()) {
Chris Lattnerbf791612004-04-05 22:58:16 +0000847 // 1. Add a string constant with its name to the global file
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000848 Constant *InitArray =
849 ConstantDataArray::getString(F->getContext(), F->getName());
Chris Lattnerbf791612004-04-05 22:58:16 +0000850 GlobalVariable *funcName =
Owen Andersonb17f3292009-07-08 19:03:57 +0000851 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
Misha Brukman650ba8e2005-04-22 00:00:37 +0000852 GlobalValue::InternalLinkage, InitArray,
Owen Andersonb17f3292009-07-08 19:03:57 +0000853 F->getName() + "_name");
Chris Lattnerbf791612004-04-05 22:58:16 +0000854
855 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
856 // sbyte* so it matches the signature of the resolver function.
857
858 // GetElementPtr *funcName, ulong 0, ulong 0
Owen Anderson55f1c092009-08-13 21:58:54 +0000859 std::vector<Constant*> GEPargs(2,
860 Constant::getNullValue(Type::getInt32Ty(F->getContext())));
David Blaikie4a2e73b2015-04-02 18:55:32 +0000861 Value *GEP = ConstantExpr::getGetElementPtr(InitArray->getType(),
862 funcName, GEPargs);
Chris Lattnerbf791612004-04-05 22:58:16 +0000863 std::vector<Value*> ResolverArgs;
864 ResolverArgs.push_back(GEP);
865
Misha Brukmance89b392004-04-19 03:36:47 +0000866 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
867 // function that dynamically resolves the calls to F via our JIT API
Chris Lattner986675c2005-07-12 01:00:32 +0000868 if (!F->use_empty()) {
869 // Create a new global to hold the cached function pointer.
Owen Andersonb292b8c2009-07-30 23:03:37 +0000870 Constant *NullPtr = ConstantPointerNull::get(F->getType());
Chris Lattner986675c2005-07-12 01:00:32 +0000871 GlobalVariable *Cache =
Michael J. Spencer3df5c042011-03-31 13:06:39 +0000872 new GlobalVariable(*F->getParent(), F->getType(),
Owen Andersonb17f3292009-07-08 19:03:57 +0000873 false, GlobalValue::InternalLinkage,
874 NullPtr,F->getName()+".fpcache");
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000875
Misha Brukmance89b392004-04-19 03:36:47 +0000876 // Construct a new stub function that will re-route calls to F
Chris Lattner229907c2011-07-18 04:54:35 +0000877 FunctionType *FuncTy = F->getFunctionType();
Gabor Greife9ecc682008-04-06 20:25:17 +0000878 Function *FuncWrapper = Function::Create(FuncTy,
879 GlobalValue::InternalLinkage,
880 F->getName() + "_wrapper",
881 F->getParent());
Owen Anderson55f1c092009-08-13 21:58:54 +0000882 BasicBlock *EntryBB = BasicBlock::Create(F->getContext(),
883 "entry", FuncWrapper);
884 BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
885 "usecache", FuncWrapper);
886 BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
887 "lookupfp", FuncWrapper);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000888
Chris Lattner986675c2005-07-12 01:00:32 +0000889 // Check to see if we already looked up the value.
890 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
Owen Anderson1e5f00e2009-07-09 23:48:35 +0000891 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
892 NullPtr, "isNull");
Gabor Greife9ecc682008-04-06 20:25:17 +0000893 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000894
Misha Brukmance89b392004-04-19 03:36:47 +0000895 // Resolve the call to function F via the JIT API:
896 //
897 // call resolver(GetElementPtr...)
Gabor Greif697e94c2008-05-15 10:04:30 +0000898 CallInst *Resolver =
Jay Foad5bd375a2011-07-15 08:37:34 +0000899 CallInst::Create(resolverFunc, ResolverArgs, "resolver", LookupBB);
Gabor Greif697e94c2008-05-15 10:04:30 +0000900
901 // Cast the result from the resolver to correctly-typed function.
902 CastInst *CastedResolver =
903 new BitCastInst(Resolver,
Owen Anderson4056ca92009-07-29 22:17:13 +0000904 PointerType::getUnqual(F->getFunctionType()),
Gabor Greif697e94c2008-05-15 10:04:30 +0000905 "resolverCast", LookupBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000906
Chris Lattner986675c2005-07-12 01:00:32 +0000907 // Save the value in our cache.
908 new StoreInst(CastedResolver, Cache, LookupBB);
Gabor Greife9ecc682008-04-06 20:25:17 +0000909 BranchInst::Create(DoCallBB, LookupBB);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000910
Jay Foad52131342011-03-30 11:28:46 +0000911 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(), 2,
Gabor Greif697e94c2008-05-15 10:04:30 +0000912 "fp", DoCallBB);
Chris Lattner986675c2005-07-12 01:00:32 +0000913 FuncPtr->addIncoming(CastedResolver, LookupBB);
914 FuncPtr->addIncoming(CachedVal, EntryBB);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000915
Chris Lattner986675c2005-07-12 01:00:32 +0000916 // Save the argument list.
Misha Brukman83018642004-04-19 01:12:01 +0000917 std::vector<Value*> Args;
Duncan P. N. Exon Smith306d16e2015-10-20 19:36:39 +0000918 for (Argument &A : FuncWrapper->args())
919 Args.push_back(&A);
Misha Brukman83018642004-04-19 01:12:01 +0000920
921 // Pass on the arguments to the real function, return its result
Dan Gohman34a22492010-06-07 20:19:26 +0000922 if (F->getReturnType()->isVoidTy()) {
Jay Foad5bd375a2011-07-15 08:37:34 +0000923 CallInst::Create(FuncPtr, Args, "", DoCallBB);
Owen Anderson55f1c092009-08-13 21:58:54 +0000924 ReturnInst::Create(F->getContext(), DoCallBB);
Misha Brukman83018642004-04-19 01:12:01 +0000925 } else {
Jay Foad5bd375a2011-07-15 08:37:34 +0000926 CallInst *Call = CallInst::Create(FuncPtr, Args,
Gabor Greife9ecc682008-04-06 20:25:17 +0000927 "retval", DoCallBB);
Owen Anderson55f1c092009-08-13 21:58:54 +0000928 ReturnInst::Create(F->getContext(),Call, DoCallBB);
Misha Brukman83018642004-04-19 01:12:01 +0000929 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000930
Misha Brukmance89b392004-04-19 03:36:47 +0000931 // Use the wrapper function instead of the old function
932 F->replaceAllUsesWith(FuncWrapper);
Misha Brukman83018642004-04-19 01:12:01 +0000933 }
Chris Lattnerbf791612004-04-05 22:58:16 +0000934 }
935 }
936 }
937
938 if (verifyModule(*Test) || verifyModule(*Safe)) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000939 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
Chris Lattnerbf791612004-04-05 22:58:16 +0000940 abort();
941 }
942}
943
944
945
946/// TestCodeGenerator - This is the predicate function used to check to see if
947/// the "Test" portion of the program is miscompiled by the code generator under
948/// test. If so, return true. In any case, both module arguments are deleted.
Misha Brukman0784a602004-04-21 18:36:43 +0000949///
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000950static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe,
951 std::string &Error) {
Chris Lattnerbf791612004-04-05 22:58:16 +0000952 CleanupAndPrepareModules(BD, Test, Safe);
953
Rafael Espindola302c0da2013-06-18 15:29:32 +0000954 SmallString<128> TestModuleBC;
955 int TestModuleFD;
Rafael Espindola4453e42942014-06-13 03:07:50 +0000956 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
957 TestModuleFD, TestModuleBC);
Rafael Espindola302c0da2013-06-18 15:29:32 +0000958 if (EC) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000959 errs() << BD.getToolName() << "Error making unique filename: "
Rafael Espindola302c0da2013-06-18 15:29:32 +0000960 << EC.message() << "\n";
Reid Spencere4ca7222006-08-23 20:34:57 +0000961 exit(1);
962 }
Rafael Espindola302c0da2013-06-18 15:29:32 +0000963 if (BD.writeProgramToFile(TestModuleBC.str(), TestModuleFD, Test)) {
Chris Lattnerc521f542009-08-23 22:45:37 +0000964 errs() << "Error writing bitcode to `" << TestModuleBC.str()
965 << "'\nExiting.";
Chris Lattnerbf791612004-04-05 22:58:16 +0000966 exit(1);
967 }
968 delete Test;
969
Michael J. Spencerc60223e2011-03-31 13:04:19 +0000970 FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
Rafael Espindola720f49e2010-06-21 02:17:36 +0000971
Chris Lattnerbf791612004-04-05 22:58:16 +0000972 // Make the shared library
Rafael Espindola302c0da2013-06-18 15:29:32 +0000973 SmallString<128> SafeModuleBC;
974 int SafeModuleFD;
Rafael Espindola155cf0f2013-07-05 20:14:52 +0000975 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
976 SafeModuleBC);
Rafael Espindola302c0da2013-06-18 15:29:32 +0000977 if (EC) {
Dan Gohmand8db3762009-07-15 16:35:29 +0000978 errs() << BD.getToolName() << "Error making unique filename: "
Rafael Espindola302c0da2013-06-18 15:29:32 +0000979 << EC.message() << "\n";
Reid Spencere4ca7222006-08-23 20:34:57 +0000980 exit(1);
981 }
Chris Lattnerbf791612004-04-05 22:58:16 +0000982
Rafael Espindola302c0da2013-06-18 15:29:32 +0000983 if (BD.writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, Safe)) {
Yaron Keren09fb7c62015-03-10 07:33:23 +0000984 errs() << "Error writing bitcode to `" << SafeModuleBC
Chris Lattnerc521f542009-08-23 22:45:37 +0000985 << "'\nExiting.";
Chris Lattnerbf791612004-04-05 22:58:16 +0000986 exit(1);
987 }
Rafael Espindola720f49e2010-06-21 02:17:36 +0000988
Michael J. Spencerc60223e2011-03-31 13:04:19 +0000989 FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
Rafael Espindola720f49e2010-06-21 02:17:36 +0000990
Nick Lewycky6ba630b2010-04-12 05:08:25 +0000991 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str(), Error);
992 if (!Error.empty())
Benjamin Kramer1f336da2010-04-12 12:22:19 +0000993 return false;
Chris Lattnerbf791612004-04-05 22:58:16 +0000994 delete Safe;
995
Michael J. Spencerc60223e2011-03-31 13:04:19 +0000996 FileRemover SharedObjectRemover(SharedObject, !SaveTemps);
Rafael Espindola720f49e2010-06-21 02:17:36 +0000997
Chris Lattnerbf791612004-04-05 22:58:16 +0000998 // Run the code generator on the `Test' code, loading the shared library.
999 // The function returns whether or not the new output differs from reference.
Rafael Espindolac89b1ef2010-07-30 14:19:00 +00001000 bool Result = BD.diffProgram(BD.getProgram(), TestModuleBC.str(),
1001 SharedObject, false, &Error);
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001002 if (!Error.empty())
1003 return false;
Chris Lattnerbf791612004-04-05 22:58:16 +00001004
1005 if (Result)
Dan Gohmand8db3762009-07-15 16:35:29 +00001006 errs() << ": still failing!\n";
Chris Lattnerbf791612004-04-05 22:58:16 +00001007 else
Dan Gohmand8db3762009-07-15 16:35:29 +00001008 errs() << ": didn't fail.\n";
Chris Lattnerbf791612004-04-05 22:58:16 +00001009
1010 return Result;
1011}
1012
1013
Misha Brukman0784a602004-04-21 18:36:43 +00001014/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
1015///
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001016bool BugDriver::debugCodeGenerator(std::string *Error) {
Dan Gohman414cf502008-12-08 04:02:47 +00001017 if ((void*)SafeInterpreter == (void*)Interpreter) {
Rafael Espindolac89b1ef2010-07-30 14:19:00 +00001018 std::string Result = executeProgramSafely(Program, "bugpoint.safe.out",
1019 Error);
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001020 if (Error->empty()) {
1021 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
1022 << "the reference diff. This may be due to a\n front-end "
1023 << "bug or a bug in the original program, but this can also "
1024 << "happen if bugpoint isn't running the program with the "
1025 << "right flags or input.\n I left the result of executing "
1026 << "the program with the \"safe\" backend in this file for "
1027 << "you: '"
1028 << Result << "'.\n";
1029 }
Chris Lattnerbf791612004-04-05 22:58:16 +00001030 return true;
1031 }
1032
1033 DisambiguateGlobalSymbols(Program);
1034
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001035 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator,
1036 *Error);
1037 if (!Error->empty())
1038 return true;
Chris Lattnerbf791612004-04-05 22:58:16 +00001039
1040 // Split the module into the two halves of the program we want.
Rafael Espindola229e38f2010-10-13 01:36:30 +00001041 ValueToValueMapTy VMap;
Rafael Espindolacab951d2015-12-08 23:57:17 +00001042 Module *ToNotCodeGen = CloneModule(getProgram(), VMap).release();
Devang Patel0dc3c2d2010-06-24 00:33:28 +00001043 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, VMap);
Chris Lattnerbf791612004-04-05 22:58:16 +00001044
1045 // Condition the modules
1046 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
1047
Rafael Espindola302c0da2013-06-18 15:29:32 +00001048 SmallString<128> TestModuleBC;
1049 int TestModuleFD;
Rafael Espindola4453e42942014-06-13 03:07:50 +00001050 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
1051 TestModuleFD, TestModuleBC);
Rafael Espindola302c0da2013-06-18 15:29:32 +00001052 if (EC) {
Dan Gohmand8db3762009-07-15 16:35:29 +00001053 errs() << getToolName() << "Error making unique filename: "
Rafael Espindola302c0da2013-06-18 15:29:32 +00001054 << EC.message() << "\n";
Reid Spencere4ca7222006-08-23 20:34:57 +00001055 exit(1);
1056 }
Reid Spencer30067f12004-12-15 01:53:08 +00001057
Rafael Espindola302c0da2013-06-18 15:29:32 +00001058 if (writeProgramToFile(TestModuleBC.str(), TestModuleFD, ToCodeGen)) {
Yaron Keren09fb7c62015-03-10 07:33:23 +00001059 errs() << "Error writing bitcode to `" << TestModuleBC
Chris Lattnerc521f542009-08-23 22:45:37 +00001060 << "'\nExiting.";
Chris Lattnerbf791612004-04-05 22:58:16 +00001061 exit(1);
1062 }
1063 delete ToCodeGen;
1064
1065 // Make the shared library
Rafael Espindola302c0da2013-06-18 15:29:32 +00001066 SmallString<128> SafeModuleBC;
1067 int SafeModuleFD;
Rafael Espindola155cf0f2013-07-05 20:14:52 +00001068 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
1069 SafeModuleBC);
Rafael Espindola302c0da2013-06-18 15:29:32 +00001070 if (EC) {
Dan Gohmand8db3762009-07-15 16:35:29 +00001071 errs() << getToolName() << "Error making unique filename: "
Rafael Espindola302c0da2013-06-18 15:29:32 +00001072 << EC.message() << "\n";
Reid Spencere4ca7222006-08-23 20:34:57 +00001073 exit(1);
1074 }
Reid Spencer30067f12004-12-15 01:53:08 +00001075
Rafael Espindola302c0da2013-06-18 15:29:32 +00001076 if (writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, ToNotCodeGen)) {
Yaron Keren09fb7c62015-03-10 07:33:23 +00001077 errs() << "Error writing bitcode to `" << SafeModuleBC
Chris Lattnerc521f542009-08-23 22:45:37 +00001078 << "'\nExiting.";
Chris Lattnerbf791612004-04-05 22:58:16 +00001079 exit(1);
1080 }
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001081 std::string SharedObject = compileSharedObject(SafeModuleBC.str(), *Error);
1082 if (!Error->empty())
1083 return true;
Chris Lattnerbf791612004-04-05 22:58:16 +00001084 delete ToNotCodeGen;
1085
Dan Gohmanee051522009-07-16 15:30:09 +00001086 outs() << "You can reproduce the problem with the command line: \n";
Chris Lattnerbf791612004-04-05 22:58:16 +00001087 if (isExecutingJIT()) {
Yaron Keren09fb7c62015-03-10 07:33:23 +00001088 outs() << " lli -load " << SharedObject << " " << TestModuleBC;
Chris Lattnerbf791612004-04-05 22:58:16 +00001089 } else {
Yaron Keren09fb7c62015-03-10 07:33:23 +00001090 outs() << " llc " << TestModuleBC << " -o " << TestModuleBC
Chris Lattnerc521f542009-08-23 22:45:37 +00001091 << ".s\n";
Davide Italianoab256212015-10-14 20:29:54 +00001092 outs() << " cc " << SharedObject << " " << TestModuleBC.str()
Yaron Keren09fb7c62015-03-10 07:33:23 +00001093 << ".s -o " << TestModuleBC << ".exe";
Chris Lattnerea2fa462005-01-15 00:07:19 +00001094#if defined (HAVE_LINK_R)
Dan Gohmanee051522009-07-16 15:30:09 +00001095 outs() << " -Wl,-R.";
Chris Lattnerea2fa462005-01-15 00:07:19 +00001096#endif
Dan Gohmanee051522009-07-16 15:30:09 +00001097 outs() << "\n";
Yaron Keren09fb7c62015-03-10 07:33:23 +00001098 outs() << " " << TestModuleBC << ".exe";
Chris Lattnerbf791612004-04-05 22:58:16 +00001099 }
Nick Lewycky6ba630b2010-04-12 05:08:25 +00001100 for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
Dan Gohmanee051522009-07-16 15:30:09 +00001101 outs() << " " << InputArgv[i];
1102 outs() << '\n';
1103 outs() << "The shared object was created with:\n llc -march=c "
Chris Lattnerc521f542009-08-23 22:45:37 +00001104 << SafeModuleBC.str() << " -o temporary.c\n"
Davide Italianoab256212015-10-14 20:29:54 +00001105 << " cc -xc temporary.c -O2 -o " << SharedObject;
Daniel Dunbar8575a602009-08-18 03:35:57 +00001106 if (TargetTriple.getArch() == Triple::sparc)
1107 outs() << " -G"; // Compile a shared library, `-G' for Sparc
1108 else
1109 outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
1110
1111 outs() << " -fno-strict-aliasing\n";
Chris Lattnerbf791612004-04-05 22:58:16 +00001112
1113 return false;
1114}