Miscompilation.cpp revision 84ae206c976c76761e307e5c45f8170d0b61015f
14a10645c70199c8d8567fbc46312158c419720abChris Lattner//===- Miscompilation.cpp - Debug program miscompilations -----------------===//
23da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman//
37c0e022c5c4be4b11e199a53f73bbdd84e34aa80John Criswell//                     The LLVM Compiler Infrastructure
47c0e022c5c4be4b11e199a53f73bbdd84e34aa80John Criswell//
521c62da287237d39d0d95004881ea4baae3be6daChris Lattner// This file is distributed under the University of Illinois Open Source
621c62da287237d39d0d95004881ea4baae3be6daChris Lattner// License. See LICENSE.TXT for details.
73da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman//
87c0e022c5c4be4b11e199a53f73bbdd84e34aa80John Criswell//===----------------------------------------------------------------------===//
94a10645c70199c8d8567fbc46312158c419720abChris Lattner//
10a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner// This file implements optimizer and code generation miscompilation debugging
11a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner// support.
124a10645c70199c8d8567fbc46312158c419720abChris Lattner//
134a10645c70199c8d8567fbc46312158c419720abChris Lattner//===----------------------------------------------------------------------===//
144a10645c70199c8d8567fbc46312158c419720abChris Lattner
154a10645c70199c8d8567fbc46312158c419720abChris Lattner#include "BugDriver.h"
16126840f49e8d49156a342e836d4b2adca46dc3baChris Lattner#include "ListReducer.h"
17ca7409664273fed4b473127295af3af0836b3077Daniel Dunbar#include "ToolRunner.h"
18a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner#include "llvm/Constants.h"
19a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner#include "llvm/DerivedTypes.h"
20a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner#include "llvm/Instructions.h"
21605b9e2c5bd1b0c151a0b15d01e6df3aba93d52fReid Spencer#include "llvm/Linker.h"
224a10645c70199c8d8567fbc46312158c419720abChris Lattner#include "llvm/Module.h"
23e49603d79d220a795bd50684c8b1f503ee40f97fMisha Brukman#include "llvm/Pass.h"
24a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner#include "llvm/Analysis/Verifier.h"
25640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner#include "llvm/Transforms/Utils/Cloning.h"
26551ccae044b0ff658fe629dd67edd5ffe75d10e8Reid Spencer#include "llvm/Support/CommandLine.h"
27551ccae044b0ff658fe629dd67edd5ffe75d10e8Reid Spencer#include "llvm/Support/FileUtilities.h"
2859615f0f85e2ac99e012cb81934d002faebd405aChris Lattner#include "llvm/Config/config.h"   // for HAVE_LINK_R
29fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattnerusing namespace llvm;
304a10645c70199c8d8567fbc46312158c419720abChris Lattner
31a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattnernamespace llvm {
3268ccdaa84909108c42417a8091c771598e26456eDaniel Dunbar  extern cl::opt<std::string> OutputPrefix;
33a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  extern cl::list<std::string> InputArgv;
34a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner}
35a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
36efdc0b505712d1ca4460def27e51c430f033d58dChris Lattnernamespace {
37dc31a8a70cab3b4c180ac1a482855e31d3fe8e6bReid Spencer  static llvm::cl::opt<bool>
38dc31a8a70cab3b4c180ac1a482855e31d3fe8e6bReid Spencer    DisableLoopExtraction("disable-loop-extraction",
39dc31a8a70cab3b4c180ac1a482855e31d3fe8e6bReid Spencer        cl::desc("Don't extract loops when searching for miscompilations"),
40dc31a8a70cab3b4c180ac1a482855e31d3fe8e6bReid Spencer        cl::init(false));
41265d82e4c68fa30b7ff1cb650456249f7068bdd6David Goodwin  static llvm::cl::opt<bool>
42265d82e4c68fa30b7ff1cb650456249f7068bdd6David Goodwin    DisableBlockExtraction("disable-block-extraction",
43265d82e4c68fa30b7ff1cb650456249f7068bdd6David Goodwin        cl::desc("Don't extract blocks when searching for miscompilations"),
44265d82e4c68fa30b7ff1cb650456249f7068bdd6David Goodwin        cl::init(false));
45dc31a8a70cab3b4c180ac1a482855e31d3fe8e6bReid Spencer
468be3291f5942e3ae4a5d66c480e7aabe2f771031Owen Anderson  class ReduceMiscompilingPasses : public ListReducer<const PassInfo*> {
47fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner    BugDriver &BD;
48fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner  public:
49fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner    ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
503da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
518be3291f5942e3ae4a5d66c480e7aabe2f771031Owen Anderson    virtual TestResult doTest(std::vector<const PassInfo*> &Prefix,
528be3291f5942e3ae4a5d66c480e7aabe2f771031Owen Anderson                              std::vector<const PassInfo*> &Suffix,
5322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                              std::string &Error);
54fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner  };
55fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner}
56640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
578c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman/// TestResult - After passes have been split into a test group and a control
588c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman/// group, see if they still break the program.
598c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman///
60640f22e66d90439857a97a83896ee68c4f7128c9Chris LattnerReduceMiscompilingPasses::TestResult
618be3291f5942e3ae4a5d66c480e7aabe2f771031Owen AndersonReduceMiscompilingPasses::doTest(std::vector<const PassInfo*> &Prefix,
628be3291f5942e3ae4a5d66c480e7aabe2f771031Owen Anderson                                 std::vector<const PassInfo*> &Suffix,
6322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                 std::string &Error) {
6406943add8b2b764e131979cca064eda9f28826c9Chris Lattner  // First, run the program with just the Suffix passes.  If it is still broken
65640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // with JUST the kept passes, discard the prefix passes.
66ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "Checking to see if '" << getPassesString(Suffix)
67ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman         << "' compiles correctly: ";
68640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
698ff70c2635bfd4e02c0140a5dc9ca909fffba35aGabor Greif  std::string BitcodeResult;
708ff70c2635bfd4e02c0140a5dc9ca909fffba35aGabor Greif  if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
7165f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << " Error running this sequence of passes"
7265f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman           << " on the input program!\n";
735ef681c19de9c675a265211f8fb0ae49cc3a3a66Chris Lattner    BD.setPassesToRun(Suffix);
748ff70c2635bfd4e02c0140a5dc9ca909fffba35aGabor Greif    BD.EmitProgressBitcode("pass-error",  false);
75025262692a6710de29a48e2b3905672cd12d13d2Chris Lattner    exit(BD.debugOptimizerCrash());
76640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  }
779adc0abad3c3ed40a268ccbcee0c74cb9e1359feOwen Anderson
78640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // Check to see if the finished program matches the reference output...
7922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  bool Diff = BD.diffProgram(BitcodeResult, "", true /*delete bitcode*/,
8022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                             &Error);
8122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error.empty())
8222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    return InternalError;
8322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (Diff) {
84ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    outs() << " nope.\n";
8559615f0f85e2ac99e012cb81934d002faebd405aChris Lattner    if (Suffix.empty()) {
8665f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman      errs() << BD.getToolName() << ": I'm confused: the test fails when "
8765f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman             << "no passes are run, nondeterministic program?\n";
8859615f0f85e2ac99e012cb81934d002faebd405aChris Lattner      exit(1);
8959615f0f85e2ac99e012cb81934d002faebd405aChris Lattner    }
90123f8fec94d1f22d876382897231868c62f8eabbMisha Brukman    return KeepSuffix;         // Miscompilation detected!
91640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  }
92ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << " yup.\n";      // No miscompilation!
93640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
94640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  if (Prefix.empty()) return NoFailure;
95640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
9606943add8b2b764e131979cca064eda9f28826c9Chris Lattner  // Next, see if the program is broken if we run the "prefix" passes first,
97bc0e998c497446f5448425b3cbd7f8f19a458764Misha Brukman  // then separately run the "kept" passes.
98ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "Checking to see if '" << getPassesString(Prefix)
99ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman         << "' compiles correctly: ";
100640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
101640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // If it is not broken with the kept passes, it's possible that the prefix
102640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // passes must be run before the kept passes to break it.  If the program
103640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // WORKS after the prefix passes, but then fails if running the prefix AND
1048ff70c2635bfd4e02c0140a5dc9ca909fffba35aGabor Greif  // kept passes, we can update our bitcode file to include the result of the
105640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // prefix passes, then discard the prefix passes.
106640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  //
1078ff70c2635bfd4e02c0140a5dc9ca909fffba35aGabor Greif  if (BD.runPasses(Prefix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
10865f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << " Error running this sequence of passes"
10965f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman           << " on the input program!\n";
1109c6cfe1bffd37f29a265457b7515839c445b3e6aChris Lattner    BD.setPassesToRun(Prefix);
1118ff70c2635bfd4e02c0140a5dc9ca909fffba35aGabor Greif    BD.EmitProgressBitcode("pass-error",  false);
112025262692a6710de29a48e2b3905672cd12d13d2Chris Lattner    exit(BD.debugOptimizerCrash());
113640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  }
114640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
115640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // If the prefix maintains the predicate by itself, only keep the prefix!
11622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  Diff = BD.diffProgram(BitcodeResult, "", false, &Error);
11722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error.empty())
11822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    return InternalError;
11922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (Diff) {
120ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    outs() << " nope.\n";
1218ff70c2635bfd4e02c0140a5dc9ca909fffba35aGabor Greif    sys::Path(BitcodeResult).eraseFromDisk();
122640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner    return KeepPrefix;
123640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  }
124ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << " yup.\n";      // No miscompilation!
125640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
126640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // Ok, so now we know that the prefix passes work, try running the suffix
127640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // passes on the result of the prefix passes.
128640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  //
1296865f29fe71559a18d7f2ff0bc4f67c5fc1d000eJeffrey Yasskin  OwningPtr<Module> PrefixOutput(ParseInputFile(BitcodeResult,
1306865f29fe71559a18d7f2ff0bc4f67c5fc1d000eJeffrey Yasskin                                                BD.getContext()));
131640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  if (PrefixOutput == 0) {
13265f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << BD.getToolName() << ": Error reading bitcode file '"
13365f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman           << BitcodeResult << "'!\n";
134640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner    exit(1);
135640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  }
1368ff70c2635bfd4e02c0140a5dc9ca909fffba35aGabor Greif  sys::Path(BitcodeResult).eraseFromDisk();  // No longer need the file on disk
137f4789e6d04c1fddb40092a1193c4a5eb67387accChris Lattner
138f4789e6d04c1fddb40092a1193c4a5eb67387accChris Lattner  // Don't check if there are no passes in the suffix.
139f4789e6d04c1fddb40092a1193c4a5eb67387accChris Lattner  if (Suffix.empty())
140f4789e6d04c1fddb40092a1193c4a5eb67387accChris Lattner    return NoFailure;
1413da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
142ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "Checking to see if '" << getPassesString(Suffix)
143640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner            << "' passes compile correctly after the '"
144640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner            << getPassesString(Prefix) << "' passes: ";
145640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
1466865f29fe71559a18d7f2ff0bc4f67c5fc1d000eJeffrey Yasskin  OwningPtr<Module> OriginalInput(BD.swapProgramIn(PrefixOutput.take()));
1478ff70c2635bfd4e02c0140a5dc9ca909fffba35aGabor Greif  if (BD.runPasses(Suffix, BitcodeResult, false/*delete*/, true/*quiet*/)) {
14865f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << " Error running this sequence of passes"
14965f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman           << " on the input program!\n";
1505ef681c19de9c675a265211f8fb0ae49cc3a3a66Chris Lattner    BD.setPassesToRun(Suffix);
1518ff70c2635bfd4e02c0140a5dc9ca909fffba35aGabor Greif    BD.EmitProgressBitcode("pass-error",  false);
152025262692a6710de29a48e2b3905672cd12d13d2Chris Lattner    exit(BD.debugOptimizerCrash());
153640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  }
154640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
155640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // Run the result...
15622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  Diff = BD.diffProgram(BitcodeResult, "", true /*delete bitcode*/, &Error);
15722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error.empty())
15822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    return InternalError;
15922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (Diff) {
160ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    outs() << " nope.\n";
16106943add8b2b764e131979cca064eda9f28826c9Chris Lattner    return KeepSuffix;
162640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  }
163640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
164640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // Otherwise, we must not be running the bad pass anymore.
165ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << " yup.\n";      // No miscompilation!
1666865f29fe71559a18d7f2ff0bc4f67c5fc1d000eJeffrey Yasskin  // Restore orig program & free test.
1676865f29fe71559a18d7f2ff0bc4f67c5fc1d000eJeffrey Yasskin  delete BD.swapProgramIn(OriginalInput.take());
168640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  return NoFailure;
169640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner}
170640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
171efdc0b505712d1ca4460def27e51c430f033d58dChris Lattnernamespace {
172fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner  class ReduceMiscompilingFunctions : public ListReducer<Function*> {
173fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner    BugDriver &BD;
17422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
175fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner  public:
176b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner    ReduceMiscompilingFunctions(BugDriver &bd,
17722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                bool (*F)(BugDriver &, Module *, Module *,
17822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                          std::string &))
179b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner      : BD(bd), TestFn(F) {}
1803da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
181fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner    virtual TestResult doTest(std::vector<Function*> &Prefix,
18222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                              std::vector<Function*> &Suffix,
18322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                              std::string &Error) {
18422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      if (!Suffix.empty()) {
18522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        bool Ret = TestFuncs(Suffix, Error);
18622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        if (!Error.empty())
18722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky          return InternalError;
18822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        if (Ret)
18922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky          return KeepSuffix;
19022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      }
19122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      if (!Prefix.empty()) {
19222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        bool Ret = TestFuncs(Prefix, Error);
19322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        if (!Error.empty())
19422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky          return InternalError;
19522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        if (Ret)
19622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky          return KeepPrefix;
19722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      }
198fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner      return NoFailure;
199fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner    }
2003da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
20184ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola    bool TestFuncs(const std::vector<Function*> &Prefix, std::string &Error);
202fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner  };
203fa76183e8e28985dfd17b1d6291c939dab4cbe1dChris Lattner}
204640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
205efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner/// TestMergedProgram - Given two modules, link them together and run the
206efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner/// program, checking to see if the program matches the diff.  If the diff
207a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner/// matches, return false, otherwise return true.  If the DeleteInputs argument
208a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner/// is set to true then this function deletes both input modules before it
209a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner/// returns.
2108c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman///
211a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattnerstatic bool TestMergedProgram(BugDriver &BD, Module *M1, Module *M2,
21222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                              bool DeleteInputs, std::string &Error) {
213efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner  // Link the two portions of the program back to together.
214efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner  std::string ErrorMsg;
21590c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner  if (!DeleteInputs) {
21690c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner    M1 = CloneModule(M1);
21790c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner    M2 = CloneModule(M2);
21890c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner  }
219e4874029c37c4b14d0646289f18e5f2a1b03fdc2Reid Spencer  if (Linker::LinkModules(M1, M2, &ErrorMsg)) {
22065f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << BD.getToolName() << ": Error linking modules together:"
22165f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman           << ErrorMsg << '\n';
222efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner    exit(1);
223efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner  }
22490c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner  delete M2;   // We are done with this module.
225efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner
2266865f29fe71559a18d7f2ff0bc4f67c5fc1d000eJeffrey Yasskin  OwningPtr<Module> OldProgram(BD.swapProgramIn(M1));
227efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner
228efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner  // Execute the program.  If it does not match the expected output, we must
229efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner  // return true.
23022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  bool Broken = BD.diffProgram("", "", false, &Error);
23122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error.empty()) {
23222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    // Delete the linked module & restore the original
2336865f29fe71559a18d7f2ff0bc4f67c5fc1d000eJeffrey Yasskin    delete BD.swapProgramIn(OldProgram.take());
23422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  }
235efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner  return Broken;
236efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner}
237efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner
2388c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman/// TestFuncs - split functions in a Module into two groups: those that are
2398c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman/// under consideration for miscompilation vs. those that are not, and test
2408c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman/// accordingly. Each group of functions becomes a separate Module.
2418c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman///
24284ae206c976c76761e307e5c45f8170d0b61015fRafael Espindolabool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*> &Funcs,
24384ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola                                            std::string &Error) {
244640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // Test to see if the function is misoptimized if we ONLY run it on the
245640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // functions listed in Funcs.
246ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "Checking to see if the program is misoptimized when "
247ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman         << (Funcs.size()==1 ? "this function is" : "these functions are")
248ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman         << " run through the pass"
249ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman         << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
250efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner  PrintFunctionList(Funcs);
251ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << '\n';
252640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
25384ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  // Create a clone for two reasons:
25484ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  // * If the optimization passes delete any function, the deleted function
25584ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  //   will be in the clone and Funcs will still point to valid memory
25684ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  // * If the optimization passes use interprocedural information to break
25784ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  //   a function, we want to continue with the original function. Otherwise
25884ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  //   we can conclude that a function triggers the bug when in fact one
25984ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  //   needs a larger set of original functions to do so.
260e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel  ValueMap<const Value*, Value*> VMap;
26184ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  Module *Clone = CloneModule(BD.getProgram(), VMap);
26284ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  Module *Orig = BD.swapProgramIn(Clone);
26384ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola
26484ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  std::vector<Function*> FuncsOnClone;
26584ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
26684ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola    Function *F = cast<Function>(VMap[Funcs[i]]);
26784ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola    FuncsOnClone.push_back(F);
26884ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  }
26984ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola
27084ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  // Split the module into the two halves of the program we want.
27184ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  VMap.clear();
272e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel  Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
27384ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, FuncsOnClone,
274e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel                                                 VMap);
275640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
2766fa98b13206583e6eb90b8304758b35548914944Nick Lewycky  // Run the predicate, note that the predicate will delete both input modules.
27784ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  bool Broken = TestFn(BD, ToOptimize, ToNotOptimize, Error);
27884ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola
27984ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  delete BD.swapProgramIn(Orig);
28084ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola
28184ae206c976c76761e307e5c45f8170d0b61015fRafael Espindola  return Broken;
282640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner}
283640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
2848abfb8adb2f383cab46a5e8b9fca4301effd8140Chris Lattner/// DisambiguateGlobalSymbols - Give anonymous global values names.
2858c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman///
28636ee07ff9d26a2c6ebf9faf9ba90923644db29c5Chris Lattnerstatic void DisambiguateGlobalSymbols(Module *M) {
28767ef9e43049c28c8fe2c9f70d2ad163045ee5876Chris Lattner  for (Module::global_iterator I = M->global_begin(), E = M->global_end();
2881ffb33d033d3593ded0adb08b05eb455cce59ea8Chris Lattner       I != E; ++I)
2898abfb8adb2f383cab46a5e8b9fca4301effd8140Chris Lattner    if (!I->hasName())
2908abfb8adb2f383cab46a5e8b9fca4301effd8140Chris Lattner      I->setName("anon_global");
2911ffb33d033d3593ded0adb08b05eb455cce59ea8Chris Lattner  for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
2928abfb8adb2f383cab46a5e8b9fca4301effd8140Chris Lattner    if (!I->hasName())
2938abfb8adb2f383cab46a5e8b9fca4301effd8140Chris Lattner      I->setName("anon_fn");
29436ee07ff9d26a2c6ebf9faf9ba90923644db29c5Chris Lattner}
29536ee07ff9d26a2c6ebf9faf9ba90923644db29c5Chris Lattner
296a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner/// ExtractLoops - Given a reduced list of functions that still exposed the bug,
297a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner/// check to see if we can extract the loops in the region without obscuring the
298a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner/// bug.  If so, it reduces the amount of code identified.
2998c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman///
300b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattnerstatic bool ExtractLoops(BugDriver &BD,
30122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                         bool (*TestFn)(BugDriver &, Module *, Module *,
30222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                        std::string &),
30322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                         std::vector<Function*> &MiscompiledFunctions,
30422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                         std::string &Error) {
305a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner  bool MadeChange = false;
306a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner  while (1) {
307aed98fa8861a28e5f7ba7c0659e106f2a441e9ffChris Lattner    if (BugpointIsInterrupted) return MadeChange;
308aed98fa8861a28e5f7ba7c0659e106f2a441e9ffChris Lattner
309e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel    ValueMap<const Value*, Value*> VMap;
310e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel    Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
311a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
312d50330cd02b00c8e3de40e8544c45701b9891d87Dan Gohman                                                   MiscompiledFunctions,
313e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel                                                   VMap);
314a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
315a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    if (!ToOptimizeLoopExtracted) {
316a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      // If the loop extractor crashed or if there were no extractible loops,
317a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      // then this chapter of our odyssey is over with.
318a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      delete ToNotOptimize;
319a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      delete ToOptimize;
320a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      return MadeChange;
321a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    }
322a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner
32365f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << "Extracted a loop from the breaking portion of the program.\n";
324a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner
325a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    // Bugpoint is intentionally not very trusting of LLVM transformations.  In
326a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    // particular, we're not going to assume that the loop extractor works, so
327a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    // we're going to test the newly loop extracted program to make sure nothing
328a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    // has broken.  If something broke, then we'll inform the user and stop
329a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    // extraction.
33070ef449741da8b1ef035e04a55958652a0200ba1Dan Gohman    AbstractInterpreter *AI = BD.switchToSafeInterpreter();
33122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    bool Failure = TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize,
33222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                     false, Error);
33322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (!Error.empty())
33422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      return false;
33522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (Failure) {
336a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      BD.switchToInterpreter(AI);
337a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
338a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      // Merged program doesn't work anymore!
33965f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman      errs() << "  *** ERROR: Loop extraction broke the program. :("
34065f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman             << " Please report a bug!\n";
34165f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman      errs() << "      Continuing on with un-loop-extracted version.\n";
34256c418676a308034e5eecf10d3f96ced2d1fab24Chris Lattner
34368ccdaa84909108c42417a8091c771598e26456eDaniel Dunbar      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
34468ccdaa84909108c42417a8091c771598e26456eDaniel Dunbar                            ToNotOptimize);
34568ccdaa84909108c42417a8091c771598e26456eDaniel Dunbar      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
34668ccdaa84909108c42417a8091c771598e26456eDaniel Dunbar                            ToOptimize);
34768ccdaa84909108c42417a8091c771598e26456eDaniel Dunbar      BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
34856c418676a308034e5eecf10d3f96ced2d1fab24Chris Lattner                            ToOptimizeLoopExtracted);
34956c418676a308034e5eecf10d3f96ced2d1fab24Chris Lattner
35068ccdaa84909108c42417a8091c771598e26456eDaniel Dunbar      errs() << "Please submit the "
35168ccdaa84909108c42417a8091c771598e26456eDaniel Dunbar             << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
35256c418676a308034e5eecf10d3f96ced2d1fab24Chris Lattner      delete ToOptimize;
353a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      delete ToNotOptimize;
354a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      delete ToOptimizeLoopExtracted;
355a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      return MadeChange;
356a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    }
35756c418676a308034e5eecf10d3f96ced2d1fab24Chris Lattner    delete ToOptimize;
358a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner    BD.switchToInterpreter(AI);
3593da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
360ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    outs() << "  Testing after loop extraction:\n";
361b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner    // Clone modules, the tester function will free them.
362b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner    Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
363b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner    Module *TNOBackup  = CloneModule(ToNotOptimize);
36422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    Failure = TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize, Error);
36522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (!Error.empty())
36622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      return false;
36722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (!Failure) {
368ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman      outs() << "*** Loop extraction masked the problem.  Undoing.\n";
369a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      // If the program is not still broken, then loop extraction did something
370a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      // that masked the error.  Stop loop extraction now.
371b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner      delete TOLEBackup;
372b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner      delete TNOBackup;
373a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      return MadeChange;
374a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    }
375b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner    ToOptimizeLoopExtracted = TOLEBackup;
376b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner    ToNotOptimize = TNOBackup;
377b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner
378ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    outs() << "*** Loop extraction successful!\n";
379a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner
38090c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner    std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
38190c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner    for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
38290c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner           E = ToOptimizeLoopExtracted->end(); I != E; ++I)
3835cbf985dcbc89fba3208e7baf8b6f488b06d3ec9Reid Spencer      if (!I->isDeclaration())
384fa1af1344910ee975f50ffdddf605c26f80ef016Chris Lattner        MisCompFunctions.push_back(std::make_pair(I->getName(),
385fa1af1344910ee975f50ffdddf605c26f80ef016Chris Lattner                                                  I->getFunctionType()));
38690c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner
387a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    // Okay, great!  Now we know that we extracted a loop and that loop
388a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    // extraction both didn't break the program, and didn't mask the problem.
389a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    // Replace the current program with the loop extracted version, and try to
390a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    // extract another loop.
391a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    std::string ErrorMsg;
392e4874029c37c4b14d0646289f18e5f2a1b03fdc2Reid Spencer    if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
39365f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman      errs() << BD.getToolName() << ": Error linking modules together:"
39465f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman             << ErrorMsg << '\n';
395a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner      exit(1);
396a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    }
39790c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner    delete ToOptimizeLoopExtracted;
398d3a533d94dae1e57194001af08763eb3ba199c8fChris Lattner
399d3a533d94dae1e57194001af08763eb3ba199c8fChris Lattner    // All of the Function*'s in the MiscompiledFunctions list are in the old
4005313f23b8c3d22a2028beb731c60fc1a25beb149Chris Lattner    // module.  Update this list to include all of the functions in the
4015313f23b8c3d22a2028beb731c60fc1a25beb149Chris Lattner    // optimized and loop extracted module.
4025313f23b8c3d22a2028beb731c60fc1a25beb149Chris Lattner    MiscompiledFunctions.clear();
40390c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner    for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
404ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer      Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
405ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer
40690c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner      assert(NewF && "Function not found??");
407ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer      assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
408ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer             "found wrong function type?");
40990c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner      MiscompiledFunctions.push_back(NewF);
410d3a533d94dae1e57194001af08763eb3ba199c8fChris Lattner    }
411d3a533d94dae1e57194001af08763eb3ba199c8fChris Lattner
412a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    BD.setNewProgram(ToNotOptimize);
413a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner    MadeChange = true;
414a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner  }
415a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner}
416a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner
4175e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattnernamespace {
4185e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
4195e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner    BugDriver &BD;
42022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
4215e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner    std::vector<Function*> FunctionsBeingTested;
4225e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  public:
4235e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner    ReduceMiscompiledBlocks(BugDriver &bd,
42422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                            bool (*F)(BugDriver &, Module *, Module *,
42522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                      std::string &),
4265e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner                            const std::vector<Function*> &Fns)
4275e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner      : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
4283da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
4295e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner    virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
43022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                              std::vector<BasicBlock*> &Suffix,
43122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                              std::string &Error) {
43222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      if (!Suffix.empty()) {
43322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        bool Ret = TestFuncs(Suffix, Error);
43422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        if (!Error.empty())
43522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky          return InternalError;
43622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        if (Ret)
43722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky          return KeepSuffix;
43822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      }
43922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      if (!Prefix.empty()) {
44022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        bool Ret = TestFuncs(Prefix, Error);
44122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        if (!Error.empty())
44222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky          return InternalError;
44322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        if (Ret)
44422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky          return KeepPrefix;
44522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      }
4465e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner      return NoFailure;
4475e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner    }
4483da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
44922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    bool TestFuncs(const std::vector<BasicBlock*> &BBs, std::string &Error);
4505e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  };
4515e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner}
4525e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
4535e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner/// TestFuncs - Extract all blocks for the miscompiled functions except for the
4545e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner/// specified blocks.  If the problem still exists, return true.
4555e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner///
45622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewyckybool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs,
45722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                        std::string &Error) {
4585e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  // Test to see if the function is misoptimized if we ONLY run it on the
4595e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  // functions listed in Funcs.
460ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "Checking to see if the program is misoptimized when all ";
46168bee938e539d884ee89ce4dfebbad777896960eChris Lattner  if (!BBs.empty()) {
462ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    outs() << "but these " << BBs.size() << " blocks are extracted: ";
46368bee938e539d884ee89ce4dfebbad777896960eChris Lattner    for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
464ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman      outs() << BBs[i]->getName() << " ";
465ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    if (BBs.size() > 10) outs() << "...";
46668bee938e539d884ee89ce4dfebbad777896960eChris Lattner  } else {
467ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    outs() << "blocks are extracted.";
46868bee938e539d884ee89ce4dfebbad777896960eChris Lattner  }
469ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << '\n';
4705e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
4715e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  // Split the module into the two halves of the program we want.
472e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel  ValueMap<const Value*, Value*> VMap;
473e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel  Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
4745e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
475d50330cd02b00c8e3de40e8544c45701b9891d87Dan Gohman                                                 FunctionsBeingTested,
476e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel                                                 VMap);
4775e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
4785e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  // Try the extraction.  If it doesn't work, then the block extractor crashed
4795e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  // or something, in which case bugpoint can't chase down this possibility.
4805e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  if (Module *New = BD.ExtractMappedBlocksFromModule(BBs, ToOptimize)) {
4815e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner    delete ToOptimize;
4825e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner    // Run the predicate, not that the predicate will delete both input modules.
48322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    return TestFn(BD, New, ToNotOptimize, Error);
4845e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  }
4855e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  delete ToOptimize;
4865e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  delete ToNotOptimize;
4875e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  return false;
4885e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner}
4895e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
4905e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
4915e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner/// ExtractBlocks - Given a reduced list of functions that still expose the bug,
4925e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner/// extract as many basic blocks from the region as possible without obscuring
4935e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner/// the bug.
4945e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner///
4955e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattnerstatic bool ExtractBlocks(BugDriver &BD,
49622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                          bool (*TestFn)(BugDriver &, Module *, Module *,
49722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                         std::string &),
49822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                          std::vector<Function*> &MiscompiledFunctions,
49922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                          std::string &Error) {
500f9aaae06cd2109082cda2b09ef3f23e0e1cff47bChris Lattner  if (BugpointIsInterrupted) return false;
501f9aaae06cd2109082cda2b09ef3f23e0e1cff47bChris Lattner
5025e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  std::vector<BasicBlock*> Blocks;
5035e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
5045e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner    for (Function::iterator I = MiscompiledFunctions[i]->begin(),
5055e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner           E = MiscompiledFunctions[i]->end(); I != E; ++I)
5065e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner      Blocks.push_back(I);
5075e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
5085e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  // Use the list reducer to identify blocks that can be extracted without
5095e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  // obscuring the bug.  The Blocks list will end up containing blocks that must
5105e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  // be retained from the original program.
5115e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  unsigned OldSize = Blocks.size();
51268bee938e539d884ee89ce4dfebbad777896960eChris Lattner
51368bee938e539d884ee89ce4dfebbad777896960eChris Lattner  // Check to see if all blocks are extractible first.
51422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  bool Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
51522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                  .TestFuncs(std::vector<BasicBlock*>(), Error);
51622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error.empty())
51722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    return false;
51822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (Ret) {
51968bee938e539d884ee89ce4dfebbad777896960eChris Lattner    Blocks.clear();
52068bee938e539d884ee89ce4dfebbad777896960eChris Lattner  } else {
52122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    ReduceMiscompiledBlocks(BD, TestFn,
52222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                            MiscompiledFunctions).reduceList(Blocks, Error);
52322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (!Error.empty())
52422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      return false;
52568bee938e539d884ee89ce4dfebbad777896960eChris Lattner    if (Blocks.size() == OldSize)
52668bee938e539d884ee89ce4dfebbad777896960eChris Lattner      return false;
52768bee938e539d884ee89ce4dfebbad777896960eChris Lattner  }
5285e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
529e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel  ValueMap<const Value*, Value*> VMap;
530e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel  Module *ProgClone = CloneModule(BD.getProgram(), VMap);
5312290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
532d50330cd02b00c8e3de40e8544c45701b9891d87Dan Gohman                                                MiscompiledFunctions,
533e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel                                                VMap);
5342290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
5352290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  if (Extracted == 0) {
536da895d63377b421dc50117befb2bec80d2973526Chris Lattner    // Weird, extraction should have worked.
53765f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << "Nondeterministic problem extracting blocks??\n";
5382290e754061f1393bb96b1808ac33dc03399c939Chris Lattner    delete ProgClone;
5392290e754061f1393bb96b1808ac33dc03399c939Chris Lattner    delete ToExtract;
5402290e754061f1393bb96b1808ac33dc03399c939Chris Lattner    return false;
5412290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  }
5425e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
5432290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  // Otherwise, block extraction succeeded.  Link the two program fragments back
5442290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  // together.
5452290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  delete ToExtract;
5465e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
54790c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner  std::vector<std::pair<std::string, const FunctionType*> > MisCompFunctions;
54890c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner  for (Module::iterator I = Extracted->begin(), E = Extracted->end();
54990c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner       I != E; ++I)
5505cbf985dcbc89fba3208e7baf8b6f488b06d3ec9Reid Spencer    if (!I->isDeclaration())
551fa1af1344910ee975f50ffdddf605c26f80ef016Chris Lattner      MisCompFunctions.push_back(std::make_pair(I->getName(),
552fa1af1344910ee975f50ffdddf605c26f80ef016Chris Lattner                                                I->getFunctionType()));
55390c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner
5542290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  std::string ErrorMsg;
555e4874029c37c4b14d0646289f18e5f2a1b03fdc2Reid Spencer  if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
55665f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << BD.getToolName() << ": Error linking modules together:"
55765f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman           << ErrorMsg << '\n';
5582290e754061f1393bb96b1808ac33dc03399c939Chris Lattner    exit(1);
5592290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  }
56090c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner  delete Extracted;
5615e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
5622290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  // Set the new program and delete the old one.
5632290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  BD.setNewProgram(ProgClone);
5645e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
5652290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  // Update the list of miscompiled functions.
5662290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  MiscompiledFunctions.clear();
5675e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
56890c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner  for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
569ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer    Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
57090c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner    assert(NewF && "Function not found??");
571ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer    assert(NewF->getFunctionType() == MisCompFunctions[i].second &&
572ef9b9a793949469cdaa4ab6d0173136229dcab7bReid Spencer           "Function has wrong type??");
57390c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner    MiscompiledFunctions.push_back(NewF);
57490c18c5c69d9c451e5fdca1e4b4b95e8ed13291aChris Lattner  }
5752290e754061f1393bb96b1808ac33dc03399c939Chris Lattner
5762290e754061f1393bb96b1808ac33dc03399c939Chris Lattner  return true;
5775e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner}
5785e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
5795e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
580b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner/// DebugAMiscompilation - This is a generic driver to narrow down
581b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner/// miscompilations, either in an optimization or a code generator.
5828c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman///
583b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattnerstatic std::vector<Function*>
584b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris LattnerDebugAMiscompilation(BugDriver &BD,
58522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                     bool (*TestFn)(BugDriver &, Module *, Module *,
58622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                    std::string &),
58722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                     std::string &Error) {
588640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // Okay, now that we have reduced the list of passes which are causing the
589640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // failure, see if we can pin down which functions are being
590640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // miscompiled... first build a list of all of the non-external functions in
591640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // the program.
592640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  std::vector<Function*> MiscompiledFunctions;
593b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner  Module *Prog = BD.getProgram();
594b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner  for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
5955cbf985dcbc89fba3208e7baf8b6f488b06d3ec9Reid Spencer    if (!I->isDeclaration())
596640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner      MiscompiledFunctions.push_back(I);
5974a10645c70199c8d8567fbc46312158c419720abChris Lattner
598640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  // Do the reduction...
599f9aaae06cd2109082cda2b09ef3f23e0e1cff47bChris Lattner  if (!BugpointIsInterrupted)
60022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
60122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                                       Error);
60222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error.empty())
60322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    return MiscompiledFunctions;
604640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner
605ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "\n*** The following function"
606ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman         << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
607ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman         << " being miscompiled: ";
608640f22e66d90439857a97a83896ee68c4f7128c9Chris Lattner  PrintFunctionList(MiscompiledFunctions);
609ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << '\n';
6104a10645c70199c8d8567fbc46312158c419720abChris Lattner
611a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner  // See if we can rip any loops out of the miscompiled functions and still
612a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner  // trigger the problem.
613dc31a8a70cab3b4c180ac1a482855e31d3fe8e6bReid Spencer
61422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!BugpointIsInterrupted && !DisableLoopExtraction) {
61522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    bool Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions, Error);
61622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (!Error.empty())
61722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      return MiscompiledFunctions;
61822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (Ret) {
61922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      // Okay, we extracted some loops and the problem still appears.  See if
62022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      // we can eliminate some of the created functions from being candidates.
62122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      DisambiguateGlobalSymbols(BD.getProgram());
62222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky
62322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      // Do the reduction...
62422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      if (!BugpointIsInterrupted)
62522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
62622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                                           Error);
62722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      if (!Error.empty())
62822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        return MiscompiledFunctions;
62922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky
63022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      outs() << "\n*** The following function"
63122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
63222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << " being miscompiled: ";
63322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      PrintFunctionList(MiscompiledFunctions);
63422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      outs() << '\n';
63522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    }
6365e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner  }
6375e783ab0b5fc3407ec59f1a598fdb9ef3b96b287Chris Lattner
63822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!BugpointIsInterrupted && !DisableBlockExtraction) {
63922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    bool Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions, Error);
64022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (!Error.empty())
64122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      return MiscompiledFunctions;
64222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (Ret) {
64322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      // Okay, we extracted some blocks and the problem still appears.  See if
64422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      // we can eliminate some of the created functions from being candidates.
64522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      DisambiguateGlobalSymbols(BD.getProgram());
64622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky
64722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      // Do the reduction...
64822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
64922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                                         Error);
65022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      if (!Error.empty())
65122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        return MiscompiledFunctions;
65222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky
65322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      outs() << "\n*** The following function"
65422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
65522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << " being miscompiled: ";
65622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      PrintFunctionList(MiscompiledFunctions);
65722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      outs() << '\n';
65822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    }
659a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner  }
660a1cf1c8c87f10f12343ff6ae75f332390e7205abChris Lattner
661b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner  return MiscompiledFunctions;
662b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner}
663b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner
664a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner/// TestOptimizer - This is the predicate function used to check to see if the
665a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner/// "Test" portion of the program is misoptimized.  If so, return true.  In any
666a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner/// case, both module arguments are deleted.
6678c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman///
66822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewyckystatic bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe,
66922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                          std::string &Error) {
670b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner  // Run the optimization passes on ToOptimize, producing a transformed version
671b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner  // of the functions being tested.
672ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "  Optimizing functions being tested: ";
673b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner  Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
674b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner                                     /*AutoDebugCrashes*/true);
675ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "done.\n";
676b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner  delete Test;
677b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner
678ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "  Checking to see if the merged program executes correctly: ";
67922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  bool Broken = TestMergedProgram(BD, Optimized, Safe, true, Error);
68022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (Error.empty()) outs() << (Broken ? " nope.\n" : " yup.\n");
681b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner  return Broken;
682b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner}
683b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner
684b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner
685b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner/// debugMiscompilation - This method is used when the passes selected are not
686b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner/// crashing, but the generated output is semantically different from the
687b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner/// input.
688b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner///
68922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewyckyvoid BugDriver::debugMiscompilation(std::string *Error) {
690b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner  // Make sure something was miscompiled...
691f9aaae06cd2109082cda2b09ef3f23e0e1cff47bChris Lattner  if (!BugpointIsInterrupted)
69222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun, *Error)) {
69322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      if (Error->empty())
69422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky        errs() << "*** Optimized program matches reference output!  No problem"
69522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky               << " detected...\nbugpoint can't help you with your problem!\n";
69622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      return;
697f9aaae06cd2109082cda2b09ef3f23e0e1cff47bChris Lattner    }
698b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner
699ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "\n*** Found miscompiling pass"
700ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman         << (getPassesToRun().size() == 1 ? "" : "es") << ": "
701ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman         << getPassesString(getPassesToRun()) << '\n';
7028ff70c2635bfd4e02c0140a5dc9ca909fffba35aGabor Greif  EmitProgressBitcode("passinput");
703b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner
70422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  std::vector<Function *> MiscompiledFunctions =
70522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    DebugAMiscompilation(*this, TestOptimizer, *Error);
70622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error->empty())
70722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    return;
708b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner
7098ff70c2635bfd4e02c0140a5dc9ca909fffba35aGabor Greif  // Output a bunch of bitcode files for the user...
710ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "Outputting reduced bitcode files which expose the problem:\n";
711e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel  ValueMap<const Value*, Value*> VMap;
712e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel  Module *ToNotOptimize = CloneModule(getProgram(), VMap);
713efdc0b505712d1ca4460def27e51c430f033d58dChris Lattner  Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
714d50330cd02b00c8e3de40e8544c45701b9891d87Dan Gohman                                                 MiscompiledFunctions,
715e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel                                                 VMap);
716be21ca54e08339ede5dd4bbb882182d22e274988Chris Lattner
717ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "  Non-optimized portion: ";
718b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner  ToNotOptimize = swapProgramIn(ToNotOptimize);
7198ff70c2635bfd4e02c0140a5dc9ca909fffba35aGabor Greif  EmitProgressBitcode("tonotoptimize", true);
720be21ca54e08339ede5dd4bbb882182d22e274988Chris Lattner  setNewProgram(ToNotOptimize);   // Delete hacked module.
7213da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
722ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "  Portion that is input to optimizer: ";
723b15825b0a29e527b361b63a6e41aff5fdb8fdd5aChris Lattner  ToOptimize = swapProgramIn(ToOptimize);
7248ff70c2635bfd4e02c0140a5dc9ca909fffba35aGabor Greif  EmitProgressBitcode("tooptimize");
725be21ca54e08339ede5dd4bbb882182d22e274988Chris Lattner  setNewProgram(ToOptimize);      // Delete hacked module.
7264a10645c70199c8d8567fbc46312158c419720abChris Lattner
72722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  return;
7284a10645c70199c8d8567fbc46312158c419720abChris Lattner}
729d0fde30ce850b78371fd1386338350591f9ff494Brian Gaeke
730a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner/// CleanupAndPrepareModules - Get the specified modules ready for code
731a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner/// generator testing.
7328c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman///
733a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattnerstatic void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
734a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner                                     Module *Safe) {
735a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // Clean up the modules, removing extra cruft that we don't need anymore...
736a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  Test = BD.performFinalCleanups(Test);
737a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
738a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // If we are executing the JIT, we have several nasty issues to take care of.
739a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  if (!BD.isExecutingJIT()) return;
740a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
741a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // First, if the main function is in the Safe module, we must add a stub to
742a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // the Test module to call into it.  Thus, we create a new function `main'
743a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // which just calls the old one.
744688b0490e22eb67623f5aaa24406209be74efcb2Reid Spencer  if (Function *oldMain = Safe->getFunction("main"))
7455cbf985dcbc89fba3208e7baf8b6f488b06d3ec9Reid Spencer    if (!oldMain->isDeclaration()) {
746a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      // Rename it
747a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      oldMain->setName("llvm_bugpoint_old_main");
748a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      // Create a NEW `main' function with same type in the test module.
749051a950000e21935165db56695e35bade668193bGabor Greif      Function *newMain = Function::Create(oldMain->getFunctionType(),
750051a950000e21935165db56695e35bade668193bGabor Greif                                           GlobalValue::ExternalLinkage,
751051a950000e21935165db56695e35bade668193bGabor Greif                                           "main", Test);
752a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      // Create an `oldmain' prototype in the test module, which will
753a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      // corresponds to the real main function in the same module.
754051a950000e21935165db56695e35bade668193bGabor Greif      Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
755051a950000e21935165db56695e35bade668193bGabor Greif                                                GlobalValue::ExternalLinkage,
756051a950000e21935165db56695e35bade668193bGabor Greif                                                oldMain->getName(), Test);
757a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      // Set up and remember the argument list for the main function.
758a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      std::vector<Value*> args;
7595a1c58d0094ff16dcd103f3752046d426ad5dd2cAlkis Evlogimenos      for (Function::arg_iterator
7605a1c58d0094ff16dcd103f3752046d426ad5dd2cAlkis Evlogimenos             I = newMain->arg_begin(), E = newMain->arg_end(),
7615a1c58d0094ff16dcd103f3752046d426ad5dd2cAlkis Evlogimenos             OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
7626bc41e8a74d1756da0003641bfebd02a3d6d9586Owen Anderson        I->setName(OI->getName());    // Copy argument names from oldMain
763a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner        args.push_back(I);
764a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      }
765a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
766a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      // Call the old main function and return its result
7671d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson      BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
768051a950000e21935165db56695e35bade668193bGabor Greif      CallInst *call = CallInst::Create(oldMainProto, args.begin(), args.end(),
769051a950000e21935165db56695e35bade668193bGabor Greif                                        "", BB);
7703da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
771a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      // If the type of old function wasn't void, return value of call
7721d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson      ReturnInst::Create(Safe->getContext(), call, BB);
773a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner    }
774a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
775a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // The second nasty issue we must deal with in the JIT is that the Safe
776a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // module cannot directly reference any functions defined in the test
777a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // module.  Instead, we use a JIT API call to dynamically resolve the
778a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // symbol.
7793da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
780a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // Add the resolver to the Safe module.
781a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // Prototype: void *getPointerToNamedFunction(const char* Name)
7822db43c864e8372823d961d961ca520ed20edca82Chris Lattner  Constant *resolverFunc =
783a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner    Safe->getOrInsertFunction("getPointerToNamedFunction",
784ac53a0b272452013124bfc70480aea5e41b60f40Duncan Sands                    Type::getInt8PtrTy(Safe->getContext()),
785ac53a0b272452013124bfc70480aea5e41b60f40Duncan Sands                    Type::getInt8PtrTy(Safe->getContext()),
7861d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                       (Type *)0);
7873da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman
788a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // Use the function we just added to get addresses of functions we need.
789dc7fef83dcab053f86119d00478e6b008166fcf5Misha Brukman  for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
7905cbf985dcbc89fba3208e7baf8b6f488b06d3ec9Reid Spencer    if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
791a3355ffb3d30d19d226bbb75707991c60f236e37Duncan Sands        !F->isIntrinsic() /* ignore intrinsics */) {
792688b0490e22eb67623f5aaa24406209be74efcb2Reid Spencer      Function *TestFn = Test->getFunction(F->getName());
793a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
794a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      // Don't forward functions which are external in the test module too.
7955cbf985dcbc89fba3208e7baf8b6f488b06d3ec9Reid Spencer      if (TestFn && !TestFn->isDeclaration()) {
796a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner        // 1. Add a string constant with its name to the global file
7971d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson        Constant *InitArray = ConstantArray::get(F->getContext(), F->getName());
798a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner        GlobalVariable *funcName =
799e9b11b431308f4766b73cda93e38ec930c912122Owen Anderson          new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
8003da94aec4d429b2ba0f65fa040c33650cade196bMisha Brukman                             GlobalValue::InternalLinkage, InitArray,
801e9b11b431308f4766b73cda93e38ec930c912122Owen Anderson                             F->getName() + "_name");
802a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
803a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner        // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
804a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner        // sbyte* so it matches the signature of the resolver function.
805a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
806a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner        // GetElementPtr *funcName, ulong 0, ulong 0
8071d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson        std::vector<Constant*> GEPargs(2,
8081d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                     Constant::getNullValue(Type::getInt32Ty(F->getContext())));
8099adc0abad3c3ed40a268ccbcee0c74cb9e1359feOwen Anderson        Value *GEP =
810baf3c404409d5e47b13984a7f95bfbd6d1f2e79eOwen Anderson                ConstantExpr::getGetElementPtr(funcName, &GEPargs[0], 2);
811a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner        std::vector<Value*> ResolverArgs;
812a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner        ResolverArgs.push_back(GEP);
813a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
814de4803d0af6824a2d5da41fa09b512084c73ce34Misha Brukman        // Rewrite uses of F in global initializers, etc. to uses of a wrapper
815de4803d0af6824a2d5da41fa09b512084c73ce34Misha Brukman        // function that dynamically resolves the calls to F via our JIT API
816a3efca16f2688981672deeb718909cf6acbe474eChris Lattner        if (!F->use_empty()) {
817a3efca16f2688981672deeb718909cf6acbe474eChris Lattner          // Create a new global to hold the cached function pointer.
8189e9a0d5fc26878e51a58a8b57900fcbf952c2691Owen Anderson          Constant *NullPtr = ConstantPointerNull::get(F->getType());
819a3efca16f2688981672deeb718909cf6acbe474eChris Lattner          GlobalVariable *Cache =
820e9b11b431308f4766b73cda93e38ec930c912122Owen Anderson            new GlobalVariable(*F->getParent(), F->getType(),
821e9b11b431308f4766b73cda93e38ec930c912122Owen Anderson                               false, GlobalValue::InternalLinkage,
822e9b11b431308f4766b73cda93e38ec930c912122Owen Anderson                               NullPtr,F->getName()+".fpcache");
82300b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen
824de4803d0af6824a2d5da41fa09b512084c73ce34Misha Brukman          // Construct a new stub function that will re-route calls to F
825dc7fef83dcab053f86119d00478e6b008166fcf5Misha Brukman          const FunctionType *FuncTy = F->getFunctionType();
826051a950000e21935165db56695e35bade668193bGabor Greif          Function *FuncWrapper = Function::Create(FuncTy,
827051a950000e21935165db56695e35bade668193bGabor Greif                                                   GlobalValue::InternalLinkage,
828051a950000e21935165db56695e35bade668193bGabor Greif                                                   F->getName() + "_wrapper",
829051a950000e21935165db56695e35bade668193bGabor Greif                                                   F->getParent());
8301d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson          BasicBlock *EntryBB  = BasicBlock::Create(F->getContext(),
8311d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                                                    "entry", FuncWrapper);
8321d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson          BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
8331d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                                                    "usecache", FuncWrapper);
8341d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson          BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
8351d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson                                                    "lookupfp", FuncWrapper);
83600b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen
837a3efca16f2688981672deeb718909cf6acbe474eChris Lattner          // Check to see if we already looked up the value.
838a3efca16f2688981672deeb718909cf6acbe474eChris Lattner          Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
839333c40096561218bc3597cf153c0a3895274414cOwen Anderson          Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
840333c40096561218bc3597cf153c0a3895274414cOwen Anderson                                       NullPtr, "isNull");
841051a950000e21935165db56695e35bade668193bGabor Greif          BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
84200b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen
843de4803d0af6824a2d5da41fa09b512084c73ce34Misha Brukman          // Resolve the call to function F via the JIT API:
844de4803d0af6824a2d5da41fa09b512084c73ce34Misha Brukman          //
845de4803d0af6824a2d5da41fa09b512084c73ce34Misha Brukman          // call resolver(GetElementPtr...)
846b1dbcd886a4b5597a839f299054b78b33fb2d6dfGabor Greif          CallInst *Resolver =
847b1dbcd886a4b5597a839f299054b78b33fb2d6dfGabor Greif            CallInst::Create(resolverFunc, ResolverArgs.begin(),
848b1dbcd886a4b5597a839f299054b78b33fb2d6dfGabor Greif                             ResolverArgs.end(), "resolver", LookupBB);
849b1dbcd886a4b5597a839f299054b78b33fb2d6dfGabor Greif
850b1dbcd886a4b5597a839f299054b78b33fb2d6dfGabor Greif          // Cast the result from the resolver to correctly-typed function.
851b1dbcd886a4b5597a839f299054b78b33fb2d6dfGabor Greif          CastInst *CastedResolver =
852b1dbcd886a4b5597a839f299054b78b33fb2d6dfGabor Greif            new BitCastInst(Resolver,
853debcb01b0f0a15f568ca69e8f288fade4bfc7297Owen Anderson                            PointerType::getUnqual(F->getFunctionType()),
854b1dbcd886a4b5597a839f299054b78b33fb2d6dfGabor Greif                            "resolverCast", LookupBB);
8553da59db637a887474c1b1346c1f3ccf53b6c4663Reid Spencer
856a3efca16f2688981672deeb718909cf6acbe474eChris Lattner          // Save the value in our cache.
857a3efca16f2688981672deeb718909cf6acbe474eChris Lattner          new StoreInst(CastedResolver, Cache, LookupBB);
858051a950000e21935165db56695e35bade668193bGabor Greif          BranchInst::Create(DoCallBB, LookupBB);
85900b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen
860b1dbcd886a4b5597a839f299054b78b33fb2d6dfGabor Greif          PHINode *FuncPtr = PHINode::Create(NullPtr->getType(),
861b1dbcd886a4b5597a839f299054b78b33fb2d6dfGabor Greif                                             "fp", DoCallBB);
862a3efca16f2688981672deeb718909cf6acbe474eChris Lattner          FuncPtr->addIncoming(CastedResolver, LookupBB);
863a3efca16f2688981672deeb718909cf6acbe474eChris Lattner          FuncPtr->addIncoming(CachedVal, EntryBB);
86400b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen
865a3efca16f2688981672deeb718909cf6acbe474eChris Lattner          // Save the argument list.
866dc7fef83dcab053f86119d00478e6b008166fcf5Misha Brukman          std::vector<Value*> Args;
8675a1c58d0094ff16dcd103f3752046d426ad5dd2cAlkis Evlogimenos          for (Function::arg_iterator i = FuncWrapper->arg_begin(),
8685a1c58d0094ff16dcd103f3752046d426ad5dd2cAlkis Evlogimenos                 e = FuncWrapper->arg_end(); i != e; ++i)
869dc7fef83dcab053f86119d00478e6b008166fcf5Misha Brukman            Args.push_back(i);
870dc7fef83dcab053f86119d00478e6b008166fcf5Misha Brukman
871dc7fef83dcab053f86119d00478e6b008166fcf5Misha Brukman          // Pass on the arguments to the real function, return its result
872e49a13e7260b83ce56d01446f2a165cc9f35da7fDan Gohman          if (F->getReturnType()->isVoidTy()) {
873051a950000e21935165db56695e35bade668193bGabor Greif            CallInst::Create(FuncPtr, Args.begin(), Args.end(), "", DoCallBB);
8741d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson            ReturnInst::Create(F->getContext(), DoCallBB);
875dc7fef83dcab053f86119d00478e6b008166fcf5Misha Brukman          } else {
876051a950000e21935165db56695e35bade668193bGabor Greif            CallInst *Call = CallInst::Create(FuncPtr, Args.begin(), Args.end(),
877051a950000e21935165db56695e35bade668193bGabor Greif                                              "retval", DoCallBB);
8781d0be15f89cb5056e20e2d24faa8d6afb1573bcaOwen Anderson            ReturnInst::Create(F->getContext(),Call, DoCallBB);
879dc7fef83dcab053f86119d00478e6b008166fcf5Misha Brukman          }
88000b16889ab461b7ecef1c91ade101186b7f1fce2Jeff Cohen
881de4803d0af6824a2d5da41fa09b512084c73ce34Misha Brukman          // Use the wrapper function instead of the old function
882de4803d0af6824a2d5da41fa09b512084c73ce34Misha Brukman          F->replaceAllUsesWith(FuncWrapper);
883dc7fef83dcab053f86119d00478e6b008166fcf5Misha Brukman        }
884a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner      }
885a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner    }
886a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  }
887a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
888a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  if (verifyModule(*Test) || verifyModule(*Safe)) {
88965f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << "Bugpoint has a bug, which corrupted a module!!\n";
890a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner    abort();
891a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  }
892a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner}
893a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
894a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
895a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
896a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner/// TestCodeGenerator - This is the predicate function used to check to see if
897a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner/// the "Test" portion of the program is miscompiled by the code generator under
898a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner/// test.  If so, return true.  In any case, both module arguments are deleted.
8998c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman///
90022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewyckystatic bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe,
90122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                              std::string &Error) {
902a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  CleanupAndPrepareModules(BD, Test, Safe);
903a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
90497182985d530dbef488696c95a39c14fe56c995bReid Spencer  sys::Path TestModuleBC("bugpoint.test.bc");
90551c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer  std::string ErrMsg;
90651c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer  if (TestModuleBC.makeUnique(true, &ErrMsg)) {
90765f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << BD.getToolName() << "Error making unique filename: "
90865f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman           << ErrMsg << "\n";
90951c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer    exit(1);
91051c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer  }
91174382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner  if (BD.writeProgramToFile(TestModuleBC.str(), Test)) {
91274382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner    errs() << "Error writing bitcode to `" << TestModuleBC.str()
91374382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner           << "'\nExiting.";
914a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner    exit(1);
915a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  }
916a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  delete Test;
917a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
918bc2ed599e877b9d76bd548546019f98ae256fe9bRafael Espindola  FileRemover TestModuleBCRemover(TestModuleBC, !SaveTemps);
919bc2ed599e877b9d76bd548546019f98ae256fe9bRafael Espindola
920a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // Make the shared library
92197182985d530dbef488696c95a39c14fe56c995bReid Spencer  sys::Path SafeModuleBC("bugpoint.safe.bc");
92251c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer  if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
92365f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << BD.getToolName() << "Error making unique filename: "
92465f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman           << ErrMsg << "\n";
92551c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer    exit(1);
92651c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer  }
927a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
92874382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner  if (BD.writeProgramToFile(SafeModuleBC.str(), Safe)) {
92974382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner    errs() << "Error writing bitcode to `" << SafeModuleBC.str()
93074382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner           << "'\nExiting.";
931a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner    exit(1);
932a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  }
933bc2ed599e877b9d76bd548546019f98ae256fe9bRafael Espindola
934bc2ed599e877b9d76bd548546019f98ae256fe9bRafael Espindola  FileRemover SafeModuleBCRemover(SafeModuleBC, !SaveTemps);
935bc2ed599e877b9d76bd548546019f98ae256fe9bRafael Espindola
93622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str(), Error);
93722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error.empty())
9382706387d37b30fc191c5b74987dc139e1835c52dBenjamin Kramer    return false;
939a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  delete Safe;
940a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
941bc2ed599e877b9d76bd548546019f98ae256fe9bRafael Espindola  FileRemover SharedObjectRemover(sys::Path(SharedObject), !SaveTemps);
942bc2ed599e877b9d76bd548546019f98ae256fe9bRafael Espindola
943a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // Run the code generator on the `Test' code, loading the shared library.
944a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // The function returns whether or not the new output differs from reference.
94522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  bool Result = BD.diffProgram(TestModuleBC.str(), SharedObject, false, &Error);
94622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error.empty())
94722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    return false;
948a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
949a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  if (Result)
95065f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << ": still failing!\n";
951a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  else
95265f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << ": didn't fail.\n";
953a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
954a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  return Result;
955a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner}
956a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
957a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
9588c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman/// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
9598c194eaa0577a207bb1ea91bf2c2a5e664fce9eeMisha Brukman///
96022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewyckybool BugDriver::debugCodeGenerator(std::string *Error) {
96170ef449741da8b1ef035e04a55958652a0200ba1Dan Gohman  if ((void*)SafeInterpreter == (void*)Interpreter) {
96222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    std::string Result = executeProgramSafely("bugpoint.safe.out", Error);
96322ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    if (Error->empty()) {
96422ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky      outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
96522ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << "the reference diff.  This may be due to a\n    front-end "
96622ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << "bug or a bug in the original program, but this can also "
96722ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << "happen if bugpoint isn't running the program with the "
96822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << "right flags or input.\n    I left the result of executing "
96922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << "the program with the \"safe\" backend in this file for "
97022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << "you: '"
97122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky             << Result << "'.\n";
97222ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    }
973a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner    return true;
974a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  }
975a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
976a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  DisambiguateGlobalSymbols(Program);
977a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
97822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator,
97922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky                                                      *Error);
98022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error->empty())
98122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    return true;
982a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
983a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // Split the module into the two halves of the program we want.
984e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel  ValueMap<const Value*, Value*> VMap;
985e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel  Module *ToNotCodeGen = CloneModule(getProgram(), VMap);
986e9916a302f1bacad234d7dafc1df3dc968a6ba0fDevang Patel  Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, VMap);
987a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
988a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // Condition the modules
989a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
990a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
99197182985d530dbef488696c95a39c14fe56c995bReid Spencer  sys::Path TestModuleBC("bugpoint.test.bc");
99251c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer  std::string ErrMsg;
99351c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer  if (TestModuleBC.makeUnique(true, &ErrMsg)) {
99465f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << getToolName() << "Error making unique filename: "
99565f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman           << ErrMsg << "\n";
99651c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer    exit(1);
99751c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer  }
99897182985d530dbef488696c95a39c14fe56c995bReid Spencer
99974382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner  if (writeProgramToFile(TestModuleBC.str(), ToCodeGen)) {
100074382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner    errs() << "Error writing bitcode to `" << TestModuleBC.str()
100174382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner           << "'\nExiting.";
1002a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner    exit(1);
1003a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  }
1004a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  delete ToCodeGen;
1005a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
1006a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  // Make the shared library
100797182985d530dbef488696c95a39c14fe56c995bReid Spencer  sys::Path SafeModuleBC("bugpoint.safe.bc");
100851c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer  if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
100965f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman    errs() << getToolName() << "Error making unique filename: "
101065f57c233cd4499e2e8b52a503201e64edfd6a9eDan Gohman           << ErrMsg << "\n";
101151c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer    exit(1);
101251c5a286bae5ad27ddc49602f44b7ea7253a4cc9Reid Spencer  }
101397182985d530dbef488696c95a39c14fe56c995bReid Spencer
101474382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner  if (writeProgramToFile(SafeModuleBC.str(), ToNotCodeGen)) {
101574382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner    errs() << "Error writing bitcode to `" << SafeModuleBC.str()
101674382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner           << "'\nExiting.";
1017a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner    exit(1);
1018a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  }
101922ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  std::string SharedObject = compileSharedObject(SafeModuleBC.str(), *Error);
102022ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  if (!Error->empty())
102122ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky    return true;
1022a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  delete ToNotCodeGen;
1023a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
1024ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "You can reproduce the problem with the command line: \n";
1025a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  if (isExecutingJIT()) {
102674382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner    outs() << "  lli -load " << SharedObject << " " << TestModuleBC.str();
1027a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  } else {
10288d0e1bcc921c942e979b0925051c663590bd618fNick Lewycky    outs() << "  llc " << TestModuleBC.str() << " -o " << TestModuleBC.str()
102974382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner           << ".s\n";
103074382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner    outs() << "  gcc " << SharedObject << " " << TestModuleBC.str()
103174382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner              << ".s -o " << TestModuleBC.str() << ".exe";
103259615f0f85e2ac99e012cb81934d002faebd405aChris Lattner#if defined (HAVE_LINK_R)
1033ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    outs() << " -Wl,-R.";
103459615f0f85e2ac99e012cb81934d002faebd405aChris Lattner#endif
1035ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    outs() << "\n";
103674382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner    outs() << "  " << TestModuleBC.str() << ".exe";
1037a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  }
103822ff748712b348300e51248339b6e8cf9b59e2c6Nick Lewycky  for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
1039ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman    outs() << " " << InputArgv[i];
1040ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << '\n';
1041ac95cc79ac0b899d566cc29c0f646f39c2fa35c0Dan Gohman  outs() << "The shared object was created with:\n  llc -march=c "
104274382b7c699120fbec5cb5603c9cf4212eb37f06Chris Lattner         << SafeModuleBC.str() << " -o temporary.c\n"
1043ca7409664273fed4b473127295af3af0836b3077Daniel Dunbar         << "  gcc -xc temporary.c -O2 -o " << SharedObject;
1044ca7409664273fed4b473127295af3af0836b3077Daniel Dunbar  if (TargetTriple.getArch() == Triple::sparc)
1045ca7409664273fed4b473127295af3af0836b3077Daniel Dunbar    outs() << " -G";              // Compile a shared library, `-G' for Sparc
1046ca7409664273fed4b473127295af3af0836b3077Daniel Dunbar  else
1047ca7409664273fed4b473127295af3af0836b3077Daniel Dunbar    outs() << " -fPIC -shared";   // `-shared' for Linux/X86, maybe others
1048ca7409664273fed4b473127295af3af0836b3077Daniel Dunbar
1049ca7409664273fed4b473127295af3af0836b3077Daniel Dunbar  outs() << " -fno-strict-aliasing\n";
1050a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner
1051a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner  return false;
1052a57d86b436549503a7f96c5266444e022bdbaf55Chris Lattner}
1053