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