blob: d7be3c909e17713de451e69a6d99adfb74dc5779 [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));
40
Chris Lattnerfa761832004-01-14 03:38:37 +000041 class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
42 BugDriver &BD;
43 public:
44 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +000045
Chris Lattnerfa761832004-01-14 03:38:37 +000046 virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
47 std::vector<const PassInfo*> &Suffix);
48 };
49}
Chris Lattner640f22e2003-04-24 17:02:17 +000050
Misha Brukman8c194ea2004-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 Lattner640f22e2003-04-24 17:02:17 +000054ReduceMiscompilingPasses::TestResult
Chris Lattner39aebca2003-04-24 22:24:22 +000055ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
Chris Lattner06943ad2003-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 Lattner640f22e2003-04-24 17:02:17 +000058 // with JUST the kept passes, discard the prefix passes.
Dan Gohmanac95cc72009-07-16 15:30:09 +000059 outs() << "Checking to see if '" << getPassesString(Suffix)
60 << "' compiles correctly: ";
Chris Lattner640f22e2003-04-24 17:02:17 +000061
Gabor Greif8ff70c22007-07-04 21:55:50 +000062 std::string BitcodeResult;
63 if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Dan Gohman65f57c22009-07-15 16:35:29 +000064 errs() << " Error running this sequence of passes"
65 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +000066 BD.setPassesToRun(Suffix);
Gabor Greif8ff70c22007-07-04 21:55:50 +000067 BD.EmitProgressBitcode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +000068 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +000069 }
Owen Anderson9adc0ab2009-07-14 23:09:55 +000070
Chris Lattner640f22e2003-04-24 17:02:17 +000071 // Check to see if the finished program matches the reference output...
Gabor Greif8ff70c22007-07-04 21:55:50 +000072 if (BD.diffProgram(BitcodeResult, "", true /*delete bitcode*/)) {
Dan Gohmanac95cc72009-07-16 15:30:09 +000073 outs() << " nope.\n";
Chris Lattner59615f02005-01-15 00:07:19 +000074 if (Suffix.empty()) {
Dan Gohman65f57c22009-07-15 16:35:29 +000075 errs() << BD.getToolName() << ": I'm confused: the test fails when "
76 << "no passes are run, nondeterministic program?\n";
Chris Lattner59615f02005-01-15 00:07:19 +000077 exit(1);
78 }
Misha Brukman123f8fe2004-04-22 20:02:09 +000079 return KeepSuffix; // Miscompilation detected!
Chris Lattner640f22e2003-04-24 17:02:17 +000080 }
Dan Gohmanac95cc72009-07-16 15:30:09 +000081 outs() << " yup.\n"; // No miscompilation!
Chris Lattner640f22e2003-04-24 17:02:17 +000082
83 if (Prefix.empty()) return NoFailure;
84
Chris Lattner06943ad2003-04-25 03:16:05 +000085 // Next, see if the program is broken if we run the "prefix" passes first,
Misha Brukmanbc0e9982003-07-14 17:20:40 +000086 // then separately run the "kept" passes.
Dan Gohmanac95cc72009-07-16 15:30:09 +000087 outs() << "Checking to see if '" << getPassesString(Prefix)
88 << "' compiles correctly: ";
Chris Lattner640f22e2003-04-24 17:02:17 +000089
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 Greif8ff70c22007-07-04 21:55:50 +000093 // kept passes, we can update our bitcode file to include the result of the
Chris Lattner640f22e2003-04-24 17:02:17 +000094 // prefix passes, then discard the prefix passes.
95 //
Gabor Greif8ff70c22007-07-04 21:55:50 +000096 if (BD.runPasses(Prefix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Dan Gohman65f57c22009-07-15 16:35:29 +000097 errs() << " Error running this sequence of passes"
98 << " on the input program!\n";
Chris Lattner9c6cfe12003-10-17 23:03:16 +000099 BD.setPassesToRun(Prefix);
Gabor Greif8ff70c22007-07-04 21:55:50 +0000100 BD.EmitProgressBitcode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +0000101 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +0000102 }
103
104 // If the prefix maintains the predicate by itself, only keep the prefix!
Gabor Greif8ff70c22007-07-04 21:55:50 +0000105 if (BD.diffProgram(BitcodeResult)) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000106 outs() << " nope.\n";
Gabor Greif8ff70c22007-07-04 21:55:50 +0000107 sys::Path(BitcodeResult).eraseFromDisk();
Chris Lattner640f22e2003-04-24 17:02:17 +0000108 return KeepPrefix;
109 }
Dan Gohmanac95cc72009-07-16 15:30:09 +0000110 outs() << " yup.\n"; // No miscompilation!
Chris Lattner640f22e2003-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 //
Owen Anderson8b477ed2009-07-01 16:58:40 +0000115 Module *PrefixOutput = ParseInputFile(BitcodeResult, BD.getContext());
Chris Lattner640f22e2003-04-24 17:02:17 +0000116 if (PrefixOutput == 0) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000117 errs() << BD.getToolName() << ": Error reading bitcode file '"
118 << BitcodeResult << "'!\n";
Chris Lattner640f22e2003-04-24 17:02:17 +0000119 exit(1);
120 }
Gabor Greif8ff70c22007-07-04 21:55:50 +0000121 sys::Path(BitcodeResult).eraseFromDisk(); // No longer need the file on disk
Chris Lattnerf4789e62004-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 Brukman3da94ae2005-04-22 00:00:37 +0000126
Dan Gohmanac95cc72009-07-16 15:30:09 +0000127 outs() << "Checking to see if '" << getPassesString(Suffix)
Chris Lattner640f22e2003-04-24 17:02:17 +0000128 << "' passes compile correctly after the '"
129 << getPassesString(Prefix) << "' passes: ";
130
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000131 Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
Gabor Greif8ff70c22007-07-04 21:55:50 +0000132 if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000133 errs() << " Error running this sequence of passes"
134 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +0000135 BD.setPassesToRun(Suffix);
Gabor Greif8ff70c22007-07-04 21:55:50 +0000136 BD.EmitProgressBitcode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +0000137 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +0000138 }
139
140 // Run the result...
Gabor Greif8ff70c22007-07-04 21:55:50 +0000141 if (BD.diffProgram(BitcodeResult, "", true/*delete bitcode*/)) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000142 outs() << " nope.\n";
Chris Lattner640f22e2003-04-24 17:02:17 +0000143 delete OriginalInput; // We pruned down the original input...
Chris Lattner06943ad2003-04-25 03:16:05 +0000144 return KeepSuffix;
Chris Lattner640f22e2003-04-24 17:02:17 +0000145 }
146
147 // Otherwise, we must not be running the bad pass anymore.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000148 outs() << " yup.\n"; // No miscompilation!
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000149 delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test
Chris Lattner640f22e2003-04-24 17:02:17 +0000150 return NoFailure;
151}
152
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000153namespace {
Chris Lattnerfa761832004-01-14 03:38:37 +0000154 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
155 BugDriver &BD;
Chris Lattnerb15825b2004-04-05 21:37:38 +0000156 bool (*TestFn)(BugDriver &, Module *, Module *);
Chris Lattnerfa761832004-01-14 03:38:37 +0000157 public:
Chris Lattnerb15825b2004-04-05 21:37:38 +0000158 ReduceMiscompilingFunctions(BugDriver &bd,
159 bool (*F)(BugDriver &, Module *, Module *))
160 : BD(bd), TestFn(F) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +0000161
Chris Lattnerfa761832004-01-14 03:38:37 +0000162 virtual TestResult doTest(std::vector<Function*> &Prefix,
163 std::vector<Function*> &Suffix) {
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000164 if (!Suffix.empty() && TestFuncs(Suffix))
Chris Lattnerfa761832004-01-14 03:38:37 +0000165 return KeepSuffix;
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000166 if (!Prefix.empty() && TestFuncs(Prefix))
Chris Lattnerfa761832004-01-14 03:38:37 +0000167 return KeepPrefix;
168 return NoFailure;
169 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000170
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000171 bool TestFuncs(const std::vector<Function*> &Prefix);
Chris Lattnerfa761832004-01-14 03:38:37 +0000172 };
173}
Chris Lattner640f22e2003-04-24 17:02:17 +0000174
Chris Lattnerefdc0b52004-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 Lattnera1cf1c82004-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 Brukman8c194ea2004-04-21 18:36:43 +0000180///
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000181static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
182 bool DeleteInputs) {
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000183 // Link the two portions of the program back to together.
184 std::string ErrorMsg;
Chris Lattner90c18c52004-11-16 06:31:38 +0000185 if (!DeleteInputs) {
186 M1 = CloneModule(M1);
187 M2 = CloneModule(M2);
188 }
Reid Spencere4874022004-12-13 03:01:03 +0000189 if (Linker::LinkModules(M1, M2, &ErrorMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000190 errs() << BD.getToolName() << ": Error linking modules together:"
191 << ErrorMsg << '\n';
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000192 exit(1);
193 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000194 delete M2; // We are done with this module.
Chris Lattnerefdc0b52004-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 Lattnera1cf1c82004-03-14 22:08:00 +0000203 BD.swapProgramIn(OldProgram);
Chris Lattner5313f232004-04-02 06:32:17 +0000204 delete M1;
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000205 return Broken;
206}
207
Misha Brukman8c194ea2004-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 Lattnerbe21ca52004-03-14 19:27:19 +0000212bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
Chris Lattner640f22e2003-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.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000215 outs() << "Checking to see if the program is misoptimized when "
216 << (Funcs.size()==1 ? "this function is" : "these functions are")
217 << " run through the pass"
218 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000219 PrintFunctionList(Funcs);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000220 outs() << '\n';
Chris Lattner640f22e2003-04-24 17:02:17 +0000221
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000222 // Split the module into the two halves of the program we want.
Dan Gohmand50330c2009-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 Lattner640f22e2003-04-24 17:02:17 +0000227
Nick Lewycky6fa98b12007-11-14 06:47:06 +0000228 // Run the predicate, note that the predicate will delete both input modules.
Chris Lattnerb15825b2004-04-05 21:37:38 +0000229 return TestFn(BD, ToOptimize, ToNotOptimize);
Chris Lattner640f22e2003-04-24 17:02:17 +0000230}
231
Misha Brukman8c194ea2004-04-21 18:36:43 +0000232/// DisambiguateGlobalSymbols - Mangle symbols to guarantee uniqueness by
233/// modifying predominantly internal symbols rather than external ones.
234///
Chris Lattner36ee07f2004-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 Lenharth0fccc742005-12-06 20:51:30 +0000242 // Agree with the CBE on symbol naming
243 Mang.markCharUnacceptable('.');
Chris Lattner67ef9e42006-05-04 23:35:31 +0000244 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
Chris Lattner9d5511b2009-07-15 04:50:47 +0000245 I != E; ++I) {
246 // Don't mangle asm names.
247 if (!I->hasName() || I->getName()[0] != 1)
248 I->setName(Mang.getMangledName(I));
249 }
250 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
Chris Lattner4285d152009-07-19 20:19:04 +0000251 // Don't mangle asm names or intrinsics.
Chris Lattnere0d5c172009-07-19 20:19:25 +0000252 if ((!I->hasName() || I->getName()[0] != 1) &&
253 I->getIntrinsicID() == 0)
Chris Lattner9d5511b2009-07-15 04:50:47 +0000254 I->setName(Mang.getMangledName(I));
255 }
Chris Lattner36ee07f2004-04-11 23:52:35 +0000256}
257
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000258/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
259/// check to see if we can extract the loops in the region without obscuring the
260/// bug. If so, it reduces the amount of code identified.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000261///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000262static bool ExtractLoops(BugDriver &BD,
263 bool (*TestFn)(BugDriver &, Module *, Module *),
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000264 std::vector<Function*> &MiscompiledFunctions) {
265 bool MadeChange = false;
266 while (1) {
Chris Lattneraed98fa2005-08-02 23:25:56 +0000267 if (BugpointIsInterrupted) return MadeChange;
268
Dan Gohmand50330c2009-04-22 15:57:18 +0000269 DenseMap<const Value*, Value*> ValueMap;
270 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000271 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohmand50330c2009-04-22 15:57:18 +0000272 MiscompiledFunctions,
273 ValueMap);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000274 Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
275 if (!ToOptimizeLoopExtracted) {
276 // If the loop extractor crashed or if there were no extractible loops,
277 // then this chapter of our odyssey is over with.
278 delete ToNotOptimize;
279 delete ToOptimize;
280 return MadeChange;
281 }
282
Dan Gohman65f57c22009-07-15 16:35:29 +0000283 errs() << "Extracted a loop from the breaking portion of the program.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000284
285 // Bugpoint is intentionally not very trusting of LLVM transformations. In
286 // particular, we're not going to assume that the loop extractor works, so
287 // we're going to test the newly loop extracted program to make sure nothing
288 // has broken. If something broke, then we'll inform the user and stop
289 // extraction.
Dan Gohman70ef4492008-12-08 04:02:47 +0000290 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000291 if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000292 BD.switchToInterpreter(AI);
293
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000294 // Merged program doesn't work anymore!
Dan Gohman65f57c22009-07-15 16:35:29 +0000295 errs() << " *** ERROR: Loop extraction broke the program. :("
296 << " Please report a bug!\n";
297 errs() << " Continuing on with un-loop-extracted version.\n";
Chris Lattner56c41862005-05-08 21:54:56 +0000298
299 BD.writeProgramToFile("bugpoint-loop-extract-fail-tno.bc", ToNotOptimize);
300 BD.writeProgramToFile("bugpoint-loop-extract-fail-to.bc", ToOptimize);
301 BD.writeProgramToFile("bugpoint-loop-extract-fail-to-le.bc",
302 ToOptimizeLoopExtracted);
303
Dan Gohman65f57c22009-07-15 16:35:29 +0000304 errs() << "Please submit the bugpoint-loop-extract-fail-*.bc files.\n";
Chris Lattner56c41862005-05-08 21:54:56 +0000305 delete ToOptimize;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000306 delete ToNotOptimize;
307 delete ToOptimizeLoopExtracted;
308 return MadeChange;
309 }
Chris Lattner56c41862005-05-08 21:54:56 +0000310 delete ToOptimize;
Chris Lattnera57d86b2004-04-05 22:58:16 +0000311 BD.switchToInterpreter(AI);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000312
Dan Gohmanac95cc72009-07-16 15:30:09 +0000313 outs() << " Testing after loop extraction:\n";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000314 // Clone modules, the tester function will free them.
315 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
316 Module *TNOBackup = CloneModule(ToNotOptimize);
317 if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000318 outs() << "*** Loop extraction masked the problem. Undoing.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000319 // If the program is not still broken, then loop extraction did something
320 // that masked the error. Stop loop extraction now.
Chris Lattnerb15825b2004-04-05 21:37:38 +0000321 delete TOLEBackup;
322 delete TNOBackup;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000323 return MadeChange;
324 }
Chris Lattnerb15825b2004-04-05 21:37:38 +0000325 ToOptimizeLoopExtracted = TOLEBackup;
326 ToNotOptimize = TNOBackup;
327
Dan Gohmanac95cc72009-07-16 15:30:09 +0000328 outs() << "*** Loop extraction successful!\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000329
Chris Lattner90c18c52004-11-16 06:31:38 +0000330 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
331 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
332 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +0000333 if (!I->isDeclaration())
Chris Lattnerfa1af132004-11-19 07:09:40 +0000334 MisCompFunctions.push_back(std::make_pair(I->getName(),
335 I->getFunctionType()));
Chris Lattner90c18c52004-11-16 06:31:38 +0000336
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000337 // Okay, great! Now we know that we extracted a loop and that loop
338 // extraction both didn't break the program, and didn't mask the problem.
339 // Replace the current program with the loop extracted version, and try to
340 // extract another loop.
341 std::string ErrorMsg;
Reid Spencere4874022004-12-13 03:01:03 +0000342 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
Dan Gohman65f57c22009-07-15 16:35:29 +0000343 errs() << BD.getToolName() << ": Error linking modules together:"
344 << ErrorMsg << '\n';
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000345 exit(1);
346 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000347 delete ToOptimizeLoopExtracted;
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000348
349 // All of the Function*'s in the MiscompiledFunctions list are in the old
Chris Lattner5313f232004-04-02 06:32:17 +0000350 // module. Update this list to include all of the functions in the
351 // optimized and loop extracted module.
352 MiscompiledFunctions.clear();
Chris Lattner90c18c52004-11-16 06:31:38 +0000353 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spenceref9b9a72007-02-05 20:47:22 +0000354 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
355
Chris Lattner90c18c52004-11-16 06:31:38 +0000356 assert(NewF && "Function not found??");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000357 assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
358 "found wrong function type?");
Chris Lattner90c18c52004-11-16 06:31:38 +0000359 MiscompiledFunctions.push_back(NewF);
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000360 }
361
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000362 BD.setNewProgram(ToNotOptimize);
363 MadeChange = true;
364 }
365}
366
Chris Lattner5e783ab2004-05-11 21:54:13 +0000367namespace {
368 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
369 BugDriver &BD;
370 bool (*TestFn)(BugDriver &, Module *, Module *);
371 std::vector<Function*> FunctionsBeingTested;
372 public:
373 ReduceMiscompiledBlocks(BugDriver &bd,
374 bool (*F)(BugDriver &, Module *, Module *),
375 const std::vector<Function*> &Fns)
376 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +0000377
Chris Lattner5e783ab2004-05-11 21:54:13 +0000378 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
379 std::vector<BasicBlock*> &Suffix) {
380 if (!Suffix.empty() && TestFuncs(Suffix))
381 return KeepSuffix;
382 if (TestFuncs(Prefix))
383 return KeepPrefix;
384 return NoFailure;
385 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000386
Chris Lattner5e783ab2004-05-11 21:54:13 +0000387 bool TestFuncs(const std::vector<BasicBlock*> &Prefix);
388 };
389}
390
391/// TestFuncs - Extract all blocks for the miscompiled functions except for the
392/// specified blocks. If the problem still exists, return true.
393///
394bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) {
395 // Test to see if the function is misoptimized if we ONLY run it on the
396 // functions listed in Funcs.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000397 outs() << "Checking to see if the program is misoptimized when all ";
Chris Lattner68bee932004-05-12 16:08:01 +0000398 if (!BBs.empty()) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000399 outs() << "but these " << BBs.size() << " blocks are extracted: ";
Chris Lattner68bee932004-05-12 16:08:01 +0000400 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000401 outs() << BBs[i]->getName() << " ";
402 if (BBs.size() > 10) outs() << "...";
Chris Lattner68bee932004-05-12 16:08:01 +0000403 } else {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000404 outs() << "blocks are extracted.";
Chris Lattner68bee932004-05-12 16:08:01 +0000405 }
Dan Gohmanac95cc72009-07-16 15:30:09 +0000406 outs() << '\n';
Chris Lattner5e783ab2004-05-11 21:54:13 +0000407
408 // Split the module into the two halves of the program we want.
Dan Gohmand50330c2009-04-22 15:57:18 +0000409 DenseMap<const Value*, Value*> ValueMap;
410 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000411 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohmand50330c2009-04-22 15:57:18 +0000412 FunctionsBeingTested,
413 ValueMap);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000414
415 // Try the extraction. If it doesn't work, then the block extractor crashed
416 // or something, in which case bugpoint can't chase down this possibility.
417 if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) {
418 delete ToOptimize;
419 // Run the predicate, not that the predicate will delete both input modules.
420 return TestFn(BD, New, ToNotOptimize);
421 }
422 delete ToOptimize;
423 delete ToNotOptimize;
424 return false;
425}
426
427
428/// ExtractBlocks - Given a reduced list of functions that still expose the bug,
429/// extract as many basic blocks from the region as possible without obscuring
430/// the bug.
431///
432static bool ExtractBlocks(BugDriver &BD,
433 bool (*TestFn)(BugDriver &, Module *, Module *),
434 std::vector<Function*> &MiscompiledFunctions) {
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000435 if (BugpointIsInterrupted) return false;
436
Chris Lattner5e783ab2004-05-11 21:54:13 +0000437 std::vector<BasicBlock*> Blocks;
438 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
439 for (Function::iterator I = MiscompiledFunctions[i]->begin(),
440 E = MiscompiledFunctions[i]->end(); I != E; ++I)
441 Blocks.push_back(I);
442
443 // Use the list reducer to identify blocks that can be extracted without
444 // obscuring the bug. The Blocks list will end up containing blocks that must
445 // be retained from the original program.
446 unsigned OldSize = Blocks.size();
Chris Lattner68bee932004-05-12 16:08:01 +0000447
448 // Check to see if all blocks are extractible first.
449 if (ReduceMiscompiledBlocks(BD, TestFn,
450 MiscompiledFunctions).TestFuncs(std::vector<BasicBlock*>())) {
451 Blocks.clear();
452 } else {
453 ReduceMiscompiledBlocks(BD, TestFn,MiscompiledFunctions).reduceList(Blocks);
454 if (Blocks.size() == OldSize)
455 return false;
456 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000457
Dan Gohmand50330c2009-04-22 15:57:18 +0000458 DenseMap<const Value*, Value*> ValueMap;
459 Module *ProgClone = CloneModule(BD.getProgram(), ValueMap);
Chris Lattner2290e752004-05-12 02:43:24 +0000460 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
Dan Gohmand50330c2009-04-22 15:57:18 +0000461 MiscompiledFunctions,
462 ValueMap);
Chris Lattner2290e752004-05-12 02:43:24 +0000463 Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
464 if (Extracted == 0) {
Chris Lattnerda895d62005-02-27 06:18:25 +0000465 // Weird, extraction should have worked.
Dan Gohman65f57c22009-07-15 16:35:29 +0000466 errs() << "Nondeterministic problem extracting blocks??\n";
Chris Lattner2290e752004-05-12 02:43:24 +0000467 delete ProgClone;
468 delete ToExtract;
469 return false;
470 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000471
Chris Lattner2290e752004-05-12 02:43:24 +0000472 // Otherwise, block extraction succeeded. Link the two program fragments back
473 // together.
474 delete ToExtract;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000475
Chris Lattner90c18c52004-11-16 06:31:38 +0000476 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
477 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
478 I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +0000479 if (!I->isDeclaration())
Chris Lattnerfa1af132004-11-19 07:09:40 +0000480 MisCompFunctions.push_back(std::make_pair(I->getName(),
481 I->getFunctionType()));
Chris Lattner90c18c52004-11-16 06:31:38 +0000482
Chris Lattner2290e752004-05-12 02:43:24 +0000483 std::string ErrorMsg;
Reid Spencere4874022004-12-13 03:01:03 +0000484 if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000485 errs() << BD.getToolName() << ": Error linking modules together:"
486 << ErrorMsg << '\n';
Chris Lattner2290e752004-05-12 02:43:24 +0000487 exit(1);
488 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000489 delete Extracted;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000490
Chris Lattner2290e752004-05-12 02:43:24 +0000491 // Set the new program and delete the old one.
492 BD.setNewProgram(ProgClone);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000493
Chris Lattner2290e752004-05-12 02:43:24 +0000494 // Update the list of miscompiled functions.
495 MiscompiledFunctions.clear();
Chris Lattner5e783ab2004-05-11 21:54:13 +0000496
Chris Lattner90c18c52004-11-16 06:31:38 +0000497 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spenceref9b9a72007-02-05 20:47:22 +0000498 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
Chris Lattner90c18c52004-11-16 06:31:38 +0000499 assert(NewF && "Function not found??");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000500 assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
501 "Function has wrong type??");
Chris Lattner90c18c52004-11-16 06:31:38 +0000502 MiscompiledFunctions.push_back(NewF);
503 }
Chris Lattner2290e752004-05-12 02:43:24 +0000504
505 return true;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000506}
507
508
Chris Lattnerb15825b2004-04-05 21:37:38 +0000509/// DebugAMiscompilation - This is a generic driver to narrow down
510/// miscompilations, either in an optimization or a code generator.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000511///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000512static std::vector<Function*>
513DebugAMiscompilation(BugDriver &BD,
514 bool (*TestFn)(BugDriver &, Module *, Module *)) {
515 // Okay, now that we have reduced the list of passes which are causing the
516 // failure, see if we can pin down which functions are being
517 // miscompiled... first build a list of all of the non-external functions in
518 // the program.
519 std::vector<Function*> MiscompiledFunctions;
520 Module *Prog = BD.getProgram();
521 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +0000522 if (!I->isDeclaration())
Chris Lattnerb15825b2004-04-05 21:37:38 +0000523 MiscompiledFunctions.push_back(I);
524
525 // Do the reduction...
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000526 if (!BugpointIsInterrupted)
527 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Chris Lattnerb15825b2004-04-05 21:37:38 +0000528
Dan Gohmanac95cc72009-07-16 15:30:09 +0000529 outs() << "\n*** The following function"
530 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
531 << " being miscompiled: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000532 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000533 outs() << '\n';
Chris Lattnerb15825b2004-04-05 21:37:38 +0000534
535 // See if we can rip any loops out of the miscompiled functions and still
536 // trigger the problem.
Reid Spencerdc31a8a2006-11-11 19:05:02 +0000537
Reid Spencer2803b4c2006-11-11 19:59:25 +0000538 if (!BugpointIsInterrupted && !DisableLoopExtraction &&
539 ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
Chris Lattnerb15825b2004-04-05 21:37:38 +0000540 // Okay, we extracted some loops and the problem still appears. See if we
541 // can eliminate some of the created functions from being candidates.
542
Chris Lattner36ee07f2004-04-11 23:52:35 +0000543 // Loop extraction can introduce functions with the same name (foo_code).
544 // Make sure to disambiguate the symbols so that when the program is split
545 // apart that we can link it back together again.
546 DisambiguateGlobalSymbols(BD.getProgram());
547
Chris Lattnerb15825b2004-04-05 21:37:38 +0000548 // Do the reduction...
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000549 if (!BugpointIsInterrupted)
550 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000551
Dan Gohmanac95cc72009-07-16 15:30:09 +0000552 outs() << "\n*** The following function"
553 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
554 << " being miscompiled: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000555 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000556 outs() << '\n';
Chris Lattnerb15825b2004-04-05 21:37:38 +0000557 }
558
Chris Lattneraed98fa2005-08-02 23:25:56 +0000559 if (!BugpointIsInterrupted &&
560 ExtractBlocks(BD, TestFn, MiscompiledFunctions)) {
Chris Lattner5e783ab2004-05-11 21:54:13 +0000561 // Okay, we extracted some blocks and the problem still appears. See if we
562 // can eliminate some of the created functions from being candidates.
563
564 // Block extraction can introduce functions with the same name (foo_code).
565 // Make sure to disambiguate the symbols so that when the program is split
566 // apart that we can link it back together again.
567 DisambiguateGlobalSymbols(BD.getProgram());
568
569 // Do the reduction...
570 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000571
Dan Gohmanac95cc72009-07-16 15:30:09 +0000572 outs() << "\n*** The following function"
573 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
574 << " being miscompiled: ";
Chris Lattner5e783ab2004-05-11 21:54:13 +0000575 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000576 outs() << '\n';
Chris Lattner5e783ab2004-05-11 21:54:13 +0000577 }
578
Chris Lattnerb15825b2004-04-05 21:37:38 +0000579 return MiscompiledFunctions;
580}
581
Chris Lattnera57d86b2004-04-05 22:58:16 +0000582/// TestOptimizer - This is the predicate function used to check to see if the
583/// "Test" portion of the program is misoptimized. If so, return true. In any
584/// case, both module arguments are deleted.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000585///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000586static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
587 // Run the optimization passes on ToOptimize, producing a transformed version
588 // of the functions being tested.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000589 outs() << " Optimizing functions being tested: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000590 Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
591 /*AutoDebugCrashes*/true);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000592 outs() << "done.\n";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000593 delete Test;
594
Dan Gohmanac95cc72009-07-16 15:30:09 +0000595 outs() << " Checking to see if the merged program executes correctly: ";
Chris Lattner2423db02004-04-09 22:28:33 +0000596 bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000597 outs() << (Broken ? " nope.\n" : " yup.\n");
Chris Lattnerb15825b2004-04-05 21:37:38 +0000598 return Broken;
599}
600
601
Chris Lattner4a106452002-12-23 23:50:16 +0000602/// debugMiscompilation - This method is used when the passes selected are not
603/// crashing, but the generated output is semantically different from the
604/// input.
605///
606bool BugDriver::debugMiscompilation() {
Chris Lattner4a106452002-12-23 23:50:16 +0000607 // Make sure something was miscompiled...
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000608 if (!BugpointIsInterrupted)
609 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000610 errs() << "*** Optimized program matches reference output! No problem"
611 << " detected...\nbugpoint can't help you with your problem!\n";
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000612 return false;
613 }
Chris Lattner4a106452002-12-23 23:50:16 +0000614
Dan Gohmanac95cc72009-07-16 15:30:09 +0000615 outs() << "\n*** Found miscompiling pass"
616 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
617 << getPassesString(getPassesToRun()) << '\n';
Gabor Greif8ff70c22007-07-04 21:55:50 +0000618 EmitProgressBitcode("passinput");
Chris Lattner4a106452002-12-23 23:50:16 +0000619
Chris Lattnerb15825b2004-04-05 21:37:38 +0000620 std::vector<Function*> MiscompiledFunctions =
621 DebugAMiscompilation(*this, TestOptimizer);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000622
Gabor Greif8ff70c22007-07-04 21:55:50 +0000623 // Output a bunch of bitcode files for the user...
Dan Gohmanac95cc72009-07-16 15:30:09 +0000624 outs() << "Outputting reduced bitcode files which expose the problem:\n";
Dan Gohmand50330c2009-04-22 15:57:18 +0000625 DenseMap<const Value*, Value*> ValueMap;
626 Module *ToNotOptimize = CloneModule(getProgram(), ValueMap);
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000627 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohmand50330c2009-04-22 15:57:18 +0000628 MiscompiledFunctions,
629 ValueMap);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000630
Dan Gohmanac95cc72009-07-16 15:30:09 +0000631 outs() << " Non-optimized portion: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000632 ToNotOptimize = swapProgramIn(ToNotOptimize);
Gabor Greif8ff70c22007-07-04 21:55:50 +0000633 EmitProgressBitcode("tonotoptimize", true);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000634 setNewProgram(ToNotOptimize); // Delete hacked module.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000635
Dan Gohmanac95cc72009-07-16 15:30:09 +0000636 outs() << " Portion that is input to optimizer: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000637 ToOptimize = swapProgramIn(ToOptimize);
Gabor Greif8ff70c22007-07-04 21:55:50 +0000638 EmitProgressBitcode("tooptimize");
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000639 setNewProgram(ToOptimize); // Delete hacked module.
Chris Lattner4a106452002-12-23 23:50:16 +0000640
Chris Lattner4a106452002-12-23 23:50:16 +0000641 return false;
642}
Brian Gaeked0fde302003-11-11 22:41:34 +0000643
Chris Lattnera57d86b2004-04-05 22:58:16 +0000644/// CleanupAndPrepareModules - Get the specified modules ready for code
645/// generator testing.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000646///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000647static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
648 Module *Safe) {
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000649 LLVMContext &Context = BD.getContext();
650
Chris Lattnera57d86b2004-04-05 22:58:16 +0000651 // Clean up the modules, removing extra cruft that we don't need anymore...
652 Test = BD.performFinalCleanups(Test);
653
654 // If we are executing the JIT, we have several nasty issues to take care of.
655 if (!BD.isExecutingJIT()) return;
656
657 // First, if the main function is in the Safe module, we must add a stub to
658 // the Test module to call into it. Thus, we create a new function `main'
659 // which just calls the old one.
Reid Spencer688b0492007-02-05 21:19:13 +0000660 if (Function *oldMain = Safe->getFunction("main"))
Reid Spencer5cbf9852007-01-30 20:08:39 +0000661 if (!oldMain->isDeclaration()) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000662 // Rename it
663 oldMain->setName("llvm_bugpoint_old_main");
664 // Create a NEW `main' function with same type in the test module.
Gabor Greif051a9502008-04-06 20:25:17 +0000665 Function *newMain = Function::Create(oldMain->getFunctionType(),
666 GlobalValue::ExternalLinkage,
667 "main", Test);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000668 // Create an `oldmain' prototype in the test module, which will
669 // corresponds to the real main function in the same module.
Gabor Greif051a9502008-04-06 20:25:17 +0000670 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
671 GlobalValue::ExternalLinkage,
672 oldMain->getName(), Test);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000673 // Set up and remember the argument list for the main function.
674 std::vector<Value*> args;
Alkis Evlogimenos5a1c58d2005-03-15 07:02:26 +0000675 for (Function::arg_iterator
676 I = newMain->arg_begin(), E = newMain->arg_end(),
677 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
Owen Anderson6bc41e82008-04-14 17:38:21 +0000678 I->setName(OI->getName()); // Copy argument names from oldMain
Chris Lattnera57d86b2004-04-05 22:58:16 +0000679 args.push_back(I);
680 }
681
682 // Call the old main function and return its result
Gabor Greif051a9502008-04-06 20:25:17 +0000683 BasicBlock *BB = BasicBlock::Create("entry", newMain);
684 CallInst *call = CallInst::Create(oldMainProto, args.begin(), args.end(),
685 "", BB);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000686
Chris Lattnera57d86b2004-04-05 22:58:16 +0000687 // If the type of old function wasn't void, return value of call
Gabor Greif051a9502008-04-06 20:25:17 +0000688 ReturnInst::Create(call, BB);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000689 }
690
691 // The second nasty issue we must deal with in the JIT is that the Safe
692 // module cannot directly reference any functions defined in the test
693 // module. Instead, we use a JIT API call to dynamically resolve the
694 // symbol.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000695
Chris Lattnera57d86b2004-04-05 22:58:16 +0000696 // Add the resolver to the Safe module.
697 // Prototype: void *getPointerToNamedFunction(const char* Name)
Chris Lattner2db43c82007-01-07 08:13:39 +0000698 Constant *resolverFunc =
Chris Lattnera57d86b2004-04-05 22:58:16 +0000699 Safe->getOrInsertFunction("getPointerToNamedFunction",
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000700 Context.getPointerTypeUnqual(Type::Int8Ty),
701 Context.getPointerTypeUnqual(Type::Int8Ty), (Type *)0);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000702
Chris Lattnera57d86b2004-04-05 22:58:16 +0000703 // Use the function we just added to get addresses of functions we need.
Misha Brukmandc7fef82004-04-19 01:12:01 +0000704 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000705 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
Duncan Sandsa3355ff2007-12-03 20:06:50 +0000706 !F->isIntrinsic() /* ignore intrinsics */) {
Reid Spencer688b0492007-02-05 21:19:13 +0000707 Function *TestFn = Test->getFunction(F->getName());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000708
709 // Don't forward functions which are external in the test module too.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000710 if (TestFn && !TestFn->isDeclaration()) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000711 // 1. Add a string constant with its name to the global file
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000712 Constant *InitArray = Context.getConstantArray(F->getName());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000713 GlobalVariable *funcName =
Owen Andersone9b11b42009-07-08 19:03:57 +0000714 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
Misha Brukman3da94ae2005-04-22 00:00:37 +0000715 GlobalValue::InternalLinkage, InitArray,
Owen Andersone9b11b42009-07-08 19:03:57 +0000716 F->getName() + "_name");
Chris Lattnera57d86b2004-04-05 22:58:16 +0000717
718 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
719 // sbyte* so it matches the signature of the resolver function.
720
721 // GetElementPtr *funcName, ulong 0, ulong 0
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000722 std::vector<Constant*> GEPargs(2, Context.getNullValue(Type::Int32Ty));
723 Value *GEP =
724 Context.getConstantExprGetElementPtr(funcName, &GEPargs[0], 2);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000725 std::vector<Value*> ResolverArgs;
726 ResolverArgs.push_back(GEP);
727
Misha Brukmande4803d2004-04-19 03:36:47 +0000728 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
729 // function that dynamically resolves the calls to F via our JIT API
Chris Lattnera3efca12005-07-12 01:00:32 +0000730 if (!F->use_empty()) {
731 // Create a new global to hold the cached function pointer.
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000732 Constant *NullPtr = Context.getConstantPointerNull(F->getType());
Chris Lattnera3efca12005-07-12 01:00:32 +0000733 GlobalVariable *Cache =
Owen Andersone9b11b42009-07-08 19:03:57 +0000734 new GlobalVariable(*F->getParent(), F->getType(),
735 false, GlobalValue::InternalLinkage,
736 NullPtr,F->getName()+".fpcache");
Jeff Cohen00b168892005-07-27 06:12:32 +0000737
Misha Brukmande4803d2004-04-19 03:36:47 +0000738 // Construct a new stub function that will re-route calls to F
Misha Brukmandc7fef82004-04-19 01:12:01 +0000739 const FunctionType *FuncTy = F->getFunctionType();
Gabor Greif051a9502008-04-06 20:25:17 +0000740 Function *FuncWrapper = Function::Create(FuncTy,
741 GlobalValue::InternalLinkage,
742 F->getName() + "_wrapper",
743 F->getParent());
744 BasicBlock *EntryBB = BasicBlock::Create("entry", FuncWrapper);
745 BasicBlock *DoCallBB = BasicBlock::Create("usecache", FuncWrapper);
746 BasicBlock *LookupBB = BasicBlock::Create("lookupfp", FuncWrapper);
Jeff Cohen00b168892005-07-27 06:12:32 +0000747
Chris Lattnera3efca12005-07-12 01:00:32 +0000748 // Check to see if we already looked up the value.
749 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
Owen Anderson333c4002009-07-09 23:48:35 +0000750 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
751 NullPtr, "isNull");
Gabor Greif051a9502008-04-06 20:25:17 +0000752 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000753
Misha Brukmande4803d2004-04-19 03:36:47 +0000754 // Resolve the call to function F via the JIT API:
755 //
756 // call resolver(GetElementPtr...)
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000757 CallInst *Resolver =
758 CallInst::Create(resolverFunc, ResolverArgs.begin(),
759 ResolverArgs.end(), "resolver", LookupBB);
760
761 // Cast the result from the resolver to correctly-typed function.
762 CastInst *CastedResolver =
763 new BitCastInst(Resolver,
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000764 Context.getPointerTypeUnqual(F->getFunctionType()),
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000765 "resolverCast", LookupBB);
Reid Spencer3da59db2006-11-27 01:05:10 +0000766
Chris Lattnera3efca12005-07-12 01:00:32 +0000767 // Save the value in our cache.
768 new StoreInst(CastedResolver, Cache, LookupBB);
Gabor Greif051a9502008-04-06 20:25:17 +0000769 BranchInst::Create(DoCallBB, LookupBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000770
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000771 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(),
772 "fp", DoCallBB);
Chris Lattnera3efca12005-07-12 01:00:32 +0000773 FuncPtr->addIncoming(CastedResolver, LookupBB);
774 FuncPtr->addIncoming(CachedVal, EntryBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000775
Chris Lattnera3efca12005-07-12 01:00:32 +0000776 // Save the argument list.
Misha Brukmandc7fef82004-04-19 01:12:01 +0000777 std::vector<Value*> Args;
Alkis Evlogimenos5a1c58d2005-03-15 07:02:26 +0000778 for (Function::arg_iterator i = FuncWrapper->arg_begin(),
779 e = FuncWrapper->arg_end(); i != e; ++i)
Misha Brukmandc7fef82004-04-19 01:12:01 +0000780 Args.push_back(i);
781
782 // Pass on the arguments to the real function, return its result
783 if (F->getReturnType() == Type::VoidTy) {
Gabor Greif051a9502008-04-06 20:25:17 +0000784 CallInst::Create(FuncPtr, Args.begin(), Args.end(), "", DoCallBB);
785 ReturnInst::Create(DoCallBB);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000786 } else {
Gabor Greif051a9502008-04-06 20:25:17 +0000787 CallInst *Call = CallInst::Create(FuncPtr, Args.begin(), Args.end(),
788 "retval", DoCallBB);
789 ReturnInst::Create(Call, DoCallBB);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000790 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000791
Misha Brukmande4803d2004-04-19 03:36:47 +0000792 // Use the wrapper function instead of the old function
793 F->replaceAllUsesWith(FuncWrapper);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000794 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000795 }
796 }
797 }
798
799 if (verifyModule(*Test) || verifyModule(*Safe)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000800 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000801 abort();
802 }
803}
804
805
806
807/// TestCodeGenerator - This is the predicate function used to check to see if
808/// the "Test" portion of the program is miscompiled by the code generator under
809/// test. If so, return true. In any case, both module arguments are deleted.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000810///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000811static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
812 CleanupAndPrepareModules(BD, Test, Safe);
813
Reid Spencer97182982004-12-15 01:53:08 +0000814 sys::Path TestModuleBC("bugpoint.test.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000815 std::string ErrMsg;
816 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000817 errs() << BD.getToolName() << "Error making unique filename: "
818 << ErrMsg << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +0000819 exit(1);
820 }
Reid Spencer97182982004-12-15 01:53:08 +0000821 if (BD.writeProgramToFile(TestModuleBC.toString(), Test)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000822 errs() << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000823 exit(1);
824 }
825 delete Test;
826
827 // Make the shared library
Reid Spencer97182982004-12-15 01:53:08 +0000828 sys::Path SafeModuleBC("bugpoint.safe.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000829 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000830 errs() << BD.getToolName() << "Error making unique filename: "
831 << ErrMsg << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +0000832 exit(1);
833 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000834
Reid Spencer97182982004-12-15 01:53:08 +0000835 if (BD.writeProgramToFile(SafeModuleBC.toString(), Safe)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000836 errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000837 exit(1);
838 }
Reid Spencer97182982004-12-15 01:53:08 +0000839 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.toString());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000840 delete Safe;
841
842 // Run the code generator on the `Test' code, loading the shared library.
843 // The function returns whether or not the new output differs from reference.
Reid Spencer97182982004-12-15 01:53:08 +0000844 int Result = BD.diffProgram(TestModuleBC.toString(), SharedObject, false);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000845
846 if (Result)
Dan Gohman65f57c22009-07-15 16:35:29 +0000847 errs() << ": still failing!\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000848 else
Dan Gohman65f57c22009-07-15 16:35:29 +0000849 errs() << ": didn't fail.\n";
Reid Spencera229c5c2005-07-08 03:08:58 +0000850 TestModuleBC.eraseFromDisk();
851 SafeModuleBC.eraseFromDisk();
852 sys::Path(SharedObject).eraseFromDisk();
Chris Lattnera57d86b2004-04-05 22:58:16 +0000853
854 return Result;
855}
856
857
Misha Brukman8c194ea2004-04-21 18:36:43 +0000858/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
859///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000860bool BugDriver::debugCodeGenerator() {
Dan Gohman70ef4492008-12-08 04:02:47 +0000861 if ((void*)SafeInterpreter == (void*)Interpreter) {
862 std::string Result = executeProgramSafely("bugpoint.safe.out");
Dan Gohmanac95cc72009-07-16 15:30:09 +0000863 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
864 << "the reference diff. This may be due to a\n front-end "
865 << "bug or a bug in the original program, but this can also "
866 << "happen if bugpoint isn't running the program with the "
867 << "right flags or input.\n I left the result of executing "
868 << "the program with the \"safe\" backend in this file for "
869 << "you: '"
870 << Result << "'.\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000871 return true;
872 }
873
874 DisambiguateGlobalSymbols(Program);
875
876 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
877
878 // Split the module into the two halves of the program we want.
Dan Gohmand50330c2009-04-22 15:57:18 +0000879 DenseMap<const Value*, Value*> ValueMap;
880 Module *ToNotCodeGen = CloneModule(getProgram(), ValueMap);
881 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, ValueMap);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000882
883 // Condition the modules
884 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
885
Reid Spencer97182982004-12-15 01:53:08 +0000886 sys::Path TestModuleBC("bugpoint.test.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000887 std::string ErrMsg;
888 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000889 errs() << getToolName() << "Error making unique filename: "
890 << ErrMsg << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +0000891 exit(1);
892 }
Reid Spencer97182982004-12-15 01:53:08 +0000893
894 if (writeProgramToFile(TestModuleBC.toString(), ToCodeGen)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000895 errs() << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000896 exit(1);
897 }
898 delete ToCodeGen;
899
900 // Make the shared library
Reid Spencer97182982004-12-15 01:53:08 +0000901 sys::Path SafeModuleBC("bugpoint.safe.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000902 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000903 errs() << getToolName() << "Error making unique filename: "
904 << ErrMsg << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +0000905 exit(1);
906 }
Reid Spencer97182982004-12-15 01:53:08 +0000907
908 if (writeProgramToFile(SafeModuleBC.toString(), ToNotCodeGen)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000909 errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000910 exit(1);
911 }
Reid Spencer97182982004-12-15 01:53:08 +0000912 std::string SharedObject = compileSharedObject(SafeModuleBC.toString());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000913 delete ToNotCodeGen;
914
Dan Gohmanac95cc72009-07-16 15:30:09 +0000915 outs() << "You can reproduce the problem with the command line: \n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000916 if (isExecutingJIT()) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000917 outs() << " lli -load " << SharedObject << " " << TestModuleBC;
Chris Lattnera57d86b2004-04-05 22:58:16 +0000918 } else {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000919 outs() << " llc -f " << TestModuleBC << " -o " << TestModuleBC<< ".s\n";
920 outs() << " gcc " << SharedObject << " " << TestModuleBC
Chris Lattner59615f02005-01-15 00:07:19 +0000921 << ".s -o " << TestModuleBC << ".exe";
922#if defined (HAVE_LINK_R)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000923 outs() << " -Wl,-R.";
Chris Lattner59615f02005-01-15 00:07:19 +0000924#endif
Dan Gohmanac95cc72009-07-16 15:30:09 +0000925 outs() << "\n";
926 outs() << " " << TestModuleBC << ".exe";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000927 }
928 for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000929 outs() << " " << InputArgv[i];
930 outs() << '\n';
931 outs() << "The shared object was created with:\n llc -march=c "
932 << SafeModuleBC << " -o temporary.c\n"
933 << " gcc -xc temporary.c -O2 -o " << SharedObject
Chris Lattnera57d86b2004-04-05 22:58:16 +0000934#if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000935 << " -G" // Compile a shared library, `-G' for Sparc
Chris Lattnera57d86b2004-04-05 22:58:16 +0000936#else
Dan Gohmanac95cc72009-07-16 15:30:09 +0000937 << " -fPIC -shared" // `-shared' for Linux/X86, maybe others
Chris Lattnera57d86b2004-04-05 22:58:16 +0000938#endif
Dan Gohmanac95cc72009-07-16 15:30:09 +0000939 << " -fno-strict-aliasing\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000940
941 return false;
942}