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