Fix printing of the instructions.
[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   // Agree with the CBE on symbol naming
236   Mang.markCharUnacceptable('.');
237   for (Module::global_iterator I = M->global_begin(), E = M->global_end(); I != E; ++I)
238     I->setName(Mang.getValueName(I));
239   for (Module::iterator  I = M->begin(),  E = M->end();  I != E; ++I)
240     I->setName(Mang.getValueName(I));
241 }
242
243 /// ExtractLoops - Given a reduced list of functions that still exposed the bug,
244 /// check to see if we can extract the loops in the region without obscuring the
245 /// bug.  If so, it reduces the amount of code identified.
246 ///
247 static bool ExtractLoops(BugDriver &BD,
248                          bool (*TestFn)(BugDriver &, Module *, Module *),
249                          std::vector<Function*> &MiscompiledFunctions) {
250   bool MadeChange = false;
251   while (1) {
252     if (BugpointIsInterrupted) return MadeChange;
253     
254     Module *ToNotOptimize = CloneModule(BD.getProgram());
255     Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
256                                                    MiscompiledFunctions);
257     Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
258     if (!ToOptimizeLoopExtracted) {
259       // If the loop extractor crashed or if there were no extractible loops,
260       // then this chapter of our odyssey is over with.
261       delete ToNotOptimize;
262       delete ToOptimize;
263       return MadeChange;
264     }
265
266     std::cerr << "Extracted a loop from the breaking portion of the program.\n";
267
268     // Bugpoint is intentionally not very trusting of LLVM transformations.  In
269     // particular, we're not going to assume that the loop extractor works, so
270     // we're going to test the newly loop extracted program to make sure nothing
271     // has broken.  If something broke, then we'll inform the user and stop
272     // extraction.
273     AbstractInterpreter *AI = BD.switchToCBE();
274     if (TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize, false)) {
275       BD.switchToInterpreter(AI);
276
277       // Merged program doesn't work anymore!
278       std::cerr << "  *** ERROR: Loop extraction broke the program. :("
279                 << " Please report a bug!\n";
280       std::cerr << "      Continuing on with un-loop-extracted version.\n";
281
282       BD.writeProgramToFile("bugpoint-loop-extract-fail-tno.bc", ToNotOptimize);
283       BD.writeProgramToFile("bugpoint-loop-extract-fail-to.bc", ToOptimize);
284       BD.writeProgramToFile("bugpoint-loop-extract-fail-to-le.bc",
285                             ToOptimizeLoopExtracted);
286
287       std::cerr << "Please submit the bugpoint-loop-extract-fail-*.bc files.\n";
288       delete ToOptimize;
289       delete ToNotOptimize;
290       delete ToOptimizeLoopExtracted;
291       return MadeChange;
292     }
293     delete ToOptimize;
294     BD.switchToInterpreter(AI);
295
296     std::cout << "  Testing after loop extraction:\n";
297     // Clone modules, the tester function will free them.
298     Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
299     Module *TNOBackup  = CloneModule(ToNotOptimize);
300     if (!TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize)) {
301       std::cout << "*** Loop extraction masked the problem.  Undoing.\n";
302       // If the program is not still broken, then loop extraction did something
303       // that masked the error.  Stop loop extraction now.
304       delete TOLEBackup;
305       delete TNOBackup;
306       return MadeChange;
307     }
308     ToOptimizeLoopExtracted = TOLEBackup;
309     ToNotOptimize = TNOBackup;
310
311     std::cout << "*** Loop extraction successful!\n";
312
313     std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
314     for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
315            E = ToOptimizeLoopExtracted->end(); I != E; ++I)
316       if (!I->isExternal())
317         MisCompFunctions.push_back(std::make_pair(I->getName(),
318                                                   I->getFunctionType()));
319
320     // Okay, great!  Now we know that we extracted a loop and that loop
321     // extraction both didn't break the program, and didn't mask the problem.
322     // Replace the current program with the loop extracted version, and try to
323     // extract another loop.
324     std::string ErrorMsg;
325     if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
326       std::cerr << BD.getToolName() << ": Error linking modules together:"
327                 << ErrorMsg << '\n';
328       exit(1);
329     }
330     delete ToOptimizeLoopExtracted;
331
332     // All of the Function*'s in the MiscompiledFunctions list are in the old
333     // module.  Update this list to include all of the functions in the
334     // optimized and loop extracted module.
335     MiscompiledFunctions.clear();
336     for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
337       Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first,
338                                                   MisCompFunctions[i].second);
339       assert(NewF && "Function not found??");
340       MiscompiledFunctions.push_back(NewF);
341     }
342
343     BD.setNewProgram(ToNotOptimize);
344     MadeChange = true;
345   }
346 }
347
348 namespace {
349   class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
350     BugDriver &BD;
351     bool (*TestFn)(BugDriver &, Module *, Module *);
352     std::vector<Function*> FunctionsBeingTested;
353   public:
354     ReduceMiscompiledBlocks(BugDriver &bd,
355                             bool (*F)(BugDriver &, Module *, Module *),
356                             const std::vector<Function*> &Fns)
357       : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
358
359     virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
360                               std::vector<BasicBlock*> &Suffix) {
361       if (!Suffix.empty() && TestFuncs(Suffix))
362         return KeepSuffix;
363       if (TestFuncs(Prefix))
364         return KeepPrefix;
365       return NoFailure;
366     }
367
368     bool TestFuncs(const std::vector<BasicBlock*> &Prefix);
369   };
370 }
371
372 /// TestFuncs - Extract all blocks for the miscompiled functions except for the
373 /// specified blocks.  If the problem still exists, return true.
374 ///
375 bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs) {
376   // Test to see if the function is misoptimized if we ONLY run it on the
377   // functions listed in Funcs.
378   std::cout << "Checking to see if the program is misoptimized when all ";
379   if (!BBs.empty()) {
380     std::cout << "but these " << BBs.size() << " blocks are extracted: ";
381     for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
382       std::cout << BBs[i]->getName() << " ";
383     if (BBs.size() > 10) std::cout << "...";
384   } else {
385     std::cout << "blocks are extracted.";
386   }
387   std::cout << '\n';
388
389   // Split the module into the two halves of the program we want.
390   Module *ToNotOptimize = CloneModule(BD.getProgram());
391   Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
392                                                  FunctionsBeingTested);
393
394   // Try the extraction.  If it doesn't work, then the block extractor crashed
395   // or something, in which case bugpoint can't chase down this possibility.
396   if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) {
397     delete ToOptimize;
398     // Run the predicate, not that the predicate will delete both input modules.
399     return TestFn(BD, New, ToNotOptimize);
400   }
401   delete ToOptimize;
402   delete ToNotOptimize;
403   return false;
404 }
405
406
407 /// ExtractBlocks - Given a reduced list of functions that still expose the bug,
408 /// extract as many basic blocks from the region as possible without obscuring
409 /// the bug.
410 ///
411 static bool ExtractBlocks(BugDriver &BD,
412                           bool (*TestFn)(BugDriver &, Module *, Module *),
413                           std::vector<Function*> &MiscompiledFunctions) {
414   if (BugpointIsInterrupted) return false;
415   
416   std::vector<BasicBlock*> Blocks;
417   for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
418     for (Function::iterator I = MiscompiledFunctions[i]->begin(),
419            E = MiscompiledFunctions[i]->end(); I != E; ++I)
420       Blocks.push_back(I);
421
422   // Use the list reducer to identify blocks that can be extracted without
423   // obscuring the bug.  The Blocks list will end up containing blocks that must
424   // be retained from the original program.
425   unsigned OldSize = Blocks.size();
426
427   // Check to see if all blocks are extractible first.
428   if (ReduceMiscompiledBlocks(BD, TestFn,
429                   MiscompiledFunctions).TestFuncs(std::vector<BasicBlock*>())) {
430     Blocks.clear();
431   } else {
432     ReduceMiscompiledBlocks(BD, TestFn,MiscompiledFunctions).reduceList(Blocks);
433     if (Blocks.size() == OldSize)
434       return false;
435   }
436
437   Module *ProgClone = CloneModule(BD.getProgram());
438   Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
439                                                 MiscompiledFunctions);
440   Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
441   if (Extracted == 0) {
442     // Weird, extraction should have worked.
443     std::cerr << "Nondeterministic problem extracting blocks??\n";
444     delete ProgClone;
445     delete ToExtract;
446     return false;
447   }
448
449   // Otherwise, block extraction succeeded.  Link the two program fragments back
450   // together.
451   delete ToExtract;
452
453   std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
454   for (Module::iterator I = Extracted->begin(), E = Extracted->end();
455        I != E; ++I)
456     if (!I->isExternal())
457       MisCompFunctions.push_back(std::make_pair(I->getName(),
458                                                 I->getFunctionType()));
459
460   std::string ErrorMsg;
461   if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
462     std::cerr << BD.getToolName() << ": Error linking modules together:"
463               << ErrorMsg << '\n';
464     exit(1);
465   }
466   delete Extracted;
467
468   // Set the new program and delete the old one.
469   BD.setNewProgram(ProgClone);
470
471   // Update the list of miscompiled functions.
472   MiscompiledFunctions.clear();
473
474   for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
475     Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first,
476                                             MisCompFunctions[i].second);
477     assert(NewF && "Function not found??");
478     MiscompiledFunctions.push_back(NewF);
479   }
480
481   return true;
482 }
483
484
485 /// DebugAMiscompilation - This is a generic driver to narrow down
486 /// miscompilations, either in an optimization or a code generator.
487 ///
488 static std::vector<Function*>
489 DebugAMiscompilation(BugDriver &BD,
490                      bool (*TestFn)(BugDriver &, Module *, Module *)) {
491   // Okay, now that we have reduced the list of passes which are causing the
492   // failure, see if we can pin down which functions are being
493   // miscompiled... first build a list of all of the non-external functions in
494   // the program.
495   std::vector<Function*> MiscompiledFunctions;
496   Module *Prog = BD.getProgram();
497   for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
498     if (!I->isExternal())
499       MiscompiledFunctions.push_back(I);
500
501   // Do the reduction...
502   if (!BugpointIsInterrupted)
503     ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
504
505   std::cout << "\n*** The following function"
506             << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
507             << " being miscompiled: ";
508   PrintFunctionList(MiscompiledFunctions);
509   std::cout << '\n';
510
511   // See if we can rip any loops out of the miscompiled functions and still
512   // trigger the problem.
513   if (!BugpointIsInterrupted && 
514       ExtractLoops(BD, TestFn, MiscompiledFunctions)) {
515     // Okay, we extracted some loops and the problem still appears.  See if we
516     // can eliminate some of the created functions from being candidates.
517
518     // Loop extraction can introduce functions with the same name (foo_code).
519     // Make sure to disambiguate the symbols so that when the program is split
520     // apart that we can link it back together again.
521     DisambiguateGlobalSymbols(BD.getProgram());
522
523     // Do the reduction...
524     if (!BugpointIsInterrupted)
525       ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
526
527     std::cout << "\n*** The following function"
528               << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
529               << " being miscompiled: ";
530     PrintFunctionList(MiscompiledFunctions);
531     std::cout << '\n';
532   }
533
534   if (!BugpointIsInterrupted &&
535       ExtractBlocks(BD, TestFn, MiscompiledFunctions)) {
536     // Okay, we extracted some blocks and the problem still appears.  See if we
537     // can eliminate some of the created functions from being candidates.
538
539     // Block extraction can introduce functions with the same name (foo_code).
540     // Make sure to disambiguate the symbols so that when the program is split
541     // apart that we can link it back together again.
542     DisambiguateGlobalSymbols(BD.getProgram());
543
544     // Do the reduction...
545     ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions);
546
547     std::cout << "\n*** The following function"
548               << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
549               << " being miscompiled: ";
550     PrintFunctionList(MiscompiledFunctions);
551     std::cout << '\n';
552   }
553
554   return MiscompiledFunctions;
555 }
556
557 /// TestOptimizer - This is the predicate function used to check to see if the
558 /// "Test" portion of the program is misoptimized.  If so, return true.  In any
559 /// case, both module arguments are deleted.
560 ///
561 static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe) {
562   // Run the optimization passes on ToOptimize, producing a transformed version
563   // of the functions being tested.
564   std::cout << "  Optimizing functions being tested: ";
565   Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
566                                      /*AutoDebugCrashes*/true);
567   std::cout << "done.\n";
568   delete Test;
569
570   std::cout << "  Checking to see if the merged program executes correctly: ";
571   bool Broken = TestMergedProgram(BD, Optimized, Safe, true);
572   std::cout << (Broken ? " nope.\n" : " yup.\n");
573   return Broken;
574 }
575
576
577 /// debugMiscompilation - This method is used when the passes selected are not
578 /// crashing, but the generated output is semantically different from the
579 /// input.
580 ///
581 bool BugDriver::debugMiscompilation() {
582   // Make sure something was miscompiled...
583   if (!BugpointIsInterrupted)
584     if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun)) {
585       std::cerr << "*** Optimized program matches reference output!  No problem"
586                 << " detected...\nbugpoint can't help you with your problem!\n";
587       return false;
588     }
589
590   std::cout << "\n*** Found miscompiling pass"
591             << (getPassesToRun().size() == 1 ? "" : "es") << ": "
592             << getPassesString(getPassesToRun()) << '\n';
593   EmitProgressBytecode("passinput");
594
595   std::vector<Function*> MiscompiledFunctions =
596     DebugAMiscompilation(*this, TestOptimizer);
597
598   // Output a bunch of bytecode files for the user...
599   std::cout << "Outputting reduced bytecode files which expose the problem:\n";
600   Module *ToNotOptimize = CloneModule(getProgram());
601   Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
602                                                  MiscompiledFunctions);
603
604   std::cout << "  Non-optimized portion: ";
605   ToNotOptimize = swapProgramIn(ToNotOptimize);
606   EmitProgressBytecode("tonotoptimize", true);
607   setNewProgram(ToNotOptimize);   // Delete hacked module.
608
609   std::cout << "  Portion that is input to optimizer: ";
610   ToOptimize = swapProgramIn(ToOptimize);
611   EmitProgressBytecode("tooptimize");
612   setNewProgram(ToOptimize);      // Delete hacked module.
613
614   return false;
615 }
616
617 /// CleanupAndPrepareModules - Get the specified modules ready for code
618 /// generator testing.
619 ///
620 static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
621                                      Module *Safe) {
622   // Clean up the modules, removing extra cruft that we don't need anymore...
623   Test = BD.performFinalCleanups(Test);
624
625   // If we are executing the JIT, we have several nasty issues to take care of.
626   if (!BD.isExecutingJIT()) return;
627
628   // First, if the main function is in the Safe module, we must add a stub to
629   // the Test module to call into it.  Thus, we create a new function `main'
630   // which just calls the old one.
631   if (Function *oldMain = Safe->getNamedFunction("main"))
632     if (!oldMain->isExternal()) {
633       // Rename it
634       oldMain->setName("llvm_bugpoint_old_main");
635       // Create a NEW `main' function with same type in the test module.
636       Function *newMain = new Function(oldMain->getFunctionType(),
637                                        GlobalValue::ExternalLinkage,
638                                        "main", Test);
639       // Create an `oldmain' prototype in the test module, which will
640       // corresponds to the real main function in the same module.
641       Function *oldMainProto = new Function(oldMain->getFunctionType(),
642                                             GlobalValue::ExternalLinkage,
643                                             oldMain->getName(), Test);
644       // Set up and remember the argument list for the main function.
645       std::vector<Value*> args;
646       for (Function::arg_iterator
647              I = newMain->arg_begin(), E = newMain->arg_end(),
648              OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
649         I->setName(OI->getName());    // Copy argument names from oldMain
650         args.push_back(I);
651       }
652
653       // Call the old main function and return its result
654       BasicBlock *BB = new BasicBlock("entry", newMain);
655       CallInst *call = new CallInst(oldMainProto, args, "", BB);
656
657       // If the type of old function wasn't void, return value of call
658       new ReturnInst(call, BB);
659     }
660
661   // The second nasty issue we must deal with in the JIT is that the Safe
662   // module cannot directly reference any functions defined in the test
663   // module.  Instead, we use a JIT API call to dynamically resolve the
664   // symbol.
665
666   // Add the resolver to the Safe module.
667   // Prototype: void *getPointerToNamedFunction(const char* Name)
668   Function *resolverFunc =
669     Safe->getOrInsertFunction("getPointerToNamedFunction",
670                               PointerType::get(Type::SByteTy),
671                               PointerType::get(Type::SByteTy), (Type *)0);
672
673   // Use the function we just added to get addresses of functions we need.
674   for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
675     if (F->isExternal() && !F->use_empty() && &*F != resolverFunc &&
676         F->getIntrinsicID() == 0 /* ignore intrinsics */) {
677       Function *TestFn = Test->getNamedFunction(F->getName());
678
679       // Don't forward functions which are external in the test module too.
680       if (TestFn && !TestFn->isExternal()) {
681         // 1. Add a string constant with its name to the global file
682         Constant *InitArray = ConstantArray::get(F->getName());
683         GlobalVariable *funcName =
684           new GlobalVariable(InitArray->getType(), true /*isConstant*/,
685                              GlobalValue::InternalLinkage, InitArray,
686                              F->getName() + "_name", Safe);
687
688         // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
689         // sbyte* so it matches the signature of the resolver function.
690
691         // GetElementPtr *funcName, ulong 0, ulong 0
692         std::vector<Constant*> GEPargs(2,Constant::getNullValue(Type::IntTy));
693         Value *GEP =
694           ConstantExpr::getGetElementPtr(funcName, GEPargs);
695         std::vector<Value*> ResolverArgs;
696         ResolverArgs.push_back(GEP);
697
698         // Rewrite uses of F in global initializers, etc. to uses of a wrapper
699         // function that dynamically resolves the calls to F via our JIT API
700         if (!F->use_empty()) {
701           // Create a new global to hold the cached function pointer.
702           Constant *NullPtr = ConstantPointerNull::get(F->getType());
703           GlobalVariable *Cache =
704             new GlobalVariable(F->getType(), false,GlobalValue::InternalLinkage,
705                                NullPtr,F->getName()+".fpcache", F->getParent());
706
707           // Construct a new stub function that will re-route calls to F
708           const FunctionType *FuncTy = F->getFunctionType();
709           Function *FuncWrapper = new Function(FuncTy,
710                                                GlobalValue::InternalLinkage,
711                                                F->getName() + "_wrapper",
712                                                F->getParent());
713           BasicBlock *EntryBB  = new BasicBlock("entry", FuncWrapper);
714           BasicBlock *DoCallBB = new BasicBlock("usecache", FuncWrapper);
715           BasicBlock *LookupBB = new BasicBlock("lookupfp", FuncWrapper);
716
717           // Check to see if we already looked up the value.
718           Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
719           Value *IsNull = new SetCondInst(Instruction::SetEQ, CachedVal,
720                                           NullPtr, "isNull", EntryBB);
721           new BranchInst(LookupBB, DoCallBB, IsNull, EntryBB);
722
723           // Resolve the call to function F via the JIT API:
724           //
725           // call resolver(GetElementPtr...)
726           CallInst *Resolver = new CallInst(resolverFunc, ResolverArgs,
727                                             "resolver", LookupBB);
728           // cast the result from the resolver to correctly-typed function
729           CastInst *CastedResolver =
730             new CastInst(Resolver, PointerType::get(F->getFunctionType()),
731                          "resolverCast", LookupBB);
732           // Save the value in our cache.
733           new StoreInst(CastedResolver, Cache, LookupBB);
734           new BranchInst(DoCallBB, LookupBB);
735
736           PHINode *FuncPtr = new PHINode(NullPtr->getType(), "fp", DoCallBB);
737           FuncPtr->addIncoming(CastedResolver, LookupBB);
738           FuncPtr->addIncoming(CachedVal, EntryBB);
739
740           // Save the argument list.
741           std::vector<Value*> Args;
742           for (Function::arg_iterator i = FuncWrapper->arg_begin(),
743                  e = FuncWrapper->arg_end(); i != e; ++i)
744             Args.push_back(i);
745
746           // Pass on the arguments to the real function, return its result
747           if (F->getReturnType() == Type::VoidTy) {
748             CallInst *Call = new CallInst(FuncPtr, Args, "", DoCallBB);
749             new ReturnInst(DoCallBB);
750           } else {
751             CallInst *Call = new CallInst(FuncPtr, Args, "retval", DoCallBB);
752             new ReturnInst(Call, DoCallBB);
753           }
754
755           // Use the wrapper function instead of the old function
756           F->replaceAllUsesWith(FuncWrapper);
757         }
758       }
759     }
760   }
761
762   if (verifyModule(*Test) || verifyModule(*Safe)) {
763     std::cerr << "Bugpoint has a bug, which corrupted a module!!\n";
764     abort();
765   }
766 }
767
768
769
770 /// TestCodeGenerator - This is the predicate function used to check to see if
771 /// the "Test" portion of the program is miscompiled by the code generator under
772 /// test.  If so, return true.  In any case, both module arguments are deleted.
773 ///
774 static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe) {
775   CleanupAndPrepareModules(BD, Test, Safe);
776
777   sys::Path TestModuleBC("bugpoint.test.bc");
778   TestModuleBC.makeUnique();
779   if (BD.writeProgramToFile(TestModuleBC.toString(), Test)) {
780     std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
781     exit(1);
782   }
783   delete Test;
784
785   // Make the shared library
786   sys::Path SafeModuleBC("bugpoint.safe.bc");
787   SafeModuleBC.makeUnique();
788
789   if (BD.writeProgramToFile(SafeModuleBC.toString(), Safe)) {
790     std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
791     exit(1);
792   }
793   std::string SharedObject = BD.compileSharedObject(SafeModuleBC.toString());
794   delete Safe;
795
796   // Run the code generator on the `Test' code, loading the shared library.
797   // The function returns whether or not the new output differs from reference.
798   int Result = BD.diffProgram(TestModuleBC.toString(), SharedObject, false);
799
800   if (Result)
801     std::cerr << ": still failing!\n";
802   else
803     std::cerr << ": didn't fail.\n";
804   TestModuleBC.eraseFromDisk();
805   SafeModuleBC.eraseFromDisk();
806   sys::Path(SharedObject).eraseFromDisk();
807
808   return Result;
809 }
810
811
812 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
813 ///
814 bool BugDriver::debugCodeGenerator() {
815   if ((void*)cbe == (void*)Interpreter) {
816     std::string Result = executeProgramWithCBE("bugpoint.cbe.out");
817     std::cout << "\n*** The C backend cannot match the reference diff, but it "
818               << "is used as the 'known good'\n    code generator, so I can't"
819               << " debug it.  Perhaps you have a front-end problem?\n    As a"
820               << " sanity check, I left the result of executing the program "
821               << "with the C backend\n    in this file for you: '"
822               << Result << "'.\n";
823     return true;
824   }
825
826   DisambiguateGlobalSymbols(Program);
827
828   std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator);
829
830   // Split the module into the two halves of the program we want.
831   Module *ToNotCodeGen = CloneModule(getProgram());
832   Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs);
833
834   // Condition the modules
835   CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
836
837   sys::Path TestModuleBC("bugpoint.test.bc");
838   TestModuleBC.makeUnique();
839
840   if (writeProgramToFile(TestModuleBC.toString(), ToCodeGen)) {
841     std::cerr << "Error writing bytecode to `" << TestModuleBC << "'\nExiting.";
842     exit(1);
843   }
844   delete ToCodeGen;
845
846   // Make the shared library
847   sys::Path SafeModuleBC("bugpoint.safe.bc");
848   SafeModuleBC.makeUnique();
849
850   if (writeProgramToFile(SafeModuleBC.toString(), ToNotCodeGen)) {
851     std::cerr << "Error writing bytecode to `" << SafeModuleBC << "'\nExiting.";
852     exit(1);
853   }
854   std::string SharedObject = compileSharedObject(SafeModuleBC.toString());
855   delete ToNotCodeGen;
856
857   std::cout << "You can reproduce the problem with the command line: \n";
858   if (isExecutingJIT()) {
859     std::cout << "  lli -load " << SharedObject << " " << TestModuleBC;
860   } else {
861     std::cout << "  llc -f " << TestModuleBC << " -o " << TestModuleBC<< ".s\n";
862     std::cout << "  gcc " << SharedObject << " " << TestModuleBC
863               << ".s -o " << TestModuleBC << ".exe";
864 #if defined (HAVE_LINK_R)
865     std::cout << " -Wl,-R.";
866 #endif
867     std::cout << "\n";
868     std::cout << "  " << TestModuleBC << ".exe";
869   }
870   for (unsigned i=0, e = InputArgv.size(); i != e; ++i)
871     std::cout << " " << InputArgv[i];
872   std::cout << '\n';
873   std::cout << "The shared object was created with:\n  llc -march=c "
874             << SafeModuleBC << " -o temporary.c\n"
875             << "  gcc -xc temporary.c -O2 -o " << SharedObject
876 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
877             << " -G"            // Compile a shared library, `-G' for Sparc
878 #else
879             << " -shared"       // `-shared' for Linux/X86, maybe others
880 #endif
881             << " -fno-strict-aliasing\n";
882
883   return false;
884 }