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