Miscompilation.cpp revision 314564
1193323Sed//===- Miscompilation.cpp - Debug program miscompilations -----------------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file implements optimizer and code generation miscompilation debugging
11193323Sed// support.
12193323Sed//
13193323Sed//===----------------------------------------------------------------------===//
14193323Sed
15193323Sed#include "BugDriver.h"
16193323Sed#include "ListReducer.h"
17198090Srdivacky#include "ToolRunner.h"
18314564Sdim#include "llvm/Config/config.h" // for HAVE_LINK_R
19249423Sdim#include "llvm/IR/Constants.h"
20249423Sdim#include "llvm/IR/DerivedTypes.h"
21249423Sdim#include "llvm/IR/Instructions.h"
22249423Sdim#include "llvm/IR/Module.h"
23276479Sdim#include "llvm/IR/Verifier.h"
24276479Sdim#include "llvm/Linker/Linker.h"
25193323Sed#include "llvm/Pass.h"
26193323Sed#include "llvm/Support/CommandLine.h"
27193323Sed#include "llvm/Support/FileUtilities.h"
28249423Sdim#include "llvm/Transforms/Utils/Cloning.h"
29309124Sdim
30193323Sedusing namespace llvm;
31193323Sed
32193323Sednamespace llvm {
33314564Sdimextern cl::opt<std::string> OutputPrefix;
34314564Sdimextern cl::list<std::string> InputArgv;
35309124Sdim} // end namespace llvm
36193323Sed
37193323Sednamespace {
38314564Sdimstatic llvm::cl::opt<bool> DisableLoopExtraction(
39314564Sdim    "disable-loop-extraction",
40314564Sdim    cl::desc("Don't extract loops when searching for miscompilations"),
41314564Sdim    cl::init(false));
42314564Sdimstatic llvm::cl::opt<bool> DisableBlockExtraction(
43314564Sdim    "disable-block-extraction",
44314564Sdim    cl::desc("Don't extract blocks when searching for miscompilations"),
45314564Sdim    cl::init(false));
46193323Sed
47314564Sdimclass ReduceMiscompilingPasses : public ListReducer<std::string> {
48314564Sdim  BugDriver &BD;
49193323Sed
50314564Sdimpublic:
51314564Sdim  ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
52314564Sdim
53314564Sdim  Expected<TestResult> doTest(std::vector<std::string> &Prefix,
54314564Sdim                              std::vector<std::string> &Suffix) override;
55314564Sdim};
56309124Sdim} // end anonymous namespace
57193323Sed
58193323Sed/// TestResult - After passes have been split into a test group and a control
59193323Sed/// group, see if they still break the program.
60193323Sed///
61314564SdimExpected<ReduceMiscompilingPasses::TestResult>
62212793SdimReduceMiscompilingPasses::doTest(std::vector<std::string> &Prefix,
63314564Sdim                                 std::vector<std::string> &Suffix) {
64193323Sed  // First, run the program with just the Suffix passes.  If it is still broken
65193323Sed  // with JUST the kept passes, discard the prefix passes.
66198090Srdivacky  outs() << "Checking to see if '" << getPassesString(Suffix)
67198090Srdivacky         << "' compiles correctly: ";
68193323Sed
69193323Sed  std::string BitcodeResult;
70314564Sdim  if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false /*delete*/,
71314564Sdim                   true /*quiet*/)) {
72198090Srdivacky    errs() << " Error running this sequence of passes"
73198090Srdivacky           << " on the input program!\n";
74193323Sed    BD.setPassesToRun(Suffix);
75314564Sdim    BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
76314564Sdim    // TODO: This should propagate the error instead of exiting.
77314564Sdim    if (Error E = BD.debugOptimizerCrash())
78314564Sdim      exit(1);
79314564Sdim    exit(0);
80193323Sed  }
81221337Sdim
82193323Sed  // Check to see if the finished program matches the reference output...
83314564Sdim  Expected<bool> Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
84314564Sdim                                       true /*delete bitcode*/);
85314564Sdim  if (Error E = Diff.takeError())
86314564Sdim    return std::move(E);
87314564Sdim  if (*Diff) {
88198090Srdivacky    outs() << " nope.\n";
89193323Sed    if (Suffix.empty()) {
90198090Srdivacky      errs() << BD.getToolName() << ": I'm confused: the test fails when "
91198090Srdivacky             << "no passes are run, nondeterministic program?\n";
92193323Sed      exit(1);
93193323Sed    }
94314564Sdim    return KeepSuffix; // Miscompilation detected!
95193323Sed  }
96314564Sdim  outs() << " yup.\n"; // No miscompilation!
97193323Sed
98314564Sdim  if (Prefix.empty())
99314564Sdim    return NoFailure;
100193323Sed
101193323Sed  // Next, see if the program is broken if we run the "prefix" passes first,
102193323Sed  // then separately run the "kept" passes.
103198090Srdivacky  outs() << "Checking to see if '" << getPassesString(Prefix)
104198090Srdivacky         << "' compiles correctly: ";
105193323Sed
106193323Sed  // If it is not broken with the kept passes, it's possible that the prefix
107193323Sed  // passes must be run before the kept passes to break it.  If the program
108193323Sed  // WORKS after the prefix passes, but then fails if running the prefix AND
109193323Sed  // kept passes, we can update our bitcode file to include the result of the
110193323Sed  // prefix passes, then discard the prefix passes.
111193323Sed  //
112314564Sdim  if (BD.runPasses(BD.getProgram(), Prefix, BitcodeResult, false /*delete*/,
113314564Sdim                   true /*quiet*/)) {
114198090Srdivacky    errs() << " Error running this sequence of passes"
115198090Srdivacky           << " on the input program!\n";
116193323Sed    BD.setPassesToRun(Prefix);
117314564Sdim    BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
118314564Sdim    // TODO: This should propagate the error instead of exiting.
119314564Sdim    if (Error E = BD.debugOptimizerCrash())
120314564Sdim      exit(1);
121314564Sdim    exit(0);
122193323Sed  }
123193323Sed
124193323Sed  // If the prefix maintains the predicate by itself, only keep the prefix!
125314564Sdim  Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "", false);
126314564Sdim  if (Error E = Diff.takeError())
127314564Sdim    return std::move(E);
128314564Sdim  if (*Diff) {
129198090Srdivacky    outs() << " nope.\n";
130261991Sdim    sys::fs::remove(BitcodeResult);
131193323Sed    return KeepPrefix;
132193323Sed  }
133314564Sdim  outs() << " yup.\n"; // No miscompilation!
134193323Sed
135193323Sed  // Ok, so now we know that the prefix passes work, try running the suffix
136193323Sed  // passes on the result of the prefix passes.
137193323Sed  //
138280031Sdim  std::unique_ptr<Module> PrefixOutput =
139280031Sdim      parseInputFile(BitcodeResult, BD.getContext());
140261991Sdim  if (!PrefixOutput) {
141198090Srdivacky    errs() << BD.getToolName() << ": Error reading bitcode file '"
142198090Srdivacky           << BitcodeResult << "'!\n";
143193323Sed    exit(1);
144193323Sed  }
145261991Sdim  sys::fs::remove(BitcodeResult);
146193323Sed
147193323Sed  // Don't check if there are no passes in the suffix.
148193323Sed  if (Suffix.empty())
149193323Sed    return NoFailure;
150193323Sed
151198090Srdivacky  outs() << "Checking to see if '" << getPassesString(Suffix)
152314564Sdim         << "' passes compile correctly after the '" << getPassesString(Prefix)
153314564Sdim         << "' passes: ";
154193323Sed
155276479Sdim  std::unique_ptr<Module> OriginalInput(
156276479Sdim      BD.swapProgramIn(PrefixOutput.release()));
157314564Sdim  if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false /*delete*/,
158314564Sdim                   true /*quiet*/)) {
159198090Srdivacky    errs() << " Error running this sequence of passes"
160198090Srdivacky           << " on the input program!\n";
161193323Sed    BD.setPassesToRun(Suffix);
162314564Sdim    BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
163314564Sdim    // TODO: This should propagate the error instead of exiting.
164314564Sdim    if (Error E = BD.debugOptimizerCrash())
165314564Sdim      exit(1);
166314564Sdim    exit(0);
167193323Sed  }
168193323Sed
169193323Sed  // Run the result...
170212793Sdim  Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
171314564Sdim                        true /*delete bitcode*/);
172314564Sdim  if (Error E = Diff.takeError())
173314564Sdim    return std::move(E);
174314564Sdim  if (*Diff) {
175198090Srdivacky    outs() << " nope.\n";
176193323Sed    return KeepSuffix;
177193323Sed  }
178193323Sed
179193323Sed  // Otherwise, we must not be running the bad pass anymore.
180314564Sdim  outs() << " yup.\n"; // No miscompilation!
181208599Srdivacky  // Restore orig program & free test.
182276479Sdim  delete BD.swapProgramIn(OriginalInput.release());
183193323Sed  return NoFailure;
184193323Sed}
185193323Sed
186193323Sednamespace {
187314564Sdimclass ReduceMiscompilingFunctions : public ListReducer<Function *> {
188314564Sdim  BugDriver &BD;
189314564Sdim  Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
190314564Sdim                           std::unique_ptr<Module>);
191296417Sdim
192314564Sdimpublic:
193314564Sdim  ReduceMiscompilingFunctions(BugDriver &bd,
194314564Sdim                              Expected<bool> (*F)(BugDriver &,
195314564Sdim                                                  std::unique_ptr<Module>,
196314564Sdim                                                  std::unique_ptr<Module>))
197314564Sdim      : BD(bd), TestFn(F) {}
198193323Sed
199314564Sdim  Expected<TestResult> doTest(std::vector<Function *> &Prefix,
200314564Sdim                              std::vector<Function *> &Suffix) override {
201314564Sdim    if (!Suffix.empty()) {
202314564Sdim      Expected<bool> Ret = TestFuncs(Suffix);
203314564Sdim      if (Error E = Ret.takeError())
204314564Sdim        return std::move(E);
205314564Sdim      if (*Ret)
206314564Sdim        return KeepSuffix;
207193323Sed    }
208314564Sdim    if (!Prefix.empty()) {
209314564Sdim      Expected<bool> Ret = TestFuncs(Prefix);
210314564Sdim      if (Error E = Ret.takeError())
211314564Sdim        return std::move(E);
212314564Sdim      if (*Ret)
213314564Sdim        return KeepPrefix;
214314564Sdim    }
215314564Sdim    return NoFailure;
216314564Sdim  }
217193323Sed
218314564Sdim  Expected<bool> TestFuncs(const std::vector<Function *> &Prefix);
219314564Sdim};
220309124Sdim} // end anonymous namespace
221193323Sed
222296417Sdim/// Given two modules, link them together and run the program, checking to see
223296417Sdim/// if the program matches the diff. If there is an error, return NULL. If not,
224296417Sdim/// return the merged module. The Broken argument will be set to true if the
225296417Sdim/// output is different. If the DeleteInputs argument is set to true then this
226296417Sdim/// function deletes both input modules before it returns.
227193323Sed///
228314564Sdimstatic Expected<std::unique_ptr<Module>>
229314564SdimtestMergedProgram(const BugDriver &BD, std::unique_ptr<Module> M1,
230314564Sdim                  std::unique_ptr<Module> M2, bool &Broken) {
231296417Sdim  if (Linker::linkModules(*M1, std::move(M2)))
232314564Sdim    // TODO: Shouldn't we thread the error up instead of exiting?
233193323Sed    exit(1);
234193323Sed
235212793Sdim  // Execute the program.
236314564Sdim  Expected<bool> Diff = BD.diffProgram(M1.get(), "", "", false);
237314564Sdim  if (Error E = Diff.takeError())
238314564Sdim    return std::move(E);
239314564Sdim  Broken = *Diff;
240314564Sdim  return std::move(M1);
241193323Sed}
242193323Sed
243193323Sed/// TestFuncs - split functions in a Module into two groups: those that are
244193323Sed/// under consideration for miscompilation vs. those that are not, and test
245193323Sed/// accordingly. Each group of functions becomes a separate Module.
246193323Sed///
247314564SdimExpected<bool>
248314564SdimReduceMiscompilingFunctions::TestFuncs(const std::vector<Function *> &Funcs) {
249193323Sed  // Test to see if the function is misoptimized if we ONLY run it on the
250193323Sed  // functions listed in Funcs.
251198090Srdivacky  outs() << "Checking to see if the program is misoptimized when "
252314564Sdim         << (Funcs.size() == 1 ? "this function is" : "these functions are")
253198090Srdivacky         << " run through the pass"
254198090Srdivacky         << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
255193323Sed  PrintFunctionList(Funcs);
256198090Srdivacky  outs() << '\n';
257193323Sed
258212793Sdim  // Create a clone for two reasons:
259212793Sdim  // * If the optimization passes delete any function, the deleted function
260212793Sdim  //   will be in the clone and Funcs will still point to valid memory
261212793Sdim  // * If the optimization passes use interprocedural information to break
262212793Sdim  //   a function, we want to continue with the original function. Otherwise
263212793Sdim  //   we can conclude that a function triggers the bug when in fact one
264212793Sdim  //   needs a larger set of original functions to do so.
265218885Sdim  ValueToValueMapTy VMap;
266296417Sdim  Module *Clone = CloneModule(BD.getProgram(), VMap).release();
267212793Sdim  Module *Orig = BD.swapProgramIn(Clone);
268212793Sdim
269314564Sdim  std::vector<Function *> FuncsOnClone;
270212793Sdim  for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
271212793Sdim    Function *F = cast<Function>(VMap[Funcs[i]]);
272212793Sdim    FuncsOnClone.push_back(F);
273212793Sdim  }
274212793Sdim
275193323Sed  // Split the module into the two halves of the program we want.
276212793Sdim  VMap.clear();
277296417Sdim  std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
278296417Sdim  std::unique_ptr<Module> ToOptimize =
279296417Sdim      SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
280193323Sed
281314564Sdim  Expected<bool> Broken =
282314564Sdim      TestFn(BD, std::move(ToOptimize), std::move(ToNotOptimize));
283212793Sdim
284212793Sdim  delete BD.swapProgramIn(Orig);
285212793Sdim
286212793Sdim  return Broken;
287193323Sed}
288193323Sed
289202878Srdivacky/// DisambiguateGlobalSymbols - Give anonymous global values names.
290193323Sed///
291193323Sedstatic void DisambiguateGlobalSymbols(Module *M) {
292193323Sed  for (Module::global_iterator I = M->global_begin(), E = M->global_end();
293202878Srdivacky       I != E; ++I)
294202878Srdivacky    if (!I->hasName())
295202878Srdivacky      I->setName("anon_global");
296202878Srdivacky  for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
297202878Srdivacky    if (!I->hasName())
298202878Srdivacky      I->setName("anon_fn");
299193323Sed}
300193323Sed
301296417Sdim/// Given a reduced list of functions that still exposed the bug, check to see
302296417Sdim/// if we can extract the loops in the region without obscuring the bug.  If so,
303296417Sdim/// it reduces the amount of code identified.
304193323Sed///
305314564Sdimstatic Expected<bool>
306314564SdimExtractLoops(BugDriver &BD,
307314564Sdim             Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
308314564Sdim                                      std::unique_ptr<Module>),
309314564Sdim             std::vector<Function *> &MiscompiledFunctions) {
310193323Sed  bool MadeChange = false;
311193323Sed  while (1) {
312314564Sdim    if (BugpointIsInterrupted)
313314564Sdim      return MadeChange;
314221337Sdim
315218885Sdim    ValueToValueMapTy VMap;
316296417Sdim    std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
317296417Sdim    Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize.get(),
318296417Sdim                                                   MiscompiledFunctions, VMap)
319296417Sdim                             .release();
320296417Sdim    std::unique_ptr<Module> ToOptimizeLoopExtracted =
321296417Sdim        BD.extractLoop(ToOptimize);
322193323Sed    if (!ToOptimizeLoopExtracted) {
323193323Sed      // If the loop extractor crashed or if there were no extractible loops,
324193323Sed      // then this chapter of our odyssey is over with.
325193323Sed      delete ToOptimize;
326193323Sed      return MadeChange;
327193323Sed    }
328193323Sed
329198090Srdivacky    errs() << "Extracted a loop from the breaking portion of the program.\n";
330193323Sed
331193323Sed    // Bugpoint is intentionally not very trusting of LLVM transformations.  In
332193323Sed    // particular, we're not going to assume that the loop extractor works, so
333193323Sed    // we're going to test the newly loop extracted program to make sure nothing
334193323Sed    // has broken.  If something broke, then we'll inform the user and stop
335193323Sed    // extraction.
336193323Sed    AbstractInterpreter *AI = BD.switchToSafeInterpreter();
337212793Sdim    bool Failure;
338314564Sdim    Expected<std::unique_ptr<Module>> New =
339296417Sdim        testMergedProgram(BD, std::move(ToOptimizeLoopExtracted),
340314564Sdim                          std::move(ToNotOptimize), Failure);
341314564Sdim    if (Error E = New.takeError())
342314564Sdim      return std::move(E);
343314564Sdim    if (!*New)
344207618Srdivacky      return false;
345261991Sdim
346212793Sdim    // Delete the original and set the new program.
347314564Sdim    Module *Old = BD.swapProgramIn(New->release());
348261991Sdim    for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
349261991Sdim      MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
350261991Sdim    delete Old;
351261991Sdim
352207618Srdivacky    if (Failure) {
353193323Sed      BD.switchToInterpreter(AI);
354193323Sed
355193323Sed      // Merged program doesn't work anymore!
356198090Srdivacky      errs() << "  *** ERROR: Loop extraction broke the program. :("
357198090Srdivacky             << " Please report a bug!\n";
358198090Srdivacky      errs() << "      Continuing on with un-loop-extracted version.\n";
359193323Sed
360198090Srdivacky      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
361296417Sdim                            ToNotOptimize.get());
362198090Srdivacky      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
363198090Srdivacky                            ToOptimize);
364198090Srdivacky      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
365296417Sdim                            ToOptimizeLoopExtracted.get());
366193323Sed
367314564Sdim      errs() << "Please submit the " << OutputPrefix
368314564Sdim             << "-loop-extract-fail-*.bc files.\n";
369193323Sed      delete ToOptimize;
370193323Sed      return MadeChange;
371193323Sed    }
372193323Sed    delete ToOptimize;
373193323Sed    BD.switchToInterpreter(AI);
374193323Sed
375198090Srdivacky    outs() << "  Testing after loop extraction:\n";
376193323Sed    // Clone modules, the tester function will free them.
377296417Sdim    std::unique_ptr<Module> TOLEBackup =
378296417Sdim        CloneModule(ToOptimizeLoopExtracted.get(), VMap);
379296417Sdim    std::unique_ptr<Module> TNOBackup = CloneModule(ToNotOptimize.get(), VMap);
380261991Sdim
381261991Sdim    for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
382261991Sdim      MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
383261991Sdim
384314564Sdim    Expected<bool> Result = TestFn(BD, std::move(ToOptimizeLoopExtracted),
385314564Sdim                                   std::move(ToNotOptimize));
386314564Sdim    if (Error E = Result.takeError())
387314564Sdim      return std::move(E);
388261991Sdim
389296417Sdim    ToOptimizeLoopExtracted = std::move(TOLEBackup);
390296417Sdim    ToNotOptimize = std::move(TNOBackup);
391261991Sdim
392314564Sdim    if (!*Result) {
393198090Srdivacky      outs() << "*** Loop extraction masked the problem.  Undoing.\n";
394193323Sed      // If the program is not still broken, then loop extraction did something
395193323Sed      // that masked the error.  Stop loop extraction now.
396261991Sdim
397314564Sdim      std::vector<std::pair<std::string, FunctionType *>> MisCompFunctions;
398288943Sdim      for (Function *F : MiscompiledFunctions) {
399288943Sdim        MisCompFunctions.emplace_back(F->getName(), F->getFunctionType());
400261991Sdim      }
401261991Sdim
402296417Sdim      if (Linker::linkModules(*ToNotOptimize,
403296417Sdim                              std::move(ToOptimizeLoopExtracted)))
404261991Sdim        exit(1);
405261991Sdim
406261991Sdim      MiscompiledFunctions.clear();
407261991Sdim      for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
408261991Sdim        Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
409261991Sdim
410261991Sdim        assert(NewF && "Function not found??");
411261991Sdim        MiscompiledFunctions.push_back(NewF);
412261991Sdim      }
413261991Sdim
414296417Sdim      BD.setNewProgram(ToNotOptimize.release());
415193323Sed      return MadeChange;
416193323Sed    }
417193323Sed
418198090Srdivacky    outs() << "*** Loop extraction successful!\n";
419193323Sed
420314564Sdim    std::vector<std::pair<std::string, FunctionType *>> MisCompFunctions;
421193323Sed    for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
422314564Sdim                          E = ToOptimizeLoopExtracted->end();
423314564Sdim         I != E; ++I)
424193323Sed      if (!I->isDeclaration())
425288943Sdim        MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
426193323Sed
427193323Sed    // Okay, great!  Now we know that we extracted a loop and that loop
428193323Sed    // extraction both didn't break the program, and didn't mask the problem.
429193323Sed    // Replace the current program with the loop extracted version, and try to
430193323Sed    // extract another loop.
431296417Sdim    if (Linker::linkModules(*ToNotOptimize, std::move(ToOptimizeLoopExtracted)))
432193323Sed      exit(1);
433280031Sdim
434193323Sed    // All of the Function*'s in the MiscompiledFunctions list are in the old
435193323Sed    // module.  Update this list to include all of the functions in the
436193323Sed    // optimized and loop extracted module.
437193323Sed    MiscompiledFunctions.clear();
438193323Sed    for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
439193323Sed      Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
440221337Sdim
441193323Sed      assert(NewF && "Function not found??");
442193323Sed      MiscompiledFunctions.push_back(NewF);
443193323Sed    }
444193323Sed
445296417Sdim    BD.setNewProgram(ToNotOptimize.release());
446193323Sed    MadeChange = true;
447193323Sed  }
448193323Sed}
449193323Sed
450193323Sednamespace {
451314564Sdimclass ReduceMiscompiledBlocks : public ListReducer<BasicBlock *> {
452314564Sdim  BugDriver &BD;
453314564Sdim  Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
454314564Sdim                           std::unique_ptr<Module>);
455314564Sdim  std::vector<Function *> FunctionsBeingTested;
456193323Sed
457314564Sdimpublic:
458314564Sdim  ReduceMiscompiledBlocks(BugDriver &bd,
459314564Sdim                          Expected<bool> (*F)(BugDriver &,
460314564Sdim                                              std::unique_ptr<Module>,
461314564Sdim                                              std::unique_ptr<Module>),
462314564Sdim                          const std::vector<Function *> &Fns)
463314564Sdim      : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
464314564Sdim
465314564Sdim  Expected<TestResult> doTest(std::vector<BasicBlock *> &Prefix,
466314564Sdim                              std::vector<BasicBlock *> &Suffix) override {
467314564Sdim    if (!Suffix.empty()) {
468314564Sdim      Expected<bool> Ret = TestFuncs(Suffix);
469314564Sdim      if (Error E = Ret.takeError())
470314564Sdim        return std::move(E);
471314564Sdim      if (*Ret)
472314564Sdim        return KeepSuffix;
473193323Sed    }
474314564Sdim    if (!Prefix.empty()) {
475314564Sdim      Expected<bool> Ret = TestFuncs(Prefix);
476314564Sdim      if (Error E = Ret.takeError())
477314564Sdim        return std::move(E);
478314564Sdim      if (*Ret)
479314564Sdim        return KeepPrefix;
480314564Sdim    }
481314564Sdim    return NoFailure;
482314564Sdim  }
483193323Sed
484314564Sdim  Expected<bool> TestFuncs(const std::vector<BasicBlock *> &BBs);
485314564Sdim};
486309124Sdim} // end anonymous namespace
487193323Sed
488193323Sed/// TestFuncs - Extract all blocks for the miscompiled functions except for the
489193323Sed/// specified blocks.  If the problem still exists, return true.
490193323Sed///
491314564SdimExpected<bool>
492314564SdimReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock *> &BBs) {
493193323Sed  // Test to see if the function is misoptimized if we ONLY run it on the
494193323Sed  // functions listed in Funcs.
495198090Srdivacky  outs() << "Checking to see if the program is misoptimized when all ";
496193323Sed  if (!BBs.empty()) {
497198090Srdivacky    outs() << "but these " << BBs.size() << " blocks are extracted: ";
498193323Sed    for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
499198090Srdivacky      outs() << BBs[i]->getName() << " ";
500314564Sdim    if (BBs.size() > 10)
501314564Sdim      outs() << "...";
502193323Sed  } else {
503198090Srdivacky    outs() << "blocks are extracted.";
504193323Sed  }
505198090Srdivacky  outs() << '\n';
506193323Sed
507193323Sed  // Split the module into the two halves of the program we want.
508218885Sdim  ValueToValueMapTy VMap;
509296417Sdim  Module *Clone = CloneModule(BD.getProgram(), VMap).release();
510212793Sdim  Module *Orig = BD.swapProgramIn(Clone);
511314564Sdim  std::vector<Function *> FuncsOnClone;
512314564Sdim  std::vector<BasicBlock *> BBsOnClone;
513212793Sdim  for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
514212793Sdim    Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
515212793Sdim    FuncsOnClone.push_back(F);
516212793Sdim  }
517212793Sdim  for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
518212793Sdim    BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
519212793Sdim    BBsOnClone.push_back(BB);
520212793Sdim  }
521212793Sdim  VMap.clear();
522212793Sdim
523296417Sdim  std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
524296417Sdim  std::unique_ptr<Module> ToOptimize =
525296417Sdim      SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
526193323Sed
527193323Sed  // Try the extraction.  If it doesn't work, then the block extractor crashed
528193323Sed  // or something, in which case bugpoint can't chase down this possibility.
529280031Sdim  if (std::unique_ptr<Module> New =
530296417Sdim          BD.extractMappedBlocksFromModule(BBsOnClone, ToOptimize.get())) {
531314564Sdim    Expected<bool> Ret = TestFn(BD, std::move(New), std::move(ToNotOptimize));
532212793Sdim    delete BD.swapProgramIn(Orig);
533212793Sdim    return Ret;
534193323Sed  }
535212793Sdim  delete BD.swapProgramIn(Orig);
536193323Sed  return false;
537193323Sed}
538193323Sed
539296417Sdim/// Given a reduced list of functions that still expose the bug, extract as many
540296417Sdim/// basic blocks from the region as possible without obscuring the bug.
541193323Sed///
542314564Sdimstatic Expected<bool>
543314564SdimExtractBlocks(BugDriver &BD,
544314564Sdim              Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
545314564Sdim                                       std::unique_ptr<Module>),
546314564Sdim              std::vector<Function *> &MiscompiledFunctions) {
547314564Sdim  if (BugpointIsInterrupted)
548314564Sdim    return false;
549221337Sdim
550314564Sdim  std::vector<BasicBlock *> Blocks;
551193323Sed  for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
552296417Sdim    for (BasicBlock &BB : *MiscompiledFunctions[i])
553296417Sdim      Blocks.push_back(&BB);
554193323Sed
555193323Sed  // Use the list reducer to identify blocks that can be extracted without
556193323Sed  // obscuring the bug.  The Blocks list will end up containing blocks that must
557193323Sed  // be retained from the original program.
558193323Sed  unsigned OldSize = Blocks.size();
559193323Sed
560193323Sed  // Check to see if all blocks are extractible first.
561314564Sdim  Expected<bool> Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
562314564Sdim                           .TestFuncs(std::vector<BasicBlock *>());
563314564Sdim  if (Error E = Ret.takeError())
564314564Sdim    return std::move(E);
565314564Sdim  if (*Ret) {
566193323Sed    Blocks.clear();
567193323Sed  } else {
568314564Sdim    Expected<bool> Ret =
569314564Sdim        ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
570314564Sdim            .reduceList(Blocks);
571314564Sdim    if (Error E = Ret.takeError())
572314564Sdim      return std::move(E);
573193323Sed    if (Blocks.size() == OldSize)
574193323Sed      return false;
575193323Sed  }
576193323Sed
577218885Sdim  ValueToValueMapTy VMap;
578296417Sdim  Module *ProgClone = CloneModule(BD.getProgram(), VMap).release();
579296417Sdim  Module *ToExtract =
580296417Sdim      SplitFunctionsOutOfModule(ProgClone, MiscompiledFunctions, VMap)
581296417Sdim          .release();
582280031Sdim  std::unique_ptr<Module> Extracted =
583280031Sdim      BD.extractMappedBlocksFromModule(Blocks, ToExtract);
584276479Sdim  if (!Extracted) {
585193323Sed    // Weird, extraction should have worked.
586198090Srdivacky    errs() << "Nondeterministic problem extracting blocks??\n";
587193323Sed    delete ProgClone;
588193323Sed    delete ToExtract;
589193323Sed    return false;
590193323Sed  }
591193323Sed
592193323Sed  // Otherwise, block extraction succeeded.  Link the two program fragments back
593193323Sed  // together.
594193323Sed  delete ToExtract;
595193323Sed
596314564Sdim  std::vector<std::pair<std::string, FunctionType *>> MisCompFunctions;
597314564Sdim  for (Module::iterator I = Extracted->begin(), E = Extracted->end(); I != E;
598314564Sdim       ++I)
599193323Sed    if (!I->isDeclaration())
600288943Sdim      MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
601193323Sed
602296417Sdim  if (Linker::linkModules(*ProgClone, std::move(Extracted)))
603193323Sed    exit(1);
604193323Sed
605193323Sed  // Set the new program and delete the old one.
606193323Sed  BD.setNewProgram(ProgClone);
607193323Sed
608193323Sed  // Update the list of miscompiled functions.
609193323Sed  MiscompiledFunctions.clear();
610193323Sed
611193323Sed  for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
612193323Sed    Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
613193323Sed    assert(NewF && "Function not found??");
614193323Sed    MiscompiledFunctions.push_back(NewF);
615193323Sed  }
616193323Sed
617193323Sed  return true;
618193323Sed}
619193323Sed
620296417Sdim/// This is a generic driver to narrow down miscompilations, either in an
621296417Sdim/// optimization or a code generator.
622193323Sed///
623314564Sdimstatic Expected<std::vector<Function *>> DebugAMiscompilation(
624314564Sdim    BugDriver &BD,
625314564Sdim    Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
626314564Sdim                             std::unique_ptr<Module>)) {
627193323Sed  // Okay, now that we have reduced the list of passes which are causing the
628193323Sed  // failure, see if we can pin down which functions are being
629193323Sed  // miscompiled... first build a list of all of the non-external functions in
630193323Sed  // the program.
631314564Sdim  std::vector<Function *> MiscompiledFunctions;
632193323Sed  Module *Prog = BD.getProgram();
633296417Sdim  for (Function &F : *Prog)
634296417Sdim    if (!F.isDeclaration())
635296417Sdim      MiscompiledFunctions.push_back(&F);
636193323Sed
637193323Sed  // Do the reduction...
638314564Sdim  if (!BugpointIsInterrupted) {
639314564Sdim    Expected<bool> Ret = ReduceMiscompilingFunctions(BD, TestFn)
640314564Sdim                             .reduceList(MiscompiledFunctions);
641314564Sdim    if (Error E = Ret.takeError()) {
642314564Sdim      errs() << "\n***Cannot reduce functions: ";
643314564Sdim      return std::move(E);
644314564Sdim    }
645223013Sdim  }
646198090Srdivacky  outs() << "\n*** The following function"
647198090Srdivacky         << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
648198090Srdivacky         << " being miscompiled: ";
649193323Sed  PrintFunctionList(MiscompiledFunctions);
650198090Srdivacky  outs() << '\n';
651193323Sed
652193323Sed  // See if we can rip any loops out of the miscompiled functions and still
653193323Sed  // trigger the problem.
654193323Sed
655207618Srdivacky  if (!BugpointIsInterrupted && !DisableLoopExtraction) {
656314564Sdim    Expected<bool> Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions);
657314564Sdim    if (Error E = Ret.takeError())
658314564Sdim      return std::move(E);
659314564Sdim    if (*Ret) {
660207618Srdivacky      // Okay, we extracted some loops and the problem still appears.  See if
661207618Srdivacky      // we can eliminate some of the created functions from being candidates.
662207618Srdivacky      DisambiguateGlobalSymbols(BD.getProgram());
663193323Sed
664207618Srdivacky      // Do the reduction...
665207618Srdivacky      if (!BugpointIsInterrupted)
666314564Sdim        Ret = ReduceMiscompilingFunctions(BD, TestFn)
667314564Sdim                  .reduceList(MiscompiledFunctions);
668314564Sdim      if (Error E = Ret.takeError())
669314564Sdim        return std::move(E);
670193323Sed
671207618Srdivacky      outs() << "\n*** The following function"
672207618Srdivacky             << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
673207618Srdivacky             << " being miscompiled: ";
674207618Srdivacky      PrintFunctionList(MiscompiledFunctions);
675207618Srdivacky      outs() << '\n';
676207618Srdivacky    }
677193323Sed  }
678193323Sed
679207618Srdivacky  if (!BugpointIsInterrupted && !DisableBlockExtraction) {
680314564Sdim    Expected<bool> Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions);
681314564Sdim    if (Error E = Ret.takeError())
682314564Sdim      return std::move(E);
683314564Sdim    if (*Ret) {
684207618Srdivacky      // Okay, we extracted some blocks and the problem still appears.  See if
685207618Srdivacky      // we can eliminate some of the created functions from being candidates.
686207618Srdivacky      DisambiguateGlobalSymbols(BD.getProgram());
687193323Sed
688207618Srdivacky      // Do the reduction...
689314564Sdim      Ret = ReduceMiscompilingFunctions(BD, TestFn)
690314564Sdim                .reduceList(MiscompiledFunctions);
691314564Sdim      if (Error E = Ret.takeError())
692314564Sdim        return std::move(E);
693193323Sed
694207618Srdivacky      outs() << "\n*** The following function"
695207618Srdivacky             << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
696207618Srdivacky             << " being miscompiled: ";
697207618Srdivacky      PrintFunctionList(MiscompiledFunctions);
698207618Srdivacky      outs() << '\n';
699207618Srdivacky    }
700193323Sed  }
701193323Sed
702193323Sed  return MiscompiledFunctions;
703193323Sed}
704193323Sed
705296417Sdim/// This is the predicate function used to check to see if the "Test" portion of
706296417Sdim/// the program is misoptimized.  If so, return true.  In any case, both module
707296417Sdim/// arguments are deleted.
708193323Sed///
709314564Sdimstatic Expected<bool> TestOptimizer(BugDriver &BD, std::unique_ptr<Module> Test,
710314564Sdim                                    std::unique_ptr<Module> Safe) {
711193323Sed  // Run the optimization passes on ToOptimize, producing a transformed version
712193323Sed  // of the functions being tested.
713198090Srdivacky  outs() << "  Optimizing functions being tested: ";
714296417Sdim  std::unique_ptr<Module> Optimized =
715309124Sdim      BD.runPassesOn(Test.get(), BD.getPassesToRun());
716309124Sdim  if (!Optimized) {
717309124Sdim    errs() << " Error running this sequence of passes"
718309124Sdim           << " on the input program!\n";
719309124Sdim    delete BD.swapProgramIn(Test.get());
720314564Sdim    BD.EmitProgressBitcode(Test.get(), "pass-error", false);
721314564Sdim    if (Error E = BD.debugOptimizerCrash())
722314564Sdim      return std::move(E);
723314564Sdim    return false;
724309124Sdim  }
725198090Srdivacky  outs() << "done.\n";
726193323Sed
727198090Srdivacky  outs() << "  Checking to see if the merged program executes correctly: ";
728212793Sdim  bool Broken;
729314564Sdim  auto Result =
730314564Sdim      testMergedProgram(BD, std::move(Optimized), std::move(Safe), Broken);
731314564Sdim  if (Error E = Result.takeError())
732314564Sdim    return std::move(E);
733314564Sdim  if (auto New = std::move(*Result)) {
734212793Sdim    outs() << (Broken ? " nope.\n" : " yup.\n");
735212793Sdim    // Delete the original and set the new program.
736296417Sdim    delete BD.swapProgramIn(New.release());
737212793Sdim  }
738193323Sed  return Broken;
739193323Sed}
740193323Sed
741193323Sed/// debugMiscompilation - This method is used when the passes selected are not
742193323Sed/// crashing, but the generated output is semantically different from the
743193323Sed/// input.
744193323Sed///
745314564SdimError BugDriver::debugMiscompilation() {
746193323Sed  // Make sure something was miscompiled...
747314564Sdim  if (!BugpointIsInterrupted) {
748314564Sdim    Expected<bool> Result =
749314564Sdim        ReduceMiscompilingPasses(*this).reduceList(PassesToRun);
750314564Sdim    if (Error E = Result.takeError())
751314564Sdim      return E;
752314564Sdim    if (!*Result)
753314564Sdim      return make_error<StringError>(
754314564Sdim          "*** Optimized program matches reference output!  No problem"
755314564Sdim          " detected...\nbugpoint can't help you with your problem!\n",
756314564Sdim          inconvertibleErrorCode());
757314564Sdim  }
758193323Sed
759198090Srdivacky  outs() << "\n*** Found miscompiling pass"
760198090Srdivacky         << (getPassesToRun().size() == 1 ? "" : "es") << ": "
761198090Srdivacky         << getPassesString(getPassesToRun()) << '\n';
762212793Sdim  EmitProgressBitcode(Program, "passinput");
763193323Sed
764314564Sdim  Expected<std::vector<Function *>> MiscompiledFunctions =
765314564Sdim      DebugAMiscompilation(*this, TestOptimizer);
766314564Sdim  if (Error E = MiscompiledFunctions.takeError())
767314564Sdim    return E;
768193323Sed
769193323Sed  // Output a bunch of bitcode files for the user...
770198090Srdivacky  outs() << "Outputting reduced bitcode files which expose the problem:\n";
771218885Sdim  ValueToValueMapTy VMap;
772296417Sdim  Module *ToNotOptimize = CloneModule(getProgram(), VMap).release();
773296417Sdim  Module *ToOptimize =
774314564Sdim      SplitFunctionsOutOfModule(ToNotOptimize, *MiscompiledFunctions, VMap)
775296417Sdim          .release();
776193323Sed
777198090Srdivacky  outs() << "  Non-optimized portion: ";
778212793Sdim  EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true);
779314564Sdim  delete ToNotOptimize; // Delete hacked module.
780193323Sed
781198090Srdivacky  outs() << "  Portion that is input to optimizer: ";
782212793Sdim  EmitProgressBitcode(ToOptimize, "tooptimize");
783314564Sdim  delete ToOptimize; // Delete hacked module.
784314564Sdim
785314564Sdim  return Error::success();
786193323Sed}
787193323Sed
788296417Sdim/// Get the specified modules ready for code generator testing.
789193323Sed///
790296417Sdimstatic void CleanupAndPrepareModules(BugDriver &BD,
791296417Sdim                                     std::unique_ptr<Module> &Test,
792193323Sed                                     Module *Safe) {
793193323Sed  // Clean up the modules, removing extra cruft that we don't need anymore...
794296417Sdim  Test = BD.performFinalCleanups(Test.get());
795193323Sed
796193323Sed  // If we are executing the JIT, we have several nasty issues to take care of.
797314564Sdim  if (!BD.isExecutingJIT())
798314564Sdim    return;
799193323Sed
800193323Sed  // First, if the main function is in the Safe module, we must add a stub to
801193323Sed  // the Test module to call into it.  Thus, we create a new function `main'
802193323Sed  // which just calls the old one.
803193323Sed  if (Function *oldMain = Safe->getFunction("main"))
804193323Sed    if (!oldMain->isDeclaration()) {
805193323Sed      // Rename it
806193323Sed      oldMain->setName("llvm_bugpoint_old_main");
807193323Sed      // Create a NEW `main' function with same type in the test module.
808296417Sdim      Function *newMain =
809296417Sdim          Function::Create(oldMain->getFunctionType(),
810296417Sdim                           GlobalValue::ExternalLinkage, "main", Test.get());
811193323Sed      // Create an `oldmain' prototype in the test module, which will
812193323Sed      // corresponds to the real main function in the same module.
813193323Sed      Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
814193323Sed                                                GlobalValue::ExternalLinkage,
815296417Sdim                                                oldMain->getName(), Test.get());
816193323Sed      // Set up and remember the argument list for the main function.
817314564Sdim      std::vector<Value *> args;
818314564Sdim      for (Function::arg_iterator I = newMain->arg_begin(),
819314564Sdim                                  E = newMain->arg_end(),
820314564Sdim                                  OI = oldMain->arg_begin();
821314564Sdim           I != E; ++I, ++OI) {
822314564Sdim        I->setName(OI->getName()); // Copy argument names from oldMain
823296417Sdim        args.push_back(&*I);
824193323Sed      }
825193323Sed
826193323Sed      // Call the old main function and return its result
827198090Srdivacky      BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
828224133Sdim      CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
829193323Sed
830193323Sed      // If the type of old function wasn't void, return value of call
831198090Srdivacky      ReturnInst::Create(Safe->getContext(), call, BB);
832193323Sed    }
833193323Sed
834193323Sed  // The second nasty issue we must deal with in the JIT is that the Safe
835193323Sed  // module cannot directly reference any functions defined in the test
836193323Sed  // module.  Instead, we use a JIT API call to dynamically resolve the
837193323Sed  // symbol.
838193323Sed
839193323Sed  // Add the resolver to the Safe module.
840193323Sed  // Prototype: void *getPointerToNamedFunction(const char* Name)
841314564Sdim  Constant *resolverFunc = Safe->getOrInsertFunction(
842314564Sdim      "getPointerToNamedFunction", Type::getInt8PtrTy(Safe->getContext()),
843314564Sdim      Type::getInt8PtrTy(Safe->getContext()), (Type *)nullptr);
844193323Sed
845193323Sed  // Use the function we just added to get addresses of functions we need.
846193323Sed  for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
847193323Sed    if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
848193323Sed        !F->isIntrinsic() /* ignore intrinsics */) {
849193323Sed      Function *TestFn = Test->getFunction(F->getName());
850193323Sed
851193323Sed      // Don't forward functions which are external in the test module too.
852193323Sed      if (TestFn && !TestFn->isDeclaration()) {
853193323Sed        // 1. Add a string constant with its name to the global file
854234353Sdim        Constant *InitArray =
855314564Sdim            ConstantDataArray::getString(F->getContext(), F->getName());
856314564Sdim        GlobalVariable *funcName = new GlobalVariable(
857314564Sdim            *Safe, InitArray->getType(), true /*isConstant*/,
858314564Sdim            GlobalValue::InternalLinkage, InitArray, F->getName() + "_name");
859193323Sed
860193323Sed        // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
861193323Sed        // sbyte* so it matches the signature of the resolver function.
862193323Sed
863193323Sed        // GetElementPtr *funcName, ulong 0, ulong 0
864314564Sdim        std::vector<Constant *> GEPargs(
865314564Sdim            2, Constant::getNullValue(Type::getInt32Ty(F->getContext())));
866288943Sdim        Value *GEP = ConstantExpr::getGetElementPtr(InitArray->getType(),
867288943Sdim                                                    funcName, GEPargs);
868314564Sdim        std::vector<Value *> ResolverArgs;
869193323Sed        ResolverArgs.push_back(GEP);
870193323Sed
871193323Sed        // Rewrite uses of F in global initializers, etc. to uses of a wrapper
872193323Sed        // function that dynamically resolves the calls to F via our JIT API
873193323Sed        if (!F->use_empty()) {
874193323Sed          // Create a new global to hold the cached function pointer.
875193323Sed          Constant *NullPtr = ConstantPointerNull::get(F->getType());
876314564Sdim          GlobalVariable *Cache = new GlobalVariable(
877314564Sdim              *F->getParent(), F->getType(), false,
878314564Sdim              GlobalValue::InternalLinkage, NullPtr, F->getName() + ".fpcache");
879193323Sed
880193323Sed          // Construct a new stub function that will re-route calls to F
881226584Sdim          FunctionType *FuncTy = F->getFunctionType();
882314564Sdim          Function *FuncWrapper =
883314564Sdim              Function::Create(FuncTy, GlobalValue::InternalLinkage,
884314564Sdim                               F->getName() + "_wrapper", F->getParent());
885314564Sdim          BasicBlock *EntryBB =
886314564Sdim              BasicBlock::Create(F->getContext(), "entry", FuncWrapper);
887314564Sdim          BasicBlock *DoCallBB =
888314564Sdim              BasicBlock::Create(F->getContext(), "usecache", FuncWrapper);
889314564Sdim          BasicBlock *LookupBB =
890314564Sdim              BasicBlock::Create(F->getContext(), "lookupfp", FuncWrapper);
891193323Sed
892193323Sed          // Check to see if we already looked up the value.
893193323Sed          Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
894198090Srdivacky          Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
895198090Srdivacky                                       NullPtr, "isNull");
896193323Sed          BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
897193323Sed
898193323Sed          // Resolve the call to function F via the JIT API:
899193323Sed          //
900193323Sed          // call resolver(GetElementPtr...)
901314564Sdim          CallInst *Resolver = CallInst::Create(resolverFunc, ResolverArgs,
902314564Sdim                                                "resolver", LookupBB);
903193323Sed
904193323Sed          // Cast the result from the resolver to correctly-typed function.
905314564Sdim          CastInst *CastedResolver = new BitCastInst(
906314564Sdim              Resolver, PointerType::getUnqual(F->getFunctionType()),
907314564Sdim              "resolverCast", LookupBB);
908193323Sed
909193323Sed          // Save the value in our cache.
910193323Sed          new StoreInst(CastedResolver, Cache, LookupBB);
911193323Sed          BranchInst::Create(DoCallBB, LookupBB);
912193323Sed
913314564Sdim          PHINode *FuncPtr =
914314564Sdim              PHINode::Create(NullPtr->getType(), 2, "fp", DoCallBB);
915193323Sed          FuncPtr->addIncoming(CastedResolver, LookupBB);
916193323Sed          FuncPtr->addIncoming(CachedVal, EntryBB);
917193323Sed
918193323Sed          // Save the argument list.
919314564Sdim          std::vector<Value *> Args;
920296417Sdim          for (Argument &A : FuncWrapper->args())
921296417Sdim            Args.push_back(&A);
922193323Sed
923193323Sed          // Pass on the arguments to the real function, return its result
924210006Srdivacky          if (F->getReturnType()->isVoidTy()) {
925224133Sdim            CallInst::Create(FuncPtr, Args, "", DoCallBB);
926198090Srdivacky            ReturnInst::Create(F->getContext(), DoCallBB);
927193323Sed          } else {
928314564Sdim            CallInst *Call =
929314564Sdim                CallInst::Create(FuncPtr, Args, "retval", DoCallBB);
930314564Sdim            ReturnInst::Create(F->getContext(), Call, DoCallBB);
931193323Sed          }
932193323Sed
933193323Sed          // Use the wrapper function instead of the old function
934193323Sed          F->replaceAllUsesWith(FuncWrapper);
935193323Sed        }
936193323Sed      }
937193323Sed    }
938193323Sed  }
939193323Sed
940193323Sed  if (verifyModule(*Test) || verifyModule(*Safe)) {
941198090Srdivacky    errs() << "Bugpoint has a bug, which corrupted a module!!\n";
942193323Sed    abort();
943193323Sed  }
944193323Sed}
945193323Sed
946296417Sdim/// This is the predicate function used to check to see if the "Test" portion of
947296417Sdim/// the program is miscompiled by the code generator under test.  If so, return
948296417Sdim/// true.  In any case, both module arguments are deleted.
949193323Sed///
950314564Sdimstatic Expected<bool> TestCodeGenerator(BugDriver &BD,
951314564Sdim                                        std::unique_ptr<Module> Test,
952314564Sdim                                        std::unique_ptr<Module> Safe) {
953296417Sdim  CleanupAndPrepareModules(BD, Test, Safe.get());
954193323Sed
955261991Sdim  SmallString<128> TestModuleBC;
956261991Sdim  int TestModuleFD;
957276479Sdim  std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
958276479Sdim                                                    TestModuleFD, TestModuleBC);
959261991Sdim  if (EC) {
960314564Sdim    errs() << BD.getToolName()
961314564Sdim           << "Error making unique filename: " << EC.message() << "\n";
962193323Sed    exit(1);
963193323Sed  }
964296417Sdim  if (BD.writeProgramToFile(TestModuleBC.str(), TestModuleFD, Test.get())) {
965198090Srdivacky    errs() << "Error writing bitcode to `" << TestModuleBC.str()
966198090Srdivacky           << "'\nExiting.";
967193323Sed    exit(1);
968193323Sed  }
969193323Sed
970221337Sdim  FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
971210006Srdivacky
972193323Sed  // Make the shared library
973261991Sdim  SmallString<128> SafeModuleBC;
974261991Sdim  int SafeModuleFD;
975261991Sdim  EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
976261991Sdim                                    SafeModuleBC);
977261991Sdim  if (EC) {
978314564Sdim    errs() << BD.getToolName()
979314564Sdim           << "Error making unique filename: " << EC.message() << "\n";
980193323Sed    exit(1);
981193323Sed  }
982193323Sed
983296417Sdim  if (BD.writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, Safe.get())) {
984314564Sdim    errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
985193323Sed    exit(1);
986193323Sed  }
987210006Srdivacky
988221337Sdim  FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
989210006Srdivacky
990314564Sdim  Expected<std::string> SharedObject =
991314564Sdim      BD.compileSharedObject(SafeModuleBC.str());
992314564Sdim  if (Error E = SharedObject.takeError())
993314564Sdim    return std::move(E);
994193323Sed
995314564Sdim  FileRemover SharedObjectRemover(*SharedObject, !SaveTemps);
996210006Srdivacky
997193323Sed  // Run the code generator on the `Test' code, loading the shared library.
998193323Sed  // The function returns whether or not the new output differs from reference.
999314564Sdim  Expected<bool> Result =
1000314564Sdim      BD.diffProgram(BD.getProgram(), TestModuleBC.str(), *SharedObject, false);
1001314564Sdim  if (Error E = Result.takeError())
1002314564Sdim    return std::move(E);
1003193323Sed
1004314564Sdim  if (*Result)
1005198090Srdivacky    errs() << ": still failing!\n";
1006193323Sed  else
1007198090Srdivacky    errs() << ": didn't fail.\n";
1008193323Sed
1009193323Sed  return Result;
1010193323Sed}
1011193323Sed
1012193323Sed/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
1013193323Sed///
1014314564SdimError BugDriver::debugCodeGenerator() {
1015314564Sdim  if ((void *)SafeInterpreter == (void *)Interpreter) {
1016314564Sdim    Expected<std::string> Result =
1017314564Sdim        executeProgramSafely(Program, "bugpoint.safe.out");
1018314564Sdim    if (Result) {
1019207618Srdivacky      outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
1020207618Srdivacky             << "the reference diff.  This may be due to a\n    front-end "
1021207618Srdivacky             << "bug or a bug in the original program, but this can also "
1022207618Srdivacky             << "happen if bugpoint isn't running the program with the "
1023207618Srdivacky             << "right flags or input.\n    I left the result of executing "
1024207618Srdivacky             << "the program with the \"safe\" backend in this file for "
1025314564Sdim             << "you: '" << *Result << "'.\n";
1026207618Srdivacky    }
1027314564Sdim    return Error::success();
1028193323Sed  }
1029193323Sed
1030193323Sed  DisambiguateGlobalSymbols(Program);
1031193323Sed
1032314564Sdim  Expected<std::vector<Function *>> Funcs =
1033314564Sdim      DebugAMiscompilation(*this, TestCodeGenerator);
1034314564Sdim  if (Error E = Funcs.takeError())
1035314564Sdim    return E;
1036193323Sed
1037193323Sed  // Split the module into the two halves of the program we want.
1038218885Sdim  ValueToValueMapTy VMap;
1039296417Sdim  std::unique_ptr<Module> ToNotCodeGen = CloneModule(getProgram(), VMap);
1040296417Sdim  std::unique_ptr<Module> ToCodeGen =
1041314564Sdim      SplitFunctionsOutOfModule(ToNotCodeGen.get(), *Funcs, VMap);
1042193323Sed
1043193323Sed  // Condition the modules
1044296417Sdim  CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen.get());
1045193323Sed
1046261991Sdim  SmallString<128> TestModuleBC;
1047261991Sdim  int TestModuleFD;
1048276479Sdim  std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
1049276479Sdim                                                    TestModuleFD, TestModuleBC);
1050261991Sdim  if (EC) {
1051314564Sdim    errs() << getToolName() << "Error making unique filename: " << EC.message()
1052314564Sdim           << "\n";
1053193323Sed    exit(1);
1054193323Sed  }
1055193323Sed
1056296417Sdim  if (writeProgramToFile(TestModuleBC.str(), TestModuleFD, ToCodeGen.get())) {
1057314564Sdim    errs() << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
1058193323Sed    exit(1);
1059193323Sed  }
1060193323Sed
1061193323Sed  // Make the shared library
1062261991Sdim  SmallString<128> SafeModuleBC;
1063261991Sdim  int SafeModuleFD;
1064261991Sdim  EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
1065261991Sdim                                    SafeModuleBC);
1066261991Sdim  if (EC) {
1067314564Sdim    errs() << getToolName() << "Error making unique filename: " << EC.message()
1068314564Sdim           << "\n";
1069193323Sed    exit(1);
1070193323Sed  }
1071193323Sed
1072296417Sdim  if (writeProgramToFile(SafeModuleBC.str(), SafeModuleFD,
1073296417Sdim                         ToNotCodeGen.get())) {
1074314564Sdim    errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
1075193323Sed    exit(1);
1076193323Sed  }
1077314564Sdim  Expected<std::string> SharedObject = compileSharedObject(SafeModuleBC.str());
1078314564Sdim  if (Error E = SharedObject.takeError())
1079314564Sdim    return E;
1080193323Sed
1081198090Srdivacky  outs() << "You can reproduce the problem with the command line: \n";
1082193323Sed  if (isExecutingJIT()) {
1083314564Sdim    outs() << "  lli -load " << *SharedObject << " " << TestModuleBC;
1084193323Sed  } else {
1085314564Sdim    outs() << "  llc " << TestModuleBC << " -o " << TestModuleBC << ".s\n";
1086314564Sdim    outs() << "  cc " << *SharedObject << " " << TestModuleBC.str() << ".s -o "
1087314564Sdim           << TestModuleBC << ".exe\n";
1088314564Sdim    outs() << "  ./" << TestModuleBC << ".exe";
1089193323Sed  }
1090207618Srdivacky  for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
1091198090Srdivacky    outs() << " " << InputArgv[i];
1092198090Srdivacky  outs() << '\n';
1093198090Srdivacky  outs() << "The shared object was created with:\n  llc -march=c "
1094198090Srdivacky         << SafeModuleBC.str() << " -o temporary.c\n"
1095314564Sdim         << "  cc -xc temporary.c -O2 -o " << *SharedObject;
1096198090Srdivacky  if (TargetTriple.getArch() == Triple::sparc)
1097314564Sdim    outs() << " -G"; // Compile a shared library, `-G' for Sparc
1098198090Srdivacky  else
1099314564Sdim    outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
1100193323Sed
1101198090Srdivacky  outs() << " -fno-strict-aliasing\n";
1102198090Srdivacky
1103314564Sdim  return Error::success();
1104193323Sed}
1105