4c957ac480e9583bf6da4ca87a6304d997d67de2
[oota-llvm.git] / tools / bugpoint / Miscompilation.cpp
1 //===- Miscompilation.cpp - Debug program miscompilations -----------------===//
2 // 
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 //===----------------------------------------------------------------------===//
9 //
10 // This file implements optimizer and code generation miscompilation debugging
11 // support.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "BugDriver.h"
16 #include "ListReducer.h"
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Analysis/Verifier.h"
23 #include "llvm/Support/Mangler.h"
24 #include "llvm/Transforms/Utils/Cloning.h"
25 #include "llvm/Transforms/Utils/Linker.h"
26 #include "Support/CommandLine.h"
27 #include "Support/FileUtilities.h"
28 using namespace llvm;
29
30 namespace llvm {
31   extern cl::list<std::string> InputArgv;
32   cl::opt<bool>
33   EnableBlockExtraction("enable-block-extraction",
34                         cl::desc("Enable basic block extraction for "
35                                  "miscompilation debugging (experimental)"));
36 }
37
38 namespace {
39   class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
40     BugDriver &BD;
41   public:
42     ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
43     
44     virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
45                               std::vector<const PassInfo*> &Suffix);
46   };
47 }
48
49 /// TestResult - After passes have been split into a test group and a control
50 /// group, see if they still break the program.
51 ///
52 ReduceMiscompilingPasses::TestResult
53 ReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
54                                  std::vector<const PassInfo*> &Suffix) {
55   // First, run the program with just the Suffix passes.  If it is still broken
56   // with JUST the kept passes, discard the prefix passes.
57   std::cout << "Checking to see if '" << getPassesString(Suffix)
58             << "' compile correctly: ";
59
60   std::string BytecodeResult;
61   if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
62     std::cerr << " Error running this sequence of passes" 
63               << " on the input program!\n";
64     BD.setPassesToRun(Suffix);
65     BD.EmitProgressBytecode("pass-error",  false);
66     exit(BD.debugOptimizerCrash());
67   }
68
69   // Check to see if the finished program matches the reference output...
70   if (BD.diffProgram(BytecodeResult, "", true /*delete bytecode*/)) {
71     std::cout << " nope.\n";
72     return KeepSuffix;         // Miscompilation detected!
73   }
74   std::cout << " yup.\n";      // No miscompilation!
75
76   if (Prefix.empty()) return NoFailure;
77
78   // Next, see if the program is broken if we run the "prefix" passes first,
79   // then separately run the "kept" passes.
80   std::cout << "Checking to see if '" << getPassesString(Prefix)
81             << "' compile correctly: ";
82
83   // If it is not broken with the kept passes, it's possible that the prefix
84   // passes must be run before the kept passes to break it.  If the program
85   // WORKS after the prefix passes, but then fails if running the prefix AND
86   // kept passes, we can update our bytecode file to include the result of the
87   // prefix passes, then discard the prefix passes.
88   //
89   if (BD.runPasses(Prefix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
90     std::cerr << " Error running this sequence of passes" 
91               << " on the input program!\n";
92     BD.setPassesToRun(Prefix);
93     BD.EmitProgressBytecode("pass-error",  false);
94     exit(BD.debugOptimizerCrash());
95   }
96
97   // If the prefix maintains the predicate by itself, only keep the prefix!
98   if (BD.diffProgram(BytecodeResult)) {
99     std::cout << " nope.\n";
100     removeFile(BytecodeResult);
101     return KeepPrefix;
102   }
103   std::cout << " yup.\n";      // No miscompilation!
104
105   // Ok, so now we know that the prefix passes work, try running the suffix
106   // passes on the result of the prefix passes.
107   //
108   Module *PrefixOutput = ParseInputFile(BytecodeResult);
109   if (PrefixOutput == 0) {
110     std::cerr << BD.getToolName() << ": Error reading bytecode file '"
111               << BytecodeResult << "'!\n";
112     exit(1);
113   }
114   removeFile(BytecodeResult);  // No longer need the file on disk
115
116   // Don't check if there are no passes in the suffix.
117   if (Suffix.empty())
118     return NoFailure;
119   
120   std::cout << "Checking to see if '" << getPassesString(Suffix)
121             << "' passes compile correctly after the '"
122             << getPassesString(Prefix) << "' passes: ";
123
124   Module *OriginalInput = BD.swapProgramIn(PrefixOutput);
125   if (BD.runPasses(Suffix, BytecodeResult, false/*delete*/, true/*quiet*/)) {
126     std::cerr << " Error running this sequence of passes" 
127               << " on the input program!\n";
128     BD.setPassesToRun(Suffix);
129     BD.EmitProgressBytecode("pass-error",  false);
130     exit(BD.debugOptimizerCrash());
131   }
132
133   // Run the result...
134   if (BD.diffProgram(BytecodeResult, "", true/*delete bytecode*/)) {
135     std::cout << " nope.\n";
136     delete OriginalInput;     // We pruned down the original input...
137     return KeepSuffix;
138   }
139
140   // Otherwise, we must not be running the bad pass anymore.
141   std::cout << " yup.\n";      // No miscompilation!
142   delete BD.swapProgramIn(OriginalInput); // Restore orig program & free test
143   return NoFailure;
144 }
145
146 namespace {
147   class ReduceMiscompilingFunctions : public ListReducer<Function*> {
148     BugDriver &BD;
149     bool (*TestFn)(BugDriver &, Module *, Module *);
150   public:
151     ReduceMiscompilingFunctions(BugDriver &bd,
152                                 bool (*F)(BugDriver &, Module *, Module *))
153       : BD(bd), TestFn(F) {}
154     
155     virtual TestResult doTest(std::vector<Function*> &Prefix,
156                               std::vector<Function*> &Suffix) {
157       if (!Suffix.empty() && TestFuncs(Suffix))
158         return KeepSuffix;
159       if (!Prefix.empty() && TestFuncs(Prefix))
160         return KeepPrefix;
161       return NoFailure;
162     }
163     
164     bool TestFuncs(const std::vector<Function*> &Prefix);
165   };
166 }
167
168 /// TestMergedProgram - Given two modules, link them together and run the
169 /// program, checking to see if the program matches the diff.  If the diff
170 /// matches, return false, otherwise return true.  If the DeleteInputs argument
171 /// is set to true then this function deletes both input modules before it
172 /// returns.
173 ///
174 static bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
175                               bool DeleteInputs) {
176   // Link the two portions of the program back to together.
177   std::string ErrorMsg;
178   if (!DeleteInputs) M1 = CloneModule(M1);
179   if (LinkModules(M1, M2, &ErrorMsg)) {
180     std::cerr << BD.getToolName() << ": Error linking modules together:"
181               << ErrorMsg << "\n";
182     exit(1);
183   }
184   if (DeleteInputs) delete M2;  // We are done with this module...
185
186   Module *OldProgram = BD.swapProgramIn(M1);
187
188   // Execute the program.  If it does not match the expected output, we must
189   // return true.
190   bool Broken = BD.diffProgram();
191
192   // Delete the linked module & restore the original
193   BD.swapProgramIn(OldProgram);
194   delete M1;
195   return Broken;
196 }
197
198 /// TestFuncs - split functions in a Module into two groups: those that are
199 /// under consideration for miscompilation vs. those that are not, and test
200 /// accordingly. Each group of functions becomes a separate Module.
201 ///
202 bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*>&Funcs){
203   // Test to see if the function is misoptimized if we ONLY run it on the
204   // functions listed in Funcs.
205   std::cout << "Checking to see if the program is misoptimized when "
206             << (Funcs.size()==1 ? "this function is" : "these functions are")
207             << " run through the pass"
208             << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
209   PrintFunctionList(Funcs);
210   std::cout << "\n";
211
212   // Split the module into the two halves of the program we want.
213   Module *ToNotOptimize = CloneModule(BD.getProgram());
214   Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, Funcs);
215
216   // Run the predicate, not that the predicate will delete both input modules.
217   return TestFn(BD, ToOptimize, ToNotOptimize);
218 }
219
220 /// DisambiguateGlobalSymbols - Mangle symbols to guarantee uniqueness by
221 /// modifying predominantly internal symbols rather than external ones.
222 ///
223 static void DisambiguateGlobalSymbols(Module *M) {
224   // Try not to cause collisions by minimizing chances of renaming an
225   // already-external symbol, so take in external globals and functions as-is.
226   // The code should work correctly without disambiguation (assuming the same
227   // mangler is used by the two code generators), but having symbols with the
228   // same name causes warnings to be emitted by the code generator.
229   Mangler Mang(*M);
230   for (Module::giterator I = M->gbegin(), E = M->gend(); I != E; ++I)
231     I->setName(Mang.getValueName(I));
232   for (Module::iterator  I = M->begin(),  E = M->end();  I != E; ++I)
233     I->setName(Mang.getValueName(I));
234 }
235
236 /// ExtractLoops - Given a reduced list of functions that still exposed the bug,
237 /// check to see if we can extract the loops in the region without obscuring the
238 /// bug.  If so, it reduces the amount of code identified.
239 ///
240 static bool ExtractLoops(BugDriver &BD,
241                          bool (*TestFn)(BugDriver &, Module *, Module *),
242                          std::vector<Function*> &MiscompiledFunctions) {
243   bool MadeChange = false;
244   while (1) {
245     Module *ToNotOptimize = CloneModule(BD.getProgram());
246     Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
247                                                    MiscompiledFunctions);
248     Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
249     if (!ToOptimizeLoopExtracted) {
250       // If the loop extractor crashed or if there were no extractible loops,
251       // then this chapter of our odyssey is over with.
252       delete ToNotOptimize;
253       delete ToOptimize;
254       return MadeChange;
255     }
256
257     std::cerr << "Extracted a loop from the breaking portion of the program.\n";
258     delete ToOptimize;
259
260     // Bugpoint is intentionally not very trusting of LLVM transformations.  In
261     // particular, we're not going to assume that the loop extractor works, so
262     // we're going to test the newly loop extracted program to make sure nothing
263     // has broken.  If something broke, then we'll inform the user and stop
264     // extraction.
265     AbstractInterpreter *AI = BD.switchToCBE();
266     if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
267       BD.switchToInterpreter(AI);
268
269       // Merged program doesn't work anymore!
270       std::cerr << "  *** ERROR: Loop extraction broke the program. :("
271                 << " Please report a bug!\n";
272       std::cerr << "      Continuing on with un-loop-extracted version.\n";
273       delete ToNotOptimize;
274       delete ToOptimizeLoopExtracted;
275       return MadeChange;
276     }
277     BD.switchToInterpreter(AI);
278     
279     std::cout << "  Testing after loop extraction:\n";
280     // Clone modules, the tester function will free them.
281     Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
282     Module *TNOBackup  = CloneModule(ToNotOptimize);
283     if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
284       std::cout << "*** Loop extraction masked the problem.  Undoing.\n";
285       // If the program is not still broken, then loop extraction did something
286       // that masked the error.  Stop loop extraction now.
287       delete TOLEBackup;
288       delete TNOBackup;
289       return MadeChange;
290     }
291     ToOptimizeLoopExtracted = TOLEBackup;
292     ToNotOptimize = TNOBackup;
293
294     std::cout << "*** Loop extraction successful!\n";
295
296     // Okay, great!  Now we know that we extracted a loop and that loop
297     // extraction both didn't break the program, and didn't mask the problem.
298     // Replace the current program with the loop extracted version, and try to
299     // extract another loop.
300     std::string ErrorMsg;
301     if (LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)) {
302       std::cerr << BD.getToolName() << ": Error linking modules together:"
303                 << ErrorMsg << "\n";
304       exit(1);
305     }
306
307     // All of the Function*'s in the MiscompiledFunctions list are in the old
308     // module.  Update this list to include all of the functions in the
309     // optimized and loop extracted module.
310     MiscompiledFunctions.clear();
311     for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
312            E = ToOptimizeLoopExtracted->end(); I != E; ++I) {
313       if (!I->isExternal()) {
314         Function *NewF = ToNotOptimize->getFunction(I->getName(),
315                                                     I->getFunctionType());
316         assert(NewF && "Function not found??");
317         MiscompiledFunctions.push_back(NewF);
318       }
319     }
320     delete ToOptimizeLoopExtracted;
321
322     BD.setNewProgram(ToNotOptimize);
323     MadeChange = true;
324   }
325 }
326
327 namespace {
328   class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
329     BugDriver &BD;
330     bool (*TestFn)(BugDriver &, Module *, Module *);
331     std::vector<Function*> FunctionsBeingTested;
332   public:
333     ReduceMiscompiledBlocks(BugDriver &bd,
334                             bool (*F)(BugDriver &, Module *, Module *),
335                             const std::vector<Function*> &Fns)
336       : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
337     
338     virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
339                               std::vector<BasicBlock*> &Suffix) {
340       if (!Suffix.empty() && TestFuncs(Suffix))
341         return KeepSuffix;
342       if (TestFuncs(Prefix))
343         return KeepPrefix;
344       return NoFailure;
345     }
346     
347     bool TestFuncs(const std::vector<BasicBlock*> &Prefix);
348   };
349 }
350
351 /// TestFuncs - Extract all blocks for the miscompiled functions except for the
352 /// specified blocks.  If the problem still exists, return true.
353 ///
354 bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) {
355   // Test to see if the function is misoptimized if we ONLY run it on the
356   // functions listed in Funcs.
357   std::cout << "Checking to see if the program is misoptimized when all but "
358             << "these " << BBs.size() << " blocks are extracted: ";
359   for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
360     std::cout << BBs[i]->getName() << " ";
361   if (BBs.size() > 10) std::cout << "...";
362   std::cout << "\n";
363
364   // Split the module into the two halves of the program we want.
365   Module *ToNotOptimize = CloneModule(BD.getProgram());
366   Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
367                                                  FunctionsBeingTested);
368
369   // Try the extraction.  If it doesn't work, then the block extractor crashed
370   // or something, in which case bugpoint can't chase down this possibility.
371   if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) {
372     delete ToOptimize;
373     // Run the predicate, not that the predicate will delete both input modules.
374     return TestFn(BD, New, ToNotOptimize);
375   }
376   delete ToOptimize;
377   delete ToNotOptimize;
378   return false;
379 }
380
381
382 /// ExtractBlocks - Given a reduced list of functions that still expose the bug,
383 /// extract as many basic blocks from the region as possible without obscuring
384 /// the bug.
385 ///
386 static bool ExtractBlocks(BugDriver &BD,
387                           bool (*TestFn)(BugDriver &, Module *, Module *),
388                           std::vector<Function*> &MiscompiledFunctions) {
389   // Not enabled??
390   if (!EnableBlockExtraction) return false;
391
392   std::vector<BasicBlock*> Blocks;
393   for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
394     for (Function::iterator I = MiscompiledFunctions[i]->begin(),
395            E = MiscompiledFunctions[i]->end(); I != E; ++I)
396       Blocks.push_back(I);
397
398   // Use the list reducer to identify blocks that can be extracted without
399   // obscuring the bug.  The Blocks list will end up containing blocks that must
400   // be retained from the original program.
401   unsigned OldSize = Blocks.size();
402   ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions).reduceList(Blocks);
403   if (Blocks.size() == OldSize)
404     return false;
405
406   Module *ProgClone = CloneModule(BD.getProgram());
407   Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
408                                                 MiscompiledFunctions);
409   Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
410   if (Extracted == 0) {
411     // Wierd, extraction should have worked.
412     std::cerr << "Nondeterministic problem extracting blocks??\n";
413     delete ProgClone;
414     delete ToExtract;
415     return false;
416   }
417
418   // Otherwise, block extraction succeeded.  Link the two program fragments back
419   // together.
420   delete ToExtract;
421
422   std::string ErrorMsg;
423   if (LinkModules(ProgClone, Extracted, &ErrorMsg)) {
424     std::cerr << BD.getToolName() << ": Error linking modules together:"
425               << ErrorMsg << "\n";
426     exit(1);
427   }
428
429   // Set the new program and delete the old one.
430   BD.setNewProgram(ProgClone);
431
432   // Update the list of miscompiled functions.
433   MiscompiledFunctions.clear();
434
435   for (Module::iterator I = Extracted->begin(), E = Extracted->end(); I != E;
436        ++I)
437     if (!I->isExternal()) {
438       Function *NF = ProgClone->getFunction(I->getName(), I->getFunctionType());
439       assert(NF && "Mapped function not found!");
440       MiscompiledFunctions.push_back(NF);
441     }
442
443   delete Extracted;
444
445   return true;
446 }
447
448
449 /// DebugAMiscompilation - This is a generic driver to narrow down
450 /// miscompilations, either in an optimization or a code generator.
451 ///
452 static std::vector<Function*>
453 DebugAMiscompilation(BugDriver &BD,
454                      bool (*TestFn)(BugDriver &, Module *, Module *)) {
455   // Okay, now that we have reduced the list of passes which are causing the
456   // failure, see if we can pin down which functions are being
457   // miscompiled... first build a list of all of the non-external functions in
458   // the program.
459   std::vector<Function*> MiscompiledFunctions;
460   Module *Prog = BD.getProgram();
461   for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
462     if (!I->isExternal())
463       MiscompiledFunctions.push_back(I);
464
465   // Do the reduction...
466   ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
467
468   std::cout << "\n*** The following function"
469             << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
470             << " being miscompiled: ";
471   PrintFunctionList(MiscompiledFunctions);
472   std::cout << "\n";
473
474   // See if we can rip any loops out of the miscompiled functions and still
475   // trigger the problem.
476   if (ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
477     // Okay, we extracted some loops and the problem still appears.  See if we
478     // can eliminate some of the created functions from being candidates.
479
480     // Loop extraction can introduce functions with the same name (foo_code).
481     // Make sure to disambiguate the symbols so that when the program is split
482     // apart that we can link it back together again.
483     DisambiguateGlobalSymbols(BD.getProgram());
484
485     // Do the reduction...
486     ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
487     
488     std::cout << "\n*** The following function"
489               << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
490               << " being miscompiled: ";
491     PrintFunctionList(MiscompiledFunctions);
492     std::cout << "\n";
493   }
494
495   if (ExtractBlocks(BD, TestFn, MiscompiledFunctions)) {
496     // Okay, we extracted some blocks and the problem still appears.  See if we
497     // can eliminate some of the created functions from being candidates.
498
499     // Block extraction can introduce functions with the same name (foo_code).
500     // Make sure to disambiguate the symbols so that when the program is split
501     // apart that we can link it back together again.
502     DisambiguateGlobalSymbols(BD.getProgram());
503
504     // Do the reduction...
505     ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
506     
507     std::cout << "\n*** The following function"
508               << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
509               << " being miscompiled: ";
510     PrintFunctionList(MiscompiledFunctions);
511     std::cout << "\n";
512   }
513
514   return MiscompiledFunctions;
515 }
516
517 /// TestOptimizer - This is the predicate function used to check to see if the
518 /// "Test" portion of the program is misoptimized.  If so, return true.  In any
519 /// case, both module arguments are deleted.
520 ///
521 static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
522   // Run the optimization passes on ToOptimize, producing a transformed version
523   // of the functions being tested.
524   std::cout << "  Optimizing functions being tested: ";
525   Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
526                                      /*AutoDebugCrashes*/true);
527   std::cout << "done.\n";
528   delete Test;
529
530   std::cout << "  Checking to see if the merged program executes correctly: ";
531   bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
532   std::cout << (Broken ? " nope.\n" : " yup.\n");
533   return Broken;
534 }
535
536
537 /// debugMiscompilation - This method is used when the passes selected are not
538 /// crashing, but the generated output is semantically different from the
539 /// input.
540 ///
541 bool BugDriver::debugMiscompilation() {
542   // Make sure something was miscompiled...
543   if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
544     std::cerr << "*** Optimized program matches reference output!  No problem "
545               << "detected...\nbugpoint can't help you with your problem!\n";
546     return false;
547   }
548
549   std::cout << "\n*** Found miscompiling pass"
550             << (getPassesToRun().size() == 1 ? "" : "es") << ": "
551             << getPassesString(getPassesToRun()) << "\n";
552   EmitProgressBytecode("passinput");
553
554   std::vector<Function*> MiscompiledFunctions =
555     DebugAMiscompilation(*this, TestOptimizer);
556
557   // Output a bunch of bytecode files for the user...
558   std::cout << "Outputting reduced bytecode files which expose the problem:\n";
559   Module *ToNotOptimize = CloneModule(getProgram());
560   Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
561                                                  MiscompiledFunctions);
562
563   std::cout << "  Non-optimized portion: ";
564   ToNotOptimize = swapProgramIn(ToNotOptimize);
565   EmitProgressBytecode("tonotoptimize", true);
566   setNewProgram(ToNotOptimize);   // Delete hacked module.
567   
568   std::cout << "  Portion that is input to optimizer: ";
569   ToOptimize = swapProgramIn(ToOptimize);
570   EmitProgressBytecode("tooptimize");
571   setNewProgram(ToOptimize);      // Delete hacked module.
572
573   return false;
574 }
575
576 /// CleanupAndPrepareModules - Get the specified modules ready for code
577 /// generator testing.
578 ///
579 static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
580                                      Module *Safe) {
581   // Clean up the modules, removing extra cruft that we don't need anymore...
582   Test = BD.performFinalCleanups(Test);
583
584   // If we are executing the JIT, we have several nasty issues to take care of.
585   if (!BD.isExecutingJIT()) return;
586
587   // First, if the main function is in the Safe module, we must add a stub to
588   // the Test module to call into it.  Thus, we create a new function `main'
589   // which just calls the old one.
590   if (Function *oldMain = Safe->getNamedFunction("main"))
591     if (!oldMain->isExternal()) {
592       // Rename it
593       oldMain->setName("llvm_bugpoint_old_main");
594       // Create a NEW `main' function with same type in the test module.
595       Function *newMain = new Function(oldMain->getFunctionType(), 
596                                        GlobalValue::ExternalLinkage,
597                                        "main", Test);
598       // Create an `oldmain' prototype in the test module, which will
599       // corresponds to the real main function in the same module.
600       Function *oldMainProto = new Function(oldMain->getFunctionType(), 
601                                             GlobalValue::ExternalLinkage,
602                                             oldMain->getName(), Test);
603       // Set up and remember the argument list for the main function.
604       std::vector<Value*> args;
605       for (Function::aiterator I = newMain->abegin(), E = newMain->aend(),
606              OI = oldMain->abegin(); I != E; ++I, ++OI) {
607         I->setName(OI->getName());    // Copy argument names from oldMain
608         args.push_back(I);
609       }
610
611       // Call the old main function and return its result
612       BasicBlock *BB = new BasicBlock("entry", newMain);
613       CallInst *call = new CallInst(oldMainProto, args);
614       BB->getInstList().push_back(call);
615     
616       // If the type of old function wasn't void, return value of call
617       new ReturnInst(oldMain->getReturnType() != Type::VoidTy ? call : 0, BB);
618     }
619
620   // The second nasty issue we must deal with in the JIT is that the Safe
621   // module cannot directly reference any functions defined in the test
622   // module.  Instead, we use a JIT API call to dynamically resolve the
623   // symbol.
624     
625   // Add the resolver to the Safe module.
626   // Prototype: void *getPointerToNamedFunction(const char* Name)
627   Function *resolverFunc = 
628     Safe->getOrInsertFunction("getPointerToNamedFunction",
629                               PointerType::get(Type::SByteTy),
630                               PointerType::get(Type::SByteTy), 0);
631     
632   // Use the function we just added to get addresses of functions we need.
633   for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
634     if (F->isExternal() && !F->use_empty() && &*F != resolverFunc &&
635         F->getIntrinsicID() == 0 /* ignore intrinsics */) {
636       Function *TestFn = Test->getFunction(F->getName(), F->getFunctionType());
637
638       // Don't forward functions which are external in the test module too.
639       if (TestFn && !TestFn->isExternal()) {
640         // 1. Add a string constant with its name to the global file
641         Constant *InitArray = ConstantArray::get(F->getName());
642         GlobalVariable *funcName =
643           new GlobalVariable(InitArray->getType(), true /*isConstant*/,
644                              GlobalValue::InternalLinkage, InitArray,    
645                              F->getName() + "_name", Safe);
646
647         // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
648         // sbyte* so it matches the signature of the resolver function.
649
650         // GetElementPtr *funcName, ulong 0, ulong 0
651         std::vector<Constant*> GEPargs(2,Constant::getNullValue(Type::IntTy));
652         Value *GEP =
653           ConstantExpr::getGetElementPtr(ConstantPointerRef::get(funcName),
654                                          GEPargs);
655         std::vector<Value*> ResolverArgs;
656         ResolverArgs.push_back(GEP);
657
658         // Rewrite uses of F in global initializers, etc. to uses of a wrapper
659         // function that dynamically resolves the calls to F via our JIT API
660         if (F->use_begin() != F->use_end()) {
661           // Construct a new stub function that will re-route calls to F
662           const FunctionType *FuncTy = F->getFunctionType();
663           Function *FuncWrapper = new Function(FuncTy,
664                                                GlobalValue::InternalLinkage,
665                                                F->getName() + "_wrapper",
666                                                F->getParent());
667           BasicBlock *Header = new BasicBlock("header", FuncWrapper);
668
669           // Resolve the call to function F via the JIT API:
670           //
671           // call resolver(GetElementPtr...)
672           CallInst *resolve = new CallInst(resolverFunc, ResolverArgs, 
673                                            "resolver");
674           Header->getInstList().push_back(resolve);
675           // cast the result from the resolver to correctly-typed function
676           CastInst *castResolver =
677             new CastInst(resolve, PointerType::get(F->getFunctionType()),
678                          "resolverCast");
679           Header->getInstList().push_back(castResolver);
680
681           // Save the argument list
682           std::vector<Value*> Args;
683           for (Function::aiterator i = FuncWrapper->abegin(),
684                  e = FuncWrapper->aend(); i != e; ++i)
685             Args.push_back(i);
686
687           // Pass on the arguments to the real function, return its result
688           if (F->getReturnType() == Type::VoidTy) {
689             CallInst *Call = new CallInst(castResolver, Args);
690             Header->getInstList().push_back(Call);
691             ReturnInst *Ret = new ReturnInst();
692             Header->getInstList().push_back(Ret);
693           } else {
694             CallInst *Call = new CallInst(castResolver, Args, "redir");
695             Header->getInstList().push_back(Call);
696             ReturnInst *Ret = new ReturnInst(Call);
697             Header->getInstList().push_back(Ret);
698           }
699
700           // Use the wrapper function instead of the old function
701           F->replaceAllUsesWith(FuncWrapper);
702         }
703       }
704     }
705   }
706
707   if (verifyModule(*Test) || verifyModule(*Safe)) {
708     std::cerr << "Bugpoint has a bug, which corrupted a module!!\n";
709     abort();
710   }
711 }
712
713
714
715 /// TestCodeGenerator - This is the predicate function used to check to see if
716 /// the "Test" portion of the program is miscompiled by the code generator under
717 /// test.  If so, return true.  In any case, both module arguments are deleted.
718 ///
719 static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
720   CleanupAndPrepareModules(BD, Test, Safe);
721
722   std::string TestModuleBC = getUniqueFilename("bugpoint.test.bc");
723   if (BD.writeProgramToFile(TestModuleBC, Test)) {
724     std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
725     exit(1);
726   }
727   delete Test;
728
729   // Make the shared library
730   std::string SafeModuleBC = getUniqueFilename("bugpoint.safe.bc");
731
732   if (BD.writeProgramToFile(SafeModuleBC, Safe)) {
733     std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
734     exit(1);
735   }
736   std::string SharedObject = BD.compileSharedObject(SafeModuleBC);
737   delete Safe;
738
739   // Run the code generator on the `Test' code, loading the shared library.
740   // The function returns whether or not the new output differs from reference.
741   int Result = BD.diffProgram(TestModuleBC, SharedObject, false);
742
743   if (Result)
744     std::cerr << ": still failing!\n";
745   else
746     std::cerr << ": didn't fail.\n";
747   removeFile(TestModuleBC);
748   removeFile(SafeModuleBC);
749   removeFile(SharedObject);
750
751   return Result;
752 }
753
754
755 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
756 ///
757 bool BugDriver::debugCodeGenerator() {
758   if ((void*)cbe == (void*)Interpreter) {
759     std::string Result = executeProgramWithCBE("bugpoint.cbe.out");
760     std::cout << "\n*** The C backend cannot match the reference diff, but it "
761               << "is used as the 'known good'\n    code generator, so I can't"
762               << " debug it.  Perhaps you have a front-end problem?\n    As a"
763               << " sanity check, I left the result of executing the program "
764               << "with the C backend\n    in this file for you: '"
765               << Result << "'.\n";
766     return true;
767   }
768
769   DisambiguateGlobalSymbols(Program);
770
771   std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
772
773   // Split the module into the two halves of the program we want.
774   Module *ToNotCodeGen = CloneModule(getProgram());
775   Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs);
776
777   // Condition the modules
778   CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
779
780   std::string TestModuleBC = getUniqueFilename("bugpoint.test.bc");
781   if (writeProgramToFile(TestModuleBC, ToCodeGen)) {
782     std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
783     exit(1);
784   }
785   delete ToCodeGen;
786
787   // Make the shared library
788   std::string SafeModuleBC = getUniqueFilename("bugpoint.safe.bc");
789   if (writeProgramToFile(SafeModuleBC, ToNotCodeGen)) {
790     std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
791     exit(1);
792   }
793   std::string SharedObject = compileSharedObject(SafeModuleBC);
794   delete ToNotCodeGen;
795
796   std::cout << "You can reproduce the problem with the command line: \n";
797   if (isExecutingJIT()) {
798     std::cout << "  lli -load " << SharedObject << " " << TestModuleBC;
799   } else {
800     std::cout << "  llc " << TestModuleBC << " -o " << TestModuleBC << ".s\n";
801     std::cout << "  gcc " << SharedObject << " " << TestModuleBC
802               << ".s -o " << TestModuleBC << ".exe -Wl,-R.\n";
803     std::cout << "  " << TestModuleBC << ".exe";
804   }
805   for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
806     std::cout << " " << InputArgv[i];
807   std::cout << "\n";
808   std::cout << "The shared object was created with:\n  llc -march=c "
809             << SafeModuleBC << " -o temporary.c\n"
810             << "  gcc -xc temporary.c -O2 -o " << SharedObject
811 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
812             << " -G"            // Compile a shared library, `-G' for Sparc
813 #else
814             << " -shared"       // `-shared' for Linux/X86, maybe others
815 #endif
816             << " -fno-strict-aliasing\n";
817
818   return false;
819 }