blob: 375bee7a0d5080cc8c56fe0ecde8adb07992d78c [file] [log] [blame]
Chris Lattner4a106452002-12-23 23:50:16 +00001//===- Miscompilation.cpp - Debug program miscompilations -----------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
John Criswell7c0e0222003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner21c62da2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
John Criswell7c0e0222003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner4a106452002-12-23 23:50:16 +00009//
Chris Lattnera57d86b2004-04-05 22:58:16 +000010// This file implements optimizer and code generation miscompilation debugging
11// support.
Chris Lattner4a106452002-12-23 23:50:16 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "BugDriver.h"
Chris Lattner126840f2003-04-24 20:16:29 +000016#include "ListReducer.h"
Daniel Dunbarca740962009-08-18 03:35:57 +000017#include "ToolRunner.h"
Justin Bogner388e8b92016-09-02 01:21:37 +000018#include "llvm/Config/config.h" // for HAVE_LINK_R
Chandler Carruth0b8c9a82013-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 Carruth56e13942014-01-13 09:26:24 +000023#include "llvm/IR/Verifier.h"
Chandler Carruth8a67f122014-03-06 03:42:23 +000024#include "llvm/Linker/Linker.h"
Misha Brukmane49603d2003-08-07 21:19:30 +000025#include "llvm/Pass.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/FileUtilities.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000028#include "llvm/Transforms/Utils/Cloning.h"
Eugene Zelenko380d47d2016-02-02 18:20:45 +000029
Chris Lattnerfa761832004-01-14 03:38:37 +000030using namespace llvm;
Chris Lattner4a106452002-12-23 23:50:16 +000031
Chris Lattnera57d86b2004-04-05 22:58:16 +000032namespace llvm {
Justin Bogner388e8b92016-09-02 01:21:37 +000033extern cl::opt<std::string> OutputPrefix;
34extern cl::list<std::string> InputArgv;
Eugene Zelenko380d47d2016-02-02 18:20:45 +000035} // end namespace llvm
Chris Lattnera57d86b2004-04-05 22:58:16 +000036
Chris Lattnerefdc0b52004-03-14 20:50:42 +000037namespace {
Justin Bogner388e8b92016-09-02 01:21:37 +000038static llvm::cl::opt<bool> DisableLoopExtraction(
39 "disable-loop-extraction",
40 cl::desc("Don't extract loops when searching for miscompilations"),
41 cl::init(false));
42static llvm::cl::opt<bool> DisableBlockExtraction(
43 "disable-block-extraction",
44 cl::desc("Don't extract blocks when searching for miscompilations"),
45 cl::init(false));
Reid Spencerdc31a8a2006-11-11 19:05:02 +000046
Justin Bogner388e8b92016-09-02 01:21:37 +000047class ReduceMiscompilingPasses : public ListReducer<std::string> {
48 BugDriver &BD;
Misha Brukman3da94ae2005-04-22 00:00:37 +000049
Justin Bogner388e8b92016-09-02 01:21:37 +000050public:
Justin Bogner79a93a62016-09-06 04:45:37 +000051 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
Justin Bogner388e8b92016-09-02 01:21:37 +000052
Justin Bognerd8090ae2016-09-06 17:18:22 +000053 Expected<TestResult> doTest(std::vector<std::string> &Prefix,
54 std::vector<std::string> &Suffix) override;
Justin Bogner388e8b92016-09-02 01:21:37 +000055};
Eugene Zelenko380d47d2016-02-02 18:20:45 +000056} // end anonymous namespace
Chris Lattner640f22e2003-04-24 17:02:17 +000057
Misha Brukman8c194ea2004-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///
Justin Bognerd8090ae2016-09-06 17:18:22 +000061Expected<ReduceMiscompilingPasses::TestResult>
Rafael Espindola8261dfe2010-08-08 03:55:08 +000062ReduceMiscompilingPasses::doTest(std::vector<std::string> &Prefix,
Justin Bognerd8090ae2016-09-06 17:18:22 +000063 std::vector<std::string> &Suffix) {
Chris Lattner06943ad2003-04-25 03:16:05 +000064 // First, run the program with just the Suffix passes. If it is still broken
Chris Lattner640f22e2003-04-24 17:02:17 +000065 // with JUST the kept passes, discard the prefix passes.
Dan Gohmanac95cc72009-07-16 15:30:09 +000066 outs() << "Checking to see if '" << getPassesString(Suffix)
67 << "' compiles correctly: ";
Chris Lattner640f22e2003-04-24 17:02:17 +000068
Gabor Greif8ff70c22007-07-04 21:55:50 +000069 std::string BitcodeResult;
Justin Bogner388e8b92016-09-02 01:21:37 +000070 if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false /*delete*/,
71 true /*quiet*/)) {
Dan Gohman65f57c22009-07-15 16:35:29 +000072 errs() << " Error running this sequence of passes"
73 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +000074 BD.setPassesToRun(Suffix);
Justin Bogner388e8b92016-09-02 01:21:37 +000075 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
Justin Bognerd8090ae2016-09-06 17:18:22 +000076 // TODO: This should propagate the error instead of exiting.
77 if (Error E = BD.debugOptimizerCrash())
78 exit(1);
79 exit(0);
Chris Lattner640f22e2003-04-24 17:02:17 +000080 }
Michael J. Spencer56584fc2011-03-31 13:06:39 +000081
Chris Lattner640f22e2003-04-24 17:02:17 +000082 // Check to see if the finished program matches the reference output...
Justin Bognerd8090ae2016-09-06 17:18:22 +000083 Expected<bool> Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
84 true /*delete bitcode*/);
85 if (Error E = Diff.takeError())
86 return std::move(E);
87 if (*Diff) {
Dan Gohmanac95cc72009-07-16 15:30:09 +000088 outs() << " nope.\n";
Chris Lattner59615f02005-01-15 00:07:19 +000089 if (Suffix.empty()) {
Dan Gohman65f57c22009-07-15 16:35:29 +000090 errs() << BD.getToolName() << ": I'm confused: the test fails when "
91 << "no passes are run, nondeterministic program?\n";
Chris Lattner59615f02005-01-15 00:07:19 +000092 exit(1);
93 }
Justin Bogner388e8b92016-09-02 01:21:37 +000094 return KeepSuffix; // Miscompilation detected!
Chris Lattner640f22e2003-04-24 17:02:17 +000095 }
Justin Bogner388e8b92016-09-02 01:21:37 +000096 outs() << " yup.\n"; // No miscompilation!
Chris Lattner640f22e2003-04-24 17:02:17 +000097
Justin Bogner388e8b92016-09-02 01:21:37 +000098 if (Prefix.empty())
99 return NoFailure;
Chris Lattner640f22e2003-04-24 17:02:17 +0000100
Chris Lattner06943ad2003-04-25 03:16:05 +0000101 // Next, see if the program is broken if we run the "prefix" passes first,
Misha Brukmanbc0e9982003-07-14 17:20:40 +0000102 // then separately run the "kept" passes.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000103 outs() << "Checking to see if '" << getPassesString(Prefix)
104 << "' compiles correctly: ";
Chris Lattner640f22e2003-04-24 17:02:17 +0000105
106 // If it is not broken with the kept passes, it's possible that the prefix
107 // passes must be run before the kept passes to break it. If the program
108 // WORKS after the prefix passes, but then fails if running the prefix AND
Gabor Greif8ff70c22007-07-04 21:55:50 +0000109 // kept passes, we can update our bitcode file to include the result of the
Chris Lattner640f22e2003-04-24 17:02:17 +0000110 // prefix passes, then discard the prefix passes.
111 //
Justin Bogner388e8b92016-09-02 01:21:37 +0000112 if (BD.runPasses(BD.getProgram(), Prefix, BitcodeResult, false /*delete*/,
113 true /*quiet*/)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000114 errs() << " Error running this sequence of passes"
115 << " on the input program!\n";
Chris Lattner9c6cfe12003-10-17 23:03:16 +0000116 BD.setPassesToRun(Prefix);
Justin Bogner388e8b92016-09-02 01:21:37 +0000117 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
Justin Bognerd8090ae2016-09-06 17:18:22 +0000118 // TODO: This should propagate the error instead of exiting.
119 if (Error E = BD.debugOptimizerCrash())
120 exit(1);
121 exit(0);
Chris Lattner640f22e2003-04-24 17:02:17 +0000122 }
123
124 // If the prefix maintains the predicate by itself, only keep the prefix!
Justin Bognerd8090ae2016-09-06 17:18:22 +0000125 Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "", false);
126 if (Error E = Diff.takeError())
127 return std::move(E);
128 if (*Diff) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000129 outs() << " nope.\n";
Rafael Espindola74aec352013-06-17 21:50:28 +0000130 sys::fs::remove(BitcodeResult);
Chris Lattner640f22e2003-04-24 17:02:17 +0000131 return KeepPrefix;
132 }
Justin Bogner388e8b92016-09-02 01:21:37 +0000133 outs() << " yup.\n"; // No miscompilation!
Chris Lattner640f22e2003-04-24 17:02:17 +0000134
135 // Ok, so now we know that the prefix passes work, try running the suffix
136 // passes on the result of the prefix passes.
137 //
Rafael Espindola1bfd87a2014-08-26 17:19:03 +0000138 std::unique_ptr<Module> PrefixOutput =
139 parseInputFile(BitcodeResult, BD.getContext());
David Blaikie453f4f02013-05-15 07:36:59 +0000140 if (!PrefixOutput) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000141 errs() << BD.getToolName() << ": Error reading bitcode file '"
142 << BitcodeResult << "'!\n";
Chris Lattner640f22e2003-04-24 17:02:17 +0000143 exit(1);
144 }
Rafael Espindola74aec352013-06-17 21:50:28 +0000145 sys::fs::remove(BitcodeResult);
Chris Lattnerf4789e62004-04-23 20:36:51 +0000146
147 // Don't check if there are no passes in the suffix.
148 if (Suffix.empty())
149 return NoFailure;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000150
Dan Gohmanac95cc72009-07-16 15:30:09 +0000151 outs() << "Checking to see if '" << getPassesString(Suffix)
Justin Bogner388e8b92016-09-02 01:21:37 +0000152 << "' passes compile correctly after the '" << getPassesString(Prefix)
153 << "' passes: ";
Chris Lattner640f22e2003-04-24 17:02:17 +0000154
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000155 std::unique_ptr<Module> OriginalInput =
156 BD.swapProgramIn(std::move(PrefixOutput));
Justin Bogner388e8b92016-09-02 01:21:37 +0000157 if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false /*delete*/,
158 true /*quiet*/)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000159 errs() << " Error running this sequence of passes"
160 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +0000161 BD.setPassesToRun(Suffix);
Justin Bogner388e8b92016-09-02 01:21:37 +0000162 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
Justin Bognerd8090ae2016-09-06 17:18:22 +0000163 // TODO: This should propagate the error instead of exiting.
164 if (Error E = BD.debugOptimizerCrash())
165 exit(1);
166 exit(0);
Chris Lattner640f22e2003-04-24 17:02:17 +0000167 }
168
169 // Run the result...
Rafael Espindola10757dd2010-07-30 14:19:00 +0000170 Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
Justin Bognerd8090ae2016-09-06 17:18:22 +0000171 true /*delete bitcode*/);
172 if (Error E = Diff.takeError())
173 return std::move(E);
174 if (*Diff) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000175 outs() << " nope.\n";
Chris Lattner06943ad2003-04-25 03:16:05 +0000176 return KeepSuffix;
Chris Lattner640f22e2003-04-24 17:02:17 +0000177 }
178
179 // Otherwise, we must not be running the bad pass anymore.
Justin Bogner388e8b92016-09-02 01:21:37 +0000180 outs() << " yup.\n"; // No miscompilation!
Jeffrey Yasskin6865f292010-05-11 23:25:16 +0000181 // Restore orig program & free test.
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000182 BD.setNewProgram(std::move(OriginalInput));
Chris Lattner640f22e2003-04-24 17:02:17 +0000183 return NoFailure;
184}
185
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000186namespace {
Justin Bogner388e8b92016-09-02 01:21:37 +0000187class ReduceMiscompilingFunctions : public ListReducer<Function *> {
188 BugDriver &BD;
Justin Bognerd8090ae2016-09-06 17:18:22 +0000189 Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
190 std::unique_ptr<Module>);
Rafael Espindola0340a6f2015-12-09 00:51:06 +0000191
Justin Bogner388e8b92016-09-02 01:21:37 +0000192public:
193 ReduceMiscompilingFunctions(BugDriver &bd,
Justin Bognerd8090ae2016-09-06 17:18:22 +0000194 Expected<bool> (*F)(BugDriver &,
195 std::unique_ptr<Module>,
196 std::unique_ptr<Module>))
Justin Bogner79a93a62016-09-06 04:45:37 +0000197 : BD(bd), TestFn(F) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +0000198
Justin Bognerd8090ae2016-09-06 17:18:22 +0000199 Expected<TestResult> doTest(std::vector<Function *> &Prefix,
200 std::vector<Function *> &Suffix) override {
Justin Bogner388e8b92016-09-02 01:21:37 +0000201 if (!Suffix.empty()) {
Justin Bognerd8090ae2016-09-06 17:18:22 +0000202 Expected<bool> Ret = TestFuncs(Suffix);
203 if (Error E = Ret.takeError())
204 return std::move(E);
205 if (*Ret)
Justin Bogner388e8b92016-09-02 01:21:37 +0000206 return KeepSuffix;
Chris Lattnerfa761832004-01-14 03:38:37 +0000207 }
Justin Bogner388e8b92016-09-02 01:21:37 +0000208 if (!Prefix.empty()) {
Justin Bognerd8090ae2016-09-06 17:18:22 +0000209 Expected<bool> Ret = TestFuncs(Prefix);
210 if (Error E = Ret.takeError())
211 return std::move(E);
212 if (*Ret)
Justin Bogner388e8b92016-09-02 01:21:37 +0000213 return KeepPrefix;
214 }
215 return NoFailure;
216 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000217
Justin Bognerd8090ae2016-09-06 17:18:22 +0000218 Expected<bool> TestFuncs(const std::vector<Function *> &Prefix);
Justin Bogner388e8b92016-09-02 01:21:37 +0000219};
Eugene Zelenko380d47d2016-02-02 18:20:45 +0000220} // end anonymous namespace
Chris Lattner640f22e2003-04-24 17:02:17 +0000221
Rafael Espindolabdc3e4d2015-12-09 00:55:05 +0000222/// Given two modules, link them together and run the program, checking to see
223/// if the program matches the diff. If there is an error, return NULL. If not,
224/// return the merged module. The Broken argument will be set to true if the
225/// output is different. If the DeleteInputs argument is set to true then this
226/// function deletes both input modules before it returns.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000227///
Bryant Wong062224c2017-04-05 22:23:48 +0000228static Expected<std::unique_ptr<Module>> testMergedProgram(const BugDriver &BD,
229 const Module &M1,
230 const Module &M2,
231 bool &Broken) {
232 // Resulting merge of M1 and M2.
Rafael Espindola22b77242018-02-14 19:50:40 +0000233 auto Merged = CloneModule(M1);
234 if (Linker::linkModules(*Merged, CloneModule(M2)))
Justin Bognerd8090ae2016-09-06 17:18:22 +0000235 // TODO: Shouldn't we thread the error up instead of exiting?
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000236 exit(1);
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000237
Rafael Espindola13793262010-07-31 14:34:49 +0000238 // Execute the program.
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000239 Expected<bool> Diff = BD.diffProgram(*Merged, "", "", false);
Justin Bognerd8090ae2016-09-06 17:18:22 +0000240 if (Error E = Diff.takeError())
241 return std::move(E);
242 Broken = *Diff;
Bryant Wong062224c2017-04-05 22:23:48 +0000243 return std::move(Merged);
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000244}
245
Rafael Espindolad86697c2018-02-14 21:10:29 +0000246/// split functions in a Module into two groups: those that are under
247/// consideration for miscompilation vs. those that are not, and test
Misha Brukman8c194ea2004-04-21 18:36:43 +0000248/// accordingly. Each group of functions becomes a separate Module.
Justin Bognerd8090ae2016-09-06 17:18:22 +0000249Expected<bool>
250ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function *> &Funcs) {
Chris Lattner640f22e2003-04-24 17:02:17 +0000251 // Test to see if the function is misoptimized if we ONLY run it on the
252 // functions listed in Funcs.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000253 outs() << "Checking to see if the program is misoptimized when "
Justin Bogner388e8b92016-09-02 01:21:37 +0000254 << (Funcs.size() == 1 ? "this function is" : "these functions are")
Dan Gohmanac95cc72009-07-16 15:30:09 +0000255 << " run through the pass"
256 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000257 PrintFunctionList(Funcs);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000258 outs() << '\n';
Chris Lattner640f22e2003-04-24 17:02:17 +0000259
Rafael Espindola84ae2062010-07-26 00:07:51 +0000260 // Create a clone for two reasons:
261 // * If the optimization passes delete any function, the deleted function
262 // will be in the clone and Funcs will still point to valid memory
263 // * If the optimization passes use interprocedural information to break
264 // a function, we want to continue with the original function. Otherwise
265 // we can conclude that a function triggers the bug when in fact one
266 // needs a larger set of original functions to do so.
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000267 ValueToValueMapTy VMap;
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000268 std::unique_ptr<Module> Clone = CloneModule(BD.getProgram(), VMap);
269 std::unique_ptr<Module> Orig = BD.swapProgramIn(std::move(Clone));
Rafael Espindola84ae2062010-07-26 00:07:51 +0000270
Justin Bogner388e8b92016-09-02 01:21:37 +0000271 std::vector<Function *> FuncsOnClone;
Rafael Espindola84ae2062010-07-26 00:07:51 +0000272 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
273 Function *F = cast<Function>(VMap[Funcs[i]]);
274 FuncsOnClone.push_back(F);
275 }
276
277 // Split the module into the two halves of the program we want.
278 VMap.clear();
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000279 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
Rafael Espindola0340a6f2015-12-09 00:51:06 +0000280 std::unique_ptr<Module> ToOptimize =
281 SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
Chris Lattner640f22e2003-04-24 17:02:17 +0000282
Justin Bognerd8090ae2016-09-06 17:18:22 +0000283 Expected<bool> Broken =
284 TestFn(BD, std::move(ToOptimize), std::move(ToNotOptimize));
Rafael Espindola84ae2062010-07-26 00:07:51 +0000285
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000286 BD.setNewProgram(std::move(Orig));
Rafael Espindola84ae2062010-07-26 00:07:51 +0000287
288 return Broken;
Chris Lattner640f22e2003-04-24 17:02:17 +0000289}
290
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000291/// Give anonymous global values names.
292static void DisambiguateGlobalSymbols(Module &M) {
293 for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E;
294 ++I)
Chris Lattner8abfb8a2010-01-16 21:34:01 +0000295 if (!I->hasName())
296 I->setName("anon_global");
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000297 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
Chris Lattner8abfb8a2010-01-16 21:34:01 +0000298 if (!I->hasName())
299 I->setName("anon_fn");
Chris Lattner36ee07f2004-04-11 23:52:35 +0000300}
301
Rafael Espindola0340a6f2015-12-09 00:51:06 +0000302/// Given a reduced list of functions that still exposed the bug, check to see
303/// if we can extract the loops in the region without obscuring the bug. If so,
304/// it reduces the amount of code identified.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000305///
Justin Bognerd8090ae2016-09-06 17:18:22 +0000306static Expected<bool>
307ExtractLoops(BugDriver &BD,
308 Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
309 std::unique_ptr<Module>),
310 std::vector<Function *> &MiscompiledFunctions) {
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000311 bool MadeChange = false;
312 while (1) {
Justin Bogner388e8b92016-09-02 01:21:37 +0000313 if (BugpointIsInterrupted)
314 return MadeChange;
Michael J. Spencer56584fc2011-03-31 13:06:39 +0000315
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000316 ValueToValueMapTy VMap;
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000317 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
Rafael Espindolaf96e6492018-02-14 21:17:36 +0000318 std::unique_ptr<Module> ToOptimize = SplitFunctionsOutOfModule(
319 ToNotOptimize.get(), MiscompiledFunctions, VMap);
Rafael Espindola5d88a3e2015-12-09 00:08:22 +0000320 std::unique_ptr<Module> ToOptimizeLoopExtracted =
Rafael Espindolaf96e6492018-02-14 21:17:36 +0000321 BD.extractLoop(ToOptimize.get());
322 if (!ToOptimizeLoopExtracted)
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000323 // If the loop extractor crashed or if there were no extractible loops,
324 // then this chapter of our odyssey is over with.
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000325 return MadeChange;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000326
Dan Gohman65f57c22009-07-15 16:35:29 +0000327 errs() << "Extracted a loop from the breaking portion of the program.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000328
329 // Bugpoint is intentionally not very trusting of LLVM transformations. In
330 // particular, we're not going to assume that the loop extractor works, so
331 // we're going to test the newly loop extracted program to make sure nothing
332 // has broken. If something broke, then we'll inform the user and stop
333 // extraction.
Dan Gohman70ef4492008-12-08 04:02:47 +0000334 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
Rafael Espindola13793262010-07-31 14:34:49 +0000335 bool Failure;
Bryant Wong062224c2017-04-05 22:23:48 +0000336 Expected<std::unique_ptr<Module>> New = testMergedProgram(
337 BD, *ToOptimizeLoopExtracted, *ToNotOptimize, Failure);
Justin Bognerd8090ae2016-09-06 17:18:22 +0000338 if (Error E = New.takeError())
339 return std::move(E);
340 if (!*New)
Nick Lewycky22ff7482010-04-12 05:08:25 +0000341 return false;
Hal Finkele8bc7002013-08-02 21:13:42 +0000342
Rafael Espindola13793262010-07-31 14:34:49 +0000343 // Delete the original and set the new program.
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000344 std::unique_ptr<Module> Old = BD.swapProgramIn(std::move(*New));
Hal Finkele8bc7002013-08-02 21:13:42 +0000345 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
346 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
Hal Finkele8bc7002013-08-02 21:13:42 +0000347
Nick Lewycky22ff7482010-04-12 05:08:25 +0000348 if (Failure) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000349 BD.switchToInterpreter(AI);
350
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000351 // Merged program doesn't work anymore!
Dan Gohman65f57c22009-07-15 16:35:29 +0000352 errs() << " *** ERROR: Loop extraction broke the program. :("
353 << " Please report a bug!\n";
354 errs() << " Continuing on with un-loop-extracted version.\n";
Chris Lattner56c41862005-05-08 21:54:56 +0000355
Daniel Dunbar68ccdaa2009-09-07 19:26:11 +0000356 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000357 *ToNotOptimize);
Daniel Dunbar68ccdaa2009-09-07 19:26:11 +0000358 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000359 *ToOptimize);
Daniel Dunbar68ccdaa2009-09-07 19:26:11 +0000360 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000361 *ToOptimizeLoopExtracted);
Chris Lattner56c41862005-05-08 21:54:56 +0000362
Justin Bogner388e8b92016-09-02 01:21:37 +0000363 errs() << "Please submit the " << OutputPrefix
364 << "-loop-extract-fail-*.bc files.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000365 return MadeChange;
366 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000367 BD.switchToInterpreter(AI);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000368
Dan Gohmanac95cc72009-07-16 15:30:09 +0000369 outs() << " Testing after loop extraction:\n";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000370 // Clone modules, the tester function will free them.
Rafael Espindola5d88a3e2015-12-09 00:08:22 +0000371 std::unique_ptr<Module> TOLEBackup =
Rafael Espindola22b77242018-02-14 19:50:40 +0000372 CloneModule(*ToOptimizeLoopExtracted, VMap);
373 std::unique_ptr<Module> TNOBackup = CloneModule(*ToNotOptimize, VMap);
Hal Finkele8bc7002013-08-02 21:13:42 +0000374
375 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
376 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
377
Justin Bognerd8090ae2016-09-06 17:18:22 +0000378 Expected<bool> Result = TestFn(BD, std::move(ToOptimizeLoopExtracted),
379 std::move(ToNotOptimize));
380 if (Error E = Result.takeError())
381 return std::move(E);
Hal Finkele8bc7002013-08-02 21:13:42 +0000382
Rafael Espindola5d88a3e2015-12-09 00:08:22 +0000383 ToOptimizeLoopExtracted = std::move(TOLEBackup);
Rafael Espindola4ed1f8c2015-12-09 00:18:41 +0000384 ToNotOptimize = std::move(TNOBackup);
Hal Finkele8bc7002013-08-02 21:13:42 +0000385
Justin Bognerd8090ae2016-09-06 17:18:22 +0000386 if (!*Result) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000387 outs() << "*** Loop extraction masked the problem. Undoing.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000388 // If the program is not still broken, then loop extraction did something
389 // that masked the error. Stop loop extraction now.
Hal Finkele8bc7002013-08-02 21:13:42 +0000390
Justin Bogner388e8b92016-09-02 01:21:37 +0000391 std::vector<std::pair<std::string, FunctionType *>> MisCompFunctions;
Benjamin Kramer9589ff82015-05-29 19:43:39 +0000392 for (Function *F : MiscompiledFunctions) {
393 MisCompFunctions.emplace_back(F->getName(), F->getFunctionType());
Hal Finkele8bc7002013-08-02 21:13:42 +0000394 }
395
Rafael Espindolad912be92015-12-16 23:16:33 +0000396 if (Linker::linkModules(*ToNotOptimize,
397 std::move(ToOptimizeLoopExtracted)))
Hal Finkele8bc7002013-08-02 21:13:42 +0000398 exit(1);
Hal Finkele8bc7002013-08-02 21:13:42 +0000399
400 MiscompiledFunctions.clear();
401 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
402 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
403
404 assert(NewF && "Function not found??");
405 MiscompiledFunctions.push_back(NewF);
406 }
407
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000408 BD.setNewProgram(std::move(ToNotOptimize));
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000409 return MadeChange;
410 }
Chris Lattnerb15825b2004-04-05 21:37:38 +0000411
Dan Gohmanac95cc72009-07-16 15:30:09 +0000412 outs() << "*** Loop extraction successful!\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000413
Justin Bogner388e8b92016-09-02 01:21:37 +0000414 std::vector<std::pair<std::string, FunctionType *>> MisCompFunctions;
Chris Lattner90c18c52004-11-16 06:31:38 +0000415 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
Justin Bogner388e8b92016-09-02 01:21:37 +0000416 E = ToOptimizeLoopExtracted->end();
417 I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +0000418 if (!I->isDeclaration())
Benjamin Kramer9589ff82015-05-29 19:43:39 +0000419 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
Chris Lattner90c18c52004-11-16 06:31:38 +0000420
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000421 // Okay, great! Now we know that we extracted a loop and that loop
422 // extraction both didn't break the program, and didn't mask the problem.
423 // Replace the current program with the loop extracted version, and try to
424 // extract another loop.
Rafael Espindolad912be92015-12-16 23:16:33 +0000425 if (Linker::linkModules(*ToNotOptimize, std::move(ToOptimizeLoopExtracted)))
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000426 exit(1);
Rafael Espindola72478e52014-10-25 04:06:10 +0000427
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000428 // All of the Function*'s in the MiscompiledFunctions list are in the old
Chris Lattner5313f232004-04-02 06:32:17 +0000429 // module. Update this list to include all of the functions in the
430 // optimized and loop extracted module.
431 MiscompiledFunctions.clear();
Chris Lattner90c18c52004-11-16 06:31:38 +0000432 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spenceref9b9a72007-02-05 20:47:22 +0000433 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
Michael J. Spencer56584fc2011-03-31 13:06:39 +0000434
Chris Lattner90c18c52004-11-16 06:31:38 +0000435 assert(NewF && "Function not found??");
436 MiscompiledFunctions.push_back(NewF);
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000437 }
438
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000439 BD.setNewProgram(std::move(ToNotOptimize));
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000440 MadeChange = true;
441 }
442}
443
Chris Lattner5e783ab2004-05-11 21:54:13 +0000444namespace {
Justin Bogner388e8b92016-09-02 01:21:37 +0000445class ReduceMiscompiledBlocks : public ListReducer<BasicBlock *> {
446 BugDriver &BD;
Justin Bognerd8090ae2016-09-06 17:18:22 +0000447 Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
448 std::unique_ptr<Module>);
Justin Bogner388e8b92016-09-02 01:21:37 +0000449 std::vector<Function *> FunctionsBeingTested;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000450
Justin Bogner388e8b92016-09-02 01:21:37 +0000451public:
452 ReduceMiscompiledBlocks(BugDriver &bd,
Justin Bognerd8090ae2016-09-06 17:18:22 +0000453 Expected<bool> (*F)(BugDriver &,
454 std::unique_ptr<Module>,
455 std::unique_ptr<Module>),
Justin Bogner79a93a62016-09-06 04:45:37 +0000456 const std::vector<Function *> &Fns)
457 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
Justin Bogner388e8b92016-09-02 01:21:37 +0000458
Justin Bognerd8090ae2016-09-06 17:18:22 +0000459 Expected<TestResult> doTest(std::vector<BasicBlock *> &Prefix,
460 std::vector<BasicBlock *> &Suffix) override {
Justin Bogner388e8b92016-09-02 01:21:37 +0000461 if (!Suffix.empty()) {
Justin Bognerd8090ae2016-09-06 17:18:22 +0000462 Expected<bool> Ret = TestFuncs(Suffix);
463 if (Error E = Ret.takeError())
464 return std::move(E);
465 if (*Ret)
Justin Bogner388e8b92016-09-02 01:21:37 +0000466 return KeepSuffix;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000467 }
Justin Bogner388e8b92016-09-02 01:21:37 +0000468 if (!Prefix.empty()) {
Justin Bognerd8090ae2016-09-06 17:18:22 +0000469 Expected<bool> Ret = TestFuncs(Prefix);
470 if (Error E = Ret.takeError())
471 return std::move(E);
472 if (*Ret)
Justin Bogner388e8b92016-09-02 01:21:37 +0000473 return KeepPrefix;
474 }
475 return NoFailure;
476 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000477
Justin Bognerd8090ae2016-09-06 17:18:22 +0000478 Expected<bool> TestFuncs(const std::vector<BasicBlock *> &BBs);
Justin Bogner388e8b92016-09-02 01:21:37 +0000479};
Eugene Zelenko380d47d2016-02-02 18:20:45 +0000480} // end anonymous namespace
Chris Lattner5e783ab2004-05-11 21:54:13 +0000481
482/// TestFuncs - Extract all blocks for the miscompiled functions except for the
483/// specified blocks. If the problem still exists, return true.
484///
Justin Bognerd8090ae2016-09-06 17:18:22 +0000485Expected<bool>
486ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock *> &BBs) {
Chris Lattner5e783ab2004-05-11 21:54:13 +0000487 // Test to see if the function is misoptimized if we ONLY run it on the
488 // functions listed in Funcs.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000489 outs() << "Checking to see if the program is misoptimized when all ";
Chris Lattner68bee932004-05-12 16:08:01 +0000490 if (!BBs.empty()) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000491 outs() << "but these " << BBs.size() << " blocks are extracted: ";
Chris Lattner68bee932004-05-12 16:08:01 +0000492 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000493 outs() << BBs[i]->getName() << " ";
Justin Bogner388e8b92016-09-02 01:21:37 +0000494 if (BBs.size() > 10)
495 outs() << "...";
Chris Lattner68bee932004-05-12 16:08:01 +0000496 } else {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000497 outs() << "blocks are extracted.";
Chris Lattner68bee932004-05-12 16:08:01 +0000498 }
Dan Gohmanac95cc72009-07-16 15:30:09 +0000499 outs() << '\n';
Chris Lattner5e783ab2004-05-11 21:54:13 +0000500
501 // Split the module into the two halves of the program we want.
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000502 ValueToValueMapTy VMap;
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000503 std::unique_ptr<Module> Clone = CloneModule(BD.getProgram(), VMap);
504 std::unique_ptr<Module> Orig = BD.swapProgramIn(std::move(Clone));
Justin Bogner388e8b92016-09-02 01:21:37 +0000505 std::vector<Function *> FuncsOnClone;
506 std::vector<BasicBlock *> BBsOnClone;
Rafael Espindola115a9322010-07-29 14:20:59 +0000507 for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
508 Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
509 FuncsOnClone.push_back(F);
510 }
511 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
512 BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
513 BBsOnClone.push_back(BB);
514 }
515 VMap.clear();
516
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000517 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
Rafael Espindola0340a6f2015-12-09 00:51:06 +0000518 std::unique_ptr<Module> ToOptimize =
519 SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000520
521 // Try the extraction. If it doesn't work, then the block extractor crashed
522 // or something, in which case bugpoint can't chase down this possibility.
Rafael Espindola1bfd87a2014-08-26 17:19:03 +0000523 if (std::unique_ptr<Module> New =
Rafael Espindola0340a6f2015-12-09 00:51:06 +0000524 BD.extractMappedBlocksFromModule(BBsOnClone, ToOptimize.get())) {
Justin Bognerd8090ae2016-09-06 17:18:22 +0000525 Expected<bool> Ret = TestFn(BD, std::move(New), std::move(ToNotOptimize));
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000526 BD.setNewProgram(std::move(Orig));
Rafael Espindola115a9322010-07-29 14:20:59 +0000527 return Ret;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000528 }
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000529 BD.setNewProgram(std::move(Orig));
Chris Lattner5e783ab2004-05-11 21:54:13 +0000530 return false;
531}
532
Rafael Espindola0340a6f2015-12-09 00:51:06 +0000533/// Given a reduced list of functions that still expose the bug, extract as many
534/// basic blocks from the region as possible without obscuring the bug.
Chris Lattner5e783ab2004-05-11 21:54:13 +0000535///
Justin Bognerd8090ae2016-09-06 17:18:22 +0000536static Expected<bool>
537ExtractBlocks(BugDriver &BD,
538 Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
539 std::unique_ptr<Module>),
540 std::vector<Function *> &MiscompiledFunctions) {
Justin Bogner388e8b92016-09-02 01:21:37 +0000541 if (BugpointIsInterrupted)
542 return false;
Michael J. Spencer56584fc2011-03-31 13:06:39 +0000543
Justin Bogner388e8b92016-09-02 01:21:37 +0000544 std::vector<BasicBlock *> Blocks;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000545 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
Duncan P. N. Exon Smith1e221d52015-10-20 19:36:39 +0000546 for (BasicBlock &BB : *MiscompiledFunctions[i])
547 Blocks.push_back(&BB);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000548
549 // Use the list reducer to identify blocks that can be extracted without
550 // obscuring the bug. The Blocks list will end up containing blocks that must
551 // be retained from the original program.
552 unsigned OldSize = Blocks.size();
Chris Lattner68bee932004-05-12 16:08:01 +0000553
554 // Check to see if all blocks are extractible first.
Justin Bognerd8090ae2016-09-06 17:18:22 +0000555 Expected<bool> Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
556 .TestFuncs(std::vector<BasicBlock *>());
557 if (Error E = Ret.takeError())
558 return std::move(E);
559 if (*Ret) {
Chris Lattner68bee932004-05-12 16:08:01 +0000560 Blocks.clear();
561 } else {
Justin Bognerd8090ae2016-09-06 17:18:22 +0000562 Expected<bool> Ret =
563 ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
564 .reduceList(Blocks);
565 if (Error E = Ret.takeError())
566 return std::move(E);
Chris Lattner68bee932004-05-12 16:08:01 +0000567 if (Blocks.size() == OldSize)
568 return false;
569 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000570
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000571 ValueToValueMapTy VMap;
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000572 std::unique_ptr<Module> ProgClone = CloneModule(BD.getProgram(), VMap);
Rafael Espindolac80da492018-02-14 20:13:01 +0000573 std::unique_ptr<Module> ToExtract =
574 SplitFunctionsOutOfModule(ProgClone.get(), MiscompiledFunctions, VMap);
Rafael Espindola1bfd87a2014-08-26 17:19:03 +0000575 std::unique_ptr<Module> Extracted =
Rafael Espindolac80da492018-02-14 20:13:01 +0000576 BD.extractMappedBlocksFromModule(Blocks, ToExtract.get());
Craig Topper573faec2014-04-25 04:24:47 +0000577 if (!Extracted) {
Chris Lattnerda895d62005-02-27 06:18:25 +0000578 // Weird, extraction should have worked.
Dan Gohman65f57c22009-07-15 16:35:29 +0000579 errs() << "Nondeterministic problem extracting blocks??\n";
Chris Lattner2290e752004-05-12 02:43:24 +0000580 return false;
581 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000582
Chris Lattner2290e752004-05-12 02:43:24 +0000583 // Otherwise, block extraction succeeded. Link the two program fragments back
584 // together.
Chris Lattner5e783ab2004-05-11 21:54:13 +0000585
Justin Bogner388e8b92016-09-02 01:21:37 +0000586 std::vector<std::pair<std::string, FunctionType *>> MisCompFunctions;
587 for (Module::iterator I = Extracted->begin(), E = Extracted->end(); I != E;
588 ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +0000589 if (!I->isDeclaration())
Benjamin Kramer9589ff82015-05-29 19:43:39 +0000590 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
Chris Lattner90c18c52004-11-16 06:31:38 +0000591
Rafael Espindolad912be92015-12-16 23:16:33 +0000592 if (Linker::linkModules(*ProgClone, std::move(Extracted)))
Chris Lattner2290e752004-05-12 02:43:24 +0000593 exit(1);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000594
Chris Lattner2290e752004-05-12 02:43:24 +0000595 // Set the new program and delete the old one.
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000596 BD.setNewProgram(std::move(ProgClone));
Chris Lattner5e783ab2004-05-11 21:54:13 +0000597
Chris Lattner2290e752004-05-12 02:43:24 +0000598 // Update the list of miscompiled functions.
599 MiscompiledFunctions.clear();
Chris Lattner5e783ab2004-05-11 21:54:13 +0000600
Chris Lattner90c18c52004-11-16 06:31:38 +0000601 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spenceref9b9a72007-02-05 20:47:22 +0000602 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
Chris Lattner90c18c52004-11-16 06:31:38 +0000603 assert(NewF && "Function not found??");
604 MiscompiledFunctions.push_back(NewF);
605 }
Chris Lattner2290e752004-05-12 02:43:24 +0000606
607 return true;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000608}
609
Rafael Espindola0340a6f2015-12-09 00:51:06 +0000610/// This is a generic driver to narrow down miscompilations, either in an
611/// optimization or a code generator.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000612///
Justin Bognerd8090ae2016-09-06 17:18:22 +0000613static Expected<std::vector<Function *>> DebugAMiscompilation(
614 BugDriver &BD,
615 Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
616 std::unique_ptr<Module>)) {
Chris Lattnerb15825b2004-04-05 21:37:38 +0000617 // Okay, now that we have reduced the list of passes which are causing the
618 // failure, see if we can pin down which functions are being
619 // miscompiled... first build a list of all of the non-external functions in
620 // the program.
Justin Bogner388e8b92016-09-02 01:21:37 +0000621 std::vector<Function *> MiscompiledFunctions;
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000622 Module &Prog = BD.getProgram();
623 for (Function &F : Prog)
Duncan P. N. Exon Smith1e221d52015-10-20 19:36:39 +0000624 if (!F.isDeclaration())
625 MiscompiledFunctions.push_back(&F);
Chris Lattnerb15825b2004-04-05 21:37:38 +0000626
627 // Do the reduction...
Justin Bognerd8090ae2016-09-06 17:18:22 +0000628 if (!BugpointIsInterrupted) {
629 Expected<bool> Ret = ReduceMiscompilingFunctions(BD, TestFn)
630 .reduceList(MiscompiledFunctions);
631 if (Error E = Ret.takeError()) {
632 errs() << "\n***Cannot reduce functions: ";
633 return std::move(E);
634 }
Andrew Trick7c863eb2011-05-11 16:31:24 +0000635 }
Dan Gohmanac95cc72009-07-16 15:30:09 +0000636 outs() << "\n*** The following function"
637 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
638 << " being miscompiled: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000639 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000640 outs() << '\n';
Chris Lattnerb15825b2004-04-05 21:37:38 +0000641
642 // See if we can rip any loops out of the miscompiled functions and still
643 // trigger the problem.
Reid Spencerdc31a8a2006-11-11 19:05:02 +0000644
Nick Lewycky22ff7482010-04-12 05:08:25 +0000645 if (!BugpointIsInterrupted && !DisableLoopExtraction) {
Justin Bognerd8090ae2016-09-06 17:18:22 +0000646 Expected<bool> Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions);
647 if (Error E = Ret.takeError())
648 return std::move(E);
649 if (*Ret) {
Nick Lewycky22ff7482010-04-12 05:08:25 +0000650 // Okay, we extracted some loops and the problem still appears. See if
651 // we can eliminate some of the created functions from being candidates.
652 DisambiguateGlobalSymbols(BD.getProgram());
Chris Lattner36ee07f2004-04-11 23:52:35 +0000653
Nick Lewycky22ff7482010-04-12 05:08:25 +0000654 // Do the reduction...
655 if (!BugpointIsInterrupted)
Justin Bognerd8090ae2016-09-06 17:18:22 +0000656 Ret = ReduceMiscompilingFunctions(BD, TestFn)
657 .reduceList(MiscompiledFunctions);
658 if (Error E = Ret.takeError())
659 return std::move(E);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000660
Nick Lewycky22ff7482010-04-12 05:08:25 +0000661 outs() << "\n*** The following function"
662 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
663 << " being miscompiled: ";
664 PrintFunctionList(MiscompiledFunctions);
665 outs() << '\n';
666 }
Chris Lattnerb15825b2004-04-05 21:37:38 +0000667 }
668
Nick Lewycky22ff7482010-04-12 05:08:25 +0000669 if (!BugpointIsInterrupted && !DisableBlockExtraction) {
Justin Bognerd8090ae2016-09-06 17:18:22 +0000670 Expected<bool> Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions);
671 if (Error E = Ret.takeError())
672 return std::move(E);
673 if (*Ret) {
Nick Lewycky22ff7482010-04-12 05:08:25 +0000674 // Okay, we extracted some blocks and the problem still appears. See if
675 // we can eliminate some of the created functions from being candidates.
676 DisambiguateGlobalSymbols(BD.getProgram());
Chris Lattner5e783ab2004-05-11 21:54:13 +0000677
Nick Lewycky22ff7482010-04-12 05:08:25 +0000678 // Do the reduction...
Justin Bognerd8090ae2016-09-06 17:18:22 +0000679 Ret = ReduceMiscompilingFunctions(BD, TestFn)
680 .reduceList(MiscompiledFunctions);
681 if (Error E = Ret.takeError())
682 return std::move(E);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000683
Nick Lewycky22ff7482010-04-12 05:08:25 +0000684 outs() << "\n*** The following function"
685 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
686 << " being miscompiled: ";
687 PrintFunctionList(MiscompiledFunctions);
688 outs() << '\n';
689 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000690 }
691
Chris Lattnerb15825b2004-04-05 21:37:38 +0000692 return MiscompiledFunctions;
693}
694
Rafael Espindola0340a6f2015-12-09 00:51:06 +0000695/// This is the predicate function used to check to see if the "Test" portion of
696/// the program is misoptimized. If so, return true. In any case, both module
697/// arguments are deleted.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000698///
Justin Bognerd8090ae2016-09-06 17:18:22 +0000699static Expected<bool> TestOptimizer(BugDriver &BD, std::unique_ptr<Module> Test,
700 std::unique_ptr<Module> Safe) {
Chris Lattnerb15825b2004-04-05 21:37:38 +0000701 // Run the optimization passes on ToOptimize, producing a transformed version
702 // of the functions being tested.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000703 outs() << " Optimizing functions being tested: ";
Rafael Espindola0340a6f2015-12-09 00:51:06 +0000704 std::unique_ptr<Module> Optimized =
Philip Reames34618d92016-06-29 00:26:21 +0000705 BD.runPassesOn(Test.get(), BD.getPassesToRun());
706 if (!Optimized) {
707 errs() << " Error running this sequence of passes"
708 << " on the input program!\n";
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000709 BD.setNewProgram(std::move(Test));
710 BD.EmitProgressBitcode(*Test, "pass-error", false);
Justin Bognerd8090ae2016-09-06 17:18:22 +0000711 if (Error E = BD.debugOptimizerCrash())
712 return std::move(E);
713 return false;
Philip Reames34618d92016-06-29 00:26:21 +0000714 }
Dan Gohmanac95cc72009-07-16 15:30:09 +0000715 outs() << "done.\n";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000716
Dan Gohmanac95cc72009-07-16 15:30:09 +0000717 outs() << " Checking to see if the merged program executes correctly: ";
Rafael Espindola13793262010-07-31 14:34:49 +0000718 bool Broken;
Bryant Wong062224c2017-04-05 22:23:48 +0000719 auto Result = testMergedProgram(BD, *Optimized, *Safe, Broken);
Justin Bognerd8090ae2016-09-06 17:18:22 +0000720 if (Error E = Result.takeError())
721 return std::move(E);
722 if (auto New = std::move(*Result)) {
Rafael Espindola13793262010-07-31 14:34:49 +0000723 outs() << (Broken ? " nope.\n" : " yup.\n");
724 // Delete the original and set the new program.
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000725 BD.setNewProgram(std::move(New));
Rafael Espindola13793262010-07-31 14:34:49 +0000726 }
Chris Lattnerb15825b2004-04-05 21:37:38 +0000727 return Broken;
728}
729
Chris Lattner4a106452002-12-23 23:50:16 +0000730/// debugMiscompilation - This method is used when the passes selected are not
731/// crashing, but the generated output is semantically different from the
732/// input.
733///
Justin Bognerd8090ae2016-09-06 17:18:22 +0000734Error BugDriver::debugMiscompilation() {
Chris Lattner4a106452002-12-23 23:50:16 +0000735 // Make sure something was miscompiled...
Justin Bognerd8090ae2016-09-06 17:18:22 +0000736 if (!BugpointIsInterrupted) {
737 Expected<bool> Result =
738 ReduceMiscompilingPasses(*this).reduceList(PassesToRun);
739 if (Error E = Result.takeError())
740 return E;
741 if (!*Result)
742 return make_error<StringError>(
743 "*** Optimized program matches reference output! No problem"
744 " detected...\nbugpoint can't help you with your problem!\n",
745 inconvertibleErrorCode());
746 }
Chris Lattner4a106452002-12-23 23:50:16 +0000747
Dan Gohmanac95cc72009-07-16 15:30:09 +0000748 outs() << "\n*** Found miscompiling pass"
749 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
750 << getPassesString(getPassesToRun()) << '\n';
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000751 EmitProgressBitcode(*Program, "passinput");
Chris Lattner4a106452002-12-23 23:50:16 +0000752
Justin Bognerd8090ae2016-09-06 17:18:22 +0000753 Expected<std::vector<Function *>> MiscompiledFunctions =
754 DebugAMiscompilation(*this, TestOptimizer);
755 if (Error E = MiscompiledFunctions.takeError())
756 return E;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000757
Gabor Greif8ff70c22007-07-04 21:55:50 +0000758 // Output a bunch of bitcode files for the user...
Dan Gohmanac95cc72009-07-16 15:30:09 +0000759 outs() << "Outputting reduced bitcode files which expose the problem:\n";
Rafael Espindola1ed219a2010-10-13 01:36:30 +0000760 ValueToValueMapTy VMap;
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000761 Module *ToNotOptimize = CloneModule(getProgram(), VMap).release();
Rafael Espindola18d70502015-12-09 00:34:10 +0000762 Module *ToOptimize =
Justin Bognerd8090ae2016-09-06 17:18:22 +0000763 SplitFunctionsOutOfModule(ToNotOptimize, *MiscompiledFunctions, VMap)
Rafael Espindola18d70502015-12-09 00:34:10 +0000764 .release();
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000765
Dan Gohmanac95cc72009-07-16 15:30:09 +0000766 outs() << " Non-optimized portion: ";
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000767 EmitProgressBitcode(*ToNotOptimize, "tonotoptimize", true);
Justin Bogner388e8b92016-09-02 01:21:37 +0000768 delete ToNotOptimize; // Delete hacked module.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000769
Dan Gohmanac95cc72009-07-16 15:30:09 +0000770 outs() << " Portion that is input to optimizer: ";
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000771 EmitProgressBitcode(*ToOptimize, "tooptimize");
Justin Bogner388e8b92016-09-02 01:21:37 +0000772 delete ToOptimize; // Delete hacked module.
Justin Bognerd8090ae2016-09-06 17:18:22 +0000773
774 return Error::success();
Chris Lattner4a106452002-12-23 23:50:16 +0000775}
Brian Gaeked0fde302003-11-11 22:41:34 +0000776
Rafael Espindola0340a6f2015-12-09 00:51:06 +0000777/// Get the specified modules ready for code generator testing.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000778///
Rafael Espindola46e55022018-04-24 20:15:27 +0000779static std::unique_ptr<Module>
780CleanupAndPrepareModules(BugDriver &BD, std::unique_ptr<Module> Test,
781 Module *Safe) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000782 // Clean up the modules, removing extra cruft that we don't need anymore...
Rafael Espindola46e55022018-04-24 20:15:27 +0000783 Test = BD.performFinalCleanups(std::move(Test));
Chris Lattnera57d86b2004-04-05 22:58:16 +0000784
785 // If we are executing the JIT, we have several nasty issues to take care of.
Justin Bogner388e8b92016-09-02 01:21:37 +0000786 if (!BD.isExecutingJIT())
Rafael Espindola46e55022018-04-24 20:15:27 +0000787 return Test;
Chris Lattnera57d86b2004-04-05 22:58:16 +0000788
789 // First, if the main function is in the Safe module, we must add a stub to
790 // the Test module to call into it. Thus, we create a new function `main'
791 // which just calls the old one.
Reid Spencer688b0492007-02-05 21:19:13 +0000792 if (Function *oldMain = Safe->getFunction("main"))
Reid Spencer5cbf9852007-01-30 20:08:39 +0000793 if (!oldMain->isDeclaration()) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000794 // Rename it
795 oldMain->setName("llvm_bugpoint_old_main");
796 // Create a NEW `main' function with same type in the test module.
Rafael Espindola0340a6f2015-12-09 00:51:06 +0000797 Function *newMain =
798 Function::Create(oldMain->getFunctionType(),
799 GlobalValue::ExternalLinkage, "main", Test.get());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000800 // Create an `oldmain' prototype in the test module, which will
801 // corresponds to the real main function in the same module.
Gabor Greif051a9502008-04-06 20:25:17 +0000802 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
803 GlobalValue::ExternalLinkage,
Rafael Espindola0340a6f2015-12-09 00:51:06 +0000804 oldMain->getName(), Test.get());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000805 // Set up and remember the argument list for the main function.
Justin Bogner388e8b92016-09-02 01:21:37 +0000806 std::vector<Value *> args;
807 for (Function::arg_iterator I = newMain->arg_begin(),
808 E = newMain->arg_end(),
809 OI = oldMain->arg_begin();
810 I != E; ++I, ++OI) {
811 I->setName(OI->getName()); // Copy argument names from oldMain
Duncan P. N. Exon Smith1e221d52015-10-20 19:36:39 +0000812 args.push_back(&*I);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000813 }
814
815 // Call the old main function and return its result
Owen Anderson1d0be152009-08-13 21:58:54 +0000816 BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
Jay Foada3efbb12011-07-15 08:37:34 +0000817 CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000818
Chris Lattnera57d86b2004-04-05 22:58:16 +0000819 // If the type of old function wasn't void, return value of call
Owen Anderson1d0be152009-08-13 21:58:54 +0000820 ReturnInst::Create(Safe->getContext(), call, BB);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000821 }
822
823 // The second nasty issue we must deal with in the JIT is that the Safe
824 // module cannot directly reference any functions defined in the test
825 // module. Instead, we use a JIT API call to dynamically resolve the
826 // symbol.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000827
Chris Lattnera57d86b2004-04-05 22:58:16 +0000828 // Add the resolver to the Safe module.
829 // Prototype: void *getPointerToNamedFunction(const char* Name)
Justin Bogner388e8b92016-09-02 01:21:37 +0000830 Constant *resolverFunc = Safe->getOrInsertFunction(
831 "getPointerToNamedFunction", Type::getInt8PtrTy(Safe->getContext()),
Serge Guelton9d544002017-04-11 15:01:18 +0000832 Type::getInt8PtrTy(Safe->getContext()));
Misha Brukman3da94ae2005-04-22 00:00:37 +0000833
Chris Lattnera57d86b2004-04-05 22:58:16 +0000834 // Use the function we just added to get addresses of functions we need.
Misha Brukmandc7fef82004-04-19 01:12:01 +0000835 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000836 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
Duncan Sandsa3355ff2007-12-03 20:06:50 +0000837 !F->isIntrinsic() /* ignore intrinsics */) {
Reid Spencer688b0492007-02-05 21:19:13 +0000838 Function *TestFn = Test->getFunction(F->getName());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000839
840 // Don't forward functions which are external in the test module too.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000841 if (TestFn && !TestFn->isDeclaration()) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000842 // 1. Add a string constant with its name to the global file
Chris Lattner18c7f802012-02-05 02:29:43 +0000843 Constant *InitArray =
Justin Bogner388e8b92016-09-02 01:21:37 +0000844 ConstantDataArray::getString(F->getContext(), F->getName());
845 GlobalVariable *funcName = new GlobalVariable(
846 *Safe, InitArray->getType(), true /*isConstant*/,
847 GlobalValue::InternalLinkage, InitArray, F->getName() + "_name");
Chris Lattnera57d86b2004-04-05 22:58:16 +0000848
849 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
850 // sbyte* so it matches the signature of the resolver function.
851
852 // GetElementPtr *funcName, ulong 0, ulong 0
Justin Bogner388e8b92016-09-02 01:21:37 +0000853 std::vector<Constant *> GEPargs(
854 2, Constant::getNullValue(Type::getInt32Ty(F->getContext())));
David Blaikie19443c12015-04-02 18:55:32 +0000855 Value *GEP = ConstantExpr::getGetElementPtr(InitArray->getType(),
856 funcName, GEPargs);
Justin Bogner388e8b92016-09-02 01:21:37 +0000857 std::vector<Value *> ResolverArgs;
Chris Lattnera57d86b2004-04-05 22:58:16 +0000858 ResolverArgs.push_back(GEP);
859
Misha Brukmande4803d2004-04-19 03:36:47 +0000860 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
861 // function that dynamically resolves the calls to F via our JIT API
Chris Lattnera3efca12005-07-12 01:00:32 +0000862 if (!F->use_empty()) {
863 // Create a new global to hold the cached function pointer.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000864 Constant *NullPtr = ConstantPointerNull::get(F->getType());
Justin Bogner388e8b92016-09-02 01:21:37 +0000865 GlobalVariable *Cache = new GlobalVariable(
866 *F->getParent(), F->getType(), false,
867 GlobalValue::InternalLinkage, NullPtr, F->getName() + ".fpcache");
Jeff Cohen00b168892005-07-27 06:12:32 +0000868
Misha Brukmande4803d2004-04-19 03:36:47 +0000869 // Construct a new stub function that will re-route calls to F
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000870 FunctionType *FuncTy = F->getFunctionType();
Justin Bogner388e8b92016-09-02 01:21:37 +0000871 Function *FuncWrapper =
872 Function::Create(FuncTy, GlobalValue::InternalLinkage,
873 F->getName() + "_wrapper", F->getParent());
874 BasicBlock *EntryBB =
875 BasicBlock::Create(F->getContext(), "entry", FuncWrapper);
876 BasicBlock *DoCallBB =
877 BasicBlock::Create(F->getContext(), "usecache", FuncWrapper);
878 BasicBlock *LookupBB =
879 BasicBlock::Create(F->getContext(), "lookupfp", FuncWrapper);
Jeff Cohen00b168892005-07-27 06:12:32 +0000880
Chris Lattnera3efca12005-07-12 01:00:32 +0000881 // Check to see if we already looked up the value.
882 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
Owen Anderson333c4002009-07-09 23:48:35 +0000883 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
884 NullPtr, "isNull");
Gabor Greif051a9502008-04-06 20:25:17 +0000885 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000886
Misha Brukmande4803d2004-04-19 03:36:47 +0000887 // Resolve the call to function F via the JIT API:
888 //
889 // call resolver(GetElementPtr...)
Justin Bogner388e8b92016-09-02 01:21:37 +0000890 CallInst *Resolver = CallInst::Create(resolverFunc, ResolverArgs,
891 "resolver", LookupBB);
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000892
893 // Cast the result from the resolver to correctly-typed function.
Justin Bogner388e8b92016-09-02 01:21:37 +0000894 CastInst *CastedResolver = new BitCastInst(
895 Resolver, PointerType::getUnqual(F->getFunctionType()),
896 "resolverCast", LookupBB);
Reid Spencer3da59db2006-11-27 01:05:10 +0000897
Chris Lattnera3efca12005-07-12 01:00:32 +0000898 // Save the value in our cache.
899 new StoreInst(CastedResolver, Cache, LookupBB);
Gabor Greif051a9502008-04-06 20:25:17 +0000900 BranchInst::Create(DoCallBB, LookupBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000901
Justin Bogner388e8b92016-09-02 01:21:37 +0000902 PHINode *FuncPtr =
903 PHINode::Create(NullPtr->getType(), 2, "fp", DoCallBB);
Chris Lattnera3efca12005-07-12 01:00:32 +0000904 FuncPtr->addIncoming(CastedResolver, LookupBB);
905 FuncPtr->addIncoming(CachedVal, EntryBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000906
Chris Lattnera3efca12005-07-12 01:00:32 +0000907 // Save the argument list.
Justin Bogner388e8b92016-09-02 01:21:37 +0000908 std::vector<Value *> Args;
Duncan P. N. Exon Smith1e221d52015-10-20 19:36:39 +0000909 for (Argument &A : FuncWrapper->args())
910 Args.push_back(&A);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000911
912 // Pass on the arguments to the real function, return its result
Dan Gohmane49a13e2010-06-07 20:19:26 +0000913 if (F->getReturnType()->isVoidTy()) {
Jay Foada3efbb12011-07-15 08:37:34 +0000914 CallInst::Create(FuncPtr, Args, "", DoCallBB);
Owen Anderson1d0be152009-08-13 21:58:54 +0000915 ReturnInst::Create(F->getContext(), DoCallBB);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000916 } else {
Justin Bogner388e8b92016-09-02 01:21:37 +0000917 CallInst *Call =
918 CallInst::Create(FuncPtr, Args, "retval", DoCallBB);
919 ReturnInst::Create(F->getContext(), Call, DoCallBB);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000920 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000921
Misha Brukmande4803d2004-04-19 03:36:47 +0000922 // Use the wrapper function instead of the old function
923 F->replaceAllUsesWith(FuncWrapper);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000924 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000925 }
926 }
927 }
928
929 if (verifyModule(*Test) || verifyModule(*Safe)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000930 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000931 abort();
932 }
Rafael Espindola46e55022018-04-24 20:15:27 +0000933
934 return Test;
Chris Lattnera57d86b2004-04-05 22:58:16 +0000935}
936
Rafael Espindola0340a6f2015-12-09 00:51:06 +0000937/// This is the predicate function used to check to see if the "Test" portion of
938/// the program is miscompiled by the code generator under test. If so, return
939/// true. In any case, both module arguments are deleted.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000940///
Justin Bognerd8090ae2016-09-06 17:18:22 +0000941static Expected<bool> TestCodeGenerator(BugDriver &BD,
942 std::unique_ptr<Module> Test,
943 std::unique_ptr<Module> Safe) {
Rafael Espindola46e55022018-04-24 20:15:27 +0000944 Test = CleanupAndPrepareModules(BD, std::move(Test), Safe.get());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000945
Rafael Espindola88088f42013-06-18 15:29:32 +0000946 SmallString<128> TestModuleBC;
947 int TestModuleFD;
Rafael Espindola1ad45022014-06-13 03:07:50 +0000948 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
949 TestModuleFD, TestModuleBC);
Rafael Espindola88088f42013-06-18 15:29:32 +0000950 if (EC) {
Justin Bogner388e8b92016-09-02 01:21:37 +0000951 errs() << BD.getToolName()
952 << "Error making unique filename: " << EC.message() << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +0000953 exit(1);
954 }
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000955 if (BD.writeProgramToFile(TestModuleBC.str(), TestModuleFD, *Test)) {
Chris Lattner74382b72009-08-23 22:45:37 +0000956 errs() << "Error writing bitcode to `" << TestModuleBC.str()
957 << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000958 exit(1);
959 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000960
Michael J. Spencerc9c08fb2011-03-31 13:04:19 +0000961 FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
Rafael Espindolabc2ed592010-06-21 02:17:36 +0000962
Chris Lattnera57d86b2004-04-05 22:58:16 +0000963 // Make the shared library
Rafael Espindola88088f42013-06-18 15:29:32 +0000964 SmallString<128> SafeModuleBC;
965 int SafeModuleFD;
Rafael Espindola1276b392013-07-05 20:14:52 +0000966 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
967 SafeModuleBC);
Rafael Espindola88088f42013-06-18 15:29:32 +0000968 if (EC) {
Justin Bogner388e8b92016-09-02 01:21:37 +0000969 errs() << BD.getToolName()
970 << "Error making unique filename: " << EC.message() << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +0000971 exit(1);
972 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000973
Rafael Espindolacdac12c2018-02-14 21:44:34 +0000974 if (BD.writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, *Safe)) {
Justin Bogner388e8b92016-09-02 01:21:37 +0000975 errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000976 exit(1);
977 }
Rafael Espindolabc2ed592010-06-21 02:17:36 +0000978
Michael J. Spencerc9c08fb2011-03-31 13:04:19 +0000979 FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
Rafael Espindolabc2ed592010-06-21 02:17:36 +0000980
Justin Bognerd8090ae2016-09-06 17:18:22 +0000981 Expected<std::string> SharedObject =
982 BD.compileSharedObject(SafeModuleBC.str());
983 if (Error E = SharedObject.takeError())
984 return std::move(E);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000985
Justin Bognerd8090ae2016-09-06 17:18:22 +0000986 FileRemover SharedObjectRemover(*SharedObject, !SaveTemps);
Rafael Espindolabc2ed592010-06-21 02:17:36 +0000987
Chris Lattnera57d86b2004-04-05 22:58:16 +0000988 // Run the code generator on the `Test' code, loading the shared library.
989 // The function returns whether or not the new output differs from reference.
Justin Bognerd8090ae2016-09-06 17:18:22 +0000990 Expected<bool> Result =
991 BD.diffProgram(BD.getProgram(), TestModuleBC.str(), *SharedObject, false);
992 if (Error E = Result.takeError())
993 return std::move(E);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000994
Justin Bognerd8090ae2016-09-06 17:18:22 +0000995 if (*Result)
Dan Gohman65f57c22009-07-15 16:35:29 +0000996 errs() << ": still failing!\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000997 else
Dan Gohman65f57c22009-07-15 16:35:29 +0000998 errs() << ": didn't fail.\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000999
1000 return Result;
1001}
1002
Misha Brukman8c194ea2004-04-21 18:36:43 +00001003/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
1004///
Justin Bognerd8090ae2016-09-06 17:18:22 +00001005Error BugDriver::debugCodeGenerator() {
Justin Bogner388e8b92016-09-02 01:21:37 +00001006 if ((void *)SafeInterpreter == (void *)Interpreter) {
Justin Bognerd8090ae2016-09-06 17:18:22 +00001007 Expected<std::string> Result =
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001008 executeProgramSafely(*Program, "bugpoint.safe.out");
Justin Bognerd8090ae2016-09-06 17:18:22 +00001009 if (Result) {
Nick Lewycky22ff7482010-04-12 05:08:25 +00001010 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
1011 << "the reference diff. This may be due to a\n front-end "
1012 << "bug or a bug in the original program, but this can also "
1013 << "happen if bugpoint isn't running the program with the "
1014 << "right flags or input.\n I left the result of executing "
1015 << "the program with the \"safe\" backend in this file for "
Justin Bognerd8090ae2016-09-06 17:18:22 +00001016 << "you: '" << *Result << "'.\n";
Nick Lewycky22ff7482010-04-12 05:08:25 +00001017 }
Justin Bognerd8090ae2016-09-06 17:18:22 +00001018 return Error::success();
Chris Lattnera57d86b2004-04-05 22:58:16 +00001019 }
1020
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001021 DisambiguateGlobalSymbols(*Program);
Chris Lattnera57d86b2004-04-05 22:58:16 +00001022
Justin Bognerd8090ae2016-09-06 17:18:22 +00001023 Expected<std::vector<Function *>> Funcs =
1024 DebugAMiscompilation(*this, TestCodeGenerator);
1025 if (Error E = Funcs.takeError())
1026 return E;
Chris Lattnera57d86b2004-04-05 22:58:16 +00001027
1028 // Split the module into the two halves of the program we want.
Rafael Espindola1ed219a2010-10-13 01:36:30 +00001029 ValueToValueMapTy VMap;
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001030 std::unique_ptr<Module> ToNotCodeGen = CloneModule(getProgram(), VMap);
Rafael Espindola0340a6f2015-12-09 00:51:06 +00001031 std::unique_ptr<Module> ToCodeGen =
Justin Bognerd8090ae2016-09-06 17:18:22 +00001032 SplitFunctionsOutOfModule(ToNotCodeGen.get(), *Funcs, VMap);
Chris Lattnera57d86b2004-04-05 22:58:16 +00001033
1034 // Condition the modules
Rafael Espindola46e55022018-04-24 20:15:27 +00001035 ToCodeGen =
1036 CleanupAndPrepareModules(*this, std::move(ToCodeGen), ToNotCodeGen.get());
Chris Lattnera57d86b2004-04-05 22:58:16 +00001037
Rafael Espindola88088f42013-06-18 15:29:32 +00001038 SmallString<128> TestModuleBC;
1039 int TestModuleFD;
Rafael Espindola1ad45022014-06-13 03:07:50 +00001040 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
1041 TestModuleFD, TestModuleBC);
Rafael Espindola88088f42013-06-18 15:29:32 +00001042 if (EC) {
Justin Bogner388e8b92016-09-02 01:21:37 +00001043 errs() << getToolName() << "Error making unique filename: " << EC.message()
1044 << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +00001045 exit(1);
1046 }
Reid Spencer97182982004-12-15 01:53:08 +00001047
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001048 if (writeProgramToFile(TestModuleBC.str(), TestModuleFD, *ToCodeGen)) {
Justin Bogner388e8b92016-09-02 01:21:37 +00001049 errs() << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +00001050 exit(1);
1051 }
Chris Lattnera57d86b2004-04-05 22:58:16 +00001052
1053 // Make the shared library
Rafael Espindola88088f42013-06-18 15:29:32 +00001054 SmallString<128> SafeModuleBC;
1055 int SafeModuleFD;
Rafael Espindola1276b392013-07-05 20:14:52 +00001056 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
1057 SafeModuleBC);
Rafael Espindola88088f42013-06-18 15:29:32 +00001058 if (EC) {
Justin Bogner388e8b92016-09-02 01:21:37 +00001059 errs() << getToolName() << "Error making unique filename: " << EC.message()
1060 << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +00001061 exit(1);
1062 }
Reid Spencer97182982004-12-15 01:53:08 +00001063
Rafael Espindolacdac12c2018-02-14 21:44:34 +00001064 if (writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, *ToNotCodeGen)) {
Justin Bogner388e8b92016-09-02 01:21:37 +00001065 errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +00001066 exit(1);
1067 }
Justin Bognerd8090ae2016-09-06 17:18:22 +00001068 Expected<std::string> SharedObject = compileSharedObject(SafeModuleBC.str());
1069 if (Error E = SharedObject.takeError())
1070 return E;
Chris Lattnera57d86b2004-04-05 22:58:16 +00001071
Dan Gohmanac95cc72009-07-16 15:30:09 +00001072 outs() << "You can reproduce the problem with the command line: \n";
Chris Lattnera57d86b2004-04-05 22:58:16 +00001073 if (isExecutingJIT()) {
Justin Bognerd8090ae2016-09-06 17:18:22 +00001074 outs() << " lli -load " << *SharedObject << " " << TestModuleBC;
Chris Lattnera57d86b2004-04-05 22:58:16 +00001075 } else {
Justin Bogner388e8b92016-09-02 01:21:37 +00001076 outs() << " llc " << TestModuleBC << " -o " << TestModuleBC << ".s\n";
Justin Bognerd8090ae2016-09-06 17:18:22 +00001077 outs() << " cc " << *SharedObject << " " << TestModuleBC.str() << ".s -o "
Joerg Sonnenbergera27efcd2016-10-01 07:34:18 +00001078 << TestModuleBC << ".exe\n";
1079 outs() << " ./" << TestModuleBC << ".exe";
Chris Lattnera57d86b2004-04-05 22:58:16 +00001080 }
Nick Lewycky22ff7482010-04-12 05:08:25 +00001081 for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
Dan Gohmanac95cc72009-07-16 15:30:09 +00001082 outs() << " " << InputArgv[i];
1083 outs() << '\n';
1084 outs() << "The shared object was created with:\n llc -march=c "
Chris Lattner74382b72009-08-23 22:45:37 +00001085 << SafeModuleBC.str() << " -o temporary.c\n"
Justin Bognerd8090ae2016-09-06 17:18:22 +00001086 << " cc -xc temporary.c -O2 -o " << *SharedObject;
Daniel Dunbarca740962009-08-18 03:35:57 +00001087 if (TargetTriple.getArch() == Triple::sparc)
Justin Bogner388e8b92016-09-02 01:21:37 +00001088 outs() << " -G"; // Compile a shared library, `-G' for Sparc
Daniel Dunbarca740962009-08-18 03:35:57 +00001089 else
Justin Bogner388e8b92016-09-02 01:21:37 +00001090 outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
Daniel Dunbarca740962009-08-18 03:35:57 +00001091
1092 outs() << " -fno-strict-aliasing\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +00001093
Justin Bognerd8090ae2016-09-06 17:18:22 +00001094 return Error::success();
Chris Lattnera57d86b2004-04-05 22:58:16 +00001095}