1 //===- Miscompilation.cpp - Debug program miscompilations -----------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements optimizer and code generation miscompilation debugging
12 //===----------------------------------------------------------------------===//
14 #include "BugDriver.h"
15 #include "ListReducer.h"
16 #include "ToolRunner.h"
17 #include "llvm/Config/config.h" // for HAVE_LINK_R
18 #include "llvm/IR/Constants.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/Instructions.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/Verifier.h"
23 #include "llvm/Linker/Linker.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/FileUtilities.h"
27 #include "llvm/Transforms/Utils/Cloning.h"
32 extern cl::opt
<std::string
> OutputPrefix
;
33 extern cl::list
<std::string
> InputArgv
;
34 } // end namespace llvm
37 static llvm::cl::opt
<bool> DisableLoopExtraction(
38 "disable-loop-extraction",
39 cl::desc("Don't extract loops when searching for miscompilations"),
41 static llvm::cl::opt
<bool> DisableBlockExtraction(
42 "disable-block-extraction",
43 cl::desc("Don't extract blocks when searching for miscompilations"),
46 class ReduceMiscompilingPasses
: public ListReducer
<std::string
> {
50 ReduceMiscompilingPasses(BugDriver
&bd
) : BD(bd
) {}
52 Expected
<TestResult
> doTest(std::vector
<std::string
> &Prefix
,
53 std::vector
<std::string
> &Suffix
) override
;
55 } // end anonymous namespace
57 /// TestResult - After passes have been split into a test group and a control
58 /// group, see if they still break the program.
60 Expected
<ReduceMiscompilingPasses::TestResult
>
61 ReduceMiscompilingPasses::doTest(std::vector
<std::string
> &Prefix
,
62 std::vector
<std::string
> &Suffix
) {
63 // First, run the program with just the Suffix passes. If it is still broken
64 // with JUST the kept passes, discard the prefix passes.
65 outs() << "Checking to see if '" << getPassesString(Suffix
)
66 << "' compiles correctly: ";
68 std::string BitcodeResult
;
69 if (BD
.runPasses(BD
.getProgram(), Suffix
, BitcodeResult
, false /*delete*/,
71 errs() << " Error running this sequence of passes"
72 << " on the input program!\n";
73 BD
.setPassesToRun(Suffix
);
74 BD
.EmitProgressBitcode(BD
.getProgram(), "pass-error", false);
75 // TODO: This should propagate the error instead of exiting.
76 if (Error E
= BD
.debugOptimizerCrash())
81 // Check to see if the finished program matches the reference output...
82 Expected
<bool> Diff
= BD
.diffProgram(BD
.getProgram(), BitcodeResult
, "",
83 true /*delete bitcode*/);
84 if (Error E
= Diff
.takeError())
89 errs() << BD
.getToolName() << ": I'm confused: the test fails when "
90 << "no passes are run, nondeterministic program?\n";
93 return KeepSuffix
; // Miscompilation detected!
95 outs() << " yup.\n"; // No miscompilation!
100 // Next, see if the program is broken if we run the "prefix" passes first,
101 // then separately run the "kept" passes.
102 outs() << "Checking to see if '" << getPassesString(Prefix
)
103 << "' compiles correctly: ";
105 // If it is not broken with the kept passes, it's possible that the prefix
106 // passes must be run before the kept passes to break it. If the program
107 // WORKS after the prefix passes, but then fails if running the prefix AND
108 // kept passes, we can update our bitcode file to include the result of the
109 // prefix passes, then discard the prefix passes.
111 if (BD
.runPasses(BD
.getProgram(), Prefix
, BitcodeResult
, false /*delete*/,
113 errs() << " Error running this sequence of passes"
114 << " on the input program!\n";
115 BD
.setPassesToRun(Prefix
);
116 BD
.EmitProgressBitcode(BD
.getProgram(), "pass-error", false);
117 // TODO: This should propagate the error instead of exiting.
118 if (Error E
= BD
.debugOptimizerCrash())
123 // If the prefix maintains the predicate by itself, only keep the prefix!
124 Diff
= BD
.diffProgram(BD
.getProgram(), BitcodeResult
, "", false);
125 if (Error E
= Diff
.takeError())
128 outs() << " nope.\n";
129 sys::fs::remove(BitcodeResult
);
132 outs() << " yup.\n"; // No miscompilation!
134 // Ok, so now we know that the prefix passes work, try running the suffix
135 // passes on the result of the prefix passes.
137 std::unique_ptr
<Module
> PrefixOutput
=
138 parseInputFile(BitcodeResult
, BD
.getContext());
140 errs() << BD
.getToolName() << ": Error reading bitcode file '"
141 << BitcodeResult
<< "'!\n";
144 sys::fs::remove(BitcodeResult
);
146 // Don't check if there are no passes in the suffix.
150 outs() << "Checking to see if '" << getPassesString(Suffix
)
151 << "' passes compile correctly after the '" << getPassesString(Prefix
)
154 std::unique_ptr
<Module
> OriginalInput
=
155 BD
.swapProgramIn(std::move(PrefixOutput
));
156 if (BD
.runPasses(BD
.getProgram(), Suffix
, BitcodeResult
, false /*delete*/,
158 errs() << " Error running this sequence of passes"
159 << " on the input program!\n";
160 BD
.setPassesToRun(Suffix
);
161 BD
.EmitProgressBitcode(BD
.getProgram(), "pass-error", false);
162 // TODO: This should propagate the error instead of exiting.
163 if (Error E
= BD
.debugOptimizerCrash())
169 Diff
= BD
.diffProgram(BD
.getProgram(), BitcodeResult
, "",
170 true /*delete bitcode*/);
171 if (Error E
= Diff
.takeError())
174 outs() << " nope.\n";
178 // Otherwise, we must not be running the bad pass anymore.
179 outs() << " yup.\n"; // No miscompilation!
180 // Restore orig program & free test.
181 BD
.setNewProgram(std::move(OriginalInput
));
186 class ReduceMiscompilingFunctions
: public ListReducer
<Function
*> {
188 Expected
<bool> (*TestFn
)(BugDriver
&, std::unique_ptr
<Module
>,
189 std::unique_ptr
<Module
>);
192 ReduceMiscompilingFunctions(BugDriver
&bd
,
193 Expected
<bool> (*F
)(BugDriver
&,
194 std::unique_ptr
<Module
>,
195 std::unique_ptr
<Module
>))
196 : BD(bd
), TestFn(F
) {}
198 Expected
<TestResult
> doTest(std::vector
<Function
*> &Prefix
,
199 std::vector
<Function
*> &Suffix
) override
{
200 if (!Suffix
.empty()) {
201 Expected
<bool> Ret
= TestFuncs(Suffix
);
202 if (Error E
= Ret
.takeError())
207 if (!Prefix
.empty()) {
208 Expected
<bool> Ret
= TestFuncs(Prefix
);
209 if (Error E
= Ret
.takeError())
217 Expected
<bool> TestFuncs(const std::vector
<Function
*> &Prefix
);
219 } // end anonymous namespace
221 /// Given two modules, link them together and run the program, checking to see
222 /// if the program matches the diff. If there is an error, return NULL. If not,
223 /// return the merged module. The Broken argument will be set to true if the
224 /// output is different. If the DeleteInputs argument is set to true then this
225 /// function deletes both input modules before it returns.
227 static Expected
<std::unique_ptr
<Module
>> testMergedProgram(const BugDriver
&BD
,
231 // Resulting merge of M1 and M2.
232 auto Merged
= CloneModule(M1
);
233 if (Linker::linkModules(*Merged
, CloneModule(M2
)))
234 // TODO: Shouldn't we thread the error up instead of exiting?
237 // Execute the program.
238 Expected
<bool> Diff
= BD
.diffProgram(*Merged
, "", "", false);
239 if (Error E
= Diff
.takeError())
242 return std::move(Merged
);
245 /// split functions in a Module into two groups: those that are under
246 /// consideration for miscompilation vs. those that are not, and test
247 /// accordingly. Each group of functions becomes a separate Module.
249 ReduceMiscompilingFunctions::TestFuncs(const std::vector
<Function
*> &Funcs
) {
250 // Test to see if the function is misoptimized if we ONLY run it on the
251 // functions listed in Funcs.
252 outs() << "Checking to see if the program is misoptimized when "
253 << (Funcs
.size() == 1 ? "this function is" : "these functions are")
254 << " run through the pass"
255 << (BD
.getPassesToRun().size() == 1 ? "" : "es") << ":";
256 PrintFunctionList(Funcs
);
259 // Create a clone for two reasons:
260 // * If the optimization passes delete any function, the deleted function
261 // will be in the clone and Funcs will still point to valid memory
262 // * If the optimization passes use interprocedural information to break
263 // a function, we want to continue with the original function. Otherwise
264 // we can conclude that a function triggers the bug when in fact one
265 // needs a larger set of original functions to do so.
266 ValueToValueMapTy VMap
;
267 std::unique_ptr
<Module
> Clone
= CloneModule(BD
.getProgram(), VMap
);
268 std::unique_ptr
<Module
> Orig
= BD
.swapProgramIn(std::move(Clone
));
270 std::vector
<Function
*> FuncsOnClone
;
271 for (unsigned i
= 0, e
= Funcs
.size(); i
!= e
; ++i
) {
272 Function
*F
= cast
<Function
>(VMap
[Funcs
[i
]]);
273 FuncsOnClone
.push_back(F
);
276 // Split the module into the two halves of the program we want.
278 std::unique_ptr
<Module
> ToNotOptimize
= CloneModule(BD
.getProgram(), VMap
);
279 std::unique_ptr
<Module
> ToOptimize
=
280 SplitFunctionsOutOfModule(ToNotOptimize
.get(), FuncsOnClone
, VMap
);
282 Expected
<bool> Broken
=
283 TestFn(BD
, std::move(ToOptimize
), std::move(ToNotOptimize
));
285 BD
.setNewProgram(std::move(Orig
));
290 /// Give anonymous global values names.
291 static void DisambiguateGlobalSymbols(Module
&M
) {
292 for (Module::global_iterator I
= M
.global_begin(), E
= M
.global_end(); I
!= E
;
295 I
->setName("anon_global");
296 for (Module::iterator I
= M
.begin(), E
= M
.end(); I
!= E
; ++I
)
298 I
->setName("anon_fn");
301 /// Given a reduced list of functions that still exposed the bug, check to see
302 /// if we can extract the loops in the region without obscuring the bug. If so,
303 /// it reduces the amount of code identified.
305 static Expected
<bool>
306 ExtractLoops(BugDriver
&BD
,
307 Expected
<bool> (*TestFn
)(BugDriver
&, std::unique_ptr
<Module
>,
308 std::unique_ptr
<Module
>),
309 std::vector
<Function
*> &MiscompiledFunctions
) {
310 bool MadeChange
= false;
312 if (BugpointIsInterrupted
)
315 ValueToValueMapTy VMap
;
316 std::unique_ptr
<Module
> ToNotOptimize
= CloneModule(BD
.getProgram(), VMap
);
317 std::unique_ptr
<Module
> ToOptimize
= SplitFunctionsOutOfModule(
318 ToNotOptimize
.get(), MiscompiledFunctions
, VMap
);
319 std::unique_ptr
<Module
> ToOptimizeLoopExtracted
=
320 BD
.extractLoop(ToOptimize
.get());
321 if (!ToOptimizeLoopExtracted
)
322 // If the loop extractor crashed or if there were no extractible loops,
323 // then this chapter of our odyssey is over with.
326 errs() << "Extracted a loop from the breaking portion of the program.\n";
328 // Bugpoint is intentionally not very trusting of LLVM transformations. In
329 // particular, we're not going to assume that the loop extractor works, so
330 // we're going to test the newly loop extracted program to make sure nothing
331 // has broken. If something broke, then we'll inform the user and stop
333 AbstractInterpreter
*AI
= BD
.switchToSafeInterpreter();
335 Expected
<std::unique_ptr
<Module
>> New
= testMergedProgram(
336 BD
, *ToOptimizeLoopExtracted
, *ToNotOptimize
, Failure
);
337 if (Error E
= New
.takeError())
342 // Delete the original and set the new program.
343 std::unique_ptr
<Module
> Old
= BD
.swapProgramIn(std::move(*New
));
344 for (unsigned i
= 0, e
= MiscompiledFunctions
.size(); i
!= e
; ++i
)
345 MiscompiledFunctions
[i
] = cast
<Function
>(VMap
[MiscompiledFunctions
[i
]]);
348 BD
.switchToInterpreter(AI
);
350 // Merged program doesn't work anymore!
351 errs() << " *** ERROR: Loop extraction broke the program. :("
352 << " Please report a bug!\n";
353 errs() << " Continuing on with un-loop-extracted version.\n";
355 BD
.writeProgramToFile(OutputPrefix
+ "-loop-extract-fail-tno.bc",
357 BD
.writeProgramToFile(OutputPrefix
+ "-loop-extract-fail-to.bc",
359 BD
.writeProgramToFile(OutputPrefix
+ "-loop-extract-fail-to-le.bc",
360 *ToOptimizeLoopExtracted
);
362 errs() << "Please submit the " << OutputPrefix
363 << "-loop-extract-fail-*.bc files.\n";
366 BD
.switchToInterpreter(AI
);
368 outs() << " Testing after loop extraction:\n";
369 // Clone modules, the tester function will free them.
370 std::unique_ptr
<Module
> TOLEBackup
=
371 CloneModule(*ToOptimizeLoopExtracted
, VMap
);
372 std::unique_ptr
<Module
> TNOBackup
= CloneModule(*ToNotOptimize
, VMap
);
374 for (unsigned i
= 0, e
= MiscompiledFunctions
.size(); i
!= e
; ++i
)
375 MiscompiledFunctions
[i
] = cast
<Function
>(VMap
[MiscompiledFunctions
[i
]]);
377 Expected
<bool> Result
= TestFn(BD
, std::move(ToOptimizeLoopExtracted
),
378 std::move(ToNotOptimize
));
379 if (Error E
= Result
.takeError())
382 ToOptimizeLoopExtracted
= std::move(TOLEBackup
);
383 ToNotOptimize
= std::move(TNOBackup
);
386 outs() << "*** Loop extraction masked the problem. Undoing.\n";
387 // If the program is not still broken, then loop extraction did something
388 // that masked the error. Stop loop extraction now.
390 std::vector
<std::pair
<std::string
, FunctionType
*>> MisCompFunctions
;
391 for (Function
*F
: MiscompiledFunctions
) {
392 MisCompFunctions
.emplace_back(F
->getName(), F
->getFunctionType());
395 if (Linker::linkModules(*ToNotOptimize
,
396 std::move(ToOptimizeLoopExtracted
)))
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 BD
.setNewProgram(std::move(ToNotOptimize
));
411 outs() << "*** Loop extraction successful!\n";
413 std::vector
<std::pair
<std::string
, FunctionType
*>> MisCompFunctions
;
414 for (Module::iterator I
= ToOptimizeLoopExtracted
->begin(),
415 E
= ToOptimizeLoopExtracted
->end();
417 if (!I
->isDeclaration())
418 MisCompFunctions
.emplace_back(I
->getName(), I
->getFunctionType());
420 // Okay, great! Now we know that we extracted a loop and that loop
421 // extraction both didn't break the program, and didn't mask the problem.
422 // Replace the current program with the loop extracted version, and try to
423 // extract another loop.
424 if (Linker::linkModules(*ToNotOptimize
, std::move(ToOptimizeLoopExtracted
)))
427 // All of the Function*'s in the MiscompiledFunctions list are in the old
428 // module. Update this list to include all of the functions in the
429 // optimized and loop extracted module.
430 MiscompiledFunctions
.clear();
431 for (unsigned i
= 0, e
= MisCompFunctions
.size(); i
!= e
; ++i
) {
432 Function
*NewF
= ToNotOptimize
->getFunction(MisCompFunctions
[i
].first
);
434 assert(NewF
&& "Function not found??");
435 MiscompiledFunctions
.push_back(NewF
);
438 BD
.setNewProgram(std::move(ToNotOptimize
));
444 class ReduceMiscompiledBlocks
: public ListReducer
<BasicBlock
*> {
446 Expected
<bool> (*TestFn
)(BugDriver
&, std::unique_ptr
<Module
>,
447 std::unique_ptr
<Module
>);
448 std::vector
<Function
*> FunctionsBeingTested
;
451 ReduceMiscompiledBlocks(BugDriver
&bd
,
452 Expected
<bool> (*F
)(BugDriver
&,
453 std::unique_ptr
<Module
>,
454 std::unique_ptr
<Module
>),
455 const std::vector
<Function
*> &Fns
)
456 : BD(bd
), TestFn(F
), FunctionsBeingTested(Fns
) {}
458 Expected
<TestResult
> doTest(std::vector
<BasicBlock
*> &Prefix
,
459 std::vector
<BasicBlock
*> &Suffix
) override
{
460 if (!Suffix
.empty()) {
461 Expected
<bool> Ret
= TestFuncs(Suffix
);
462 if (Error E
= Ret
.takeError())
467 if (!Prefix
.empty()) {
468 Expected
<bool> Ret
= TestFuncs(Prefix
);
469 if (Error E
= Ret
.takeError())
477 Expected
<bool> TestFuncs(const std::vector
<BasicBlock
*> &BBs
);
479 } // end anonymous namespace
481 /// TestFuncs - Extract all blocks for the miscompiled functions except for the
482 /// specified blocks. If the problem still exists, return true.
485 ReduceMiscompiledBlocks::TestFuncs(const std::vector
<BasicBlock
*> &BBs
) {
486 // Test to see if the function is misoptimized if we ONLY run it on the
487 // functions listed in Funcs.
488 outs() << "Checking to see if the program is misoptimized when all ";
490 outs() << "but these " << BBs
.size() << " blocks are extracted: ";
491 for (unsigned i
= 0, e
= BBs
.size() < 10 ? BBs
.size() : 10; i
!= e
; ++i
)
492 outs() << BBs
[i
]->getName() << " ";
496 outs() << "blocks are extracted.";
500 // Split the module into the two halves of the program we want.
501 ValueToValueMapTy VMap
;
502 std::unique_ptr
<Module
> Clone
= CloneModule(BD
.getProgram(), VMap
);
503 std::unique_ptr
<Module
> Orig
= BD
.swapProgramIn(std::move(Clone
));
504 std::vector
<Function
*> FuncsOnClone
;
505 std::vector
<BasicBlock
*> BBsOnClone
;
506 for (unsigned i
= 0, e
= FunctionsBeingTested
.size(); i
!= e
; ++i
) {
507 Function
*F
= cast
<Function
>(VMap
[FunctionsBeingTested
[i
]]);
508 FuncsOnClone
.push_back(F
);
510 for (unsigned i
= 0, e
= BBs
.size(); i
!= e
; ++i
) {
511 BasicBlock
*BB
= cast
<BasicBlock
>(VMap
[BBs
[i
]]);
512 BBsOnClone
.push_back(BB
);
516 std::unique_ptr
<Module
> ToNotOptimize
= CloneModule(BD
.getProgram(), VMap
);
517 std::unique_ptr
<Module
> ToOptimize
=
518 SplitFunctionsOutOfModule(ToNotOptimize
.get(), FuncsOnClone
, VMap
);
520 // Try the extraction. If it doesn't work, then the block extractor crashed
521 // or something, in which case bugpoint can't chase down this possibility.
522 if (std::unique_ptr
<Module
> New
=
523 BD
.extractMappedBlocksFromModule(BBsOnClone
, ToOptimize
.get())) {
524 Expected
<bool> Ret
= TestFn(BD
, std::move(New
), std::move(ToNotOptimize
));
525 BD
.setNewProgram(std::move(Orig
));
528 BD
.setNewProgram(std::move(Orig
));
532 /// Given a reduced list of functions that still expose the bug, extract as many
533 /// basic blocks from the region as possible without obscuring the bug.
535 static Expected
<bool>
536 ExtractBlocks(BugDriver
&BD
,
537 Expected
<bool> (*TestFn
)(BugDriver
&, std::unique_ptr
<Module
>,
538 std::unique_ptr
<Module
>),
539 std::vector
<Function
*> &MiscompiledFunctions
) {
540 if (BugpointIsInterrupted
)
543 std::vector
<BasicBlock
*> Blocks
;
544 for (unsigned i
= 0, e
= MiscompiledFunctions
.size(); i
!= e
; ++i
)
545 for (BasicBlock
&BB
: *MiscompiledFunctions
[i
])
546 Blocks
.push_back(&BB
);
548 // Use the list reducer to identify blocks that can be extracted without
549 // obscuring the bug. The Blocks list will end up containing blocks that must
550 // be retained from the original program.
551 unsigned OldSize
= Blocks
.size();
553 // Check to see if all blocks are extractible first.
554 Expected
<bool> Ret
= ReduceMiscompiledBlocks(BD
, TestFn
, MiscompiledFunctions
)
555 .TestFuncs(std::vector
<BasicBlock
*>());
556 if (Error E
= Ret
.takeError())
562 ReduceMiscompiledBlocks(BD
, TestFn
, MiscompiledFunctions
)
564 if (Error E
= Ret
.takeError())
566 if (Blocks
.size() == OldSize
)
570 ValueToValueMapTy VMap
;
571 std::unique_ptr
<Module
> ProgClone
= CloneModule(BD
.getProgram(), VMap
);
572 std::unique_ptr
<Module
> ToExtract
=
573 SplitFunctionsOutOfModule(ProgClone
.get(), MiscompiledFunctions
, VMap
);
574 std::unique_ptr
<Module
> Extracted
=
575 BD
.extractMappedBlocksFromModule(Blocks
, ToExtract
.get());
577 // Weird, extraction should have worked.
578 errs() << "Nondeterministic problem extracting blocks??\n";
582 // Otherwise, block extraction succeeded. Link the two program fragments back
585 std::vector
<std::pair
<std::string
, FunctionType
*>> MisCompFunctions
;
586 for (Module::iterator I
= Extracted
->begin(), E
= Extracted
->end(); I
!= E
;
588 if (!I
->isDeclaration())
589 MisCompFunctions
.emplace_back(I
->getName(), I
->getFunctionType());
591 if (Linker::linkModules(*ProgClone
, std::move(Extracted
)))
594 // Update the list of miscompiled functions.
595 MiscompiledFunctions
.clear();
597 for (unsigned i
= 0, e
= MisCompFunctions
.size(); i
!= e
; ++i
) {
598 Function
*NewF
= ProgClone
->getFunction(MisCompFunctions
[i
].first
);
599 assert(NewF
&& "Function not found??");
600 MiscompiledFunctions
.push_back(NewF
);
603 // Set the new program and delete the old one.
604 BD
.setNewProgram(std::move(ProgClone
));
609 /// This is a generic driver to narrow down miscompilations, either in an
610 /// optimization or a code generator.
612 static Expected
<std::vector
<Function
*>> DebugAMiscompilation(
614 Expected
<bool> (*TestFn
)(BugDriver
&, std::unique_ptr
<Module
>,
615 std::unique_ptr
<Module
>)) {
616 // Okay, now that we have reduced the list of passes which are causing the
617 // failure, see if we can pin down which functions are being
618 // miscompiled... first build a list of all of the non-external functions in
620 std::vector
<Function
*> MiscompiledFunctions
;
621 Module
&Prog
= BD
.getProgram();
622 for (Function
&F
: Prog
)
623 if (!F
.isDeclaration())
624 MiscompiledFunctions
.push_back(&F
);
626 // Do the reduction...
627 if (!BugpointIsInterrupted
) {
628 Expected
<bool> Ret
= ReduceMiscompilingFunctions(BD
, TestFn
)
629 .reduceList(MiscompiledFunctions
);
630 if (Error E
= Ret
.takeError()) {
631 errs() << "\n***Cannot reduce functions: ";
635 outs() << "\n*** The following function"
636 << (MiscompiledFunctions
.size() == 1 ? " is" : "s are")
637 << " being miscompiled: ";
638 PrintFunctionList(MiscompiledFunctions
);
641 // See if we can rip any loops out of the miscompiled functions and still
642 // trigger the problem.
644 if (!BugpointIsInterrupted
&& !DisableLoopExtraction
) {
645 Expected
<bool> Ret
= ExtractLoops(BD
, TestFn
, MiscompiledFunctions
);
646 if (Error E
= Ret
.takeError())
649 // Okay, we extracted some loops and the problem still appears. See if
650 // we can eliminate some of the created functions from being candidates.
651 DisambiguateGlobalSymbols(BD
.getProgram());
653 // Do the reduction...
654 if (!BugpointIsInterrupted
)
655 Ret
= ReduceMiscompilingFunctions(BD
, TestFn
)
656 .reduceList(MiscompiledFunctions
);
657 if (Error E
= Ret
.takeError())
660 outs() << "\n*** The following function"
661 << (MiscompiledFunctions
.size() == 1 ? " is" : "s are")
662 << " being miscompiled: ";
663 PrintFunctionList(MiscompiledFunctions
);
668 if (!BugpointIsInterrupted
&& !DisableBlockExtraction
) {
669 Expected
<bool> Ret
= ExtractBlocks(BD
, TestFn
, MiscompiledFunctions
);
670 if (Error E
= Ret
.takeError())
673 // Okay, we extracted some blocks and the problem still appears. See if
674 // we can eliminate some of the created functions from being candidates.
675 DisambiguateGlobalSymbols(BD
.getProgram());
677 // Do the reduction...
678 Ret
= ReduceMiscompilingFunctions(BD
, TestFn
)
679 .reduceList(MiscompiledFunctions
);
680 if (Error E
= Ret
.takeError())
683 outs() << "\n*** The following function"
684 << (MiscompiledFunctions
.size() == 1 ? " is" : "s are")
685 << " being miscompiled: ";
686 PrintFunctionList(MiscompiledFunctions
);
691 return MiscompiledFunctions
;
694 /// This is the predicate function used to check to see if the "Test" portion of
695 /// the program is misoptimized. If so, return true. In any case, both module
696 /// arguments are deleted.
698 static Expected
<bool> TestOptimizer(BugDriver
&BD
, std::unique_ptr
<Module
> Test
,
699 std::unique_ptr
<Module
> Safe
) {
700 // Run the optimization passes on ToOptimize, producing a transformed version
701 // of the functions being tested.
702 outs() << " Optimizing functions being tested: ";
703 std::unique_ptr
<Module
> Optimized
=
704 BD
.runPassesOn(Test
.get(), BD
.getPassesToRun());
706 errs() << " Error running this sequence of passes"
707 << " on the input program!\n";
708 BD
.EmitProgressBitcode(*Test
, "pass-error", false);
709 BD
.setNewProgram(std::move(Test
));
710 if (Error E
= BD
.debugOptimizerCrash())
716 outs() << " Checking to see if the merged program executes correctly: ";
718 auto Result
= testMergedProgram(BD
, *Optimized
, *Safe
, Broken
);
719 if (Error E
= Result
.takeError())
721 if (auto New
= std::move(*Result
)) {
722 outs() << (Broken
? " nope.\n" : " yup.\n");
723 // Delete the original and set the new program.
724 BD
.setNewProgram(std::move(New
));
729 /// debugMiscompilation - This method is used when the passes selected are not
730 /// crashing, but the generated output is semantically different from the
733 Error
BugDriver::debugMiscompilation() {
734 // Make sure something was miscompiled...
735 if (!BugpointIsInterrupted
) {
736 Expected
<bool> Result
=
737 ReduceMiscompilingPasses(*this).reduceList(PassesToRun
);
738 if (Error E
= Result
.takeError())
741 return make_error
<StringError
>(
742 "*** Optimized program matches reference output! No problem"
743 " detected...\nbugpoint can't help you with your problem!\n",
744 inconvertibleErrorCode());
747 outs() << "\n*** Found miscompiling pass"
748 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
749 << getPassesString(getPassesToRun()) << '\n';
750 EmitProgressBitcode(*Program
, "passinput");
752 Expected
<std::vector
<Function
*>> MiscompiledFunctions
=
753 DebugAMiscompilation(*this, TestOptimizer
);
754 if (Error E
= MiscompiledFunctions
.takeError())
757 // Output a bunch of bitcode files for the user...
758 outs() << "Outputting reduced bitcode files which expose the problem:\n";
759 ValueToValueMapTy VMap
;
760 Module
*ToNotOptimize
= CloneModule(getProgram(), VMap
).release();
762 SplitFunctionsOutOfModule(ToNotOptimize
, *MiscompiledFunctions
, VMap
)
765 outs() << " Non-optimized portion: ";
766 EmitProgressBitcode(*ToNotOptimize
, "tonotoptimize", true);
767 delete ToNotOptimize
; // Delete hacked module.
769 outs() << " Portion that is input to optimizer: ";
770 EmitProgressBitcode(*ToOptimize
, "tooptimize");
771 delete ToOptimize
; // Delete hacked module.
773 return Error::success();
776 /// Get the specified modules ready for code generator testing.
778 static std::unique_ptr
<Module
>
779 CleanupAndPrepareModules(BugDriver
&BD
, std::unique_ptr
<Module
> Test
,
781 // Clean up the modules, removing extra cruft that we don't need anymore...
782 Test
= BD
.performFinalCleanups(std::move(Test
));
784 // If we are executing the JIT, we have several nasty issues to take care of.
785 if (!BD
.isExecutingJIT())
788 // First, if the main function is in the Safe module, we must add a stub to
789 // the Test module to call into it. Thus, we create a new function `main'
790 // which just calls the old one.
791 if (Function
*oldMain
= Safe
->getFunction("main"))
792 if (!oldMain
->isDeclaration()) {
794 oldMain
->setName("llvm_bugpoint_old_main");
795 // Create a NEW `main' function with same type in the test module.
797 Function::Create(oldMain
->getFunctionType(),
798 GlobalValue::ExternalLinkage
, "main", Test
.get());
799 // Create an `oldmain' prototype in the test module, which will
800 // corresponds to the real main function in the same module.
801 Function
*oldMainProto
= Function::Create(oldMain
->getFunctionType(),
802 GlobalValue::ExternalLinkage
,
803 oldMain
->getName(), Test
.get());
804 // Set up and remember the argument list for the main function.
805 std::vector
<Value
*> args
;
806 for (Function::arg_iterator I
= newMain
->arg_begin(),
807 E
= newMain
->arg_end(),
808 OI
= oldMain
->arg_begin();
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 FunctionCallee resolverFunc
= Safe
->getOrInsertFunction(
830 "getPointerToNamedFunction", Type::getInt8PtrTy(Safe
->getContext()),
831 Type::getInt8PtrTy(Safe
->getContext()));
833 // Use the function we just added to get addresses of functions we need.
834 for (Module::iterator F
= Safe
->begin(), E
= Safe
->end(); F
!= E
; ++F
) {
835 if (F
->isDeclaration() && !F
->use_empty() &&
836 &*F
!= resolverFunc
.getCallee() &&
837 !F
->isIntrinsic() /* ignore intrinsics */) {
838 Function
*TestFn
= Test
->getFunction(F
->getName());
840 // Don't forward functions which are external in the test module too.
841 if (TestFn
&& !TestFn
->isDeclaration()) {
842 // 1. Add a string constant with its name to the global file
843 Constant
*InitArray
=
844 ConstantDataArray::getString(F
->getContext(), F
->getName());
845 GlobalVariable
*funcName
= new GlobalVariable(
846 *Safe
, InitArray
->getType(), true /*isConstant*/,
847 GlobalValue::InternalLinkage
, InitArray
, F
->getName() + "_name");
849 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
850 // sbyte* so it matches the signature of the resolver function.
852 // GetElementPtr *funcName, ulong 0, ulong 0
853 std::vector
<Constant
*> GEPargs(
854 2, Constant::getNullValue(Type::getInt32Ty(F
->getContext())));
855 Value
*GEP
= ConstantExpr::getGetElementPtr(InitArray
->getType(),
857 std::vector
<Value
*> ResolverArgs
;
858 ResolverArgs
.push_back(GEP
);
860 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
861 // function that dynamically resolves the calls to F via our JIT API
862 if (!F
->use_empty()) {
863 // Create a new global to hold the cached function pointer.
864 Constant
*NullPtr
= ConstantPointerNull::get(F
->getType());
865 GlobalVariable
*Cache
= new GlobalVariable(
866 *F
->getParent(), F
->getType(), false,
867 GlobalValue::InternalLinkage
, NullPtr
, F
->getName() + ".fpcache");
869 // Construct a new stub function that will re-route calls to F
870 FunctionType
*FuncTy
= F
->getFunctionType();
871 Function
*FuncWrapper
=
872 Function::Create(FuncTy
, GlobalValue::InternalLinkage
,
873 F
->getName() + "_wrapper", F
->getParent());
874 BasicBlock
*EntryBB
=
875 BasicBlock::Create(F
->getContext(), "entry", FuncWrapper
);
876 BasicBlock
*DoCallBB
=
877 BasicBlock::Create(F
->getContext(), "usecache", FuncWrapper
);
878 BasicBlock
*LookupBB
=
879 BasicBlock::Create(F
->getContext(), "lookupfp", FuncWrapper
);
881 // Check to see if we already looked up the value.
883 new LoadInst(F
->getType(), Cache
, "fpcache", EntryBB
);
884 Value
*IsNull
= new ICmpInst(*EntryBB
, ICmpInst::ICMP_EQ
, CachedVal
,
886 BranchInst::Create(LookupBB
, DoCallBB
, IsNull
, EntryBB
);
888 // Resolve the call to function F via the JIT API:
890 // call resolver(GetElementPtr...)
891 CallInst
*Resolver
= CallInst::Create(resolverFunc
, ResolverArgs
,
892 "resolver", LookupBB
);
894 // Cast the result from the resolver to correctly-typed function.
895 CastInst
*CastedResolver
= new BitCastInst(
896 Resolver
, PointerType::getUnqual(F
->getFunctionType()),
897 "resolverCast", LookupBB
);
899 // Save the value in our cache.
900 new StoreInst(CastedResolver
, Cache
, LookupBB
);
901 BranchInst::Create(DoCallBB
, LookupBB
);
904 PHINode::Create(NullPtr
->getType(), 2, "fp", DoCallBB
);
905 FuncPtr
->addIncoming(CastedResolver
, LookupBB
);
906 FuncPtr
->addIncoming(CachedVal
, EntryBB
);
908 // Save the argument list.
909 std::vector
<Value
*> Args
;
910 for (Argument
&A
: FuncWrapper
->args())
913 // Pass on the arguments to the real function, return its result
914 if (F
->getReturnType()->isVoidTy()) {
915 CallInst::Create(FuncTy
, FuncPtr
, Args
, "", DoCallBB
);
916 ReturnInst::Create(F
->getContext(), DoCallBB
);
919 CallInst::Create(FuncTy
, FuncPtr
, Args
, "retval", DoCallBB
);
920 ReturnInst::Create(F
->getContext(), Call
, DoCallBB
);
923 // Use the wrapper function instead of the old function
924 F
->replaceAllUsesWith(FuncWrapper
);
930 if (verifyModule(*Test
) || verifyModule(*Safe
)) {
931 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
938 /// This is the predicate function used to check to see if the "Test" portion of
939 /// the program is miscompiled by the code generator under test. If so, return
940 /// true. In any case, both module arguments are deleted.
942 static Expected
<bool> TestCodeGenerator(BugDriver
&BD
,
943 std::unique_ptr
<Module
> Test
,
944 std::unique_ptr
<Module
> Safe
) {
945 Test
= CleanupAndPrepareModules(BD
, std::move(Test
), Safe
.get());
947 SmallString
<128> TestModuleBC
;
949 std::error_code EC
= sys::fs::createTemporaryFile("bugpoint.test", "bc",
950 TestModuleFD
, TestModuleBC
);
952 errs() << BD
.getToolName()
953 << "Error making unique filename: " << EC
.message() << "\n";
956 if (BD
.writeProgramToFile(TestModuleBC
.str(), TestModuleFD
, *Test
)) {
957 errs() << "Error writing bitcode to `" << TestModuleBC
.str()
962 FileRemover
TestModuleBCRemover(TestModuleBC
.str(), !SaveTemps
);
964 // Make the shared library
965 SmallString
<128> SafeModuleBC
;
967 EC
= sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD
,
970 errs() << BD
.getToolName()
971 << "Error making unique filename: " << EC
.message() << "\n";
975 if (BD
.writeProgramToFile(SafeModuleBC
.str(), SafeModuleFD
, *Safe
)) {
976 errs() << "Error writing bitcode to `" << SafeModuleBC
<< "'\nExiting.";
980 FileRemover
SafeModuleBCRemover(SafeModuleBC
.str(), !SaveTemps
);
982 Expected
<std::string
> SharedObject
=
983 BD
.compileSharedObject(SafeModuleBC
.str());
984 if (Error E
= SharedObject
.takeError())
987 FileRemover
SharedObjectRemover(*SharedObject
, !SaveTemps
);
989 // Run the code generator on the `Test' code, loading the shared library.
990 // The function returns whether or not the new output differs from reference.
991 Expected
<bool> Result
=
992 BD
.diffProgram(BD
.getProgram(), TestModuleBC
.str(), *SharedObject
, false);
993 if (Error E
= Result
.takeError())
997 errs() << ": still failing!\n";
999 errs() << ": didn't fail.\n";
1004 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
1006 Error
BugDriver::debugCodeGenerator() {
1007 if ((void *)SafeInterpreter
== (void *)Interpreter
) {
1008 Expected
<std::string
> Result
=
1009 executeProgramSafely(*Program
, "bugpoint.safe.out");
1011 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
1012 << "the reference diff. This may be due to a\n front-end "
1013 << "bug or a bug in the original program, but this can also "
1014 << "happen if bugpoint isn't running the program with the "
1015 << "right flags or input.\n I left the result of executing "
1016 << "the program with the \"safe\" backend in this file for "
1017 << "you: '" << *Result
<< "'.\n";
1019 return Error::success();
1022 DisambiguateGlobalSymbols(*Program
);
1024 Expected
<std::vector
<Function
*>> Funcs
=
1025 DebugAMiscompilation(*this, TestCodeGenerator
);
1026 if (Error E
= Funcs
.takeError())
1029 // Split the module into the two halves of the program we want.
1030 ValueToValueMapTy VMap
;
1031 std::unique_ptr
<Module
> ToNotCodeGen
= CloneModule(getProgram(), VMap
);
1032 std::unique_ptr
<Module
> ToCodeGen
=
1033 SplitFunctionsOutOfModule(ToNotCodeGen
.get(), *Funcs
, VMap
);
1035 // Condition the modules
1037 CleanupAndPrepareModules(*this, std::move(ToCodeGen
), ToNotCodeGen
.get());
1039 SmallString
<128> TestModuleBC
;
1041 std::error_code EC
= sys::fs::createTemporaryFile("bugpoint.test", "bc",
1042 TestModuleFD
, TestModuleBC
);
1044 errs() << getToolName() << "Error making unique filename: " << EC
.message()
1049 if (writeProgramToFile(TestModuleBC
.str(), TestModuleFD
, *ToCodeGen
)) {
1050 errs() << "Error writing bitcode to `" << TestModuleBC
<< "'\nExiting.";
1054 // Make the shared library
1055 SmallString
<128> SafeModuleBC
;
1057 EC
= sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD
,
1060 errs() << getToolName() << "Error making unique filename: " << EC
.message()
1065 if (writeProgramToFile(SafeModuleBC
.str(), SafeModuleFD
, *ToNotCodeGen
)) {
1066 errs() << "Error writing bitcode to `" << SafeModuleBC
<< "'\nExiting.";
1069 Expected
<std::string
> SharedObject
= compileSharedObject(SafeModuleBC
.str());
1070 if (Error E
= SharedObject
.takeError())
1073 outs() << "You can reproduce the problem with the command line: \n";
1074 if (isExecutingJIT()) {
1075 outs() << " lli -load " << *SharedObject
<< " " << TestModuleBC
;
1077 outs() << " llc " << TestModuleBC
<< " -o " << TestModuleBC
<< ".s\n";
1078 outs() << " cc " << *SharedObject
<< " " << TestModuleBC
.str() << ".s -o "
1079 << TestModuleBC
<< ".exe\n";
1080 outs() << " ./" << TestModuleBC
<< ".exe";
1082 for (unsigned i
= 0, e
= InputArgv
.size(); i
!= e
; ++i
)
1083 outs() << " " << InputArgv
[i
];
1085 outs() << "The shared object was created with:\n llc -march=c "
1086 << SafeModuleBC
.str() << " -o temporary.c\n"
1087 << " cc -xc temporary.c -O2 -o " << *SharedObject
;
1088 if (TargetTriple
.getArch() == Triple::sparc
)
1089 outs() << " -G"; // Compile a shared library, `-G' for Sparc
1091 outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
1093 outs() << " -fno-strict-aliasing\n";
1095 return Error::success();