blob: 7e8ff78a9cf2404cb367886436899e23d233e874 [file] [log] [blame]
Chris Lattnerde4aa4c2002-12-23 23:50:16 +00001//===- Miscompilation.cpp - Debug program miscompilations -----------------===//
Misha Brukman650ba8e2005-04-22 00:00:37 +00002//
John Criswell09344dc2003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner345353d2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman650ba8e2005-04-22 00:00:37 +00007//
John Criswell09344dc2003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerde4aa4c2002-12-23 23:50:16 +00009//
Chris Lattnerbf791612004-04-05 22:58:16 +000010// This file implements optimizer and code generation miscompilation debugging
11// support.
Chris Lattnerde4aa4c2002-12-23 23:50:16 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "BugDriver.h"
Chris Lattner9f5a1972003-04-24 20:16:29 +000016#include "ListReducer.h"
Chris Lattnerbf791612004-04-05 22:58:16 +000017#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Instructions.h"
Reid Spencer16c3bb32004-11-14 23:00:08 +000020#include "llvm/Linker.h"
Chris Lattnerde4aa4c2002-12-23 23:50:16 +000021#include "llvm/Module.h"
Misha Brukman0c2305b2003-08-07 21:19:30 +000022#include "llvm/Pass.h"
Chris Lattnerbf791612004-04-05 22:58:16 +000023#include "llvm/Analysis/Verifier.h"
24#include "llvm/Support/Mangler.h"
Chris Lattner16a41312003-04-24 17:02:17 +000025#include "llvm/Transforms/Utils/Cloning.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000026#include "llvm/Support/CommandLine.h"
27#include "llvm/Support/FileUtilities.h"
Chris Lattnerea2fa462005-01-15 00:07:19 +000028#include "llvm/Config/config.h" // for HAVE_LINK_R
Chris Lattner2f1aa112004-01-14 03:38:37 +000029using namespace llvm;
Chris Lattnerde4aa4c2002-12-23 23:50:16 +000030
Chris Lattnerbf791612004-04-05 22:58:16 +000031namespace llvm {
32 extern cl::list<std::string> InputArgv;
33}
34
Chris Lattnerfd72bed2004-03-14 20:50:42 +000035namespace {
Reid Spencer471bcb72006-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));
40
Chris Lattner2f1aa112004-01-14 03:38:37 +000041 class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
42 BugDriver &BD;
43 public:
44 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +000045
Chris Lattner2f1aa112004-01-14 03:38:37 +000046 virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
47 std::vector<const PassInfo*> &Suffix);
48 };
49}
Chris Lattner16a41312003-04-24 17:02:17 +000050
Misha Brukman0784a602004-04-21 18:36:43 +000051/// TestResult - After passes have been split into a test group and a control
52/// group, see if they still break the program.
53///
Chris Lattner16a41312003-04-24 17:02:17 +000054ReduceMiscompilingPasses::TestResult
Chris Lattnerba159e22003-04-24 22:24:22 +000055ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
Chris Lattner4a1a9d22003-04-25 03:16:05 +000056 std::vector<const PassInfo*> &Suffix) {
57 // First, run the program with just the Suffix passes. If it is still broken
Chris Lattner16a41312003-04-24 17:02:17 +000058 // with JUST the kept passes, discard the prefix passes.
Chris Lattner4a1a9d22003-04-25 03:16:05 +000059 std::cout << "Checking to see if '" << getPassesString(Suffix)
Chris Lattner16a41312003-04-24 17:02:17 +000060 << "' compile correctly: ";
61
Gabor Greif0e535c3c2007-07-04 21:55:50 +000062 std::string BitcodeResult;
63 if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Misha Brukman650ba8e2005-04-22 00:00:37 +000064 std::cerr << " Error running this sequence of passes"
Chris Lattner16a41312003-04-24 17:02:17 +000065 << " on the input program!\n";
Chris Lattner92a9f7a2003-10-17 23:07:47 +000066 BD.setPassesToRun(Suffix);
Gabor Greif0e535c3c2007-07-04 21:55:50 +000067 BD.EmitProgressBitcode("pass-error", false);
Chris Lattneread1dff2004-02-18 21:02:04 +000068 exit(BD.debugOptimizerCrash());
Chris Lattner16a41312003-04-24 17:02:17 +000069 }
70
71 // Check to see if the finished program matches the reference output...
Gabor Greif0e535c3c2007-07-04 21:55:50 +000072 if (BD.diffProgram(BitcodeResult, "", true /*delete bitcode*/)) {
Misha Brukman324e9e02004-04-22 20:02:09 +000073 std::cout << " nope.\n";
Chris Lattnerea2fa462005-01-15 00:07:19 +000074 if (Suffix.empty()) {
75 std::cerr << BD.getToolName() << ": I'm confused: the test fails when "
76 << "no passes are run, nondeterministic program?\n";
77 exit(1);
78 }
Misha Brukman324e9e02004-04-22 20:02:09 +000079 return KeepSuffix; // Miscompilation detected!
Chris Lattner16a41312003-04-24 17:02:17 +000080 }
Misha Brukman324e9e02004-04-22 20:02:09 +000081 std::cout << " yup.\n"; // No miscompilation!
Chris Lattner16a41312003-04-24 17:02:17 +000082
83 if (Prefix.empty()) return NoFailure;
84
Chris Lattner4a1a9d22003-04-25 03:16:05 +000085 // Next, see if the program is broken if we run the "prefix" passes first,
Misha Brukman7fdaab42003-07-14 17:20:40 +000086 // then separately run the "kept" passes.
Chris Lattner16a41312003-04-24 17:02:17 +000087 std::cout << "Checking to see if '" << getPassesString(Prefix)
88 << "' compile correctly: ";
89
90 // If it is not broken with the kept passes, it's possible that the prefix
91 // passes must be run before the kept passes to break it. If the program
92 // WORKS after the prefix passes, but then fails if running the prefix AND
Gabor Greif0e535c3c2007-07-04 21:55:50 +000093 // kept passes, we can update our bitcode file to include the result of the
Chris Lattner16a41312003-04-24 17:02:17 +000094 // prefix passes, then discard the prefix passes.
95 //
Gabor Greif0e535c3c2007-07-04 21:55:50 +000096 if (BD.runPasses(Prefix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Misha Brukman650ba8e2005-04-22 00:00:37 +000097 std::cerr << " Error running this sequence of passes"
Chris Lattner16a41312003-04-24 17:02:17 +000098 << " on the input program!\n";
Chris Lattner7d147ae2003-10-17 23:03:16 +000099 BD.setPassesToRun(Prefix);
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000100 BD.EmitProgressBitcode("pass-error", false);
Chris Lattneread1dff2004-02-18 21:02:04 +0000101 exit(BD.debugOptimizerCrash());
Chris Lattner16a41312003-04-24 17:02:17 +0000102 }
103
104 // If the prefix maintains the predicate by itself, only keep the prefix!
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000105 if (BD.diffProgram(BitcodeResult)) {
Misha Brukman324e9e02004-04-22 20:02:09 +0000106 std::cout << " nope.\n";
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000107 sys::Path(BitcodeResult).eraseFromDisk();
Chris Lattner16a41312003-04-24 17:02:17 +0000108 return KeepPrefix;
109 }
Misha Brukman324e9e02004-04-22 20:02:09 +0000110 std::cout << " yup.\n"; // No miscompilation!
Chris Lattner16a41312003-04-24 17:02:17 +0000111
112 // Ok, so now we know that the prefix passes work, try running the suffix
113 // passes on the result of the prefix passes.
114 //
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000115 Module *PrefixOutput = ParseInputFile(BitcodeResult);
Chris Lattner16a41312003-04-24 17:02:17 +0000116 if (PrefixOutput == 0) {
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000117 std::cerr << BD.getToolName() << ": Error reading bitcode file '"
118 << BitcodeResult << "'!\n";
Chris Lattner16a41312003-04-24 17:02:17 +0000119 exit(1);
120 }
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000121 sys::Path(BitcodeResult).eraseFromDisk(); // No longer need the file on disk
Chris Lattner02cea4a2004-04-23 20:36:51 +0000122
123 // Don't check if there are no passes in the suffix.
124 if (Suffix.empty())
125 return NoFailure;
Misha Brukman650ba8e2005-04-22 00:00:37 +0000126
Chris Lattner4a1a9d22003-04-25 03:16:05 +0000127 std::cout << "Checking to see if '" << getPassesString(Suffix)
Chris Lattner16a41312003-04-24 17:02:17 +0000128 << "' passes compile correctly after the '"
129 << getPassesString(Prefix) << "' passes: ";
130
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000131 Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000132 if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Misha Brukman650ba8e2005-04-22 00:00:37 +0000133 std::cerr << " Error running this sequence of passes"
Chris Lattner16a41312003-04-24 17:02:17 +0000134 << " on the input program!\n";
Chris Lattner92a9f7a2003-10-17 23:07:47 +0000135 BD.setPassesToRun(Suffix);
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000136 BD.EmitProgressBitcode("pass-error", false);
Chris Lattneread1dff2004-02-18 21:02:04 +0000137 exit(BD.debugOptimizerCrash());
Chris Lattner16a41312003-04-24 17:02:17 +0000138 }
139
140 // Run the result...
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000141 if (BD.diffProgram(BitcodeResult, "", true/*delete bitcode*/)) {
Misha Brukman324e9e02004-04-22 20:02:09 +0000142 std::cout << " nope.\n";
Chris Lattner16a41312003-04-24 17:02:17 +0000143 delete OriginalInput; // We pruned down the original input...
Chris Lattner4a1a9d22003-04-25 03:16:05 +0000144 return KeepSuffix;
Chris Lattner16a41312003-04-24 17:02:17 +0000145 }
146
147 // Otherwise, we must not be running the bad pass anymore.
Misha Brukman324e9e02004-04-22 20:02:09 +0000148 std::cout << " yup.\n"; // No miscompilation!
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000149 delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test
Chris Lattner16a41312003-04-24 17:02:17 +0000150 return NoFailure;
151}
152
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000153namespace {
Chris Lattner2f1aa112004-01-14 03:38:37 +0000154 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
155 BugDriver &BD;
Chris Lattner0434ba32004-04-05 21:37:38 +0000156 bool (*TestFn)(BugDriver &, Module *, Module *);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000157 public:
Chris Lattner0434ba32004-04-05 21:37:38 +0000158 ReduceMiscompilingFunctions(BugDriver &bd,
159 bool (*F)(BugDriver &, Module *, Module *))
160 : BD(bd), TestFn(F) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000161
Chris Lattner2f1aa112004-01-14 03:38:37 +0000162 virtual TestResult doTest(std::vector<Function*> &Prefix,
163 std::vector<Function*> &Suffix) {
Chris Lattner567543f2004-03-14 19:27:19 +0000164 if (!Suffix.empty() && TestFuncs(Suffix))
Chris Lattner2f1aa112004-01-14 03:38:37 +0000165 return KeepSuffix;
Chris Lattner567543f2004-03-14 19:27:19 +0000166 if (!Prefix.empty() && TestFuncs(Prefix))
Chris Lattner2f1aa112004-01-14 03:38:37 +0000167 return KeepPrefix;
168 return NoFailure;
169 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000170
Chris Lattner567543f2004-03-14 19:27:19 +0000171 bool TestFuncs(const std::vector<Function*> &Prefix);
Chris Lattner2f1aa112004-01-14 03:38:37 +0000172 };
173}
Chris Lattner16a41312003-04-24 17:02:17 +0000174
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000175/// TestMergedProgram - Given two modules, link them together and run the
176/// program, checking to see if the program matches the diff. If the diff
Chris Lattnerbcec7872004-03-14 22:08:00 +0000177/// matches, return false, otherwise return true. If the DeleteInputs argument
178/// is set to true then this function deletes both input modules before it
179/// returns.
Misha Brukman0784a602004-04-21 18:36:43 +0000180///
Chris Lattnerbcec7872004-03-14 22:08:00 +0000181static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
182 bool DeleteInputs) {
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000183 // Link the two portions of the program back to together.
184 std::string ErrorMsg;
Chris Lattnerd3087972004-11-16 06:31:38 +0000185 if (!DeleteInputs) {
186 M1 = CloneModule(M1);
187 M2 = CloneModule(M2);
188 }
Reid Spencer0ebb9262004-12-13 03:01:03 +0000189 if (Linker::LinkModules(M1, M2, &ErrorMsg)) {
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000190 std::cerr << BD.getToolName() << ": Error linking modules together:"
Misha Brukman6aa3c832004-07-23 01:30:49 +0000191 << ErrorMsg << '\n';
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000192 exit(1);
193 }
Chris Lattnerd3087972004-11-16 06:31:38 +0000194 delete M2; // We are done with this module.
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000195
196 Module *OldProgram = BD.swapProgramIn(M1);
197
198 // Execute the program. If it does not match the expected output, we must
199 // return true.
200 bool Broken = BD.diffProgram();
201
202 // Delete the linked module & restore the original
Chris Lattnerbcec7872004-03-14 22:08:00 +0000203 BD.swapProgramIn(OldProgram);
Chris Lattnera413b082004-04-02 06:32:17 +0000204 delete M1;
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000205 return Broken;
206}
207
Misha Brukman0784a602004-04-21 18:36:43 +0000208/// TestFuncs - split functions in a Module into two groups: those that are
209/// under consideration for miscompilation vs. those that are not, and test
210/// accordingly. Each group of functions becomes a separate Module.
211///
Chris Lattner567543f2004-03-14 19:27:19 +0000212bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
Chris Lattner16a41312003-04-24 17:02:17 +0000213 // Test to see if the function is misoptimized if we ONLY run it on the
214 // functions listed in Funcs.
Chris Lattner567543f2004-03-14 19:27:19 +0000215 std::cout << "Checking to see if the program is misoptimized when "
216 << (Funcs.size()==1 ? "this function is" : "these functions are")
217 << " run through the pass"
Chris Lattnerbcec7872004-03-14 22:08:00 +0000218 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000219 PrintFunctionList(Funcs);
Misha Brukman6aa3c832004-07-23 01:30:49 +0000220 std::cout << '\n';
Chris Lattner16a41312003-04-24 17:02:17 +0000221
Chris Lattner567543f2004-03-14 19:27:19 +0000222 // Split the module into the two halves of the program we want.
Dan Gohman956ae9d2009-04-22 15:57:18 +0000223 DenseMap<const Value*, Value*> ValueMap;
224 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
225 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, Funcs,
226 ValueMap);
Chris Lattner16a41312003-04-24 17:02:17 +0000227
Nick Lewyckyc6243022007-11-14 06:47:06 +0000228 // Run the predicate, note that the predicate will delete both input modules.
Chris Lattner0434ba32004-04-05 21:37:38 +0000229 return TestFn(BD, ToOptimize, ToNotOptimize);
Chris Lattner16a41312003-04-24 17:02:17 +0000230}
231
Misha Brukman0784a602004-04-21 18:36:43 +0000232/// DisambiguateGlobalSymbols - Mangle symbols to guarantee uniqueness by
233/// modifying predominantly internal symbols rather than external ones.
234///
Chris Lattnerdfbb1d12004-04-11 23:52:35 +0000235static void DisambiguateGlobalSymbols(Module *M) {
236 // Try not to cause collisions by minimizing chances of renaming an
237 // already-external symbol, so take in external globals and functions as-is.
238 // The code should work correctly without disambiguation (assuming the same
239 // mangler is used by the two code generators), but having symbols with the
240 // same name causes warnings to be emitted by the code generator.
241 Mangler Mang(*M);
Andrew Lenharth312e6552005-12-06 20:51:30 +0000242 // Agree with the CBE on symbol naming
243 Mang.markCharUnacceptable('.');
Chris Lattner3b18c1a2006-09-07 18:21:07 +0000244 Mang.setPreserveAsmNames(true);
Chris Lattner34d26c32006-05-04 23:35:31 +0000245 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
246 I != E; ++I)
Chris Lattnerdfbb1d12004-04-11 23:52:35 +0000247 I->setName(Mang.getValueName(I));
248 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
249 I->setName(Mang.getValueName(I));
250}
251
Chris Lattnerbcec7872004-03-14 22:08:00 +0000252/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
253/// check to see if we can extract the loops in the region without obscuring the
254/// bug. If so, it reduces the amount of code identified.
Misha Brukman0784a602004-04-21 18:36:43 +0000255///
Chris Lattner0434ba32004-04-05 21:37:38 +0000256static bool ExtractLoops(BugDriver &BD,
257 bool (*TestFn)(BugDriver &, Module *, Module *),
Chris Lattnerbcec7872004-03-14 22:08:00 +0000258 std::vector<Function*> &MiscompiledFunctions) {
259 bool MadeChange = false;
260 while (1) {
Chris Lattnerbd615f52005-08-02 23:25:56 +0000261 if (BugpointIsInterrupted) return MadeChange;
262
Dan Gohman956ae9d2009-04-22 15:57:18 +0000263 DenseMap<const Value*, Value*> ValueMap;
264 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
Chris Lattnerbcec7872004-03-14 22:08:00 +0000265 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohman956ae9d2009-04-22 15:57:18 +0000266 MiscompiledFunctions,
267 ValueMap);
Chris Lattnerbcec7872004-03-14 22:08:00 +0000268 Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
269 if (!ToOptimizeLoopExtracted) {
270 // If the loop extractor crashed or if there were no extractible loops,
271 // then this chapter of our odyssey is over with.
272 delete ToNotOptimize;
273 delete ToOptimize;
274 return MadeChange;
275 }
276
277 std::cerr << "Extracted a loop from the breaking portion of the program.\n";
Chris Lattnerbcec7872004-03-14 22:08:00 +0000278
279 // Bugpoint is intentionally not very trusting of LLVM transformations. In
280 // particular, we're not going to assume that the loop extractor works, so
281 // we're going to test the newly loop extracted program to make sure nothing
282 // has broken. If something broke, then we'll inform the user and stop
283 // extraction.
Dan Gohman414cf502008-12-08 04:02:47 +0000284 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
Chris Lattnerbcec7872004-03-14 22:08:00 +0000285 if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
Chris Lattnerbf791612004-04-05 22:58:16 +0000286 BD.switchToInterpreter(AI);
287
Chris Lattnerbcec7872004-03-14 22:08:00 +0000288 // Merged program doesn't work anymore!
289 std::cerr << " *** ERROR: Loop extraction broke the program. :("
290 << " Please report a bug!\n";
291 std::cerr << " Continuing on with un-loop-extracted version.\n";
Chris Lattner257008b2005-05-08 21:54:56 +0000292
293 BD.writeProgramToFile("bugpoint-loop-extract-fail-tno.bc", ToNotOptimize);
294 BD.writeProgramToFile("bugpoint-loop-extract-fail-to.bc", ToOptimize);
295 BD.writeProgramToFile("bugpoint-loop-extract-fail-to-le.bc",
296 ToOptimizeLoopExtracted);
297
298 std::cerr << "Please submit the bugpoint-loop-extract-fail-*.bc files.\n";
299 delete ToOptimize;
Chris Lattnerbcec7872004-03-14 22:08:00 +0000300 delete ToNotOptimize;
301 delete ToOptimizeLoopExtracted;
302 return MadeChange;
303 }
Chris Lattner257008b2005-05-08 21:54:56 +0000304 delete ToOptimize;
Chris Lattnerbf791612004-04-05 22:58:16 +0000305 BD.switchToInterpreter(AI);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000306
Chris Lattner0434ba32004-04-05 21:37:38 +0000307 std::cout << " Testing after loop extraction:\n";
308 // Clone modules, the tester function will free them.
309 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
310 Module *TNOBackup = CloneModule(ToNotOptimize);
311 if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
312 std::cout << "*** Loop extraction masked the problem. Undoing.\n";
Chris Lattnerbcec7872004-03-14 22:08:00 +0000313 // If the program is not still broken, then loop extraction did something
314 // that masked the error. Stop loop extraction now.
Chris Lattner0434ba32004-04-05 21:37:38 +0000315 delete TOLEBackup;
316 delete TNOBackup;
Chris Lattnerbcec7872004-03-14 22:08:00 +0000317 return MadeChange;
318 }
Chris Lattner0434ba32004-04-05 21:37:38 +0000319 ToOptimizeLoopExtracted = TOLEBackup;
320 ToNotOptimize = TNOBackup;
321
322 std::cout << "*** Loop extraction successful!\n";
Chris Lattnerbcec7872004-03-14 22:08:00 +0000323
Chris Lattnerd3087972004-11-16 06:31:38 +0000324 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
325 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
326 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
Reid Spencer5301e7c2007-01-30 20:08:39 +0000327 if (!I->isDeclaration())
Chris Lattnerdad18232004-11-19 07:09:40 +0000328 MisCompFunctions.push_back(std::make_pair(I->getName(),
329 I->getFunctionType()));
Chris Lattnerd3087972004-11-16 06:31:38 +0000330
Chris Lattnerbcec7872004-03-14 22:08:00 +0000331 // Okay, great! Now we know that we extracted a loop and that loop
332 // extraction both didn't break the program, and didn't mask the problem.
333 // Replace the current program with the loop extracted version, and try to
334 // extract another loop.
335 std::string ErrorMsg;
Reid Spencer0ebb9262004-12-13 03:01:03 +0000336 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
Chris Lattnerbcec7872004-03-14 22:08:00 +0000337 std::cerr << BD.getToolName() << ": Error linking modules together:"
Misha Brukman6aa3c832004-07-23 01:30:49 +0000338 << ErrorMsg << '\n';
Chris Lattnerbcec7872004-03-14 22:08:00 +0000339 exit(1);
340 }
Chris Lattnerd3087972004-11-16 06:31:38 +0000341 delete ToOptimizeLoopExtracted;
Chris Lattnerb38cc9c2004-03-17 17:42:09 +0000342
343 // All of the Function*'s in the MiscompiledFunctions list are in the old
Chris Lattnera413b082004-04-02 06:32:17 +0000344 // module. Update this list to include all of the functions in the
345 // optimized and loop extracted module.
346 MiscompiledFunctions.clear();
Chris Lattnerd3087972004-11-16 06:31:38 +0000347 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000348 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
349
Chris Lattnerd3087972004-11-16 06:31:38 +0000350 assert(NewF && "Function not found??");
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000351 assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
352 "found wrong function type?");
Chris Lattnerd3087972004-11-16 06:31:38 +0000353 MiscompiledFunctions.push_back(NewF);
Chris Lattnerb38cc9c2004-03-17 17:42:09 +0000354 }
355
Chris Lattnerbcec7872004-03-14 22:08:00 +0000356 BD.setNewProgram(ToNotOptimize);
357 MadeChange = true;
358 }
359}
360
Chris Lattnera060b102004-05-11 21:54:13 +0000361namespace {
362 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
363 BugDriver &BD;
364 bool (*TestFn)(BugDriver &, Module *, Module *);
365 std::vector<Function*> FunctionsBeingTested;
366 public:
367 ReduceMiscompiledBlocks(BugDriver &bd,
368 bool (*F)(BugDriver &, Module *, Module *),
369 const std::vector<Function*> &Fns)
370 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
Misha Brukman650ba8e2005-04-22 00:00:37 +0000371
Chris Lattnera060b102004-05-11 21:54:13 +0000372 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
373 std::vector<BasicBlock*> &Suffix) {
374 if (!Suffix.empty() && TestFuncs(Suffix))
375 return KeepSuffix;
376 if (TestFuncs(Prefix))
377 return KeepPrefix;
378 return NoFailure;
379 }
Misha Brukman650ba8e2005-04-22 00:00:37 +0000380
Chris Lattnera060b102004-05-11 21:54:13 +0000381 bool TestFuncs(const std::vector<BasicBlock*> &Prefix);
382 };
383}
384
385/// TestFuncs - Extract all blocks for the miscompiled functions except for the
386/// specified blocks. If the problem still exists, return true.
387///
388bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) {
389 // Test to see if the function is misoptimized if we ONLY run it on the
390 // functions listed in Funcs.
Chris Lattner6c0c3132004-05-12 16:08:01 +0000391 std::cout << "Checking to see if the program is misoptimized when all ";
392 if (!BBs.empty()) {
393 std::cout << "but these " << BBs.size() << " blocks are extracted: ";
394 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
395 std::cout << BBs[i]->getName() << " ";
396 if (BBs.size() > 10) std::cout << "...";
397 } else {
398 std::cout << "blocks are extracted.";
399 }
Misha Brukman6aa3c832004-07-23 01:30:49 +0000400 std::cout << '\n';
Chris Lattnera060b102004-05-11 21:54:13 +0000401
402 // Split the module into the two halves of the program we want.
Dan Gohman956ae9d2009-04-22 15:57:18 +0000403 DenseMap<const Value*, Value*> ValueMap;
404 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
Chris Lattnera060b102004-05-11 21:54:13 +0000405 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohman956ae9d2009-04-22 15:57:18 +0000406 FunctionsBeingTested,
407 ValueMap);
Chris Lattnera060b102004-05-11 21:54:13 +0000408
409 // Try the extraction. If it doesn't work, then the block extractor crashed
410 // or something, in which case bugpoint can't chase down this possibility.
411 if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) {
412 delete ToOptimize;
413 // Run the predicate, not that the predicate will delete both input modules.
414 return TestFn(BD, New, ToNotOptimize);
415 }
416 delete ToOptimize;
417 delete ToNotOptimize;
418 return false;
419}
420
421
422/// ExtractBlocks - Given a reduced list of functions that still expose the bug,
423/// extract as many basic blocks from the region as possible without obscuring
424/// the bug.
425///
426static bool ExtractBlocks(BugDriver &BD,
427 bool (*TestFn)(BugDriver &, Module *, Module *),
428 std::vector<Function*> &MiscompiledFunctions) {
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000429 if (BugpointIsInterrupted) return false;
430
Chris Lattnera060b102004-05-11 21:54:13 +0000431 std::vector<BasicBlock*> Blocks;
432 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
433 for (Function::iterator I = MiscompiledFunctions[i]->begin(),
434 E = MiscompiledFunctions[i]->end(); I != E; ++I)
435 Blocks.push_back(I);
436
437 // Use the list reducer to identify blocks that can be extracted without
438 // obscuring the bug. The Blocks list will end up containing blocks that must
439 // be retained from the original program.
440 unsigned OldSize = Blocks.size();
Chris Lattner6c0c3132004-05-12 16:08:01 +0000441
442 // Check to see if all blocks are extractible first.
443 if (ReduceMiscompiledBlocks(BD, TestFn,
444 MiscompiledFunctions).TestFuncs(std::vector<BasicBlock*>())) {
445 Blocks.clear();
446 } else {
447 ReduceMiscompiledBlocks(BD, TestFn,MiscompiledFunctions).reduceList(Blocks);
448 if (Blocks.size() == OldSize)
449 return false;
450 }
Chris Lattnera060b102004-05-11 21:54:13 +0000451
Dan Gohman956ae9d2009-04-22 15:57:18 +0000452 DenseMap<const Value*, Value*> ValueMap;
453 Module *ProgClone = CloneModule(BD.getProgram(), ValueMap);
Chris Lattner49e4a332004-05-12 02:43:24 +0000454 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
Dan Gohman956ae9d2009-04-22 15:57:18 +0000455 MiscompiledFunctions,
456 ValueMap);
Chris Lattner49e4a332004-05-12 02:43:24 +0000457 Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
458 if (Extracted == 0) {
Chris Lattner0ce80cd2005-02-27 06:18:25 +0000459 // Weird, extraction should have worked.
Chris Lattner49e4a332004-05-12 02:43:24 +0000460 std::cerr << "Nondeterministic problem extracting blocks??\n";
461 delete ProgClone;
462 delete ToExtract;
463 return false;
464 }
Chris Lattnera060b102004-05-11 21:54:13 +0000465
Chris Lattner49e4a332004-05-12 02:43:24 +0000466 // Otherwise, block extraction succeeded. Link the two program fragments back
467 // together.
468 delete ToExtract;
Chris Lattnera060b102004-05-11 21:54:13 +0000469
Chris Lattnerd3087972004-11-16 06:31:38 +0000470 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
471 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
472 I != E; ++I)
Reid Spencer5301e7c2007-01-30 20:08:39 +0000473 if (!I->isDeclaration())
Chris Lattnerdad18232004-11-19 07:09:40 +0000474 MisCompFunctions.push_back(std::make_pair(I->getName(),
475 I->getFunctionType()));
Chris Lattnerd3087972004-11-16 06:31:38 +0000476
Chris Lattner49e4a332004-05-12 02:43:24 +0000477 std::string ErrorMsg;
Reid Spencer0ebb9262004-12-13 03:01:03 +0000478 if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
Chris Lattner49e4a332004-05-12 02:43:24 +0000479 std::cerr << BD.getToolName() << ": Error linking modules together:"
Misha Brukman6aa3c832004-07-23 01:30:49 +0000480 << ErrorMsg << '\n';
Chris Lattner49e4a332004-05-12 02:43:24 +0000481 exit(1);
482 }
Chris Lattnerd3087972004-11-16 06:31:38 +0000483 delete Extracted;
Chris Lattnera060b102004-05-11 21:54:13 +0000484
Chris Lattner49e4a332004-05-12 02:43:24 +0000485 // Set the new program and delete the old one.
486 BD.setNewProgram(ProgClone);
Chris Lattnera060b102004-05-11 21:54:13 +0000487
Chris Lattner49e4a332004-05-12 02:43:24 +0000488 // Update the list of miscompiled functions.
489 MiscompiledFunctions.clear();
Chris Lattnera060b102004-05-11 21:54:13 +0000490
Chris Lattnerd3087972004-11-16 06:31:38 +0000491 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000492 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
Chris Lattnerd3087972004-11-16 06:31:38 +0000493 assert(NewF && "Function not found??");
Reid Spencer3aaaa0b2007-02-05 20:47:22 +0000494 assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
495 "Function has wrong type??");
Chris Lattnerd3087972004-11-16 06:31:38 +0000496 MiscompiledFunctions.push_back(NewF);
497 }
Chris Lattner49e4a332004-05-12 02:43:24 +0000498
499 return true;
Chris Lattnera060b102004-05-11 21:54:13 +0000500}
501
502
Chris Lattner0434ba32004-04-05 21:37:38 +0000503/// DebugAMiscompilation - This is a generic driver to narrow down
504/// miscompilations, either in an optimization or a code generator.
Misha Brukman0784a602004-04-21 18:36:43 +0000505///
Chris Lattner0434ba32004-04-05 21:37:38 +0000506static std::vector<Function*>
507DebugAMiscompilation(BugDriver &BD,
508 bool (*TestFn)(BugDriver &, Module *, Module *)) {
509 // Okay, now that we have reduced the list of passes which are causing the
510 // failure, see if we can pin down which functions are being
511 // miscompiled... first build a list of all of the non-external functions in
512 // the program.
513 std::vector<Function*> MiscompiledFunctions;
514 Module *Prog = BD.getProgram();
515 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
Reid Spencer5301e7c2007-01-30 20:08:39 +0000516 if (!I->isDeclaration())
Chris Lattner0434ba32004-04-05 21:37:38 +0000517 MiscompiledFunctions.push_back(I);
518
519 // Do the reduction...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000520 if (!BugpointIsInterrupted)
521 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Chris Lattner0434ba32004-04-05 21:37:38 +0000522
523 std::cout << "\n*** The following function"
524 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
525 << " being miscompiled: ";
526 PrintFunctionList(MiscompiledFunctions);
Misha Brukman6aa3c832004-07-23 01:30:49 +0000527 std::cout << '\n';
Chris Lattner0434ba32004-04-05 21:37:38 +0000528
529 // See if we can rip any loops out of the miscompiled functions and still
530 // trigger the problem.
Reid Spencer471bcb72006-11-11 19:05:02 +0000531
Reid Spencer3005d472006-11-11 19:59:25 +0000532 if (!BugpointIsInterrupted && !DisableLoopExtraction &&
533 ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
Chris Lattner0434ba32004-04-05 21:37:38 +0000534 // Okay, we extracted some loops and the problem still appears. See if we
535 // can eliminate some of the created functions from being candidates.
536
Chris Lattnerdfbb1d12004-04-11 23:52:35 +0000537 // Loop extraction can introduce functions with the same name (foo_code).
538 // Make sure to disambiguate the symbols so that when the program is split
539 // apart that we can link it back together again.
540 DisambiguateGlobalSymbols(BD.getProgram());
541
Chris Lattner0434ba32004-04-05 21:37:38 +0000542 // Do the reduction...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000543 if (!BugpointIsInterrupted)
544 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000545
Chris Lattner0434ba32004-04-05 21:37:38 +0000546 std::cout << "\n*** The following function"
547 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
548 << " being miscompiled: ";
549 PrintFunctionList(MiscompiledFunctions);
Misha Brukman6aa3c832004-07-23 01:30:49 +0000550 std::cout << '\n';
Chris Lattner0434ba32004-04-05 21:37:38 +0000551 }
552
Chris Lattnerbd615f52005-08-02 23:25:56 +0000553 if (!BugpointIsInterrupted &&
554 ExtractBlocks(BD, TestFn, MiscompiledFunctions)) {
Chris Lattnera060b102004-05-11 21:54:13 +0000555 // Okay, we extracted some blocks and the problem still appears. See if we
556 // can eliminate some of the created functions from being candidates.
557
558 // Block extraction can introduce functions with the same name (foo_code).
559 // Make sure to disambiguate the symbols so that when the program is split
560 // apart that we can link it back together again.
561 DisambiguateGlobalSymbols(BD.getProgram());
562
563 // Do the reduction...
564 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000565
Chris Lattnera060b102004-05-11 21:54:13 +0000566 std::cout << "\n*** The following function"
567 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
568 << " being miscompiled: ";
569 PrintFunctionList(MiscompiledFunctions);
Misha Brukman6aa3c832004-07-23 01:30:49 +0000570 std::cout << '\n';
Chris Lattnera060b102004-05-11 21:54:13 +0000571 }
572
Chris Lattner0434ba32004-04-05 21:37:38 +0000573 return MiscompiledFunctions;
574}
575
Chris Lattnerbf791612004-04-05 22:58:16 +0000576/// TestOptimizer - This is the predicate function used to check to see if the
577/// "Test" portion of the program is misoptimized. If so, return true. In any
578/// case, both module arguments are deleted.
Misha Brukman0784a602004-04-21 18:36:43 +0000579///
Chris Lattner0434ba32004-04-05 21:37:38 +0000580static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
581 // Run the optimization passes on ToOptimize, producing a transformed version
582 // of the functions being tested.
583 std::cout << " Optimizing functions being tested: ";
584 Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
585 /*AutoDebugCrashes*/true);
586 std::cout << "done.\n";
587 delete Test;
588
589 std::cout << " Checking to see if the merged program executes correctly: ";
Chris Lattner5bcb4eb2004-04-09 22:28:33 +0000590 bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
Chris Lattner0434ba32004-04-05 21:37:38 +0000591 std::cout << (Broken ? " nope.\n" : " yup.\n");
592 return Broken;
593}
594
595
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000596/// debugMiscompilation - This method is used when the passes selected are not
597/// crashing, but the generated output is semantically different from the
598/// input.
599///
600bool BugDriver::debugMiscompilation() {
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000601 // Make sure something was miscompiled...
Chris Lattnerbeb01fa2005-08-02 02:16:17 +0000602 if (!BugpointIsInterrupted)
603 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
604 std::cerr << "*** Optimized program matches reference output! No problem"
605 << " detected...\nbugpoint can't help you with your problem!\n";
606 return false;
607 }
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000608
Chris Lattner16a41312003-04-24 17:02:17 +0000609 std::cout << "\n*** Found miscompiling pass"
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000610 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
Misha Brukman6aa3c832004-07-23 01:30:49 +0000611 << getPassesString(getPassesToRun()) << '\n';
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000612 EmitProgressBitcode("passinput");
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000613
Chris Lattner0434ba32004-04-05 21:37:38 +0000614 std::vector<Function*> MiscompiledFunctions =
615 DebugAMiscompilation(*this, TestOptimizer);
Chris Lattnerbcec7872004-03-14 22:08:00 +0000616
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000617 // Output a bunch of bitcode files for the user...
618 std::cout << "Outputting reduced bitcode files which expose the problem:\n";
Dan Gohman956ae9d2009-04-22 15:57:18 +0000619 DenseMap<const Value*, Value*> ValueMap;
620 Module *ToNotOptimize = CloneModule(getProgram(), ValueMap);
Chris Lattnerfd72bed2004-03-14 20:50:42 +0000621 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohman956ae9d2009-04-22 15:57:18 +0000622 MiscompiledFunctions,
623 ValueMap);
Chris Lattner567543f2004-03-14 19:27:19 +0000624
625 std::cout << " Non-optimized portion: ";
Chris Lattner0434ba32004-04-05 21:37:38 +0000626 ToNotOptimize = swapProgramIn(ToNotOptimize);
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000627 EmitProgressBitcode("tonotoptimize", true);
Chris Lattner567543f2004-03-14 19:27:19 +0000628 setNewProgram(ToNotOptimize); // Delete hacked module.
Misha Brukman650ba8e2005-04-22 00:00:37 +0000629
Chris Lattner567543f2004-03-14 19:27:19 +0000630 std::cout << " Portion that is input to optimizer: ";
Chris Lattner0434ba32004-04-05 21:37:38 +0000631 ToOptimize = swapProgramIn(ToOptimize);
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000632 EmitProgressBitcode("tooptimize");
Chris Lattner567543f2004-03-14 19:27:19 +0000633 setNewProgram(ToOptimize); // Delete hacked module.
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000634
Chris Lattnerde4aa4c2002-12-23 23:50:16 +0000635 return false;
636}
Brian Gaeke960707c2003-11-11 22:41:34 +0000637
Chris Lattnerbf791612004-04-05 22:58:16 +0000638/// CleanupAndPrepareModules - Get the specified modules ready for code
639/// generator testing.
Misha Brukman0784a602004-04-21 18:36:43 +0000640///
Chris Lattnerbf791612004-04-05 22:58:16 +0000641static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
642 Module *Safe) {
643 // Clean up the modules, removing extra cruft that we don't need anymore...
644 Test = BD.performFinalCleanups(Test);
645
646 // If we are executing the JIT, we have several nasty issues to take care of.
647 if (!BD.isExecutingJIT()) return;
648
649 // First, if the main function is in the Safe module, we must add a stub to
650 // the Test module to call into it. Thus, we create a new function `main'
651 // which just calls the old one.
Reid Spencer1241d6d2007-02-05 21:19:13 +0000652 if (Function *oldMain = Safe->getFunction("main"))
Reid Spencer5301e7c2007-01-30 20:08:39 +0000653 if (!oldMain->isDeclaration()) {
Chris Lattnerbf791612004-04-05 22:58:16 +0000654 // Rename it
655 oldMain->setName("llvm_bugpoint_old_main");
656 // Create a NEW `main' function with same type in the test module.
Gabor Greife9ecc682008-04-06 20:25:17 +0000657 Function *newMain = Function::Create(oldMain->getFunctionType(),
658 GlobalValue::ExternalLinkage,
659 "main", Test);
Chris Lattnerbf791612004-04-05 22:58:16 +0000660 // Create an `oldmain' prototype in the test module, which will
661 // corresponds to the real main function in the same module.
Gabor Greife9ecc682008-04-06 20:25:17 +0000662 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
663 GlobalValue::ExternalLinkage,
664 oldMain->getName(), Test);
Chris Lattnerbf791612004-04-05 22:58:16 +0000665 // Set up and remember the argument list for the main function.
666 std::vector<Value*> args;
Alkis Evlogimenosa67bafa2005-03-15 07:02:26 +0000667 for (Function::arg_iterator
668 I = newMain->arg_begin(), E = newMain->arg_end(),
669 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
Owen Anderson7629b712008-04-14 17:38:21 +0000670 I->setName(OI->getName()); // Copy argument names from oldMain
Chris Lattnerbf791612004-04-05 22:58:16 +0000671 args.push_back(I);
672 }
673
674 // Call the old main function and return its result
Gabor Greife9ecc682008-04-06 20:25:17 +0000675 BasicBlock *BB = BasicBlock::Create("entry", newMain);
676 CallInst *call = CallInst::Create(oldMainProto, args.begin(), args.end(),
677 "", BB);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000678
Chris Lattnerbf791612004-04-05 22:58:16 +0000679 // If the type of old function wasn't void, return value of call
Gabor Greife9ecc682008-04-06 20:25:17 +0000680 ReturnInst::Create(call, BB);
Chris Lattnerbf791612004-04-05 22:58:16 +0000681 }
682
683 // The second nasty issue we must deal with in the JIT is that the Safe
684 // module cannot directly reference any functions defined in the test
685 // module. Instead, we use a JIT API call to dynamically resolve the
686 // symbol.
Misha Brukman650ba8e2005-04-22 00:00:37 +0000687
Chris Lattnerbf791612004-04-05 22:58:16 +0000688 // Add the resolver to the Safe module.
689 // Prototype: void *getPointerToNamedFunction(const char* Name)
Chris Lattner7b864c02007-01-07 08:13:39 +0000690 Constant *resolverFunc =
Chris Lattnerbf791612004-04-05 22:58:16 +0000691 Safe->getOrInsertFunction("getPointerToNamedFunction",
Christopher Lambedf07882007-12-17 01:12:55 +0000692 PointerType::getUnqual(Type::Int8Ty),
693 PointerType::getUnqual(Type::Int8Ty), (Type *)0);
Misha Brukman650ba8e2005-04-22 00:00:37 +0000694
Chris Lattnerbf791612004-04-05 22:58:16 +0000695 // Use the function we just added to get addresses of functions we need.
Misha Brukman83018642004-04-19 01:12:01 +0000696 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
Reid Spencer5301e7c2007-01-30 20:08:39 +0000697 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
Duncan Sands38ef3a82007-12-03 20:06:50 +0000698 !F->isIntrinsic() /* ignore intrinsics */) {
Reid Spencer1241d6d2007-02-05 21:19:13 +0000699 Function *TestFn = Test->getFunction(F->getName());
Chris Lattnerbf791612004-04-05 22:58:16 +0000700
701 // Don't forward functions which are external in the test module too.
Reid Spencer5301e7c2007-01-30 20:08:39 +0000702 if (TestFn && !TestFn->isDeclaration()) {
Chris Lattnerbf791612004-04-05 22:58:16 +0000703 // 1. Add a string constant with its name to the global file
704 Constant *InitArray = ConstantArray::get(F->getName());
705 GlobalVariable *funcName =
706 new GlobalVariable(InitArray->getType(), true /*isConstant*/,
Misha Brukman650ba8e2005-04-22 00:00:37 +0000707 GlobalValue::InternalLinkage, InitArray,
Chris Lattnerbf791612004-04-05 22:58:16 +0000708 F->getName() + "_name", Safe);
709
710 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
711 // sbyte* so it matches the signature of the resolver function.
712
713 // GetElementPtr *funcName, ulong 0, ulong 0
Reid Spencereb14edc2006-12-31 06:02:26 +0000714 std::vector<Constant*> GEPargs(2,Constant::getNullValue(Type::Int32Ty));
Chris Lattner86e36db2007-02-19 07:41:31 +0000715 Value *GEP = ConstantExpr::getGetElementPtr(funcName, &GEPargs[0], 2);
Chris Lattnerbf791612004-04-05 22:58:16 +0000716 std::vector<Value*> ResolverArgs;
717 ResolverArgs.push_back(GEP);
718
Misha Brukmance89b392004-04-19 03:36:47 +0000719 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
720 // function that dynamically resolves the calls to F via our JIT API
Chris Lattner986675c2005-07-12 01:00:32 +0000721 if (!F->use_empty()) {
722 // Create a new global to hold the cached function pointer.
723 Constant *NullPtr = ConstantPointerNull::get(F->getType());
724 GlobalVariable *Cache =
725 new GlobalVariable(F->getType(), false,GlobalValue::InternalLinkage,
726 NullPtr,F->getName()+".fpcache", F->getParent());
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000727
Misha Brukmance89b392004-04-19 03:36:47 +0000728 // Construct a new stub function that will re-route calls to F
Misha Brukman83018642004-04-19 01:12:01 +0000729 const FunctionType *FuncTy = F->getFunctionType();
Gabor Greife9ecc682008-04-06 20:25:17 +0000730 Function *FuncWrapper = Function::Create(FuncTy,
731 GlobalValue::InternalLinkage,
732 F->getName() + "_wrapper",
733 F->getParent());
734 BasicBlock *EntryBB = BasicBlock::Create("entry", FuncWrapper);
735 BasicBlock *DoCallBB = BasicBlock::Create("usecache", FuncWrapper);
736 BasicBlock *LookupBB = BasicBlock::Create("lookupfp", FuncWrapper);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000737
Chris Lattner986675c2005-07-12 01:00:32 +0000738 // Check to see if we already looked up the value.
739 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
Reid Spencer266e42b2006-12-23 06:05:41 +0000740 Value *IsNull = new ICmpInst(ICmpInst::ICMP_EQ, CachedVal,
741 NullPtr, "isNull", EntryBB);
Gabor Greife9ecc682008-04-06 20:25:17 +0000742 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000743
Misha Brukmance89b392004-04-19 03:36:47 +0000744 // Resolve the call to function F via the JIT API:
745 //
746 // call resolver(GetElementPtr...)
Gabor Greif697e94c2008-05-15 10:04:30 +0000747 CallInst *Resolver =
748 CallInst::Create(resolverFunc, ResolverArgs.begin(),
749 ResolverArgs.end(), "resolver", LookupBB);
750
751 // Cast the result from the resolver to correctly-typed function.
752 CastInst *CastedResolver =
753 new BitCastInst(Resolver,
754 PointerType::getUnqual(F->getFunctionType()),
755 "resolverCast", LookupBB);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000756
Chris Lattner986675c2005-07-12 01:00:32 +0000757 // Save the value in our cache.
758 new StoreInst(CastedResolver, Cache, LookupBB);
Gabor Greife9ecc682008-04-06 20:25:17 +0000759 BranchInst::Create(DoCallBB, LookupBB);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000760
Gabor Greif697e94c2008-05-15 10:04:30 +0000761 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(),
762 "fp", DoCallBB);
Chris Lattner986675c2005-07-12 01:00:32 +0000763 FuncPtr->addIncoming(CastedResolver, LookupBB);
764 FuncPtr->addIncoming(CachedVal, EntryBB);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000765
Chris Lattner986675c2005-07-12 01:00:32 +0000766 // Save the argument list.
Misha Brukman83018642004-04-19 01:12:01 +0000767 std::vector<Value*> Args;
Alkis Evlogimenosa67bafa2005-03-15 07:02:26 +0000768 for (Function::arg_iterator i = FuncWrapper->arg_begin(),
769 e = FuncWrapper->arg_end(); i != e; ++i)
Misha Brukman83018642004-04-19 01:12:01 +0000770 Args.push_back(i);
771
772 // Pass on the arguments to the real function, return its result
773 if (F->getReturnType() == Type::VoidTy) {
Gabor Greife9ecc682008-04-06 20:25:17 +0000774 CallInst::Create(FuncPtr, Args.begin(), Args.end(), "", DoCallBB);
775 ReturnInst::Create(DoCallBB);
Misha Brukman83018642004-04-19 01:12:01 +0000776 } else {
Gabor Greife9ecc682008-04-06 20:25:17 +0000777 CallInst *Call = CallInst::Create(FuncPtr, Args.begin(), Args.end(),
778 "retval", DoCallBB);
779 ReturnInst::Create(Call, DoCallBB);
Misha Brukman83018642004-04-19 01:12:01 +0000780 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000781
Misha Brukmance89b392004-04-19 03:36:47 +0000782 // Use the wrapper function instead of the old function
783 F->replaceAllUsesWith(FuncWrapper);
Misha Brukman83018642004-04-19 01:12:01 +0000784 }
Chris Lattnerbf791612004-04-05 22:58:16 +0000785 }
786 }
787 }
788
789 if (verifyModule(*Test) || verifyModule(*Safe)) {
790 std::cerr << "Bugpoint has a bug, which corrupted a module!!\n";
791 abort();
792 }
793}
794
795
796
797/// TestCodeGenerator - This is the predicate function used to check to see if
798/// the "Test" portion of the program is miscompiled by the code generator under
799/// test. If so, return true. In any case, both module arguments are deleted.
Misha Brukman0784a602004-04-21 18:36:43 +0000800///
Chris Lattnerbf791612004-04-05 22:58:16 +0000801static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
802 CleanupAndPrepareModules(BD, Test, Safe);
803
Reid Spencer30067f12004-12-15 01:53:08 +0000804 sys::Path TestModuleBC("bugpoint.test.bc");
Reid Spencere4ca7222006-08-23 20:34:57 +0000805 std::string ErrMsg;
806 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
807 std::cerr << BD.getToolName() << "Error making unique filename: "
808 << ErrMsg << "\n";
809 exit(1);
810 }
Reid Spencer30067f12004-12-15 01:53:08 +0000811 if (BD.writeProgramToFile(TestModuleBC.toString(), Test)) {
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000812 std::cerr << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
Chris Lattnerbf791612004-04-05 22:58:16 +0000813 exit(1);
814 }
815 delete Test;
816
817 // Make the shared library
Reid Spencer30067f12004-12-15 01:53:08 +0000818 sys::Path SafeModuleBC("bugpoint.safe.bc");
Reid Spencere4ca7222006-08-23 20:34:57 +0000819 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
820 std::cerr << BD.getToolName() << "Error making unique filename: "
821 << ErrMsg << "\n";
822 exit(1);
823 }
Chris Lattnerbf791612004-04-05 22:58:16 +0000824
Reid Spencer30067f12004-12-15 01:53:08 +0000825 if (BD.writeProgramToFile(SafeModuleBC.toString(), Safe)) {
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000826 std::cerr << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
Chris Lattnerbf791612004-04-05 22:58:16 +0000827 exit(1);
828 }
Reid Spencer30067f12004-12-15 01:53:08 +0000829 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.toString());
Chris Lattnerbf791612004-04-05 22:58:16 +0000830 delete Safe;
831
832 // Run the code generator on the `Test' code, loading the shared library.
833 // The function returns whether or not the new output differs from reference.
Reid Spencer30067f12004-12-15 01:53:08 +0000834 int Result = BD.diffProgram(TestModuleBC.toString(), SharedObject, false);
Chris Lattnerbf791612004-04-05 22:58:16 +0000835
836 if (Result)
837 std::cerr << ": still failing!\n";
838 else
839 std::cerr << ": didn't fail.\n";
Reid Spenceraf48d862005-07-08 03:08:58 +0000840 TestModuleBC.eraseFromDisk();
841 SafeModuleBC.eraseFromDisk();
842 sys::Path(SharedObject).eraseFromDisk();
Chris Lattnerbf791612004-04-05 22:58:16 +0000843
844 return Result;
845}
846
847
Misha Brukman0784a602004-04-21 18:36:43 +0000848/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
849///
Chris Lattnerbf791612004-04-05 22:58:16 +0000850bool BugDriver::debugCodeGenerator() {
Dan Gohman414cf502008-12-08 04:02:47 +0000851 if ((void*)SafeInterpreter == (void*)Interpreter) {
852 std::string Result = executeProgramSafely("bugpoint.safe.out");
853 std::cout << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
854 << "the reference diff. This may be due to a\n front-end "
855 << "bug or a bug in the original program, but this can also "
856 << "happen if bugpoint isn't running the program with the "
857 << "right flags or input.\n I left the result of executing "
858 << "the program with the \"safe\" backend in this file for "
859 << "you: '"
Chris Lattnerbf791612004-04-05 22:58:16 +0000860 << Result << "'.\n";
861 return true;
862 }
863
864 DisambiguateGlobalSymbols(Program);
865
866 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
867
868 // Split the module into the two halves of the program we want.
Dan Gohman956ae9d2009-04-22 15:57:18 +0000869 DenseMap<const Value*, Value*> ValueMap;
870 Module *ToNotCodeGen = CloneModule(getProgram(), ValueMap);
871 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, ValueMap);
Chris Lattnerbf791612004-04-05 22:58:16 +0000872
873 // Condition the modules
874 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
875
Reid Spencer30067f12004-12-15 01:53:08 +0000876 sys::Path TestModuleBC("bugpoint.test.bc");
Reid Spencere4ca7222006-08-23 20:34:57 +0000877 std::string ErrMsg;
878 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
879 std::cerr << getToolName() << "Error making unique filename: "
880 << ErrMsg << "\n";
881 exit(1);
882 }
Reid Spencer30067f12004-12-15 01:53:08 +0000883
884 if (writeProgramToFile(TestModuleBC.toString(), ToCodeGen)) {
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000885 std::cerr << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
Chris Lattnerbf791612004-04-05 22:58:16 +0000886 exit(1);
887 }
888 delete ToCodeGen;
889
890 // Make the shared library
Reid Spencer30067f12004-12-15 01:53:08 +0000891 sys::Path SafeModuleBC("bugpoint.safe.bc");
Reid Spencere4ca7222006-08-23 20:34:57 +0000892 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
893 std::cerr << getToolName() << "Error making unique filename: "
894 << ErrMsg << "\n";
895 exit(1);
896 }
Reid Spencer30067f12004-12-15 01:53:08 +0000897
898 if (writeProgramToFile(SafeModuleBC.toString(), ToNotCodeGen)) {
Gabor Greif0e535c3c2007-07-04 21:55:50 +0000899 std::cerr << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
Chris Lattnerbf791612004-04-05 22:58:16 +0000900 exit(1);
901 }
Reid Spencer30067f12004-12-15 01:53:08 +0000902 std::string SharedObject = compileSharedObject(SafeModuleBC.toString());
Chris Lattnerbf791612004-04-05 22:58:16 +0000903 delete ToNotCodeGen;
904
905 std::cout << "You can reproduce the problem with the command line: \n";
906 if (isExecutingJIT()) {
907 std::cout << " lli -load " << SharedObject << " " << TestModuleBC;
908 } else {
Chris Lattnerea2fa462005-01-15 00:07:19 +0000909 std::cout << " llc -f " << TestModuleBC << " -o " << TestModuleBC<< ".s\n";
Chris Lattnerbf791612004-04-05 22:58:16 +0000910 std::cout << " gcc " << SharedObject << " " << TestModuleBC
Chris Lattnerea2fa462005-01-15 00:07:19 +0000911 << ".s -o " << TestModuleBC << ".exe";
912#if defined (HAVE_LINK_R)
Chris Lattner8dea0ec2005-12-14 22:01:07 +0000913 std::cout << " -Wl,-R.";
Chris Lattnerea2fa462005-01-15 00:07:19 +0000914#endif
915 std::cout << "\n";
Chris Lattnerbf791612004-04-05 22:58:16 +0000916 std::cout << " " << TestModuleBC << ".exe";
917 }
918 for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
919 std::cout << " " << InputArgv[i];
Misha Brukman6aa3c832004-07-23 01:30:49 +0000920 std::cout << '\n';
Chris Lattnerbf791612004-04-05 22:58:16 +0000921 std::cout << "The shared object was created with:\n llc -march=c "
922 << SafeModuleBC << " -o temporary.c\n"
923 << " gcc -xc temporary.c -O2 -o " << SharedObject
924#if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
925 << " -G" // Compile a shared library, `-G' for Sparc
926#else
Torok Edwin538160b2008-04-06 12:42:29 +0000927 << " -fPIC -shared" // `-shared' for Linux/X86, maybe others
Chris Lattnerbf791612004-04-05 22:58:16 +0000928#endif
929 << " -fno-strict-aliasing\n";
930
931 return false;
932}