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