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