Miscompilation.cpp 42 KB

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