Move a few more APIs back to 2.5 forms. The only remaining ones left to change back are
[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("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(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::Int8Ty),
703                         PointerType::getUnqual(Type::Int8Ty), (Type *)0);
704
705   // Use the function we just added to get addresses of functions we need.
706   for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
707     if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
708         !F->isIntrinsic() /* ignore intrinsics */) {
709       Function *TestFn = Test->getFunction(F->getName());
710
711       // Don't forward functions which are external in the test module too.
712       if (TestFn && !TestFn->isDeclaration()) {
713         // 1. Add a string constant with its name to the global file
714         Constant *InitArray = ConstantArray::get(F->getName());
715         GlobalVariable *funcName =
716           new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
717                              GlobalValue::InternalLinkage, InitArray,
718                              F->getName() + "_name");
719
720         // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
721         // sbyte* so it matches the signature of the resolver function.
722
723         // GetElementPtr *funcName, ulong 0, ulong 0
724         std::vector<Constant*> GEPargs(2, Constant::getNullValue(Type::Int32Ty));
725         Value *GEP =
726                 ConstantExpr::getGetElementPtr(funcName, &GEPargs[0], 2);
727         std::vector<Value*> ResolverArgs;
728         ResolverArgs.push_back(GEP);
729
730         // Rewrite uses of F in global initializers, etc. to uses of a wrapper
731         // function that dynamically resolves the calls to F via our JIT API
732         if (!F->use_empty()) {
733           // Create a new global to hold the cached function pointer.
734           Constant *NullPtr = ConstantPointerNull::get(F->getType());
735           GlobalVariable *Cache =
736             new GlobalVariable(*F->getParent(), F->getType(), 
737                                false, GlobalValue::InternalLinkage,
738                                NullPtr,F->getName()+".fpcache");
739
740           // Construct a new stub function that will re-route calls to F
741           const FunctionType *FuncTy = F->getFunctionType();
742           Function *FuncWrapper = Function::Create(FuncTy,
743                                                    GlobalValue::InternalLinkage,
744                                                    F->getName() + "_wrapper",
745                                                    F->getParent());
746           BasicBlock *EntryBB  = BasicBlock::Create("entry", FuncWrapper);
747           BasicBlock *DoCallBB = BasicBlock::Create("usecache", FuncWrapper);
748           BasicBlock *LookupBB = BasicBlock::Create("lookupfp", FuncWrapper);
749
750           // Check to see if we already looked up the value.
751           Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
752           Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
753                                        NullPtr, "isNull");
754           BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
755
756           // Resolve the call to function F via the JIT API:
757           //
758           // call resolver(GetElementPtr...)
759           CallInst *Resolver =
760             CallInst::Create(resolverFunc, ResolverArgs.begin(),
761                              ResolverArgs.end(), "resolver", LookupBB);
762
763           // Cast the result from the resolver to correctly-typed function.
764           CastInst *CastedResolver =
765             new BitCastInst(Resolver,
766                             PointerType::getUnqual(F->getFunctionType()),
767                             "resolverCast", LookupBB);
768
769           // Save the value in our cache.
770           new StoreInst(CastedResolver, Cache, LookupBB);
771           BranchInst::Create(DoCallBB, LookupBB);
772
773           PHINode *FuncPtr = PHINode::Create(NullPtr->getType(),
774                                              "fp", DoCallBB);
775           FuncPtr->addIncoming(CastedResolver, LookupBB);
776           FuncPtr->addIncoming(CachedVal, EntryBB);
777
778           // Save the argument list.
779           std::vector<Value*> Args;
780           for (Function::arg_iterator i = FuncWrapper->arg_begin(),
781                  e = FuncWrapper->arg_end(); i != e; ++i)
782             Args.push_back(i);
783
784           // Pass on the arguments to the real function, return its result
785           if (F->getReturnType() == Type::VoidTy) {
786             CallInst::Create(FuncPtr, Args.begin(), Args.end(), "", DoCallBB);
787             ReturnInst::Create(DoCallBB);
788           } else {
789             CallInst *Call = CallInst::Create(FuncPtr, Args.begin(), Args.end(),
790                                               "retval", DoCallBB);
791             ReturnInst::Create(Call, DoCallBB);
792           }
793
794           // Use the wrapper function instead of the old function
795           F->replaceAllUsesWith(FuncWrapper);
796         }
797       }
798     }
799   }
800
801   if (verifyModule(*Test) || verifyModule(*Safe)) {
802     errs() << "Bugpoint has a bug, which corrupted a module!!\n";
803     abort();
804   }
805 }
806
807
808
809 /// TestCodeGenerator - This is the predicate function used to check to see if
810 /// the "Test" portion of the program is miscompiled by the code generator under
811 /// test.  If so, return true.  In any case, both module arguments are deleted.
812 ///
813 static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
814   CleanupAndPrepareModules(BD, Test, Safe);
815
816   sys::Path TestModuleBC("bugpoint.test.bc");
817   std::string ErrMsg;
818   if (TestModuleBC.makeUnique(true, &ErrMsg)) {
819     errs() << BD.getToolName() << "Error making unique filename: "
820            << ErrMsg << "\n";
821     exit(1);
822   }
823   if (BD.writeProgramToFile(TestModuleBC.toString(), Test)) {
824     errs() << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
825     exit(1);
826   }
827   delete Test;
828
829   // Make the shared library
830   sys::Path SafeModuleBC("bugpoint.safe.bc");
831   if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
832     errs() << BD.getToolName() << "Error making unique filename: "
833            << ErrMsg << "\n";
834     exit(1);
835   }
836
837   if (BD.writeProgramToFile(SafeModuleBC.toString(), Safe)) {
838     errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
839     exit(1);
840   }
841   std::string SharedObject = BD.compileSharedObject(SafeModuleBC.toString());
842   delete Safe;
843
844   // Run the code generator on the `Test' code, loading the shared library.
845   // The function returns whether or not the new output differs from reference.
846   int Result = BD.diffProgram(TestModuleBC.toString(), SharedObject, false);
847
848   if (Result)
849     errs() << ": still failing!\n";
850   else
851     errs() << ": didn't fail.\n";
852   TestModuleBC.eraseFromDisk();
853   SafeModuleBC.eraseFromDisk();
854   sys::Path(SharedObject).eraseFromDisk();
855
856   return Result;
857 }
858
859
860 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
861 ///
862 bool BugDriver::debugCodeGenerator() {
863   if ((void*)SafeInterpreter == (void*)Interpreter) {
864     std::string Result = executeProgramSafely("bugpoint.safe.out");
865     outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
866            << "the reference diff.  This may be due to a\n    front-end "
867            << "bug or a bug in the original program, but this can also "
868            << "happen if bugpoint isn't running the program with the "
869            << "right flags or input.\n    I left the result of executing "
870            << "the program with the \"safe\" backend in this file for "
871            << "you: '"
872            << Result << "'.\n";
873     return true;
874   }
875
876   DisambiguateGlobalSymbols(Program);
877
878   std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
879
880   // Split the module into the two halves of the program we want.
881   DenseMap<const Value*, Value*> ValueMap;
882   Module *ToNotCodeGen = CloneModule(getProgram(), ValueMap);
883   Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, ValueMap);
884
885   // Condition the modules
886   CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
887
888   sys::Path TestModuleBC("bugpoint.test.bc");
889   std::string ErrMsg;
890   if (TestModuleBC.makeUnique(true, &ErrMsg)) {
891     errs() << getToolName() << "Error making unique filename: "
892            << ErrMsg << "\n";
893     exit(1);
894   }
895
896   if (writeProgramToFile(TestModuleBC.toString(), ToCodeGen)) {
897     errs() << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
898     exit(1);
899   }
900   delete ToCodeGen;
901
902   // Make the shared library
903   sys::Path SafeModuleBC("bugpoint.safe.bc");
904   if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
905     errs() << getToolName() << "Error making unique filename: "
906            << ErrMsg << "\n";
907     exit(1);
908   }
909
910   if (writeProgramToFile(SafeModuleBC.toString(), ToNotCodeGen)) {
911     errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
912     exit(1);
913   }
914   std::string SharedObject = compileSharedObject(SafeModuleBC.toString());
915   delete ToNotCodeGen;
916
917   outs() << "You can reproduce the problem with the command line: \n";
918   if (isExecutingJIT()) {
919     outs() << "  lli -load " << SharedObject << " " << TestModuleBC;
920   } else {
921     outs() << "  llc -f " << TestModuleBC << " -o " << TestModuleBC<< ".s\n";
922     outs() << "  gcc " << SharedObject << " " << TestModuleBC
923               << ".s -o " << TestModuleBC << ".exe";
924 #if defined (HAVE_LINK_R)
925     outs() << " -Wl,-R.";
926 #endif
927     outs() << "\n";
928     outs() << "  " << TestModuleBC << ".exe";
929   }
930   for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
931     outs() << " " << InputArgv[i];
932   outs() << '\n';
933   outs() << "The shared object was created with:\n  llc -march=c "
934          << SafeModuleBC << " -o temporary.c\n"
935          << "  gcc -xc temporary.c -O2 -o " << SharedObject
936 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
937          << " -G"            // Compile a shared library, `-G' for Sparc
938 #else
939          << " -fPIC -shared"       // `-shared' for Linux/X86, maybe others
940 #endif
941          << " -fno-strict-aliasing\n";
942
943   return false;
944 }