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