blob: fddbebddfe7274e103c7160c873683de45ca33cc [file] [log] [blame]
Chris Lattner4a106452002-12-23 23:50:16 +00001//===- Miscompilation.cpp - Debug program miscompilations -----------------===//
John Criswell7c0e0222003-10-20 17:47:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
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"
Chris Lattner4a106452002-12-23 23:50:16 +000020#include "llvm/Module.h"
Misha Brukmane49603d2003-08-07 21:19:30 +000021#include "llvm/Pass.h"
Chris Lattnera57d86b2004-04-05 22:58:16 +000022#include "llvm/Analysis/Verifier.h"
23#include "llvm/Support/Mangler.h"
Chris Lattner640f22e2003-04-24 17:02:17 +000024#include "llvm/Transforms/Utils/Cloning.h"
25#include "llvm/Transforms/Utils/Linker.h"
Chris Lattnera57d86b2004-04-05 22:58:16 +000026#include "Support/CommandLine.h"
Misha Brukman3d9cafa2003-08-07 21:42:28 +000027#include "Support/FileUtilities.h"
Chris Lattnerfa761832004-01-14 03:38:37 +000028using namespace llvm;
Chris Lattner4a106452002-12-23 23:50:16 +000029
Chris Lattnera57d86b2004-04-05 22:58:16 +000030namespace llvm {
31 extern cl::list<std::string> InputArgv;
32}
33
Chris Lattnerefdc0b52004-03-14 20:50:42 +000034namespace {
Chris Lattnerfa761832004-01-14 03:38:37 +000035 class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
36 BugDriver &BD;
37 public:
38 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
39
40 virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
41 std::vector<const PassInfo*> &Suffix);
42 };
43}
Chris Lattner640f22e2003-04-24 17:02:17 +000044
45ReduceMiscompilingPasses::TestResult
Chris Lattner39aebca2003-04-24 22:24:22 +000046ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
Chris Lattner06943ad2003-04-25 03:16:05 +000047 std::vector<const PassInfo*> &Suffix) {
48 // First, run the program with just the Suffix passes. If it is still broken
Chris Lattner640f22e2003-04-24 17:02:17 +000049 // with JUST the kept passes, discard the prefix passes.
Chris Lattner06943ad2003-04-25 03:16:05 +000050 std::cout << "Checking to see if '" << getPassesString(Suffix)
Chris Lattner640f22e2003-04-24 17:02:17 +000051 << "' compile correctly: ";
52
53 std::string BytecodeResult;
Chris Lattner06943ad2003-04-25 03:16:05 +000054 if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
Chris Lattner9f71e792003-10-18 00:05:05 +000055 std::cerr << " Error running this sequence of passes"
Chris Lattner640f22e2003-04-24 17:02:17 +000056 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +000057 BD.setPassesToRun(Suffix);
58 BD.EmitProgressBytecode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +000059 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +000060 }
61
62 // Check to see if the finished program matches the reference output...
Misha Brukman50733362003-07-24 18:17:43 +000063 if (BD.diffProgram(BytecodeResult, "", true /*delete bytecode*/)) {
Chris Lattner640f22e2003-04-24 17:02:17 +000064 std::cout << "nope.\n";
65 return KeepSuffix; // Miscompilation detected!
66 }
67 std::cout << "yup.\n"; // No miscompilation!
68
69 if (Prefix.empty()) return NoFailure;
70
Chris Lattner06943ad2003-04-25 03:16:05 +000071 // Next, see if the program is broken if we run the "prefix" passes first,
Misha Brukmanbc0e9982003-07-14 17:20:40 +000072 // then separately run the "kept" passes.
Chris Lattner640f22e2003-04-24 17:02:17 +000073 std::cout << "Checking to see if '" << getPassesString(Prefix)
74 << "' compile correctly: ";
75
76 // If it is not broken with the kept passes, it's possible that the prefix
77 // passes must be run before the kept passes to break it. If the program
78 // WORKS after the prefix passes, but then fails if running the prefix AND
79 // kept passes, we can update our bytecode file to include the result of the
80 // prefix passes, then discard the prefix passes.
81 //
82 if (BD.runPasses(Prefix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
Chris Lattner9f71e792003-10-18 00:05:05 +000083 std::cerr << " Error running this sequence of passes"
Chris Lattner640f22e2003-04-24 17:02:17 +000084 << " on the input program!\n";
Chris Lattner9c6cfe12003-10-17 23:03:16 +000085 BD.setPassesToRun(Prefix);
86 BD.EmitProgressBytecode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +000087 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +000088 }
89
90 // If the prefix maintains the predicate by itself, only keep the prefix!
Misha Brukman50733362003-07-24 18:17:43 +000091 if (BD.diffProgram(BytecodeResult)) {
Chris Lattner640f22e2003-04-24 17:02:17 +000092 std::cout << "nope.\n";
93 removeFile(BytecodeResult);
94 return KeepPrefix;
95 }
96 std::cout << "yup.\n"; // No miscompilation!
97
98 // Ok, so now we know that the prefix passes work, try running the suffix
99 // passes on the result of the prefix passes.
100 //
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000101 Module *PrefixOutput = ParseInputFile(BytecodeResult);
Chris Lattner640f22e2003-04-24 17:02:17 +0000102 if (PrefixOutput == 0) {
103 std::cerr << BD.getToolName() << ": Error reading bytecode file '"
104 << BytecodeResult << "'!\n";
105 exit(1);
106 }
107 removeFile(BytecodeResult); // No longer need the file on disk
108
Chris Lattner06943ad2003-04-25 03:16:05 +0000109 std::cout << "Checking to see if '" << getPassesString(Suffix)
Chris Lattner640f22e2003-04-24 17:02:17 +0000110 << "' passes compile correctly after the '"
111 << getPassesString(Prefix) << "' passes: ";
112
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000113 Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
Chris Lattner06943ad2003-04-25 03:16:05 +0000114 if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
Chris Lattner9f71e792003-10-18 00:05:05 +0000115 std::cerr << " Error running this sequence of passes"
Chris Lattner640f22e2003-04-24 17:02:17 +0000116 << " on the input program!\n";
Chris Lattner5ef681c2003-10-17 23:07:47 +0000117 BD.setPassesToRun(Suffix);
Chris Lattner9c6cfe12003-10-17 23:03:16 +0000118 BD.EmitProgressBytecode("pass-error", false);
Chris Lattner02526262004-02-18 21:02:04 +0000119 exit(BD.debugOptimizerCrash());
Chris Lattner640f22e2003-04-24 17:02:17 +0000120 }
121
122 // Run the result...
Misha Brukman50733362003-07-24 18:17:43 +0000123 if (BD.diffProgram(BytecodeResult, "", true/*delete bytecode*/)) {
Chris Lattner640f22e2003-04-24 17:02:17 +0000124 std::cout << "nope.\n";
125 delete OriginalInput; // We pruned down the original input...
Chris Lattner06943ad2003-04-25 03:16:05 +0000126 return KeepSuffix;
Chris Lattner640f22e2003-04-24 17:02:17 +0000127 }
128
129 // Otherwise, we must not be running the bad pass anymore.
130 std::cout << "yup.\n"; // No miscompilation!
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000131 delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test
Chris Lattner640f22e2003-04-24 17:02:17 +0000132 return NoFailure;
133}
134
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000135namespace {
Chris Lattnerfa761832004-01-14 03:38:37 +0000136 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
137 BugDriver &BD;
Chris Lattnerb15825b2004-04-05 21:37:38 +0000138 bool (*TestFn)(BugDriver &, Module *, Module *);
Chris Lattnerfa761832004-01-14 03:38:37 +0000139 public:
Chris Lattnerb15825b2004-04-05 21:37:38 +0000140 ReduceMiscompilingFunctions(BugDriver &bd,
141 bool (*F)(BugDriver &, Module *, Module *))
142 : BD(bd), TestFn(F) {}
Chris Lattnerfa761832004-01-14 03:38:37 +0000143
144 virtual TestResult doTest(std::vector<Function*> &Prefix,
145 std::vector<Function*> &Suffix) {
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000146 if (!Suffix.empty() && TestFuncs(Suffix))
Chris Lattnerfa761832004-01-14 03:38:37 +0000147 return KeepSuffix;
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000148 if (!Prefix.empty() && TestFuncs(Prefix))
Chris Lattnerfa761832004-01-14 03:38:37 +0000149 return KeepPrefix;
150 return NoFailure;
151 }
152
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000153 bool TestFuncs(const std::vector<Function*> &Prefix);
Chris Lattnerfa761832004-01-14 03:38:37 +0000154 };
155}
Chris Lattner640f22e2003-04-24 17:02:17 +0000156
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000157/// TestMergedProgram - Given two modules, link them together and run the
158/// program, checking to see if the program matches the diff. If the diff
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000159/// matches, return false, otherwise return true. If the DeleteInputs argument
160/// is set to true then this function deletes both input modules before it
161/// returns.
162static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
163 bool DeleteInputs) {
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000164 // Link the two portions of the program back to together.
165 std::string ErrorMsg;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000166 if (!DeleteInputs) M1 = CloneModule(M1);
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000167 if (LinkModules(M1, M2, &ErrorMsg)) {
168 std::cerr << BD.getToolName() << ": Error linking modules together:"
169 << ErrorMsg << "\n";
170 exit(1);
171 }
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000172 if (DeleteInputs) delete M2; // We are done with this module...
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000173
174 Module *OldProgram = BD.swapProgramIn(M1);
175
176 // Execute the program. If it does not match the expected output, we must
177 // return true.
178 bool Broken = BD.diffProgram();
179
180 // Delete the linked module & restore the original
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000181 BD.swapProgramIn(OldProgram);
Chris Lattner5313f232004-04-02 06:32:17 +0000182 delete M1;
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000183 return Broken;
184}
185
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000186bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
Chris Lattner640f22e2003-04-24 17:02:17 +0000187 // Test to see if the function is misoptimized if we ONLY run it on the
188 // functions listed in Funcs.
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000189 std::cout << "Checking to see if the program is misoptimized when "
190 << (Funcs.size()==1 ? "this function is" : "these functions are")
191 << " run through the pass"
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000192 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000193 PrintFunctionList(Funcs);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000194 std::cout << "\n";
Chris Lattner640f22e2003-04-24 17:02:17 +0000195
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000196 // Split the module into the two halves of the program we want.
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000197 Module *ToNotOptimize = CloneModule(BD.getProgram());
198 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, Funcs);
Chris Lattner640f22e2003-04-24 17:02:17 +0000199
Chris Lattnerb15825b2004-04-05 21:37:38 +0000200 // Run the predicate, not that the predicate will delete both input modules.
201 return TestFn(BD, ToOptimize, ToNotOptimize);
Chris Lattner640f22e2003-04-24 17:02:17 +0000202}
203
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000204/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
205/// check to see if we can extract the loops in the region without obscuring the
206/// bug. If so, it reduces the amount of code identified.
Chris Lattnerb15825b2004-04-05 21:37:38 +0000207static bool ExtractLoops(BugDriver &BD,
208 bool (*TestFn)(BugDriver &, Module *, Module *),
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000209 std::vector<Function*> &MiscompiledFunctions) {
210 bool MadeChange = false;
211 while (1) {
212 Module *ToNotOptimize = CloneModule(BD.getProgram());
213 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
214 MiscompiledFunctions);
215 Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
216 if (!ToOptimizeLoopExtracted) {
217 // If the loop extractor crashed or if there were no extractible loops,
218 // then this chapter of our odyssey is over with.
219 delete ToNotOptimize;
220 delete ToOptimize;
221 return MadeChange;
222 }
223
224 std::cerr << "Extracted a loop from the breaking portion of the program.\n";
225 delete ToOptimize;
226
227 // Bugpoint is intentionally not very trusting of LLVM transformations. In
228 // particular, we're not going to assume that the loop extractor works, so
229 // we're going to test the newly loop extracted program to make sure nothing
230 // has broken. If something broke, then we'll inform the user and stop
231 // extraction.
Chris Lattnera57d86b2004-04-05 22:58:16 +0000232 AbstractInterpreter *AI = BD.switchToCBE();
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000233 if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
Chris Lattnera57d86b2004-04-05 22:58:16 +0000234 BD.switchToInterpreter(AI);
235
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000236 // Merged program doesn't work anymore!
237 std::cerr << " *** ERROR: Loop extraction broke the program. :("
238 << " Please report a bug!\n";
239 std::cerr << " Continuing on with un-loop-extracted version.\n";
240 delete ToNotOptimize;
241 delete ToOptimizeLoopExtracted;
242 return MadeChange;
243 }
Chris Lattnera57d86b2004-04-05 22:58:16 +0000244 BD.switchToInterpreter(AI);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000245
Chris Lattnerb15825b2004-04-05 21:37:38 +0000246 std::cout << " Testing after loop extraction:\n";
247 // Clone modules, the tester function will free them.
248 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
249 Module *TNOBackup = CloneModule(ToNotOptimize);
250 if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
251 std::cout << "*** Loop extraction masked the problem. Undoing.\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000252 // If the program is not still broken, then loop extraction did something
253 // that masked the error. Stop loop extraction now.
Chris Lattnerb15825b2004-04-05 21:37:38 +0000254 delete TOLEBackup;
255 delete TNOBackup;
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000256 return MadeChange;
257 }
Chris Lattnerb15825b2004-04-05 21:37:38 +0000258 ToOptimizeLoopExtracted = TOLEBackup;
259 ToNotOptimize = TNOBackup;
260
261 std::cout << "*** Loop extraction successful!\n";
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000262
263 // Okay, great! Now we know that we extracted a loop and that loop
264 // extraction both didn't break the program, and didn't mask the problem.
265 // Replace the current program with the loop extracted version, and try to
266 // extract another loop.
267 std::string ErrorMsg;
268 if (LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)) {
269 std::cerr << BD.getToolName() << ": Error linking modules together:"
270 << ErrorMsg << "\n";
271 exit(1);
272 }
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000273
274 // All of the Function*'s in the MiscompiledFunctions list are in the old
Chris Lattner5313f232004-04-02 06:32:17 +0000275 // module. Update this list to include all of the functions in the
276 // optimized and loop extracted module.
277 MiscompiledFunctions.clear();
278 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
279 E = ToOptimizeLoopExtracted->end(); I != E; ++I) {
280 if (!I->isExternal()) {
Chris Lattner02bb4812004-04-02 06:32:45 +0000281 Function *NewF = ToNotOptimize->getFunction(I->getName(),
282 I->getFunctionType());
Chris Lattner5313f232004-04-02 06:32:17 +0000283 assert(NewF && "Function not found??");
284 MiscompiledFunctions.push_back(NewF);
285 }
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000286 }
Chris Lattner5313f232004-04-02 06:32:17 +0000287 delete ToOptimizeLoopExtracted;
Chris Lattnerd3a533d2004-03-17 17:42:09 +0000288
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000289 BD.setNewProgram(ToNotOptimize);
290 MadeChange = true;
291 }
292}
293
Chris Lattnerb15825b2004-04-05 21:37:38 +0000294/// DebugAMiscompilation - This is a generic driver to narrow down
295/// miscompilations, either in an optimization or a code generator.
296static std::vector<Function*>
297DebugAMiscompilation(BugDriver &BD,
298 bool (*TestFn)(BugDriver &, Module *, Module *)) {
299 // Okay, now that we have reduced the list of passes which are causing the
300 // failure, see if we can pin down which functions are being
301 // miscompiled... first build a list of all of the non-external functions in
302 // the program.
303 std::vector<Function*> MiscompiledFunctions;
304 Module *Prog = BD.getProgram();
305 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
306 if (!I->isExternal())
307 MiscompiledFunctions.push_back(I);
308
309 // Do the reduction...
310 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
311
312 std::cout << "\n*** The following function"
313 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
314 << " being miscompiled: ";
315 PrintFunctionList(MiscompiledFunctions);
316 std::cout << "\n";
317
318 // See if we can rip any loops out of the miscompiled functions and still
319 // trigger the problem.
320 if (ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
321 // Okay, we extracted some loops and the problem still appears. See if we
322 // can eliminate some of the created functions from being candidates.
323
324 // Do the reduction...
325 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
326
327 std::cout << "\n*** The following function"
328 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
329 << " being miscompiled: ";
330 PrintFunctionList(MiscompiledFunctions);
331 std::cout << "\n";
332 }
333
334 return MiscompiledFunctions;
335}
336
Chris Lattnera57d86b2004-04-05 22:58:16 +0000337/// TestOptimizer - This is the predicate function used to check to see if the
338/// "Test" portion of the program is misoptimized. If so, return true. In any
339/// case, both module arguments are deleted.
Chris Lattnerb15825b2004-04-05 21:37:38 +0000340static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
341 // Run the optimization passes on ToOptimize, producing a transformed version
342 // of the functions being tested.
343 std::cout << " Optimizing functions being tested: ";
344 Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
345 /*AutoDebugCrashes*/true);
346 std::cout << "done.\n";
347 delete Test;
348
349 std::cout << " Checking to see if the merged program executes correctly: ";
Chris Lattner2423db02004-04-09 22:28:33 +0000350 bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
Chris Lattnerb15825b2004-04-05 21:37:38 +0000351 std::cout << (Broken ? " nope.\n" : " yup.\n");
352 return Broken;
353}
354
355
Chris Lattner4a106452002-12-23 23:50:16 +0000356/// debugMiscompilation - This method is used when the passes selected are not
357/// crashing, but the generated output is semantically different from the
358/// input.
359///
360bool BugDriver::debugMiscompilation() {
Chris Lattner4a106452002-12-23 23:50:16 +0000361 // Make sure something was miscompiled...
Misha Brukmanbe6bf562003-07-30 20:15:56 +0000362 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
Chris Lattner4a106452002-12-23 23:50:16 +0000363 std::cerr << "*** Optimized program matches reference output! No problem "
364 << "detected...\nbugpoint can't help you with your problem!\n";
365 return false;
366 }
367
Chris Lattner640f22e2003-04-24 17:02:17 +0000368 std::cout << "\n*** Found miscompiling pass"
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000369 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
370 << getPassesString(getPassesToRun()) << "\n";
Chris Lattner640f22e2003-04-24 17:02:17 +0000371 EmitProgressBytecode("passinput");
Chris Lattner4a106452002-12-23 23:50:16 +0000372
Chris Lattnerb15825b2004-04-05 21:37:38 +0000373 std::vector<Function*> MiscompiledFunctions =
374 DebugAMiscompilation(*this, TestOptimizer);
Chris Lattnera1cf1c82004-03-14 22:08:00 +0000375
Chris Lattner640f22e2003-04-24 17:02:17 +0000376 // Output a bunch of bytecode files for the user...
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000377 std::cout << "Outputting reduced bytecode files which expose the problem:\n";
Chris Lattnerefdc0b52004-03-14 20:50:42 +0000378 Module *ToNotOptimize = CloneModule(getProgram());
379 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
380 MiscompiledFunctions);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000381
382 std::cout << " Non-optimized portion: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000383 ToNotOptimize = swapProgramIn(ToNotOptimize);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000384 EmitProgressBytecode("tonotoptimize", true);
385 setNewProgram(ToNotOptimize); // Delete hacked module.
386
387 std::cout << " Portion that is input to optimizer: ";
Chris Lattnerb15825b2004-04-05 21:37:38 +0000388 ToOptimize = swapProgramIn(ToOptimize);
Chris Lattnerbe21ca52004-03-14 19:27:19 +0000389 EmitProgressBytecode("tooptimize");
390 setNewProgram(ToOptimize); // Delete hacked module.
Chris Lattner4a106452002-12-23 23:50:16 +0000391
Chris Lattner4a106452002-12-23 23:50:16 +0000392 return false;
393}
Brian Gaeked0fde302003-11-11 22:41:34 +0000394
Chris Lattnera57d86b2004-04-05 22:58:16 +0000395/// CleanupAndPrepareModules - Get the specified modules ready for code
396/// generator testing.
397static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
398 Module *Safe) {
399 // Clean up the modules, removing extra cruft that we don't need anymore...
400 Test = BD.performFinalCleanups(Test);
401
402 // If we are executing the JIT, we have several nasty issues to take care of.
403 if (!BD.isExecutingJIT()) return;
404
405 // First, if the main function is in the Safe module, we must add a stub to
406 // the Test module to call into it. Thus, we create a new function `main'
407 // which just calls the old one.
408 if (Function *oldMain = Safe->getNamedFunction("main"))
409 if (!oldMain->isExternal()) {
410 // Rename it
411 oldMain->setName("llvm_bugpoint_old_main");
412 // Create a NEW `main' function with same type in the test module.
413 Function *newMain = new Function(oldMain->getFunctionType(),
414 GlobalValue::ExternalLinkage,
415 "main", Test);
416 // Create an `oldmain' prototype in the test module, which will
417 // corresponds to the real main function in the same module.
418 Function *oldMainProto = new Function(oldMain->getFunctionType(),
419 GlobalValue::ExternalLinkage,
420 oldMain->getName(), Test);
421 // Set up and remember the argument list for the main function.
422 std::vector<Value*> args;
423 for (Function::aiterator I = newMain->abegin(), E = newMain->aend(),
424 OI = oldMain->abegin(); I != E; ++I, ++OI) {
425 I->setName(OI->getName()); // Copy argument names from oldMain
426 args.push_back(I);
427 }
428
429 // Call the old main function and return its result
430 BasicBlock *BB = new BasicBlock("entry", newMain);
431 CallInst *call = new CallInst(oldMainProto, args);
432 BB->getInstList().push_back(call);
433
434 // If the type of old function wasn't void, return value of call
435 new ReturnInst(oldMain->getReturnType() != Type::VoidTy ? call : 0, BB);
436 }
437
438 // The second nasty issue we must deal with in the JIT is that the Safe
439 // module cannot directly reference any functions defined in the test
440 // module. Instead, we use a JIT API call to dynamically resolve the
441 // symbol.
442
443 // Add the resolver to the Safe module.
444 // Prototype: void *getPointerToNamedFunction(const char* Name)
445 Function *resolverFunc =
446 Safe->getOrInsertFunction("getPointerToNamedFunction",
447 PointerType::get(Type::SByteTy),
448 PointerType::get(Type::SByteTy), 0);
449
450 // Use the function we just added to get addresses of functions we need.
451 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F){
452 if (F->isExternal() && !F->use_empty() && &*F != resolverFunc &&
453 F->getIntrinsicID() == 0 /* ignore intrinsics */) {
454 Function *TestFn =Test->getFunction(F->getName(), F->getFunctionType());
455
456 // Don't forward functions which are external in the test module too.
457 if (TestFn && !TestFn->isExternal()) {
458 // 1. Add a string constant with its name to the global file
459 Constant *InitArray = ConstantArray::get(F->getName());
460 GlobalVariable *funcName =
461 new GlobalVariable(InitArray->getType(), true /*isConstant*/,
462 GlobalValue::InternalLinkage, InitArray,
463 F->getName() + "_name", Safe);
464
465 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
466 // sbyte* so it matches the signature of the resolver function.
467
468 // GetElementPtr *funcName, ulong 0, ulong 0
469 std::vector<Constant*> GEPargs(2,Constant::getNullValue(Type::IntTy));
470 Value *GEP =
471 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(funcName),
472 GEPargs);
473 std::vector<Value*> ResolverArgs;
474 ResolverArgs.push_back(GEP);
475
476 // 3. Replace all uses of `func' with calls to resolver by:
477 // (a) Iterating through the list of uses of this function
478 // (b) Insert a cast instruction in front of each use
479 // (c) Replace use of old call with new call
480
481 // Insert code at the beginning of the function
482 while (!F->use_empty())
483 if (Instruction *Inst = dyn_cast<Instruction>(F->use_back())) {
484 // call resolver(GetElementPtr...)
485 CallInst *resolve = new CallInst(resolverFunc, ResolverArgs,
486 "resolver", Inst);
487 // cast the result from the resolver to correctly-typed function
488 CastInst *castResolver =
489 new CastInst(resolve, PointerType::get(F->getFunctionType()),
490 "resolverCast", Inst);
491 // actually use the resolved function
492 Inst->replaceUsesOfWith(F, castResolver);
493 } else {
494 // FIXME: need to take care of cases where a function is used by
495 // something other than an instruction; e.g., global variable
496 // initializers and constant expressions.
497 std::cerr << "UNSUPPORTED: Non-instruction is using an external "
498 << "function, " << F->getName() << "().\n";
499 abort();
500 }
501 }
502 }
503 }
504
505 if (verifyModule(*Test) || verifyModule(*Safe)) {
506 std::cerr << "Bugpoint has a bug, which corrupted a module!!\n";
507 abort();
508 }
509}
510
511
512
513/// TestCodeGenerator - This is the predicate function used to check to see if
514/// the "Test" portion of the program is miscompiled by the code generator under
515/// test. If so, return true. In any case, both module arguments are deleted.
516static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
517 CleanupAndPrepareModules(BD, Test, Safe);
518
519 std::string TestModuleBC = getUniqueFilename("bugpoint.test.bc");
520 if (BD.writeProgramToFile(TestModuleBC, Test)) {
521 std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
522 exit(1);
523 }
524 delete Test;
525
526 // Make the shared library
527 std::string SafeModuleBC = getUniqueFilename("bugpoint.safe.bc");
528
529 if (BD.writeProgramToFile(SafeModuleBC, Safe)) {
530 std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
531 exit(1);
532 }
533 std::string SharedObject = BD.compileSharedObject(SafeModuleBC);
534 delete Safe;
535
536 // Run the code generator on the `Test' code, loading the shared library.
537 // The function returns whether or not the new output differs from reference.
538 int Result = BD.diffProgram(TestModuleBC, SharedObject, false);
539
540 if (Result)
541 std::cerr << ": still failing!\n";
542 else
543 std::cerr << ": didn't fail.\n";
544 removeFile(TestModuleBC);
545 removeFile(SafeModuleBC);
546 removeFile(SharedObject);
547
548 return Result;
549}
550
551
552
553static void DisambiguateGlobalSymbols(Module *M) {
554 // Try not to cause collisions by minimizing chances of renaming an
555 // already-external symbol, so take in external globals and functions as-is.
556 // The code should work correctly without disambiguation (assuming the same
557 // mangler is used by the two code generators), but having symbols with the
558 // same name causes warnings to be emitted by the code generator.
559 Mangler Mang(*M);
560 for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
561 I->setName(Mang.getValueName(I));
562 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
563 I->setName(Mang.getValueName(I));
564}
565
566
567
568bool BugDriver::debugCodeGenerator() {
569 if ((void*)cbe == (void*)Interpreter) {
570 std::string Result = executeProgramWithCBE("bugpoint.cbe.out");
571 std::cout << "\n*** The C backend cannot match the reference diff, but it "
572 << "is used as the 'known good'\n code generator, so I can't"
573 << " debug it. Perhaps you have a front-end problem?\n As a"
574 << " sanity check, I left the result of executing the program "
575 << "with the C backend\n in this file for you: '"
576 << Result << "'.\n";
577 return true;
578 }
579
580 DisambiguateGlobalSymbols(Program);
581
582 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
583
584 // Split the module into the two halves of the program we want.
585 Module *ToNotCodeGen = CloneModule(getProgram());
586 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs);
587
588 // Condition the modules
589 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
590
591 std::string TestModuleBC = getUniqueFilename("bugpoint.test.bc");
592 if (writeProgramToFile(TestModuleBC, ToCodeGen)) {
593 std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
594 exit(1);
595 }
596 delete ToCodeGen;
597
598 // Make the shared library
599 std::string SafeModuleBC = getUniqueFilename("bugpoint.safe.bc");
600 if (writeProgramToFile(SafeModuleBC, ToNotCodeGen)) {
601 std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
602 exit(1);
603 }
604 std::string SharedObject = compileSharedObject(SafeModuleBC);
605 delete ToNotCodeGen;
606
607 std::cout << "You can reproduce the problem with the command line: \n";
608 if (isExecutingJIT()) {
609 std::cout << " lli -load " << SharedObject << " " << TestModuleBC;
610 } else {
611 std::cout << " llc " << TestModuleBC << " -o " << TestModuleBC << ".s\n";
612 std::cout << " gcc " << SharedObject << " " << TestModuleBC
613 << ".s -o " << TestModuleBC << ".exe -Wl,-R.\n";
614 std::cout << " " << TestModuleBC << ".exe";
615 }
616 for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
617 std::cout << " " << InputArgv[i];
618 std::cout << "\n";
619 std::cout << "The shared object was created with:\n llc -march=c "
620 << SafeModuleBC << " -o temporary.c\n"
621 << " gcc -xc temporary.c -O2 -o " << SharedObject
622#if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
623 << " -G" // Compile a shared library, `-G' for Sparc
624#else
625 << " -shared" // `-shared' for Linux/X86, maybe others
626#endif
627 << " -fno-strict-aliasing\n";
628
629 return false;
630}