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/Instructions.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/IR/Verifier.h"
24 #include "llvm/Linker/Linker.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/FileUtilities.h"
28 #include "llvm/Transforms/Utils/Cloning.h"
33 extern cl::opt<std::string> OutputPrefix;
34 extern cl::list<std::string> InputArgv;
35 } // end namespace llvm
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;
56 } // end anonymous namespace
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);
212 } // end anonymous namespace
214 /// Given two modules, link them together and run the program, checking to see
215 /// if the program matches the diff. If there is an error, return NULL. If not,
216 /// return the merged module. The Broken argument will be set to true if the
217 /// output is different. If the DeleteInputs argument is set to true then this
218 /// function deletes both input modules before it returns.
220 static std::unique_ptr<Module> testMergedProgram(const BugDriver &BD,
221 std::unique_ptr<Module> M1,
222 std::unique_ptr<Module> M2,
225 if (Linker::linkModules(*M1, std::move(M2)))
228 // Execute the program.
229 Broken = BD.diffProgram(M1.get(), "", "", false, &Error);
235 /// TestFuncs - split functions in a Module into two groups: those that are
236 /// under consideration for miscompilation vs. those that are not, and test
237 /// accordingly. Each group of functions becomes a separate Module.
239 bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*> &Funcs,
240 std::string &Error) {
241 // Test to see if the function is misoptimized if we ONLY run it on the
242 // functions listed in Funcs.
243 outs() << "Checking to see if the program is misoptimized when "
244 << (Funcs.size()==1 ? "this function is" : "these functions are")
245 << " run through the pass"
246 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
247 PrintFunctionList(Funcs);
250 // Create a clone for two reasons:
251 // * If the optimization passes delete any function, the deleted function
252 // will be in the clone and Funcs will still point to valid memory
253 // * If the optimization passes use interprocedural information to break
254 // a function, we want to continue with the original function. Otherwise
255 // we can conclude that a function triggers the bug when in fact one
256 // needs a larger set of original functions to do so.
257 ValueToValueMapTy VMap;
258 Module *Clone = CloneModule(BD.getProgram(), VMap).release();
259 Module *Orig = BD.swapProgramIn(Clone);
261 std::vector<Function*> FuncsOnClone;
262 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
263 Function *F = cast<Function>(VMap[Funcs[i]]);
264 FuncsOnClone.push_back(F);
267 // Split the module into the two halves of the program we want.
269 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
270 std::unique_ptr<Module> ToOptimize =
271 SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
274 TestFn(BD, std::move(ToOptimize), std::move(ToNotOptimize), Error);
276 delete BD.swapProgramIn(Orig);
281 /// DisambiguateGlobalSymbols - Give anonymous global values names.
283 static void DisambiguateGlobalSymbols(Module *M) {
284 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
287 I->setName("anon_global");
288 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
290 I->setName("anon_fn");
293 /// Given a reduced list of functions that still exposed the bug, check to see
294 /// if we can extract the loops in the region without obscuring the bug. If so,
295 /// it reduces the amount of code identified.
297 static bool ExtractLoops(BugDriver &BD,
298 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
299 std::unique_ptr<Module>, std::string &),
300 std::vector<Function *> &MiscompiledFunctions,
301 std::string &Error) {
302 bool MadeChange = false;
304 if (BugpointIsInterrupted) return MadeChange;
306 ValueToValueMapTy VMap;
307 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
308 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize.get(),
309 MiscompiledFunctions, VMap)
311 std::unique_ptr<Module> ToOptimizeLoopExtracted =
312 BD.extractLoop(ToOptimize);
313 if (!ToOptimizeLoopExtracted) {
314 // If the loop extractor crashed or if there were no extractible loops,
315 // then this chapter of our odyssey is over with.
320 errs() << "Extracted a loop from the breaking portion of the program.\n";
322 // Bugpoint is intentionally not very trusting of LLVM transformations. In
323 // particular, we're not going to assume that the loop extractor works, so
324 // we're going to test the newly loop extracted program to make sure nothing
325 // has broken. If something broke, then we'll inform the user and stop
327 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
329 std::unique_ptr<Module> New =
330 testMergedProgram(BD, std::move(ToOptimizeLoopExtracted),
331 std::move(ToNotOptimize), Error, Failure);
335 // Delete the original and set the new program.
336 Module *Old = BD.swapProgramIn(New.release());
337 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
338 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
342 BD.switchToInterpreter(AI);
344 // Merged program doesn't work anymore!
345 errs() << " *** ERROR: Loop extraction broke the program. :("
346 << " Please report a bug!\n";
347 errs() << " Continuing on with un-loop-extracted version.\n";
349 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
350 ToNotOptimize.get());
351 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
353 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
354 ToOptimizeLoopExtracted.get());
356 errs() << "Please submit the "
357 << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
362 BD.switchToInterpreter(AI);
364 outs() << " Testing after loop extraction:\n";
365 // Clone modules, the tester function will free them.
366 std::unique_ptr<Module> TOLEBackup =
367 CloneModule(ToOptimizeLoopExtracted.get(), VMap);
368 std::unique_ptr<Module> TNOBackup = CloneModule(ToNotOptimize.get(), VMap);
370 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
371 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
373 Failure = TestFn(BD, std::move(ToOptimizeLoopExtracted),
374 std::move(ToNotOptimize), Error);
378 ToOptimizeLoopExtracted = std::move(TOLEBackup);
379 ToNotOptimize = std::move(TNOBackup);
382 outs() << "*** Loop extraction masked the problem. Undoing.\n";
383 // If the program is not still broken, then loop extraction did something
384 // that masked the error. Stop loop extraction now.
386 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
387 for (Function *F : MiscompiledFunctions) {
388 MisCompFunctions.emplace_back(F->getName(), F->getFunctionType());
391 if (Linker::linkModules(*ToNotOptimize,
392 std::move(ToOptimizeLoopExtracted)))
395 MiscompiledFunctions.clear();
396 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
397 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
399 assert(NewF && "Function not found??");
400 MiscompiledFunctions.push_back(NewF);
403 BD.setNewProgram(ToNotOptimize.release());
407 outs() << "*** Loop extraction successful!\n";
409 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
410 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
411 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
412 if (!I->isDeclaration())
413 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
415 // Okay, great! Now we know that we extracted a loop and that loop
416 // extraction both didn't break the program, and didn't mask the problem.
417 // Replace the current program with the loop extracted version, and try to
418 // extract another loop.
419 if (Linker::linkModules(*ToNotOptimize, std::move(ToOptimizeLoopExtracted)))
422 // All of the Function*'s in the MiscompiledFunctions list are in the old
423 // module. Update this list to include all of the functions in the
424 // optimized and loop extracted module.
425 MiscompiledFunctions.clear();
426 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
427 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
429 assert(NewF && "Function not found??");
430 MiscompiledFunctions.push_back(NewF);
433 BD.setNewProgram(ToNotOptimize.release());
439 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
441 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
442 std::unique_ptr<Module>, std::string &);
443 std::vector<Function*> FunctionsBeingTested;
445 ReduceMiscompiledBlocks(BugDriver &bd,
446 bool (*F)(BugDriver &, std::unique_ptr<Module>,
447 std::unique_ptr<Module>, std::string &),
448 const std::vector<Function *> &Fns)
449 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
451 TestResult doTest(std::vector<BasicBlock*> &Prefix,
452 std::vector<BasicBlock*> &Suffix,
453 std::string &Error) override {
454 if (!Suffix.empty()) {
455 bool Ret = TestFuncs(Suffix, Error);
457 return InternalError;
461 if (!Prefix.empty()) {
462 bool Ret = TestFuncs(Prefix, Error);
464 return InternalError;
471 bool TestFuncs(const std::vector<BasicBlock*> &BBs, std::string &Error);
473 } // end anonymous namespace
475 /// TestFuncs - Extract all blocks for the miscompiled functions except for the
476 /// specified blocks. If the problem still exists, return true.
478 bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs,
479 std::string &Error) {
480 // Test to see if the function is misoptimized if we ONLY run it on the
481 // functions listed in Funcs.
482 outs() << "Checking to see if the program is misoptimized when all ";
484 outs() << "but these " << BBs.size() << " blocks are extracted: ";
485 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
486 outs() << BBs[i]->getName() << " ";
487 if (BBs.size() > 10) outs() << "...";
489 outs() << "blocks are extracted.";
493 // Split the module into the two halves of the program we want.
494 ValueToValueMapTy VMap;
495 Module *Clone = CloneModule(BD.getProgram(), VMap).release();
496 Module *Orig = BD.swapProgramIn(Clone);
497 std::vector<Function*> FuncsOnClone;
498 std::vector<BasicBlock*> BBsOnClone;
499 for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
500 Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
501 FuncsOnClone.push_back(F);
503 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
504 BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
505 BBsOnClone.push_back(BB);
509 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
510 std::unique_ptr<Module> ToOptimize =
511 SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
513 // Try the extraction. If it doesn't work, then the block extractor crashed
514 // or something, in which case bugpoint can't chase down this possibility.
515 if (std::unique_ptr<Module> New =
516 BD.extractMappedBlocksFromModule(BBsOnClone, ToOptimize.get())) {
517 bool Ret = TestFn(BD, std::move(New), std::move(ToNotOptimize), Error);
518 delete BD.swapProgramIn(Orig);
521 delete BD.swapProgramIn(Orig);
525 /// Given a reduced list of functions that still expose the bug, extract as many
526 /// basic blocks from the region as possible without obscuring the bug.
528 static bool ExtractBlocks(BugDriver &BD,
529 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
530 std::unique_ptr<Module>,
532 std::vector<Function *> &MiscompiledFunctions,
533 std::string &Error) {
534 if (BugpointIsInterrupted) return false;
536 std::vector<BasicBlock*> Blocks;
537 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
538 for (BasicBlock &BB : *MiscompiledFunctions[i])
539 Blocks.push_back(&BB);
541 // Use the list reducer to identify blocks that can be extracted without
542 // obscuring the bug. The Blocks list will end up containing blocks that must
543 // be retained from the original program.
544 unsigned OldSize = Blocks.size();
546 // Check to see if all blocks are extractible first.
547 bool Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
548 .TestFuncs(std::vector<BasicBlock*>(), Error);
554 ReduceMiscompiledBlocks(BD, TestFn,
555 MiscompiledFunctions).reduceList(Blocks, Error);
558 if (Blocks.size() == OldSize)
562 ValueToValueMapTy VMap;
563 Module *ProgClone = CloneModule(BD.getProgram(), VMap).release();
565 SplitFunctionsOutOfModule(ProgClone, MiscompiledFunctions, VMap)
567 std::unique_ptr<Module> Extracted =
568 BD.extractMappedBlocksFromModule(Blocks, ToExtract);
570 // Weird, extraction should have worked.
571 errs() << "Nondeterministic problem extracting blocks??\n";
577 // Otherwise, block extraction succeeded. Link the two program fragments back
581 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
582 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
584 if (!I->isDeclaration())
585 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
587 if (Linker::linkModules(*ProgClone, std::move(Extracted)))
590 // Set the new program and delete the old one.
591 BD.setNewProgram(ProgClone);
593 // Update the list of miscompiled functions.
594 MiscompiledFunctions.clear();
596 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
597 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
598 assert(NewF && "Function not found??");
599 MiscompiledFunctions.push_back(NewF);
605 /// This is a generic driver to narrow down miscompilations, either in an
606 /// optimization or a code generator.
608 static std::vector<Function *>
609 DebugAMiscompilation(BugDriver &BD,
610 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
611 std::unique_ptr<Module>, std::string &),
612 std::string &Error) {
613 // Okay, now that we have reduced the list of passes which are causing the
614 // failure, see if we can pin down which functions are being
615 // miscompiled... first build a list of all of the non-external functions in
617 std::vector<Function*> MiscompiledFunctions;
618 Module *Prog = BD.getProgram();
619 for (Function &F : *Prog)
620 if (!F.isDeclaration())
621 MiscompiledFunctions.push_back(&F);
623 // Do the reduction...
624 if (!BugpointIsInterrupted)
625 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
627 if (!Error.empty()) {
628 errs() << "\n***Cannot reduce functions: ";
629 return MiscompiledFunctions;
631 outs() << "\n*** The following function"
632 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
633 << " being miscompiled: ";
634 PrintFunctionList(MiscompiledFunctions);
637 // See if we can rip any loops out of the miscompiled functions and still
638 // trigger the problem.
640 if (!BugpointIsInterrupted && !DisableLoopExtraction) {
641 bool Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions, Error);
643 return MiscompiledFunctions;
645 // Okay, we extracted some loops and the problem still appears. See if
646 // we can eliminate some of the created functions from being candidates.
647 DisambiguateGlobalSymbols(BD.getProgram());
649 // Do the reduction...
650 if (!BugpointIsInterrupted)
651 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
654 return MiscompiledFunctions;
656 outs() << "\n*** The following function"
657 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
658 << " being miscompiled: ";
659 PrintFunctionList(MiscompiledFunctions);
664 if (!BugpointIsInterrupted && !DisableBlockExtraction) {
665 bool Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions, Error);
667 return MiscompiledFunctions;
669 // Okay, we extracted some blocks and the problem still appears. See if
670 // we can eliminate some of the created functions from being candidates.
671 DisambiguateGlobalSymbols(BD.getProgram());
673 // Do the reduction...
674 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
677 return MiscompiledFunctions;
679 outs() << "\n*** The following function"
680 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
681 << " being miscompiled: ";
682 PrintFunctionList(MiscompiledFunctions);
687 return MiscompiledFunctions;
690 /// This is the predicate function used to check to see if the "Test" portion of
691 /// the program is misoptimized. If so, return true. In any case, both module
692 /// arguments are deleted.
694 static bool TestOptimizer(BugDriver &BD, std::unique_ptr<Module> Test,
695 std::unique_ptr<Module> Safe, std::string &Error) {
696 // Run the optimization passes on ToOptimize, producing a transformed version
697 // of the functions being tested.
698 outs() << " Optimizing functions being tested: ";
699 std::unique_ptr<Module> Optimized =
700 BD.runPassesOn(Test.get(), BD.getPassesToRun());
702 errs() << " Error running this sequence of passes"
703 << " on the input program!\n";
704 delete BD.swapProgramIn(Test.get());
705 BD.EmitProgressBitcode(Test.get(), "pass-error", false);
706 return BD.debugOptimizerCrash();
710 outs() << " Checking to see if the merged program executes correctly: ";
712 std::unique_ptr<Module> New = testMergedProgram(
713 BD, std::move(Optimized), std::move(Safe), Error, Broken);
715 outs() << (Broken ? " nope.\n" : " yup.\n");
716 // Delete the original and set the new program.
717 delete BD.swapProgramIn(New.release());
722 /// debugMiscompilation - This method is used when the passes selected are not
723 /// crashing, but the generated output is semantically different from the
726 void BugDriver::debugMiscompilation(std::string *Error) {
727 // Make sure something was miscompiled...
728 if (!BugpointIsInterrupted)
729 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun, *Error)) {
731 errs() << "*** Optimized program matches reference output! No problem"
732 << " detected...\nbugpoint can't help you with your problem!\n";
736 outs() << "\n*** Found miscompiling pass"
737 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
738 << getPassesString(getPassesToRun()) << '\n';
739 EmitProgressBitcode(Program, "passinput");
741 std::vector<Function *> MiscompiledFunctions =
742 DebugAMiscompilation(*this, TestOptimizer, *Error);
746 // Output a bunch of bitcode files for the user...
747 outs() << "Outputting reduced bitcode files which expose the problem:\n";
748 ValueToValueMapTy VMap;
749 Module *ToNotOptimize = CloneModule(getProgram(), VMap).release();
751 SplitFunctionsOutOfModule(ToNotOptimize, MiscompiledFunctions, VMap)
754 outs() << " Non-optimized portion: ";
755 EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true);
756 delete ToNotOptimize; // Delete hacked module.
758 outs() << " Portion that is input to optimizer: ";
759 EmitProgressBitcode(ToOptimize, "tooptimize");
760 delete ToOptimize; // Delete hacked module.
763 /// Get the specified modules ready for code generator testing.
765 static void CleanupAndPrepareModules(BugDriver &BD,
766 std::unique_ptr<Module> &Test,
768 // Clean up the modules, removing extra cruft that we don't need anymore...
769 Test = BD.performFinalCleanups(Test.get());
771 // If we are executing the JIT, we have several nasty issues to take care of.
772 if (!BD.isExecutingJIT()) return;
774 // First, if the main function is in the Safe module, we must add a stub to
775 // the Test module to call into it. Thus, we create a new function `main'
776 // which just calls the old one.
777 if (Function *oldMain = Safe->getFunction("main"))
778 if (!oldMain->isDeclaration()) {
780 oldMain->setName("llvm_bugpoint_old_main");
781 // Create a NEW `main' function with same type in the test module.
783 Function::Create(oldMain->getFunctionType(),
784 GlobalValue::ExternalLinkage, "main", Test.get());
785 // Create an `oldmain' prototype in the test module, which will
786 // corresponds to the real main function in the same module.
787 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
788 GlobalValue::ExternalLinkage,
789 oldMain->getName(), Test.get());
790 // Set up and remember the argument list for the main function.
791 std::vector<Value*> args;
792 for (Function::arg_iterator
793 I = newMain->arg_begin(), E = newMain->arg_end(),
794 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
795 I->setName(OI->getName()); // Copy argument names from oldMain
799 // Call the old main function and return its result
800 BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
801 CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
803 // If the type of old function wasn't void, return value of call
804 ReturnInst::Create(Safe->getContext(), call, BB);
807 // The second nasty issue we must deal with in the JIT is that the Safe
808 // module cannot directly reference any functions defined in the test
809 // module. Instead, we use a JIT API call to dynamically resolve the
812 // Add the resolver to the Safe module.
813 // Prototype: void *getPointerToNamedFunction(const char* Name)
814 Constant *resolverFunc =
815 Safe->getOrInsertFunction("getPointerToNamedFunction",
816 Type::getInt8PtrTy(Safe->getContext()),
817 Type::getInt8PtrTy(Safe->getContext()),
820 // Use the function we just added to get addresses of functions we need.
821 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
822 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
823 !F->isIntrinsic() /* ignore intrinsics */) {
824 Function *TestFn = Test->getFunction(F->getName());
826 // Don't forward functions which are external in the test module too.
827 if (TestFn && !TestFn->isDeclaration()) {
828 // 1. Add a string constant with its name to the global file
829 Constant *InitArray =
830 ConstantDataArray::getString(F->getContext(), F->getName());
831 GlobalVariable *funcName =
832 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
833 GlobalValue::InternalLinkage, InitArray,
834 F->getName() + "_name");
836 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
837 // sbyte* so it matches the signature of the resolver function.
839 // GetElementPtr *funcName, ulong 0, ulong 0
840 std::vector<Constant*> GEPargs(2,
841 Constant::getNullValue(Type::getInt32Ty(F->getContext())));
842 Value *GEP = ConstantExpr::getGetElementPtr(InitArray->getType(),
844 std::vector<Value*> ResolverArgs;
845 ResolverArgs.push_back(GEP);
847 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
848 // function that dynamically resolves the calls to F via our JIT API
849 if (!F->use_empty()) {
850 // Create a new global to hold the cached function pointer.
851 Constant *NullPtr = ConstantPointerNull::get(F->getType());
852 GlobalVariable *Cache =
853 new GlobalVariable(*F->getParent(), F->getType(),
854 false, GlobalValue::InternalLinkage,
855 NullPtr,F->getName()+".fpcache");
857 // Construct a new stub function that will re-route calls to F
858 FunctionType *FuncTy = F->getFunctionType();
859 Function *FuncWrapper = Function::Create(FuncTy,
860 GlobalValue::InternalLinkage,
861 F->getName() + "_wrapper",
863 BasicBlock *EntryBB = BasicBlock::Create(F->getContext(),
864 "entry", FuncWrapper);
865 BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
866 "usecache", FuncWrapper);
867 BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
868 "lookupfp", FuncWrapper);
870 // Check to see if we already looked up the value.
871 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
872 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
874 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
876 // Resolve the call to function F via the JIT API:
878 // call resolver(GetElementPtr...)
880 CallInst::Create(resolverFunc, ResolverArgs, "resolver", LookupBB);
882 // Cast the result from the resolver to correctly-typed function.
883 CastInst *CastedResolver =
884 new BitCastInst(Resolver,
885 PointerType::getUnqual(F->getFunctionType()),
886 "resolverCast", LookupBB);
888 // Save the value in our cache.
889 new StoreInst(CastedResolver, Cache, LookupBB);
890 BranchInst::Create(DoCallBB, LookupBB);
892 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(), 2,
894 FuncPtr->addIncoming(CastedResolver, LookupBB);
895 FuncPtr->addIncoming(CachedVal, EntryBB);
897 // Save the argument list.
898 std::vector<Value*> Args;
899 for (Argument &A : FuncWrapper->args())
902 // Pass on the arguments to the real function, return its result
903 if (F->getReturnType()->isVoidTy()) {
904 CallInst::Create(FuncPtr, Args, "", DoCallBB);
905 ReturnInst::Create(F->getContext(), DoCallBB);
907 CallInst *Call = CallInst::Create(FuncPtr, Args,
909 ReturnInst::Create(F->getContext(),Call, DoCallBB);
912 // Use the wrapper function instead of the old function
913 F->replaceAllUsesWith(FuncWrapper);
919 if (verifyModule(*Test) || verifyModule(*Safe)) {
920 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
925 /// This is the predicate function used to check to see if the "Test" portion of
926 /// the program is miscompiled by the code generator under test. If so, return
927 /// true. In any case, both module arguments are deleted.
929 static bool TestCodeGenerator(BugDriver &BD, std::unique_ptr<Module> Test,
930 std::unique_ptr<Module> Safe,
931 std::string &Error) {
932 CleanupAndPrepareModules(BD, Test, Safe.get());
934 SmallString<128> TestModuleBC;
936 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
937 TestModuleFD, TestModuleBC);
939 errs() << BD.getToolName() << "Error making unique filename: "
940 << EC.message() << "\n";
943 if (BD.writeProgramToFile(TestModuleBC.str(), TestModuleFD, Test.get())) {
944 errs() << "Error writing bitcode to `" << TestModuleBC.str()
949 FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
951 // Make the shared library
952 SmallString<128> SafeModuleBC;
954 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
957 errs() << BD.getToolName() << "Error making unique filename: "
958 << EC.message() << "\n";
962 if (BD.writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, Safe.get())) {
963 errs() << "Error writing bitcode to `" << SafeModuleBC
968 FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
970 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str(), Error);
974 FileRemover SharedObjectRemover(SharedObject, !SaveTemps);
976 // Run the code generator on the `Test' code, loading the shared library.
977 // The function returns whether or not the new output differs from reference.
978 bool Result = BD.diffProgram(BD.getProgram(), TestModuleBC.str(),
979 SharedObject, false, &Error);
984 errs() << ": still failing!\n";
986 errs() << ": didn't fail.\n";
991 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
993 bool BugDriver::debugCodeGenerator(std::string *Error) {
994 if ((void*)SafeInterpreter == (void*)Interpreter) {
995 std::string Result = executeProgramSafely(Program, "bugpoint.safe.out",
997 if (Error->empty()) {
998 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
999 << "the reference diff. This may be due to a\n front-end "
1000 << "bug or a bug in the original program, but this can also "
1001 << "happen if bugpoint isn't running the program with the "
1002 << "right flags or input.\n I left the result of executing "
1003 << "the program with the \"safe\" backend in this file for "
1005 << Result << "'.\n";
1010 DisambiguateGlobalSymbols(Program);
1012 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator,
1014 if (!Error->empty())
1017 // Split the module into the two halves of the program we want.
1018 ValueToValueMapTy VMap;
1019 std::unique_ptr<Module> ToNotCodeGen = CloneModule(getProgram(), VMap);
1020 std::unique_ptr<Module> ToCodeGen =
1021 SplitFunctionsOutOfModule(ToNotCodeGen.get(), Funcs, VMap);
1023 // Condition the modules
1024 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen.get());
1026 SmallString<128> TestModuleBC;
1028 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
1029 TestModuleFD, TestModuleBC);
1031 errs() << getToolName() << "Error making unique filename: "
1032 << EC.message() << "\n";
1036 if (writeProgramToFile(TestModuleBC.str(), TestModuleFD, ToCodeGen.get())) {
1037 errs() << "Error writing bitcode to `" << TestModuleBC
1042 // Make the shared library
1043 SmallString<128> SafeModuleBC;
1045 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
1048 errs() << getToolName() << "Error making unique filename: "
1049 << EC.message() << "\n";
1053 if (writeProgramToFile(SafeModuleBC.str(), SafeModuleFD,
1054 ToNotCodeGen.get())) {
1055 errs() << "Error writing bitcode to `" << SafeModuleBC
1059 std::string SharedObject = compileSharedObject(SafeModuleBC.str(), *Error);
1060 if (!Error->empty())
1063 outs() << "You can reproduce the problem with the command line: \n";
1064 if (isExecutingJIT()) {
1065 outs() << " lli -load " << SharedObject << " " << TestModuleBC;
1067 outs() << " llc " << TestModuleBC << " -o " << TestModuleBC
1069 outs() << " cc " << SharedObject << " " << TestModuleBC.str()
1070 << ".s -o " << TestModuleBC << ".exe";
1071 #if defined (HAVE_LINK_R)
1072 outs() << " -Wl,-R.";
1075 outs() << " " << TestModuleBC << ".exe";
1077 for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
1078 outs() << " " << InputArgv[i];
1080 outs() << "The shared object was created with:\n llc -march=c "
1081 << SafeModuleBC.str() << " -o temporary.c\n"
1082 << " cc -xc temporary.c -O2 -o " << SharedObject;
1083 if (TargetTriple.getArch() == Triple::sparc)
1084 outs() << " -G"; // Compile a shared library, `-G' for Sparc
1086 outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
1088 outs() << " -fno-strict-aliasing\n";