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