blob: 57a4fc717fe641b59e4bad7231a7278e4c8f37d3 [file] [log] [blame]
Chris Lattner4a106452002-12-23 23:50:16 +00001//===- Miscompilation.cpp - Debug program miscompilations -----------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
John Criswell7c0e0222003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner21c62da2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
John Criswell7c0e0222003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner4a106452002-12-23 23:50:16 +00009//
Chris Lattnera57d86b2004-04-05 22:58:16 +000010// This file implements optimizer and code generation miscompilation debugging
11// support.
Chris Lattner4a106452002-12-23 23:50:16 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "BugDriver.h"
Chris Lattner126840f2003-04-24 20:16:29 +000016#include "ListReducer.h"
Daniel Dunbarca740962009-08-18 03:35:57 +000017#include "ToolRunner.h"
Chris Lattnera57d86b2004-04-05 22:58:16 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Instructions.h"
Reid Spencer605b9e22004-11-14 23:00:08 +000021#include "llvm/Linker.h"
Chris Lattner4a106452002-12-23 23:50:16 +000022#include "llvm/Module.h"
Misha Brukmane49603d2003-08-07 21:19:30 +000023#include "llvm/Pass.h"
Chris Lattnera57d86b2004-04-05 22:58:16 +000024#include "llvm/Analysis/Verifier.h"
25#include "llvm/Support/Mangler.h"
Chris Lattner640f22e2003-04-24 17:02:17 +000026#include "llvm/Transforms/Utils/Cloning.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000027#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/FileUtilities.h"
Chris Lattner59615f02005-01-15 00:07:19 +000029#include "llvm/Config/config.h" // for HAVE_LINK_R
Chris Lattnerfa761832004-01-14 03:38:37 +000030using namespace llvm;
Chris Lattner4a106452002-12-23 23:50:16 +000031
Chris Lattnera57d86b2004-04-05 22:58:16 +000032namespace llvm {
33 extern cl::list<std::string> InputArgv;
34}
35
Chris Lattnerefdc0b52004-03-14 20:50:42 +000036namespace {
Reid Spencerdc31a8a2006-11-11 19:05:02 +000037 static llvm::cl::opt<bool>
38 DisableLoopExtraction("disable-loop-extraction",
39 cl::desc("Don't extract loops when searching for miscompilations"),
40 cl::init(false));
David Goodwin265d82e2009-07-28 23:08:36 +000041 static llvm::cl::opt<bool>
42 DisableBlockExtraction("disable-block-extraction",
43 cl::desc("Don't extract blocks when searching for miscompilations"),
44 cl::init(false));
Reid Spencerdc31a8a2006-11-11 19:05:02 +000045
Chris Lattnerfa761832004-01-14 03:38:37 +000046 class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
47 BugDriver &BD;
48 public:
49 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +000050
Chris Lattnerfa761832004-01-14 03:38:37 +000051 virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
52 std::vector<const PassInfo*> &Suffix);
53 };
54}
Chris Lattner640f22e2003-04-24 17:02:17 +000055
Misha Brukman8c194ea2004-04-21 18:36:43 +000056/// TestResult - After passes have been split into a test group and a control
57/// group, see if they still break the program.
58///
Chris Lattner640f22e2003-04-24 17:02:17 +000059ReduceMiscompilingPasses::TestResult
Chris Lattner39aebca2003-04-24 22:24:22 +000060ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
Chris Lattner06943ad2003-04-25 03:16:05 +000061 std::vector<const PassInfo*> &Suffix) {
62 // First, run the program with just the Suffix passes. If it is still broken
Chris Lattner640f22e2003-04-24 17:02:17 +000063 // with JUST the kept passes, discard the prefix passes.
Dan Gohmanac95cc72009-07-16 15:30:09 +000064 outs() << "Checking to see if '" << getPassesString(Suffix)
65 << "' compiles correctly: ";
Chris Lattner640f22e2003-04-24 17:02:17 +000066
Gabor Greif8ff70c22007-07-04 21:55:50 +000067 std::string BitcodeResult;
68 if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Dan Gohman65f57c22009-07-15 16:35:29 +000069 errs() << " Error running this sequence of passes"
70 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +000071 BD.setPassesToRun(Suffix);
Gabor Greif8ff70c22007-07-04 21:55:50 +000072 BD.EmitProgressBitcode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +000073 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +000074 }
Owen Anderson9adc0ab2009-07-14 23:09:55 +000075
Chris Lattner640f22e2003-04-24 17:02:17 +000076 // Check to see if the finished program matches the reference output...
Gabor Greif8ff70c22007-07-04 21:55:50 +000077 if (BD.diffProgram(BitcodeResult, "", true /*delete bitcode*/)) {
Dan Gohmanac95cc72009-07-16 15:30:09 +000078 outs() << " nope.\n";
Chris Lattner59615f02005-01-15 00:07:19 +000079 if (Suffix.empty()) {
Dan Gohman65f57c22009-07-15 16:35:29 +000080 errs() << BD.getToolName() << ": I'm confused: the test fails when "
81 << "no passes are run, nondeterministic program?\n";
Chris Lattner59615f02005-01-15 00:07:19 +000082 exit(1);
83 }
Misha Brukman123f8fe2004-04-22 20:02:09 +000084 return KeepSuffix; // Miscompilation detected!
Chris Lattner640f22e2003-04-24 17:02:17 +000085 }
Dan Gohmanac95cc72009-07-16 15:30:09 +000086 outs() << " yup.\n"; // No miscompilation!
Chris Lattner640f22e2003-04-24 17:02:17 +000087
88 if (Prefix.empty()) return NoFailure;
89
Chris Lattner06943ad2003-04-25 03:16:05 +000090 // Next, see if the program is broken if we run the "prefix" passes first,
Misha Brukmanbc0e9982003-07-14 17:20:40 +000091 // then separately run the "kept" passes.
Dan Gohmanac95cc72009-07-16 15:30:09 +000092 outs() << "Checking to see if '" << getPassesString(Prefix)
93 << "' compiles correctly: ";
Chris Lattner640f22e2003-04-24 17:02:17 +000094
95 // If it is not broken with the kept passes, it's possible that the prefix
96 // passes must be run before the kept passes to break it. If the program
97 // WORKS after the prefix passes, but then fails if running the prefix AND
Gabor Greif8ff70c22007-07-04 21:55:50 +000098 // kept passes, we can update our bitcode file to include the result of the
Chris Lattner640f22e2003-04-24 17:02:17 +000099 // prefix passes, then discard the prefix passes.
100 //
Gabor Greif8ff70c22007-07-04 21:55:50 +0000101 if (BD.runPasses(Prefix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000102 errs() << " Error running this sequence of passes"
103 << " on the input program!\n";
Chris Lattner9c6cfe12003-10-17 23:03:16 +0000104 BD.setPassesToRun(Prefix);
Gabor Greif8ff70c22007-07-04 21:55:50 +0000105 BD.EmitProgressBitcode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +0000106 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +0000107 }
108
109 // If the prefix maintains the predicate by itself, only keep the prefix!
Gabor Greif8ff70c22007-07-04 21:55:50 +0000110 if (BD.diffProgram(BitcodeResult)) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000111 outs() << " nope.\n";
Gabor Greif8ff70c22007-07-04 21:55:50 +0000112 sys::Path(BitcodeResult).eraseFromDisk();
Chris Lattner640f22e2003-04-24 17:02:17 +0000113 return KeepPrefix;
114 }
Dan Gohmanac95cc72009-07-16 15:30:09 +0000115 outs() << " yup.\n"; // No miscompilation!
Chris Lattner640f22e2003-04-24 17:02:17 +0000116
117 // Ok, so now we know that the prefix passes work, try running the suffix
118 // passes on the result of the prefix passes.
119 //
Owen Anderson8b477ed2009-07-01 16:58:40 +0000120 Module *PrefixOutput = ParseInputFile(BitcodeResult, BD.getContext());
Chris Lattner640f22e2003-04-24 17:02:17 +0000121 if (PrefixOutput == 0) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000122 errs() << BD.getToolName() << ": Error reading bitcode file '"
123 << BitcodeResult << "'!\n";
Chris Lattner640f22e2003-04-24 17:02:17 +0000124 exit(1);
125 }
Gabor Greif8ff70c22007-07-04 21:55:50 +0000126 sys::Path(BitcodeResult).eraseFromDisk(); // No longer need the file on disk
Chris Lattnerf4789e62004-04-23 20:36:51 +0000127
128 // Don't check if there are no passes in the suffix.
129 if (Suffix.empty())
130 return NoFailure;
Misha Brukman3da94ae2005-04-22 00:00:37 +0000131
Dan Gohmanac95cc72009-07-16 15:30:09 +0000132 outs() << "Checking to see if '" << getPassesString(Suffix)
Chris Lattner640f22e2003-04-24 17:02:17 +0000133 << "' passes compile correctly after the '"
134 << getPassesString(Prefix) << "' passes: ";
135
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000136 Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
Gabor Greif8ff70c22007-07-04 21:55:50 +0000137 if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000138 errs() << " Error running this sequence of passes"
139 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +0000140 BD.setPassesToRun(Suffix);
Gabor Greif8ff70c22007-07-04 21:55:50 +0000141 BD.EmitProgressBitcode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +0000142 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +0000143 }
144
145 // Run the result...
Gabor Greif8ff70c22007-07-04 21:55:50 +0000146 if (BD.diffProgram(BitcodeResult, "", true/*delete bitcode*/)) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000147 outs() << " nope.\n";
Chris Lattner640f22e2003-04-24 17:02:17 +0000148 delete OriginalInput; // We pruned down the original input...
Chris Lattner06943ad2003-04-25 03:16:05 +0000149 return KeepSuffix;
Chris Lattner640f22e2003-04-24 17:02:17 +0000150 }
151
152 // Otherwise, we must not be running the bad pass anymore.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000153 outs() << " yup.\n"; // No miscompilation!
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000154 delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test
Chris Lattner640f22e2003-04-24 17:02:17 +0000155 return NoFailure;
156}
157
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000158namespace {
Chris Lattnerfa761832004-01-14 03:38:37 +0000159 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
160 BugDriver &BD;
Chris Lattnerb15825b2004-04-05 21:37:38 +0000161 bool (*TestFn)(BugDriver &, Module *, Module *);
Chris Lattnerfa761832004-01-14 03:38:37 +0000162 public:
Chris Lattnerb15825b2004-04-05 21:37:38 +0000163 ReduceMiscompilingFunctions(BugDriver &bd,
164 bool (*F)(BugDriver &, Module *, Module *))
165 : BD(bd), TestFn(F) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +0000166
Chris Lattnerfa761832004-01-14 03:38:37 +0000167 virtual TestResult doTest(std::vector<Function*> &Prefix,
168 std::vector<Function*> &Suffix) {
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000169 if (!Suffix.empty() && TestFuncs(Suffix))
Chris Lattnerfa761832004-01-14 03:38:37 +0000170 return KeepSuffix;
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000171 if (!Prefix.empty() && TestFuncs(Prefix))
Chris Lattnerfa761832004-01-14 03:38:37 +0000172 return KeepPrefix;
173 return NoFailure;
174 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000175
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000176 bool TestFuncs(const std::vector<Function*> &Prefix);
Chris Lattnerfa761832004-01-14 03:38:37 +0000177 };
178}
Chris Lattner640f22e2003-04-24 17:02:17 +0000179
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000180/// TestMergedProgram - Given two modules, link them together and run the
181/// program, checking to see if the program matches the diff. If the diff
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000182/// matches, return false, otherwise return true. If the DeleteInputs argument
183/// is set to true then this function deletes both input modules before it
184/// returns.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000185///
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000186static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
187 bool DeleteInputs) {
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000188 // Link the two portions of the program back to together.
189 std::string ErrorMsg;
Chris Lattner90c18c52004-11-16 06:31:38 +0000190 if (!DeleteInputs) {
191 M1 = CloneModule(M1);
192 M2 = CloneModule(M2);
193 }
Reid Spencere4874022004-12-13 03:01:03 +0000194 if (Linker::LinkModules(M1, M2, &ErrorMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000195 errs() << BD.getToolName() << ": Error linking modules together:"
196 << ErrorMsg << '\n';
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000197 exit(1);
198 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000199 delete M2; // We are done with this module.
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000200
201 Module *OldProgram = BD.swapProgramIn(M1);
202
203 // Execute the program. If it does not match the expected output, we must
204 // return true.
205 bool Broken = BD.diffProgram();
206
207 // Delete the linked module & restore the original
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000208 BD.swapProgramIn(OldProgram);
Chris Lattner5313f232004-04-02 06:32:17 +0000209 delete M1;
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000210 return Broken;
211}
212
Misha Brukman8c194ea2004-04-21 18:36:43 +0000213/// TestFuncs - split functions in a Module into two groups: those that are
214/// under consideration for miscompilation vs. those that are not, and test
215/// accordingly. Each group of functions becomes a separate Module.
216///
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000217bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
Chris Lattner640f22e2003-04-24 17:02:17 +0000218 // Test to see if the function is misoptimized if we ONLY run it on the
219 // functions listed in Funcs.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000220 outs() << "Checking to see if the program is misoptimized when "
221 << (Funcs.size()==1 ? "this function is" : "these functions are")
222 << " run through the pass"
223 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000224 PrintFunctionList(Funcs);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000225 outs() << '\n';
Chris Lattner640f22e2003-04-24 17:02:17 +0000226
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000227 // Split the module into the two halves of the program we want.
Dan Gohmand50330c2009-04-22 15:57:18 +0000228 DenseMap<const Value*, Value*> ValueMap;
229 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
230 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, Funcs,
231 ValueMap);
Chris Lattner640f22e2003-04-24 17:02:17 +0000232
Nick Lewycky6fa98b12007-11-14 06:47:06 +0000233 // Run the predicate, note that the predicate will delete both input modules.
Chris Lattnerb15825b2004-04-05 21:37:38 +0000234 return TestFn(BD, ToOptimize, ToNotOptimize);
Chris Lattner640f22e2003-04-24 17:02:17 +0000235}
236
Misha Brukman8c194ea2004-04-21 18:36:43 +0000237/// DisambiguateGlobalSymbols - Mangle symbols to guarantee uniqueness by
238/// modifying predominantly internal symbols rather than external ones.
239///
Chris Lattner36ee07f2004-04-11 23:52:35 +0000240static void DisambiguateGlobalSymbols(Module *M) {
241 // Try not to cause collisions by minimizing chances of renaming an
242 // already-external symbol, so take in external globals and functions as-is.
243 // The code should work correctly without disambiguation (assuming the same
244 // mangler is used by the two code generators), but having symbols with the
245 // same name causes warnings to be emitted by the code generator.
246 Mangler Mang(*M);
Andrew Lenharth0fccc742005-12-06 20:51:30 +0000247 // Agree with the CBE on symbol naming
248 Mang.markCharUnacceptable('.');
Chris Lattner67ef9e42006-05-04 23:35:31 +0000249 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
Chris Lattner9d5511b2009-07-15 04:50:47 +0000250 I != E; ++I) {
251 // Don't mangle asm names.
252 if (!I->hasName() || I->getName()[0] != 1)
253 I->setName(Mang.getMangledName(I));
254 }
255 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I) {
Chris Lattner4285d152009-07-19 20:19:04 +0000256 // Don't mangle asm names or intrinsics.
Chris Lattnere0d5c172009-07-19 20:19:25 +0000257 if ((!I->hasName() || I->getName()[0] != 1) &&
258 I->getIntrinsicID() == 0)
Chris Lattner9d5511b2009-07-15 04:50:47 +0000259 I->setName(Mang.getMangledName(I));
260 }
Chris Lattner36ee07f2004-04-11 23:52:35 +0000261}
262
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000263/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
264/// check to see if we can extract the loops in the region without obscuring the
265/// bug. If so, it reduces the amount of code identified.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000266///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000267static bool ExtractLoops(BugDriver &BD,
268 bool (*TestFn)(BugDriver &, Module *, Module *),
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000269 std::vector<Function*> &MiscompiledFunctions) {
270 bool MadeChange = false;
271 while (1) {
Chris Lattneraed98fa2005-08-02 23:25:56 +0000272 if (BugpointIsInterrupted) return MadeChange;
273
Dan Gohmand50330c2009-04-22 15:57:18 +0000274 DenseMap<const Value*, Value*> ValueMap;
275 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000276 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohmand50330c2009-04-22 15:57:18 +0000277 MiscompiledFunctions,
278 ValueMap);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000279 Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
280 if (!ToOptimizeLoopExtracted) {
281 // If the loop extractor crashed or if there were no extractible loops,
282 // then this chapter of our odyssey is over with.
283 delete ToNotOptimize;
284 delete ToOptimize;
285 return MadeChange;
286 }
287
Dan Gohman65f57c22009-07-15 16:35:29 +0000288 errs() << "Extracted a loop from the breaking portion of the program.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000289
290 // Bugpoint is intentionally not very trusting of LLVM transformations. In
291 // particular, we're not going to assume that the loop extractor works, so
292 // we're going to test the newly loop extracted program to make sure nothing
293 // has broken. If something broke, then we'll inform the user and stop
294 // extraction.
Dan Gohman70ef4492008-12-08 04:02:47 +0000295 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000296 if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000297 BD.switchToInterpreter(AI);
298
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000299 // Merged program doesn't work anymore!
Dan Gohman65f57c22009-07-15 16:35:29 +0000300 errs() << " *** ERROR: Loop extraction broke the program. :("
301 << " Please report a bug!\n";
302 errs() << " Continuing on with un-loop-extracted version.\n";
Chris Lattner56c41862005-05-08 21:54:56 +0000303
304 BD.writeProgramToFile("bugpoint-loop-extract-fail-tno.bc", ToNotOptimize);
305 BD.writeProgramToFile("bugpoint-loop-extract-fail-to.bc", ToOptimize);
306 BD.writeProgramToFile("bugpoint-loop-extract-fail-to-le.bc",
307 ToOptimizeLoopExtracted);
308
Dan Gohman65f57c22009-07-15 16:35:29 +0000309 errs() << "Please submit the bugpoint-loop-extract-fail-*.bc files.\n";
Chris Lattner56c41862005-05-08 21:54:56 +0000310 delete ToOptimize;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000311 delete ToNotOptimize;
312 delete ToOptimizeLoopExtracted;
313 return MadeChange;
314 }
Chris Lattner56c41862005-05-08 21:54:56 +0000315 delete ToOptimize;
Chris Lattnera57d86b2004-04-05 22:58:16 +0000316 BD.switchToInterpreter(AI);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000317
Dan Gohmanac95cc72009-07-16 15:30:09 +0000318 outs() << " Testing after loop extraction:\n";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000319 // Clone modules, the tester function will free them.
320 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
321 Module *TNOBackup = CloneModule(ToNotOptimize);
322 if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000323 outs() << "*** Loop extraction masked the problem. Undoing.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000324 // If the program is not still broken, then loop extraction did something
325 // that masked the error. Stop loop extraction now.
Chris Lattnerb15825b2004-04-05 21:37:38 +0000326 delete TOLEBackup;
327 delete TNOBackup;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000328 return MadeChange;
329 }
Chris Lattnerb15825b2004-04-05 21:37:38 +0000330 ToOptimizeLoopExtracted = TOLEBackup;
331 ToNotOptimize = TNOBackup;
332
Dan Gohmanac95cc72009-07-16 15:30:09 +0000333 outs() << "*** Loop extraction successful!\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000334
Chris Lattner90c18c52004-11-16 06:31:38 +0000335 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
336 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
337 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +0000338 if (!I->isDeclaration())
Chris Lattnerfa1af132004-11-19 07:09:40 +0000339 MisCompFunctions.push_back(std::make_pair(I->getName(),
340 I->getFunctionType()));
Chris Lattner90c18c52004-11-16 06:31:38 +0000341
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000342 // Okay, great! Now we know that we extracted a loop and that loop
343 // extraction both didn't break the program, and didn't mask the problem.
344 // Replace the current program with the loop extracted version, and try to
345 // extract another loop.
346 std::string ErrorMsg;
Reid Spencere4874022004-12-13 03:01:03 +0000347 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
Dan Gohman65f57c22009-07-15 16:35:29 +0000348 errs() << BD.getToolName() << ": Error linking modules together:"
349 << ErrorMsg << '\n';
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000350 exit(1);
351 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000352 delete ToOptimizeLoopExtracted;
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000353
354 // All of the Function*'s in the MiscompiledFunctions list are in the old
Chris Lattner5313f232004-04-02 06:32:17 +0000355 // module. Update this list to include all of the functions in the
356 // optimized and loop extracted module.
357 MiscompiledFunctions.clear();
Chris Lattner90c18c52004-11-16 06:31:38 +0000358 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spenceref9b9a72007-02-05 20:47:22 +0000359 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
360
Chris Lattner90c18c52004-11-16 06:31:38 +0000361 assert(NewF && "Function not found??");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000362 assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
363 "found wrong function type?");
Chris Lattner90c18c52004-11-16 06:31:38 +0000364 MiscompiledFunctions.push_back(NewF);
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000365 }
366
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000367 BD.setNewProgram(ToNotOptimize);
368 MadeChange = true;
369 }
370}
371
Chris Lattner5e783ab2004-05-11 21:54:13 +0000372namespace {
373 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
374 BugDriver &BD;
375 bool (*TestFn)(BugDriver &, Module *, Module *);
376 std::vector<Function*> FunctionsBeingTested;
377 public:
378 ReduceMiscompiledBlocks(BugDriver &bd,
379 bool (*F)(BugDriver &, Module *, Module *),
380 const std::vector<Function*> &Fns)
381 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
Misha Brukman3da94ae2005-04-22 00:00:37 +0000382
Chris Lattner5e783ab2004-05-11 21:54:13 +0000383 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
384 std::vector<BasicBlock*> &Suffix) {
385 if (!Suffix.empty() && TestFuncs(Suffix))
386 return KeepSuffix;
387 if (TestFuncs(Prefix))
388 return KeepPrefix;
389 return NoFailure;
390 }
Misha Brukman3da94ae2005-04-22 00:00:37 +0000391
Chris Lattner5e783ab2004-05-11 21:54:13 +0000392 bool TestFuncs(const std::vector<BasicBlock*> &Prefix);
393 };
394}
395
396/// TestFuncs - Extract all blocks for the miscompiled functions except for the
397/// specified blocks. If the problem still exists, return true.
398///
399bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) {
400 // Test to see if the function is misoptimized if we ONLY run it on the
401 // functions listed in Funcs.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000402 outs() << "Checking to see if the program is misoptimized when all ";
Chris Lattner68bee932004-05-12 16:08:01 +0000403 if (!BBs.empty()) {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000404 outs() << "but these " << BBs.size() << " blocks are extracted: ";
Chris Lattner68bee932004-05-12 16:08:01 +0000405 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000406 outs() << BBs[i]->getName() << " ";
407 if (BBs.size() > 10) outs() << "...";
Chris Lattner68bee932004-05-12 16:08:01 +0000408 } else {
Dan Gohmanac95cc72009-07-16 15:30:09 +0000409 outs() << "blocks are extracted.";
Chris Lattner68bee932004-05-12 16:08:01 +0000410 }
Dan Gohmanac95cc72009-07-16 15:30:09 +0000411 outs() << '\n';
Chris Lattner5e783ab2004-05-11 21:54:13 +0000412
413 // Split the module into the two halves of the program we want.
Dan Gohmand50330c2009-04-22 15:57:18 +0000414 DenseMap<const Value*, Value*> ValueMap;
415 Module *ToNotOptimize = CloneModule(BD.getProgram(), ValueMap);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000416 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohmand50330c2009-04-22 15:57:18 +0000417 FunctionsBeingTested,
418 ValueMap);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000419
420 // Try the extraction. If it doesn't work, then the block extractor crashed
421 // or something, in which case bugpoint can't chase down this possibility.
422 if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) {
423 delete ToOptimize;
424 // Run the predicate, not that the predicate will delete both input modules.
425 return TestFn(BD, New, ToNotOptimize);
426 }
427 delete ToOptimize;
428 delete ToNotOptimize;
429 return false;
430}
431
432
433/// ExtractBlocks - Given a reduced list of functions that still expose the bug,
434/// extract as many basic blocks from the region as possible without obscuring
435/// the bug.
436///
437static bool ExtractBlocks(BugDriver &BD,
438 bool (*TestFn)(BugDriver &, Module *, Module *),
439 std::vector<Function*> &MiscompiledFunctions) {
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000440 if (BugpointIsInterrupted) return false;
441
Chris Lattner5e783ab2004-05-11 21:54:13 +0000442 std::vector<BasicBlock*> Blocks;
443 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
444 for (Function::iterator I = MiscompiledFunctions[i]->begin(),
445 E = MiscompiledFunctions[i]->end(); I != E; ++I)
446 Blocks.push_back(I);
447
448 // Use the list reducer to identify blocks that can be extracted without
449 // obscuring the bug. The Blocks list will end up containing blocks that must
450 // be retained from the original program.
451 unsigned OldSize = Blocks.size();
Chris Lattner68bee932004-05-12 16:08:01 +0000452
453 // Check to see if all blocks are extractible first.
454 if (ReduceMiscompiledBlocks(BD, TestFn,
455 MiscompiledFunctions).TestFuncs(std::vector<BasicBlock*>())) {
456 Blocks.clear();
457 } else {
458 ReduceMiscompiledBlocks(BD, TestFn,MiscompiledFunctions).reduceList(Blocks);
459 if (Blocks.size() == OldSize)
460 return false;
461 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000462
Dan Gohmand50330c2009-04-22 15:57:18 +0000463 DenseMap<const Value*, Value*> ValueMap;
464 Module *ProgClone = CloneModule(BD.getProgram(), ValueMap);
Chris Lattner2290e752004-05-12 02:43:24 +0000465 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
Dan Gohmand50330c2009-04-22 15:57:18 +0000466 MiscompiledFunctions,
467 ValueMap);
Chris Lattner2290e752004-05-12 02:43:24 +0000468 Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
469 if (Extracted == 0) {
Chris Lattnerda895d62005-02-27 06:18:25 +0000470 // Weird, extraction should have worked.
Dan Gohman65f57c22009-07-15 16:35:29 +0000471 errs() << "Nondeterministic problem extracting blocks??\n";
Chris Lattner2290e752004-05-12 02:43:24 +0000472 delete ProgClone;
473 delete ToExtract;
474 return false;
475 }
Chris Lattner5e783ab2004-05-11 21:54:13 +0000476
Chris Lattner2290e752004-05-12 02:43:24 +0000477 // Otherwise, block extraction succeeded. Link the two program fragments back
478 // together.
479 delete ToExtract;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000480
Chris Lattner90c18c52004-11-16 06:31:38 +0000481 std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
482 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
483 I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +0000484 if (!I->isDeclaration())
Chris Lattnerfa1af132004-11-19 07:09:40 +0000485 MisCompFunctions.push_back(std::make_pair(I->getName(),
486 I->getFunctionType()));
Chris Lattner90c18c52004-11-16 06:31:38 +0000487
Chris Lattner2290e752004-05-12 02:43:24 +0000488 std::string ErrorMsg;
Reid Spencere4874022004-12-13 03:01:03 +0000489 if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000490 errs() << BD.getToolName() << ": Error linking modules together:"
491 << ErrorMsg << '\n';
Chris Lattner2290e752004-05-12 02:43:24 +0000492 exit(1);
493 }
Chris Lattner90c18c52004-11-16 06:31:38 +0000494 delete Extracted;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000495
Chris Lattner2290e752004-05-12 02:43:24 +0000496 // Set the new program and delete the old one.
497 BD.setNewProgram(ProgClone);
Chris Lattner5e783ab2004-05-11 21:54:13 +0000498
Chris Lattner2290e752004-05-12 02:43:24 +0000499 // Update the list of miscompiled functions.
500 MiscompiledFunctions.clear();
Chris Lattner5e783ab2004-05-11 21:54:13 +0000501
Chris Lattner90c18c52004-11-16 06:31:38 +0000502 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
Reid Spenceref9b9a72007-02-05 20:47:22 +0000503 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
Chris Lattner90c18c52004-11-16 06:31:38 +0000504 assert(NewF && "Function not found??");
Reid Spenceref9b9a72007-02-05 20:47:22 +0000505 assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
506 "Function has wrong type??");
Chris Lattner90c18c52004-11-16 06:31:38 +0000507 MiscompiledFunctions.push_back(NewF);
508 }
Chris Lattner2290e752004-05-12 02:43:24 +0000509
510 return true;
Chris Lattner5e783ab2004-05-11 21:54:13 +0000511}
512
513
Chris Lattnerb15825b2004-04-05 21:37:38 +0000514/// DebugAMiscompilation - This is a generic driver to narrow down
515/// miscompilations, either in an optimization or a code generator.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000516///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000517static std::vector<Function*>
518DebugAMiscompilation(BugDriver &BD,
519 bool (*TestFn)(BugDriver &, Module *, Module *)) {
520 // Okay, now that we have reduced the list of passes which are causing the
521 // failure, see if we can pin down which functions are being
522 // miscompiled... first build a list of all of the non-external functions in
523 // the program.
524 std::vector<Function*> MiscompiledFunctions;
525 Module *Prog = BD.getProgram();
526 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
Reid Spencer5cbf9852007-01-30 20:08:39 +0000527 if (!I->isDeclaration())
Chris Lattnerb15825b2004-04-05 21:37:38 +0000528 MiscompiledFunctions.push_back(I);
529
530 // Do the reduction...
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000531 if (!BugpointIsInterrupted)
532 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Chris Lattnerb15825b2004-04-05 21:37:38 +0000533
Dan Gohmanac95cc72009-07-16 15:30:09 +0000534 outs() << "\n*** The following function"
535 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
536 << " being miscompiled: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000537 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000538 outs() << '\n';
Chris Lattnerb15825b2004-04-05 21:37:38 +0000539
540 // See if we can rip any loops out of the miscompiled functions and still
541 // trigger the problem.
Reid Spencerdc31a8a2006-11-11 19:05:02 +0000542
Reid Spencer2803b4c2006-11-11 19:59:25 +0000543 if (!BugpointIsInterrupted && !DisableLoopExtraction &&
544 ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
Chris Lattnerb15825b2004-04-05 21:37:38 +0000545 // Okay, we extracted some loops and the problem still appears. See if we
546 // can eliminate some of the created functions from being candidates.
547
Chris Lattner36ee07f2004-04-11 23:52:35 +0000548 // Loop extraction can introduce functions with the same name (foo_code).
549 // Make sure to disambiguate the symbols so that when the program is split
550 // apart that we can link it back together again.
551 DisambiguateGlobalSymbols(BD.getProgram());
552
Chris Lattnerb15825b2004-04-05 21:37:38 +0000553 // Do the reduction...
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000554 if (!BugpointIsInterrupted)
555 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000556
Dan Gohmanac95cc72009-07-16 15:30:09 +0000557 outs() << "\n*** The following function"
558 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
559 << " being miscompiled: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000560 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000561 outs() << '\n';
Chris Lattnerb15825b2004-04-05 21:37:38 +0000562 }
563
David Goodwin265d82e2009-07-28 23:08:36 +0000564 if (!BugpointIsInterrupted && !DisableBlockExtraction &&
Chris Lattneraed98fa2005-08-02 23:25:56 +0000565 ExtractBlocks(BD, TestFn, MiscompiledFunctions)) {
Chris Lattner5e783ab2004-05-11 21:54:13 +0000566 // Okay, we extracted some blocks and the problem still appears. See if we
567 // can eliminate some of the created functions from being candidates.
568
569 // Block extraction can introduce functions with the same name (foo_code).
570 // Make sure to disambiguate the symbols so that when the program is split
571 // apart that we can link it back together again.
572 DisambiguateGlobalSymbols(BD.getProgram());
573
574 // Do the reduction...
575 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000576
Dan Gohmanac95cc72009-07-16 15:30:09 +0000577 outs() << "\n*** The following function"
578 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
579 << " being miscompiled: ";
Chris Lattner5e783ab2004-05-11 21:54:13 +0000580 PrintFunctionList(MiscompiledFunctions);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000581 outs() << '\n';
Chris Lattner5e783ab2004-05-11 21:54:13 +0000582 }
583
Chris Lattnerb15825b2004-04-05 21:37:38 +0000584 return MiscompiledFunctions;
585}
586
Chris Lattnera57d86b2004-04-05 22:58:16 +0000587/// TestOptimizer - This is the predicate function used to check to see if the
588/// "Test" portion of the program is misoptimized. If so, return true. In any
589/// case, both module arguments are deleted.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000590///
Chris Lattnerb15825b2004-04-05 21:37:38 +0000591static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
592 // Run the optimization passes on ToOptimize, producing a transformed version
593 // of the functions being tested.
Dan Gohmanac95cc72009-07-16 15:30:09 +0000594 outs() << " Optimizing functions being tested: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000595 Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
596 /*AutoDebugCrashes*/true);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000597 outs() << "done.\n";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000598 delete Test;
599
Dan Gohmanac95cc72009-07-16 15:30:09 +0000600 outs() << " Checking to see if the merged program executes correctly: ";
Chris Lattner2423db02004-04-09 22:28:33 +0000601 bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
Dan Gohmanac95cc72009-07-16 15:30:09 +0000602 outs() << (Broken ? " nope.\n" : " yup.\n");
Chris Lattnerb15825b2004-04-05 21:37:38 +0000603 return Broken;
604}
605
606
Chris Lattner4a106452002-12-23 23:50:16 +0000607/// debugMiscompilation - This method is used when the passes selected are not
608/// crashing, but the generated output is semantically different from the
609/// input.
610///
611bool BugDriver::debugMiscompilation() {
Chris Lattner4a106452002-12-23 23:50:16 +0000612 // Make sure something was miscompiled...
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000613 if (!BugpointIsInterrupted)
614 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000615 errs() << "*** Optimized program matches reference output! No problem"
616 << " detected...\nbugpoint can't help you with your problem!\n";
Chris Lattnerf9aaae02005-08-02 02:16:17 +0000617 return false;
618 }
Chris Lattner4a106452002-12-23 23:50:16 +0000619
Dan Gohmanac95cc72009-07-16 15:30:09 +0000620 outs() << "\n*** Found miscompiling pass"
621 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
622 << getPassesString(getPassesToRun()) << '\n';
Gabor Greif8ff70c22007-07-04 21:55:50 +0000623 EmitProgressBitcode("passinput");
Chris Lattner4a106452002-12-23 23:50:16 +0000624
Chris Lattnerb15825b2004-04-05 21:37:38 +0000625 std::vector<Function*> MiscompiledFunctions =
626 DebugAMiscompilation(*this, TestOptimizer);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000627
Gabor Greif8ff70c22007-07-04 21:55:50 +0000628 // Output a bunch of bitcode files for the user...
Dan Gohmanac95cc72009-07-16 15:30:09 +0000629 outs() << "Outputting reduced bitcode files which expose the problem:\n";
Dan Gohmand50330c2009-04-22 15:57:18 +0000630 DenseMap<const Value*, Value*> ValueMap;
631 Module *ToNotOptimize = CloneModule(getProgram(), ValueMap);
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000632 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
Dan Gohmand50330c2009-04-22 15:57:18 +0000633 MiscompiledFunctions,
634 ValueMap);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000635
Dan Gohmanac95cc72009-07-16 15:30:09 +0000636 outs() << " Non-optimized portion: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000637 ToNotOptimize = swapProgramIn(ToNotOptimize);
Gabor Greif8ff70c22007-07-04 21:55:50 +0000638 EmitProgressBitcode("tonotoptimize", true);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000639 setNewProgram(ToNotOptimize); // Delete hacked module.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000640
Dan Gohmanac95cc72009-07-16 15:30:09 +0000641 outs() << " Portion that is input to optimizer: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000642 ToOptimize = swapProgramIn(ToOptimize);
Gabor Greif8ff70c22007-07-04 21:55:50 +0000643 EmitProgressBitcode("tooptimize");
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000644 setNewProgram(ToOptimize); // Delete hacked module.
Chris Lattner4a106452002-12-23 23:50:16 +0000645
Chris Lattner4a106452002-12-23 23:50:16 +0000646 return false;
647}
Brian Gaeked0fde302003-11-11 22:41:34 +0000648
Chris Lattnera57d86b2004-04-05 22:58:16 +0000649/// CleanupAndPrepareModules - Get the specified modules ready for code
650/// generator testing.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000651///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000652static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
653 Module *Safe) {
654 // Clean up the modules, removing extra cruft that we don't need anymore...
655 Test = BD.performFinalCleanups(Test);
656
657 // If we are executing the JIT, we have several nasty issues to take care of.
658 if (!BD.isExecutingJIT()) return;
659
660 // First, if the main function is in the Safe module, we must add a stub to
661 // the Test module to call into it. Thus, we create a new function `main'
662 // which just calls the old one.
Reid Spencer688b0492007-02-05 21:19:13 +0000663 if (Function *oldMain = Safe->getFunction("main"))
Reid Spencer5cbf9852007-01-30 20:08:39 +0000664 if (!oldMain->isDeclaration()) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000665 // Rename it
666 oldMain->setName("llvm_bugpoint_old_main");
667 // Create a NEW `main' function with same type in the test module.
Gabor Greif051a9502008-04-06 20:25:17 +0000668 Function *newMain = Function::Create(oldMain->getFunctionType(),
669 GlobalValue::ExternalLinkage,
670 "main", Test);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000671 // Create an `oldmain' prototype in the test module, which will
672 // corresponds to the real main function in the same module.
Gabor Greif051a9502008-04-06 20:25:17 +0000673 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
674 GlobalValue::ExternalLinkage,
675 oldMain->getName(), Test);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000676 // Set up and remember the argument list for the main function.
677 std::vector<Value*> args;
Alkis Evlogimenos5a1c58d2005-03-15 07:02:26 +0000678 for (Function::arg_iterator
679 I = newMain->arg_begin(), E = newMain->arg_end(),
680 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
Owen Anderson6bc41e82008-04-14 17:38:21 +0000681 I->setName(OI->getName()); // Copy argument names from oldMain
Chris Lattnera57d86b2004-04-05 22:58:16 +0000682 args.push_back(I);
683 }
684
685 // Call the old main function and return its result
Owen Anderson1d0be152009-08-13 21:58:54 +0000686 BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
Gabor Greif051a9502008-04-06 20:25:17 +0000687 CallInst *call = CallInst::Create(oldMainProto, args.begin(), args.end(),
688 "", BB);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000689
Chris Lattnera57d86b2004-04-05 22:58:16 +0000690 // If the type of old function wasn't void, return value of call
Owen Anderson1d0be152009-08-13 21:58:54 +0000691 ReturnInst::Create(Safe->getContext(), call, BB);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000692 }
693
694 // The second nasty issue we must deal with in the JIT is that the Safe
695 // module cannot directly reference any functions defined in the test
696 // module. Instead, we use a JIT API call to dynamically resolve the
697 // symbol.
Misha Brukman3da94ae2005-04-22 00:00:37 +0000698
Chris Lattnera57d86b2004-04-05 22:58:16 +0000699 // Add the resolver to the Safe module.
700 // Prototype: void *getPointerToNamedFunction(const char* Name)
Chris Lattner2db43c82007-01-07 08:13:39 +0000701 Constant *resolverFunc =
Chris Lattnera57d86b2004-04-05 22:58:16 +0000702 Safe->getOrInsertFunction("getPointerToNamedFunction",
Owen Anderson1d0be152009-08-13 21:58:54 +0000703 PointerType::getUnqual(Type::getInt8Ty(Safe->getContext())),
704 PointerType::getUnqual(Type::getInt8Ty(Safe->getContext())),
705 (Type *)0);
Misha Brukman3da94ae2005-04-22 00:00:37 +0000706
Chris Lattnera57d86b2004-04-05 22:58:16 +0000707 // Use the function we just added to get addresses of functions we need.
Misha Brukmandc7fef82004-04-19 01:12:01 +0000708 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
Reid Spencer5cbf9852007-01-30 20:08:39 +0000709 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
Duncan Sandsa3355ff2007-12-03 20:06:50 +0000710 !F->isIntrinsic() /* ignore intrinsics */) {
Reid Spencer688b0492007-02-05 21:19:13 +0000711 Function *TestFn = Test->getFunction(F->getName());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000712
713 // Don't forward functions which are external in the test module too.
Reid Spencer5cbf9852007-01-30 20:08:39 +0000714 if (TestFn && !TestFn->isDeclaration()) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000715 // 1. Add a string constant with its name to the global file
Owen Anderson1d0be152009-08-13 21:58:54 +0000716 Constant *InitArray = ConstantArray::get(F->getContext(), F->getName());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000717 GlobalVariable *funcName =
Owen Andersone9b11b42009-07-08 19:03:57 +0000718 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
Misha Brukman3da94ae2005-04-22 00:00:37 +0000719 GlobalValue::InternalLinkage, InitArray,
Owen Andersone9b11b42009-07-08 19:03:57 +0000720 F->getName() + "_name");
Chris Lattnera57d86b2004-04-05 22:58:16 +0000721
722 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
723 // sbyte* so it matches the signature of the resolver function.
724
725 // GetElementPtr *funcName, ulong 0, ulong 0
Owen Anderson1d0be152009-08-13 21:58:54 +0000726 std::vector<Constant*> GEPargs(2,
727 Constant::getNullValue(Type::getInt32Ty(F->getContext())));
Owen Anderson9adc0ab2009-07-14 23:09:55 +0000728 Value *GEP =
Owen Andersonbaf3c402009-07-29 18:55:55 +0000729 ConstantExpr::getGetElementPtr(funcName, &GEPargs[0], 2);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000730 std::vector<Value*> ResolverArgs;
731 ResolverArgs.push_back(GEP);
732
Misha Brukmande4803d2004-04-19 03:36:47 +0000733 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
734 // function that dynamically resolves the calls to F via our JIT API
Chris Lattnera3efca12005-07-12 01:00:32 +0000735 if (!F->use_empty()) {
736 // Create a new global to hold the cached function pointer.
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000737 Constant *NullPtr = ConstantPointerNull::get(F->getType());
Chris Lattnera3efca12005-07-12 01:00:32 +0000738 GlobalVariable *Cache =
Owen Andersone9b11b42009-07-08 19:03:57 +0000739 new GlobalVariable(*F->getParent(), F->getType(),
740 false, GlobalValue::InternalLinkage,
741 NullPtr,F->getName()+".fpcache");
Jeff Cohen00b168892005-07-27 06:12:32 +0000742
Misha Brukmande4803d2004-04-19 03:36:47 +0000743 // Construct a new stub function that will re-route calls to F
Misha Brukmandc7fef82004-04-19 01:12:01 +0000744 const FunctionType *FuncTy = F->getFunctionType();
Gabor Greif051a9502008-04-06 20:25:17 +0000745 Function *FuncWrapper = Function::Create(FuncTy,
746 GlobalValue::InternalLinkage,
747 F->getName() + "_wrapper",
748 F->getParent());
Owen Anderson1d0be152009-08-13 21:58:54 +0000749 BasicBlock *EntryBB = BasicBlock::Create(F->getContext(),
750 "entry", FuncWrapper);
751 BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
752 "usecache", FuncWrapper);
753 BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
754 "lookupfp", FuncWrapper);
Jeff Cohen00b168892005-07-27 06:12:32 +0000755
Chris Lattnera3efca12005-07-12 01:00:32 +0000756 // Check to see if we already looked up the value.
757 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
Owen Anderson333c4002009-07-09 23:48:35 +0000758 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
759 NullPtr, "isNull");
Gabor Greif051a9502008-04-06 20:25:17 +0000760 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000761
Misha Brukmande4803d2004-04-19 03:36:47 +0000762 // Resolve the call to function F via the JIT API:
763 //
764 // call resolver(GetElementPtr...)
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000765 CallInst *Resolver =
766 CallInst::Create(resolverFunc, ResolverArgs.begin(),
767 ResolverArgs.end(), "resolver", LookupBB);
768
769 // Cast the result from the resolver to correctly-typed function.
770 CastInst *CastedResolver =
771 new BitCastInst(Resolver,
Owen Andersondebcb012009-07-29 22:17:13 +0000772 PointerType::getUnqual(F->getFunctionType()),
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000773 "resolverCast", LookupBB);
Reid Spencer3da59db2006-11-27 01:05:10 +0000774
Chris Lattnera3efca12005-07-12 01:00:32 +0000775 // Save the value in our cache.
776 new StoreInst(CastedResolver, Cache, LookupBB);
Gabor Greif051a9502008-04-06 20:25:17 +0000777 BranchInst::Create(DoCallBB, LookupBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000778
Gabor Greifb1dbcd82008-05-15 10:04:30 +0000779 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(),
780 "fp", DoCallBB);
Chris Lattnera3efca12005-07-12 01:00:32 +0000781 FuncPtr->addIncoming(CastedResolver, LookupBB);
782 FuncPtr->addIncoming(CachedVal, EntryBB);
Jeff Cohen00b168892005-07-27 06:12:32 +0000783
Chris Lattnera3efca12005-07-12 01:00:32 +0000784 // Save the argument list.
Misha Brukmandc7fef82004-04-19 01:12:01 +0000785 std::vector<Value*> Args;
Alkis Evlogimenos5a1c58d2005-03-15 07:02:26 +0000786 for (Function::arg_iterator i = FuncWrapper->arg_begin(),
787 e = FuncWrapper->arg_end(); i != e; ++i)
Misha Brukmandc7fef82004-04-19 01:12:01 +0000788 Args.push_back(i);
789
790 // Pass on the arguments to the real function, return its result
Owen Anderson1d0be152009-08-13 21:58:54 +0000791 if (F->getReturnType() == Type::getVoidTy(F->getContext())) {
Gabor Greif051a9502008-04-06 20:25:17 +0000792 CallInst::Create(FuncPtr, Args.begin(), Args.end(), "", DoCallBB);
Owen Anderson1d0be152009-08-13 21:58:54 +0000793 ReturnInst::Create(F->getContext(), DoCallBB);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000794 } else {
Gabor Greif051a9502008-04-06 20:25:17 +0000795 CallInst *Call = CallInst::Create(FuncPtr, Args.begin(), Args.end(),
796 "retval", DoCallBB);
Owen Anderson1d0be152009-08-13 21:58:54 +0000797 ReturnInst::Create(F->getContext(),Call, DoCallBB);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000798 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000799
Misha Brukmande4803d2004-04-19 03:36:47 +0000800 // Use the wrapper function instead of the old function
801 F->replaceAllUsesWith(FuncWrapper);
Misha Brukmandc7fef82004-04-19 01:12:01 +0000802 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000803 }
804 }
805 }
806
807 if (verifyModule(*Test) || verifyModule(*Safe)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000808 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000809 abort();
810 }
811}
812
813
814
815/// TestCodeGenerator - This is the predicate function used to check to see if
816/// the "Test" portion of the program is miscompiled by the code generator under
817/// test. If so, return true. In any case, both module arguments are deleted.
Misha Brukman8c194ea2004-04-21 18:36:43 +0000818///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000819static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
820 CleanupAndPrepareModules(BD, Test, Safe);
821
Reid Spencer97182982004-12-15 01:53:08 +0000822 sys::Path TestModuleBC("bugpoint.test.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000823 std::string ErrMsg;
824 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000825 errs() << BD.getToolName() << "Error making unique filename: "
826 << ErrMsg << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +0000827 exit(1);
828 }
Chris Lattner74382b72009-08-23 22:45:37 +0000829 if (BD.writeProgramToFile(TestModuleBC.str(), Test)) {
830 errs() << "Error writing bitcode to `" << TestModuleBC.str()
831 << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000832 exit(1);
833 }
834 delete Test;
835
836 // Make the shared library
Reid Spencer97182982004-12-15 01:53:08 +0000837 sys::Path SafeModuleBC("bugpoint.safe.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000838 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000839 errs() << BD.getToolName() << "Error making unique filename: "
840 << ErrMsg << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +0000841 exit(1);
842 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000843
Chris Lattner74382b72009-08-23 22:45:37 +0000844 if (BD.writeProgramToFile(SafeModuleBC.str(), Safe)) {
845 errs() << "Error writing bitcode to `" << SafeModuleBC.str()
846 << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000847 exit(1);
848 }
Chris Lattner74382b72009-08-23 22:45:37 +0000849 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000850 delete Safe;
851
852 // Run the code generator on the `Test' code, loading the shared library.
853 // The function returns whether or not the new output differs from reference.
Chris Lattner74382b72009-08-23 22:45:37 +0000854 int Result = BD.diffProgram(TestModuleBC.str(), SharedObject, false);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000855
856 if (Result)
Dan Gohman65f57c22009-07-15 16:35:29 +0000857 errs() << ": still failing!\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000858 else
Dan Gohman65f57c22009-07-15 16:35:29 +0000859 errs() << ": didn't fail.\n";
Reid Spencera229c5c2005-07-08 03:08:58 +0000860 TestModuleBC.eraseFromDisk();
861 SafeModuleBC.eraseFromDisk();
862 sys::Path(SharedObject).eraseFromDisk();
Chris Lattnera57d86b2004-04-05 22:58:16 +0000863
864 return Result;
865}
866
867
Misha Brukman8c194ea2004-04-21 18:36:43 +0000868/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
869///
Chris Lattnera57d86b2004-04-05 22:58:16 +0000870bool BugDriver::debugCodeGenerator() {
Dan Gohman70ef4492008-12-08 04:02:47 +0000871 if ((void*)SafeInterpreter == (void*)Interpreter) {
872 std::string Result = executeProgramSafely("bugpoint.safe.out");
Dan Gohmanac95cc72009-07-16 15:30:09 +0000873 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
874 << "the reference diff. This may be due to a\n front-end "
875 << "bug or a bug in the original program, but this can also "
876 << "happen if bugpoint isn't running the program with the "
877 << "right flags or input.\n I left the result of executing "
878 << "the program with the \"safe\" backend in this file for "
879 << "you: '"
880 << Result << "'.\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000881 return true;
882 }
883
884 DisambiguateGlobalSymbols(Program);
885
886 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
887
888 // Split the module into the two halves of the program we want.
Dan Gohmand50330c2009-04-22 15:57:18 +0000889 DenseMap<const Value*, Value*> ValueMap;
890 Module *ToNotCodeGen = CloneModule(getProgram(), ValueMap);
891 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, ValueMap);
Chris Lattnera57d86b2004-04-05 22:58:16 +0000892
893 // Condition the modules
894 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
895
Reid Spencer97182982004-12-15 01:53:08 +0000896 sys::Path TestModuleBC("bugpoint.test.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000897 std::string ErrMsg;
898 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000899 errs() << getToolName() << "Error making unique filename: "
900 << ErrMsg << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +0000901 exit(1);
902 }
Reid Spencer97182982004-12-15 01:53:08 +0000903
Chris Lattner74382b72009-08-23 22:45:37 +0000904 if (writeProgramToFile(TestModuleBC.str(), ToCodeGen)) {
905 errs() << "Error writing bitcode to `" << TestModuleBC.str()
906 << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000907 exit(1);
908 }
909 delete ToCodeGen;
910
911 // Make the shared library
Reid Spencer97182982004-12-15 01:53:08 +0000912 sys::Path SafeModuleBC("bugpoint.safe.bc");
Reid Spencer51c5a282006-08-23 20:34:57 +0000913 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
Dan Gohman65f57c22009-07-15 16:35:29 +0000914 errs() << getToolName() << "Error making unique filename: "
915 << ErrMsg << "\n";
Reid Spencer51c5a282006-08-23 20:34:57 +0000916 exit(1);
917 }
Reid Spencer97182982004-12-15 01:53:08 +0000918
Chris Lattner74382b72009-08-23 22:45:37 +0000919 if (writeProgramToFile(SafeModuleBC.str(), ToNotCodeGen)) {
920 errs() << "Error writing bitcode to `" << SafeModuleBC.str()
921 << "'\nExiting.";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000922 exit(1);
923 }
Chris Lattner74382b72009-08-23 22:45:37 +0000924 std::string SharedObject = compileSharedObject(SafeModuleBC.str());
Chris Lattnera57d86b2004-04-05 22:58:16 +0000925 delete ToNotCodeGen;
926
Dan Gohmanac95cc72009-07-16 15:30:09 +0000927 outs() << "You can reproduce the problem with the command line: \n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000928 if (isExecutingJIT()) {
Chris Lattner74382b72009-08-23 22:45:37 +0000929 outs() << " lli -load " << SharedObject << " " << TestModuleBC.str();
Chris Lattnera57d86b2004-04-05 22:58:16 +0000930 } else {
Chris Lattner74382b72009-08-23 22:45:37 +0000931 outs() << " llc -f " << TestModuleBC.str() << " -o " << TestModuleBC.str()
932 << ".s\n";
933 outs() << " gcc " << SharedObject << " " << TestModuleBC.str()
934 << ".s -o " << TestModuleBC.str() << ".exe";
Chris Lattner59615f02005-01-15 00:07:19 +0000935#if defined (HAVE_LINK_R)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000936 outs() << " -Wl,-R.";
Chris Lattner59615f02005-01-15 00:07:19 +0000937#endif
Dan Gohmanac95cc72009-07-16 15:30:09 +0000938 outs() << "\n";
Chris Lattner74382b72009-08-23 22:45:37 +0000939 outs() << " " << TestModuleBC.str() << ".exe";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000940 }
941 for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
Dan Gohmanac95cc72009-07-16 15:30:09 +0000942 outs() << " " << InputArgv[i];
943 outs() << '\n';
944 outs() << "The shared object was created with:\n llc -march=c "
Chris Lattner74382b72009-08-23 22:45:37 +0000945 << SafeModuleBC.str() << " -o temporary.c\n"
Daniel Dunbarca740962009-08-18 03:35:57 +0000946 << " gcc -xc temporary.c -O2 -o " << SharedObject;
947 if (TargetTriple.getArch() == Triple::sparc)
948 outs() << " -G"; // Compile a shared library, `-G' for Sparc
949 else
950 outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
951
952 outs() << " -fno-strict-aliasing\n";
Chris Lattnera57d86b2004-04-05 22:58:16 +0000953
954 return false;
955}