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 "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Linker.h"
21 #include "llvm/Module.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Analysis/Verifier.h"
24 #include "llvm/Support/Mangler.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::list
<std::string
> InputArgv
;
36 static llvm::cl::opt
<bool>
37 DisableLoopExtraction("disable-loop-extraction",
38 cl::desc("Don't extract loops when searching for miscompilations"),
40 static llvm::cl::opt
<bool>
41 DisableBlockExtraction("disable-block-extraction",
42 cl::desc("Don't extract blocks when searching for miscompilations"),
45 class ReduceMiscompilingPasses
: public ListReducer
<const PassInfo
*> {
48 ReduceMiscompilingPasses(BugDriver
&bd
) : BD(bd
) {}
50 virtual TestResult
doTest(std::vector
<const PassInfo
*> &Prefix
,
51 std::vector
<const PassInfo
*> &Suffix
);
55 /// TestResult - After passes have been split into a test group and a control
56 /// group, see if they still break the program.
58 ReduceMiscompilingPasses::TestResult
59 ReduceMiscompilingPasses::doTest(std::vector
<const PassInfo
*> &Prefix
,
60 std::vector
<const PassInfo
*> &Suffix
) {
61 // First, run the program with just the Suffix passes. If it is still broken
62 // with JUST the kept passes, discard the prefix passes.
63 outs() << "Checking to see if '" << getPassesString(Suffix
)
64 << "' compiles correctly: ";
66 std::string BitcodeResult
;
67 if (BD
.runPasses(Suffix
, BitcodeResult
, false/*delete*/, true/*quiet*/)) {
68 errs() << " Error running this sequence of passes"
69 << " on the input program!\n";
70 BD
.setPassesToRun(Suffix
);
71 BD
.EmitProgressBitcode("pass-error", false);
72 exit(BD
.debugOptimizerCrash());
75 // Check to see if the finished program matches the reference output...
76 if (BD
.diffProgram(BitcodeResult
, "", true /*delete bitcode*/)) {
79 errs() << BD
.getToolName() << ": I'm confused: the test fails when "
80 << "no passes are run, nondeterministic program?\n";
83 return KeepSuffix
; // Miscompilation detected!
85 outs() << " yup.\n"; // No miscompilation!
87 if (Prefix
.empty()) return NoFailure
;
89 // Next, see if the program is broken if we run the "prefix" passes first,
90 // then separately run the "kept" passes.
91 outs() << "Checking to see if '" << getPassesString(Prefix
)
92 << "' compiles correctly: ";
94 // If it is not broken with the kept passes, it's possible that the prefix
95 // passes must be run before the kept passes to break it. If the program
96 // WORKS after the prefix passes, but then fails if running the prefix AND
97 // kept passes, we can update our bitcode file to include the result of the
98 // prefix passes, then discard the prefix passes.
100 if (BD
.runPasses(Prefix
, BitcodeResult
, false/*delete*/, true/*quiet*/)) {
101 errs() << " Error running this sequence of passes"
102 << " on the input program!\n";
103 BD
.setPassesToRun(Prefix
);
104 BD
.EmitProgressBitcode("pass-error", false);
105 exit(BD
.debugOptimizerCrash());
108 // If the prefix maintains the predicate by itself, only keep the prefix!
109 if (BD
.diffProgram(BitcodeResult
)) {
110 outs() << " nope.\n";
111 sys::Path(BitcodeResult
).eraseFromDisk();
114 outs() << " yup.\n"; // No miscompilation!
116 // Ok, so now we know that the prefix passes work, try running the suffix
117 // passes on the result of the prefix passes.
119 Module
*PrefixOutput
= ParseInputFile(BitcodeResult
, BD
.getContext());
120 if (PrefixOutput
== 0) {
121 errs() << BD
.getToolName() << ": Error reading bitcode file '"
122 << BitcodeResult
<< "'!\n";
125 sys::Path(BitcodeResult
).eraseFromDisk(); // No longer need the file on disk
127 // Don't check if there are no passes in the suffix.
131 outs() << "Checking to see if '" << getPassesString(Suffix
)
132 << "' passes compile correctly after the '"
133 << getPassesString(Prefix
) << "' passes: ";
135 Module
*OriginalInput
= BD
.swapProgramIn(PrefixOutput
);
136 if (BD
.runPasses(Suffix
, BitcodeResult
, false/*delete*/, true/*quiet*/)) {
137 errs() << " Error running this sequence of passes"
138 << " on the input program!\n";
139 BD
.setPassesToRun(Suffix
);
140 BD
.EmitProgressBitcode("pass-error", false);
141 exit(BD
.debugOptimizerCrash());
145 if (BD
.diffProgram(BitcodeResult
, "", true/*delete bitcode*/)) {
146 outs() << " nope.\n";
147 delete OriginalInput
; // We pruned down the original input...
151 // Otherwise, we must not be running the bad pass anymore.
152 outs() << " yup.\n"; // No miscompilation!
153 delete BD
.swapProgramIn(OriginalInput
); // Restore orig program & free test
158 class ReduceMiscompilingFunctions
: public ListReducer
<Function
*> {
160 bool (*TestFn
)(BugDriver
&, Module
*, Module
*);
162 ReduceMiscompilingFunctions(BugDriver
&bd
,
163 bool (*F
)(BugDriver
&, Module
*, Module
*))
164 : BD(bd
), TestFn(F
) {}
166 virtual TestResult
doTest(std::vector
<Function
*> &Prefix
,
167 std::vector
<Function
*> &Suffix
) {
168 if (!Suffix
.empty() && TestFuncs(Suffix
))
170 if (!Prefix
.empty() && TestFuncs(Prefix
))
175 bool TestFuncs(const std::vector
<Function
*> &Prefix
);
179 /// TestMergedProgram - Given two modules, link them together and run the
180 /// program, checking to see if the program matches the diff. If the diff
181 /// matches, return false, otherwise return true. If the DeleteInputs argument
182 /// is set to true then this function deletes both input modules before it
185 static bool TestMergedProgram(BugDriver
&BD
, Module
*M1
, Module
*M2
,
187 // Link the two portions of the program back to together.
188 std::string ErrorMsg
;
190 M1
= CloneModule(M1
);
191 M2
= CloneModule(M2
);
193 if (Linker::LinkModules(M1
, M2
, &ErrorMsg
)) {
194 errs() << BD
.getToolName() << ": Error linking modules together:"
198 delete M2
; // We are done with this module.
200 Module
*OldProgram
= BD
.swapProgramIn(M1
);
202 // Execute the program. If it does not match the expected output, we must
204 bool Broken
= BD
.diffProgram();
206 // Delete the linked module & restore the original
207 BD
.swapProgramIn(OldProgram
);
212 /// TestFuncs - split functions in a Module into two groups: those that are
213 /// under consideration for miscompilation vs. those that are not, and test
214 /// accordingly. Each group of functions becomes a separate Module.
216 bool ReduceMiscompilingFunctions::TestFuncs(const std::vector
<Function
*>&Funcs
){
217 // Test to see if the function is misoptimized if we ONLY run it on the
218 // functions listed in Funcs.
219 outs() << "Checking to see if the program is misoptimized when "
220 << (Funcs
.size()==1 ? "this function is" : "these functions are")
221 << " run through the pass"
222 << (BD
.getPassesToRun().size() == 1 ? "" : "es") << ":";
223 PrintFunctionList(Funcs
);
226 // Split the module into the two halves of the program we want.
227 DenseMap
<const Value
*, Value
*> ValueMap
;
228 Module
*ToNotOptimize
= CloneModule(BD
.getProgram(), ValueMap
);
229 Module
*ToOptimize
= SplitFunctionsOutOfModule(ToNotOptimize
, Funcs
,
232 // Run the predicate, note that the predicate will delete both input modules.
233 return TestFn(BD
, ToOptimize
, ToNotOptimize
);
236 /// DisambiguateGlobalSymbols - Mangle symbols to guarantee uniqueness by
237 /// modifying predominantly internal symbols rather than external ones.
239 static void DisambiguateGlobalSymbols(Module
*M
) {
240 // Try not to cause collisions by minimizing chances of renaming an
241 // already-external symbol, so take in external globals and functions as-is.
242 // The code should work correctly without disambiguation (assuming the same
243 // mangler is used by the two code generators), but having symbols with the
244 // same name causes warnings to be emitted by the code generator.
246 // Agree with the CBE on symbol naming
247 Mang
.markCharUnacceptable('.');
248 for (Module::global_iterator I
= M
->global_begin(), E
= M
->global_end();
250 // Don't mangle asm names.
251 if (!I
->hasName() || I
->getName()[0] != 1)
252 I
->setName(Mang
.getMangledName(I
));
254 for (Module::iterator I
= M
->begin(), E
= M
->end(); I
!= E
; ++I
) {
255 // Don't mangle asm names or intrinsics.
256 if ((!I
->hasName() || I
->getName()[0] != 1) &&
257 I
->getIntrinsicID() == 0)
258 I
->setName(Mang
.getMangledName(I
));
262 /// ExtractLoops - Given a reduced list of functions that still exposed the bug,
263 /// check to see if we can extract the loops in the region without obscuring the
264 /// bug. If so, it reduces the amount of code identified.
266 static bool ExtractLoops(BugDriver
&BD
,
267 bool (*TestFn
)(BugDriver
&, Module
*, Module
*),
268 std::vector
<Function
*> &MiscompiledFunctions
) {
269 bool MadeChange
= false;
271 if (BugpointIsInterrupted
) return MadeChange
;
273 DenseMap
<const Value
*, Value
*> ValueMap
;
274 Module
*ToNotOptimize
= CloneModule(BD
.getProgram(), ValueMap
);
275 Module
*ToOptimize
= SplitFunctionsOutOfModule(ToNotOptimize
,
276 MiscompiledFunctions
,
278 Module
*ToOptimizeLoopExtracted
= BD
.ExtractLoop(ToOptimize
);
279 if (!ToOptimizeLoopExtracted
) {
280 // If the loop extractor crashed or if there were no extractible loops,
281 // then this chapter of our odyssey is over with.
282 delete ToNotOptimize
;
287 errs() << "Extracted a loop from the breaking portion of the program.\n";
289 // Bugpoint is intentionally not very trusting of LLVM transformations. In
290 // particular, we're not going to assume that the loop extractor works, so
291 // we're going to test the newly loop extracted program to make sure nothing
292 // has broken. If something broke, then we'll inform the user and stop
294 AbstractInterpreter
*AI
= BD
.switchToSafeInterpreter();
295 if (TestMergedProgram(BD
, ToOptimizeLoopExtracted
, ToNotOptimize
, false)) {
296 BD
.switchToInterpreter(AI
);
298 // Merged program doesn't work anymore!
299 errs() << " *** ERROR: Loop extraction broke the program. :("
300 << " Please report a bug!\n";
301 errs() << " Continuing on with un-loop-extracted version.\n";
303 BD
.writeProgramToFile("bugpoint-loop-extract-fail-tno.bc", ToNotOptimize
);
304 BD
.writeProgramToFile("bugpoint-loop-extract-fail-to.bc", ToOptimize
);
305 BD
.writeProgramToFile("bugpoint-loop-extract-fail-to-le.bc",
306 ToOptimizeLoopExtracted
);
308 errs() << "Please submit the bugpoint-loop-extract-fail-*.bc files.\n";
310 delete ToNotOptimize
;
311 delete ToOptimizeLoopExtracted
;
315 BD
.switchToInterpreter(AI
);
317 outs() << " Testing after loop extraction:\n";
318 // Clone modules, the tester function will free them.
319 Module
*TOLEBackup
= CloneModule(ToOptimizeLoopExtracted
);
320 Module
*TNOBackup
= CloneModule(ToNotOptimize
);
321 if (!TestFn(BD
, ToOptimizeLoopExtracted
, ToNotOptimize
)) {
322 outs() << "*** Loop extraction masked the problem. Undoing.\n";
323 // If the program is not still broken, then loop extraction did something
324 // that masked the error. Stop loop extraction now.
329 ToOptimizeLoopExtracted
= TOLEBackup
;
330 ToNotOptimize
= TNOBackup
;
332 outs() << "*** Loop extraction successful!\n";
334 std::vector
<std::pair
<std::string
, const FunctionType
*> > MisCompFunctions
;
335 for (Module::iterator I
= ToOptimizeLoopExtracted
->begin(),
336 E
= ToOptimizeLoopExtracted
->end(); I
!= E
; ++I
)
337 if (!I
->isDeclaration())
338 MisCompFunctions
.push_back(std::make_pair(I
->getName(),
339 I
->getFunctionType()));
341 // Okay, great! Now we know that we extracted a loop and that loop
342 // extraction both didn't break the program, and didn't mask the problem.
343 // Replace the current program with the loop extracted version, and try to
344 // extract another loop.
345 std::string ErrorMsg
;
346 if (Linker::LinkModules(ToNotOptimize
, ToOptimizeLoopExtracted
, &ErrorMsg
)){
347 errs() << BD
.getToolName() << ": Error linking modules together:"
351 delete ToOptimizeLoopExtracted
;
353 // All of the Function*'s in the MiscompiledFunctions list are in the old
354 // module. Update this list to include all of the functions in the
355 // optimized and loop extracted module.
356 MiscompiledFunctions
.clear();
357 for (unsigned i
= 0, e
= MisCompFunctions
.size(); i
!= e
; ++i
) {
358 Function
*NewF
= ToNotOptimize
->getFunction(MisCompFunctions
[i
].first
);
360 assert(NewF
&& "Function not found??");
361 assert(NewF
->getFunctionType() == MisCompFunctions
[i
].second
&&
362 "found wrong function type?");
363 MiscompiledFunctions
.push_back(NewF
);
366 BD
.setNewProgram(ToNotOptimize
);
372 class ReduceMiscompiledBlocks
: public ListReducer
<BasicBlock
*> {
374 bool (*TestFn
)(BugDriver
&, Module
*, Module
*);
375 std::vector
<Function
*> FunctionsBeingTested
;
377 ReduceMiscompiledBlocks(BugDriver
&bd
,
378 bool (*F
)(BugDriver
&, Module
*, Module
*),
379 const std::vector
<Function
*> &Fns
)
380 : BD(bd
), TestFn(F
), FunctionsBeingTested(Fns
) {}
382 virtual TestResult
doTest(std::vector
<BasicBlock
*> &Prefix
,
383 std::vector
<BasicBlock
*> &Suffix
) {
384 if (!Suffix
.empty() && TestFuncs(Suffix
))
386 if (TestFuncs(Prefix
))
391 bool TestFuncs(const std::vector
<BasicBlock
*> &Prefix
);
395 /// TestFuncs - Extract all blocks for the miscompiled functions except for the
396 /// specified blocks. If the problem still exists, return true.
398 bool ReduceMiscompiledBlocks::TestFuncs(const std::vector
<BasicBlock
*> &BBs
) {
399 // Test to see if the function is misoptimized if we ONLY run it on the
400 // functions listed in Funcs.
401 outs() << "Checking to see if the program is misoptimized when all ";
403 outs() << "but these " << BBs
.size() << " blocks are extracted: ";
404 for (unsigned i
= 0, e
= BBs
.size() < 10 ? BBs
.size() : 10; i
!= e
; ++i
)
405 outs() << BBs
[i
]->getName() << " ";
406 if (BBs
.size() > 10) outs() << "...";
408 outs() << "blocks are extracted.";
412 // Split the module into the two halves of the program we want.
413 DenseMap
<const Value
*, Value
*> ValueMap
;
414 Module
*ToNotOptimize
= CloneModule(BD
.getProgram(), ValueMap
);
415 Module
*ToOptimize
= SplitFunctionsOutOfModule(ToNotOptimize
,
416 FunctionsBeingTested
,
419 // Try the extraction. If it doesn't work, then the block extractor crashed
420 // or something, in which case bugpoint can't chase down this possibility.
421 if (Module
*New
= BD
.ExtractMappedBlocksFromModule(BBs
, ToOptimize
)) {
423 // Run the predicate, not that the predicate will delete both input modules.
424 return TestFn(BD
, New
, ToNotOptimize
);
427 delete ToNotOptimize
;
432 /// ExtractBlocks - Given a reduced list of functions that still expose the bug,
433 /// extract as many basic blocks from the region as possible without obscuring
436 static bool ExtractBlocks(BugDriver
&BD
,
437 bool (*TestFn
)(BugDriver
&, Module
*, Module
*),
438 std::vector
<Function
*> &MiscompiledFunctions
) {
439 if (BugpointIsInterrupted
) return false;
441 std::vector
<BasicBlock
*> Blocks
;
442 for (unsigned i
= 0, e
= MiscompiledFunctions
.size(); i
!= e
; ++i
)
443 for (Function::iterator I
= MiscompiledFunctions
[i
]->begin(),
444 E
= MiscompiledFunctions
[i
]->end(); I
!= E
; ++I
)
447 // Use the list reducer to identify blocks that can be extracted without
448 // obscuring the bug. The Blocks list will end up containing blocks that must
449 // be retained from the original program.
450 unsigned OldSize
= Blocks
.size();
452 // Check to see if all blocks are extractible first.
453 if (ReduceMiscompiledBlocks(BD
, TestFn
,
454 MiscompiledFunctions
).TestFuncs(std::vector
<BasicBlock
*>())) {
457 ReduceMiscompiledBlocks(BD
, TestFn
,MiscompiledFunctions
).reduceList(Blocks
);
458 if (Blocks
.size() == OldSize
)
462 DenseMap
<const Value
*, Value
*> ValueMap
;
463 Module
*ProgClone
= CloneModule(BD
.getProgram(), ValueMap
);
464 Module
*ToExtract
= SplitFunctionsOutOfModule(ProgClone
,
465 MiscompiledFunctions
,
467 Module
*Extracted
= BD
.ExtractMappedBlocksFromModule(Blocks
, ToExtract
);
468 if (Extracted
== 0) {
469 // Weird, extraction should have worked.
470 errs() << "Nondeterministic problem extracting blocks??\n";
476 // Otherwise, block extraction succeeded. Link the two program fragments back
480 std::vector
<std::pair
<std::string
, const FunctionType
*> > MisCompFunctions
;
481 for (Module::iterator I
= Extracted
->begin(), E
= Extracted
->end();
483 if (!I
->isDeclaration())
484 MisCompFunctions
.push_back(std::make_pair(I
->getName(),
485 I
->getFunctionType()));
487 std::string ErrorMsg
;
488 if (Linker::LinkModules(ProgClone
, Extracted
, &ErrorMsg
)) {
489 errs() << BD
.getToolName() << ": Error linking modules together:"
495 // Set the new program and delete the old one.
496 BD
.setNewProgram(ProgClone
);
498 // Update the list of miscompiled functions.
499 MiscompiledFunctions
.clear();
501 for (unsigned i
= 0, e
= MisCompFunctions
.size(); i
!= e
; ++i
) {
502 Function
*NewF
= ProgClone
->getFunction(MisCompFunctions
[i
].first
);
503 assert(NewF
&& "Function not found??");
504 assert(NewF
->getFunctionType() == MisCompFunctions
[i
].second
&&
505 "Function has wrong type??");
506 MiscompiledFunctions
.push_back(NewF
);
513 /// DebugAMiscompilation - This is a generic driver to narrow down
514 /// miscompilations, either in an optimization or a code generator.
516 static std::vector
<Function
*>
517 DebugAMiscompilation(BugDriver
&BD
,
518 bool (*TestFn
)(BugDriver
&, Module
*, Module
*)) {
519 // Okay, now that we have reduced the list of passes which are causing the
520 // failure, see if we can pin down which functions are being
521 // miscompiled... first build a list of all of the non-external functions in
523 std::vector
<Function
*> MiscompiledFunctions
;
524 Module
*Prog
= BD
.getProgram();
525 for (Module::iterator I
= Prog
->begin(), E
= Prog
->end(); I
!= E
; ++I
)
526 if (!I
->isDeclaration())
527 MiscompiledFunctions
.push_back(I
);
529 // Do the reduction...
530 if (!BugpointIsInterrupted
)
531 ReduceMiscompilingFunctions(BD
, TestFn
).reduceList(MiscompiledFunctions
);
533 outs() << "\n*** The following function"
534 << (MiscompiledFunctions
.size() == 1 ? " is" : "s are")
535 << " being miscompiled: ";
536 PrintFunctionList(MiscompiledFunctions
);
539 // See if we can rip any loops out of the miscompiled functions and still
540 // trigger the problem.
542 if (!BugpointIsInterrupted
&& !DisableLoopExtraction
&&
543 ExtractLoops(BD
, TestFn
, MiscompiledFunctions
)) {
544 // Okay, we extracted some loops and the problem still appears. See if we
545 // can eliminate some of the created functions from being candidates.
547 // Loop extraction can introduce functions with the same name (foo_code).
548 // Make sure to disambiguate the symbols so that when the program is split
549 // apart that we can link it back together again.
550 DisambiguateGlobalSymbols(BD
.getProgram());
552 // Do the reduction...
553 if (!BugpointIsInterrupted
)
554 ReduceMiscompilingFunctions(BD
, TestFn
).reduceList(MiscompiledFunctions
);
556 outs() << "\n*** The following function"
557 << (MiscompiledFunctions
.size() == 1 ? " is" : "s are")
558 << " being miscompiled: ";
559 PrintFunctionList(MiscompiledFunctions
);
563 if (!BugpointIsInterrupted
&& !DisableBlockExtraction
&&
564 ExtractBlocks(BD
, TestFn
, MiscompiledFunctions
)) {
565 // Okay, we extracted some blocks and the problem still appears. See if we
566 // can eliminate some of the created functions from being candidates.
568 // Block extraction can introduce functions with the same name (foo_code).
569 // Make sure to disambiguate the symbols so that when the program is split
570 // apart that we can link it back together again.
571 DisambiguateGlobalSymbols(BD
.getProgram());
573 // Do the reduction...
574 ReduceMiscompilingFunctions(BD
, TestFn
).reduceList(MiscompiledFunctions
);
576 outs() << "\n*** The following function"
577 << (MiscompiledFunctions
.size() == 1 ? " is" : "s are")
578 << " being miscompiled: ";
579 PrintFunctionList(MiscompiledFunctions
);
583 return MiscompiledFunctions
;
586 /// TestOptimizer - This is the predicate function used to check to see if the
587 /// "Test" portion of the program is misoptimized. If so, return true. In any
588 /// case, both module arguments are deleted.
590 static bool TestOptimizer(BugDriver
&BD
, Module
*Test
, Module
*Safe
) {
591 // Run the optimization passes on ToOptimize, producing a transformed version
592 // of the functions being tested.
593 outs() << " Optimizing functions being tested: ";
594 Module
*Optimized
= BD
.runPassesOn(Test
, BD
.getPassesToRun(),
595 /*AutoDebugCrashes*/true);
599 outs() << " Checking to see if the merged program executes correctly: ";
600 bool Broken
= TestMergedProgram(BD
, Optimized
, Safe
, true);
601 outs() << (Broken
? " nope.\n" : " yup.\n");
606 /// debugMiscompilation - This method is used when the passes selected are not
607 /// crashing, but the generated output is semantically different from the
610 bool BugDriver::debugMiscompilation() {
611 // Make sure something was miscompiled...
612 if (!BugpointIsInterrupted
)
613 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun
)) {
614 errs() << "*** Optimized program matches reference output! No problem"
615 << " detected...\nbugpoint can't help you with your problem!\n";
619 outs() << "\n*** Found miscompiling pass"
620 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
621 << getPassesString(getPassesToRun()) << '\n';
622 EmitProgressBitcode("passinput");
624 std::vector
<Function
*> MiscompiledFunctions
=
625 DebugAMiscompilation(*this, TestOptimizer
);
627 // Output a bunch of bitcode files for the user...
628 outs() << "Outputting reduced bitcode files which expose the problem:\n";
629 DenseMap
<const Value
*, Value
*> ValueMap
;
630 Module
*ToNotOptimize
= CloneModule(getProgram(), ValueMap
);
631 Module
*ToOptimize
= SplitFunctionsOutOfModule(ToNotOptimize
,
632 MiscompiledFunctions
,
635 outs() << " Non-optimized portion: ";
636 ToNotOptimize
= swapProgramIn(ToNotOptimize
);
637 EmitProgressBitcode("tonotoptimize", true);
638 setNewProgram(ToNotOptimize
); // Delete hacked module.
640 outs() << " Portion that is input to optimizer: ";
641 ToOptimize
= swapProgramIn(ToOptimize
);
642 EmitProgressBitcode("tooptimize");
643 setNewProgram(ToOptimize
); // Delete hacked module.
648 /// CleanupAndPrepareModules - Get the specified modules ready for code
649 /// generator testing.
651 static void CleanupAndPrepareModules(BugDriver
&BD
, Module
*&Test
,
653 // Clean up the modules, removing extra cruft that we don't need anymore...
654 Test
= BD
.performFinalCleanups(Test
);
656 // If we are executing the JIT, we have several nasty issues to take care of.
657 if (!BD
.isExecutingJIT()) return;
659 // First, if the main function is in the Safe module, we must add a stub to
660 // the Test module to call into it. Thus, we create a new function `main'
661 // which just calls the old one.
662 if (Function
*oldMain
= Safe
->getFunction("main"))
663 if (!oldMain
->isDeclaration()) {
665 oldMain
->setName("llvm_bugpoint_old_main");
666 // Create a NEW `main' function with same type in the test module.
667 Function
*newMain
= Function::Create(oldMain
->getFunctionType(),
668 GlobalValue::ExternalLinkage
,
670 // Create an `oldmain' prototype in the test module, which will
671 // corresponds to the real main function in the same module.
672 Function
*oldMainProto
= Function::Create(oldMain
->getFunctionType(),
673 GlobalValue::ExternalLinkage
,
674 oldMain
->getName(), Test
);
675 // Set up and remember the argument list for the main function.
676 std::vector
<Value
*> args
;
677 for (Function::arg_iterator
678 I
= newMain
->arg_begin(), E
= newMain
->arg_end(),
679 OI
= oldMain
->arg_begin(); I
!= E
; ++I
, ++OI
) {
680 I
->setName(OI
->getName()); // Copy argument names from oldMain
684 // Call the old main function and return its result
685 BasicBlock
*BB
= BasicBlock::Create("entry", newMain
);
686 CallInst
*call
= CallInst::Create(oldMainProto
, args
.begin(), args
.end(),
689 // If the type of old function wasn't void, return value of call
690 ReturnInst::Create(call
, BB
);
693 // The second nasty issue we must deal with in the JIT is that the Safe
694 // module cannot directly reference any functions defined in the test
695 // module. Instead, we use a JIT API call to dynamically resolve the
698 // Add the resolver to the Safe module.
699 // Prototype: void *getPointerToNamedFunction(const char* Name)
700 Constant
*resolverFunc
=
701 Safe
->getOrInsertFunction("getPointerToNamedFunction",
702 PointerType::getUnqual(Type::Int8Ty
),
703 PointerType::getUnqual(Type::Int8Ty
), (Type
*)0);
705 // Use the function we just added to get addresses of functions we need.
706 for (Module::iterator F
= Safe
->begin(), E
= Safe
->end(); F
!= E
; ++F
) {
707 if (F
->isDeclaration() && !F
->use_empty() && &*F
!= resolverFunc
&&
708 !F
->isIntrinsic() /* ignore intrinsics */) {
709 Function
*TestFn
= Test
->getFunction(F
->getName());
711 // Don't forward functions which are external in the test module too.
712 if (TestFn
&& !TestFn
->isDeclaration()) {
713 // 1. Add a string constant with its name to the global file
714 Constant
*InitArray
= ConstantArray::get(F
->getName());
715 GlobalVariable
*funcName
=
716 new GlobalVariable(*Safe
, InitArray
->getType(), true /*isConstant*/,
717 GlobalValue::InternalLinkage
, InitArray
,
718 F
->getName() + "_name");
720 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
721 // sbyte* so it matches the signature of the resolver function.
723 // GetElementPtr *funcName, ulong 0, ulong 0
724 std::vector
<Constant
*> GEPargs(2, Constant::getNullValue(Type::Int32Ty
));
726 ConstantExpr::getGetElementPtr(funcName
, &GEPargs
[0], 2);
727 std::vector
<Value
*> ResolverArgs
;
728 ResolverArgs
.push_back(GEP
);
730 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
731 // function that dynamically resolves the calls to F via our JIT API
732 if (!F
->use_empty()) {
733 // Create a new global to hold the cached function pointer.
734 Constant
*NullPtr
= ConstantPointerNull::get(F
->getType());
735 GlobalVariable
*Cache
=
736 new GlobalVariable(*F
->getParent(), F
->getType(),
737 false, GlobalValue::InternalLinkage
,
738 NullPtr
,F
->getName()+".fpcache");
740 // Construct a new stub function that will re-route calls to F
741 const FunctionType
*FuncTy
= F
->getFunctionType();
742 Function
*FuncWrapper
= Function::Create(FuncTy
,
743 GlobalValue::InternalLinkage
,
744 F
->getName() + "_wrapper",
746 BasicBlock
*EntryBB
= BasicBlock::Create("entry", FuncWrapper
);
747 BasicBlock
*DoCallBB
= BasicBlock::Create("usecache", FuncWrapper
);
748 BasicBlock
*LookupBB
= BasicBlock::Create("lookupfp", FuncWrapper
);
750 // Check to see if we already looked up the value.
751 Value
*CachedVal
= new LoadInst(Cache
, "fpcache", EntryBB
);
752 Value
*IsNull
= new ICmpInst(*EntryBB
, ICmpInst::ICMP_EQ
, CachedVal
,
754 BranchInst::Create(LookupBB
, DoCallBB
, IsNull
, EntryBB
);
756 // Resolve the call to function F via the JIT API:
758 // call resolver(GetElementPtr...)
760 CallInst::Create(resolverFunc
, ResolverArgs
.begin(),
761 ResolverArgs
.end(), "resolver", LookupBB
);
763 // Cast the result from the resolver to correctly-typed function.
764 CastInst
*CastedResolver
=
765 new BitCastInst(Resolver
,
766 PointerType::getUnqual(F
->getFunctionType()),
767 "resolverCast", LookupBB
);
769 // Save the value in our cache.
770 new StoreInst(CastedResolver
, Cache
, LookupBB
);
771 BranchInst::Create(DoCallBB
, LookupBB
);
773 PHINode
*FuncPtr
= PHINode::Create(NullPtr
->getType(),
775 FuncPtr
->addIncoming(CastedResolver
, LookupBB
);
776 FuncPtr
->addIncoming(CachedVal
, EntryBB
);
778 // Save the argument list.
779 std::vector
<Value
*> Args
;
780 for (Function::arg_iterator i
= FuncWrapper
->arg_begin(),
781 e
= FuncWrapper
->arg_end(); i
!= e
; ++i
)
784 // Pass on the arguments to the real function, return its result
785 if (F
->getReturnType() == Type::VoidTy
) {
786 CallInst::Create(FuncPtr
, Args
.begin(), Args
.end(), "", DoCallBB
);
787 ReturnInst::Create(DoCallBB
);
789 CallInst
*Call
= CallInst::Create(FuncPtr
, Args
.begin(), Args
.end(),
791 ReturnInst::Create(Call
, DoCallBB
);
794 // Use the wrapper function instead of the old function
795 F
->replaceAllUsesWith(FuncWrapper
);
801 if (verifyModule(*Test
) || verifyModule(*Safe
)) {
802 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
809 /// TestCodeGenerator - This is the predicate function used to check to see if
810 /// the "Test" portion of the program is miscompiled by the code generator under
811 /// test. If so, return true. In any case, both module arguments are deleted.
813 static bool TestCodeGenerator(BugDriver
&BD
, Module
*Test
, Module
*Safe
) {
814 CleanupAndPrepareModules(BD
, Test
, Safe
);
816 sys::Path
TestModuleBC("bugpoint.test.bc");
818 if (TestModuleBC
.makeUnique(true, &ErrMsg
)) {
819 errs() << BD
.getToolName() << "Error making unique filename: "
823 if (BD
.writeProgramToFile(TestModuleBC
.toString(), Test
)) {
824 errs() << "Error writing bitcode to `" << TestModuleBC
<< "'\nExiting.";
829 // Make the shared library
830 sys::Path
SafeModuleBC("bugpoint.safe.bc");
831 if (SafeModuleBC
.makeUnique(true, &ErrMsg
)) {
832 errs() << BD
.getToolName() << "Error making unique filename: "
837 if (BD
.writeProgramToFile(SafeModuleBC
.toString(), Safe
)) {
838 errs() << "Error writing bitcode to `" << SafeModuleBC
<< "'\nExiting.";
841 std::string SharedObject
= BD
.compileSharedObject(SafeModuleBC
.toString());
844 // Run the code generator on the `Test' code, loading the shared library.
845 // The function returns whether or not the new output differs from reference.
846 int Result
= BD
.diffProgram(TestModuleBC
.toString(), SharedObject
, false);
849 errs() << ": still failing!\n";
851 errs() << ": didn't fail.\n";
852 TestModuleBC
.eraseFromDisk();
853 SafeModuleBC
.eraseFromDisk();
854 sys::Path(SharedObject
).eraseFromDisk();
860 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
862 bool BugDriver::debugCodeGenerator() {
863 if ((void*)SafeInterpreter
== (void*)Interpreter
) {
864 std::string Result
= executeProgramSafely("bugpoint.safe.out");
865 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
866 << "the reference diff. This may be due to a\n front-end "
867 << "bug or a bug in the original program, but this can also "
868 << "happen if bugpoint isn't running the program with the "
869 << "right flags or input.\n I left the result of executing "
870 << "the program with the \"safe\" backend in this file for "
876 DisambiguateGlobalSymbols(Program
);
878 std::vector
<Function
*> Funcs
= DebugAMiscompilation(*this, TestCodeGenerator
);
880 // Split the module into the two halves of the program we want.
881 DenseMap
<const Value
*, Value
*> ValueMap
;
882 Module
*ToNotCodeGen
= CloneModule(getProgram(), ValueMap
);
883 Module
*ToCodeGen
= SplitFunctionsOutOfModule(ToNotCodeGen
, Funcs
, ValueMap
);
885 // Condition the modules
886 CleanupAndPrepareModules(*this, ToCodeGen
, ToNotCodeGen
);
888 sys::Path
TestModuleBC("bugpoint.test.bc");
890 if (TestModuleBC
.makeUnique(true, &ErrMsg
)) {
891 errs() << getToolName() << "Error making unique filename: "
896 if (writeProgramToFile(TestModuleBC
.toString(), ToCodeGen
)) {
897 errs() << "Error writing bitcode to `" << TestModuleBC
<< "'\nExiting.";
902 // Make the shared library
903 sys::Path
SafeModuleBC("bugpoint.safe.bc");
904 if (SafeModuleBC
.makeUnique(true, &ErrMsg
)) {
905 errs() << getToolName() << "Error making unique filename: "
910 if (writeProgramToFile(SafeModuleBC
.toString(), ToNotCodeGen
)) {
911 errs() << "Error writing bitcode to `" << SafeModuleBC
<< "'\nExiting.";
914 std::string SharedObject
= compileSharedObject(SafeModuleBC
.toString());
917 outs() << "You can reproduce the problem with the command line: \n";
918 if (isExecutingJIT()) {
919 outs() << " lli -load " << SharedObject
<< " " << TestModuleBC
;
921 outs() << " llc -f " << TestModuleBC
<< " -o " << TestModuleBC
<< ".s\n";
922 outs() << " gcc " << SharedObject
<< " " << TestModuleBC
923 << ".s -o " << TestModuleBC
<< ".exe";
924 #if defined (HAVE_LINK_R)
925 outs() << " -Wl,-R.";
928 outs() << " " << TestModuleBC
<< ".exe";
930 for (unsigned i
=0, e
= InputArgv
.size(); i
!= e
; ++i
)
931 outs() << " " << InputArgv
[i
];
933 outs() << "The shared object was created with:\n llc -march=c "
934 << SafeModuleBC
<< " -o temporary.c\n"
935 << " gcc -xc temporary.c -O2 -o " << SharedObject
936 #if defined(sparc) || defined(__sparc__) || defined(__sparcv9)
937 << " -G" // Compile a shared library, `-G' for Sparc
939 << " -fPIC -shared" // `-shared' for Linux/X86, maybe others
941 << " -fno-strict-aliasing\n";