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 &, Module *, Module *, std::string &);
181 ReduceMiscompilingFunctions(BugDriver &bd,
182 bool (*F)(BugDriver &, Module *, Module *,
184 : BD(bd), TestFn(F) {}
186 TestResult doTest(std::vector<Function*> &Prefix,
187 std::vector<Function*> &Suffix,
188 std::string &Error) override {
189 if (!Suffix.empty()) {
190 bool Ret = TestFuncs(Suffix, Error);
192 return InternalError;
196 if (!Prefix.empty()) {
197 bool Ret = TestFuncs(Prefix, Error);
199 return InternalError;
206 bool TestFuncs(const std::vector<Function*> &Prefix, std::string &Error);
210 /// TestMergedProgram - Given two modules, link them together and run the
211 /// program, checking to see if the program matches the diff. If there is
212 /// an error, return NULL. If not, return the merged module. The Broken argument
213 /// will be set to true if the output is different. If the DeleteInputs
214 /// argument is set to true then this function deletes both input
215 /// modules before it returns.
217 static Module *TestMergedProgram(const BugDriver &BD, Module *M1, Module *M2,
218 bool DeleteInputs, std::string &Error,
220 // Link the two portions of the program back to together.
222 M1 = CloneModule(M1);
223 M2 = CloneModule(M2);
225 if (Linker::LinkModules(M1, M2, Linker::DestroySource))
227 delete M2; // We are done with this module.
229 // Execute the program.
230 Broken = BD.diffProgram(M1, "", "", false, &Error);
231 if (!Error.empty()) {
232 // Delete the linked module
239 /// TestFuncs - split functions in a Module into two groups: those that are
240 /// under consideration for miscompilation vs. those that are not, and test
241 /// accordingly. Each group of functions becomes a separate Module.
243 bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*> &Funcs,
244 std::string &Error) {
245 // Test to see if the function is misoptimized if we ONLY run it on the
246 // functions listed in Funcs.
247 outs() << "Checking to see if the program is misoptimized when "
248 << (Funcs.size()==1 ? "this function is" : "these functions are")
249 << " run through the pass"
250 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
251 PrintFunctionList(Funcs);
254 // Create a clone for two reasons:
255 // * If the optimization passes delete any function, the deleted function
256 // will be in the clone and Funcs will still point to valid memory
257 // * If the optimization passes use interprocedural information to break
258 // a function, we want to continue with the original function. Otherwise
259 // we can conclude that a function triggers the bug when in fact one
260 // needs a larger set of original functions to do so.
261 ValueToValueMapTy VMap;
262 Module *Clone = CloneModule(BD.getProgram(), VMap);
263 Module *Orig = BD.swapProgramIn(Clone);
265 std::vector<Function*> FuncsOnClone;
266 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
267 Function *F = cast<Function>(VMap[Funcs[i]]);
268 FuncsOnClone.push_back(F);
271 // Split the module into the two halves of the program we want.
273 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
274 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, FuncsOnClone,
277 // Run the predicate, note that the predicate will delete both input modules.
278 bool Broken = TestFn(BD, ToOptimize, ToNotOptimize, Error);
280 delete BD.swapProgramIn(Orig);
285 /// DisambiguateGlobalSymbols - Give anonymous global values names.
287 static void DisambiguateGlobalSymbols(Module *M) {
288 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
291 I->setName("anon_global");
292 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
294 I->setName("anon_fn");
297 /// ExtractLoops - Given a reduced list of functions that still exposed the bug,
298 /// check to see if we can extract the loops in the region without obscuring the
299 /// bug. If so, it reduces the amount of code identified.
301 static bool ExtractLoops(BugDriver &BD,
302 bool (*TestFn)(BugDriver &, Module *, Module *,
304 std::vector<Function*> &MiscompiledFunctions,
305 std::string &Error) {
306 bool MadeChange = false;
308 if (BugpointIsInterrupted) return MadeChange;
310 ValueToValueMapTy VMap;
311 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
312 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
313 MiscompiledFunctions,
315 Module *ToOptimizeLoopExtracted = BD.extractLoop(ToOptimize).release();
316 if (!ToOptimizeLoopExtracted) {
317 // If the loop extractor crashed or if there were no extractible loops,
318 // then this chapter of our odyssey is over with.
319 delete ToNotOptimize;
324 errs() << "Extracted a loop from the breaking portion of the program.\n";
326 // Bugpoint is intentionally not very trusting of LLVM transformations. In
327 // particular, we're not going to assume that the loop extractor works, so
328 // we're going to test the newly loop extracted program to make sure nothing
329 // has broken. If something broke, then we'll inform the user and stop
331 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
333 Module *New = TestMergedProgram(BD, ToOptimizeLoopExtracted,
334 ToNotOptimize, false, Error, Failure);
338 // Delete the original and set the new program.
339 Module *Old = BD.swapProgramIn(New);
340 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
341 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
345 BD.switchToInterpreter(AI);
347 // Merged program doesn't work anymore!
348 errs() << " *** ERROR: Loop extraction broke the program. :("
349 << " Please report a bug!\n";
350 errs() << " Continuing on with un-loop-extracted version.\n";
352 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
354 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
356 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
357 ToOptimizeLoopExtracted);
359 errs() << "Please submit the "
360 << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
362 delete ToNotOptimize;
366 BD.switchToInterpreter(AI);
368 outs() << " Testing after loop extraction:\n";
369 // Clone modules, the tester function will free them.
370 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted, VMap);
371 Module *TNOBackup = CloneModule(ToNotOptimize, VMap);
373 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
374 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
376 Failure = TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize, Error);
380 ToOptimizeLoopExtracted = TOLEBackup;
381 ToNotOptimize = TNOBackup;
384 outs() << "*** Loop extraction masked the problem. Undoing.\n";
385 // If the program is not still broken, then loop extraction did something
386 // that masked the error. Stop loop extraction now.
388 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
389 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i) {
390 Function *F = MiscompiledFunctions[i];
391 MisCompFunctions.push_back(std::make_pair(F->getName(),
392 F->getFunctionType()));
395 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted,
396 Linker::DestroySource))
399 MiscompiledFunctions.clear();
400 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
401 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
403 assert(NewF && "Function not found??");
404 MiscompiledFunctions.push_back(NewF);
407 delete ToOptimizeLoopExtracted;
408 BD.setNewProgram(ToNotOptimize);
412 outs() << "*** Loop extraction successful!\n";
414 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
415 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
416 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
417 if (!I->isDeclaration())
418 MisCompFunctions.push_back(std::make_pair(I->getName(),
419 I->getFunctionType()));
421 // Okay, great! Now we know that we extracted a loop and that loop
422 // extraction both didn't break the program, and didn't mask the problem.
423 // Replace the current program with the loop extracted version, and try to
424 // extract another loop.
425 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted,
426 Linker::DestroySource))
429 delete 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);
448 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
450 bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
451 std::vector<Function*> FunctionsBeingTested;
453 ReduceMiscompiledBlocks(BugDriver &bd,
454 bool (*F)(BugDriver &, Module *, Module *,
456 const std::vector<Function*> &Fns)
457 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
459 TestResult doTest(std::vector<BasicBlock*> &Prefix,
460 std::vector<BasicBlock*> &Suffix,
461 std::string &Error) override {
462 if (!Suffix.empty()) {
463 bool Ret = TestFuncs(Suffix, Error);
465 return InternalError;
469 if (!Prefix.empty()) {
470 bool Ret = TestFuncs(Prefix, Error);
472 return InternalError;
479 bool TestFuncs(const std::vector<BasicBlock*> &BBs, std::string &Error);
483 /// TestFuncs - Extract all blocks for the miscompiled functions except for the
484 /// specified blocks. If the problem still exists, return true.
486 bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs,
487 std::string &Error) {
488 // Test to see if the function is misoptimized if we ONLY run it on the
489 // functions listed in Funcs.
490 outs() << "Checking to see if the program is misoptimized when all ";
492 outs() << "but these " << BBs.size() << " blocks are extracted: ";
493 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
494 outs() << BBs[i]->getName() << " ";
495 if (BBs.size() > 10) outs() << "...";
497 outs() << "blocks are extracted.";
501 // Split the module into the two halves of the program we want.
502 ValueToValueMapTy VMap;
503 Module *Clone = CloneModule(BD.getProgram(), VMap);
504 Module *Orig = BD.swapProgramIn(Clone);
505 std::vector<Function*> FuncsOnClone;
506 std::vector<BasicBlock*> BBsOnClone;
507 for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
508 Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
509 FuncsOnClone.push_back(F);
511 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
512 BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
513 BBsOnClone.push_back(BB);
517 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
518 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
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)) {
527 // Run the predicate,
528 // note that the predicate will delete both input modules.
529 bool Ret = TestFn(BD, New.get(), ToNotOptimize, Error);
530 delete BD.swapProgramIn(Orig);
533 delete BD.swapProgramIn(Orig);
535 delete ToNotOptimize;
540 /// ExtractBlocks - Given a reduced list of functions that still expose the bug,
541 /// extract as many basic blocks from the region as possible without obscuring
544 static bool ExtractBlocks(BugDriver &BD,
545 bool (*TestFn)(BugDriver &, Module *, Module *,
547 std::vector<Function*> &MiscompiledFunctions,
548 std::string &Error) {
549 if (BugpointIsInterrupted) return false;
551 std::vector<BasicBlock*> Blocks;
552 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
553 for (Function::iterator I = MiscompiledFunctions[i]->begin(),
554 E = MiscompiledFunctions[i]->end(); I != E; ++I)
557 // Use the list reducer to identify blocks that can be extracted without
558 // obscuring the bug. The Blocks list will end up containing blocks that must
559 // be retained from the original program.
560 unsigned OldSize = Blocks.size();
562 // Check to see if all blocks are extractible first.
563 bool Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
564 .TestFuncs(std::vector<BasicBlock*>(), Error);
570 ReduceMiscompiledBlocks(BD, TestFn,
571 MiscompiledFunctions).reduceList(Blocks, Error);
574 if (Blocks.size() == OldSize)
578 ValueToValueMapTy VMap;
579 Module *ProgClone = CloneModule(BD.getProgram(), VMap);
580 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
581 MiscompiledFunctions,
583 std::unique_ptr<Module> Extracted =
584 BD.extractMappedBlocksFromModule(Blocks, ToExtract);
586 // Weird, extraction should have worked.
587 errs() << "Nondeterministic problem extracting blocks??\n";
593 // Otherwise, block extraction succeeded. Link the two program fragments back
597 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
598 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
600 if (!I->isDeclaration())
601 MisCompFunctions.push_back(std::make_pair(I->getName(),
602 I->getFunctionType()));
604 if (Linker::LinkModules(ProgClone, Extracted.get(), Linker::DestroySource))
607 // Set the new program and delete the old one.
608 BD.setNewProgram(ProgClone);
610 // Update the list of miscompiled functions.
611 MiscompiledFunctions.clear();
613 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
614 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
615 assert(NewF && "Function not found??");
616 MiscompiledFunctions.push_back(NewF);
623 /// DebugAMiscompilation - This is a generic driver to narrow down
624 /// miscompilations, either in an optimization or a code generator.
626 static std::vector<Function*>
627 DebugAMiscompilation(BugDriver &BD,
628 bool (*TestFn)(BugDriver &, Module *, Module *,
630 std::string &Error) {
631 // Okay, now that we have reduced the list of passes which are causing the
632 // failure, see if we can pin down which functions are being
633 // miscompiled... first build a list of all of the non-external functions in
635 std::vector<Function*> MiscompiledFunctions;
636 Module *Prog = BD.getProgram();
637 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
638 if (!I->isDeclaration())
639 MiscompiledFunctions.push_back(I);
641 // Do the reduction...
642 if (!BugpointIsInterrupted)
643 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
645 if (!Error.empty()) {
646 errs() << "\n***Cannot reduce functions: ";
647 return MiscompiledFunctions;
649 outs() << "\n*** The following function"
650 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
651 << " being miscompiled: ";
652 PrintFunctionList(MiscompiledFunctions);
655 // See if we can rip any loops out of the miscompiled functions and still
656 // trigger the problem.
658 if (!BugpointIsInterrupted && !DisableLoopExtraction) {
659 bool Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions, Error);
661 return MiscompiledFunctions;
663 // Okay, we extracted some loops and the problem still appears. See if
664 // we can eliminate some of the created functions from being candidates.
665 DisambiguateGlobalSymbols(BD.getProgram());
667 // Do the reduction...
668 if (!BugpointIsInterrupted)
669 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
672 return MiscompiledFunctions;
674 outs() << "\n*** The following function"
675 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
676 << " being miscompiled: ";
677 PrintFunctionList(MiscompiledFunctions);
682 if (!BugpointIsInterrupted && !DisableBlockExtraction) {
683 bool Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions, Error);
685 return MiscompiledFunctions;
687 // Okay, we extracted some blocks and the problem still appears. See if
688 // we can eliminate some of the created functions from being candidates.
689 DisambiguateGlobalSymbols(BD.getProgram());
691 // Do the reduction...
692 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
695 return MiscompiledFunctions;
697 outs() << "\n*** The following function"
698 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
699 << " being miscompiled: ";
700 PrintFunctionList(MiscompiledFunctions);
705 return MiscompiledFunctions;
708 /// TestOptimizer - This is the predicate function used to check to see if the
709 /// "Test" portion of the program is misoptimized. If so, return true. In any
710 /// case, both module arguments are deleted.
712 static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe,
713 std::string &Error) {
714 // Run the optimization passes on ToOptimize, producing a transformed version
715 // of the functions being tested.
716 outs() << " Optimizing functions being tested: ";
717 std::unique_ptr<Module> Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
718 /*AutoDebugCrashes*/ true);
722 outs() << " Checking to see if the merged program executes correctly: ";
725 TestMergedProgram(BD, Optimized.get(), Safe, true, Error, Broken);
727 outs() << (Broken ? " nope.\n" : " yup.\n");
728 // Delete the original and set the new program.
729 delete BD.swapProgramIn(New);
735 /// debugMiscompilation - This method is used when the passes selected are not
736 /// crashing, but the generated output is semantically different from the
739 void BugDriver::debugMiscompilation(std::string *Error) {
740 // Make sure something was miscompiled...
741 if (!BugpointIsInterrupted)
742 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun, *Error)) {
744 errs() << "*** Optimized program matches reference output! No problem"
745 << " detected...\nbugpoint can't help you with your problem!\n";
749 outs() << "\n*** Found miscompiling pass"
750 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
751 << getPassesString(getPassesToRun()) << '\n';
752 EmitProgressBitcode(Program, "passinput");
754 std::vector<Function *> MiscompiledFunctions =
755 DebugAMiscompilation(*this, TestOptimizer, *Error);
759 // Output a bunch of bitcode files for the user...
760 outs() << "Outputting reduced bitcode files which expose the problem:\n";
761 ValueToValueMapTy VMap;
762 Module *ToNotOptimize = CloneModule(getProgram(), VMap);
763 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
764 MiscompiledFunctions,
767 outs() << " Non-optimized portion: ";
768 EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true);
769 delete ToNotOptimize; // Delete hacked module.
771 outs() << " Portion that is input to optimizer: ";
772 EmitProgressBitcode(ToOptimize, "tooptimize");
773 delete ToOptimize; // Delete hacked module.
778 /// CleanupAndPrepareModules - Get the specified modules ready for code
779 /// generator testing.
781 static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
783 // Clean up the modules, removing extra cruft that we don't need anymore...
784 Test = BD.performFinalCleanups(Test).release();
786 // If we are executing the JIT, we have several nasty issues to take care of.
787 if (!BD.isExecutingJIT()) return;
789 // First, if the main function is in the Safe module, we must add a stub to
790 // the Test module to call into it. Thus, we create a new function `main'
791 // which just calls the old one.
792 if (Function *oldMain = Safe->getFunction("main"))
793 if (!oldMain->isDeclaration()) {
795 oldMain->setName("llvm_bugpoint_old_main");
796 // Create a NEW `main' function with same type in the test module.
797 Function *newMain = Function::Create(oldMain->getFunctionType(),
798 GlobalValue::ExternalLinkage,
800 // Create an `oldmain' prototype in the test module, which will
801 // corresponds to the real main function in the same module.
802 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
803 GlobalValue::ExternalLinkage,
804 oldMain->getName(), Test);
805 // Set up and remember the argument list for the main function.
806 std::vector<Value*> args;
807 for (Function::arg_iterator
808 I = newMain->arg_begin(), E = newMain->arg_end(),
809 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
810 I->setName(OI->getName()); // Copy argument names from oldMain
814 // Call the old main function and return its result
815 BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
816 CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
818 // If the type of old function wasn't void, return value of call
819 ReturnInst::Create(Safe->getContext(), call, BB);
822 // The second nasty issue we must deal with in the JIT is that the Safe
823 // module cannot directly reference any functions defined in the test
824 // module. Instead, we use a JIT API call to dynamically resolve the
827 // Add the resolver to the Safe module.
828 // Prototype: void *getPointerToNamedFunction(const char* Name)
829 Constant *resolverFunc =
830 Safe->getOrInsertFunction("getPointerToNamedFunction",
831 Type::getInt8PtrTy(Safe->getContext()),
832 Type::getInt8PtrTy(Safe->getContext()),
835 // Use the function we just added to get addresses of functions we need.
836 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
837 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
838 !F->isIntrinsic() /* ignore intrinsics */) {
839 Function *TestFn = Test->getFunction(F->getName());
841 // Don't forward functions which are external in the test module too.
842 if (TestFn && !TestFn->isDeclaration()) {
843 // 1. Add a string constant with its name to the global file
844 Constant *InitArray =
845 ConstantDataArray::getString(F->getContext(), F->getName());
846 GlobalVariable *funcName =
847 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
848 GlobalValue::InternalLinkage, InitArray,
849 F->getName() + "_name");
851 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
852 // sbyte* so it matches the signature of the resolver function.
854 // GetElementPtr *funcName, ulong 0, ulong 0
855 std::vector<Constant*> GEPargs(2,
856 Constant::getNullValue(Type::getInt32Ty(F->getContext())));
857 Value *GEP = ConstantExpr::getGetElementPtr(funcName, GEPargs);
858 std::vector<Value*> ResolverArgs;
859 ResolverArgs.push_back(GEP);
861 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
862 // function that dynamically resolves the calls to F via our JIT API
863 if (!F->use_empty()) {
864 // Create a new global to hold the cached function pointer.
865 Constant *NullPtr = ConstantPointerNull::get(F->getType());
866 GlobalVariable *Cache =
867 new GlobalVariable(*F->getParent(), F->getType(),
868 false, GlobalValue::InternalLinkage,
869 NullPtr,F->getName()+".fpcache");
871 // Construct a new stub function that will re-route calls to F
872 FunctionType *FuncTy = F->getFunctionType();
873 Function *FuncWrapper = Function::Create(FuncTy,
874 GlobalValue::InternalLinkage,
875 F->getName() + "_wrapper",
877 BasicBlock *EntryBB = BasicBlock::Create(F->getContext(),
878 "entry", FuncWrapper);
879 BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
880 "usecache", FuncWrapper);
881 BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
882 "lookupfp", FuncWrapper);
884 // Check to see if we already looked up the value.
885 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
886 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
888 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
890 // Resolve the call to function F via the JIT API:
892 // call resolver(GetElementPtr...)
894 CallInst::Create(resolverFunc, ResolverArgs, "resolver", LookupBB);
896 // Cast the result from the resolver to correctly-typed function.
897 CastInst *CastedResolver =
898 new BitCastInst(Resolver,
899 PointerType::getUnqual(F->getFunctionType()),
900 "resolverCast", LookupBB);
902 // Save the value in our cache.
903 new StoreInst(CastedResolver, Cache, LookupBB);
904 BranchInst::Create(DoCallBB, LookupBB);
906 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(), 2,
908 FuncPtr->addIncoming(CastedResolver, LookupBB);
909 FuncPtr->addIncoming(CachedVal, EntryBB);
911 // Save the argument list.
912 std::vector<Value*> Args;
913 for (Function::arg_iterator i = FuncWrapper->arg_begin(),
914 e = FuncWrapper->arg_end(); i != e; ++i)
917 // Pass on the arguments to the real function, return its result
918 if (F->getReturnType()->isVoidTy()) {
919 CallInst::Create(FuncPtr, Args, "", DoCallBB);
920 ReturnInst::Create(F->getContext(), DoCallBB);
922 CallInst *Call = CallInst::Create(FuncPtr, Args,
924 ReturnInst::Create(F->getContext(),Call, DoCallBB);
927 // Use the wrapper function instead of the old function
928 F->replaceAllUsesWith(FuncWrapper);
934 if (verifyModule(*Test) || verifyModule(*Safe)) {
935 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
942 /// TestCodeGenerator - This is the predicate function used to check to see if
943 /// the "Test" portion of the program is miscompiled by the code generator under
944 /// test. If so, return true. In any case, both module arguments are deleted.
946 static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe,
947 std::string &Error) {
948 CleanupAndPrepareModules(BD, Test, Safe);
950 SmallString<128> TestModuleBC;
952 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
953 TestModuleFD, TestModuleBC);
955 errs() << BD.getToolName() << "Error making unique filename: "
956 << EC.message() << "\n";
959 if (BD.writeProgramToFile(TestModuleBC.str(), TestModuleFD, Test)) {
960 errs() << "Error writing bitcode to `" << TestModuleBC.str()
966 FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
968 // Make the shared library
969 SmallString<128> SafeModuleBC;
971 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
974 errs() << BD.getToolName() << "Error making unique filename: "
975 << EC.message() << "\n";
979 if (BD.writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, Safe)) {
980 errs() << "Error writing bitcode to `" << SafeModuleBC.str()
985 FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
987 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str(), Error);
992 FileRemover SharedObjectRemover(SharedObject, !SaveTemps);
994 // Run the code generator on the `Test' code, loading the shared library.
995 // The function returns whether or not the new output differs from reference.
996 bool Result = BD.diffProgram(BD.getProgram(), TestModuleBC.str(),
997 SharedObject, false, &Error);
1002 errs() << ": still failing!\n";
1004 errs() << ": didn't fail.\n";
1010 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
1012 bool BugDriver::debugCodeGenerator(std::string *Error) {
1013 if ((void*)SafeInterpreter == (void*)Interpreter) {
1014 std::string Result = executeProgramSafely(Program, "bugpoint.safe.out",
1016 if (Error->empty()) {
1017 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
1018 << "the reference diff. This may be due to a\n front-end "
1019 << "bug or a bug in the original program, but this can also "
1020 << "happen if bugpoint isn't running the program with the "
1021 << "right flags or input.\n I left the result of executing "
1022 << "the program with the \"safe\" backend in this file for "
1024 << Result << "'.\n";
1029 DisambiguateGlobalSymbols(Program);
1031 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator,
1033 if (!Error->empty())
1036 // Split the module into the two halves of the program we want.
1037 ValueToValueMapTy VMap;
1038 Module *ToNotCodeGen = CloneModule(getProgram(), VMap);
1039 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, VMap);
1041 // Condition the modules
1042 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
1044 SmallString<128> TestModuleBC;
1046 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
1047 TestModuleFD, TestModuleBC);
1049 errs() << getToolName() << "Error making unique filename: "
1050 << EC.message() << "\n";
1054 if (writeProgramToFile(TestModuleBC.str(), TestModuleFD, ToCodeGen)) {
1055 errs() << "Error writing bitcode to `" << TestModuleBC.str()
1061 // Make the shared library
1062 SmallString<128> SafeModuleBC;
1064 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
1067 errs() << getToolName() << "Error making unique filename: "
1068 << EC.message() << "\n";
1072 if (writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, ToNotCodeGen)) {
1073 errs() << "Error writing bitcode to `" << SafeModuleBC.str()
1077 std::string SharedObject = compileSharedObject(SafeModuleBC.str(), *Error);
1078 if (!Error->empty())
1080 delete ToNotCodeGen;
1082 outs() << "You can reproduce the problem with the command line: \n";
1083 if (isExecutingJIT()) {
1084 outs() << " lli -load " << SharedObject << " " << TestModuleBC.str();
1086 outs() << " llc " << TestModuleBC.str() << " -o " << TestModuleBC.str()
1088 outs() << " gcc " << SharedObject << " " << TestModuleBC.str()
1089 << ".s -o " << TestModuleBC.str() << ".exe";
1090 #if defined (HAVE_LINK_R)
1091 outs() << " -Wl,-R.";
1094 outs() << " " << TestModuleBC.str() << ".exe";
1096 for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
1097 outs() << " " << InputArgv[i];
1099 outs() << "The shared object was created with:\n llc -march=c "
1100 << SafeModuleBC.str() << " -o temporary.c\n"
1101 << " gcc -xc temporary.c -O2 -o " << SharedObject;
1102 if (TargetTriple.getArch() == Triple::sparc)
1103 outs() << " -G"; // Compile a shared library, `-G' for Sparc
1105 outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
1107 outs() << " -fno-strict-aliasing\n";