blob: c021418905aead7c2ea9ba95ab244080e85ccd33 [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"
Chris Lattnera57d86b2004-04-05 22:58:16 +000017#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Instructions.h"
Reid Spencer605b9e22004-11-14 23:00:08 +000020#include "llvm/Linker.h"
Chris Lattner4a106452002-12-23 23:50:16 +000021#include "llvm/Module.h"
Misha Brukmane49603d2003-08-07 21:19:30 +000022#include "llvm/Pass.h"
Chris Lattnera57d86b2004-04-05 22:58:16 +000023#include "llvm/Analysis/Verifier.h"
24#include "llvm/Support/Mangler.h"
Chris Lattner640f22e2003-04-24 17:02:17 +000025#include "llvm/Transforms/Utils/Cloning.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/FileUtilities.h"
Chris Lattner59615f02005-01-15 00:07:19 +000028#include "llvm/Config/config.h" // for HAVE_LINK_R
Chris Lattnerfa761832004-01-14 03:38:37 +000029using namespace llvm;
Chris Lattner4a106452002-12-23 23:50:16 +000030
Chris Lattnera57d86b2004-04-05 22:58:16 +000031namespace llvm {
32 extern cl::list<std::string> InputArgv;
33}
34
Chris Lattnerefdc0b52004-03-14 20:50:42 +000035namespace {
Reid Spencerdc31a8a2006-11-11 19:05:02 +000036 static llvm::cl::opt<bool>
37 DisableLoopExtraction("disable-loop-extraction",
38 cl::desc("Don't extract loops when searching for miscompilations"),
39 cl::init(false));
David Goodwin265d82e2009-07-28 23:08:36 +000040 static llvm::cl::opt<bool>
41 DisableBlockExtraction("disable-block-extraction",
42 cl::desc("Don't extract blocks when searching for miscompilations"),
43 cl::init(false));
Reid Spencerdc31a8a2006-11-11 19:05:02 +000044
Chris Lattnerfa761832004-01-14 03:38:37 +000045 class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
46 BugDriver &BD;
47 public:
48 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +000049
Chris Lattnerfa761832004-01-14 03:38:37 +000050 virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
51 std::vector<const PassInfo*> &Suffix);
52 };
53}
Chris Lattner640f22e2003-04-24 17:02:17 +000054
Misha Brukman8c194ea2004-04-21 18:36:43 +000055/// TestResult - After passes have been split into a test group and a control
56/// group, see if they still break the program.
57///
Chris Lattner640f22e2003-04-24 17:02:17 +000058ReduceMiscompilingPasses::TestResult
Chris Lattner39aebca2003-04-24 22:24:22 +000059ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
Chris Lattner06943ad2003-04-25 03:16:05 +000060 std::vector<const PassInfo*> &Suffix) {
61 // First, run the program with just the Suffix passes. If it is still broken
Chris Lattner640f22e2003-04-24 17:02:17 +000062 // with JUST the kept passes, discard the prefix passes.
Dan Gohmanac95cc72009-07-16 15:30:09 +000063 outs() << "Checking to see if '" << getPassesString(Suffix)
64 << "' compiles correctly: ";
Chris Lattner640f22e2003-04-24 17:02:17 +000065
Gabor Greif8ff70c22007-07-04 21:55:50 +000066 std::string BitcodeResult;
67 if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Dan Gohman65f57c22009-07-15 16:35:29 +000068 errs() << " Error running this sequence of passes"
69 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +000070 BD.setPassesToRun(Suffix);
Gabor Greif8ff70c22007-07-04 21:55:50 +000071 BD.EmitProgressBitcode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +000072 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +000073 }
Owen Anderson9adc0ab2009-07-14 23:09:55 +000074
Chris Lattner640f22e2003-04-24 17:02:17 +000075 // Check to see if the finished program matches the reference output...
Gabor Greif8ff70c22007-07-04 21:55:50 +000076 if (BD.diffProgram(BitcodeResult, "", true /*delete bitcode*/)) {
Dan Gohmanac95cc72009-07-16 15:30:09 +000077 outs() << " nope.\n";
Chris Lattner59615f02005-01-15 00:07:19 +000078 if (Suffix.empty()) {
Dan Gohman65f57c22009-07-15 16:35:29 +000079 errs() << BD.getToolName() << ": I'm confused: the test fails when "
80 << "no passes are run, nondeterministic program?\n";
Chris Lattner59615f02005-01-15 00:07:19 +000081 exit(1);
82 }
Misha Brukman123f8fe2004-04-22 20:02:09 +000083 return KeepSuffix; // Miscompilation detected!
Chris Lattner640f22e2003-04-24 17:02:17 +000084 }
Dan Gohmanac95cc72009-07-16 15:30:09 +000085 outs() << " yup.\n"; // No miscompilation!
Chris Lattner640f22e2003-04-24 17:02:17 +000086
87 if (Prefix.empty()) return NoFailure;
88
Chris Lattner06943ad2003-04-25 03:16:05 +000089 // Next, see if the program is broken if we run the "prefix" passes first,
Misha Brukmanbc0e9982003-07-14 17:20:40 +000090 // then separately run the "kept" passes.
Dan Gohmanac95cc72009-07-16 15:30:09 +000091 outs() << "Checking to see if '" << getPassesString(Prefix)
92 << "' compiles correctly: ";
Chris Lattner640f22e2003-04-24 17:02:17 +000093
94 // If it is not broken with the kept passes, it's possible that the prefix
95 // passes must be run before the kept passes to break it. If the program
96 // WORKS after the prefix passes, but then fails if running the prefix AND
Gabor Greif8ff70c22007-07-04 21:55:50 +000097 // kept passes, we can update our bitcode file to include the result of the
Chris Lattner640f22e2003-04-24 17:02:17 +000098 // prefix passes, then discard the prefix passes.
99 //
Gabor Greif8ff70c22007-07-04 21:55:50 +0000100 if (BD.runPasses(Prefix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000101 errs() << " Error running this sequence of passes"
102 << " on the input program!\n";
Chris Lattner9c6cfe12003-10-17 23:03:16 +0000103 BD.setPassesToRun(Prefix);
Gabor Greif8ff70c22007-07-04 21:55:50 +0000104 BD.EmitProgressBitcode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +0000105 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +0000106 }
107
108 // If the prefix maintains the predicate by itself, only keep the prefix!
Gabor Greif8ff70c22007-07-04 21:55:50 +0000109 if (BD.diffProgram(BitcodeResult)) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000110 outs() << " nope.\n";
Gabor Greif8ff70c22007-07-04 21:55:50 +0000111 sys::Path(BitcodeResult).eraseFromDisk();
Chris Lattner640f22e2003-04-24 17:02:17 +0000112 return KeepPrefix;
113 }
Dan Gohmanac95cc72009-07-16 15:30:09 +0000114 outs() << " yup.\n"; // No miscompilation!
Chris Lattner640f22e2003-04-24 17:02:17 +0000115
116 // Ok, so now we know that the prefix passes work, try running the suffix
117 // passes on the result of the prefix passes.
118 //
Owen Anderson8b477ed2009-07-01 16:58:40 +0000119 Module *PrefixOutput = ParseInputFile(BitcodeResult, BD.getContext());
Chris Lattner640f22e2003-04-24 17:02:17 +0000120 if (PrefixOutput == 0) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000121 errs() << BD.getToolName() << ": Error reading bitcode file '"
122 << BitcodeResult << "'!\n";
Chris Lattner640f22e2003-04-24 17:02:17 +0000123 exit(1);
124 }
Gabor Greif8ff70c22007-07-04 21:55:50 +0000125 sys::Path(BitcodeResult).eraseFromDisk(); // No longer need the file on disk
Chris Lattnerf4789e62004-04-23 20:36:51 +0000126
127 // Don't check if there are no passes in the suffix.
128 if (Suffix.empty())
129 return NoFailure;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000130
Dan Gohmanac95cc72009-07-16 15:30:09 +0000131 outs() << "Checking to see if '" << getPassesString(Suffix)
Chris Lattner640f22e2003-04-24 17:02:17 +0000132 << "' passes compile correctly after the '"
133 << getPassesString(Prefix) << "' passes: ";
134
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000135 Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
Gabor Greif8ff70c22007-07-04 21:55:50 +0000136 if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000137 errs() << " Error running this sequence of passes"
138 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +0000139 BD.setPassesToRun(Suffix);
Gabor Greif8ff70c22007-07-04 21:55:50 +0000140 BD.EmitProgressBitcode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +0000141 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +0000142 }
143
144 // Run the result...
Gabor Greif8ff70c22007-07-04 21:55:50 +0000145 if (BD.diffProgram(BitcodeResult, "", true/*delete bitcode*/)) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000146 outs() << " nope.\n";
Chris Lattner640f22e2003-04-24 17:02:17 +0000147 delete OriginalInput; // We pruned down the original input...
Chris Lattner06943ad2003-04-25 03:16:05 +0000148 return KeepSuffix;
Chris Lattner640f22e2003-04-24 17:02:17 +0000149 }
150
151 // Otherwise, we must not be running the bad pass anymore.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000152 outs() << " yup.\n"; // No miscompilation!
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000153 delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test
Chris Lattner640f22e2003-04-24 17:02:17 +0000154 return NoFailure;
155}
156
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000157namespace {
Chris Lattnerfa761832004-01-14 03:38:37 +0000158 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
159 BugDriver &BD;
Chris Lattnerb15825b2004-04-05 21:37:38 +0000160 bool (*TestFn)(BugDriver &, Module *, Module *);
Chris Lattnerfa761832004-01-14 03:38:37 +0000161 public:
Chris Lattnerb15825b2004-04-05 21:37:38 +0000162 ReduceMiscompilingFunctions(BugDriver &bd,
163 bool (*F)(BugDriver &, Module *, Module *))
164 : BD(bd), TestFn(F) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +0000165
Chris Lattnerfa761832004-01-14 03:38:37 +0000166 virtual TestResult doTest(std::vector<Function*> &Prefix,
167 std::vector<Function*> &Suffix) {
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000168 if (!Suffix.empty() && TestFuncs(Suffix))
Chris Lattnerfa761832004-01-14 03:38:37 +0000169 return KeepSuffix;
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000170 if (!Prefix.empty() && TestFuncs(Prefix))
Chris Lattnerfa761832004-01-14 03:38:37 +0000171 return KeepPrefix;
172 return NoFailure;
173 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000174
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000175 bool TestFuncs(const std::vector<Function*> &Prefix);
Chris Lattnerfa761832004-01-14 03:38:37 +0000176 };
177}
Chris Lattner640f22e2003-04-24 17:02:17 +0000178
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000179/// TestMergedProgram - Given two modules, link them together and run the
180/// program, checking to see if the program matches the diff. If the diff
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000181/// matches, return false, otherwise return true. If the DeleteInputs argument
182/// is set to true then this function deletes both input modules before it
183/// returns.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000184///
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000185static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
186 bool DeleteInputs) {
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000187 // Link the two portions of the program back to together.
188 std::string ErrorMsg;
Chris Lattner90c18c52004-11-16 06:31:38 +0000189 if (!DeleteInputs) {
190 M1 = CloneModule(M1);
191 M2 = CloneModule(M2);
192 }
Reid Spencere4874022004-12-13 03:01:03 +0000193 if (Linker::LinkModules(M1, M2, &ErrorMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000194 errs() << BD.getToolName() << ": Error linking modules together:"
195 << ErrorMsg << '\n';
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000196 exit(1);
197 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000198 delete M2; // We are done with this module.
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000199
200 Module *OldProgram = BD.swapProgramIn(M1);
201
202 // Execute the program. If it does not match the expected output, we must
203 // return true.
204 bool Broken = BD.diffProgram();
205
206 // Delete the linked module & restore the original
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000207 BD.swapProgramIn(OldProgram);
Chris Lattner5313f232004-04-02 06:32:17 +0000208 delete M1;
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000209 return Broken;
210}
211
Misha Brukman8c194ea2004-04-21 18:36:43 +0000212/// TestFuncs - split functions in a Module into two groups: those that are
213/// under consideration for miscompilation vs. those that are not, and test
214/// accordingly. Each group of functions becomes a separate Module.
215///
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000216bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
Chris Lattner640f22e2003-04-24 17:02:17 +0000217 // Test to see if the function is misoptimized if we ONLY run it on the
218 // functions listed in Funcs.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000219 outs() << "Checking to see if the program is misoptimized when "
220 << (Funcs.size()==1 ? "this function is" : "these functions are")
221 << " run through the pass"
222 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000223 PrintFunctionList(Funcs);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000224 outs() << '\n';
Chris Lattner640f22e2003-04-24 17:02:17 +0000225
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000226 // Split the module into the two halves of the program we want.
Dan Gohmand50330c2009-04-22 15:57:18 +0000227 DenseMap<const Value*, Value*> ValueMap;
228 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
229 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, Funcs,
230 ValueMap);
Chris Lattner640f22e2003-04-24 17:02:17 +0000231
Nick Lewycky6fa98b12007-11-14 06:47:06 +0000232 // Run the predicate, note that the predicate will delete both input modules.
Chris Lattnerb15825b2004-04-05 21:37:38 +0000233 return TestFn(BD, ToOptimize, ToNotOptimize);
Chris Lattner640f22e2003-04-24 17:02:17 +0000234}
235
Misha Brukman8c194ea2004-04-21 18:36:43 +0000236/// DisambiguateGlobalSymbols - Mangle symbols to guarantee uniqueness by
237/// modifying predominantly internal symbols rather than external ones.
238///
Chris Lattner36ee07f2004-04-11 23:52:35 +0000239static void DisambiguateGlobalSymbols(Module *M) {
240 // Try not to cause collisions by minimizing chances of renaming an
241 // already-external symbol, so take in external globals and functions as-is.
242 // The code should work correctly without disambiguation (assuming the same
243 // mangler is used by the two code generators), but having symbols with the
244 // same name causes warnings to be emitted by the code generator.
245 Mangler Mang(*M);
Andrew Lenharth0fccc742005-12-06 20:51:30 +0000246 // Agree with the CBE on symbol naming
247 Mang.markCharUnacceptable('.');
Chris Lattner67ef9e42006-05-04 23:35:31 +0000248 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
Chris Lattner9d5511b2009-07-15 04:50:47 +0000249 I != E; ++I) {
250 // Don't mangle asm names.
251 if (!I->hasName() || I->getName()[0] != 1)
252 I->setName(Mang.getMangledName(I));
253 }
254 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
Chris Lattner4285d152009-07-19 20:19:04 +0000255 // Don't mangle asm names or intrinsics.
Chris Lattnere0d5c172009-07-19 20:19:25 +0000256 if ((!I->hasName() || I->getName()[0] != 1) &&
257 I->getIntrinsicID() == 0)
Chris Lattner9d5511b2009-07-15 04:50:47 +0000258 I->setName(Mang.getMangledName(I));
259 }
Chris Lattner36ee07f2004-04-11 23:52:35 +0000260}
261
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000262/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
263/// check to see if we can extract the loops in the region without obscuring the
264/// bug. If so, it reduces the amount of code identified.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000265///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000266static bool ExtractLoops(BugDriver &BD,
267 bool (*TestFn)(BugDriver &, Module *, Module *),
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000268 std::vector<Function*> &MiscompiledFunctions) {
269 bool MadeChange = false;
270 while (1) {
Chris Lattneraed98fa2005-08-02 23:25:56 +0000271 if (BugpointIsInterrupted) return MadeChange;
272
Dan Gohmand50330c2009-04-22 15:57:18 +0000273 DenseMap<const Value*, Value*> ValueMap;
274 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000275 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohmand50330c2009-04-22 15:57:18 +0000276 MiscompiledFunctions,
277 ValueMap);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000278 Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
279 if (!ToOptimizeLoopExtracted) {
280 // If the loop extractor crashed or if there were no extractible loops,
281 // then this chapter of our odyssey is over with.
282 delete ToNotOptimize;
283 delete ToOptimize;
284 return MadeChange;
285 }
286
Dan Gohman65f57c22009-07-15 16:35:29 +0000287 errs() << "Extracted a loop from the breaking portion of the program.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000288
289 // Bugpoint is intentionally not very trusting of LLVM transformations. In
290 // particular, we're not going to assume that the loop extractor works, so
291 // we're going to test the newly loop extracted program to make sure nothing
292 // has broken. If something broke, then we'll inform the user and stop
293 // extraction.
Dan Gohman70ef4492008-12-08 04:02:47 +0000294 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000295 if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000296 BD.switchToInterpreter(AI);
297
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000298 // Merged program doesn't work anymore!
Dan Gohman65f57c22009-07-15 16:35:29 +0000299 errs() << " *** ERROR: Loop extraction broke the program. :("
300 << " Please report a bug!\n";
301 errs() << " Continuing on with un-loop-extracted version.\n";
Chris Lattner56c41862005-05-08 21:54:56 +0000302
303 BD.writeProgramToFile("bugpoint-loop-extract-fail-tno.bc", ToNotOptimize);
304 BD.writeProgramToFile("bugpoint-loop-extract-fail-to.bc", ToOptimize);
305 BD.writeProgramToFile("bugpoint-loop-extract-fail-to-le.bc",
306 ToOptimizeLoopExtracted);
307
Dan Gohman65f57c22009-07-15 16:35:29 +0000308 errs() << "Please submit the bugpoint-loop-extract-fail-*.bc files.\n";
Chris Lattner56c41862005-05-08 21:54:56 +0000309 delete ToOptimize;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000310 delete ToNotOptimize;
311 delete ToOptimizeLoopExtracted;
312 return MadeChange;
313 }
Chris Lattner56c41862005-05-08 21:54:56 +0000314 delete ToOptimize;
Chris Lattnera57d86b2004-04-05 22:58:16 +0000315 BD.switchToInterpreter(AI);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000316
Dan Gohmanac95cc72009-07-16 15:30:09 +0000317 outs() << " Testing after loop extraction:\n";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000318 // Clone modules, the tester function will free them.
319 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
320 Module *TNOBackup = CloneModule(ToNotOptimize);
321 if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000322 outs() << "*** Loop extraction masked the problem. Undoing.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000323 // If the program is not still broken, then loop extraction did something
324 // that masked the error. Stop loop extraction now.
Chris Lattnerb15825b2004-04-05 21:37:38 +0000325 delete TOLEBackup;
326 delete TNOBackup;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000327 return MadeChange;
328 }
Chris Lattnerb15825b2004-04-05 21:37:38 +0000329 ToOptimizeLoopExtracted = TOLEBackup;
330 ToNotOptimize = TNOBackup;
331
Dan Gohmanac95cc72009-07-16 15:30:09 +0000332 outs() << "*** Loop extraction successful!\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000333
Chris Lattner90c18c52004-11-16 06:31:38 +0000334 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
335 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
336 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +0000337 if (!I->isDeclaration())
Chris Lattnerfa1af132004-11-19 07:09:40 +0000338 MisCompFunctions.push_back(std::make_pair(I->getName(),
339 I->getFunctionType()));
Chris Lattner90c18c52004-11-16 06:31:38 +0000340
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000341 // Okay, great! Now we know that we extracted a loop and that loop
342 // extraction both didn't break the program, and didn't mask the problem.
343 // Replace the current program with the loop extracted version, and try to
344 // extract another loop.
345 std::string ErrorMsg;
Reid Spencere4874022004-12-13 03:01:03 +0000346 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
Dan Gohman65f57c22009-07-15 16:35:29 +0000347 errs() << BD.getToolName() << ": Error linking modules together:"
348 << ErrorMsg << '\n';
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000349 exit(1);
350 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000351 delete ToOptimizeLoopExtracted;
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000352
353 // All of the Function*'s in the MiscompiledFunctions list are in the old
Chris Lattner5313f232004-04-02 06:32:17 +0000354 // module. Update this list to include all of the functions in the
355 // optimized and loop extracted module.
356 MiscompiledFunctions.clear();
Chris Lattner90c18c52004-11-16 06:31:38 +0000357 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spenceref9b9a72007-02-05 20:47:22 +0000358 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
359
Chris Lattner90c18c52004-11-16 06:31:38 +0000360 assert(NewF && "Function not found??");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000361 assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
362 "found wrong function type?");
Chris Lattner90c18c52004-11-16 06:31:38 +0000363 MiscompiledFunctions.push_back(NewF);
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000364 }
365
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000366 BD.setNewProgram(ToNotOptimize);
367 MadeChange = true;
368 }
369}
370
Chris Lattner5e783ab2004-05-11 21:54:13 +0000371namespace {
372 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
373 BugDriver &BD;
374 bool (*TestFn)(BugDriver &, Module *, Module *);
375 std::vector<Function*> FunctionsBeingTested;
376 public:
377 ReduceMiscompiledBlocks(BugDriver &bd,
378 bool (*F)(BugDriver &, Module *, Module *),
379 const std::vector<Function*> &Fns)
380 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +0000381
Chris Lattner5e783ab2004-05-11 21:54:13 +0000382 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
383 std::vector<BasicBlock*> &Suffix) {
384 if (!Suffix.empty() && TestFuncs(Suffix))
385 return KeepSuffix;
386 if (TestFuncs(Prefix))
387 return KeepPrefix;
388 return NoFailure;
389 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000390
Chris Lattner5e783ab2004-05-11 21:54:13 +0000391 bool TestFuncs(const std::vector<BasicBlock*> &Prefix);
392 };
393}
394
395/// TestFuncs - Extract all blocks for the miscompiled functions except for the
396/// specified blocks. If the problem still exists, return true.
397///
398bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) {
399 // Test to see if the function is misoptimized if we ONLY run it on the
400 // functions listed in Funcs.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000401 outs() << "Checking to see if the program is misoptimized when all ";
Chris Lattner68bee932004-05-12 16:08:01 +0000402 if (!BBs.empty()) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000403 outs() << "but these " << BBs.size() << " blocks are extracted: ";
Chris Lattner68bee932004-05-12 16:08:01 +0000404 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000405 outs() << BBs[i]->getName() << " ";
406 if (BBs.size() > 10) outs() << "...";
Chris Lattner68bee932004-05-12 16:08:01 +0000407 } else {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000408 outs() << "blocks are extracted.";
Chris Lattner68bee932004-05-12 16:08:01 +0000409 }
Dan Gohmanac95cc72009-07-16 15:30:09 +0000410 outs() << '\n';
Chris Lattner5e783ab2004-05-11 21:54:13 +0000411
412 // Split the module into the two halves of the program we want.
Dan Gohmand50330c2009-04-22 15:57:18 +0000413 DenseMap<const Value*, Value*> ValueMap;
414 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000415 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohmand50330c2009-04-22 15:57:18 +0000416 FunctionsBeingTested,
417 ValueMap);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000418
419 // Try the extraction. If it doesn't work, then the block extractor crashed
420 // or something, in which case bugpoint can't chase down this possibility.
421 if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) {
422 delete ToOptimize;
423 // Run the predicate, not that the predicate will delete both input modules.
424 return TestFn(BD, New, ToNotOptimize);
425 }
426 delete ToOptimize;
427 delete ToNotOptimize;
428 return false;
429}
430
431
432/// ExtractBlocks - Given a reduced list of functions that still expose the bug,
433/// extract as many basic blocks from the region as possible without obscuring
434/// the bug.
435///
436static bool ExtractBlocks(BugDriver &BD,
437 bool (*TestFn)(BugDriver &, Module *, Module *),
438 std::vector<Function*> &MiscompiledFunctions) {
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000439 if (BugpointIsInterrupted) return false;
440
Chris Lattner5e783ab2004-05-11 21:54:13 +0000441 std::vector<BasicBlock*> Blocks;
442 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
443 for (Function::iterator I = MiscompiledFunctions[i]->begin(),
444 E = MiscompiledFunctions[i]->end(); I != E; ++I)
445 Blocks.push_back(I);
446
447 // Use the list reducer to identify blocks that can be extracted without
448 // obscuring the bug. The Blocks list will end up containing blocks that must
449 // be retained from the original program.
450 unsigned OldSize = Blocks.size();
Chris Lattner68bee932004-05-12 16:08:01 +0000451
452 // Check to see if all blocks are extractible first.
453 if (ReduceMiscompiledBlocks(BD, TestFn,
454 MiscompiledFunctions).TestFuncs(std::vector<BasicBlock*>())) {
455 Blocks.clear();
456 } else {
457 ReduceMiscompiledBlocks(BD, TestFn,MiscompiledFunctions).reduceList(Blocks);
458 if (Blocks.size() == OldSize)
459 return false;
460 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000461
Dan Gohmand50330c2009-04-22 15:57:18 +0000462 DenseMap<const Value*, Value*> ValueMap;
463 Module *ProgClone = CloneModule(BD.getProgram(), ValueMap);
Chris Lattner2290e752004-05-12 02:43:24 +0000464 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
Dan Gohmand50330c2009-04-22 15:57:18 +0000465 MiscompiledFunctions,
466 ValueMap);
Chris Lattner2290e752004-05-12 02:43:24 +0000467 Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
468 if (Extracted == 0) {
Chris Lattnerda895d62005-02-27 06:18:25 +0000469 // Weird, extraction should have worked.
Dan Gohman65f57c22009-07-15 16:35:29 +0000470 errs() << "Nondeterministic problem extracting blocks??\n";
Chris Lattner2290e752004-05-12 02:43:24 +0000471 delete ProgClone;
472 delete ToExtract;
473 return false;
474 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000475
Chris Lattner2290e752004-05-12 02:43:24 +0000476 // Otherwise, block extraction succeeded. Link the two program fragments back
477 // together.
478 delete ToExtract;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000479
Chris Lattner90c18c52004-11-16 06:31:38 +0000480 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
481 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
482 I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +0000483 if (!I->isDeclaration())
Chris Lattnerfa1af132004-11-19 07:09:40 +0000484 MisCompFunctions.push_back(std::make_pair(I->getName(),
485 I->getFunctionType()));
Chris Lattner90c18c52004-11-16 06:31:38 +0000486
Chris Lattner2290e752004-05-12 02:43:24 +0000487 std::string ErrorMsg;
Reid Spencere4874022004-12-13 03:01:03 +0000488 if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000489 errs() << BD.getToolName() << ": Error linking modules together:"
490 << ErrorMsg << '\n';
Chris Lattner2290e752004-05-12 02:43:24 +0000491 exit(1);
492 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000493 delete Extracted;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000494
Chris Lattner2290e752004-05-12 02:43:24 +0000495 // Set the new program and delete the old one.
496 BD.setNewProgram(ProgClone);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000497
Chris Lattner2290e752004-05-12 02:43:24 +0000498 // Update the list of miscompiled functions.
499 MiscompiledFunctions.clear();
Chris Lattner5e783ab2004-05-11 21:54:13 +0000500
Chris Lattner90c18c52004-11-16 06:31:38 +0000501 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spenceref9b9a72007-02-05 20:47:22 +0000502 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
Chris Lattner90c18c52004-11-16 06:31:38 +0000503 assert(NewF && "Function not found??");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000504 assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
505 "Function has wrong type??");
Chris Lattner90c18c52004-11-16 06:31:38 +0000506 MiscompiledFunctions.push_back(NewF);
507 }
Chris Lattner2290e752004-05-12 02:43:24 +0000508
509 return true;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000510}
511
512
Chris Lattnerb15825b2004-04-05 21:37:38 +0000513/// DebugAMiscompilation - This is a generic driver to narrow down
514/// miscompilations, either in an optimization or a code generator.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000515///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000516static std::vector<Function*>
517DebugAMiscompilation(BugDriver &BD,
518 bool (*TestFn)(BugDriver &, Module *, Module *)) {
519 // Okay, now that we have reduced the list of passes which are causing the
520 // failure, see if we can pin down which functions are being
521 // miscompiled... first build a list of all of the non-external functions in
522 // the program.
523 std::vector<Function*> MiscompiledFunctions;
524 Module *Prog = BD.getProgram();
525 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +0000526 if (!I->isDeclaration())
Chris Lattnerb15825b2004-04-05 21:37:38 +0000527 MiscompiledFunctions.push_back(I);
528
529 // Do the reduction...
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000530 if (!BugpointIsInterrupted)
531 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Chris Lattnerb15825b2004-04-05 21:37:38 +0000532
Dan Gohmanac95cc72009-07-16 15:30:09 +0000533 outs() << "\n*** The following function"
534 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
535 << " being miscompiled: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000536 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000537 outs() << '\n';
Chris Lattnerb15825b2004-04-05 21:37:38 +0000538
539 // See if we can rip any loops out of the miscompiled functions and still
540 // trigger the problem.
Reid Spencerdc31a8a2006-11-11 19:05:02 +0000541
Reid Spencer2803b4c2006-11-11 19:59:25 +0000542 if (!BugpointIsInterrupted && !DisableLoopExtraction &&
543 ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
Chris Lattnerb15825b2004-04-05 21:37:38 +0000544 // Okay, we extracted some loops and the problem still appears. See if we
545 // can eliminate some of the created functions from being candidates.
546
Chris Lattner36ee07f2004-04-11 23:52:35 +0000547 // Loop extraction can introduce functions with the same name (foo_code).
548 // Make sure to disambiguate the symbols so that when the program is split
549 // apart that we can link it back together again.
550 DisambiguateGlobalSymbols(BD.getProgram());
551
Chris Lattnerb15825b2004-04-05 21:37:38 +0000552 // Do the reduction...
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000553 if (!BugpointIsInterrupted)
554 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000555
Dan Gohmanac95cc72009-07-16 15:30:09 +0000556 outs() << "\n*** The following function"
557 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
558 << " being miscompiled: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000559 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000560 outs() << '\n';
Chris Lattnerb15825b2004-04-05 21:37:38 +0000561 }
562
David Goodwin265d82e2009-07-28 23:08:36 +0000563 if (!BugpointIsInterrupted && !DisableBlockExtraction &&
Chris Lattneraed98fa2005-08-02 23:25:56 +0000564 ExtractBlocks(BD, TestFn, MiscompiledFunctions)) {
Chris Lattner5e783ab2004-05-11 21:54:13 +0000565 // Okay, we extracted some blocks and the problem still appears. See if we
566 // can eliminate some of the created functions from being candidates.
567
568 // Block extraction can introduce functions with the same name (foo_code).
569 // Make sure to disambiguate the symbols so that when the program is split
570 // apart that we can link it back together again.
571 DisambiguateGlobalSymbols(BD.getProgram());
572
573 // Do the reduction...
574 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000575
Dan Gohmanac95cc72009-07-16 15:30:09 +0000576 outs() << "\n*** The following function"
577 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
578 << " being miscompiled: ";
Chris Lattner5e783ab2004-05-11 21:54:13 +0000579 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000580 outs() << '\n';
Chris Lattner5e783ab2004-05-11 21:54:13 +0000581 }
582
Chris Lattnerb15825b2004-04-05 21:37:38 +0000583 return MiscompiledFunctions;
584}
585
Chris Lattnera57d86b2004-04-05 22:58:16 +0000586/// TestOptimizer - This is the predicate function used to check to see if the
587/// "Test" portion of the program is misoptimized. If so, return true. In any
588/// case, both module arguments are deleted.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000589///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000590static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
591 // Run the optimization passes on ToOptimize, producing a transformed version
592 // of the functions being tested.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000593 outs() << " Optimizing functions being tested: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000594 Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
595 /*AutoDebugCrashes*/true);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000596 outs() << "done.\n";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000597 delete Test;
598
Dan Gohmanac95cc72009-07-16 15:30:09 +0000599 outs() << " Checking to see if the merged program executes correctly: ";
Chris Lattner2423db02004-04-09 22:28:33 +0000600 bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000601 outs() << (Broken ? " nope.\n" : " yup.\n");
Chris Lattnerb15825b2004-04-05 21:37:38 +0000602 return Broken;
603}
604
605
Chris Lattner4a106452002-12-23 23:50:16 +0000606/// debugMiscompilation - This method is used when the passes selected are not
607/// crashing, but the generated output is semantically different from the
608/// input.
609///
610bool BugDriver::debugMiscompilation() {
Chris Lattner4a106452002-12-23 23:50:16 +0000611 // Make sure something was miscompiled...
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000612 if (!BugpointIsInterrupted)
613 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000614 errs() << "*** Optimized program matches reference output! No problem"
615 << " detected...\nbugpoint can't help you with your problem!\n";
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000616 return false;
617 }
Chris Lattner4a106452002-12-23 23:50:16 +0000618
Dan Gohmanac95cc72009-07-16 15:30:09 +0000619 outs() << "\n*** Found miscompiling pass"
620 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
621 << getPassesString(getPassesToRun()) << '\n';
Gabor Greif8ff70c22007-07-04 21:55:50 +0000622 EmitProgressBitcode("passinput");
Chris Lattner4a106452002-12-23 23:50:16 +0000623
Chris Lattnerb15825b2004-04-05 21:37:38 +0000624 std::vector<Function*> MiscompiledFunctions =
625 DebugAMiscompilation(*this, TestOptimizer);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000626
Gabor Greif8ff70c22007-07-04 21:55:50 +0000627 // Output a bunch of bitcode files for the user...
Dan Gohmanac95cc72009-07-16 15:30:09 +0000628 outs() << "Outputting reduced bitcode files which expose the problem:\n";
Dan Gohmand50330c2009-04-22 15:57:18 +0000629 DenseMap<const Value*, Value*> ValueMap;
630 Module *ToNotOptimize = CloneModule(getProgram(), ValueMap);
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000631 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohmand50330c2009-04-22 15:57:18 +0000632 MiscompiledFunctions,
633 ValueMap);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000634
Dan Gohmanac95cc72009-07-16 15:30:09 +0000635 outs() << " Non-optimized portion: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000636 ToNotOptimize = swapProgramIn(ToNotOptimize);
Gabor Greif8ff70c22007-07-04 21:55:50 +0000637 EmitProgressBitcode("tonotoptimize", true);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000638 setNewProgram(ToNotOptimize); // Delete hacked module.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000639
Dan Gohmanac95cc72009-07-16 15:30:09 +0000640 outs() << " Portion that is input to optimizer: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000641 ToOptimize = swapProgramIn(ToOptimize);
Gabor Greif8ff70c22007-07-04 21:55:50 +0000642 EmitProgressBitcode("tooptimize");
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000643 setNewProgram(ToOptimize); // Delete hacked module.
Chris Lattner4a106452002-12-23 23:50:16 +0000644
Chris Lattner4a106452002-12-23 23:50:16 +0000645 return false;
646}
Brian Gaeked0fde302003-11-11 22:41:34 +0000647
Chris Lattnera57d86b2004-04-05 22:58:16 +0000648/// CleanupAndPrepareModules - Get the specified modules ready for code
649/// generator testing.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000650///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000651static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
652 Module *Safe) {
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000653 LLVMContext &Context = BD.getContext();
654
Chris Lattnera57d86b2004-04-05 22:58:16 +0000655 // Clean up the modules, removing extra cruft that we don't need anymore...
656 Test = BD.performFinalCleanups(Test);
657
658 // If we are executing the JIT, we have several nasty issues to take care of.
659 if (!BD.isExecutingJIT()) return;
660
661 // First, if the main function is in the Safe module, we must add a stub to
662 // the Test module to call into it. Thus, we create a new function `main'
663 // which just calls the old one.
Reid Spencer688b0492007-02-05 21:19:13 +0000664 if (Function *oldMain = Safe->getFunction("main"))
Reid Spencer5cbf9852007-01-30 20:08:39 +0000665 if (!oldMain->isDeclaration()) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000666 // Rename it
667 oldMain->setName("llvm_bugpoint_old_main");
668 // Create a NEW `main' function with same type in the test module.
Gabor Greif051a9502008-04-06 20:25:17 +0000669 Function *newMain = Function::Create(oldMain->getFunctionType(),
670 GlobalValue::ExternalLinkage,
671 "main", Test);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000672 // Create an `oldmain' prototype in the test module, which will
673 // corresponds to the real main function in the same module.
Gabor Greif051a9502008-04-06 20:25:17 +0000674 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
675 GlobalValue::ExternalLinkage,
676 oldMain->getName(), Test);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000677 // Set up and remember the argument list for the main function.
678 std::vector<Value*> args;
Alkis Evlogimenos5a1c58d2005-03-15 07:02:26 +0000679 for (Function::arg_iterator
680 I = newMain->arg_begin(), E = newMain->arg_end(),
681 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
Owen Anderson6bc41e82008-04-14 17:38:21 +0000682 I->setName(OI->getName()); // Copy argument names from oldMain
Chris Lattnera57d86b2004-04-05 22:58:16 +0000683 args.push_back(I);
684 }
685
686 // Call the old main function and return its result
Gabor Greif051a9502008-04-06 20:25:17 +0000687 BasicBlock *BB = BasicBlock::Create("entry", newMain);
688 CallInst *call = CallInst::Create(oldMainProto, args.begin(), args.end(),
689 "", BB);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000690
Chris Lattnera57d86b2004-04-05 22:58:16 +0000691 // If the type of old function wasn't void, return value of call
Gabor Greif051a9502008-04-06 20:25:17 +0000692 ReturnInst::Create(call, BB);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000693 }
694
695 // The second nasty issue we must deal with in the JIT is that the Safe
696 // module cannot directly reference any functions defined in the test
697 // module. Instead, we use a JIT API call to dynamically resolve the
698 // symbol.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000699
Chris Lattnera57d86b2004-04-05 22:58:16 +0000700 // Add the resolver to the Safe module.
701 // Prototype: void *getPointerToNamedFunction(const char* Name)
Chris Lattner2db43c82007-01-07 08:13:39 +0000702 Constant *resolverFunc =
Chris Lattnera57d86b2004-04-05 22:58:16 +0000703 Safe->getOrInsertFunction("getPointerToNamedFunction",
Owen Andersondebcb012009-07-29 22:17:13 +0000704 PointerType::getUnqual(Type::Int8Ty),
705 PointerType::getUnqual(Type::Int8Ty), (Type *)0);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000706
Chris Lattnera57d86b2004-04-05 22:58:16 +0000707 // Use the function we just added to get addresses of functions we need.
Misha Brukmandc7fef82004-04-19 01:12:01 +0000708 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000709 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
Duncan Sandsa3355ff2007-12-03 20:06:50 +0000710 !F->isIntrinsic() /* ignore intrinsics */) {
Reid Spencer688b0492007-02-05 21:19:13 +0000711 Function *TestFn = Test->getFunction(F->getName());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000712
713 // Don't forward functions which are external in the test module too.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000714 if (TestFn && !TestFn->isDeclaration()) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000715 // 1. Add a string constant with its name to the global file
Owen Anderson1fd70962009-07-28 18:32:17 +0000716 Constant *InitArray = ConstantArray::get(F->getName());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000717 GlobalVariable *funcName =
Owen Andersone9b11b42009-07-08 19:03:57 +0000718 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
Misha Brukman3da94ae2005-04-22 00:00:37 +0000719 GlobalValue::InternalLinkage, InitArray,
Owen Andersone9b11b42009-07-08 19:03:57 +0000720 F->getName() + "_name");
Chris Lattnera57d86b2004-04-05 22:58:16 +0000721
722 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
723 // sbyte* so it matches the signature of the resolver function.
724
725 // GetElementPtr *funcName, ulong 0, ulong 0
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000726 std::vector<Constant*> GEPargs(2, Context.getNullValue(Type::Int32Ty));
727 Value *GEP =
Owen Andersonbaf3c402009-07-29 18:55:55 +0000728 ConstantExpr::getGetElementPtr(funcName, &GEPargs[0], 2);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000729 std::vector<Value*> ResolverArgs;
730 ResolverArgs.push_back(GEP);
731
Misha Brukmande4803d2004-04-19 03:36:47 +0000732 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
733 // function that dynamically resolves the calls to F via our JIT API
Chris Lattnera3efca12005-07-12 01:00:32 +0000734 if (!F->use_empty()) {
735 // Create a new global to hold the cached function pointer.
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000736 Constant *NullPtr = Context.getConstantPointerNull(F->getType());
Chris Lattnera3efca12005-07-12 01:00:32 +0000737 GlobalVariable *Cache =
Owen Andersone9b11b42009-07-08 19:03:57 +0000738 new GlobalVariable(*F->getParent(), F->getType(),
739 false, GlobalValue::InternalLinkage,
740 NullPtr,F->getName()+".fpcache");
Jeff Cohen00b168892005-07-27 06:12:32 +0000741
Misha Brukmande4803d2004-04-19 03:36:47 +0000742 // Construct a new stub function that will re-route calls to F
Misha Brukmandc7fef82004-04-19 01:12:01 +0000743 const FunctionType *FuncTy = F->getFunctionType();
Gabor Greif051a9502008-04-06 20:25:17 +0000744 Function *FuncWrapper = Function::Create(FuncTy,
745 GlobalValue::InternalLinkage,
746 F->getName() + "_wrapper",
747 F->getParent());
748 BasicBlock *EntryBB = BasicBlock::Create("entry", FuncWrapper);
749 BasicBlock *DoCallBB = BasicBlock::Create("usecache", FuncWrapper);
750 BasicBlock *LookupBB = BasicBlock::Create("lookupfp", FuncWrapper);
Jeff Cohen00b168892005-07-27 06:12:32 +0000751
Chris Lattnera3efca12005-07-12 01:00:32 +0000752 // Check to see if we already looked up the value.
753 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
Owen Anderson333c4002009-07-09 23:48:35 +0000754 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
755 NullPtr, "isNull");
Gabor Greif051a9502008-04-06 20:25:17 +0000756 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000757
Misha Brukmande4803d2004-04-19 03:36:47 +0000758 // Resolve the call to function F via the JIT API:
759 //
760 // call resolver(GetElementPtr...)
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000761 CallInst *Resolver =
762 CallInst::Create(resolverFunc, ResolverArgs.begin(),
763 ResolverArgs.end(), "resolver", LookupBB);
764
765 // Cast the result from the resolver to correctly-typed function.
766 CastInst *CastedResolver =
767 new BitCastInst(Resolver,
Owen Andersondebcb012009-07-29 22:17:13 +0000768 PointerType::getUnqual(F->getFunctionType()),
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000769 "resolverCast", LookupBB);
Reid Spencer3da59db2006-11-27 01:05:10 +0000770
Chris Lattnera3efca12005-07-12 01:00:32 +0000771 // Save the value in our cache.
772 new StoreInst(CastedResolver, Cache, LookupBB);
Gabor Greif051a9502008-04-06 20:25:17 +0000773 BranchInst::Create(DoCallBB, LookupBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000774
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000775 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(),
776 "fp", DoCallBB);
Chris Lattnera3efca12005-07-12 01:00:32 +0000777 FuncPtr->addIncoming(CastedResolver, LookupBB);
778 FuncPtr->addIncoming(CachedVal, EntryBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000779
Chris Lattnera3efca12005-07-12 01:00:32 +0000780 // Save the argument list.
Misha Brukmandc7fef82004-04-19 01:12:01 +0000781 std::vector<Value*> Args;
Alkis Evlogimenos5a1c58d2005-03-15 07:02:26 +0000782 for (Function::arg_iterator i = FuncWrapper->arg_begin(),
783 e = FuncWrapper->arg_end(); i != e; ++i)
Misha Brukmandc7fef82004-04-19 01:12:01 +0000784 Args.push_back(i);
785
786 // Pass on the arguments to the real function, return its result
787 if (F->getReturnType() == Type::VoidTy) {
Gabor Greif051a9502008-04-06 20:25:17 +0000788 CallInst::Create(FuncPtr, Args.begin(), Args.end(), "", DoCallBB);
789 ReturnInst::Create(DoCallBB);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000790 } else {
Gabor Greif051a9502008-04-06 20:25:17 +0000791 CallInst *Call = CallInst::Create(FuncPtr, Args.begin(), Args.end(),
792 "retval", DoCallBB);
793 ReturnInst::Create(Call, DoCallBB);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000794 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000795
Misha Brukmande4803d2004-04-19 03:36:47 +0000796 // Use the wrapper function instead of the old function
797 F->replaceAllUsesWith(FuncWrapper);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000798 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000799 }
800 }
801 }
802
803 if (verifyModule(*Test) || verifyModule(*Safe)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000804 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000805 abort();
806 }
807}
808
809
810
811/// TestCodeGenerator - This is the predicate function used to check to see if
812/// the "Test" portion of the program is miscompiled by the code generator under
813/// test. If so, return true. In any case, both module arguments are deleted.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000814///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000815static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
816 CleanupAndPrepareModules(BD, Test, Safe);
817
Reid Spencer97182982004-12-15 01:53:08 +0000818 sys::Path TestModuleBC("bugpoint.test.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000819 std::string ErrMsg;
820 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000821 errs() << BD.getToolName() << "Error making unique filename: "
822 << ErrMsg << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +0000823 exit(1);
824 }
Reid Spencer97182982004-12-15 01:53:08 +0000825 if (BD.writeProgramToFile(TestModuleBC.toString(), Test)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000826 errs() << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000827 exit(1);
828 }
829 delete Test;
830
831 // Make the shared library
Reid Spencer97182982004-12-15 01:53:08 +0000832 sys::Path SafeModuleBC("bugpoint.safe.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000833 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000834 errs() << BD.getToolName() << "Error making unique filename: "
835 << ErrMsg << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +0000836 exit(1);
837 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000838
Reid Spencer97182982004-12-15 01:53:08 +0000839 if (BD.writeProgramToFile(SafeModuleBC.toString(), Safe)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000840 errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000841 exit(1);
842 }
Reid Spencer97182982004-12-15 01:53:08 +0000843 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.toString());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000844 delete Safe;
845
846 // Run the code generator on the `Test' code, loading the shared library.
847 // The function returns whether or not the new output differs from reference.
Reid Spencer97182982004-12-15 01:53:08 +0000848 int Result = BD.diffProgram(TestModuleBC.toString(), SharedObject, false);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000849
850 if (Result)
Dan Gohman65f57c22009-07-15 16:35:29 +0000851 errs() << ": still failing!\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000852 else
Dan Gohman65f57c22009-07-15 16:35:29 +0000853 errs() << ": didn't fail.\n";
Reid Spencera229c5c2005-07-08 03:08:58 +0000854 TestModuleBC.eraseFromDisk();
855 SafeModuleBC.eraseFromDisk();
856 sys::Path(SharedObject).eraseFromDisk();
Chris Lattnera57d86b2004-04-05 22:58:16 +0000857
858 return Result;
859}
860
861
Misha Brukman8c194ea2004-04-21 18:36:43 +0000862/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
863///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000864bool BugDriver::debugCodeGenerator() {
Dan Gohman70ef4492008-12-08 04:02:47 +0000865 if ((void*)SafeInterpreter == (void*)Interpreter) {
866 std::string Result = executeProgramSafely("bugpoint.safe.out");
Dan Gohmanac95cc72009-07-16 15:30:09 +0000867 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
868 << "the reference diff. This may be due to a\n front-end "
869 << "bug or a bug in the original program, but this can also "
870 << "happen if bugpoint isn't running the program with the "
871 << "right flags or input.\n I left the result of executing "
872 << "the program with the \"safe\" backend in this file for "
873 << "you: '"
874 << Result << "'.\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000875 return true;
876 }
877
878 DisambiguateGlobalSymbols(Program);
879
880 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
881
882 // Split the module into the two halves of the program we want.
Dan Gohmand50330c2009-04-22 15:57:18 +0000883 DenseMap<const Value*, Value*> ValueMap;
884 Module *ToNotCodeGen = CloneModule(getProgram(), ValueMap);
885 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, ValueMap);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000886
887 // Condition the modules
888 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
889
Reid Spencer97182982004-12-15 01:53:08 +0000890 sys::Path TestModuleBC("bugpoint.test.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000891 std::string ErrMsg;
892 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000893 errs() << getToolName() << "Error making unique filename: "
894 << ErrMsg << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +0000895 exit(1);
896 }
Reid Spencer97182982004-12-15 01:53:08 +0000897
898 if (writeProgramToFile(TestModuleBC.toString(), ToCodeGen)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000899 errs() << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000900 exit(1);
901 }
902 delete ToCodeGen;
903
904 // Make the shared library
Reid Spencer97182982004-12-15 01:53:08 +0000905 sys::Path SafeModuleBC("bugpoint.safe.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000906 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000907 errs() << getToolName() << "Error making unique filename: "
908 << ErrMsg << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +0000909 exit(1);
910 }
Reid Spencer97182982004-12-15 01:53:08 +0000911
912 if (writeProgramToFile(SafeModuleBC.toString(), ToNotCodeGen)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000913 errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000914 exit(1);
915 }
Reid Spencer97182982004-12-15 01:53:08 +0000916 std::string SharedObject = compileSharedObject(SafeModuleBC.toString());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000917 delete ToNotCodeGen;
918
Dan Gohmanac95cc72009-07-16 15:30:09 +0000919 outs() << "You can reproduce the problem with the command line: \n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000920 if (isExecutingJIT()) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000921 outs() << " lli -load " << SharedObject << " " << TestModuleBC;
Chris Lattnera57d86b2004-04-05 22:58:16 +0000922 } else {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000923 outs() << " llc -f " << TestModuleBC << " -o " << TestModuleBC<< ".s\n";
924 outs() << " gcc " << SharedObject << " " << TestModuleBC
Chris Lattner59615f02005-01-15 00:07:19 +0000925 << ".s -o " << TestModuleBC << ".exe";
926#if defined (HAVE_LINK_R)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000927 outs() << " -Wl,-R.";
Chris Lattner59615f02005-01-15 00:07:19 +0000928#endif
Dan Gohmanac95cc72009-07-16 15:30:09 +0000929 outs() << "\n";
930 outs() << " " << TestModuleBC << ".exe";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000931 }
932 for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000933 outs() << " " << InputArgv[i];
934 outs() << '\n';
935 outs() << "The shared object was created with:\n llc -march=c "
936 << SafeModuleBC << " -o temporary.c\n"
937 << " gcc -xc temporary.c -O2 -o " << SharedObject
Chris Lattnera57d86b2004-04-05 22:58:16 +0000938#if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000939 << " -G" // Compile a shared library, `-G' for Sparc
Chris Lattnera57d86b2004-04-05 22:58:16 +0000940#else
Dan Gohmanac95cc72009-07-16 15:30:09 +0000941 << " -fPIC -shared" // `-shared' for Linux/X86, maybe others
Chris Lattnera57d86b2004-04-05 22:58:16 +0000942#endif
Dan Gohmanac95cc72009-07-16 15:30:09 +0000943 << " -fno-strict-aliasing\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000944
945 return false;
946}