1 //===- Miscompilation.cpp - Debug program miscompilations -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements optimizer and code generation miscompilation debugging
13 //===----------------------------------------------------------------------===//
15 #include "BugDriver.h"
16 #include "ListReducer.h"
17 #include "ToolRunner.h"
18 #include "llvm/Config/config.h" // for HAVE_LINK_R
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Verifier.h"
25 #include "llvm/Linker/Linker.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/FileUtilities.h"
29 #include "llvm/Transforms/Utils/Cloning.h"
33 extern cl::opt<std::string> OutputPrefix;
34 extern cl::list<std::string> InputArgv;
38 static llvm::cl::opt<bool>
39 DisableLoopExtraction("disable-loop-extraction",
40 cl::desc("Don't extract loops when searching for miscompilations"),
42 static llvm::cl::opt<bool>
43 DisableBlockExtraction("disable-block-extraction",
44 cl::desc("Don't extract blocks when searching for miscompilations"),
47 class ReduceMiscompilingPasses : public ListReducer<std::string> {
50 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
52 TestResult doTest(std::vector<std::string> &Prefix,
53 std::vector<std::string> &Suffix,
54 std::string &Error) override;
58 /// TestResult - After passes have been split into a test group and a control
59 /// group, see if they still break the program.
61 ReduceMiscompilingPasses::TestResult
62 ReduceMiscompilingPasses::doTest(std::vector<std::string> &Prefix,
63 std::vector<std::string> &Suffix,
65 // First, run the program with just the Suffix passes. If it is still broken
66 // with JUST the kept passes, discard the prefix passes.
67 outs() << "Checking to see if '" << getPassesString(Suffix)
68 << "' compiles correctly: ";
70 std::string BitcodeResult;
71 if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false/*delete*/,
73 errs() << " Error running this sequence of passes"
74 << " on the input program!\n";
75 BD.setPassesToRun(Suffix);
76 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
77 exit(BD.debugOptimizerCrash());
80 // Check to see if the finished program matches the reference output...
81 bool Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
82 true /*delete bitcode*/, &Error);
88 errs() << BD.getToolName() << ": I'm confused: the test fails when "
89 << "no passes are run, nondeterministic program?\n";
92 return KeepSuffix; // Miscompilation detected!
94 outs() << " yup.\n"; // No miscompilation!
96 if (Prefix.empty()) return NoFailure;
98 // Next, see if the program is broken if we run the "prefix" passes first,
99 // then separately run the "kept" passes.
100 outs() << "Checking to see if '" << getPassesString(Prefix)
101 << "' compiles correctly: ";
103 // If it is not broken with the kept passes, it's possible that the prefix
104 // passes must be run before the kept passes to break it. If the program
105 // WORKS after the prefix passes, but then fails if running the prefix AND
106 // kept passes, we can update our bitcode file to include the result of the
107 // prefix passes, then discard the prefix passes.
109 if (BD.runPasses(BD.getProgram(), Prefix, BitcodeResult, false/*delete*/,
111 errs() << " Error running this sequence of passes"
112 << " on the input program!\n";
113 BD.setPassesToRun(Prefix);
114 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
115 exit(BD.debugOptimizerCrash());
118 // If the prefix maintains the predicate by itself, only keep the prefix!
119 Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "", false, &Error);
121 return InternalError;
123 outs() << " nope.\n";
124 sys::fs::remove(BitcodeResult);
127 outs() << " yup.\n"; // No miscompilation!
129 // Ok, so now we know that the prefix passes work, try running the suffix
130 // passes on the result of the prefix passes.
132 std::unique_ptr<Module> PrefixOutput =
133 parseInputFile(BitcodeResult, BD.getContext());
135 errs() << BD.getToolName() << ": Error reading bitcode file '"
136 << BitcodeResult << "'!\n";
139 sys::fs::remove(BitcodeResult);
141 // Don't check if there are no passes in the suffix.
145 outs() << "Checking to see if '" << getPassesString(Suffix)
146 << "' passes compile correctly after the '"
147 << getPassesString(Prefix) << "' passes: ";
149 std::unique_ptr<Module> OriginalInput(
150 BD.swapProgramIn(PrefixOutput.release()));
151 if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false/*delete*/,
153 errs() << " Error running this sequence of passes"
154 << " on the input program!\n";
155 BD.setPassesToRun(Suffix);
156 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
157 exit(BD.debugOptimizerCrash());
161 Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
162 true /*delete bitcode*/, &Error);
164 return InternalError;
166 outs() << " nope.\n";
170 // Otherwise, we must not be running the bad pass anymore.
171 outs() << " yup.\n"; // No miscompilation!
172 // Restore orig program & free test.
173 delete BD.swapProgramIn(OriginalInput.release());
178 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
180 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
181 std::unique_ptr<Module>, std::string &);
184 ReduceMiscompilingFunctions(BugDriver &bd,
185 bool (*F)(BugDriver &, std::unique_ptr<Module>,
186 std::unique_ptr<Module>,
188 : BD(bd), TestFn(F) {}
190 TestResult doTest(std::vector<Function*> &Prefix,
191 std::vector<Function*> &Suffix,
192 std::string &Error) override {
193 if (!Suffix.empty()) {
194 bool Ret = TestFuncs(Suffix, Error);
196 return InternalError;
200 if (!Prefix.empty()) {
201 bool Ret = TestFuncs(Prefix, Error);
203 return InternalError;
210 bool TestFuncs(const std::vector<Function*> &Prefix, std::string &Error);
214 static void diagnosticHandler(const DiagnosticInfo &DI) {
215 DiagnosticPrinterRawOStream DP(errs());
218 if (DI.getSeverity() == DS_Error)
222 /// TestMergedProgram - Given two modules, link them together and run the
223 /// program, checking to see if the program matches the diff. If there is
224 /// an error, return NULL. If not, return the merged module. The Broken argument
225 /// will be set to true if the output is different. If the DeleteInputs
226 /// argument is set to true then this function deletes both input
227 /// modules before it returns.
229 static Module *TestMergedProgram(const BugDriver &BD, Module *M1, Module *M2,
230 bool DeleteInputs, std::string &Error,
232 // Link the two portions of the program back to together.
234 M1 = CloneModule(M1).release();
235 M2 = CloneModule(M2).release();
237 if (Linker::linkModules(*M1, *M2, diagnosticHandler))
239 delete M2; // We are done with this module.
241 // Execute the program.
242 Broken = BD.diffProgram(M1, "", "", false, &Error);
243 if (!Error.empty()) {
244 // Delete the linked module
251 /// TestFuncs - split functions in a Module into two groups: those that are
252 /// under consideration for miscompilation vs. those that are not, and test
253 /// accordingly. Each group of functions becomes a separate Module.
255 bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*> &Funcs,
256 std::string &Error) {
257 // Test to see if the function is misoptimized if we ONLY run it on the
258 // functions listed in Funcs.
259 outs() << "Checking to see if the program is misoptimized when "
260 << (Funcs.size()==1 ? "this function is" : "these functions are")
261 << " run through the pass"
262 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
263 PrintFunctionList(Funcs);
266 // Create a clone for two reasons:
267 // * If the optimization passes delete any function, the deleted function
268 // will be in the clone and Funcs will still point to valid memory
269 // * If the optimization passes use interprocedural information to break
270 // a function, we want to continue with the original function. Otherwise
271 // we can conclude that a function triggers the bug when in fact one
272 // needs a larger set of original functions to do so.
273 ValueToValueMapTy VMap;
274 Module *Clone = CloneModule(BD.getProgram(), VMap).release();
275 Module *Orig = BD.swapProgramIn(Clone);
277 std::vector<Function*> FuncsOnClone;
278 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
279 Function *F = cast<Function>(VMap[Funcs[i]]);
280 FuncsOnClone.push_back(F);
283 // Split the module into the two halves of the program we want.
285 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
286 std::unique_ptr<Module> ToOptimize =
287 SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
290 TestFn(BD, std::move(ToOptimize), std::move(ToNotOptimize), Error);
292 delete BD.swapProgramIn(Orig);
297 /// DisambiguateGlobalSymbols - Give anonymous global values names.
299 static void DisambiguateGlobalSymbols(Module *M) {
300 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
303 I->setName("anon_global");
304 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
306 I->setName("anon_fn");
309 /// Given a reduced list of functions that still exposed the bug, check to see
310 /// if we can extract the loops in the region without obscuring the bug. If so,
311 /// it reduces the amount of code identified.
313 static bool ExtractLoops(BugDriver &BD,
314 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
315 std::unique_ptr<Module>, std::string &),
316 std::vector<Function *> &MiscompiledFunctions,
317 std::string &Error) {
318 bool MadeChange = false;
320 if (BugpointIsInterrupted) return MadeChange;
322 ValueToValueMapTy VMap;
323 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
324 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize.get(),
325 MiscompiledFunctions, VMap)
327 std::unique_ptr<Module> ToOptimizeLoopExtracted =
328 BD.extractLoop(ToOptimize);
329 if (!ToOptimizeLoopExtracted) {
330 // If the loop extractor crashed or if there were no extractible loops,
331 // then this chapter of our odyssey is over with.
336 errs() << "Extracted a loop from the breaking portion of the program.\n";
338 // Bugpoint is intentionally not very trusting of LLVM transformations. In
339 // particular, we're not going to assume that the loop extractor works, so
340 // we're going to test the newly loop extracted program to make sure nothing
341 // has broken. If something broke, then we'll inform the user and stop
343 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
345 Module *New = TestMergedProgram(BD, ToOptimizeLoopExtracted.get(),
346 ToNotOptimize.get(), false, Error, Failure);
350 // Delete the original and set the new program.
351 Module *Old = BD.swapProgramIn(New);
352 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
353 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
357 BD.switchToInterpreter(AI);
359 // Merged program doesn't work anymore!
360 errs() << " *** ERROR: Loop extraction broke the program. :("
361 << " Please report a bug!\n";
362 errs() << " Continuing on with un-loop-extracted version.\n";
364 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
365 ToNotOptimize.get());
366 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
368 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
369 ToOptimizeLoopExtracted.get());
371 errs() << "Please submit the "
372 << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
377 BD.switchToInterpreter(AI);
379 outs() << " Testing after loop extraction:\n";
380 // Clone modules, the tester function will free them.
381 std::unique_ptr<Module> TOLEBackup =
382 CloneModule(ToOptimizeLoopExtracted.get(), VMap);
383 std::unique_ptr<Module> TNOBackup = CloneModule(ToNotOptimize.get(), VMap);
385 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
386 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
388 Failure = TestFn(BD, std::move(ToOptimizeLoopExtracted),
389 std::move(ToNotOptimize), Error);
393 ToOptimizeLoopExtracted = std::move(TOLEBackup);
394 ToNotOptimize = std::move(TNOBackup);
397 outs() << "*** Loop extraction masked the problem. Undoing.\n";
398 // If the program is not still broken, then loop extraction did something
399 // that masked the error. Stop loop extraction now.
401 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
402 for (Function *F : MiscompiledFunctions) {
403 MisCompFunctions.emplace_back(F->getName(), F->getFunctionType());
406 if (Linker::linkModules(*ToNotOptimize, *ToOptimizeLoopExtracted,
410 MiscompiledFunctions.clear();
411 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
412 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
414 assert(NewF && "Function not found??");
415 MiscompiledFunctions.push_back(NewF);
418 BD.setNewProgram(ToNotOptimize.release());
422 outs() << "*** Loop extraction successful!\n";
424 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
425 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
426 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
427 if (!I->isDeclaration())
428 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
430 // Okay, great! Now we know that we extracted a loop and that loop
431 // extraction both didn't break the program, and didn't mask the problem.
432 // Replace the current program with the loop extracted version, and try to
433 // extract another loop.
434 if (Linker::linkModules(*ToNotOptimize, *ToOptimizeLoopExtracted,
438 // All of the Function*'s in the MiscompiledFunctions list are in the old
439 // module. Update this list to include all of the functions in the
440 // optimized and loop extracted module.
441 MiscompiledFunctions.clear();
442 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
443 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
445 assert(NewF && "Function not found??");
446 MiscompiledFunctions.push_back(NewF);
449 BD.setNewProgram(ToNotOptimize.release());
455 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
457 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
458 std::unique_ptr<Module>, std::string &);
459 std::vector<Function*> FunctionsBeingTested;
461 ReduceMiscompiledBlocks(BugDriver &bd,
462 bool (*F)(BugDriver &, std::unique_ptr<Module>,
463 std::unique_ptr<Module>, std::string &),
464 const std::vector<Function *> &Fns)
465 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
467 TestResult doTest(std::vector<BasicBlock*> &Prefix,
468 std::vector<BasicBlock*> &Suffix,
469 std::string &Error) override {
470 if (!Suffix.empty()) {
471 bool Ret = TestFuncs(Suffix, Error);
473 return InternalError;
477 if (!Prefix.empty()) {
478 bool Ret = TestFuncs(Prefix, Error);
480 return InternalError;
487 bool TestFuncs(const std::vector<BasicBlock*> &BBs, std::string &Error);
491 /// TestFuncs - Extract all blocks for the miscompiled functions except for the
492 /// specified blocks. If the problem still exists, return true.
494 bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs,
495 std::string &Error) {
496 // Test to see if the function is misoptimized if we ONLY run it on the
497 // functions listed in Funcs.
498 outs() << "Checking to see if the program is misoptimized when all ";
500 outs() << "but these " << BBs.size() << " blocks are extracted: ";
501 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
502 outs() << BBs[i]->getName() << " ";
503 if (BBs.size() > 10) outs() << "...";
505 outs() << "blocks are extracted.";
509 // Split the module into the two halves of the program we want.
510 ValueToValueMapTy VMap;
511 Module *Clone = CloneModule(BD.getProgram(), VMap).release();
512 Module *Orig = BD.swapProgramIn(Clone);
513 std::vector<Function*> FuncsOnClone;
514 std::vector<BasicBlock*> BBsOnClone;
515 for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
516 Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
517 FuncsOnClone.push_back(F);
519 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
520 BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
521 BBsOnClone.push_back(BB);
525 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
526 std::unique_ptr<Module> ToOptimize =
527 SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
529 // Try the extraction. If it doesn't work, then the block extractor crashed
530 // or something, in which case bugpoint can't chase down this possibility.
531 if (std::unique_ptr<Module> New =
532 BD.extractMappedBlocksFromModule(BBsOnClone, ToOptimize.get())) {
533 bool Ret = TestFn(BD, std::move(New), std::move(ToNotOptimize), Error);
534 delete BD.swapProgramIn(Orig);
537 delete BD.swapProgramIn(Orig);
541 /// Given a reduced list of functions that still expose the bug, extract as many
542 /// basic blocks from the region as possible without obscuring the bug.
544 static bool ExtractBlocks(BugDriver &BD,
545 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
546 std::unique_ptr<Module>,
548 std::vector<Function *> &MiscompiledFunctions,
549 std::string &Error) {
550 if (BugpointIsInterrupted) return false;
552 std::vector<BasicBlock*> Blocks;
553 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
554 for (BasicBlock &BB : *MiscompiledFunctions[i])
555 Blocks.push_back(&BB);
557 // Use the list reducer to identify blocks that can be extracted without
558 // obscuring the bug. The Blocks list will end up containing blocks that must
559 // be retained from the original program.
560 unsigned OldSize = Blocks.size();
562 // Check to see if all blocks are extractible first.
563 bool Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
564 .TestFuncs(std::vector<BasicBlock*>(), Error);
570 ReduceMiscompiledBlocks(BD, TestFn,
571 MiscompiledFunctions).reduceList(Blocks, Error);
574 if (Blocks.size() == OldSize)
578 ValueToValueMapTy VMap;
579 Module *ProgClone = CloneModule(BD.getProgram(), VMap).release();
581 SplitFunctionsOutOfModule(ProgClone, MiscompiledFunctions, VMap)
583 std::unique_ptr<Module> Extracted =
584 BD.extractMappedBlocksFromModule(Blocks, ToExtract);
586 // Weird, extraction should have worked.
587 errs() << "Nondeterministic problem extracting blocks??\n";
593 // Otherwise, block extraction succeeded. Link the two program fragments back
597 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
598 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
600 if (!I->isDeclaration())
601 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
603 if (Linker::linkModules(*ProgClone, *Extracted, diagnosticHandler))
606 // Set the new program and delete the old one.
607 BD.setNewProgram(ProgClone);
609 // Update the list of miscompiled functions.
610 MiscompiledFunctions.clear();
612 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
613 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
614 assert(NewF && "Function not found??");
615 MiscompiledFunctions.push_back(NewF);
621 /// This is a generic driver to narrow down miscompilations, either in an
622 /// optimization or a code generator.
624 static std::vector<Function *>
625 DebugAMiscompilation(BugDriver &BD,
626 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
627 std::unique_ptr<Module>, std::string &),
628 std::string &Error) {
629 // Okay, now that we have reduced the list of passes which are causing the
630 // failure, see if we can pin down which functions are being
631 // miscompiled... first build a list of all of the non-external functions in
633 std::vector<Function*> MiscompiledFunctions;
634 Module *Prog = BD.getProgram();
635 for (Function &F : *Prog)
636 if (!F.isDeclaration())
637 MiscompiledFunctions.push_back(&F);
639 // Do the reduction...
640 if (!BugpointIsInterrupted)
641 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
643 if (!Error.empty()) {
644 errs() << "\n***Cannot reduce functions: ";
645 return MiscompiledFunctions;
647 outs() << "\n*** The following function"
648 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
649 << " being miscompiled: ";
650 PrintFunctionList(MiscompiledFunctions);
653 // See if we can rip any loops out of the miscompiled functions and still
654 // trigger the problem.
656 if (!BugpointIsInterrupted && !DisableLoopExtraction) {
657 bool Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions, Error);
659 return MiscompiledFunctions;
661 // Okay, we extracted some loops and the problem still appears. See if
662 // we can eliminate some of the created functions from being candidates.
663 DisambiguateGlobalSymbols(BD.getProgram());
665 // Do the reduction...
666 if (!BugpointIsInterrupted)
667 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
670 return MiscompiledFunctions;
672 outs() << "\n*** The following function"
673 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
674 << " being miscompiled: ";
675 PrintFunctionList(MiscompiledFunctions);
680 if (!BugpointIsInterrupted && !DisableBlockExtraction) {
681 bool Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions, Error);
683 return MiscompiledFunctions;
685 // Okay, we extracted some blocks and the problem still appears. See if
686 // we can eliminate some of the created functions from being candidates.
687 DisambiguateGlobalSymbols(BD.getProgram());
689 // Do the reduction...
690 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
693 return MiscompiledFunctions;
695 outs() << "\n*** The following function"
696 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
697 << " being miscompiled: ";
698 PrintFunctionList(MiscompiledFunctions);
703 return MiscompiledFunctions;
706 /// This is the predicate function used to check to see if the "Test" portion of
707 /// the program is misoptimized. If so, return true. In any case, both module
708 /// arguments are deleted.
710 static bool TestOptimizer(BugDriver &BD, std::unique_ptr<Module> Test,
711 std::unique_ptr<Module> Safe, std::string &Error) {
712 // Run the optimization passes on ToOptimize, producing a transformed version
713 // of the functions being tested.
714 outs() << " Optimizing functions being tested: ";
715 std::unique_ptr<Module> Optimized =
716 BD.runPassesOn(Test.get(), BD.getPassesToRun(),
717 /*AutoDebugCrashes*/ true);
720 outs() << " Checking to see if the merged program executes correctly: ";
723 TestMergedProgram(BD, Optimized.get(), Safe.get(), true, Error, Broken);
725 outs() << (Broken ? " nope.\n" : " yup.\n");
726 // Delete the original and set the new program.
727 delete BD.swapProgramIn(New);
733 /// debugMiscompilation - This method is used when the passes selected are not
734 /// crashing, but the generated output is semantically different from the
737 void BugDriver::debugMiscompilation(std::string *Error) {
738 // Make sure something was miscompiled...
739 if (!BugpointIsInterrupted)
740 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun, *Error)) {
742 errs() << "*** Optimized program matches reference output! No problem"
743 << " detected...\nbugpoint can't help you with your problem!\n";
747 outs() << "\n*** Found miscompiling pass"
748 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
749 << getPassesString(getPassesToRun()) << '\n';
750 EmitProgressBitcode(Program, "passinput");
752 std::vector<Function *> MiscompiledFunctions =
753 DebugAMiscompilation(*this, TestOptimizer, *Error);
757 // Output a bunch of bitcode files for the user...
758 outs() << "Outputting reduced bitcode files which expose the problem:\n";
759 ValueToValueMapTy VMap;
760 Module *ToNotOptimize = CloneModule(getProgram(), VMap).release();
762 SplitFunctionsOutOfModule(ToNotOptimize, MiscompiledFunctions, VMap)
765 outs() << " Non-optimized portion: ";
766 EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true);
767 delete ToNotOptimize; // Delete hacked module.
769 outs() << " Portion that is input to optimizer: ";
770 EmitProgressBitcode(ToOptimize, "tooptimize");
771 delete ToOptimize; // Delete hacked module.
776 /// Get the specified modules ready for code generator testing.
778 static void CleanupAndPrepareModules(BugDriver &BD,
779 std::unique_ptr<Module> &Test,
781 // Clean up the modules, removing extra cruft that we don't need anymore...
782 Test = BD.performFinalCleanups(Test.get());
784 // If we are executing the JIT, we have several nasty issues to take care of.
785 if (!BD.isExecutingJIT()) return;
787 // First, if the main function is in the Safe module, we must add a stub to
788 // the Test module to call into it. Thus, we create a new function `main'
789 // which just calls the old one.
790 if (Function *oldMain = Safe->getFunction("main"))
791 if (!oldMain->isDeclaration()) {
793 oldMain->setName("llvm_bugpoint_old_main");
794 // Create a NEW `main' function with same type in the test module.
796 Function::Create(oldMain->getFunctionType(),
797 GlobalValue::ExternalLinkage, "main", Test.get());
798 // Create an `oldmain' prototype in the test module, which will
799 // corresponds to the real main function in the same module.
800 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
801 GlobalValue::ExternalLinkage,
802 oldMain->getName(), Test.get());
803 // Set up and remember the argument list for the main function.
804 std::vector<Value*> args;
805 for (Function::arg_iterator
806 I = newMain->arg_begin(), E = newMain->arg_end(),
807 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
808 I->setName(OI->getName()); // Copy argument names from oldMain
812 // Call the old main function and return its result
813 BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
814 CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
816 // If the type of old function wasn't void, return value of call
817 ReturnInst::Create(Safe->getContext(), call, BB);
820 // The second nasty issue we must deal with in the JIT is that the Safe
821 // module cannot directly reference any functions defined in the test
822 // module. Instead, we use a JIT API call to dynamically resolve the
825 // Add the resolver to the Safe module.
826 // Prototype: void *getPointerToNamedFunction(const char* Name)
827 Constant *resolverFunc =
828 Safe->getOrInsertFunction("getPointerToNamedFunction",
829 Type::getInt8PtrTy(Safe->getContext()),
830 Type::getInt8PtrTy(Safe->getContext()),
833 // Use the function we just added to get addresses of functions we need.
834 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
835 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
836 !F->isIntrinsic() /* ignore intrinsics */) {
837 Function *TestFn = Test->getFunction(F->getName());
839 // Don't forward functions which are external in the test module too.
840 if (TestFn && !TestFn->isDeclaration()) {
841 // 1. Add a string constant with its name to the global file
842 Constant *InitArray =
843 ConstantDataArray::getString(F->getContext(), F->getName());
844 GlobalVariable *funcName =
845 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
846 GlobalValue::InternalLinkage, InitArray,
847 F->getName() + "_name");
849 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
850 // sbyte* so it matches the signature of the resolver function.
852 // GetElementPtr *funcName, ulong 0, ulong 0
853 std::vector<Constant*> GEPargs(2,
854 Constant::getNullValue(Type::getInt32Ty(F->getContext())));
855 Value *GEP = ConstantExpr::getGetElementPtr(InitArray->getType(),
857 std::vector<Value*> ResolverArgs;
858 ResolverArgs.push_back(GEP);
860 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
861 // function that dynamically resolves the calls to F via our JIT API
862 if (!F->use_empty()) {
863 // Create a new global to hold the cached function pointer.
864 Constant *NullPtr = ConstantPointerNull::get(F->getType());
865 GlobalVariable *Cache =
866 new GlobalVariable(*F->getParent(), F->getType(),
867 false, GlobalValue::InternalLinkage,
868 NullPtr,F->getName()+".fpcache");
870 // Construct a new stub function that will re-route calls to F
871 FunctionType *FuncTy = F->getFunctionType();
872 Function *FuncWrapper = Function::Create(FuncTy,
873 GlobalValue::InternalLinkage,
874 F->getName() + "_wrapper",
876 BasicBlock *EntryBB = BasicBlock::Create(F->getContext(),
877 "entry", FuncWrapper);
878 BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
879 "usecache", FuncWrapper);
880 BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
881 "lookupfp", FuncWrapper);
883 // Check to see if we already looked up the value.
884 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
885 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
887 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
889 // Resolve the call to function F via the JIT API:
891 // call resolver(GetElementPtr...)
893 CallInst::Create(resolverFunc, ResolverArgs, "resolver", LookupBB);
895 // Cast the result from the resolver to correctly-typed function.
896 CastInst *CastedResolver =
897 new BitCastInst(Resolver,
898 PointerType::getUnqual(F->getFunctionType()),
899 "resolverCast", LookupBB);
901 // Save the value in our cache.
902 new StoreInst(CastedResolver, Cache, LookupBB);
903 BranchInst::Create(DoCallBB, LookupBB);
905 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(), 2,
907 FuncPtr->addIncoming(CastedResolver, LookupBB);
908 FuncPtr->addIncoming(CachedVal, EntryBB);
910 // Save the argument list.
911 std::vector<Value*> Args;
912 for (Argument &A : FuncWrapper->args())
915 // Pass on the arguments to the real function, return its result
916 if (F->getReturnType()->isVoidTy()) {
917 CallInst::Create(FuncPtr, Args, "", DoCallBB);
918 ReturnInst::Create(F->getContext(), DoCallBB);
920 CallInst *Call = CallInst::Create(FuncPtr, Args,
922 ReturnInst::Create(F->getContext(),Call, DoCallBB);
925 // Use the wrapper function instead of the old function
926 F->replaceAllUsesWith(FuncWrapper);
932 if (verifyModule(*Test) || verifyModule(*Safe)) {
933 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
938 /// This is the predicate function used to check to see if the "Test" portion of
939 /// the program is miscompiled by the code generator under test. If so, return
940 /// true. In any case, both module arguments are deleted.
942 static bool TestCodeGenerator(BugDriver &BD, std::unique_ptr<Module> Test,
943 std::unique_ptr<Module> Safe,
944 std::string &Error) {
945 CleanupAndPrepareModules(BD, Test, Safe.get());
947 SmallString<128> TestModuleBC;
949 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
950 TestModuleFD, TestModuleBC);
952 errs() << BD.getToolName() << "Error making unique filename: "
953 << EC.message() << "\n";
956 if (BD.writeProgramToFile(TestModuleBC.str(), TestModuleFD, Test.get())) {
957 errs() << "Error writing bitcode to `" << TestModuleBC.str()
962 FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
964 // Make the shared library
965 SmallString<128> SafeModuleBC;
967 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
970 errs() << BD.getToolName() << "Error making unique filename: "
971 << EC.message() << "\n";
975 if (BD.writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, Safe.get())) {
976 errs() << "Error writing bitcode to `" << SafeModuleBC
981 FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
983 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str(), Error);
987 FileRemover SharedObjectRemover(SharedObject, !SaveTemps);
989 // Run the code generator on the `Test' code, loading the shared library.
990 // The function returns whether or not the new output differs from reference.
991 bool Result = BD.diffProgram(BD.getProgram(), TestModuleBC.str(),
992 SharedObject, false, &Error);
997 errs() << ": still failing!\n";
999 errs() << ": didn't fail.\n";
1005 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
1007 bool BugDriver::debugCodeGenerator(std::string *Error) {
1008 if ((void*)SafeInterpreter == (void*)Interpreter) {
1009 std::string Result = executeProgramSafely(Program, "bugpoint.safe.out",
1011 if (Error->empty()) {
1012 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
1013 << "the reference diff. This may be due to a\n front-end "
1014 << "bug or a bug in the original program, but this can also "
1015 << "happen if bugpoint isn't running the program with the "
1016 << "right flags or input.\n I left the result of executing "
1017 << "the program with the \"safe\" backend in this file for "
1019 << Result << "'.\n";
1024 DisambiguateGlobalSymbols(Program);
1026 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator,
1028 if (!Error->empty())
1031 // Split the module into the two halves of the program we want.
1032 ValueToValueMapTy VMap;
1033 std::unique_ptr<Module> ToNotCodeGen = CloneModule(getProgram(), VMap);
1034 std::unique_ptr<Module> ToCodeGen =
1035 SplitFunctionsOutOfModule(ToNotCodeGen.get(), Funcs, VMap);
1037 // Condition the modules
1038 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen.get());
1040 SmallString<128> TestModuleBC;
1042 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
1043 TestModuleFD, TestModuleBC);
1045 errs() << getToolName() << "Error making unique filename: "
1046 << EC.message() << "\n";
1050 if (writeProgramToFile(TestModuleBC.str(), TestModuleFD, ToCodeGen.get())) {
1051 errs() << "Error writing bitcode to `" << TestModuleBC
1056 // Make the shared library
1057 SmallString<128> SafeModuleBC;
1059 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
1062 errs() << getToolName() << "Error making unique filename: "
1063 << EC.message() << "\n";
1067 if (writeProgramToFile(SafeModuleBC.str(), SafeModuleFD,
1068 ToNotCodeGen.get())) {
1069 errs() << "Error writing bitcode to `" << SafeModuleBC
1073 std::string SharedObject = compileSharedObject(SafeModuleBC.str(), *Error);
1074 if (!Error->empty())
1077 outs() << "You can reproduce the problem with the command line: \n";
1078 if (isExecutingJIT()) {
1079 outs() << " lli -load " << SharedObject << " " << TestModuleBC;
1081 outs() << " llc " << TestModuleBC << " -o " << TestModuleBC
1083 outs() << " cc " << SharedObject << " " << TestModuleBC.str()
1084 << ".s -o " << TestModuleBC << ".exe";
1085 #if defined (HAVE_LINK_R)
1086 outs() << " -Wl,-R.";
1089 outs() << " " << TestModuleBC << ".exe";
1091 for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
1092 outs() << " " << InputArgv[i];
1094 outs() << "The shared object was created with:\n llc -march=c "
1095 << SafeModuleBC.str() << " -o temporary.c\n"
1096 << " cc -xc temporary.c -O2 -o " << SharedObject;
1097 if (TargetTriple.getArch() == Triple::sparc)
1098 outs() << " -G"; // Compile a shared library, `-G' for Sparc
1100 outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
1102 outs() << " -fno-strict-aliasing\n";