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/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Linker.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Analysis/Verifier.h"
25 #include "llvm/Transforms/Utils/Cloning.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/FileUtilities.h"
28 #include "llvm/Config/config.h" // for HAVE_LINK_R
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 virtual TestResult doTest(std::vector<std::string> &Prefix,
52 std::vector<std::string> &Suffix,
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::Path(BitcodeResult).eraseFromDisk();
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 OwningPtr<Module> PrefixOutput(ParseInputFile(BitcodeResult,
133 if (PrefixOutput == 0) {
134 errs() << BD.getToolName() << ": Error reading bitcode file '"
135 << BitcodeResult << "'!\n";
138 sys::Path(BitcodeResult).eraseFromDisk(); // No longer need the file on disk
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 OwningPtr<Module> OriginalInput(BD.swapProgramIn(PrefixOutput.take()));
149 if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false/*delete*/,
151 errs() << " Error running this sequence of passes"
152 << " on the input program!\n";
153 BD.setPassesToRun(Suffix);
154 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
155 exit(BD.debugOptimizerCrash());
159 Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
160 true /*delete bitcode*/, &Error);
162 return InternalError;
164 outs() << " nope.\n";
168 // Otherwise, we must not be running the bad pass anymore.
169 outs() << " yup.\n"; // No miscompilation!
170 // Restore orig program & free test.
171 delete BD.swapProgramIn(OriginalInput.take());
176 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
178 bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
180 ReduceMiscompilingFunctions(BugDriver &bd,
181 bool (*F)(BugDriver &, Module *, Module *,
183 : BD(bd), TestFn(F) {}
185 virtual TestResult doTest(std::vector<Function*> &Prefix,
186 std::vector<Function*> &Suffix,
187 std::string &Error) {
188 if (!Suffix.empty()) {
189 bool Ret = TestFuncs(Suffix, Error);
191 return InternalError;
195 if (!Prefix.empty()) {
196 bool Ret = TestFuncs(Prefix, Error);
198 return InternalError;
205 bool TestFuncs(const std::vector<Function*> &Prefix, std::string &Error);
209 /// TestMergedProgram - Given two modules, link them together and run the
210 /// program, checking to see if the program matches the diff. If there is
211 /// an error, return NULL. If not, return the merged module. The Broken argument
212 /// will be set to true if the output is different. If the DeleteInputs
213 /// argument is set to true then this function deletes both input
214 /// modules before it returns.
216 static Module *TestMergedProgram(const BugDriver &BD, Module *M1, Module *M2,
217 bool DeleteInputs, std::string &Error,
219 // Link the two portions of the program back to together.
220 std::string ErrorMsg;
222 M1 = CloneModule(M1);
223 M2 = CloneModule(M2);
225 if (Linker::LinkModules(M1, M2, &ErrorMsg)) {
226 errs() << BD.getToolName() << ": Error linking modules together:"
230 delete M2; // We are done with this module.
232 // Execute the program.
233 Broken = BD.diffProgram(M1, "", "", false, &Error);
234 if (!Error.empty()) {
235 // Delete the linked module
242 /// TestFuncs - split functions in a Module into two groups: those that are
243 /// under consideration for miscompilation vs. those that are not, and test
244 /// accordingly. Each group of functions becomes a separate Module.
246 bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*> &Funcs,
247 std::string &Error) {
248 // Test to see if the function is misoptimized if we ONLY run it on the
249 // functions listed in Funcs.
250 outs() << "Checking to see if the program is misoptimized when "
251 << (Funcs.size()==1 ? "this function is" : "these functions are")
252 << " run through the pass"
253 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
254 PrintFunctionList(Funcs);
257 // Create a clone for two reasons:
258 // * If the optimization passes delete any function, the deleted function
259 // will be in the clone and Funcs will still point to valid memory
260 // * If the optimization passes use interprocedural information to break
261 // a function, we want to continue with the original function. Otherwise
262 // we can conclude that a function triggers the bug when in fact one
263 // needs a larger set of original functions to do so.
264 ValueToValueMapTy VMap;
265 Module *Clone = CloneModule(BD.getProgram(), VMap);
266 Module *Orig = BD.swapProgramIn(Clone);
268 std::vector<Function*> FuncsOnClone;
269 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
270 Function *F = cast<Function>(VMap[Funcs[i]]);
271 FuncsOnClone.push_back(F);
274 // Split the module into the two halves of the program we want.
276 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
277 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize, FuncsOnClone,
280 // Run the predicate, note that the predicate will delete both input modules.
281 bool Broken = TestFn(BD, ToOptimize, ToNotOptimize, Error);
283 delete BD.swapProgramIn(Orig);
288 /// DisambiguateGlobalSymbols - Give anonymous global values names.
290 static void DisambiguateGlobalSymbols(Module *M) {
291 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
294 I->setName("anon_global");
295 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
297 I->setName("anon_fn");
300 /// ExtractLoops - Given a reduced list of functions that still exposed the bug,
301 /// check to see if we can extract the loops in the region without obscuring the
302 /// bug. If so, it reduces the amount of code identified.
304 static bool ExtractLoops(BugDriver &BD,
305 bool (*TestFn)(BugDriver &, Module *, Module *,
307 std::vector<Function*> &MiscompiledFunctions,
308 std::string &Error) {
309 bool MadeChange = false;
311 if (BugpointIsInterrupted) return MadeChange;
313 ValueToValueMapTy VMap;
314 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
315 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
316 MiscompiledFunctions,
318 Module *ToOptimizeLoopExtracted = BD.ExtractLoop(ToOptimize);
319 if (!ToOptimizeLoopExtracted) {
320 // If the loop extractor crashed or if there were no extractible loops,
321 // then this chapter of our odyssey is over with.
322 delete ToNotOptimize;
327 errs() << "Extracted a loop from the breaking portion of the program.\n";
329 // Bugpoint is intentionally not very trusting of LLVM transformations. In
330 // particular, we're not going to assume that the loop extractor works, so
331 // we're going to test the newly loop extracted program to make sure nothing
332 // has broken. If something broke, then we'll inform the user and stop
334 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
336 Module *New = TestMergedProgram(BD, ToOptimizeLoopExtracted, ToNotOptimize,
337 false, Error, Failure);
340 // Delete the original and set the new program.
341 delete BD.swapProgramIn(New);
343 BD.switchToInterpreter(AI);
345 // Merged program doesn't work anymore!
346 errs() << " *** ERROR: Loop extraction broke the program. :("
347 << " Please report a bug!\n";
348 errs() << " Continuing on with un-loop-extracted version.\n";
350 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
352 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
354 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
355 ToOptimizeLoopExtracted);
357 errs() << "Please submit the "
358 << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
360 delete ToNotOptimize;
361 delete ToOptimizeLoopExtracted;
365 BD.switchToInterpreter(AI);
367 outs() << " Testing after loop extraction:\n";
368 // Clone modules, the tester function will free them.
369 Module *TOLEBackup = CloneModule(ToOptimizeLoopExtracted);
370 Module *TNOBackup = CloneModule(ToNotOptimize);
371 Failure = TestFn(BD, ToOptimizeLoopExtracted, ToNotOptimize, Error);
375 outs() << "*** Loop extraction masked the problem. Undoing.\n";
376 // If the program is not still broken, then loop extraction did something
377 // that masked the error. Stop loop extraction now.
382 ToOptimizeLoopExtracted = TOLEBackup;
383 ToNotOptimize = TNOBackup;
385 outs() << "*** Loop extraction successful!\n";
387 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
388 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
389 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
390 if (!I->isDeclaration())
391 MisCompFunctions.push_back(std::make_pair(I->getName(),
392 I->getFunctionType()));
394 // Okay, great! Now we know that we extracted a loop and that loop
395 // extraction both didn't break the program, and didn't mask the problem.
396 // Replace the current program with the loop extracted version, and try to
397 // extract another loop.
398 std::string ErrorMsg;
399 if (Linker::LinkModules(ToNotOptimize, ToOptimizeLoopExtracted, &ErrorMsg)){
400 errs() << BD.getToolName() << ": Error linking modules together:"
404 delete ToOptimizeLoopExtracted;
406 // All of the Function*'s in the MiscompiledFunctions list are in the old
407 // module. Update this list to include all of the functions in the
408 // optimized and loop extracted module.
409 MiscompiledFunctions.clear();
410 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
411 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
413 assert(NewF && "Function not found??");
414 MiscompiledFunctions.push_back(NewF);
417 BD.setNewProgram(ToNotOptimize);
423 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
425 bool (*TestFn)(BugDriver &, Module *, Module *, std::string &);
426 std::vector<Function*> FunctionsBeingTested;
428 ReduceMiscompiledBlocks(BugDriver &bd,
429 bool (*F)(BugDriver &, Module *, Module *,
431 const std::vector<Function*> &Fns)
432 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
434 virtual TestResult doTest(std::vector<BasicBlock*> &Prefix,
435 std::vector<BasicBlock*> &Suffix,
436 std::string &Error) {
437 if (!Suffix.empty()) {
438 bool Ret = TestFuncs(Suffix, Error);
440 return InternalError;
444 if (!Prefix.empty()) {
445 bool Ret = TestFuncs(Prefix, Error);
447 return InternalError;
454 bool TestFuncs(const std::vector<BasicBlock*> &BBs, std::string &Error);
458 /// TestFuncs - Extract all blocks for the miscompiled functions except for the
459 /// specified blocks. If the problem still exists, return true.
461 bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs,
462 std::string &Error) {
463 // Test to see if the function is misoptimized if we ONLY run it on the
464 // functions listed in Funcs.
465 outs() << "Checking to see if the program is misoptimized when all ";
467 outs() << "but these " << BBs.size() << " blocks are extracted: ";
468 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
469 outs() << BBs[i]->getName() << " ";
470 if (BBs.size() > 10) outs() << "...";
472 outs() << "blocks are extracted.";
476 // Split the module into the two halves of the program we want.
477 ValueToValueMapTy VMap;
478 Module *Clone = CloneModule(BD.getProgram(), VMap);
479 Module *Orig = BD.swapProgramIn(Clone);
480 std::vector<Function*> FuncsOnClone;
481 std::vector<BasicBlock*> BBsOnClone;
482 for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
483 Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
484 FuncsOnClone.push_back(F);
486 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
487 BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
488 BBsOnClone.push_back(BB);
492 Module *ToNotOptimize = CloneModule(BD.getProgram(), VMap);
493 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
497 // Try the extraction. If it doesn't work, then the block extractor crashed
498 // or something, in which case bugpoint can't chase down this possibility.
499 if (Module *New = BD.ExtractMappedBlocksFromModule(BBsOnClone, ToOptimize)) {
501 // Run the predicate,
502 // note that the predicate will delete both input modules.
503 bool Ret = TestFn(BD, New, ToNotOptimize, Error);
504 delete BD.swapProgramIn(Orig);
507 delete BD.swapProgramIn(Orig);
509 delete ToNotOptimize;
514 /// ExtractBlocks - Given a reduced list of functions that still expose the bug,
515 /// extract as many basic blocks from the region as possible without obscuring
518 static bool ExtractBlocks(BugDriver &BD,
519 bool (*TestFn)(BugDriver &, Module *, Module *,
521 std::vector<Function*> &MiscompiledFunctions,
522 std::string &Error) {
523 if (BugpointIsInterrupted) return false;
525 std::vector<BasicBlock*> Blocks;
526 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
527 for (Function::iterator I = MiscompiledFunctions[i]->begin(),
528 E = MiscompiledFunctions[i]->end(); I != E; ++I)
531 // Use the list reducer to identify blocks that can be extracted without
532 // obscuring the bug. The Blocks list will end up containing blocks that must
533 // be retained from the original program.
534 unsigned OldSize = Blocks.size();
536 // Check to see if all blocks are extractible first.
537 bool Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
538 .TestFuncs(std::vector<BasicBlock*>(), Error);
544 ReduceMiscompiledBlocks(BD, TestFn,
545 MiscompiledFunctions).reduceList(Blocks, Error);
548 if (Blocks.size() == OldSize)
552 ValueToValueMapTy VMap;
553 Module *ProgClone = CloneModule(BD.getProgram(), VMap);
554 Module *ToExtract = SplitFunctionsOutOfModule(ProgClone,
555 MiscompiledFunctions,
557 Module *Extracted = BD.ExtractMappedBlocksFromModule(Blocks, ToExtract);
558 if (Extracted == 0) {
559 // Weird, extraction should have worked.
560 errs() << "Nondeterministic problem extracting blocks??\n";
566 // Otherwise, block extraction succeeded. Link the two program fragments back
570 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
571 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
573 if (!I->isDeclaration())
574 MisCompFunctions.push_back(std::make_pair(I->getName(),
575 I->getFunctionType()));
577 std::string ErrorMsg;
578 if (Linker::LinkModules(ProgClone, Extracted, &ErrorMsg)) {
579 errs() << BD.getToolName() << ": Error linking modules together:"
585 // Set the new program and delete the old one.
586 BD.setNewProgram(ProgClone);
588 // Update the list of miscompiled functions.
589 MiscompiledFunctions.clear();
591 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
592 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
593 assert(NewF && "Function not found??");
594 MiscompiledFunctions.push_back(NewF);
601 /// DebugAMiscompilation - This is a generic driver to narrow down
602 /// miscompilations, either in an optimization or a code generator.
604 static std::vector<Function*>
605 DebugAMiscompilation(BugDriver &BD,
606 bool (*TestFn)(BugDriver &, Module *, Module *,
608 std::string &Error) {
609 // Okay, now that we have reduced the list of passes which are causing the
610 // failure, see if we can pin down which functions are being
611 // miscompiled... first build a list of all of the non-external functions in
613 std::vector<Function*> MiscompiledFunctions;
614 Module *Prog = BD.getProgram();
615 for (Module::iterator I = Prog->begin(), E = Prog->end(); I != E; ++I)
616 if (!I->isDeclaration())
617 MiscompiledFunctions.push_back(I);
619 // Do the reduction...
620 if (!BugpointIsInterrupted)
621 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
623 if (!Error.empty()) {
624 errs() << "\n***Cannot reduce functions: ";
625 return MiscompiledFunctions;
627 outs() << "\n*** The following function"
628 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
629 << " being miscompiled: ";
630 PrintFunctionList(MiscompiledFunctions);
633 // See if we can rip any loops out of the miscompiled functions and still
634 // trigger the problem.
636 if (!BugpointIsInterrupted && !DisableLoopExtraction) {
637 bool Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions, Error);
639 return MiscompiledFunctions;
641 // Okay, we extracted some loops and the problem still appears. See if
642 // we can eliminate some of the created functions from being candidates.
643 DisambiguateGlobalSymbols(BD.getProgram());
645 // Do the reduction...
646 if (!BugpointIsInterrupted)
647 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
650 return MiscompiledFunctions;
652 outs() << "\n*** The following function"
653 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
654 << " being miscompiled: ";
655 PrintFunctionList(MiscompiledFunctions);
660 if (!BugpointIsInterrupted && !DisableBlockExtraction) {
661 bool Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions, Error);
663 return MiscompiledFunctions;
665 // Okay, we extracted some blocks and the problem still appears. See if
666 // we can eliminate some of the created functions from being candidates.
667 DisambiguateGlobalSymbols(BD.getProgram());
669 // Do the reduction...
670 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
673 return MiscompiledFunctions;
675 outs() << "\n*** The following function"
676 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
677 << " being miscompiled: ";
678 PrintFunctionList(MiscompiledFunctions);
683 return MiscompiledFunctions;
686 /// TestOptimizer - This is the predicate function used to check to see if the
687 /// "Test" portion of the program is misoptimized. If so, return true. In any
688 /// case, both module arguments are deleted.
690 static bool TestOptimizer(BugDriver &BD, Module *Test, Module *Safe,
691 std::string &Error) {
692 // Run the optimization passes on ToOptimize, producing a transformed version
693 // of the functions being tested.
694 outs() << " Optimizing functions being tested: ";
695 Module *Optimized = BD.runPassesOn(Test, BD.getPassesToRun(),
696 /*AutoDebugCrashes*/true);
700 outs() << " Checking to see if the merged program executes correctly: ";
702 Module *New = TestMergedProgram(BD, Optimized, Safe, true, Error, Broken);
704 outs() << (Broken ? " nope.\n" : " yup.\n");
705 // Delete the original and set the new program.
706 delete BD.swapProgramIn(New);
712 /// debugMiscompilation - This method is used when the passes selected are not
713 /// crashing, but the generated output is semantically different from the
716 void BugDriver::debugMiscompilation(std::string *Error) {
717 // Make sure something was miscompiled...
718 if (!BugpointIsInterrupted)
719 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun, *Error)) {
721 errs() << "*** Optimized program matches reference output! No problem"
722 << " detected...\nbugpoint can't help you with your problem!\n";
726 outs() << "\n*** Found miscompiling pass"
727 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
728 << getPassesString(getPassesToRun()) << '\n';
729 EmitProgressBitcode(Program, "passinput");
731 std::vector<Function *> MiscompiledFunctions =
732 DebugAMiscompilation(*this, TestOptimizer, *Error);
736 // Output a bunch of bitcode files for the user...
737 outs() << "Outputting reduced bitcode files which expose the problem:\n";
738 ValueToValueMapTy VMap;
739 Module *ToNotOptimize = CloneModule(getProgram(), VMap);
740 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize,
741 MiscompiledFunctions,
744 outs() << " Non-optimized portion: ";
745 EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true);
746 delete ToNotOptimize; // Delete hacked module.
748 outs() << " Portion that is input to optimizer: ";
749 EmitProgressBitcode(ToOptimize, "tooptimize");
750 delete ToOptimize; // Delete hacked module.
755 /// CleanupAndPrepareModules - Get the specified modules ready for code
756 /// generator testing.
758 static void CleanupAndPrepareModules(BugDriver &BD, Module *&Test,
760 // Clean up the modules, removing extra cruft that we don't need anymore...
761 Test = BD.performFinalCleanups(Test);
763 // If we are executing the JIT, we have several nasty issues to take care of.
764 if (!BD.isExecutingJIT()) return;
766 // First, if the main function is in the Safe module, we must add a stub to
767 // the Test module to call into it. Thus, we create a new function `main'
768 // which just calls the old one.
769 if (Function *oldMain = Safe->getFunction("main"))
770 if (!oldMain->isDeclaration()) {
772 oldMain->setName("llvm_bugpoint_old_main");
773 // Create a NEW `main' function with same type in the test module.
774 Function *newMain = Function::Create(oldMain->getFunctionType(),
775 GlobalValue::ExternalLinkage,
777 // Create an `oldmain' prototype in the test module, which will
778 // corresponds to the real main function in the same module.
779 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
780 GlobalValue::ExternalLinkage,
781 oldMain->getName(), Test);
782 // Set up and remember the argument list for the main function.
783 std::vector<Value*> args;
784 for (Function::arg_iterator
785 I = newMain->arg_begin(), E = newMain->arg_end(),
786 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
787 I->setName(OI->getName()); // Copy argument names from oldMain
791 // Call the old main function and return its result
792 BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
793 CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
795 // If the type of old function wasn't void, return value of call
796 ReturnInst::Create(Safe->getContext(), call, BB);
799 // The second nasty issue we must deal with in the JIT is that the Safe
800 // module cannot directly reference any functions defined in the test
801 // module. Instead, we use a JIT API call to dynamically resolve the
804 // Add the resolver to the Safe module.
805 // Prototype: void *getPointerToNamedFunction(const char* Name)
806 Constant *resolverFunc =
807 Safe->getOrInsertFunction("getPointerToNamedFunction",
808 Type::getInt8PtrTy(Safe->getContext()),
809 Type::getInt8PtrTy(Safe->getContext()),
812 // Use the function we just added to get addresses of functions we need.
813 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
814 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
815 !F->isIntrinsic() /* ignore intrinsics */) {
816 Function *TestFn = Test->getFunction(F->getName());
818 // Don't forward functions which are external in the test module too.
819 if (TestFn && !TestFn->isDeclaration()) {
820 // 1. Add a string constant with its name to the global file
821 Constant *InitArray = ConstantArray::get(F->getContext(), F->getName());
822 GlobalVariable *funcName =
823 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
824 GlobalValue::InternalLinkage, InitArray,
825 F->getName() + "_name");
827 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
828 // sbyte* so it matches the signature of the resolver function.
830 // GetElementPtr *funcName, ulong 0, ulong 0
831 std::vector<Constant*> GEPargs(2,
832 Constant::getNullValue(Type::getInt32Ty(F->getContext())));
833 Value *GEP = ConstantExpr::getGetElementPtr(funcName, GEPargs);
834 std::vector<Value*> ResolverArgs;
835 ResolverArgs.push_back(GEP);
837 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
838 // function that dynamically resolves the calls to F via our JIT API
839 if (!F->use_empty()) {
840 // Create a new global to hold the cached function pointer.
841 Constant *NullPtr = ConstantPointerNull::get(F->getType());
842 GlobalVariable *Cache =
843 new GlobalVariable(*F->getParent(), F->getType(),
844 false, GlobalValue::InternalLinkage,
845 NullPtr,F->getName()+".fpcache");
847 // Construct a new stub function that will re-route calls to F
848 FunctionType *FuncTy = F->getFunctionType();
849 Function *FuncWrapper = Function::Create(FuncTy,
850 GlobalValue::InternalLinkage,
851 F->getName() + "_wrapper",
853 BasicBlock *EntryBB = BasicBlock::Create(F->getContext(),
854 "entry", FuncWrapper);
855 BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
856 "usecache", FuncWrapper);
857 BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
858 "lookupfp", FuncWrapper);
860 // Check to see if we already looked up the value.
861 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
862 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
864 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
866 // Resolve the call to function F via the JIT API:
868 // call resolver(GetElementPtr...)
870 CallInst::Create(resolverFunc, ResolverArgs, "resolver", LookupBB);
872 // Cast the result from the resolver to correctly-typed function.
873 CastInst *CastedResolver =
874 new BitCastInst(Resolver,
875 PointerType::getUnqual(F->getFunctionType()),
876 "resolverCast", LookupBB);
878 // Save the value in our cache.
879 new StoreInst(CastedResolver, Cache, LookupBB);
880 BranchInst::Create(DoCallBB, LookupBB);
882 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(), 2,
884 FuncPtr->addIncoming(CastedResolver, LookupBB);
885 FuncPtr->addIncoming(CachedVal, EntryBB);
887 // Save the argument list.
888 std::vector<Value*> Args;
889 for (Function::arg_iterator i = FuncWrapper->arg_begin(),
890 e = FuncWrapper->arg_end(); i != e; ++i)
893 // Pass on the arguments to the real function, return its result
894 if (F->getReturnType()->isVoidTy()) {
895 CallInst::Create(FuncPtr, Args, "", DoCallBB);
896 ReturnInst::Create(F->getContext(), DoCallBB);
898 CallInst *Call = CallInst::Create(FuncPtr, Args,
900 ReturnInst::Create(F->getContext(),Call, DoCallBB);
903 // Use the wrapper function instead of the old function
904 F->replaceAllUsesWith(FuncWrapper);
910 if (verifyModule(*Test) || verifyModule(*Safe)) {
911 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
918 /// TestCodeGenerator - This is the predicate function used to check to see if
919 /// the "Test" portion of the program is miscompiled by the code generator under
920 /// test. If so, return true. In any case, both module arguments are deleted.
922 static bool TestCodeGenerator(BugDriver &BD, Module *Test, Module *Safe,
923 std::string &Error) {
924 CleanupAndPrepareModules(BD, Test, Safe);
926 sys::Path TestModuleBC("bugpoint.test.bc");
928 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
929 errs() << BD.getToolName() << "Error making unique filename: "
933 if (BD.writeProgramToFile(TestModuleBC.str(), Test)) {
934 errs() << "Error writing bitcode to `" << TestModuleBC.str()
940 FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
942 // Make the shared library
943 sys::Path SafeModuleBC("bugpoint.safe.bc");
944 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
945 errs() << BD.getToolName() << "Error making unique filename: "
950 if (BD.writeProgramToFile(SafeModuleBC.str(), Safe)) {
951 errs() << "Error writing bitcode to `" << SafeModuleBC.str()
956 FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
958 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str(), Error);
963 FileRemover SharedObjectRemover(SharedObject, !SaveTemps);
965 // Run the code generator on the `Test' code, loading the shared library.
966 // The function returns whether or not the new output differs from reference.
967 bool Result = BD.diffProgram(BD.getProgram(), TestModuleBC.str(),
968 SharedObject, false, &Error);
973 errs() << ": still failing!\n";
975 errs() << ": didn't fail.\n";
981 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
983 bool BugDriver::debugCodeGenerator(std::string *Error) {
984 if ((void*)SafeInterpreter == (void*)Interpreter) {
985 std::string Result = executeProgramSafely(Program, "bugpoint.safe.out",
987 if (Error->empty()) {
988 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
989 << "the reference diff. This may be due to a\n front-end "
990 << "bug or a bug in the original program, but this can also "
991 << "happen if bugpoint isn't running the program with the "
992 << "right flags or input.\n I left the result of executing "
993 << "the program with the \"safe\" backend in this file for "
1000 DisambiguateGlobalSymbols(Program);
1002 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator,
1004 if (!Error->empty())
1007 // Split the module into the two halves of the program we want.
1008 ValueToValueMapTy VMap;
1009 Module *ToNotCodeGen = CloneModule(getProgram(), VMap);
1010 Module *ToCodeGen = SplitFunctionsOutOfModule(ToNotCodeGen, Funcs, VMap);
1012 // Condition the modules
1013 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen);
1015 sys::Path TestModuleBC("bugpoint.test.bc");
1017 if (TestModuleBC.makeUnique(true, &ErrMsg)) {
1018 errs() << getToolName() << "Error making unique filename: "
1023 if (writeProgramToFile(TestModuleBC.str(), ToCodeGen)) {
1024 errs() << "Error writing bitcode to `" << TestModuleBC.str()
1030 // Make the shared library
1031 sys::Path SafeModuleBC("bugpoint.safe.bc");
1032 if (SafeModuleBC.makeUnique(true, &ErrMsg)) {
1033 errs() << getToolName() << "Error making unique filename: "
1038 if (writeProgramToFile(SafeModuleBC.str(), ToNotCodeGen)) {
1039 errs() << "Error writing bitcode to `" << SafeModuleBC.str()
1043 std::string SharedObject = compileSharedObject(SafeModuleBC.str(), *Error);
1044 if (!Error->empty())
1046 delete ToNotCodeGen;
1048 outs() << "You can reproduce the problem with the command line: \n";
1049 if (isExecutingJIT()) {
1050 outs() << " lli -load " << SharedObject << " " << TestModuleBC.str();
1052 outs() << " llc " << TestModuleBC.str() << " -o " << TestModuleBC.str()
1054 outs() << " gcc " << SharedObject << " " << TestModuleBC.str()
1055 << ".s -o " << TestModuleBC.str() << ".exe";
1056 #if defined (HAVE_LINK_R)
1057 outs() << " -Wl,-R.";
1060 outs() << " " << TestModuleBC.str() << ".exe";
1062 for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
1063 outs() << " " << InputArgv[i];
1065 outs() << "The shared object was created with:\n llc -march=c "
1066 << SafeModuleBC.str() << " -o temporary.c\n"
1067 << " gcc -xc temporary.c -O2 -o " << SharedObject;
1068 if (TargetTriple.getArch() == Triple::sparc)
1069 outs() << " -G"; // Compile a shared library, `-G' for Sparc
1071 outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
1073 outs() << " -fno-strict-aliasing\n";