Add const to some methods and change TestMergedProgram to return the merged
[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 there is
208 /// an error, return NULL. If not, return the merged module. The Broken argument
209 /// will be set to true if the output is different. If the DeleteInputs
210 /// argument is set to true then this function deletes both input
211 /// modules before it returns.
212 ///
213 static Module *TestMergedProgram(const BugDriver &BD, Module *M1, Module *M2,
214                                  bool DeleteInputs, std::string &Error,
215                                  bool &Broken) {
216   // Link the two portions of the program back to together.
217   std::string ErrorMsg;
218   if (!DeleteInputs) {
219     M1 = CloneModule(M1);
220     M2 = CloneModule(M2);
221   }
222   if (Linker::LinkModules(M1, M2, &ErrorMsg)) {
223     errs() << BD.getToolName() << ": Error linking modules together:"
224            << ErrorMsg << '\n';
225     exit(1);
226   }
227   delete M2;   // We are done with this module.
228
229   // Execute the program.
230   Broken = BD.diffProgram(M1, "", "", false, &Error);
231   if (!Error.empty()) {
232     // Delete the linked module
233     delete M1;
234     return NULL;
235   }
236   return M1;
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;
333     Module *New = TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize,
334                                     false, Error, Failure);
335     if (!New)
336       return false;
337     // Delete the original and set the new program.
338     delete BD.swapProgramIn(New);
339     if (Failure) {
340       BD.switchToInterpreter(AI);
341
342       // Merged program doesn't work anymore!
343       errs() << "  *** ERROR: Loop extraction broke the program. :("
344              << " Please report a bug!\n";
345       errs() << "      Continuing on with un-loop-extracted version.\n";
346
347       BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
348                             ToNotOptimize);
349       BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
350                             ToOptimize);
351       BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
352                             ToOptimizeLoopExtracted);
353
354       errs() << "Please submit the " 
355              << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
356       delete ToOptimize;
357       delete ToNotOptimize;
358       delete ToOptimizeLoopExtracted;
359       return MadeChange;
360     }
361     delete ToOptimize;
362     BD.switchToInterpreter(AI);
363
364     outs() << "  Testing after loop extraction:\n";
365     // Clone modules, the tester function will free them.
366     Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
367     Module *TNOBackup  = CloneModule(ToNotOptimize);
368     Failure = TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize, Error);
369     if (!Error.empty())
370       return false;
371     if (!Failure) {
372       outs() << "*** Loop extraction masked the problem.  Undoing.\n";
373       // If the program is not still broken, then loop extraction did something
374       // that masked the error.  Stop loop extraction now.
375       delete TOLEBackup;
376       delete TNOBackup;
377       return MadeChange;
378     }
379     ToOptimizeLoopExtracted = TOLEBackup;
380     ToNotOptimize = TNOBackup;
381
382     outs() << "*** Loop extraction successful!\n";
383
384     std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
385     for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
386            E = ToOptimizeLoopExtracted->end(); I != E; ++I)
387       if (!I->isDeclaration())
388         MisCompFunctions.push_back(std::make_pair(I->getName(),
389                                                   I->getFunctionType()));
390
391     // Okay, great!  Now we know that we extracted a loop and that loop
392     // extraction both didn't break the program, and didn't mask the problem.
393     // Replace the current program with the loop extracted version, and try to
394     // extract another loop.
395     std::string ErrorMsg;
396     if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
397       errs() << BD.getToolName() << ": Error linking modules together:"
398              << ErrorMsg << '\n';
399       exit(1);
400     }
401     delete ToOptimizeLoopExtracted;
402
403     // All of the Function*'s in the MiscompiledFunctions list are in the old
404     // module.  Update this list to include all of the functions in the
405     // optimized and loop extracted module.
406     MiscompiledFunctions.clear();
407     for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
408       Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
409                                                   
410       assert(NewF && "Function not found??");
411       assert(NewF->getFunctionType() == MisCompFunctions[i].second && 
412              "found wrong function type?");
413       MiscompiledFunctions.push_back(NewF);
414     }
415
416     BD.setNewProgram(ToNotOptimize);
417     MadeChange = true;
418   }
419 }
420
421 namespace {
422   class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
423     BugDriver &BD;
424     bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
425     std::vector<Function*> FunctionsBeingTested;
426   public:
427     ReduceMiscompiledBlocks(BugDriver &bd,
428                             bool (*F)(BugDriver &, Module *, Module *,
429                                       std::string &),
430                             const std::vector<Function*> &Fns)
431       : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
432
433     virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
434                               std::vector<BasicBlock*> &Suffix,
435                               std::string &Error) {
436       if (!Suffix.empty()) {
437         bool Ret = TestFuncs(Suffix, Error);
438         if (!Error.empty())
439           return InternalError;
440         if (Ret)
441           return KeepSuffix;
442       }
443       if (!Prefix.empty()) {
444         bool Ret = TestFuncs(Prefix, Error);
445         if (!Error.empty())
446           return InternalError;
447         if (Ret)
448           return KeepPrefix;
449       }
450       return NoFailure;
451     }
452
453     bool TestFuncs(const std::vector<BasicBlock*> &BBs, std::string &Error);
454   };
455 }
456
457 /// TestFuncs - Extract all blocks for the miscompiled functions except for the
458 /// specified blocks.  If the problem still exists, return true.
459 ///
460 bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs,
461                                         std::string &Error) {
462   // Test to see if the function is misoptimized if we ONLY run it on the
463   // functions listed in Funcs.
464   outs() << "Checking to see if the program is misoptimized when all ";
465   if (!BBs.empty()) {
466     outs() << "but these " << BBs.size() << " blocks are extracted: ";
467     for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
468       outs() << BBs[i]->getName() << " ";
469     if (BBs.size() > 10) outs() << "...";
470   } else {
471     outs() << "blocks are extracted.";
472   }
473   outs() << '\n';
474
475   // Split the module into the two halves of the program we want.
476   ValueMap<const Value*, Value*> VMap;
477   Module *Clone = CloneModule(BD.getProgram(), VMap);
478   Module *Orig = BD.swapProgramIn(Clone);
479   std::vector<Function*> FuncsOnClone;
480   std::vector<BasicBlock*> BBsOnClone;
481   for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
482     Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
483     FuncsOnClone.push_back(F);
484   }
485   for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
486     BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
487     BBsOnClone.push_back(BB);
488   }
489   VMap.clear();
490
491   Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
492   Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
493                                                  FuncsOnClone,
494                                                  VMap);
495
496   // Try the extraction.  If it doesn't work, then the block extractor crashed
497   // or something, in which case bugpoint can't chase down this possibility.
498   if (Module *New = BD.ExtractMappedBlocksFromModule(BBsOnClone, ToOptimize)) {
499     delete ToOptimize;
500     // Run the predicate,
501     // note that the predicate will delete both input modules.
502     bool Ret = TestFn(BD, New, ToNotOptimize, Error);
503     delete BD.swapProgramIn(Orig);
504     return Ret;
505   }
506   delete BD.swapProgramIn(Orig);
507   delete ToOptimize;
508   delete ToNotOptimize;
509   return false;
510 }
511
512
513 /// ExtractBlocks - Given a reduced list of functions that still expose the bug,
514 /// extract as many basic blocks from the region as possible without obscuring
515 /// the bug.
516 ///
517 static bool ExtractBlocks(BugDriver &BD,
518                           bool (*TestFn)(BugDriver &, Module *, Module *,
519                                          std::string &),
520                           std::vector<Function*> &MiscompiledFunctions,
521                           std::string &Error) {
522   if (BugpointIsInterrupted) return false;
523   
524   std::vector<BasicBlock*> Blocks;
525   for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
526     for (Function::iterator I = MiscompiledFunctions[i]->begin(),
527            E = MiscompiledFunctions[i]->end(); I != E; ++I)
528       Blocks.push_back(I);
529
530   // Use the list reducer to identify blocks that can be extracted without
531   // obscuring the bug.  The Blocks list will end up containing blocks that must
532   // be retained from the original program.
533   unsigned OldSize = Blocks.size();
534
535   // Check to see if all blocks are extractible first.
536   bool Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
537                                   .TestFuncs(std::vector<BasicBlock*>(), Error);
538   if (!Error.empty())
539     return false;
540   if (Ret) {
541     Blocks.clear();
542   } else {
543     ReduceMiscompiledBlocks(BD, TestFn,
544                             MiscompiledFunctions).reduceList(Blocks, Error);
545     if (!Error.empty())
546       return false;
547     if (Blocks.size() == OldSize)
548       return false;
549   }
550
551   ValueMap<const Value*, Value*> VMap;
552   Module *ProgClone = CloneModule(BD.getProgram(), VMap);
553   Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
554                                                 MiscompiledFunctions,
555                                                 VMap);
556   Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
557   if (Extracted == 0) {
558     // Weird, extraction should have worked.
559     errs() << "Nondeterministic problem extracting blocks??\n";
560     delete ProgClone;
561     delete ToExtract;
562     return false;
563   }
564
565   // Otherwise, block extraction succeeded.  Link the two program fragments back
566   // together.
567   delete ToExtract;
568
569   std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
570   for (Module::iterator I = Extracted->begin(), E = Extracted->end();
571        I != E; ++I)
572     if (!I->isDeclaration())
573       MisCompFunctions.push_back(std::make_pair(I->getName(),
574                                                 I->getFunctionType()));
575
576   std::string ErrorMsg;
577   if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
578     errs() << BD.getToolName() << ": Error linking modules together:"
579            << ErrorMsg << '\n';
580     exit(1);
581   }
582   delete Extracted;
583
584   // Set the new program and delete the old one.
585   BD.setNewProgram(ProgClone);
586
587   // Update the list of miscompiled functions.
588   MiscompiledFunctions.clear();
589
590   for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
591     Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
592     assert(NewF && "Function not found??");
593     assert(NewF->getFunctionType() == MisCompFunctions[i].second && 
594            "Function has wrong type??");
595     MiscompiledFunctions.push_back(NewF);
596   }
597
598   return true;
599 }
600
601
602 /// DebugAMiscompilation - This is a generic driver to narrow down
603 /// miscompilations, either in an optimization or a code generator.
604 ///
605 static std::vector<Function*>
606 DebugAMiscompilation(BugDriver &BD,
607                      bool (*TestFn)(BugDriver &, Module *, Module *,
608                                     std::string &),
609                      std::string &Error) {
610   // Okay, now that we have reduced the list of passes which are causing the
611   // failure, see if we can pin down which functions are being
612   // miscompiled... first build a list of all of the non-external functions in
613   // the program.
614   std::vector<Function*> MiscompiledFunctions;
615   Module *Prog = BD.getProgram();
616   for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
617     if (!I->isDeclaration())
618       MiscompiledFunctions.push_back(I);
619
620   // Do the reduction...
621   if (!BugpointIsInterrupted)
622     ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
623                                                        Error);
624   if (!Error.empty())
625     return MiscompiledFunctions;
626
627   outs() << "\n*** The following function"
628          << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
629          << " being miscompiled: ";
630   PrintFunctionList(MiscompiledFunctions);
631   outs() << '\n';
632
633   // See if we can rip any loops out of the miscompiled functions and still
634   // trigger the problem.
635
636   if (!BugpointIsInterrupted && !DisableLoopExtraction) {
637     bool Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions, Error);
638     if (!Error.empty())
639       return MiscompiledFunctions;
640     if (Ret) {
641       // Okay, we extracted some loops and the problem still appears.  See if
642       // we can eliminate some of the created functions from being candidates.
643       DisambiguateGlobalSymbols(BD.getProgram());
644
645       // Do the reduction...
646       if (!BugpointIsInterrupted)
647         ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
648                                                            Error);
649       if (!Error.empty())
650         return MiscompiledFunctions;
651
652       outs() << "\n*** The following function"
653              << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
654              << " being miscompiled: ";
655       PrintFunctionList(MiscompiledFunctions);
656       outs() << '\n';
657     }
658   }
659
660   if (!BugpointIsInterrupted && !DisableBlockExtraction) {
661     bool Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions, Error);
662     if (!Error.empty())
663       return MiscompiledFunctions;
664     if (Ret) {
665       // Okay, we extracted some blocks and the problem still appears.  See if
666       // we can eliminate some of the created functions from being candidates.
667       DisambiguateGlobalSymbols(BD.getProgram());
668
669       // Do the reduction...
670       ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
671                                                          Error);
672       if (!Error.empty())
673         return MiscompiledFunctions;
674
675       outs() << "\n*** The following function"
676              << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
677              << " being miscompiled: ";
678       PrintFunctionList(MiscompiledFunctions);
679       outs() << '\n';
680     }
681   }
682
683   return MiscompiledFunctions;
684 }
685
686 /// TestOptimizer - This is the predicate function used to check to see if the
687 /// "Test" portion of the program is misoptimized.  If so, return true.  In any
688 /// case, both module arguments are deleted.
689 ///
690 static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe,
691                           std::string &Error) {
692   // Run the optimization passes on ToOptimize, producing a transformed version
693   // of the functions being tested.
694   outs() << "  Optimizing functions being tested: ";
695   Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
696                                      /*AutoDebugCrashes*/true);
697   outs() << "done.\n";
698   delete Test;
699
700   outs() << "  Checking to see if the merged program executes correctly: ";
701   bool Broken;
702   Module *New = TestMergedProgram(BD, Optimized, Safe, true, Error, Broken);
703   if (New) {
704     outs() << (Broken ? " nope.\n" : " yup.\n");
705     // Delete the original and set the new program.
706     delete BD.swapProgramIn(New);
707   }
708   return Broken;
709 }
710
711
712 /// debugMiscompilation - This method is used when the passes selected are not
713 /// crashing, but the generated output is semantically different from the
714 /// input.
715 ///
716 void BugDriver::debugMiscompilation(std::string *Error) {
717   // Make sure something was miscompiled...
718   if (!BugpointIsInterrupted)
719     if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun, *Error)) {
720       if (Error->empty())
721         errs() << "*** Optimized program matches reference output!  No problem"
722                << " detected...\nbugpoint can't help you with your problem!\n";
723       return;
724     }
725
726   outs() << "\n*** Found miscompiling pass"
727          << (getPassesToRun().size() == 1 ? "" : "es") << ": "
728          << getPassesString(getPassesToRun()) << '\n';
729   EmitProgressBitcode(Program, "passinput");
730
731   std::vector<Function *> MiscompiledFunctions = 
732     DebugAMiscompilation(*this, TestOptimizer, *Error);
733   if (!Error->empty())
734     return;
735
736   // Output a bunch of bitcode files for the user...
737   outs() << "Outputting reduced bitcode files which expose the problem:\n";
738   ValueMap<const Value*, Value*> VMap;
739   Module *ToNotOptimize = CloneModule(getProgram(), VMap);
740   Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
741                                                  MiscompiledFunctions,
742                                                  VMap);
743
744   outs() << "  Non-optimized portion: ";
745   EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true);
746   delete ToNotOptimize;  // Delete hacked module.
747
748   outs() << "  Portion that is input to optimizer: ";
749   EmitProgressBitcode(ToOptimize, "tooptimize");
750   delete ToOptimize;      // Delete hacked module.
751
752   return;
753 }
754
755 /// CleanupAndPrepareModules - Get the specified modules ready for code
756 /// generator testing.
757 ///
758 static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
759                                      Module *Safe) {
760   // Clean up the modules, removing extra cruft that we don't need anymore...
761   Test = BD.performFinalCleanups(Test);
762
763   // If we are executing the JIT, we have several nasty issues to take care of.
764   if (!BD.isExecutingJIT()) return;
765
766   // First, if the main function is in the Safe module, we must add a stub to
767   // the Test module to call into it.  Thus, we create a new function `main'
768   // which just calls the old one.
769   if (Function *oldMain = Safe->getFunction("main"))
770     if (!oldMain->isDeclaration()) {
771       // Rename it
772       oldMain->setName("llvm_bugpoint_old_main");
773       // Create a NEW `main' function with same type in the test module.
774       Function *newMain = Function::Create(oldMain->getFunctionType(),
775                                            GlobalValue::ExternalLinkage,
776                                            "main", Test);
777       // Create an `oldmain' prototype in the test module, which will
778       // corresponds to the real main function in the same module.
779       Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
780                                                 GlobalValue::ExternalLinkage,
781                                                 oldMain->getName(), Test);
782       // Set up and remember the argument list for the main function.
783       std::vector<Value*> args;
784       for (Function::arg_iterator
785              I = newMain->arg_begin(), E = newMain->arg_end(),
786              OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
787         I->setName(OI->getName());    // Copy argument names from oldMain
788         args.push_back(I);
789       }
790
791       // Call the old main function and return its result
792       BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
793       CallInst *call = CallInst::Create(oldMainProto, args.begin(), args.end(),
794                                         "", BB);
795
796       // If the type of old function wasn't void, return value of call
797       ReturnInst::Create(Safe->getContext(), call, BB);
798     }
799
800   // The second nasty issue we must deal with in the JIT is that the Safe
801   // module cannot directly reference any functions defined in the test
802   // module.  Instead, we use a JIT API call to dynamically resolve the
803   // symbol.
804
805   // Add the resolver to the Safe module.
806   // Prototype: void *getPointerToNamedFunction(const char* Name)
807   Constant *resolverFunc =
808     Safe->getOrInsertFunction("getPointerToNamedFunction",
809                     Type::getInt8PtrTy(Safe->getContext()),
810                     Type::getInt8PtrTy(Safe->getContext()),
811                        (Type *)0);
812
813   // Use the function we just added to get addresses of functions we need.
814   for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
815     if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
816         !F->isIntrinsic() /* ignore intrinsics */) {
817       Function *TestFn = Test->getFunction(F->getName());
818
819       // Don't forward functions which are external in the test module too.
820       if (TestFn && !TestFn->isDeclaration()) {
821         // 1. Add a string constant with its name to the global file
822         Constant *InitArray = ConstantArray::get(F->getContext(), F->getName());
823         GlobalVariable *funcName =
824           new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
825                              GlobalValue::InternalLinkage, InitArray,
826                              F->getName() + "_name");
827
828         // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
829         // sbyte* so it matches the signature of the resolver function.
830
831         // GetElementPtr *funcName, ulong 0, ulong 0
832         std::vector<Constant*> GEPargs(2,
833                      Constant::getNullValue(Type::getInt32Ty(F->getContext())));
834         Value *GEP =
835                 ConstantExpr::getGetElementPtr(funcName, &GEPargs[0], 2);
836         std::vector<Value*> ResolverArgs;
837         ResolverArgs.push_back(GEP);
838
839         // Rewrite uses of F in global initializers, etc. to uses of a wrapper
840         // function that dynamically resolves the calls to F via our JIT API
841         if (!F->use_empty()) {
842           // Create a new global to hold the cached function pointer.
843           Constant *NullPtr = ConstantPointerNull::get(F->getType());
844           GlobalVariable *Cache =
845             new GlobalVariable(*F->getParent(), F->getType(), 
846                                false, GlobalValue::InternalLinkage,
847                                NullPtr,F->getName()+".fpcache");
848
849           // Construct a new stub function that will re-route calls to F
850           const FunctionType *FuncTy = F->getFunctionType();
851           Function *FuncWrapper = Function::Create(FuncTy,
852                                                    GlobalValue::InternalLinkage,
853                                                    F->getName() + "_wrapper",
854                                                    F->getParent());
855           BasicBlock *EntryBB  = BasicBlock::Create(F->getContext(),
856                                                     "entry", FuncWrapper);
857           BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
858                                                     "usecache", FuncWrapper);
859           BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
860                                                     "lookupfp", FuncWrapper);
861
862           // Check to see if we already looked up the value.
863           Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
864           Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
865                                        NullPtr, "isNull");
866           BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
867
868           // Resolve the call to function F via the JIT API:
869           //
870           // call resolver(GetElementPtr...)
871           CallInst *Resolver =
872             CallInst::Create(resolverFunc, ResolverArgs.begin(),
873                              ResolverArgs.end(), "resolver", LookupBB);
874
875           // Cast the result from the resolver to correctly-typed function.
876           CastInst *CastedResolver =
877             new BitCastInst(Resolver,
878                             PointerType::getUnqual(F->getFunctionType()),
879                             "resolverCast", LookupBB);
880
881           // Save the value in our cache.
882           new StoreInst(CastedResolver, Cache, LookupBB);
883           BranchInst::Create(DoCallBB, LookupBB);
884
885           PHINode *FuncPtr = PHINode::Create(NullPtr->getType(),
886                                              "fp", DoCallBB);
887           FuncPtr->addIncoming(CastedResolver, LookupBB);
888           FuncPtr->addIncoming(CachedVal, EntryBB);
889
890           // Save the argument list.
891           std::vector<Value*> Args;
892           for (Function::arg_iterator i = FuncWrapper->arg_begin(),
893                  e = FuncWrapper->arg_end(); i != e; ++i)
894             Args.push_back(i);
895
896           // Pass on the arguments to the real function, return its result
897           if (F->getReturnType()->isVoidTy()) {
898             CallInst::Create(FuncPtr, Args.begin(), Args.end(), "", DoCallBB);
899             ReturnInst::Create(F->getContext(), DoCallBB);
900           } else {
901             CallInst *Call = CallInst::Create(FuncPtr, Args.begin(), Args.end(),
902                                               "retval", DoCallBB);
903             ReturnInst::Create(F->getContext(),Call, DoCallBB);
904           }
905
906           // Use the wrapper function instead of the old function
907           F->replaceAllUsesWith(FuncWrapper);
908         }
909       }
910     }
911   }
912
913   if (verifyModule(*Test) || verifyModule(*Safe)) {
914     errs() << "Bugpoint has a bug, which corrupted a module!!\n";
915     abort();
916   }
917 }
918
919
920
921 /// TestCodeGenerator - This is the predicate function used to check to see if
922 /// the "Test" portion of the program is miscompiled by the code generator under
923 /// test.  If so, return true.  In any case, both module arguments are deleted.
924 ///
925 static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe,
926                               std::string &Error) {
927   CleanupAndPrepareModules(BD, Test, Safe);
928
929   sys::Path TestModuleBC("bugpoint.test.bc");
930   std::string ErrMsg;
931   if (TestModuleBC.makeUnique(true, &ErrMsg)) {
932     errs() << BD.getToolName() << "Error making unique filename: "
933            << ErrMsg << "\n";
934     exit(1);
935   }
936   if (BD.writeProgramToFile(TestModuleBC.str(), Test)) {
937     errs() << "Error writing bitcode to `" << TestModuleBC.str()
938            << "'\nExiting.";
939     exit(1);
940   }
941   delete Test;
942
943   FileRemover TestModuleBCRemover(TestModuleBC, !SaveTemps);
944
945   // Make the shared library
946   sys::Path SafeModuleBC("bugpoint.safe.bc");
947   if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
948     errs() << BD.getToolName() << "Error making unique filename: "
949            << ErrMsg << "\n";
950     exit(1);
951   }
952
953   if (BD.writeProgramToFile(SafeModuleBC.str(), Safe)) {
954     errs() << "Error writing bitcode to `" << SafeModuleBC.str()
955            << "'\nExiting.";
956     exit(1);
957   }
958
959   FileRemover SafeModuleBCRemover(SafeModuleBC, !SaveTemps);
960
961   std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str(), Error);
962   if (!Error.empty())
963     return false;
964   delete Safe;
965
966   FileRemover SharedObjectRemover(sys::Path(SharedObject), !SaveTemps);
967
968   // Run the code generator on the `Test' code, loading the shared library.
969   // The function returns whether or not the new output differs from reference.
970   bool Result = BD.diffProgram(BD.getProgram(), TestModuleBC.str(),
971                                SharedObject, false, &Error);
972   if (!Error.empty())
973     return false;
974
975   if (Result)
976     errs() << ": still failing!\n";
977   else
978     errs() << ": didn't fail.\n";
979
980   return Result;
981 }
982
983
984 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
985 ///
986 bool BugDriver::debugCodeGenerator(std::string *Error) {
987   if ((void*)SafeInterpreter == (void*)Interpreter) {
988     std::string Result = executeProgramSafely(Program, "bugpoint.safe.out",
989                                               Error);
990     if (Error->empty()) {
991       outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
992              << "the reference diff.  This may be due to a\n    front-end "
993              << "bug or a bug in the original program, but this can also "
994              << "happen if bugpoint isn't running the program with the "
995              << "right flags or input.\n    I left the result of executing "
996              << "the program with the \"safe\" backend in this file for "
997              << "you: '"
998              << Result << "'.\n";
999     }
1000     return true;
1001   }
1002
1003   DisambiguateGlobalSymbols(Program);
1004
1005   std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator,
1006                                                       *Error);
1007   if (!Error->empty())
1008     return true;
1009
1010   // Split the module into the two halves of the program we want.
1011   ValueMap<const Value*, Value*> VMap;
1012   Module *ToNotCodeGen = CloneModule(getProgram(), VMap);
1013   Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, VMap);
1014
1015   // Condition the modules
1016   CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
1017
1018   sys::Path TestModuleBC("bugpoint.test.bc");
1019   std::string ErrMsg;
1020   if (TestModuleBC.makeUnique(true, &ErrMsg)) {
1021     errs() << getToolName() << "Error making unique filename: "
1022            << ErrMsg << "\n";
1023     exit(1);
1024   }
1025
1026   if (writeProgramToFile(TestModuleBC.str(), ToCodeGen)) {
1027     errs() << "Error writing bitcode to `" << TestModuleBC.str()
1028            << "'\nExiting.";
1029     exit(1);
1030   }
1031   delete ToCodeGen;
1032
1033   // Make the shared library
1034   sys::Path SafeModuleBC("bugpoint.safe.bc");
1035   if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
1036     errs() << getToolName() << "Error making unique filename: "
1037            << ErrMsg << "\n";
1038     exit(1);
1039   }
1040
1041   if (writeProgramToFile(SafeModuleBC.str(), ToNotCodeGen)) {
1042     errs() << "Error writing bitcode to `" << SafeModuleBC.str()
1043            << "'\nExiting.";
1044     exit(1);
1045   }
1046   std::string SharedObject = compileSharedObject(SafeModuleBC.str(), *Error);
1047   if (!Error->empty())
1048     return true;
1049   delete ToNotCodeGen;
1050
1051   outs() << "You can reproduce the problem with the command line: \n";
1052   if (isExecutingJIT()) {
1053     outs() << "  lli -load " << SharedObject << " " << TestModuleBC.str();
1054   } else {
1055     outs() << "  llc " << TestModuleBC.str() << " -o " << TestModuleBC.str()
1056            << ".s\n";
1057     outs() << "  gcc " << SharedObject << " " << TestModuleBC.str()
1058               << ".s -o " << TestModuleBC.str() << ".exe";
1059 #if defined (HAVE_LINK_R)
1060     outs() << " -Wl,-R.";
1061 #endif
1062     outs() << "\n";
1063     outs() << "  " << TestModuleBC.str() << ".exe";
1064   }
1065   for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
1066     outs() << " " << InputArgv[i];
1067   outs() << '\n';
1068   outs() << "The shared object was created with:\n  llc -march=c "
1069          << SafeModuleBC.str() << " -o temporary.c\n"
1070          << "  gcc -xc temporary.c -O2 -o " << SharedObject;
1071   if (TargetTriple.getArch() == Triple::sparc)
1072     outs() << " -G";              // Compile a shared library, `-G' for Sparc
1073   else
1074     outs() << " -fPIC -shared";   // `-shared' for Linux/X86, maybe others
1075
1076   outs() << " -fno-strict-aliasing\n";
1077
1078   return false;
1079 }