106f32e7eSjoerg //===- Miscompilation.cpp - Debug program miscompilations -----------------===//
206f32e7eSjoerg //
306f32e7eSjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
406f32e7eSjoerg // See https://llvm.org/LICENSE.txt for license information.
506f32e7eSjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606f32e7eSjoerg //
706f32e7eSjoerg //===----------------------------------------------------------------------===//
806f32e7eSjoerg //
906f32e7eSjoerg // This file implements optimizer and code generation miscompilation debugging
1006f32e7eSjoerg // support.
1106f32e7eSjoerg //
1206f32e7eSjoerg //===----------------------------------------------------------------------===//
1306f32e7eSjoerg 
1406f32e7eSjoerg #include "BugDriver.h"
1506f32e7eSjoerg #include "ListReducer.h"
1606f32e7eSjoerg #include "ToolRunner.h"
1706f32e7eSjoerg #include "llvm/Config/config.h" // for HAVE_LINK_R
1806f32e7eSjoerg #include "llvm/IR/Constants.h"
1906f32e7eSjoerg #include "llvm/IR/DerivedTypes.h"
2006f32e7eSjoerg #include "llvm/IR/Instructions.h"
2106f32e7eSjoerg #include "llvm/IR/Module.h"
2206f32e7eSjoerg #include "llvm/IR/Verifier.h"
2306f32e7eSjoerg #include "llvm/Linker/Linker.h"
2406f32e7eSjoerg #include "llvm/Pass.h"
2506f32e7eSjoerg #include "llvm/Support/CommandLine.h"
2606f32e7eSjoerg #include "llvm/Support/FileUtilities.h"
2706f32e7eSjoerg #include "llvm/Transforms/Utils/Cloning.h"
2806f32e7eSjoerg 
2906f32e7eSjoerg using namespace llvm;
3006f32e7eSjoerg 
3106f32e7eSjoerg namespace llvm {
3206f32e7eSjoerg extern cl::opt<std::string> OutputPrefix;
3306f32e7eSjoerg extern cl::list<std::string> InputArgv;
3406f32e7eSjoerg } // end namespace llvm
3506f32e7eSjoerg 
3606f32e7eSjoerg namespace {
3706f32e7eSjoerg static llvm::cl::opt<bool> DisableLoopExtraction(
3806f32e7eSjoerg     "disable-loop-extraction",
3906f32e7eSjoerg     cl::desc("Don't extract loops when searching for miscompilations"),
4006f32e7eSjoerg     cl::init(false));
4106f32e7eSjoerg static llvm::cl::opt<bool> DisableBlockExtraction(
4206f32e7eSjoerg     "disable-block-extraction",
4306f32e7eSjoerg     cl::desc("Don't extract blocks when searching for miscompilations"),
4406f32e7eSjoerg     cl::init(false));
4506f32e7eSjoerg 
4606f32e7eSjoerg class ReduceMiscompilingPasses : public ListReducer<std::string> {
4706f32e7eSjoerg   BugDriver &BD;
4806f32e7eSjoerg 
4906f32e7eSjoerg public:
ReduceMiscompilingPasses(BugDriver & bd)5006f32e7eSjoerg   ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
5106f32e7eSjoerg 
5206f32e7eSjoerg   Expected<TestResult> doTest(std::vector<std::string> &Prefix,
5306f32e7eSjoerg                               std::vector<std::string> &Suffix) override;
5406f32e7eSjoerg };
5506f32e7eSjoerg } // end anonymous namespace
5606f32e7eSjoerg 
5706f32e7eSjoerg /// TestResult - After passes have been split into a test group and a control
5806f32e7eSjoerg /// group, see if they still break the program.
5906f32e7eSjoerg ///
6006f32e7eSjoerg Expected<ReduceMiscompilingPasses::TestResult>
doTest(std::vector<std::string> & Prefix,std::vector<std::string> & Suffix)6106f32e7eSjoerg ReduceMiscompilingPasses::doTest(std::vector<std::string> &Prefix,
6206f32e7eSjoerg                                  std::vector<std::string> &Suffix) {
6306f32e7eSjoerg   // First, run the program with just the Suffix passes.  If it is still broken
6406f32e7eSjoerg   // with JUST the kept passes, discard the prefix passes.
6506f32e7eSjoerg   outs() << "Checking to see if '" << getPassesString(Suffix)
6606f32e7eSjoerg          << "' compiles correctly: ";
6706f32e7eSjoerg 
6806f32e7eSjoerg   std::string BitcodeResult;
6906f32e7eSjoerg   if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false /*delete*/,
7006f32e7eSjoerg                    true /*quiet*/)) {
7106f32e7eSjoerg     errs() << " Error running this sequence of passes"
7206f32e7eSjoerg            << " on the input program!\n";
7306f32e7eSjoerg     BD.setPassesToRun(Suffix);
7406f32e7eSjoerg     BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
7506f32e7eSjoerg     // TODO: This should propagate the error instead of exiting.
7606f32e7eSjoerg     if (Error E = BD.debugOptimizerCrash())
7706f32e7eSjoerg       exit(1);
7806f32e7eSjoerg     exit(0);
7906f32e7eSjoerg   }
8006f32e7eSjoerg 
8106f32e7eSjoerg   // Check to see if the finished program matches the reference output...
8206f32e7eSjoerg   Expected<bool> Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
8306f32e7eSjoerg                                        true /*delete bitcode*/);
8406f32e7eSjoerg   if (Error E = Diff.takeError())
8506f32e7eSjoerg     return std::move(E);
8606f32e7eSjoerg   if (*Diff) {
8706f32e7eSjoerg     outs() << " nope.\n";
8806f32e7eSjoerg     if (Suffix.empty()) {
8906f32e7eSjoerg       errs() << BD.getToolName() << ": I'm confused: the test fails when "
9006f32e7eSjoerg              << "no passes are run, nondeterministic program?\n";
9106f32e7eSjoerg       exit(1);
9206f32e7eSjoerg     }
9306f32e7eSjoerg     return KeepSuffix; // Miscompilation detected!
9406f32e7eSjoerg   }
9506f32e7eSjoerg   outs() << " yup.\n"; // No miscompilation!
9606f32e7eSjoerg 
9706f32e7eSjoerg   if (Prefix.empty())
9806f32e7eSjoerg     return NoFailure;
9906f32e7eSjoerg 
10006f32e7eSjoerg   // Next, see if the program is broken if we run the "prefix" passes first,
10106f32e7eSjoerg   // then separately run the "kept" passes.
10206f32e7eSjoerg   outs() << "Checking to see if '" << getPassesString(Prefix)
10306f32e7eSjoerg          << "' compiles correctly: ";
10406f32e7eSjoerg 
10506f32e7eSjoerg   // If it is not broken with the kept passes, it's possible that the prefix
10606f32e7eSjoerg   // passes must be run before the kept passes to break it.  If the program
10706f32e7eSjoerg   // WORKS after the prefix passes, but then fails if running the prefix AND
10806f32e7eSjoerg   // kept passes, we can update our bitcode file to include the result of the
10906f32e7eSjoerg   // prefix passes, then discard the prefix passes.
11006f32e7eSjoerg   //
11106f32e7eSjoerg   if (BD.runPasses(BD.getProgram(), Prefix, BitcodeResult, false /*delete*/,
11206f32e7eSjoerg                    true /*quiet*/)) {
11306f32e7eSjoerg     errs() << " Error running this sequence of passes"
11406f32e7eSjoerg            << " on the input program!\n";
11506f32e7eSjoerg     BD.setPassesToRun(Prefix);
11606f32e7eSjoerg     BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
11706f32e7eSjoerg     // TODO: This should propagate the error instead of exiting.
11806f32e7eSjoerg     if (Error E = BD.debugOptimizerCrash())
11906f32e7eSjoerg       exit(1);
12006f32e7eSjoerg     exit(0);
12106f32e7eSjoerg   }
12206f32e7eSjoerg 
12306f32e7eSjoerg   // If the prefix maintains the predicate by itself, only keep the prefix!
12406f32e7eSjoerg   Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "", false);
12506f32e7eSjoerg   if (Error E = Diff.takeError())
12606f32e7eSjoerg     return std::move(E);
12706f32e7eSjoerg   if (*Diff) {
12806f32e7eSjoerg     outs() << " nope.\n";
12906f32e7eSjoerg     sys::fs::remove(BitcodeResult);
13006f32e7eSjoerg     return KeepPrefix;
13106f32e7eSjoerg   }
13206f32e7eSjoerg   outs() << " yup.\n"; // No miscompilation!
13306f32e7eSjoerg 
13406f32e7eSjoerg   // Ok, so now we know that the prefix passes work, try running the suffix
13506f32e7eSjoerg   // passes on the result of the prefix passes.
13606f32e7eSjoerg   //
13706f32e7eSjoerg   std::unique_ptr<Module> PrefixOutput =
13806f32e7eSjoerg       parseInputFile(BitcodeResult, BD.getContext());
13906f32e7eSjoerg   if (!PrefixOutput) {
14006f32e7eSjoerg     errs() << BD.getToolName() << ": Error reading bitcode file '"
14106f32e7eSjoerg            << BitcodeResult << "'!\n";
14206f32e7eSjoerg     exit(1);
14306f32e7eSjoerg   }
14406f32e7eSjoerg   sys::fs::remove(BitcodeResult);
14506f32e7eSjoerg 
14606f32e7eSjoerg   // Don't check if there are no passes in the suffix.
14706f32e7eSjoerg   if (Suffix.empty())
14806f32e7eSjoerg     return NoFailure;
14906f32e7eSjoerg 
15006f32e7eSjoerg   outs() << "Checking to see if '" << getPassesString(Suffix)
15106f32e7eSjoerg          << "' passes compile correctly after the '" << getPassesString(Prefix)
15206f32e7eSjoerg          << "' passes: ";
15306f32e7eSjoerg 
15406f32e7eSjoerg   std::unique_ptr<Module> OriginalInput =
15506f32e7eSjoerg       BD.swapProgramIn(std::move(PrefixOutput));
15606f32e7eSjoerg   if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false /*delete*/,
15706f32e7eSjoerg                    true /*quiet*/)) {
15806f32e7eSjoerg     errs() << " Error running this sequence of passes"
15906f32e7eSjoerg            << " on the input program!\n";
16006f32e7eSjoerg     BD.setPassesToRun(Suffix);
16106f32e7eSjoerg     BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
16206f32e7eSjoerg     // TODO: This should propagate the error instead of exiting.
16306f32e7eSjoerg     if (Error E = BD.debugOptimizerCrash())
16406f32e7eSjoerg       exit(1);
16506f32e7eSjoerg     exit(0);
16606f32e7eSjoerg   }
16706f32e7eSjoerg 
16806f32e7eSjoerg   // Run the result...
16906f32e7eSjoerg   Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
17006f32e7eSjoerg                         true /*delete bitcode*/);
17106f32e7eSjoerg   if (Error E = Diff.takeError())
17206f32e7eSjoerg     return std::move(E);
17306f32e7eSjoerg   if (*Diff) {
17406f32e7eSjoerg     outs() << " nope.\n";
17506f32e7eSjoerg     return KeepSuffix;
17606f32e7eSjoerg   }
17706f32e7eSjoerg 
17806f32e7eSjoerg   // Otherwise, we must not be running the bad pass anymore.
17906f32e7eSjoerg   outs() << " yup.\n"; // No miscompilation!
18006f32e7eSjoerg   // Restore orig program & free test.
18106f32e7eSjoerg   BD.setNewProgram(std::move(OriginalInput));
18206f32e7eSjoerg   return NoFailure;
18306f32e7eSjoerg }
18406f32e7eSjoerg 
18506f32e7eSjoerg namespace {
18606f32e7eSjoerg class ReduceMiscompilingFunctions : public ListReducer<Function *> {
18706f32e7eSjoerg   BugDriver &BD;
18806f32e7eSjoerg   Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
18906f32e7eSjoerg                            std::unique_ptr<Module>);
19006f32e7eSjoerg 
19106f32e7eSjoerg public:
ReduceMiscompilingFunctions(BugDriver & bd,Expected<bool> (* F)(BugDriver &,std::unique_ptr<Module>,std::unique_ptr<Module>))19206f32e7eSjoerg   ReduceMiscompilingFunctions(BugDriver &bd,
19306f32e7eSjoerg                               Expected<bool> (*F)(BugDriver &,
19406f32e7eSjoerg                                                   std::unique_ptr<Module>,
19506f32e7eSjoerg                                                   std::unique_ptr<Module>))
19606f32e7eSjoerg       : BD(bd), TestFn(F) {}
19706f32e7eSjoerg 
doTest(std::vector<Function * > & Prefix,std::vector<Function * > & Suffix)19806f32e7eSjoerg   Expected<TestResult> doTest(std::vector<Function *> &Prefix,
19906f32e7eSjoerg                               std::vector<Function *> &Suffix) override {
20006f32e7eSjoerg     if (!Suffix.empty()) {
20106f32e7eSjoerg       Expected<bool> Ret = TestFuncs(Suffix);
20206f32e7eSjoerg       if (Error E = Ret.takeError())
20306f32e7eSjoerg         return std::move(E);
20406f32e7eSjoerg       if (*Ret)
20506f32e7eSjoerg         return KeepSuffix;
20606f32e7eSjoerg     }
20706f32e7eSjoerg     if (!Prefix.empty()) {
20806f32e7eSjoerg       Expected<bool> Ret = TestFuncs(Prefix);
20906f32e7eSjoerg       if (Error E = Ret.takeError())
21006f32e7eSjoerg         return std::move(E);
21106f32e7eSjoerg       if (*Ret)
21206f32e7eSjoerg         return KeepPrefix;
21306f32e7eSjoerg     }
21406f32e7eSjoerg     return NoFailure;
21506f32e7eSjoerg   }
21606f32e7eSjoerg 
21706f32e7eSjoerg   Expected<bool> TestFuncs(const std::vector<Function *> &Prefix);
21806f32e7eSjoerg };
21906f32e7eSjoerg } // end anonymous namespace
22006f32e7eSjoerg 
22106f32e7eSjoerg /// Given two modules, link them together and run the program, checking to see
22206f32e7eSjoerg /// if the program matches the diff. If there is an error, return NULL. If not,
22306f32e7eSjoerg /// return the merged module. The Broken argument will be set to true if the
22406f32e7eSjoerg /// output is different. If the DeleteInputs argument is set to true then this
22506f32e7eSjoerg /// function deletes both input modules before it returns.
22606f32e7eSjoerg ///
testMergedProgram(const BugDriver & BD,const Module & M1,const Module & M2,bool & Broken)22706f32e7eSjoerg static Expected<std::unique_ptr<Module>> testMergedProgram(const BugDriver &BD,
22806f32e7eSjoerg                                                            const Module &M1,
22906f32e7eSjoerg                                                            const Module &M2,
23006f32e7eSjoerg                                                            bool &Broken) {
23106f32e7eSjoerg   // Resulting merge of M1 and M2.
23206f32e7eSjoerg   auto Merged = CloneModule(M1);
23306f32e7eSjoerg   if (Linker::linkModules(*Merged, CloneModule(M2)))
23406f32e7eSjoerg     // TODO: Shouldn't we thread the error up instead of exiting?
23506f32e7eSjoerg     exit(1);
23606f32e7eSjoerg 
23706f32e7eSjoerg   // Execute the program.
23806f32e7eSjoerg   Expected<bool> Diff = BD.diffProgram(*Merged, "", "", false);
23906f32e7eSjoerg   if (Error E = Diff.takeError())
24006f32e7eSjoerg     return std::move(E);
24106f32e7eSjoerg   Broken = *Diff;
24206f32e7eSjoerg   return std::move(Merged);
24306f32e7eSjoerg }
24406f32e7eSjoerg 
24506f32e7eSjoerg /// split functions in a Module into two groups: those that are under
24606f32e7eSjoerg /// consideration for miscompilation vs. those that are not, and test
24706f32e7eSjoerg /// accordingly. Each group of functions becomes a separate Module.
24806f32e7eSjoerg Expected<bool>
TestFuncs(const std::vector<Function * > & Funcs)24906f32e7eSjoerg ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function *> &Funcs) {
25006f32e7eSjoerg   // Test to see if the function is misoptimized if we ONLY run it on the
25106f32e7eSjoerg   // functions listed in Funcs.
25206f32e7eSjoerg   outs() << "Checking to see if the program is misoptimized when "
25306f32e7eSjoerg          << (Funcs.size() == 1 ? "this function is" : "these functions are")
25406f32e7eSjoerg          << " run through the pass"
25506f32e7eSjoerg          << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
25606f32e7eSjoerg   PrintFunctionList(Funcs);
25706f32e7eSjoerg   outs() << '\n';
25806f32e7eSjoerg 
25906f32e7eSjoerg   // Create a clone for two reasons:
26006f32e7eSjoerg   // * If the optimization passes delete any function, the deleted function
26106f32e7eSjoerg   //   will be in the clone and Funcs will still point to valid memory
26206f32e7eSjoerg   // * If the optimization passes use interprocedural information to break
26306f32e7eSjoerg   //   a function, we want to continue with the original function. Otherwise
26406f32e7eSjoerg   //   we can conclude that a function triggers the bug when in fact one
26506f32e7eSjoerg   //   needs a larger set of original functions to do so.
26606f32e7eSjoerg   ValueToValueMapTy VMap;
26706f32e7eSjoerg   std::unique_ptr<Module> Clone = CloneModule(BD.getProgram(), VMap);
26806f32e7eSjoerg   std::unique_ptr<Module> Orig = BD.swapProgramIn(std::move(Clone));
26906f32e7eSjoerg 
27006f32e7eSjoerg   std::vector<Function *> FuncsOnClone;
27106f32e7eSjoerg   for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
27206f32e7eSjoerg     Function *F = cast<Function>(VMap[Funcs[i]]);
27306f32e7eSjoerg     FuncsOnClone.push_back(F);
27406f32e7eSjoerg   }
27506f32e7eSjoerg 
27606f32e7eSjoerg   // Split the module into the two halves of the program we want.
27706f32e7eSjoerg   VMap.clear();
27806f32e7eSjoerg   std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
27906f32e7eSjoerg   std::unique_ptr<Module> ToOptimize =
28006f32e7eSjoerg       SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
28106f32e7eSjoerg 
28206f32e7eSjoerg   Expected<bool> Broken =
28306f32e7eSjoerg       TestFn(BD, std::move(ToOptimize), std::move(ToNotOptimize));
28406f32e7eSjoerg 
28506f32e7eSjoerg   BD.setNewProgram(std::move(Orig));
28606f32e7eSjoerg 
28706f32e7eSjoerg   return Broken;
28806f32e7eSjoerg }
28906f32e7eSjoerg 
29006f32e7eSjoerg /// Give anonymous global values names.
DisambiguateGlobalSymbols(Module & M)29106f32e7eSjoerg static void DisambiguateGlobalSymbols(Module &M) {
29206f32e7eSjoerg   for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E;
29306f32e7eSjoerg        ++I)
29406f32e7eSjoerg     if (!I->hasName())
29506f32e7eSjoerg       I->setName("anon_global");
29606f32e7eSjoerg   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
29706f32e7eSjoerg     if (!I->hasName())
29806f32e7eSjoerg       I->setName("anon_fn");
29906f32e7eSjoerg }
30006f32e7eSjoerg 
30106f32e7eSjoerg /// Given a reduced list of functions that still exposed the bug, check to see
30206f32e7eSjoerg /// if we can extract the loops in the region without obscuring the bug.  If so,
30306f32e7eSjoerg /// it reduces the amount of code identified.
30406f32e7eSjoerg ///
30506f32e7eSjoerg static Expected<bool>
ExtractLoops(BugDriver & BD,Expected<bool> (* TestFn)(BugDriver &,std::unique_ptr<Module>,std::unique_ptr<Module>),std::vector<Function * > & MiscompiledFunctions)30606f32e7eSjoerg ExtractLoops(BugDriver &BD,
30706f32e7eSjoerg              Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
30806f32e7eSjoerg                                       std::unique_ptr<Module>),
30906f32e7eSjoerg              std::vector<Function *> &MiscompiledFunctions) {
31006f32e7eSjoerg   bool MadeChange = false;
31106f32e7eSjoerg   while (1) {
31206f32e7eSjoerg     if (BugpointIsInterrupted)
31306f32e7eSjoerg       return MadeChange;
31406f32e7eSjoerg 
31506f32e7eSjoerg     ValueToValueMapTy VMap;
31606f32e7eSjoerg     std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
31706f32e7eSjoerg     std::unique_ptr<Module> ToOptimize = SplitFunctionsOutOfModule(
31806f32e7eSjoerg         ToNotOptimize.get(), MiscompiledFunctions, VMap);
31906f32e7eSjoerg     std::unique_ptr<Module> ToOptimizeLoopExtracted =
32006f32e7eSjoerg         BD.extractLoop(ToOptimize.get());
32106f32e7eSjoerg     if (!ToOptimizeLoopExtracted)
32206f32e7eSjoerg       // If the loop extractor crashed or if there were no extractible loops,
32306f32e7eSjoerg       // then this chapter of our odyssey is over with.
32406f32e7eSjoerg       return MadeChange;
32506f32e7eSjoerg 
32606f32e7eSjoerg     errs() << "Extracted a loop from the breaking portion of the program.\n";
32706f32e7eSjoerg 
32806f32e7eSjoerg     // Bugpoint is intentionally not very trusting of LLVM transformations.  In
32906f32e7eSjoerg     // particular, we're not going to assume that the loop extractor works, so
33006f32e7eSjoerg     // we're going to test the newly loop extracted program to make sure nothing
33106f32e7eSjoerg     // has broken.  If something broke, then we'll inform the user and stop
33206f32e7eSjoerg     // extraction.
33306f32e7eSjoerg     AbstractInterpreter *AI = BD.switchToSafeInterpreter();
33406f32e7eSjoerg     bool Failure;
33506f32e7eSjoerg     Expected<std::unique_ptr<Module>> New = testMergedProgram(
33606f32e7eSjoerg         BD, *ToOptimizeLoopExtracted, *ToNotOptimize, Failure);
33706f32e7eSjoerg     if (Error E = New.takeError())
33806f32e7eSjoerg       return std::move(E);
33906f32e7eSjoerg     if (!*New)
34006f32e7eSjoerg       return false;
34106f32e7eSjoerg 
34206f32e7eSjoerg     // Delete the original and set the new program.
34306f32e7eSjoerg     std::unique_ptr<Module> Old = BD.swapProgramIn(std::move(*New));
34406f32e7eSjoerg     for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
34506f32e7eSjoerg       MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
34606f32e7eSjoerg 
34706f32e7eSjoerg     if (Failure) {
34806f32e7eSjoerg       BD.switchToInterpreter(AI);
34906f32e7eSjoerg 
35006f32e7eSjoerg       // Merged program doesn't work anymore!
35106f32e7eSjoerg       errs() << "  *** ERROR: Loop extraction broke the program. :("
35206f32e7eSjoerg              << " Please report a bug!\n";
35306f32e7eSjoerg       errs() << "      Continuing on with un-loop-extracted version.\n";
35406f32e7eSjoerg 
35506f32e7eSjoerg       BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
35606f32e7eSjoerg                             *ToNotOptimize);
35706f32e7eSjoerg       BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
35806f32e7eSjoerg                             *ToOptimize);
35906f32e7eSjoerg       BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
36006f32e7eSjoerg                             *ToOptimizeLoopExtracted);
36106f32e7eSjoerg 
36206f32e7eSjoerg       errs() << "Please submit the " << OutputPrefix
36306f32e7eSjoerg              << "-loop-extract-fail-*.bc files.\n";
36406f32e7eSjoerg       return MadeChange;
36506f32e7eSjoerg     }
36606f32e7eSjoerg     BD.switchToInterpreter(AI);
36706f32e7eSjoerg 
36806f32e7eSjoerg     outs() << "  Testing after loop extraction:\n";
36906f32e7eSjoerg     // Clone modules, the tester function will free them.
37006f32e7eSjoerg     std::unique_ptr<Module> TOLEBackup =
37106f32e7eSjoerg         CloneModule(*ToOptimizeLoopExtracted, VMap);
37206f32e7eSjoerg     std::unique_ptr<Module> TNOBackup = CloneModule(*ToNotOptimize, VMap);
37306f32e7eSjoerg 
37406f32e7eSjoerg     for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
37506f32e7eSjoerg       MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
37606f32e7eSjoerg 
37706f32e7eSjoerg     Expected<bool> Result = TestFn(BD, std::move(ToOptimizeLoopExtracted),
37806f32e7eSjoerg                                    std::move(ToNotOptimize));
37906f32e7eSjoerg     if (Error E = Result.takeError())
38006f32e7eSjoerg       return std::move(E);
38106f32e7eSjoerg 
38206f32e7eSjoerg     ToOptimizeLoopExtracted = std::move(TOLEBackup);
38306f32e7eSjoerg     ToNotOptimize = std::move(TNOBackup);
38406f32e7eSjoerg 
38506f32e7eSjoerg     if (!*Result) {
38606f32e7eSjoerg       outs() << "*** Loop extraction masked the problem.  Undoing.\n";
38706f32e7eSjoerg       // If the program is not still broken, then loop extraction did something
38806f32e7eSjoerg       // that masked the error.  Stop loop extraction now.
38906f32e7eSjoerg 
39006f32e7eSjoerg       std::vector<std::pair<std::string, FunctionType *>> MisCompFunctions;
39106f32e7eSjoerg       for (Function *F : MiscompiledFunctions) {
392*da58b97aSjoerg         MisCompFunctions.emplace_back(std::string(F->getName()),
393*da58b97aSjoerg                                       F->getFunctionType());
39406f32e7eSjoerg       }
39506f32e7eSjoerg 
39606f32e7eSjoerg       if (Linker::linkModules(*ToNotOptimize,
39706f32e7eSjoerg                               std::move(ToOptimizeLoopExtracted)))
39806f32e7eSjoerg         exit(1);
39906f32e7eSjoerg 
40006f32e7eSjoerg       MiscompiledFunctions.clear();
40106f32e7eSjoerg       for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
40206f32e7eSjoerg         Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
40306f32e7eSjoerg 
40406f32e7eSjoerg         assert(NewF && "Function not found??");
40506f32e7eSjoerg         MiscompiledFunctions.push_back(NewF);
40606f32e7eSjoerg       }
40706f32e7eSjoerg 
40806f32e7eSjoerg       BD.setNewProgram(std::move(ToNotOptimize));
40906f32e7eSjoerg       return MadeChange;
41006f32e7eSjoerg     }
41106f32e7eSjoerg 
41206f32e7eSjoerg     outs() << "*** Loop extraction successful!\n";
41306f32e7eSjoerg 
41406f32e7eSjoerg     std::vector<std::pair<std::string, FunctionType *>> MisCompFunctions;
41506f32e7eSjoerg     for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
41606f32e7eSjoerg                           E = ToOptimizeLoopExtracted->end();
41706f32e7eSjoerg          I != E; ++I)
41806f32e7eSjoerg       if (!I->isDeclaration())
419*da58b97aSjoerg         MisCompFunctions.emplace_back(std::string(I->getName()),
420*da58b97aSjoerg                                       I->getFunctionType());
42106f32e7eSjoerg 
42206f32e7eSjoerg     // Okay, great!  Now we know that we extracted a loop and that loop
42306f32e7eSjoerg     // extraction both didn't break the program, and didn't mask the problem.
42406f32e7eSjoerg     // Replace the current program with the loop extracted version, and try to
42506f32e7eSjoerg     // extract another loop.
42606f32e7eSjoerg     if (Linker::linkModules(*ToNotOptimize, std::move(ToOptimizeLoopExtracted)))
42706f32e7eSjoerg       exit(1);
42806f32e7eSjoerg 
42906f32e7eSjoerg     // All of the Function*'s in the MiscompiledFunctions list are in the old
43006f32e7eSjoerg     // module.  Update this list to include all of the functions in the
43106f32e7eSjoerg     // optimized and loop extracted module.
43206f32e7eSjoerg     MiscompiledFunctions.clear();
43306f32e7eSjoerg     for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
43406f32e7eSjoerg       Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
43506f32e7eSjoerg 
43606f32e7eSjoerg       assert(NewF && "Function not found??");
43706f32e7eSjoerg       MiscompiledFunctions.push_back(NewF);
43806f32e7eSjoerg     }
43906f32e7eSjoerg 
44006f32e7eSjoerg     BD.setNewProgram(std::move(ToNotOptimize));
44106f32e7eSjoerg     MadeChange = true;
44206f32e7eSjoerg   }
44306f32e7eSjoerg }
44406f32e7eSjoerg 
44506f32e7eSjoerg namespace {
44606f32e7eSjoerg class ReduceMiscompiledBlocks : public ListReducer<BasicBlock *> {
44706f32e7eSjoerg   BugDriver &BD;
44806f32e7eSjoerg   Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
44906f32e7eSjoerg                            std::unique_ptr<Module>);
45006f32e7eSjoerg   std::vector<Function *> FunctionsBeingTested;
45106f32e7eSjoerg 
45206f32e7eSjoerg public:
ReduceMiscompiledBlocks(BugDriver & bd,Expected<bool> (* F)(BugDriver &,std::unique_ptr<Module>,std::unique_ptr<Module>),const std::vector<Function * > & Fns)45306f32e7eSjoerg   ReduceMiscompiledBlocks(BugDriver &bd,
45406f32e7eSjoerg                           Expected<bool> (*F)(BugDriver &,
45506f32e7eSjoerg                                               std::unique_ptr<Module>,
45606f32e7eSjoerg                                               std::unique_ptr<Module>),
45706f32e7eSjoerg                           const std::vector<Function *> &Fns)
45806f32e7eSjoerg       : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
45906f32e7eSjoerg 
doTest(std::vector<BasicBlock * > & Prefix,std::vector<BasicBlock * > & Suffix)46006f32e7eSjoerg   Expected<TestResult> doTest(std::vector<BasicBlock *> &Prefix,
46106f32e7eSjoerg                               std::vector<BasicBlock *> &Suffix) override {
46206f32e7eSjoerg     if (!Suffix.empty()) {
46306f32e7eSjoerg       Expected<bool> Ret = TestFuncs(Suffix);
46406f32e7eSjoerg       if (Error E = Ret.takeError())
46506f32e7eSjoerg         return std::move(E);
46606f32e7eSjoerg       if (*Ret)
46706f32e7eSjoerg         return KeepSuffix;
46806f32e7eSjoerg     }
46906f32e7eSjoerg     if (!Prefix.empty()) {
47006f32e7eSjoerg       Expected<bool> Ret = TestFuncs(Prefix);
47106f32e7eSjoerg       if (Error E = Ret.takeError())
47206f32e7eSjoerg         return std::move(E);
47306f32e7eSjoerg       if (*Ret)
47406f32e7eSjoerg         return KeepPrefix;
47506f32e7eSjoerg     }
47606f32e7eSjoerg     return NoFailure;
47706f32e7eSjoerg   }
47806f32e7eSjoerg 
47906f32e7eSjoerg   Expected<bool> TestFuncs(const std::vector<BasicBlock *> &BBs);
48006f32e7eSjoerg };
48106f32e7eSjoerg } // end anonymous namespace
48206f32e7eSjoerg 
48306f32e7eSjoerg /// TestFuncs - Extract all blocks for the miscompiled functions except for the
48406f32e7eSjoerg /// specified blocks.  If the problem still exists, return true.
48506f32e7eSjoerg ///
48606f32e7eSjoerg Expected<bool>
TestFuncs(const std::vector<BasicBlock * > & BBs)48706f32e7eSjoerg ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock *> &BBs) {
48806f32e7eSjoerg   // Test to see if the function is misoptimized if we ONLY run it on the
48906f32e7eSjoerg   // functions listed in Funcs.
49006f32e7eSjoerg   outs() << "Checking to see if the program is misoptimized when all ";
49106f32e7eSjoerg   if (!BBs.empty()) {
49206f32e7eSjoerg     outs() << "but these " << BBs.size() << " blocks are extracted: ";
49306f32e7eSjoerg     for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
49406f32e7eSjoerg       outs() << BBs[i]->getName() << " ";
49506f32e7eSjoerg     if (BBs.size() > 10)
49606f32e7eSjoerg       outs() << "...";
49706f32e7eSjoerg   } else {
49806f32e7eSjoerg     outs() << "blocks are extracted.";
49906f32e7eSjoerg   }
50006f32e7eSjoerg   outs() << '\n';
50106f32e7eSjoerg 
50206f32e7eSjoerg   // Split the module into the two halves of the program we want.
50306f32e7eSjoerg   ValueToValueMapTy VMap;
50406f32e7eSjoerg   std::unique_ptr<Module> Clone = CloneModule(BD.getProgram(), VMap);
50506f32e7eSjoerg   std::unique_ptr<Module> Orig = BD.swapProgramIn(std::move(Clone));
50606f32e7eSjoerg   std::vector<Function *> FuncsOnClone;
50706f32e7eSjoerg   std::vector<BasicBlock *> BBsOnClone;
50806f32e7eSjoerg   for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
50906f32e7eSjoerg     Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
51006f32e7eSjoerg     FuncsOnClone.push_back(F);
51106f32e7eSjoerg   }
51206f32e7eSjoerg   for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
51306f32e7eSjoerg     BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
51406f32e7eSjoerg     BBsOnClone.push_back(BB);
51506f32e7eSjoerg   }
51606f32e7eSjoerg   VMap.clear();
51706f32e7eSjoerg 
51806f32e7eSjoerg   std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
51906f32e7eSjoerg   std::unique_ptr<Module> ToOptimize =
52006f32e7eSjoerg       SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
52106f32e7eSjoerg 
52206f32e7eSjoerg   // Try the extraction.  If it doesn't work, then the block extractor crashed
52306f32e7eSjoerg   // or something, in which case bugpoint can't chase down this possibility.
52406f32e7eSjoerg   if (std::unique_ptr<Module> New =
52506f32e7eSjoerg           BD.extractMappedBlocksFromModule(BBsOnClone, ToOptimize.get())) {
52606f32e7eSjoerg     Expected<bool> Ret = TestFn(BD, std::move(New), std::move(ToNotOptimize));
52706f32e7eSjoerg     BD.setNewProgram(std::move(Orig));
52806f32e7eSjoerg     return Ret;
52906f32e7eSjoerg   }
53006f32e7eSjoerg   BD.setNewProgram(std::move(Orig));
53106f32e7eSjoerg   return false;
53206f32e7eSjoerg }
53306f32e7eSjoerg 
53406f32e7eSjoerg /// Given a reduced list of functions that still expose the bug, extract as many
53506f32e7eSjoerg /// basic blocks from the region as possible without obscuring the bug.
53606f32e7eSjoerg ///
53706f32e7eSjoerg static Expected<bool>
ExtractBlocks(BugDriver & BD,Expected<bool> (* TestFn)(BugDriver &,std::unique_ptr<Module>,std::unique_ptr<Module>),std::vector<Function * > & MiscompiledFunctions)53806f32e7eSjoerg ExtractBlocks(BugDriver &BD,
53906f32e7eSjoerg               Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
54006f32e7eSjoerg                                        std::unique_ptr<Module>),
54106f32e7eSjoerg               std::vector<Function *> &MiscompiledFunctions) {
54206f32e7eSjoerg   if (BugpointIsInterrupted)
54306f32e7eSjoerg     return false;
54406f32e7eSjoerg 
54506f32e7eSjoerg   std::vector<BasicBlock *> Blocks;
54606f32e7eSjoerg   for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
54706f32e7eSjoerg     for (BasicBlock &BB : *MiscompiledFunctions[i])
54806f32e7eSjoerg       Blocks.push_back(&BB);
54906f32e7eSjoerg 
55006f32e7eSjoerg   // Use the list reducer to identify blocks that can be extracted without
55106f32e7eSjoerg   // obscuring the bug.  The Blocks list will end up containing blocks that must
55206f32e7eSjoerg   // be retained from the original program.
55306f32e7eSjoerg   unsigned OldSize = Blocks.size();
55406f32e7eSjoerg 
55506f32e7eSjoerg   // Check to see if all blocks are extractible first.
55606f32e7eSjoerg   Expected<bool> Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
55706f32e7eSjoerg                            .TestFuncs(std::vector<BasicBlock *>());
55806f32e7eSjoerg   if (Error E = Ret.takeError())
55906f32e7eSjoerg     return std::move(E);
56006f32e7eSjoerg   if (*Ret) {
56106f32e7eSjoerg     Blocks.clear();
56206f32e7eSjoerg   } else {
56306f32e7eSjoerg     Expected<bool> Ret =
56406f32e7eSjoerg         ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
56506f32e7eSjoerg             .reduceList(Blocks);
56606f32e7eSjoerg     if (Error E = Ret.takeError())
56706f32e7eSjoerg       return std::move(E);
56806f32e7eSjoerg     if (Blocks.size() == OldSize)
56906f32e7eSjoerg       return false;
57006f32e7eSjoerg   }
57106f32e7eSjoerg 
57206f32e7eSjoerg   ValueToValueMapTy VMap;
57306f32e7eSjoerg   std::unique_ptr<Module> ProgClone = CloneModule(BD.getProgram(), VMap);
57406f32e7eSjoerg   std::unique_ptr<Module> ToExtract =
57506f32e7eSjoerg       SplitFunctionsOutOfModule(ProgClone.get(), MiscompiledFunctions, VMap);
57606f32e7eSjoerg   std::unique_ptr<Module> Extracted =
57706f32e7eSjoerg       BD.extractMappedBlocksFromModule(Blocks, ToExtract.get());
57806f32e7eSjoerg   if (!Extracted) {
57906f32e7eSjoerg     // Weird, extraction should have worked.
58006f32e7eSjoerg     errs() << "Nondeterministic problem extracting blocks??\n";
58106f32e7eSjoerg     return false;
58206f32e7eSjoerg   }
58306f32e7eSjoerg 
58406f32e7eSjoerg   // Otherwise, block extraction succeeded.  Link the two program fragments back
58506f32e7eSjoerg   // together.
58606f32e7eSjoerg 
58706f32e7eSjoerg   std::vector<std::pair<std::string, FunctionType *>> MisCompFunctions;
58806f32e7eSjoerg   for (Module::iterator I = Extracted->begin(), E = Extracted->end(); I != E;
58906f32e7eSjoerg        ++I)
59006f32e7eSjoerg     if (!I->isDeclaration())
591*da58b97aSjoerg       MisCompFunctions.emplace_back(std::string(I->getName()),
592*da58b97aSjoerg                                     I->getFunctionType());
59306f32e7eSjoerg 
59406f32e7eSjoerg   if (Linker::linkModules(*ProgClone, std::move(Extracted)))
59506f32e7eSjoerg     exit(1);
59606f32e7eSjoerg 
59706f32e7eSjoerg   // Update the list of miscompiled functions.
59806f32e7eSjoerg   MiscompiledFunctions.clear();
59906f32e7eSjoerg 
60006f32e7eSjoerg   for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
60106f32e7eSjoerg     Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
60206f32e7eSjoerg     assert(NewF && "Function not found??");
60306f32e7eSjoerg     MiscompiledFunctions.push_back(NewF);
60406f32e7eSjoerg   }
60506f32e7eSjoerg 
60606f32e7eSjoerg   // Set the new program and delete the old one.
60706f32e7eSjoerg   BD.setNewProgram(std::move(ProgClone));
60806f32e7eSjoerg 
60906f32e7eSjoerg   return true;
61006f32e7eSjoerg }
61106f32e7eSjoerg 
61206f32e7eSjoerg /// This is a generic driver to narrow down miscompilations, either in an
61306f32e7eSjoerg /// optimization or a code generator.
61406f32e7eSjoerg ///
DebugAMiscompilation(BugDriver & BD,Expected<bool> (* TestFn)(BugDriver &,std::unique_ptr<Module>,std::unique_ptr<Module>))61506f32e7eSjoerg static Expected<std::vector<Function *>> DebugAMiscompilation(
61606f32e7eSjoerg     BugDriver &BD,
61706f32e7eSjoerg     Expected<bool> (*TestFn)(BugDriver &, std::unique_ptr<Module>,
61806f32e7eSjoerg                              std::unique_ptr<Module>)) {
61906f32e7eSjoerg   // Okay, now that we have reduced the list of passes which are causing the
62006f32e7eSjoerg   // failure, see if we can pin down which functions are being
62106f32e7eSjoerg   // miscompiled... first build a list of all of the non-external functions in
62206f32e7eSjoerg   // the program.
62306f32e7eSjoerg   std::vector<Function *> MiscompiledFunctions;
62406f32e7eSjoerg   Module &Prog = BD.getProgram();
62506f32e7eSjoerg   for (Function &F : Prog)
62606f32e7eSjoerg     if (!F.isDeclaration())
62706f32e7eSjoerg       MiscompiledFunctions.push_back(&F);
62806f32e7eSjoerg 
62906f32e7eSjoerg   // Do the reduction...
63006f32e7eSjoerg   if (!BugpointIsInterrupted) {
63106f32e7eSjoerg     Expected<bool> Ret = ReduceMiscompilingFunctions(BD, TestFn)
63206f32e7eSjoerg                              .reduceList(MiscompiledFunctions);
63306f32e7eSjoerg     if (Error E = Ret.takeError()) {
63406f32e7eSjoerg       errs() << "\n***Cannot reduce functions: ";
63506f32e7eSjoerg       return std::move(E);
63606f32e7eSjoerg     }
63706f32e7eSjoerg   }
63806f32e7eSjoerg   outs() << "\n*** The following function"
63906f32e7eSjoerg          << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
64006f32e7eSjoerg          << " being miscompiled: ";
64106f32e7eSjoerg   PrintFunctionList(MiscompiledFunctions);
64206f32e7eSjoerg   outs() << '\n';
64306f32e7eSjoerg 
64406f32e7eSjoerg   // See if we can rip any loops out of the miscompiled functions and still
64506f32e7eSjoerg   // trigger the problem.
64606f32e7eSjoerg 
64706f32e7eSjoerg   if (!BugpointIsInterrupted && !DisableLoopExtraction) {
64806f32e7eSjoerg     Expected<bool> Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions);
64906f32e7eSjoerg     if (Error E = Ret.takeError())
65006f32e7eSjoerg       return std::move(E);
65106f32e7eSjoerg     if (*Ret) {
65206f32e7eSjoerg       // Okay, we extracted some loops and the problem still appears.  See if
65306f32e7eSjoerg       // we can eliminate some of the created functions from being candidates.
65406f32e7eSjoerg       DisambiguateGlobalSymbols(BD.getProgram());
65506f32e7eSjoerg 
65606f32e7eSjoerg       // Do the reduction...
65706f32e7eSjoerg       if (!BugpointIsInterrupted)
65806f32e7eSjoerg         Ret = ReduceMiscompilingFunctions(BD, TestFn)
65906f32e7eSjoerg                   .reduceList(MiscompiledFunctions);
66006f32e7eSjoerg       if (Error E = Ret.takeError())
66106f32e7eSjoerg         return std::move(E);
66206f32e7eSjoerg 
66306f32e7eSjoerg       outs() << "\n*** The following function"
66406f32e7eSjoerg              << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
66506f32e7eSjoerg              << " being miscompiled: ";
66606f32e7eSjoerg       PrintFunctionList(MiscompiledFunctions);
66706f32e7eSjoerg       outs() << '\n';
66806f32e7eSjoerg     }
66906f32e7eSjoerg   }
67006f32e7eSjoerg 
67106f32e7eSjoerg   if (!BugpointIsInterrupted && !DisableBlockExtraction) {
67206f32e7eSjoerg     Expected<bool> Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions);
67306f32e7eSjoerg     if (Error E = Ret.takeError())
67406f32e7eSjoerg       return std::move(E);
67506f32e7eSjoerg     if (*Ret) {
67606f32e7eSjoerg       // Okay, we extracted some blocks and the problem still appears.  See if
67706f32e7eSjoerg       // we can eliminate some of the created functions from being candidates.
67806f32e7eSjoerg       DisambiguateGlobalSymbols(BD.getProgram());
67906f32e7eSjoerg 
68006f32e7eSjoerg       // Do the reduction...
68106f32e7eSjoerg       Ret = ReduceMiscompilingFunctions(BD, TestFn)
68206f32e7eSjoerg                 .reduceList(MiscompiledFunctions);
68306f32e7eSjoerg       if (Error E = Ret.takeError())
68406f32e7eSjoerg         return std::move(E);
68506f32e7eSjoerg 
68606f32e7eSjoerg       outs() << "\n*** The following function"
68706f32e7eSjoerg              << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
68806f32e7eSjoerg              << " being miscompiled: ";
68906f32e7eSjoerg       PrintFunctionList(MiscompiledFunctions);
69006f32e7eSjoerg       outs() << '\n';
69106f32e7eSjoerg     }
69206f32e7eSjoerg   }
69306f32e7eSjoerg 
69406f32e7eSjoerg   return MiscompiledFunctions;
69506f32e7eSjoerg }
69606f32e7eSjoerg 
69706f32e7eSjoerg /// This is the predicate function used to check to see if the "Test" portion of
69806f32e7eSjoerg /// the program is misoptimized.  If so, return true.  In any case, both module
69906f32e7eSjoerg /// arguments are deleted.
70006f32e7eSjoerg ///
TestOptimizer(BugDriver & BD,std::unique_ptr<Module> Test,std::unique_ptr<Module> Safe)70106f32e7eSjoerg static Expected<bool> TestOptimizer(BugDriver &BD, std::unique_ptr<Module> Test,
70206f32e7eSjoerg                                     std::unique_ptr<Module> Safe) {
70306f32e7eSjoerg   // Run the optimization passes on ToOptimize, producing a transformed version
70406f32e7eSjoerg   // of the functions being tested.
70506f32e7eSjoerg   outs() << "  Optimizing functions being tested: ";
70606f32e7eSjoerg   std::unique_ptr<Module> Optimized =
70706f32e7eSjoerg       BD.runPassesOn(Test.get(), BD.getPassesToRun());
70806f32e7eSjoerg   if (!Optimized) {
70906f32e7eSjoerg     errs() << " Error running this sequence of passes"
71006f32e7eSjoerg            << " on the input program!\n";
71106f32e7eSjoerg     BD.EmitProgressBitcode(*Test, "pass-error", false);
71206f32e7eSjoerg     BD.setNewProgram(std::move(Test));
71306f32e7eSjoerg     if (Error E = BD.debugOptimizerCrash())
71406f32e7eSjoerg       return std::move(E);
71506f32e7eSjoerg     return false;
71606f32e7eSjoerg   }
71706f32e7eSjoerg   outs() << "done.\n";
71806f32e7eSjoerg 
71906f32e7eSjoerg   outs() << "  Checking to see if the merged program executes correctly: ";
72006f32e7eSjoerg   bool Broken;
72106f32e7eSjoerg   auto Result = testMergedProgram(BD, *Optimized, *Safe, Broken);
72206f32e7eSjoerg   if (Error E = Result.takeError())
72306f32e7eSjoerg     return std::move(E);
72406f32e7eSjoerg   if (auto New = std::move(*Result)) {
72506f32e7eSjoerg     outs() << (Broken ? " nope.\n" : " yup.\n");
72606f32e7eSjoerg     // Delete the original and set the new program.
72706f32e7eSjoerg     BD.setNewProgram(std::move(New));
72806f32e7eSjoerg   }
72906f32e7eSjoerg   return Broken;
73006f32e7eSjoerg }
73106f32e7eSjoerg 
73206f32e7eSjoerg /// debugMiscompilation - This method is used when the passes selected are not
73306f32e7eSjoerg /// crashing, but the generated output is semantically different from the
73406f32e7eSjoerg /// input.
73506f32e7eSjoerg ///
debugMiscompilation()73606f32e7eSjoerg Error BugDriver::debugMiscompilation() {
73706f32e7eSjoerg   // Make sure something was miscompiled...
73806f32e7eSjoerg   if (!BugpointIsInterrupted) {
73906f32e7eSjoerg     Expected<bool> Result =
74006f32e7eSjoerg         ReduceMiscompilingPasses(*this).reduceList(PassesToRun);
74106f32e7eSjoerg     if (Error E = Result.takeError())
74206f32e7eSjoerg       return E;
74306f32e7eSjoerg     if (!*Result)
74406f32e7eSjoerg       return make_error<StringError>(
74506f32e7eSjoerg           "*** Optimized program matches reference output!  No problem"
74606f32e7eSjoerg           " detected...\nbugpoint can't help you with your problem!\n",
74706f32e7eSjoerg           inconvertibleErrorCode());
74806f32e7eSjoerg   }
74906f32e7eSjoerg 
75006f32e7eSjoerg   outs() << "\n*** Found miscompiling pass"
75106f32e7eSjoerg          << (getPassesToRun().size() == 1 ? "" : "es") << ": "
75206f32e7eSjoerg          << getPassesString(getPassesToRun()) << '\n';
75306f32e7eSjoerg   EmitProgressBitcode(*Program, "passinput");
75406f32e7eSjoerg 
75506f32e7eSjoerg   Expected<std::vector<Function *>> MiscompiledFunctions =
75606f32e7eSjoerg       DebugAMiscompilation(*this, TestOptimizer);
75706f32e7eSjoerg   if (Error E = MiscompiledFunctions.takeError())
75806f32e7eSjoerg     return E;
75906f32e7eSjoerg 
76006f32e7eSjoerg   // Output a bunch of bitcode files for the user...
76106f32e7eSjoerg   outs() << "Outputting reduced bitcode files which expose the problem:\n";
76206f32e7eSjoerg   ValueToValueMapTy VMap;
76306f32e7eSjoerg   Module *ToNotOptimize = CloneModule(getProgram(), VMap).release();
76406f32e7eSjoerg   Module *ToOptimize =
76506f32e7eSjoerg       SplitFunctionsOutOfModule(ToNotOptimize, *MiscompiledFunctions, VMap)
76606f32e7eSjoerg           .release();
76706f32e7eSjoerg 
76806f32e7eSjoerg   outs() << "  Non-optimized portion: ";
76906f32e7eSjoerg   EmitProgressBitcode(*ToNotOptimize, "tonotoptimize", true);
77006f32e7eSjoerg   delete ToNotOptimize; // Delete hacked module.
77106f32e7eSjoerg 
77206f32e7eSjoerg   outs() << "  Portion that is input to optimizer: ";
77306f32e7eSjoerg   EmitProgressBitcode(*ToOptimize, "tooptimize");
77406f32e7eSjoerg   delete ToOptimize; // Delete hacked module.
77506f32e7eSjoerg 
77606f32e7eSjoerg   return Error::success();
77706f32e7eSjoerg }
77806f32e7eSjoerg 
77906f32e7eSjoerg /// Get the specified modules ready for code generator testing.
78006f32e7eSjoerg ///
78106f32e7eSjoerg static std::unique_ptr<Module>
CleanupAndPrepareModules(BugDriver & BD,std::unique_ptr<Module> Test,Module * Safe)78206f32e7eSjoerg CleanupAndPrepareModules(BugDriver &BD, std::unique_ptr<Module> Test,
78306f32e7eSjoerg                          Module *Safe) {
78406f32e7eSjoerg   // Clean up the modules, removing extra cruft that we don't need anymore...
78506f32e7eSjoerg   Test = BD.performFinalCleanups(std::move(Test));
78606f32e7eSjoerg 
78706f32e7eSjoerg   // If we are executing the JIT, we have several nasty issues to take care of.
78806f32e7eSjoerg   if (!BD.isExecutingJIT())
78906f32e7eSjoerg     return Test;
79006f32e7eSjoerg 
79106f32e7eSjoerg   // First, if the main function is in the Safe module, we must add a stub to
79206f32e7eSjoerg   // the Test module to call into it.  Thus, we create a new function `main'
79306f32e7eSjoerg   // which just calls the old one.
79406f32e7eSjoerg   if (Function *oldMain = Safe->getFunction("main"))
79506f32e7eSjoerg     if (!oldMain->isDeclaration()) {
79606f32e7eSjoerg       // Rename it
79706f32e7eSjoerg       oldMain->setName("llvm_bugpoint_old_main");
79806f32e7eSjoerg       // Create a NEW `main' function with same type in the test module.
79906f32e7eSjoerg       Function *newMain =
80006f32e7eSjoerg           Function::Create(oldMain->getFunctionType(),
80106f32e7eSjoerg                            GlobalValue::ExternalLinkage, "main", Test.get());
80206f32e7eSjoerg       // Create an `oldmain' prototype in the test module, which will
80306f32e7eSjoerg       // corresponds to the real main function in the same module.
80406f32e7eSjoerg       Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
80506f32e7eSjoerg                                                 GlobalValue::ExternalLinkage,
80606f32e7eSjoerg                                                 oldMain->getName(), Test.get());
80706f32e7eSjoerg       // Set up and remember the argument list for the main function.
80806f32e7eSjoerg       std::vector<Value *> args;
80906f32e7eSjoerg       for (Function::arg_iterator I = newMain->arg_begin(),
81006f32e7eSjoerg                                   E = newMain->arg_end(),
81106f32e7eSjoerg                                   OI = oldMain->arg_begin();
81206f32e7eSjoerg            I != E; ++I, ++OI) {
81306f32e7eSjoerg         I->setName(OI->getName()); // Copy argument names from oldMain
81406f32e7eSjoerg         args.push_back(&*I);
81506f32e7eSjoerg       }
81606f32e7eSjoerg 
81706f32e7eSjoerg       // Call the old main function and return its result
81806f32e7eSjoerg       BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
81906f32e7eSjoerg       CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
82006f32e7eSjoerg 
82106f32e7eSjoerg       // If the type of old function wasn't void, return value of call
82206f32e7eSjoerg       ReturnInst::Create(Safe->getContext(), call, BB);
82306f32e7eSjoerg     }
82406f32e7eSjoerg 
82506f32e7eSjoerg   // The second nasty issue we must deal with in the JIT is that the Safe
82606f32e7eSjoerg   // module cannot directly reference any functions defined in the test
82706f32e7eSjoerg   // module.  Instead, we use a JIT API call to dynamically resolve the
82806f32e7eSjoerg   // symbol.
82906f32e7eSjoerg 
83006f32e7eSjoerg   // Add the resolver to the Safe module.
83106f32e7eSjoerg   // Prototype: void *getPointerToNamedFunction(const char* Name)
83206f32e7eSjoerg   FunctionCallee resolverFunc = Safe->getOrInsertFunction(
83306f32e7eSjoerg       "getPointerToNamedFunction", Type::getInt8PtrTy(Safe->getContext()),
83406f32e7eSjoerg       Type::getInt8PtrTy(Safe->getContext()));
83506f32e7eSjoerg 
83606f32e7eSjoerg   // Use the function we just added to get addresses of functions we need.
83706f32e7eSjoerg   for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
83806f32e7eSjoerg     if (F->isDeclaration() && !F->use_empty() &&
83906f32e7eSjoerg         &*F != resolverFunc.getCallee() &&
84006f32e7eSjoerg         !F->isIntrinsic() /* ignore intrinsics */) {
84106f32e7eSjoerg       Function *TestFn = Test->getFunction(F->getName());
84206f32e7eSjoerg 
84306f32e7eSjoerg       // Don't forward functions which are external in the test module too.
84406f32e7eSjoerg       if (TestFn && !TestFn->isDeclaration()) {
84506f32e7eSjoerg         // 1. Add a string constant with its name to the global file
84606f32e7eSjoerg         Constant *InitArray =
84706f32e7eSjoerg             ConstantDataArray::getString(F->getContext(), F->getName());
84806f32e7eSjoerg         GlobalVariable *funcName = new GlobalVariable(
84906f32e7eSjoerg             *Safe, InitArray->getType(), true /*isConstant*/,
85006f32e7eSjoerg             GlobalValue::InternalLinkage, InitArray, F->getName() + "_name");
85106f32e7eSjoerg 
85206f32e7eSjoerg         // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
85306f32e7eSjoerg         // sbyte* so it matches the signature of the resolver function.
85406f32e7eSjoerg 
85506f32e7eSjoerg         // GetElementPtr *funcName, ulong 0, ulong 0
85606f32e7eSjoerg         std::vector<Constant *> GEPargs(
85706f32e7eSjoerg             2, Constant::getNullValue(Type::getInt32Ty(F->getContext())));
85806f32e7eSjoerg         Value *GEP = ConstantExpr::getGetElementPtr(InitArray->getType(),
85906f32e7eSjoerg                                                     funcName, GEPargs);
86006f32e7eSjoerg         std::vector<Value *> ResolverArgs;
86106f32e7eSjoerg         ResolverArgs.push_back(GEP);
86206f32e7eSjoerg 
86306f32e7eSjoerg         // Rewrite uses of F in global initializers, etc. to uses of a wrapper
86406f32e7eSjoerg         // function that dynamically resolves the calls to F via our JIT API
86506f32e7eSjoerg         if (!F->use_empty()) {
86606f32e7eSjoerg           // Create a new global to hold the cached function pointer.
86706f32e7eSjoerg           Constant *NullPtr = ConstantPointerNull::get(F->getType());
86806f32e7eSjoerg           GlobalVariable *Cache = new GlobalVariable(
86906f32e7eSjoerg               *F->getParent(), F->getType(), false,
87006f32e7eSjoerg               GlobalValue::InternalLinkage, NullPtr, F->getName() + ".fpcache");
87106f32e7eSjoerg 
87206f32e7eSjoerg           // Construct a new stub function that will re-route calls to F
87306f32e7eSjoerg           FunctionType *FuncTy = F->getFunctionType();
87406f32e7eSjoerg           Function *FuncWrapper =
87506f32e7eSjoerg               Function::Create(FuncTy, GlobalValue::InternalLinkage,
87606f32e7eSjoerg                                F->getName() + "_wrapper", F->getParent());
87706f32e7eSjoerg           BasicBlock *EntryBB =
87806f32e7eSjoerg               BasicBlock::Create(F->getContext(), "entry", FuncWrapper);
87906f32e7eSjoerg           BasicBlock *DoCallBB =
88006f32e7eSjoerg               BasicBlock::Create(F->getContext(), "usecache", FuncWrapper);
88106f32e7eSjoerg           BasicBlock *LookupBB =
88206f32e7eSjoerg               BasicBlock::Create(F->getContext(), "lookupfp", FuncWrapper);
88306f32e7eSjoerg 
88406f32e7eSjoerg           // Check to see if we already looked up the value.
88506f32e7eSjoerg           Value *CachedVal =
88606f32e7eSjoerg               new LoadInst(F->getType(), Cache, "fpcache", EntryBB);
88706f32e7eSjoerg           Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
88806f32e7eSjoerg                                        NullPtr, "isNull");
88906f32e7eSjoerg           BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
89006f32e7eSjoerg 
89106f32e7eSjoerg           // Resolve the call to function F via the JIT API:
89206f32e7eSjoerg           //
89306f32e7eSjoerg           // call resolver(GetElementPtr...)
89406f32e7eSjoerg           CallInst *Resolver = CallInst::Create(resolverFunc, ResolverArgs,
89506f32e7eSjoerg                                                 "resolver", LookupBB);
89606f32e7eSjoerg 
89706f32e7eSjoerg           // Cast the result from the resolver to correctly-typed function.
89806f32e7eSjoerg           CastInst *CastedResolver = new BitCastInst(
89906f32e7eSjoerg               Resolver, PointerType::getUnqual(F->getFunctionType()),
90006f32e7eSjoerg               "resolverCast", LookupBB);
90106f32e7eSjoerg 
90206f32e7eSjoerg           // Save the value in our cache.
90306f32e7eSjoerg           new StoreInst(CastedResolver, Cache, LookupBB);
90406f32e7eSjoerg           BranchInst::Create(DoCallBB, LookupBB);
90506f32e7eSjoerg 
90606f32e7eSjoerg           PHINode *FuncPtr =
90706f32e7eSjoerg               PHINode::Create(NullPtr->getType(), 2, "fp", DoCallBB);
90806f32e7eSjoerg           FuncPtr->addIncoming(CastedResolver, LookupBB);
90906f32e7eSjoerg           FuncPtr->addIncoming(CachedVal, EntryBB);
91006f32e7eSjoerg 
91106f32e7eSjoerg           // Save the argument list.
91206f32e7eSjoerg           std::vector<Value *> Args;
91306f32e7eSjoerg           for (Argument &A : FuncWrapper->args())
91406f32e7eSjoerg             Args.push_back(&A);
91506f32e7eSjoerg 
91606f32e7eSjoerg           // Pass on the arguments to the real function, return its result
91706f32e7eSjoerg           if (F->getReturnType()->isVoidTy()) {
91806f32e7eSjoerg             CallInst::Create(FuncTy, FuncPtr, Args, "", DoCallBB);
91906f32e7eSjoerg             ReturnInst::Create(F->getContext(), DoCallBB);
92006f32e7eSjoerg           } else {
92106f32e7eSjoerg             CallInst *Call =
92206f32e7eSjoerg                 CallInst::Create(FuncTy, FuncPtr, Args, "retval", DoCallBB);
92306f32e7eSjoerg             ReturnInst::Create(F->getContext(), Call, DoCallBB);
92406f32e7eSjoerg           }
92506f32e7eSjoerg 
92606f32e7eSjoerg           // Use the wrapper function instead of the old function
92706f32e7eSjoerg           F->replaceAllUsesWith(FuncWrapper);
92806f32e7eSjoerg         }
92906f32e7eSjoerg       }
93006f32e7eSjoerg     }
93106f32e7eSjoerg   }
93206f32e7eSjoerg 
93306f32e7eSjoerg   if (verifyModule(*Test) || verifyModule(*Safe)) {
93406f32e7eSjoerg     errs() << "Bugpoint has a bug, which corrupted a module!!\n";
93506f32e7eSjoerg     abort();
93606f32e7eSjoerg   }
93706f32e7eSjoerg 
93806f32e7eSjoerg   return Test;
93906f32e7eSjoerg }
94006f32e7eSjoerg 
94106f32e7eSjoerg /// This is the predicate function used to check to see if the "Test" portion of
94206f32e7eSjoerg /// the program is miscompiled by the code generator under test.  If so, return
94306f32e7eSjoerg /// true.  In any case, both module arguments are deleted.
94406f32e7eSjoerg ///
TestCodeGenerator(BugDriver & BD,std::unique_ptr<Module> Test,std::unique_ptr<Module> Safe)94506f32e7eSjoerg static Expected<bool> TestCodeGenerator(BugDriver &BD,
94606f32e7eSjoerg                                         std::unique_ptr<Module> Test,
94706f32e7eSjoerg                                         std::unique_ptr<Module> Safe) {
94806f32e7eSjoerg   Test = CleanupAndPrepareModules(BD, std::move(Test), Safe.get());
94906f32e7eSjoerg 
95006f32e7eSjoerg   SmallString<128> TestModuleBC;
95106f32e7eSjoerg   int TestModuleFD;
95206f32e7eSjoerg   std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
95306f32e7eSjoerg                                                     TestModuleFD, TestModuleBC);
95406f32e7eSjoerg   if (EC) {
95506f32e7eSjoerg     errs() << BD.getToolName()
95606f32e7eSjoerg            << "Error making unique filename: " << EC.message() << "\n";
95706f32e7eSjoerg     exit(1);
95806f32e7eSjoerg   }
959*da58b97aSjoerg   if (BD.writeProgramToFile(std::string(TestModuleBC.str()), TestModuleFD,
960*da58b97aSjoerg                             *Test)) {
96106f32e7eSjoerg     errs() << "Error writing bitcode to `" << TestModuleBC.str()
96206f32e7eSjoerg            << "'\nExiting.";
96306f32e7eSjoerg     exit(1);
96406f32e7eSjoerg   }
96506f32e7eSjoerg 
96606f32e7eSjoerg   FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
96706f32e7eSjoerg 
96806f32e7eSjoerg   // Make the shared library
96906f32e7eSjoerg   SmallString<128> SafeModuleBC;
97006f32e7eSjoerg   int SafeModuleFD;
97106f32e7eSjoerg   EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
97206f32e7eSjoerg                                     SafeModuleBC);
97306f32e7eSjoerg   if (EC) {
97406f32e7eSjoerg     errs() << BD.getToolName()
97506f32e7eSjoerg            << "Error making unique filename: " << EC.message() << "\n";
97606f32e7eSjoerg     exit(1);
97706f32e7eSjoerg   }
97806f32e7eSjoerg 
979*da58b97aSjoerg   if (BD.writeProgramToFile(std::string(SafeModuleBC.str()), SafeModuleFD,
980*da58b97aSjoerg                             *Safe)) {
98106f32e7eSjoerg     errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
98206f32e7eSjoerg     exit(1);
98306f32e7eSjoerg   }
98406f32e7eSjoerg 
98506f32e7eSjoerg   FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
98606f32e7eSjoerg 
98706f32e7eSjoerg   Expected<std::string> SharedObject =
988*da58b97aSjoerg       BD.compileSharedObject(std::string(SafeModuleBC.str()));
98906f32e7eSjoerg   if (Error E = SharedObject.takeError())
99006f32e7eSjoerg     return std::move(E);
99106f32e7eSjoerg 
99206f32e7eSjoerg   FileRemover SharedObjectRemover(*SharedObject, !SaveTemps);
99306f32e7eSjoerg 
99406f32e7eSjoerg   // Run the code generator on the `Test' code, loading the shared library.
99506f32e7eSjoerg   // The function returns whether or not the new output differs from reference.
996*da58b97aSjoerg   Expected<bool> Result = BD.diffProgram(
997*da58b97aSjoerg       BD.getProgram(), std::string(TestModuleBC.str()), *SharedObject, false);
99806f32e7eSjoerg   if (Error E = Result.takeError())
99906f32e7eSjoerg     return std::move(E);
100006f32e7eSjoerg 
100106f32e7eSjoerg   if (*Result)
100206f32e7eSjoerg     errs() << ": still failing!\n";
100306f32e7eSjoerg   else
100406f32e7eSjoerg     errs() << ": didn't fail.\n";
100506f32e7eSjoerg 
100606f32e7eSjoerg   return Result;
100706f32e7eSjoerg }
100806f32e7eSjoerg 
100906f32e7eSjoerg /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
101006f32e7eSjoerg ///
debugCodeGenerator()101106f32e7eSjoerg Error BugDriver::debugCodeGenerator() {
101206f32e7eSjoerg   if ((void *)SafeInterpreter == (void *)Interpreter) {
101306f32e7eSjoerg     Expected<std::string> Result =
101406f32e7eSjoerg         executeProgramSafely(*Program, "bugpoint.safe.out");
101506f32e7eSjoerg     if (Result) {
101606f32e7eSjoerg       outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
101706f32e7eSjoerg              << "the reference diff.  This may be due to a\n    front-end "
101806f32e7eSjoerg              << "bug or a bug in the original program, but this can also "
101906f32e7eSjoerg              << "happen if bugpoint isn't running the program with the "
102006f32e7eSjoerg              << "right flags or input.\n    I left the result of executing "
102106f32e7eSjoerg              << "the program with the \"safe\" backend in this file for "
102206f32e7eSjoerg              << "you: '" << *Result << "'.\n";
102306f32e7eSjoerg     }
102406f32e7eSjoerg     return Error::success();
102506f32e7eSjoerg   }
102606f32e7eSjoerg 
102706f32e7eSjoerg   DisambiguateGlobalSymbols(*Program);
102806f32e7eSjoerg 
102906f32e7eSjoerg   Expected<std::vector<Function *>> Funcs =
103006f32e7eSjoerg       DebugAMiscompilation(*this, TestCodeGenerator);
103106f32e7eSjoerg   if (Error E = Funcs.takeError())
103206f32e7eSjoerg     return E;
103306f32e7eSjoerg 
103406f32e7eSjoerg   // Split the module into the two halves of the program we want.
103506f32e7eSjoerg   ValueToValueMapTy VMap;
103606f32e7eSjoerg   std::unique_ptr<Module> ToNotCodeGen = CloneModule(getProgram(), VMap);
103706f32e7eSjoerg   std::unique_ptr<Module> ToCodeGen =
103806f32e7eSjoerg       SplitFunctionsOutOfModule(ToNotCodeGen.get(), *Funcs, VMap);
103906f32e7eSjoerg 
104006f32e7eSjoerg   // Condition the modules
104106f32e7eSjoerg   ToCodeGen =
104206f32e7eSjoerg       CleanupAndPrepareModules(*this, std::move(ToCodeGen), ToNotCodeGen.get());
104306f32e7eSjoerg 
104406f32e7eSjoerg   SmallString<128> TestModuleBC;
104506f32e7eSjoerg   int TestModuleFD;
104606f32e7eSjoerg   std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
104706f32e7eSjoerg                                                     TestModuleFD, TestModuleBC);
104806f32e7eSjoerg   if (EC) {
104906f32e7eSjoerg     errs() << getToolName() << "Error making unique filename: " << EC.message()
105006f32e7eSjoerg            << "\n";
105106f32e7eSjoerg     exit(1);
105206f32e7eSjoerg   }
105306f32e7eSjoerg 
1054*da58b97aSjoerg   if (writeProgramToFile(std::string(TestModuleBC.str()), TestModuleFD,
1055*da58b97aSjoerg                          *ToCodeGen)) {
105606f32e7eSjoerg     errs() << "Error writing bitcode to `" << TestModuleBC << "'\nExiting.";
105706f32e7eSjoerg     exit(1);
105806f32e7eSjoerg   }
105906f32e7eSjoerg 
106006f32e7eSjoerg   // Make the shared library
106106f32e7eSjoerg   SmallString<128> SafeModuleBC;
106206f32e7eSjoerg   int SafeModuleFD;
106306f32e7eSjoerg   EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
106406f32e7eSjoerg                                     SafeModuleBC);
106506f32e7eSjoerg   if (EC) {
106606f32e7eSjoerg     errs() << getToolName() << "Error making unique filename: " << EC.message()
106706f32e7eSjoerg            << "\n";
106806f32e7eSjoerg     exit(1);
106906f32e7eSjoerg   }
107006f32e7eSjoerg 
1071*da58b97aSjoerg   if (writeProgramToFile(std::string(SafeModuleBC.str()), SafeModuleFD,
1072*da58b97aSjoerg                          *ToNotCodeGen)) {
107306f32e7eSjoerg     errs() << "Error writing bitcode to `" << SafeModuleBC << "'\nExiting.";
107406f32e7eSjoerg     exit(1);
107506f32e7eSjoerg   }
1076*da58b97aSjoerg   Expected<std::string> SharedObject =
1077*da58b97aSjoerg       compileSharedObject(std::string(SafeModuleBC.str()));
107806f32e7eSjoerg   if (Error E = SharedObject.takeError())
107906f32e7eSjoerg     return E;
108006f32e7eSjoerg 
108106f32e7eSjoerg   outs() << "You can reproduce the problem with the command line: \n";
108206f32e7eSjoerg   if (isExecutingJIT()) {
108306f32e7eSjoerg     outs() << "  lli -load " << *SharedObject << " " << TestModuleBC;
108406f32e7eSjoerg   } else {
108506f32e7eSjoerg     outs() << "  llc " << TestModuleBC << " -o " << TestModuleBC << ".s\n";
108606f32e7eSjoerg     outs() << "  cc " << *SharedObject << " " << TestModuleBC.str() << ".s -o "
108706f32e7eSjoerg            << TestModuleBC << ".exe\n";
108806f32e7eSjoerg     outs() << "  ./" << TestModuleBC << ".exe";
108906f32e7eSjoerg   }
109006f32e7eSjoerg   for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
109106f32e7eSjoerg     outs() << " " << InputArgv[i];
109206f32e7eSjoerg   outs() << '\n';
109306f32e7eSjoerg   outs() << "The shared object was created with:\n  llc -march=c "
109406f32e7eSjoerg          << SafeModuleBC.str() << " -o temporary.c\n"
109506f32e7eSjoerg          << "  cc -xc temporary.c -O2 -o " << *SharedObject;
109606f32e7eSjoerg   if (TargetTriple.getArch() == Triple::sparc)
109706f32e7eSjoerg     outs() << " -G"; // Compile a shared library, `-G' for Sparc
109806f32e7eSjoerg   else
109906f32e7eSjoerg     outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
110006f32e7eSjoerg 
110106f32e7eSjoerg   outs() << " -fno-strict-aliasing\n";
110206f32e7eSjoerg 
110306f32e7eSjoerg   return Error::success();
110406f32e7eSjoerg }
1105