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 /// Given two modules, link them together and run the program, checking to see
223 /// if the program matches the diff. If there is an error, return NULL. If not,
224 /// return the merged module. The Broken argument will be set to true if the
225 /// output is different. If the DeleteInputs argument is set to true then this
226 /// function deletes both input modules before it returns.
228 static std::unique_ptr<Module> testMergedProgram(const BugDriver &BD,
229 std::unique_ptr<Module> M1,
230 std::unique_ptr<Module> M2,
233 if (Linker::linkModules(*M1, *M2, diagnosticHandler))
236 // Execute the program.
237 Broken = BD.diffProgram(M1.get(), "", "", false, &Error);
243 /// TestFuncs - split functions in a Module into two groups: those that are
244 /// under consideration for miscompilation vs. those that are not, and test
245 /// accordingly. Each group of functions becomes a separate Module.
247 bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*> &Funcs,
248 std::string &Error) {
249 // Test to see if the function is misoptimized if we ONLY run it on the
250 // functions listed in Funcs.
251 outs() << "Checking to see if the program is misoptimized when "
252 << (Funcs.size()==1 ? "this function is" : "these functions are")
253 << " run through the pass"
254 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
255 PrintFunctionList(Funcs);
258 // Create a clone for two reasons:
259 // * If the optimization passes delete any function, the deleted function
260 // will be in the clone and Funcs will still point to valid memory
261 // * If the optimization passes use interprocedural information to break
262 // a function, we want to continue with the original function. Otherwise
263 // we can conclude that a function triggers the bug when in fact one
264 // needs a larger set of original functions to do so.
265 ValueToValueMapTy VMap;
266 Module *Clone = CloneModule(BD.getProgram(), VMap).release();
267 Module *Orig = BD.swapProgramIn(Clone);
269 std::vector<Function*> FuncsOnClone;
270 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
271 Function *F = cast<Function>(VMap[Funcs[i]]);
272 FuncsOnClone.push_back(F);
275 // Split the module into the two halves of the program we want.
277 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
278 std::unique_ptr<Module> ToOptimize =
279 SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
282 TestFn(BD, std::move(ToOptimize), std::move(ToNotOptimize), Error);
284 delete BD.swapProgramIn(Orig);
289 /// DisambiguateGlobalSymbols - Give anonymous global values names.
291 static void DisambiguateGlobalSymbols(Module *M) {
292 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
295 I->setName("anon_global");
296 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
298 I->setName("anon_fn");
301 /// Given a reduced list of functions that still exposed the bug, check to see
302 /// if we can extract the loops in the region without obscuring the bug. If so,
303 /// it reduces the amount of code identified.
305 static bool ExtractLoops(BugDriver &BD,
306 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
307 std::unique_ptr<Module>, std::string &),
308 std::vector<Function *> &MiscompiledFunctions,
309 std::string &Error) {
310 bool MadeChange = false;
312 if (BugpointIsInterrupted) return MadeChange;
314 ValueToValueMapTy VMap;
315 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
316 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize.get(),
317 MiscompiledFunctions, VMap)
319 std::unique_ptr<Module> ToOptimizeLoopExtracted =
320 BD.extractLoop(ToOptimize);
321 if (!ToOptimizeLoopExtracted) {
322 // If the loop extractor crashed or if there were no extractible loops,
323 // then this chapter of our odyssey is over with.
328 errs() << "Extracted a loop from the breaking portion of the program.\n";
330 // Bugpoint is intentionally not very trusting of LLVM transformations. In
331 // particular, we're not going to assume that the loop extractor works, so
332 // we're going to test the newly loop extracted program to make sure nothing
333 // has broken. If something broke, then we'll inform the user and stop
335 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
337 std::unique_ptr<Module> New =
338 testMergedProgram(BD, std::move(ToOptimizeLoopExtracted),
339 std::move(ToNotOptimize), Error, Failure);
343 // Delete the original and set the new program.
344 Module *Old = BD.swapProgramIn(New.release());
345 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
346 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
350 BD.switchToInterpreter(AI);
352 // Merged program doesn't work anymore!
353 errs() << " *** ERROR: Loop extraction broke the program. :("
354 << " Please report a bug!\n";
355 errs() << " Continuing on with un-loop-extracted version.\n";
357 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
358 ToNotOptimize.get());
359 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
361 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
362 ToOptimizeLoopExtracted.get());
364 errs() << "Please submit the "
365 << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
370 BD.switchToInterpreter(AI);
372 outs() << " Testing after loop extraction:\n";
373 // Clone modules, the tester function will free them.
374 std::unique_ptr<Module> TOLEBackup =
375 CloneModule(ToOptimizeLoopExtracted.get(), VMap);
376 std::unique_ptr<Module> TNOBackup = CloneModule(ToNotOptimize.get(), VMap);
378 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
379 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
381 Failure = TestFn(BD, std::move(ToOptimizeLoopExtracted),
382 std::move(ToNotOptimize), Error);
386 ToOptimizeLoopExtracted = std::move(TOLEBackup);
387 ToNotOptimize = std::move(TNOBackup);
390 outs() << "*** Loop extraction masked the problem. Undoing.\n";
391 // If the program is not still broken, then loop extraction did something
392 // that masked the error. Stop loop extraction now.
394 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
395 for (Function *F : MiscompiledFunctions) {
396 MisCompFunctions.emplace_back(F->getName(), F->getFunctionType());
399 if (Linker::linkModules(*ToNotOptimize, *ToOptimizeLoopExtracted,
403 MiscompiledFunctions.clear();
404 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
405 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
407 assert(NewF && "Function not found??");
408 MiscompiledFunctions.push_back(NewF);
411 BD.setNewProgram(ToNotOptimize.release());
415 outs() << "*** Loop extraction successful!\n";
417 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
418 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
419 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
420 if (!I->isDeclaration())
421 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
423 // Okay, great! Now we know that we extracted a loop and that loop
424 // extraction both didn't break the program, and didn't mask the problem.
425 // Replace the current program with the loop extracted version, and try to
426 // extract another loop.
427 if (Linker::linkModules(*ToNotOptimize, *ToOptimizeLoopExtracted,
431 // All of the Function*'s in the MiscompiledFunctions list are in the old
432 // module. Update this list to include all of the functions in the
433 // optimized and loop extracted module.
434 MiscompiledFunctions.clear();
435 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
436 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
438 assert(NewF && "Function not found??");
439 MiscompiledFunctions.push_back(NewF);
442 BD.setNewProgram(ToNotOptimize.release());
448 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
450 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
451 std::unique_ptr<Module>, std::string &);
452 std::vector<Function*> FunctionsBeingTested;
454 ReduceMiscompiledBlocks(BugDriver &bd,
455 bool (*F)(BugDriver &, std::unique_ptr<Module>,
456 std::unique_ptr<Module>, std::string &),
457 const std::vector<Function *> &Fns)
458 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
460 TestResult doTest(std::vector<BasicBlock*> &Prefix,
461 std::vector<BasicBlock*> &Suffix,
462 std::string &Error) override {
463 if (!Suffix.empty()) {
464 bool Ret = TestFuncs(Suffix, Error);
466 return InternalError;
470 if (!Prefix.empty()) {
471 bool Ret = TestFuncs(Prefix, Error);
473 return InternalError;
480 bool TestFuncs(const std::vector<BasicBlock*> &BBs, std::string &Error);
484 /// TestFuncs - Extract all blocks for the miscompiled functions except for the
485 /// specified blocks. If the problem still exists, return true.
487 bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs,
488 std::string &Error) {
489 // Test to see if the function is misoptimized if we ONLY run it on the
490 // functions listed in Funcs.
491 outs() << "Checking to see if the program is misoptimized when all ";
493 outs() << "but these " << BBs.size() << " blocks are extracted: ";
494 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
495 outs() << BBs[i]->getName() << " ";
496 if (BBs.size() > 10) outs() << "...";
498 outs() << "blocks are extracted.";
502 // Split the module into the two halves of the program we want.
503 ValueToValueMapTy VMap;
504 Module *Clone = CloneModule(BD.getProgram(), VMap).release();
505 Module *Orig = BD.swapProgramIn(Clone);
506 std::vector<Function*> FuncsOnClone;
507 std::vector<BasicBlock*> BBsOnClone;
508 for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
509 Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
510 FuncsOnClone.push_back(F);
512 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
513 BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
514 BBsOnClone.push_back(BB);
518 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
519 std::unique_ptr<Module> ToOptimize =
520 SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
522 // Try the extraction. If it doesn't work, then the block extractor crashed
523 // or something, in which case bugpoint can't chase down this possibility.
524 if (std::unique_ptr<Module> New =
525 BD.extractMappedBlocksFromModule(BBsOnClone, ToOptimize.get())) {
526 bool Ret = TestFn(BD, std::move(New), std::move(ToNotOptimize), Error);
527 delete BD.swapProgramIn(Orig);
530 delete BD.swapProgramIn(Orig);
534 /// Given a reduced list of functions that still expose the bug, extract as many
535 /// basic blocks from the region as possible without obscuring the bug.
537 static bool ExtractBlocks(BugDriver &BD,
538 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
539 std::unique_ptr<Module>,
541 std::vector<Function *> &MiscompiledFunctions,
542 std::string &Error) {
543 if (BugpointIsInterrupted) return false;
545 std::vector<BasicBlock*> Blocks;
546 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
547 for (BasicBlock &BB : *MiscompiledFunctions[i])
548 Blocks.push_back(&BB);
550 // Use the list reducer to identify blocks that can be extracted without
551 // obscuring the bug. The Blocks list will end up containing blocks that must
552 // be retained from the original program.
553 unsigned OldSize = Blocks.size();
555 // Check to see if all blocks are extractible first.
556 bool Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
557 .TestFuncs(std::vector<BasicBlock*>(), Error);
563 ReduceMiscompiledBlocks(BD, TestFn,
564 MiscompiledFunctions).reduceList(Blocks, Error);
567 if (Blocks.size() == OldSize)
571 ValueToValueMapTy VMap;
572 Module *ProgClone = CloneModule(BD.getProgram(), VMap).release();
574 SplitFunctionsOutOfModule(ProgClone, MiscompiledFunctions, VMap)
576 std::unique_ptr<Module> Extracted =
577 BD.extractMappedBlocksFromModule(Blocks, ToExtract);
579 // Weird, extraction should have worked.
580 errs() << "Nondeterministic problem extracting blocks??\n";
586 // Otherwise, block extraction succeeded. Link the two program fragments back
590 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
591 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
593 if (!I->isDeclaration())
594 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
596 if (Linker::linkModules(*ProgClone, *Extracted, diagnosticHandler))
599 // Set the new program and delete the old one.
600 BD.setNewProgram(ProgClone);
602 // Update the list of miscompiled functions.
603 MiscompiledFunctions.clear();
605 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
606 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
607 assert(NewF && "Function not found??");
608 MiscompiledFunctions.push_back(NewF);
614 /// This is a generic driver to narrow down miscompilations, either in an
615 /// optimization or a code generator.
617 static std::vector<Function *>
618 DebugAMiscompilation(BugDriver &BD,
619 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
620 std::unique_ptr<Module>, std::string &),
621 std::string &Error) {
622 // Okay, now that we have reduced the list of passes which are causing the
623 // failure, see if we can pin down which functions are being
624 // miscompiled... first build a list of all of the non-external functions in
626 std::vector<Function*> MiscompiledFunctions;
627 Module *Prog = BD.getProgram();
628 for (Function &F : *Prog)
629 if (!F.isDeclaration())
630 MiscompiledFunctions.push_back(&F);
632 // Do the reduction...
633 if (!BugpointIsInterrupted)
634 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
636 if (!Error.empty()) {
637 errs() << "\n***Cannot reduce functions: ";
638 return MiscompiledFunctions;
640 outs() << "\n*** The following function"
641 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
642 << " being miscompiled: ";
643 PrintFunctionList(MiscompiledFunctions);
646 // See if we can rip any loops out of the miscompiled functions and still
647 // trigger the problem.
649 if (!BugpointIsInterrupted && !DisableLoopExtraction) {
650 bool Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions, Error);
652 return MiscompiledFunctions;
654 // Okay, we extracted some loops and the problem still appears. See if
655 // we can eliminate some of the created functions from being candidates.
656 DisambiguateGlobalSymbols(BD.getProgram());
658 // Do the reduction...
659 if (!BugpointIsInterrupted)
660 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
663 return MiscompiledFunctions;
665 outs() << "\n*** The following function"
666 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
667 << " being miscompiled: ";
668 PrintFunctionList(MiscompiledFunctions);
673 if (!BugpointIsInterrupted && !DisableBlockExtraction) {
674 bool Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions, Error);
676 return MiscompiledFunctions;
678 // Okay, we extracted some blocks and the problem still appears. See if
679 // we can eliminate some of the created functions from being candidates.
680 DisambiguateGlobalSymbols(BD.getProgram());
682 // Do the reduction...
683 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
686 return MiscompiledFunctions;
688 outs() << "\n*** The following function"
689 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
690 << " being miscompiled: ";
691 PrintFunctionList(MiscompiledFunctions);
696 return MiscompiledFunctions;
699 /// This is the predicate function used to check to see if the "Test" portion of
700 /// the program is misoptimized. If so, return true. In any case, both module
701 /// arguments are deleted.
703 static bool TestOptimizer(BugDriver &BD, std::unique_ptr<Module> Test,
704 std::unique_ptr<Module> Safe, std::string &Error) {
705 // Run the optimization passes on ToOptimize, producing a transformed version
706 // of the functions being tested.
707 outs() << " Optimizing functions being tested: ";
708 std::unique_ptr<Module> Optimized =
709 BD.runPassesOn(Test.get(), BD.getPassesToRun(),
710 /*AutoDebugCrashes*/ true);
713 outs() << " Checking to see if the merged program executes correctly: ";
715 std::unique_ptr<Module> New = testMergedProgram(
716 BD, std::move(Optimized), std::move(Safe), Error, Broken);
718 outs() << (Broken ? " nope.\n" : " yup.\n");
719 // Delete the original and set the new program.
720 delete BD.swapProgramIn(New.release());
726 /// debugMiscompilation - This method is used when the passes selected are not
727 /// crashing, but the generated output is semantically different from the
730 void BugDriver::debugMiscompilation(std::string *Error) {
731 // Make sure something was miscompiled...
732 if (!BugpointIsInterrupted)
733 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun, *Error)) {
735 errs() << "*** Optimized program matches reference output! No problem"
736 << " detected...\nbugpoint can't help you with your problem!\n";
740 outs() << "\n*** Found miscompiling pass"
741 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
742 << getPassesString(getPassesToRun()) << '\n';
743 EmitProgressBitcode(Program, "passinput");
745 std::vector<Function *> MiscompiledFunctions =
746 DebugAMiscompilation(*this, TestOptimizer, *Error);
750 // Output a bunch of bitcode files for the user...
751 outs() << "Outputting reduced bitcode files which expose the problem:\n";
752 ValueToValueMapTy VMap;
753 Module *ToNotOptimize = CloneModule(getProgram(), VMap).release();
755 SplitFunctionsOutOfModule(ToNotOptimize, MiscompiledFunctions, VMap)
758 outs() << " Non-optimized portion: ";
759 EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true);
760 delete ToNotOptimize; // Delete hacked module.
762 outs() << " Portion that is input to optimizer: ";
763 EmitProgressBitcode(ToOptimize, "tooptimize");
764 delete ToOptimize; // Delete hacked module.
769 /// Get the specified modules ready for code generator testing.
771 static void CleanupAndPrepareModules(BugDriver &BD,
772 std::unique_ptr<Module> &Test,
774 // Clean up the modules, removing extra cruft that we don't need anymore...
775 Test = BD.performFinalCleanups(Test.get());
777 // If we are executing the JIT, we have several nasty issues to take care of.
778 if (!BD.isExecutingJIT()) return;
780 // First, if the main function is in the Safe module, we must add a stub to
781 // the Test module to call into it. Thus, we create a new function `main'
782 // which just calls the old one.
783 if (Function *oldMain = Safe->getFunction("main"))
784 if (!oldMain->isDeclaration()) {
786 oldMain->setName("llvm_bugpoint_old_main");
787 // Create a NEW `main' function with same type in the test module.
789 Function::Create(oldMain->getFunctionType(),
790 GlobalValue::ExternalLinkage, "main", Test.get());
791 // Create an `oldmain' prototype in the test module, which will
792 // corresponds to the real main function in the same module.
793 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
794 GlobalValue::ExternalLinkage,
795 oldMain->getName(), Test.get());
796 // Set up and remember the argument list for the main function.
797 std::vector<Value*> args;
798 for (Function::arg_iterator
799 I = newMain->arg_begin(), E = newMain->arg_end(),
800 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
801 I->setName(OI->getName()); // Copy argument names from oldMain
805 // Call the old main function and return its result
806 BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
807 CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
809 // If the type of old function wasn't void, return value of call
810 ReturnInst::Create(Safe->getContext(), call, BB);
813 // The second nasty issue we must deal with in the JIT is that the Safe
814 // module cannot directly reference any functions defined in the test
815 // module. Instead, we use a JIT API call to dynamically resolve the
818 // Add the resolver to the Safe module.
819 // Prototype: void *getPointerToNamedFunction(const char* Name)
820 Constant *resolverFunc =
821 Safe->getOrInsertFunction("getPointerToNamedFunction",
822 Type::getInt8PtrTy(Safe->getContext()),
823 Type::getInt8PtrTy(Safe->getContext()),
826 // Use the function we just added to get addresses of functions we need.
827 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
828 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
829 !F->isIntrinsic() /* ignore intrinsics */) {
830 Function *TestFn = Test->getFunction(F->getName());
832 // Don't forward functions which are external in the test module too.
833 if (TestFn && !TestFn->isDeclaration()) {
834 // 1. Add a string constant with its name to the global file
835 Constant *InitArray =
836 ConstantDataArray::getString(F->getContext(), F->getName());
837 GlobalVariable *funcName =
838 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
839 GlobalValue::InternalLinkage, InitArray,
840 F->getName() + "_name");
842 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
843 // sbyte* so it matches the signature of the resolver function.
845 // GetElementPtr *funcName, ulong 0, ulong 0
846 std::vector<Constant*> GEPargs(2,
847 Constant::getNullValue(Type::getInt32Ty(F->getContext())));
848 Value *GEP = ConstantExpr::getGetElementPtr(InitArray->getType(),
850 std::vector<Value*> ResolverArgs;
851 ResolverArgs.push_back(GEP);
853 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
854 // function that dynamically resolves the calls to F via our JIT API
855 if (!F->use_empty()) {
856 // Create a new global to hold the cached function pointer.
857 Constant *NullPtr = ConstantPointerNull::get(F->getType());
858 GlobalVariable *Cache =
859 new GlobalVariable(*F->getParent(), F->getType(),
860 false, GlobalValue::InternalLinkage,
861 NullPtr,F->getName()+".fpcache");
863 // Construct a new stub function that will re-route calls to F
864 FunctionType *FuncTy = F->getFunctionType();
865 Function *FuncWrapper = Function::Create(FuncTy,
866 GlobalValue::InternalLinkage,
867 F->getName() + "_wrapper",
869 BasicBlock *EntryBB = BasicBlock::Create(F->getContext(),
870 "entry", FuncWrapper);
871 BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
872 "usecache", FuncWrapper);
873 BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
874 "lookupfp", FuncWrapper);
876 // Check to see if we already looked up the value.
877 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
878 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
880 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
882 // Resolve the call to function F via the JIT API:
884 // call resolver(GetElementPtr...)
886 CallInst::Create(resolverFunc, ResolverArgs, "resolver", LookupBB);
888 // Cast the result from the resolver to correctly-typed function.
889 CastInst *CastedResolver =
890 new BitCastInst(Resolver,
891 PointerType::getUnqual(F->getFunctionType()),
892 "resolverCast", LookupBB);
894 // Save the value in our cache.
895 new StoreInst(CastedResolver, Cache, LookupBB);
896 BranchInst::Create(DoCallBB, LookupBB);
898 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(), 2,
900 FuncPtr->addIncoming(CastedResolver, LookupBB);
901 FuncPtr->addIncoming(CachedVal, EntryBB);
903 // Save the argument list.
904 std::vector<Value*> Args;
905 for (Argument &A : FuncWrapper->args())
908 // Pass on the arguments to the real function, return its result
909 if (F->getReturnType()->isVoidTy()) {
910 CallInst::Create(FuncPtr, Args, "", DoCallBB);
911 ReturnInst::Create(F->getContext(), DoCallBB);
913 CallInst *Call = CallInst::Create(FuncPtr, Args,
915 ReturnInst::Create(F->getContext(),Call, DoCallBB);
918 // Use the wrapper function instead of the old function
919 F->replaceAllUsesWith(FuncWrapper);
925 if (verifyModule(*Test) || verifyModule(*Safe)) {
926 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
931 /// This is the predicate function used to check to see if the "Test" portion of
932 /// the program is miscompiled by the code generator under test. If so, return
933 /// true. In any case, both module arguments are deleted.
935 static bool TestCodeGenerator(BugDriver &BD, std::unique_ptr<Module> Test,
936 std::unique_ptr<Module> Safe,
937 std::string &Error) {
938 CleanupAndPrepareModules(BD, Test, Safe.get());
940 SmallString<128> TestModuleBC;
942 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
943 TestModuleFD, TestModuleBC);
945 errs() << BD.getToolName() << "Error making unique filename: "
946 << EC.message() << "\n";
949 if (BD.writeProgramToFile(TestModuleBC.str(), TestModuleFD, Test.get())) {
950 errs() << "Error writing bitcode to `" << TestModuleBC.str()
955 FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
957 // Make the shared library
958 SmallString<128> SafeModuleBC;
960 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
963 errs() << BD.getToolName() << "Error making unique filename: "
964 << EC.message() << "\n";
968 if (BD.writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, Safe.get())) {
969 errs() << "Error writing bitcode to `" << SafeModuleBC
974 FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
976 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str(), Error);
980 FileRemover SharedObjectRemover(SharedObject, !SaveTemps);
982 // Run the code generator on the `Test' code, loading the shared library.
983 // The function returns whether or not the new output differs from reference.
984 bool Result = BD.diffProgram(BD.getProgram(), TestModuleBC.str(),
985 SharedObject, false, &Error);
990 errs() << ": still failing!\n";
992 errs() << ": didn't fail.\n";
998 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
1000 bool BugDriver::debugCodeGenerator(std::string *Error) {
1001 if ((void*)SafeInterpreter == (void*)Interpreter) {
1002 std::string Result = executeProgramSafely(Program, "bugpoint.safe.out",
1004 if (Error->empty()) {
1005 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
1006 << "the reference diff. This may be due to a\n front-end "
1007 << "bug or a bug in the original program, but this can also "
1008 << "happen if bugpoint isn't running the program with the "
1009 << "right flags or input.\n I left the result of executing "
1010 << "the program with the \"safe\" backend in this file for "
1012 << Result << "'.\n";
1017 DisambiguateGlobalSymbols(Program);
1019 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator,
1021 if (!Error->empty())
1024 // Split the module into the two halves of the program we want.
1025 ValueToValueMapTy VMap;
1026 std::unique_ptr<Module> ToNotCodeGen = CloneModule(getProgram(), VMap);
1027 std::unique_ptr<Module> ToCodeGen =
1028 SplitFunctionsOutOfModule(ToNotCodeGen.get(), Funcs, VMap);
1030 // Condition the modules
1031 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen.get());
1033 SmallString<128> TestModuleBC;
1035 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
1036 TestModuleFD, TestModuleBC);
1038 errs() << getToolName() << "Error making unique filename: "
1039 << EC.message() << "\n";
1043 if (writeProgramToFile(TestModuleBC.str(), TestModuleFD, ToCodeGen.get())) {
1044 errs() << "Error writing bitcode to `" << TestModuleBC
1049 // Make the shared library
1050 SmallString<128> SafeModuleBC;
1052 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
1055 errs() << getToolName() << "Error making unique filename: "
1056 << EC.message() << "\n";
1060 if (writeProgramToFile(SafeModuleBC.str(), SafeModuleFD,
1061 ToNotCodeGen.get())) {
1062 errs() << "Error writing bitcode to `" << SafeModuleBC
1066 std::string SharedObject = compileSharedObject(SafeModuleBC.str(), *Error);
1067 if (!Error->empty())
1070 outs() << "You can reproduce the problem with the command line: \n";
1071 if (isExecutingJIT()) {
1072 outs() << " lli -load " << SharedObject << " " << TestModuleBC;
1074 outs() << " llc " << TestModuleBC << " -o " << TestModuleBC
1076 outs() << " cc " << SharedObject << " " << TestModuleBC.str()
1077 << ".s -o " << TestModuleBC << ".exe";
1078 #if defined (HAVE_LINK_R)
1079 outs() << " -Wl,-R.";
1082 outs() << " " << TestModuleBC << ".exe";
1084 for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
1085 outs() << " " << InputArgv[i];
1087 outs() << "The shared object was created with:\n llc -march=c "
1088 << SafeModuleBC.str() << " -o temporary.c\n"
1089 << " cc -xc temporary.c -O2 -o " << SharedObject;
1090 if (TargetTriple.getArch() == Triple::sparc)
1091 outs() << " -G"; // Compile a shared library, `-G' for Sparc
1093 outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
1095 outs() << " -fno-strict-aliasing\n";