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"
32 extern cl::opt<std::string> OutputPrefix;
33 extern cl::list<std::string> InputArgv;
37 static llvm::cl::opt<bool>
38 DisableLoopExtraction("disable-loop-extraction",
39 cl::desc("Don't extract loops when searching for miscompilations"),
41 static llvm::cl::opt<bool>
42 DisableBlockExtraction("disable-block-extraction",
43 cl::desc("Don't extract blocks when searching for miscompilations"),
46 class ReduceMiscompilingPasses : public ListReducer<std::string> {
49 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
51 TestResult doTest(std::vector<std::string> &Prefix,
52 std::vector<std::string> &Suffix,
53 std::string &Error) override;
57 /// TestResult - After passes have been split into a test group and a control
58 /// group, see if they still break the program.
60 ReduceMiscompilingPasses::TestResult
61 ReduceMiscompilingPasses::doTest(std::vector<std::string> &Prefix,
62 std::vector<std::string> &Suffix,
64 // First, run the program with just the Suffix passes. If it is still broken
65 // with JUST the kept passes, discard the prefix passes.
66 outs() << "Checking to see if '" << getPassesString(Suffix)
67 << "' compiles correctly: ";
69 std::string BitcodeResult;
70 if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false/*delete*/,
72 errs() << " Error running this sequence of passes"
73 << " on the input program!\n";
74 BD.setPassesToRun(Suffix);
75 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
76 exit(BD.debugOptimizerCrash());
79 // Check to see if the finished program matches the reference output...
80 bool Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
81 true /*delete bitcode*/, &Error);
87 errs() << BD.getToolName() << ": I'm confused: the test fails when "
88 << "no passes are run, nondeterministic program?\n";
91 return KeepSuffix; // Miscompilation detected!
93 outs() << " yup.\n"; // No miscompilation!
95 if (Prefix.empty()) return NoFailure;
97 // Next, see if the program is broken if we run the "prefix" passes first,
98 // then separately run the "kept" passes.
99 outs() << "Checking to see if '" << getPassesString(Prefix)
100 << "' compiles correctly: ";
102 // If it is not broken with the kept passes, it's possible that the prefix
103 // passes must be run before the kept passes to break it. If the program
104 // WORKS after the prefix passes, but then fails if running the prefix AND
105 // kept passes, we can update our bitcode file to include the result of the
106 // prefix passes, then discard the prefix passes.
108 if (BD.runPasses(BD.getProgram(), Prefix, BitcodeResult, false/*delete*/,
110 errs() << " Error running this sequence of passes"
111 << " on the input program!\n";
112 BD.setPassesToRun(Prefix);
113 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
114 exit(BD.debugOptimizerCrash());
117 // If the prefix maintains the predicate by itself, only keep the prefix!
118 Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "", false, &Error);
120 return InternalError;
122 outs() << " nope.\n";
123 sys::fs::remove(BitcodeResult);
126 outs() << " yup.\n"; // No miscompilation!
128 // Ok, so now we know that the prefix passes work, try running the suffix
129 // passes on the result of the prefix passes.
131 std::unique_ptr<Module> PrefixOutput =
132 parseInputFile(BitcodeResult, BD.getContext());
134 errs() << BD.getToolName() << ": Error reading bitcode file '"
135 << BitcodeResult << "'!\n";
138 sys::fs::remove(BitcodeResult);
140 // Don't check if there are no passes in the suffix.
144 outs() << "Checking to see if '" << getPassesString(Suffix)
145 << "' passes compile correctly after the '"
146 << getPassesString(Prefix) << "' passes: ";
148 std::unique_ptr<Module> OriginalInput(
149 BD.swapProgramIn(PrefixOutput.release()));
150 if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false/*delete*/,
152 errs() << " Error running this sequence of passes"
153 << " on the input program!\n";
154 BD.setPassesToRun(Suffix);
155 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
156 exit(BD.debugOptimizerCrash());
160 Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
161 true /*delete bitcode*/, &Error);
163 return InternalError;
165 outs() << " nope.\n";
169 // Otherwise, we must not be running the bad pass anymore.
170 outs() << " yup.\n"; // No miscompilation!
171 // Restore orig program & free test.
172 delete BD.swapProgramIn(OriginalInput.release());
177 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
179 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
180 std::unique_ptr<Module>, std::string &);
183 ReduceMiscompilingFunctions(BugDriver &bd,
184 bool (*F)(BugDriver &, std::unique_ptr<Module>,
185 std::unique_ptr<Module>,
187 : BD(bd), TestFn(F) {}
189 TestResult doTest(std::vector<Function*> &Prefix,
190 std::vector<Function*> &Suffix,
191 std::string &Error) override {
192 if (!Suffix.empty()) {
193 bool Ret = TestFuncs(Suffix, Error);
195 return InternalError;
199 if (!Prefix.empty()) {
200 bool Ret = TestFuncs(Prefix, Error);
202 return InternalError;
209 bool TestFuncs(const std::vector<Function*> &Prefix, std::string &Error);
213 /// Given two modules, link them together and run the program, checking to see
214 /// if the program matches the diff. If there is an error, return NULL. If not,
215 /// return the merged module. The Broken argument will be set to true if the
216 /// output is different. If the DeleteInputs argument is set to true then this
217 /// function deletes both input modules before it returns.
219 static std::unique_ptr<Module> testMergedProgram(const BugDriver &BD,
220 std::unique_ptr<Module> M1,
221 std::unique_ptr<Module> M2,
224 if (Linker::linkModules(*M1, *M2))
227 // Execute the program.
228 Broken = BD.diffProgram(M1.get(), "", "", false, &Error);
234 /// TestFuncs - split functions in a Module into two groups: those that are
235 /// under consideration for miscompilation vs. those that are not, and test
236 /// accordingly. Each group of functions becomes a separate Module.
238 bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*> &Funcs,
239 std::string &Error) {
240 // Test to see if the function is misoptimized if we ONLY run it on the
241 // functions listed in Funcs.
242 outs() << "Checking to see if the program is misoptimized when "
243 << (Funcs.size()==1 ? "this function is" : "these functions are")
244 << " run through the pass"
245 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
246 PrintFunctionList(Funcs);
249 // Create a clone for two reasons:
250 // * If the optimization passes delete any function, the deleted function
251 // will be in the clone and Funcs will still point to valid memory
252 // * If the optimization passes use interprocedural information to break
253 // a function, we want to continue with the original function. Otherwise
254 // we can conclude that a function triggers the bug when in fact one
255 // needs a larger set of original functions to do so.
256 ValueToValueMapTy VMap;
257 Module *Clone = CloneModule(BD.getProgram(), VMap).release();
258 Module *Orig = BD.swapProgramIn(Clone);
260 std::vector<Function*> FuncsOnClone;
261 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
262 Function *F = cast<Function>(VMap[Funcs[i]]);
263 FuncsOnClone.push_back(F);
266 // Split the module into the two halves of the program we want.
268 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
269 std::unique_ptr<Module> ToOptimize =
270 SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
273 TestFn(BD, std::move(ToOptimize), std::move(ToNotOptimize), Error);
275 delete BD.swapProgramIn(Orig);
280 /// DisambiguateGlobalSymbols - Give anonymous global values names.
282 static void DisambiguateGlobalSymbols(Module *M) {
283 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
286 I->setName("anon_global");
287 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
289 I->setName("anon_fn");
292 /// Given a reduced list of functions that still exposed the bug, check to see
293 /// if we can extract the loops in the region without obscuring the bug. If so,
294 /// it reduces the amount of code identified.
296 static bool ExtractLoops(BugDriver &BD,
297 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
298 std::unique_ptr<Module>, std::string &),
299 std::vector<Function *> &MiscompiledFunctions,
300 std::string &Error) {
301 bool MadeChange = false;
303 if (BugpointIsInterrupted) return MadeChange;
305 ValueToValueMapTy VMap;
306 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
307 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize.get(),
308 MiscompiledFunctions, VMap)
310 std::unique_ptr<Module> ToOptimizeLoopExtracted =
311 BD.extractLoop(ToOptimize);
312 if (!ToOptimizeLoopExtracted) {
313 // If the loop extractor crashed or if there were no extractible loops,
314 // then this chapter of our odyssey is over with.
319 errs() << "Extracted a loop from the breaking portion of the program.\n";
321 // Bugpoint is intentionally not very trusting of LLVM transformations. In
322 // particular, we're not going to assume that the loop extractor works, so
323 // we're going to test the newly loop extracted program to make sure nothing
324 // has broken. If something broke, then we'll inform the user and stop
326 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
328 std::unique_ptr<Module> New =
329 testMergedProgram(BD, std::move(ToOptimizeLoopExtracted),
330 std::move(ToNotOptimize), Error, Failure);
334 // Delete the original and set the new program.
335 Module *Old = BD.swapProgramIn(New.release());
336 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
337 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
341 BD.switchToInterpreter(AI);
343 // Merged program doesn't work anymore!
344 errs() << " *** ERROR: Loop extraction broke the program. :("
345 << " Please report a bug!\n";
346 errs() << " Continuing on with un-loop-extracted version.\n";
348 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
349 ToNotOptimize.get());
350 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
352 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
353 ToOptimizeLoopExtracted.get());
355 errs() << "Please submit the "
356 << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
361 BD.switchToInterpreter(AI);
363 outs() << " Testing after loop extraction:\n";
364 // Clone modules, the tester function will free them.
365 std::unique_ptr<Module> TOLEBackup =
366 CloneModule(ToOptimizeLoopExtracted.get(), VMap);
367 std::unique_ptr<Module> TNOBackup = CloneModule(ToNotOptimize.get(), VMap);
369 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
370 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
372 Failure = TestFn(BD, std::move(ToOptimizeLoopExtracted),
373 std::move(ToNotOptimize), Error);
377 ToOptimizeLoopExtracted = std::move(TOLEBackup);
378 ToNotOptimize = std::move(TNOBackup);
381 outs() << "*** Loop extraction masked the problem. Undoing.\n";
382 // If the program is not still broken, then loop extraction did something
383 // that masked the error. Stop loop extraction now.
385 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
386 for (Function *F : MiscompiledFunctions) {
387 MisCompFunctions.emplace_back(F->getName(), F->getFunctionType());
390 if (Linker::linkModules(*ToNotOptimize, *ToOptimizeLoopExtracted))
393 MiscompiledFunctions.clear();
394 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
395 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
397 assert(NewF && "Function not found??");
398 MiscompiledFunctions.push_back(NewF);
401 BD.setNewProgram(ToNotOptimize.release());
405 outs() << "*** Loop extraction successful!\n";
407 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
408 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
409 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
410 if (!I->isDeclaration())
411 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
413 // Okay, great! Now we know that we extracted a loop and that loop
414 // extraction both didn't break the program, and didn't mask the problem.
415 // Replace the current program with the loop extracted version, and try to
416 // extract another loop.
417 if (Linker::linkModules(*ToNotOptimize, *ToOptimizeLoopExtracted))
420 // All of the Function*'s in the MiscompiledFunctions list are in the old
421 // module. Update this list to include all of the functions in the
422 // optimized and loop extracted module.
423 MiscompiledFunctions.clear();
424 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
425 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
427 assert(NewF && "Function not found??");
428 MiscompiledFunctions.push_back(NewF);
431 BD.setNewProgram(ToNotOptimize.release());
437 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
439 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
440 std::unique_ptr<Module>, std::string &);
441 std::vector<Function*> FunctionsBeingTested;
443 ReduceMiscompiledBlocks(BugDriver &bd,
444 bool (*F)(BugDriver &, std::unique_ptr<Module>,
445 std::unique_ptr<Module>, std::string &),
446 const std::vector<Function *> &Fns)
447 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
449 TestResult doTest(std::vector<BasicBlock*> &Prefix,
450 std::vector<BasicBlock*> &Suffix,
451 std::string &Error) override {
452 if (!Suffix.empty()) {
453 bool Ret = TestFuncs(Suffix, Error);
455 return InternalError;
459 if (!Prefix.empty()) {
460 bool Ret = TestFuncs(Prefix, Error);
462 return InternalError;
469 bool TestFuncs(const std::vector<BasicBlock*> &BBs, std::string &Error);
473 /// TestFuncs - Extract all blocks for the miscompiled functions except for the
474 /// specified blocks. If the problem still exists, return true.
476 bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs,
477 std::string &Error) {
478 // Test to see if the function is misoptimized if we ONLY run it on the
479 // functions listed in Funcs.
480 outs() << "Checking to see if the program is misoptimized when all ";
482 outs() << "but these " << BBs.size() << " blocks are extracted: ";
483 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
484 outs() << BBs[i]->getName() << " ";
485 if (BBs.size() > 10) outs() << "...";
487 outs() << "blocks are extracted.";
491 // Split the module into the two halves of the program we want.
492 ValueToValueMapTy VMap;
493 Module *Clone = CloneModule(BD.getProgram(), VMap).release();
494 Module *Orig = BD.swapProgramIn(Clone);
495 std::vector<Function*> FuncsOnClone;
496 std::vector<BasicBlock*> BBsOnClone;
497 for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
498 Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
499 FuncsOnClone.push_back(F);
501 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
502 BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
503 BBsOnClone.push_back(BB);
507 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
508 std::unique_ptr<Module> ToOptimize =
509 SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
511 // Try the extraction. If it doesn't work, then the block extractor crashed
512 // or something, in which case bugpoint can't chase down this possibility.
513 if (std::unique_ptr<Module> New =
514 BD.extractMappedBlocksFromModule(BBsOnClone, ToOptimize.get())) {
515 bool Ret = TestFn(BD, std::move(New), std::move(ToNotOptimize), Error);
516 delete BD.swapProgramIn(Orig);
519 delete BD.swapProgramIn(Orig);
523 /// Given a reduced list of functions that still expose the bug, extract as many
524 /// basic blocks from the region as possible without obscuring the bug.
526 static bool ExtractBlocks(BugDriver &BD,
527 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
528 std::unique_ptr<Module>,
530 std::vector<Function *> &MiscompiledFunctions,
531 std::string &Error) {
532 if (BugpointIsInterrupted) return false;
534 std::vector<BasicBlock*> Blocks;
535 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
536 for (BasicBlock &BB : *MiscompiledFunctions[i])
537 Blocks.push_back(&BB);
539 // Use the list reducer to identify blocks that can be extracted without
540 // obscuring the bug. The Blocks list will end up containing blocks that must
541 // be retained from the original program.
542 unsigned OldSize = Blocks.size();
544 // Check to see if all blocks are extractible first.
545 bool Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
546 .TestFuncs(std::vector<BasicBlock*>(), Error);
552 ReduceMiscompiledBlocks(BD, TestFn,
553 MiscompiledFunctions).reduceList(Blocks, Error);
556 if (Blocks.size() == OldSize)
560 ValueToValueMapTy VMap;
561 Module *ProgClone = CloneModule(BD.getProgram(), VMap).release();
563 SplitFunctionsOutOfModule(ProgClone, MiscompiledFunctions, VMap)
565 std::unique_ptr<Module> Extracted =
566 BD.extractMappedBlocksFromModule(Blocks, ToExtract);
568 // Weird, extraction should have worked.
569 errs() << "Nondeterministic problem extracting blocks??\n";
575 // Otherwise, block extraction succeeded. Link the two program fragments back
579 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
580 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
582 if (!I->isDeclaration())
583 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
585 if (Linker::linkModules(*ProgClone, *Extracted))
588 // Set the new program and delete the old one.
589 BD.setNewProgram(ProgClone);
591 // Update the list of miscompiled functions.
592 MiscompiledFunctions.clear();
594 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
595 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
596 assert(NewF && "Function not found??");
597 MiscompiledFunctions.push_back(NewF);
603 /// This is a generic driver to narrow down miscompilations, either in an
604 /// optimization or a code generator.
606 static std::vector<Function *>
607 DebugAMiscompilation(BugDriver &BD,
608 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
609 std::unique_ptr<Module>, std::string &),
610 std::string &Error) {
611 // Okay, now that we have reduced the list of passes which are causing the
612 // failure, see if we can pin down which functions are being
613 // miscompiled... first build a list of all of the non-external functions in
615 std::vector<Function*> MiscompiledFunctions;
616 Module *Prog = BD.getProgram();
617 for (Function &F : *Prog)
618 if (!F.isDeclaration())
619 MiscompiledFunctions.push_back(&F);
621 // Do the reduction...
622 if (!BugpointIsInterrupted)
623 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
625 if (!Error.empty()) {
626 errs() << "\n***Cannot reduce functions: ";
627 return MiscompiledFunctions;
629 outs() << "\n*** The following function"
630 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
631 << " being miscompiled: ";
632 PrintFunctionList(MiscompiledFunctions);
635 // See if we can rip any loops out of the miscompiled functions and still
636 // trigger the problem.
638 if (!BugpointIsInterrupted && !DisableLoopExtraction) {
639 bool Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions, Error);
641 return MiscompiledFunctions;
643 // Okay, we extracted some loops and the problem still appears. See if
644 // we can eliminate some of the created functions from being candidates.
645 DisambiguateGlobalSymbols(BD.getProgram());
647 // Do the reduction...
648 if (!BugpointIsInterrupted)
649 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
652 return MiscompiledFunctions;
654 outs() << "\n*** The following function"
655 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
656 << " being miscompiled: ";
657 PrintFunctionList(MiscompiledFunctions);
662 if (!BugpointIsInterrupted && !DisableBlockExtraction) {
663 bool Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions, Error);
665 return MiscompiledFunctions;
667 // Okay, we extracted some blocks and the problem still appears. See if
668 // we can eliminate some of the created functions from being candidates.
669 DisambiguateGlobalSymbols(BD.getProgram());
671 // Do the reduction...
672 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
675 return MiscompiledFunctions;
677 outs() << "\n*** The following function"
678 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
679 << " being miscompiled: ";
680 PrintFunctionList(MiscompiledFunctions);
685 return MiscompiledFunctions;
688 /// This is the predicate function used to check to see if the "Test" portion of
689 /// the program is misoptimized. If so, return true. In any case, both module
690 /// arguments are deleted.
692 static bool TestOptimizer(BugDriver &BD, std::unique_ptr<Module> Test,
693 std::unique_ptr<Module> Safe, std::string &Error) {
694 // Run the optimization passes on ToOptimize, producing a transformed version
695 // of the functions being tested.
696 outs() << " Optimizing functions being tested: ";
697 std::unique_ptr<Module> Optimized =
698 BD.runPassesOn(Test.get(), BD.getPassesToRun(),
699 /*AutoDebugCrashes*/ true);
702 outs() << " Checking to see if the merged program executes correctly: ";
704 std::unique_ptr<Module> New = testMergedProgram(
705 BD, std::move(Optimized), std::move(Safe), Error, Broken);
707 outs() << (Broken ? " nope.\n" : " yup.\n");
708 // Delete the original and set the new program.
709 delete BD.swapProgramIn(New.release());
715 /// debugMiscompilation - This method is used when the passes selected are not
716 /// crashing, but the generated output is semantically different from the
719 void BugDriver::debugMiscompilation(std::string *Error) {
720 // Make sure something was miscompiled...
721 if (!BugpointIsInterrupted)
722 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun, *Error)) {
724 errs() << "*** Optimized program matches reference output! No problem"
725 << " detected...\nbugpoint can't help you with your problem!\n";
729 outs() << "\n*** Found miscompiling pass"
730 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
731 << getPassesString(getPassesToRun()) << '\n';
732 EmitProgressBitcode(Program, "passinput");
734 std::vector<Function *> MiscompiledFunctions =
735 DebugAMiscompilation(*this, TestOptimizer, *Error);
739 // Output a bunch of bitcode files for the user...
740 outs() << "Outputting reduced bitcode files which expose the problem:\n";
741 ValueToValueMapTy VMap;
742 Module *ToNotOptimize = CloneModule(getProgram(), VMap).release();
744 SplitFunctionsOutOfModule(ToNotOptimize, MiscompiledFunctions, VMap)
747 outs() << " Non-optimized portion: ";
748 EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true);
749 delete ToNotOptimize; // Delete hacked module.
751 outs() << " Portion that is input to optimizer: ";
752 EmitProgressBitcode(ToOptimize, "tooptimize");
753 delete ToOptimize; // Delete hacked module.
758 /// Get the specified modules ready for code generator testing.
760 static void CleanupAndPrepareModules(BugDriver &BD,
761 std::unique_ptr<Module> &Test,
763 // Clean up the modules, removing extra cruft that we don't need anymore...
764 Test = BD.performFinalCleanups(Test.get());
766 // If we are executing the JIT, we have several nasty issues to take care of.
767 if (!BD.isExecutingJIT()) return;
769 // First, if the main function is in the Safe module, we must add a stub to
770 // the Test module to call into it. Thus, we create a new function `main'
771 // which just calls the old one.
772 if (Function *oldMain = Safe->getFunction("main"))
773 if (!oldMain->isDeclaration()) {
775 oldMain->setName("llvm_bugpoint_old_main");
776 // Create a NEW `main' function with same type in the test module.
778 Function::Create(oldMain->getFunctionType(),
779 GlobalValue::ExternalLinkage, "main", Test.get());
780 // Create an `oldmain' prototype in the test module, which will
781 // corresponds to the real main function in the same module.
782 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
783 GlobalValue::ExternalLinkage,
784 oldMain->getName(), Test.get());
785 // Set up and remember the argument list for the main function.
786 std::vector<Value*> args;
787 for (Function::arg_iterator
788 I = newMain->arg_begin(), E = newMain->arg_end(),
789 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
790 I->setName(OI->getName()); // Copy argument names from oldMain
794 // Call the old main function and return its result
795 BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
796 CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
798 // If the type of old function wasn't void, return value of call
799 ReturnInst::Create(Safe->getContext(), call, BB);
802 // The second nasty issue we must deal with in the JIT is that the Safe
803 // module cannot directly reference any functions defined in the test
804 // module. Instead, we use a JIT API call to dynamically resolve the
807 // Add the resolver to the Safe module.
808 // Prototype: void *getPointerToNamedFunction(const char* Name)
809 Constant *resolverFunc =
810 Safe->getOrInsertFunction("getPointerToNamedFunction",
811 Type::getInt8PtrTy(Safe->getContext()),
812 Type::getInt8PtrTy(Safe->getContext()),
815 // Use the function we just added to get addresses of functions we need.
816 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
817 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
818 !F->isIntrinsic() /* ignore intrinsics */) {
819 Function *TestFn = Test->getFunction(F->getName());
821 // Don't forward functions which are external in the test module too.
822 if (TestFn && !TestFn->isDeclaration()) {
823 // 1. Add a string constant with its name to the global file
824 Constant *InitArray =
825 ConstantDataArray::getString(F->getContext(), F->getName());
826 GlobalVariable *funcName =
827 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
828 GlobalValue::InternalLinkage, InitArray,
829 F->getName() + "_name");
831 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
832 // sbyte* so it matches the signature of the resolver function.
834 // GetElementPtr *funcName, ulong 0, ulong 0
835 std::vector<Constant*> GEPargs(2,
836 Constant::getNullValue(Type::getInt32Ty(F->getContext())));
837 Value *GEP = ConstantExpr::getGetElementPtr(InitArray->getType(),
839 std::vector<Value*> ResolverArgs;
840 ResolverArgs.push_back(GEP);
842 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
843 // function that dynamically resolves the calls to F via our JIT API
844 if (!F->use_empty()) {
845 // Create a new global to hold the cached function pointer.
846 Constant *NullPtr = ConstantPointerNull::get(F->getType());
847 GlobalVariable *Cache =
848 new GlobalVariable(*F->getParent(), F->getType(),
849 false, GlobalValue::InternalLinkage,
850 NullPtr,F->getName()+".fpcache");
852 // Construct a new stub function that will re-route calls to F
853 FunctionType *FuncTy = F->getFunctionType();
854 Function *FuncWrapper = Function::Create(FuncTy,
855 GlobalValue::InternalLinkage,
856 F->getName() + "_wrapper",
858 BasicBlock *EntryBB = BasicBlock::Create(F->getContext(),
859 "entry", FuncWrapper);
860 BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
861 "usecache", FuncWrapper);
862 BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
863 "lookupfp", FuncWrapper);
865 // Check to see if we already looked up the value.
866 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
867 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
869 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
871 // Resolve the call to function F via the JIT API:
873 // call resolver(GetElementPtr...)
875 CallInst::Create(resolverFunc, ResolverArgs, "resolver", LookupBB);
877 // Cast the result from the resolver to correctly-typed function.
878 CastInst *CastedResolver =
879 new BitCastInst(Resolver,
880 PointerType::getUnqual(F->getFunctionType()),
881 "resolverCast", LookupBB);
883 // Save the value in our cache.
884 new StoreInst(CastedResolver, Cache, LookupBB);
885 BranchInst::Create(DoCallBB, LookupBB);
887 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(), 2,
889 FuncPtr->addIncoming(CastedResolver, LookupBB);
890 FuncPtr->addIncoming(CachedVal, EntryBB);
892 // Save the argument list.
893 std::vector<Value*> Args;
894 for (Argument &A : FuncWrapper->args())
897 // Pass on the arguments to the real function, return its result
898 if (F->getReturnType()->isVoidTy()) {
899 CallInst::Create(FuncPtr, Args, "", DoCallBB);
900 ReturnInst::Create(F->getContext(), DoCallBB);
902 CallInst *Call = CallInst::Create(FuncPtr, Args,
904 ReturnInst::Create(F->getContext(),Call, DoCallBB);
907 // Use the wrapper function instead of the old function
908 F->replaceAllUsesWith(FuncWrapper);
914 if (verifyModule(*Test) || verifyModule(*Safe)) {
915 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
920 /// This is the predicate function used to check to see if the "Test" portion of
921 /// the program is miscompiled by the code generator under test. If so, return
922 /// true. In any case, both module arguments are deleted.
924 static bool TestCodeGenerator(BugDriver &BD, std::unique_ptr<Module> Test,
925 std::unique_ptr<Module> Safe,
926 std::string &Error) {
927 CleanupAndPrepareModules(BD, Test, Safe.get());
929 SmallString<128> TestModuleBC;
931 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
932 TestModuleFD, TestModuleBC);
934 errs() << BD.getToolName() << "Error making unique filename: "
935 << EC.message() << "\n";
938 if (BD.writeProgramToFile(TestModuleBC.str(), TestModuleFD, Test.get())) {
939 errs() << "Error writing bitcode to `" << TestModuleBC.str()
944 FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
946 // Make the shared library
947 SmallString<128> SafeModuleBC;
949 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
952 errs() << BD.getToolName() << "Error making unique filename: "
953 << EC.message() << "\n";
957 if (BD.writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, Safe.get())) {
958 errs() << "Error writing bitcode to `" << SafeModuleBC
963 FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
965 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str(), Error);
969 FileRemover SharedObjectRemover(SharedObject, !SaveTemps);
971 // Run the code generator on the `Test' code, loading the shared library.
972 // The function returns whether or not the new output differs from reference.
973 bool Result = BD.diffProgram(BD.getProgram(), TestModuleBC.str(),
974 SharedObject, false, &Error);
979 errs() << ": still failing!\n";
981 errs() << ": didn't fail.\n";
987 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
989 bool BugDriver::debugCodeGenerator(std::string *Error) {
990 if ((void*)SafeInterpreter == (void*)Interpreter) {
991 std::string Result = executeProgramSafely(Program, "bugpoint.safe.out",
993 if (Error->empty()) {
994 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
995 << "the reference diff. This may be due to a\n front-end "
996 << "bug or a bug in the original program, but this can also "
997 << "happen if bugpoint isn't running the program with the "
998 << "right flags or input.\n I left the result of executing "
999 << "the program with the \"safe\" backend in this file for "
1001 << Result << "'.\n";
1006 DisambiguateGlobalSymbols(Program);
1008 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator,
1010 if (!Error->empty())
1013 // Split the module into the two halves of the program we want.
1014 ValueToValueMapTy VMap;
1015 std::unique_ptr<Module> ToNotCodeGen = CloneModule(getProgram(), VMap);
1016 std::unique_ptr<Module> ToCodeGen =
1017 SplitFunctionsOutOfModule(ToNotCodeGen.get(), Funcs, VMap);
1019 // Condition the modules
1020 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen.get());
1022 SmallString<128> TestModuleBC;
1024 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
1025 TestModuleFD, TestModuleBC);
1027 errs() << getToolName() << "Error making unique filename: "
1028 << EC.message() << "\n";
1032 if (writeProgramToFile(TestModuleBC.str(), TestModuleFD, ToCodeGen.get())) {
1033 errs() << "Error writing bitcode to `" << TestModuleBC
1038 // Make the shared library
1039 SmallString<128> SafeModuleBC;
1041 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
1044 errs() << getToolName() << "Error making unique filename: "
1045 << EC.message() << "\n";
1049 if (writeProgramToFile(SafeModuleBC.str(), SafeModuleFD,
1050 ToNotCodeGen.get())) {
1051 errs() << "Error writing bitcode to `" << SafeModuleBC
1055 std::string SharedObject = compileSharedObject(SafeModuleBC.str(), *Error);
1056 if (!Error->empty())
1059 outs() << "You can reproduce the problem with the command line: \n";
1060 if (isExecutingJIT()) {
1061 outs() << " lli -load " << SharedObject << " " << TestModuleBC;
1063 outs() << " llc " << TestModuleBC << " -o " << TestModuleBC
1065 outs() << " cc " << SharedObject << " " << TestModuleBC.str()
1066 << ".s -o " << TestModuleBC << ".exe";
1067 #if defined (HAVE_LINK_R)
1068 outs() << " -Wl,-R.";
1071 outs() << " " << TestModuleBC << ".exe";
1073 for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
1074 outs() << " " << InputArgv[i];
1076 outs() << "The shared object was created with:\n llc -march=c "
1077 << SafeModuleBC.str() << " -o temporary.c\n"
1078 << " cc -xc temporary.c -O2 -o " << SharedObject;
1079 if (TargetTriple.getArch() == Triple::sparc)
1080 outs() << " -G"; // Compile a shared library, `-G' for Sparc
1082 outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
1084 outs() << " -fno-strict-aliasing\n";