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