1 //===- Miscompilation.cpp - Debug program miscompilations -----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements optimizer and code generation miscompilation debugging
11 // support.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "BugDriver.h"
16 #include "ListReducer.h"
17 #include "ToolRunner.h"
18 #include "llvm/Config/config.h" // for HAVE_LINK_R
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/DerivedTypes.h"
21 #include "llvm/IR/Instructions.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/IR/Verifier.h"
24 #include "llvm/Linker/Linker.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/FileUtilities.h"
28 #include "llvm/Transforms/Utils/Cloning.h"
29
30 using namespace llvm;
31
32 namespace llvm {
33 extern cl::opt<std::string> OutputPrefix;
34 extern cl::list<std::string> InputArgv;
35 } // end namespace llvm
36
37 namespace {
38 static llvm::cl::opt<bool>
39 DisableLoopExtraction("disable-loop-extraction",
40 cl::desc("Don't extract loops when searching for miscompilations"),
41 cl::init(false));
42 static llvm::cl::opt<bool>
43 DisableBlockExtraction("disable-block-extraction",
44 cl::desc("Don't extract blocks when searching for miscompilations"),
45 cl::init(false));
46
47 class ReduceMiscompilingPasses : public ListReducer<std::string> {
48 BugDriver &BD;
49 public:
ReduceMiscompilingPasses(BugDriver & bd)50 ReduceMiscompilingPasses(BugDriver &bd) : BD(bd) {}
51
52 TestResult doTest(std::vector<std::string> &Prefix,
53 std::vector<std::string> &Suffix,
54 std::string &Error) override;
55 };
56 } // end anonymous namespace
57
58 /// TestResult - After passes have been split into a test group and a control
59 /// group, see if they still break the program.
60 ///
61 ReduceMiscompilingPasses::TestResult
doTest(std::vector<std::string> & Prefix,std::vector<std::string> & Suffix,std::string & Error)62 ReduceMiscompilingPasses::doTest(std::vector<std::string> &Prefix,
63 std::vector<std::string> &Suffix,
64 std::string &Error) {
65 // First, run the program with just the Suffix passes. If it is still broken
66 // with JUST the kept passes, discard the prefix passes.
67 outs() << "Checking to see if '" << getPassesString(Suffix)
68 << "' compiles correctly: ";
69
70 std::string BitcodeResult;
71 if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false/*delete*/,
72 true/*quiet*/)) {
73 errs() << " Error running this sequence of passes"
74 << " on the input program!\n";
75 BD.setPassesToRun(Suffix);
76 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
77 exit(BD.debugOptimizerCrash());
78 }
79
80 // Check to see if the finished program matches the reference output...
81 bool Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
82 true /*delete bitcode*/, &Error);
83 if (!Error.empty())
84 return InternalError;
85 if (Diff) {
86 outs() << " nope.\n";
87 if (Suffix.empty()) {
88 errs() << BD.getToolName() << ": I'm confused: the test fails when "
89 << "no passes are run, nondeterministic program?\n";
90 exit(1);
91 }
92 return KeepSuffix; // Miscompilation detected!
93 }
94 outs() << " yup.\n"; // No miscompilation!
95
96 if (Prefix.empty()) return NoFailure;
97
98 // Next, see if the program is broken if we run the "prefix" passes first,
99 // then separately run the "kept" passes.
100 outs() << "Checking to see if '" << getPassesString(Prefix)
101 << "' compiles correctly: ";
102
103 // If it is not broken with the kept passes, it's possible that the prefix
104 // passes must be run before the kept passes to break it. If the program
105 // WORKS after the prefix passes, but then fails if running the prefix AND
106 // kept passes, we can update our bitcode file to include the result of the
107 // prefix passes, then discard the prefix passes.
108 //
109 if (BD.runPasses(BD.getProgram(), Prefix, BitcodeResult, false/*delete*/,
110 true/*quiet*/)) {
111 errs() << " Error running this sequence of passes"
112 << " on the input program!\n";
113 BD.setPassesToRun(Prefix);
114 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
115 exit(BD.debugOptimizerCrash());
116 }
117
118 // If the prefix maintains the predicate by itself, only keep the prefix!
119 Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "", false, &Error);
120 if (!Error.empty())
121 return InternalError;
122 if (Diff) {
123 outs() << " nope.\n";
124 sys::fs::remove(BitcodeResult);
125 return KeepPrefix;
126 }
127 outs() << " yup.\n"; // No miscompilation!
128
129 // Ok, so now we know that the prefix passes work, try running the suffix
130 // passes on the result of the prefix passes.
131 //
132 std::unique_ptr<Module> PrefixOutput =
133 parseInputFile(BitcodeResult, BD.getContext());
134 if (!PrefixOutput) {
135 errs() << BD.getToolName() << ": Error reading bitcode file '"
136 << BitcodeResult << "'!\n";
137 exit(1);
138 }
139 sys::fs::remove(BitcodeResult);
140
141 // Don't check if there are no passes in the suffix.
142 if (Suffix.empty())
143 return NoFailure;
144
145 outs() << "Checking to see if '" << getPassesString(Suffix)
146 << "' passes compile correctly after the '"
147 << getPassesString(Prefix) << "' passes: ";
148
149 std::unique_ptr<Module> OriginalInput(
150 BD.swapProgramIn(PrefixOutput.release()));
151 if (BD.runPasses(BD.getProgram(), Suffix, BitcodeResult, false/*delete*/,
152 true/*quiet*/)) {
153 errs() << " Error running this sequence of passes"
154 << " on the input program!\n";
155 BD.setPassesToRun(Suffix);
156 BD.EmitProgressBitcode(BD.getProgram(), "pass-error", false);
157 exit(BD.debugOptimizerCrash());
158 }
159
160 // Run the result...
161 Diff = BD.diffProgram(BD.getProgram(), BitcodeResult, "",
162 true /*delete bitcode*/, &Error);
163 if (!Error.empty())
164 return InternalError;
165 if (Diff) {
166 outs() << " nope.\n";
167 return KeepSuffix;
168 }
169
170 // Otherwise, we must not be running the bad pass anymore.
171 outs() << " yup.\n"; // No miscompilation!
172 // Restore orig program & free test.
173 delete BD.swapProgramIn(OriginalInput.release());
174 return NoFailure;
175 }
176
177 namespace {
178 class ReduceMiscompilingFunctions : public ListReducer<Function*> {
179 BugDriver &BD;
180 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
181 std::unique_ptr<Module>, std::string &);
182
183 public:
ReduceMiscompilingFunctions(BugDriver & bd,bool (* F)(BugDriver &,std::unique_ptr<Module>,std::unique_ptr<Module>,std::string &))184 ReduceMiscompilingFunctions(BugDriver &bd,
185 bool (*F)(BugDriver &, std::unique_ptr<Module>,
186 std::unique_ptr<Module>,
187 std::string &))
188 : BD(bd), TestFn(F) {}
189
doTest(std::vector<Function * > & Prefix,std::vector<Function * > & Suffix,std::string & Error)190 TestResult doTest(std::vector<Function*> &Prefix,
191 std::vector<Function*> &Suffix,
192 std::string &Error) override {
193 if (!Suffix.empty()) {
194 bool Ret = TestFuncs(Suffix, Error);
195 if (!Error.empty())
196 return InternalError;
197 if (Ret)
198 return KeepSuffix;
199 }
200 if (!Prefix.empty()) {
201 bool Ret = TestFuncs(Prefix, Error);
202 if (!Error.empty())
203 return InternalError;
204 if (Ret)
205 return KeepPrefix;
206 }
207 return NoFailure;
208 }
209
210 bool TestFuncs(const std::vector<Function*> &Prefix, std::string &Error);
211 };
212 } // end anonymous namespace
213
214 /// Given two modules, link them together and run the program, checking to see
215 /// if the program matches the diff. If there is an error, return NULL. If not,
216 /// return the merged module. The Broken argument will be set to true if the
217 /// output is different. If the DeleteInputs argument is set to true then this
218 /// function deletes both input modules before it returns.
219 ///
testMergedProgram(const BugDriver & BD,std::unique_ptr<Module> M1,std::unique_ptr<Module> M2,std::string & Error,bool & Broken)220 static std::unique_ptr<Module> testMergedProgram(const BugDriver &BD,
221 std::unique_ptr<Module> M1,
222 std::unique_ptr<Module> M2,
223 std::string &Error,
224 bool &Broken) {
225 if (Linker::linkModules(*M1, std::move(M2)))
226 exit(1);
227
228 // Execute the program.
229 Broken = BD.diffProgram(M1.get(), "", "", false, &Error);
230 if (!Error.empty())
231 return nullptr;
232 return M1;
233 }
234
235 /// TestFuncs - split functions in a Module into two groups: those that are
236 /// under consideration for miscompilation vs. those that are not, and test
237 /// accordingly. Each group of functions becomes a separate Module.
238 ///
TestFuncs(const std::vector<Function * > & Funcs,std::string & Error)239 bool ReduceMiscompilingFunctions::TestFuncs(const std::vector<Function*> &Funcs,
240 std::string &Error) {
241 // Test to see if the function is misoptimized if we ONLY run it on the
242 // functions listed in Funcs.
243 outs() << "Checking to see if the program is misoptimized when "
244 << (Funcs.size()==1 ? "this function is" : "these functions are")
245 << " run through the pass"
246 << (BD.getPassesToRun().size() == 1 ? "" : "es") << ":";
247 PrintFunctionList(Funcs);
248 outs() << '\n';
249
250 // Create a clone for two reasons:
251 // * If the optimization passes delete any function, the deleted function
252 // will be in the clone and Funcs will still point to valid memory
253 // * If the optimization passes use interprocedural information to break
254 // a function, we want to continue with the original function. Otherwise
255 // we can conclude that a function triggers the bug when in fact one
256 // needs a larger set of original functions to do so.
257 ValueToValueMapTy VMap;
258 Module *Clone = CloneModule(BD.getProgram(), VMap).release();
259 Module *Orig = BD.swapProgramIn(Clone);
260
261 std::vector<Function*> FuncsOnClone;
262 for (unsigned i = 0, e = Funcs.size(); i != e; ++i) {
263 Function *F = cast<Function>(VMap[Funcs[i]]);
264 FuncsOnClone.push_back(F);
265 }
266
267 // Split the module into the two halves of the program we want.
268 VMap.clear();
269 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
270 std::unique_ptr<Module> ToOptimize =
271 SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
272
273 bool Broken =
274 TestFn(BD, std::move(ToOptimize), std::move(ToNotOptimize), Error);
275
276 delete BD.swapProgramIn(Orig);
277
278 return Broken;
279 }
280
281 /// DisambiguateGlobalSymbols - Give anonymous global values names.
282 ///
DisambiguateGlobalSymbols(Module * M)283 static void DisambiguateGlobalSymbols(Module *M) {
284 for (Module::global_iterator I = M->global_begin(), E = M->global_end();
285 I != E; ++I)
286 if (!I->hasName())
287 I->setName("anon_global");
288 for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
289 if (!I->hasName())
290 I->setName("anon_fn");
291 }
292
293 /// Given a reduced list of functions that still exposed the bug, check to see
294 /// if we can extract the loops in the region without obscuring the bug. If so,
295 /// it reduces the amount of code identified.
296 ///
ExtractLoops(BugDriver & BD,bool (* TestFn)(BugDriver &,std::unique_ptr<Module>,std::unique_ptr<Module>,std::string &),std::vector<Function * > & MiscompiledFunctions,std::string & Error)297 static bool ExtractLoops(BugDriver &BD,
298 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
299 std::unique_ptr<Module>, std::string &),
300 std::vector<Function *> &MiscompiledFunctions,
301 std::string &Error) {
302 bool MadeChange = false;
303 while (1) {
304 if (BugpointIsInterrupted) return MadeChange;
305
306 ValueToValueMapTy VMap;
307 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
308 Module *ToOptimize = SplitFunctionsOutOfModule(ToNotOptimize.get(),
309 MiscompiledFunctions, VMap)
310 .release();
311 std::unique_ptr<Module> ToOptimizeLoopExtracted =
312 BD.extractLoop(ToOptimize);
313 if (!ToOptimizeLoopExtracted) {
314 // If the loop extractor crashed or if there were no extractible loops,
315 // then this chapter of our odyssey is over with.
316 delete ToOptimize;
317 return MadeChange;
318 }
319
320 errs() << "Extracted a loop from the breaking portion of the program.\n";
321
322 // Bugpoint is intentionally not very trusting of LLVM transformations. In
323 // particular, we're not going to assume that the loop extractor works, so
324 // we're going to test the newly loop extracted program to make sure nothing
325 // has broken. If something broke, then we'll inform the user and stop
326 // extraction.
327 AbstractInterpreter *AI = BD.switchToSafeInterpreter();
328 bool Failure;
329 std::unique_ptr<Module> New =
330 testMergedProgram(BD, std::move(ToOptimizeLoopExtracted),
331 std::move(ToNotOptimize), Error, Failure);
332 if (!New)
333 return false;
334
335 // Delete the original and set the new program.
336 Module *Old = BD.swapProgramIn(New.release());
337 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
338 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
339 delete Old;
340
341 if (Failure) {
342 BD.switchToInterpreter(AI);
343
344 // Merged program doesn't work anymore!
345 errs() << " *** ERROR: Loop extraction broke the program. :("
346 << " Please report a bug!\n";
347 errs() << " Continuing on with un-loop-extracted version.\n";
348
349 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-tno.bc",
350 ToNotOptimize.get());
351 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to.bc",
352 ToOptimize);
353 BD.writeProgramToFile(OutputPrefix + "-loop-extract-fail-to-le.bc",
354 ToOptimizeLoopExtracted.get());
355
356 errs() << "Please submit the "
357 << OutputPrefix << "-loop-extract-fail-*.bc files.\n";
358 delete ToOptimize;
359 return MadeChange;
360 }
361 delete ToOptimize;
362 BD.switchToInterpreter(AI);
363
364 outs() << " Testing after loop extraction:\n";
365 // Clone modules, the tester function will free them.
366 std::unique_ptr<Module> TOLEBackup =
367 CloneModule(ToOptimizeLoopExtracted.get(), VMap);
368 std::unique_ptr<Module> TNOBackup = CloneModule(ToNotOptimize.get(), VMap);
369
370 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
371 MiscompiledFunctions[i] = cast<Function>(VMap[MiscompiledFunctions[i]]);
372
373 Failure = TestFn(BD, std::move(ToOptimizeLoopExtracted),
374 std::move(ToNotOptimize), Error);
375 if (!Error.empty())
376 return false;
377
378 ToOptimizeLoopExtracted = std::move(TOLEBackup);
379 ToNotOptimize = std::move(TNOBackup);
380
381 if (!Failure) {
382 outs() << "*** Loop extraction masked the problem. Undoing.\n";
383 // If the program is not still broken, then loop extraction did something
384 // that masked the error. Stop loop extraction now.
385
386 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
387 for (Function *F : MiscompiledFunctions) {
388 MisCompFunctions.emplace_back(F->getName(), F->getFunctionType());
389 }
390
391 if (Linker::linkModules(*ToNotOptimize,
392 std::move(ToOptimizeLoopExtracted)))
393 exit(1);
394
395 MiscompiledFunctions.clear();
396 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
397 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
398
399 assert(NewF && "Function not found??");
400 MiscompiledFunctions.push_back(NewF);
401 }
402
403 BD.setNewProgram(ToNotOptimize.release());
404 return MadeChange;
405 }
406
407 outs() << "*** Loop extraction successful!\n";
408
409 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
410 for (Module::iterator I = ToOptimizeLoopExtracted->begin(),
411 E = ToOptimizeLoopExtracted->end(); I != E; ++I)
412 if (!I->isDeclaration())
413 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
414
415 // Okay, great! Now we know that we extracted a loop and that loop
416 // extraction both didn't break the program, and didn't mask the problem.
417 // Replace the current program with the loop extracted version, and try to
418 // extract another loop.
419 if (Linker::linkModules(*ToNotOptimize, std::move(ToOptimizeLoopExtracted)))
420 exit(1);
421
422 // All of the Function*'s in the MiscompiledFunctions list are in the old
423 // module. Update this list to include all of the functions in the
424 // optimized and loop extracted module.
425 MiscompiledFunctions.clear();
426 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
427 Function *NewF = ToNotOptimize->getFunction(MisCompFunctions[i].first);
428
429 assert(NewF && "Function not found??");
430 MiscompiledFunctions.push_back(NewF);
431 }
432
433 BD.setNewProgram(ToNotOptimize.release());
434 MadeChange = true;
435 }
436 }
437
438 namespace {
439 class ReduceMiscompiledBlocks : public ListReducer<BasicBlock*> {
440 BugDriver &BD;
441 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
442 std::unique_ptr<Module>, std::string &);
443 std::vector<Function*> FunctionsBeingTested;
444 public:
ReduceMiscompiledBlocks(BugDriver & bd,bool (* F)(BugDriver &,std::unique_ptr<Module>,std::unique_ptr<Module>,std::string &),const std::vector<Function * > & Fns)445 ReduceMiscompiledBlocks(BugDriver &bd,
446 bool (*F)(BugDriver &, std::unique_ptr<Module>,
447 std::unique_ptr<Module>, std::string &),
448 const std::vector<Function *> &Fns)
449 : BD(bd), TestFn(F), FunctionsBeingTested(Fns) {}
450
doTest(std::vector<BasicBlock * > & Prefix,std::vector<BasicBlock * > & Suffix,std::string & Error)451 TestResult doTest(std::vector<BasicBlock*> &Prefix,
452 std::vector<BasicBlock*> &Suffix,
453 std::string &Error) override {
454 if (!Suffix.empty()) {
455 bool Ret = TestFuncs(Suffix, Error);
456 if (!Error.empty())
457 return InternalError;
458 if (Ret)
459 return KeepSuffix;
460 }
461 if (!Prefix.empty()) {
462 bool Ret = TestFuncs(Prefix, Error);
463 if (!Error.empty())
464 return InternalError;
465 if (Ret)
466 return KeepPrefix;
467 }
468 return NoFailure;
469 }
470
471 bool TestFuncs(const std::vector<BasicBlock*> &BBs, std::string &Error);
472 };
473 } // end anonymous namespace
474
475 /// TestFuncs - Extract all blocks for the miscompiled functions except for the
476 /// specified blocks. If the problem still exists, return true.
477 ///
TestFuncs(const std::vector<BasicBlock * > & BBs,std::string & Error)478 bool ReduceMiscompiledBlocks::TestFuncs(const std::vector<BasicBlock*> &BBs,
479 std::string &Error) {
480 // Test to see if the function is misoptimized if we ONLY run it on the
481 // functions listed in Funcs.
482 outs() << "Checking to see if the program is misoptimized when all ";
483 if (!BBs.empty()) {
484 outs() << "but these " << BBs.size() << " blocks are extracted: ";
485 for (unsigned i = 0, e = BBs.size() < 10 ? BBs.size() : 10; i != e; ++i)
486 outs() << BBs[i]->getName() << " ";
487 if (BBs.size() > 10) outs() << "...";
488 } else {
489 outs() << "blocks are extracted.";
490 }
491 outs() << '\n';
492
493 // Split the module into the two halves of the program we want.
494 ValueToValueMapTy VMap;
495 Module *Clone = CloneModule(BD.getProgram(), VMap).release();
496 Module *Orig = BD.swapProgramIn(Clone);
497 std::vector<Function*> FuncsOnClone;
498 std::vector<BasicBlock*> BBsOnClone;
499 for (unsigned i = 0, e = FunctionsBeingTested.size(); i != e; ++i) {
500 Function *F = cast<Function>(VMap[FunctionsBeingTested[i]]);
501 FuncsOnClone.push_back(F);
502 }
503 for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
504 BasicBlock *BB = cast<BasicBlock>(VMap[BBs[i]]);
505 BBsOnClone.push_back(BB);
506 }
507 VMap.clear();
508
509 std::unique_ptr<Module> ToNotOptimize = CloneModule(BD.getProgram(), VMap);
510 std::unique_ptr<Module> ToOptimize =
511 SplitFunctionsOutOfModule(ToNotOptimize.get(), FuncsOnClone, VMap);
512
513 // Try the extraction. If it doesn't work, then the block extractor crashed
514 // or something, in which case bugpoint can't chase down this possibility.
515 if (std::unique_ptr<Module> New =
516 BD.extractMappedBlocksFromModule(BBsOnClone, ToOptimize.get())) {
517 bool Ret = TestFn(BD, std::move(New), std::move(ToNotOptimize), Error);
518 delete BD.swapProgramIn(Orig);
519 return Ret;
520 }
521 delete BD.swapProgramIn(Orig);
522 return false;
523 }
524
525 /// Given a reduced list of functions that still expose the bug, extract as many
526 /// basic blocks from the region as possible without obscuring the bug.
527 ///
ExtractBlocks(BugDriver & BD,bool (* TestFn)(BugDriver &,std::unique_ptr<Module>,std::unique_ptr<Module>,std::string &),std::vector<Function * > & MiscompiledFunctions,std::string & Error)528 static bool ExtractBlocks(BugDriver &BD,
529 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
530 std::unique_ptr<Module>,
531 std::string &),
532 std::vector<Function *> &MiscompiledFunctions,
533 std::string &Error) {
534 if (BugpointIsInterrupted) return false;
535
536 std::vector<BasicBlock*> Blocks;
537 for (unsigned i = 0, e = MiscompiledFunctions.size(); i != e; ++i)
538 for (BasicBlock &BB : *MiscompiledFunctions[i])
539 Blocks.push_back(&BB);
540
541 // Use the list reducer to identify blocks that can be extracted without
542 // obscuring the bug. The Blocks list will end up containing blocks that must
543 // be retained from the original program.
544 unsigned OldSize = Blocks.size();
545
546 // Check to see if all blocks are extractible first.
547 bool Ret = ReduceMiscompiledBlocks(BD, TestFn, MiscompiledFunctions)
548 .TestFuncs(std::vector<BasicBlock*>(), Error);
549 if (!Error.empty())
550 return false;
551 if (Ret) {
552 Blocks.clear();
553 } else {
554 ReduceMiscompiledBlocks(BD, TestFn,
555 MiscompiledFunctions).reduceList(Blocks, Error);
556 if (!Error.empty())
557 return false;
558 if (Blocks.size() == OldSize)
559 return false;
560 }
561
562 ValueToValueMapTy VMap;
563 Module *ProgClone = CloneModule(BD.getProgram(), VMap).release();
564 Module *ToExtract =
565 SplitFunctionsOutOfModule(ProgClone, MiscompiledFunctions, VMap)
566 .release();
567 std::unique_ptr<Module> Extracted =
568 BD.extractMappedBlocksFromModule(Blocks, ToExtract);
569 if (!Extracted) {
570 // Weird, extraction should have worked.
571 errs() << "Nondeterministic problem extracting blocks??\n";
572 delete ProgClone;
573 delete ToExtract;
574 return false;
575 }
576
577 // Otherwise, block extraction succeeded. Link the two program fragments back
578 // together.
579 delete ToExtract;
580
581 std::vector<std::pair<std::string, FunctionType*> > MisCompFunctions;
582 for (Module::iterator I = Extracted->begin(), E = Extracted->end();
583 I != E; ++I)
584 if (!I->isDeclaration())
585 MisCompFunctions.emplace_back(I->getName(), I->getFunctionType());
586
587 if (Linker::linkModules(*ProgClone, std::move(Extracted)))
588 exit(1);
589
590 // Set the new program and delete the old one.
591 BD.setNewProgram(ProgClone);
592
593 // Update the list of miscompiled functions.
594 MiscompiledFunctions.clear();
595
596 for (unsigned i = 0, e = MisCompFunctions.size(); i != e; ++i) {
597 Function *NewF = ProgClone->getFunction(MisCompFunctions[i].first);
598 assert(NewF && "Function not found??");
599 MiscompiledFunctions.push_back(NewF);
600 }
601
602 return true;
603 }
604
605 /// This is a generic driver to narrow down miscompilations, either in an
606 /// optimization or a code generator.
607 ///
608 static std::vector<Function *>
DebugAMiscompilation(BugDriver & BD,bool (* TestFn)(BugDriver &,std::unique_ptr<Module>,std::unique_ptr<Module>,std::string &),std::string & Error)609 DebugAMiscompilation(BugDriver &BD,
610 bool (*TestFn)(BugDriver &, std::unique_ptr<Module>,
611 std::unique_ptr<Module>, std::string &),
612 std::string &Error) {
613 // Okay, now that we have reduced the list of passes which are causing the
614 // failure, see if we can pin down which functions are being
615 // miscompiled... first build a list of all of the non-external functions in
616 // the program.
617 std::vector<Function*> MiscompiledFunctions;
618 Module *Prog = BD.getProgram();
619 for (Function &F : *Prog)
620 if (!F.isDeclaration())
621 MiscompiledFunctions.push_back(&F);
622
623 // Do the reduction...
624 if (!BugpointIsInterrupted)
625 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
626 Error);
627 if (!Error.empty()) {
628 errs() << "\n***Cannot reduce functions: ";
629 return MiscompiledFunctions;
630 }
631 outs() << "\n*** The following function"
632 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
633 << " being miscompiled: ";
634 PrintFunctionList(MiscompiledFunctions);
635 outs() << '\n';
636
637 // See if we can rip any loops out of the miscompiled functions and still
638 // trigger the problem.
639
640 if (!BugpointIsInterrupted && !DisableLoopExtraction) {
641 bool Ret = ExtractLoops(BD, TestFn, MiscompiledFunctions, Error);
642 if (!Error.empty())
643 return MiscompiledFunctions;
644 if (Ret) {
645 // Okay, we extracted some loops and the problem still appears. See if
646 // we can eliminate some of the created functions from being candidates.
647 DisambiguateGlobalSymbols(BD.getProgram());
648
649 // Do the reduction...
650 if (!BugpointIsInterrupted)
651 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
652 Error);
653 if (!Error.empty())
654 return MiscompiledFunctions;
655
656 outs() << "\n*** The following function"
657 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
658 << " being miscompiled: ";
659 PrintFunctionList(MiscompiledFunctions);
660 outs() << '\n';
661 }
662 }
663
664 if (!BugpointIsInterrupted && !DisableBlockExtraction) {
665 bool Ret = ExtractBlocks(BD, TestFn, MiscompiledFunctions, Error);
666 if (!Error.empty())
667 return MiscompiledFunctions;
668 if (Ret) {
669 // Okay, we extracted some blocks and the problem still appears. See if
670 // we can eliminate some of the created functions from being candidates.
671 DisambiguateGlobalSymbols(BD.getProgram());
672
673 // Do the reduction...
674 ReduceMiscompilingFunctions(BD, TestFn).reduceList(MiscompiledFunctions,
675 Error);
676 if (!Error.empty())
677 return MiscompiledFunctions;
678
679 outs() << "\n*** The following function"
680 << (MiscompiledFunctions.size() == 1 ? " is" : "s are")
681 << " being miscompiled: ";
682 PrintFunctionList(MiscompiledFunctions);
683 outs() << '\n';
684 }
685 }
686
687 return MiscompiledFunctions;
688 }
689
690 /// This is the predicate function used to check to see if the "Test" portion of
691 /// the program is misoptimized. If so, return true. In any case, both module
692 /// arguments are deleted.
693 ///
TestOptimizer(BugDriver & BD,std::unique_ptr<Module> Test,std::unique_ptr<Module> Safe,std::string & Error)694 static bool TestOptimizer(BugDriver &BD, std::unique_ptr<Module> Test,
695 std::unique_ptr<Module> Safe, std::string &Error) {
696 // Run the optimization passes on ToOptimize, producing a transformed version
697 // of the functions being tested.
698 outs() << " Optimizing functions being tested: ";
699 std::unique_ptr<Module> Optimized =
700 BD.runPassesOn(Test.get(), BD.getPassesToRun());
701 if (!Optimized) {
702 errs() << " Error running this sequence of passes"
703 << " on the input program!\n";
704 delete BD.swapProgramIn(Test.get());
705 BD.EmitProgressBitcode(Test.get(), "pass-error", false);
706 return BD.debugOptimizerCrash();
707 }
708 outs() << "done.\n";
709
710 outs() << " Checking to see if the merged program executes correctly: ";
711 bool Broken;
712 std::unique_ptr<Module> New = testMergedProgram(
713 BD, std::move(Optimized), std::move(Safe), Error, Broken);
714 if (New) {
715 outs() << (Broken ? " nope.\n" : " yup.\n");
716 // Delete the original and set the new program.
717 delete BD.swapProgramIn(New.release());
718 }
719 return Broken;
720 }
721
722 /// debugMiscompilation - This method is used when the passes selected are not
723 /// crashing, but the generated output is semantically different from the
724 /// input.
725 ///
debugMiscompilation(std::string * Error)726 void BugDriver::debugMiscompilation(std::string *Error) {
727 // Make sure something was miscompiled...
728 if (!BugpointIsInterrupted)
729 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun, *Error)) {
730 if (Error->empty())
731 errs() << "*** Optimized program matches reference output! No problem"
732 << " detected...\nbugpoint can't help you with your problem!\n";
733 return;
734 }
735
736 outs() << "\n*** Found miscompiling pass"
737 << (getPassesToRun().size() == 1 ? "" : "es") << ": "
738 << getPassesString(getPassesToRun()) << '\n';
739 EmitProgressBitcode(Program, "passinput");
740
741 std::vector<Function *> MiscompiledFunctions =
742 DebugAMiscompilation(*this, TestOptimizer, *Error);
743 if (!Error->empty())
744 return;
745
746 // Output a bunch of bitcode files for the user...
747 outs() << "Outputting reduced bitcode files which expose the problem:\n";
748 ValueToValueMapTy VMap;
749 Module *ToNotOptimize = CloneModule(getProgram(), VMap).release();
750 Module *ToOptimize =
751 SplitFunctionsOutOfModule(ToNotOptimize, MiscompiledFunctions, VMap)
752 .release();
753
754 outs() << " Non-optimized portion: ";
755 EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true);
756 delete ToNotOptimize; // Delete hacked module.
757
758 outs() << " Portion that is input to optimizer: ";
759 EmitProgressBitcode(ToOptimize, "tooptimize");
760 delete ToOptimize; // Delete hacked module.
761 }
762
763 /// Get the specified modules ready for code generator testing.
764 ///
CleanupAndPrepareModules(BugDriver & BD,std::unique_ptr<Module> & Test,Module * Safe)765 static void CleanupAndPrepareModules(BugDriver &BD,
766 std::unique_ptr<Module> &Test,
767 Module *Safe) {
768 // Clean up the modules, removing extra cruft that we don't need anymore...
769 Test = BD.performFinalCleanups(Test.get());
770
771 // If we are executing the JIT, we have several nasty issues to take care of.
772 if (!BD.isExecutingJIT()) return;
773
774 // First, if the main function is in the Safe module, we must add a stub to
775 // the Test module to call into it. Thus, we create a new function `main'
776 // which just calls the old one.
777 if (Function *oldMain = Safe->getFunction("main"))
778 if (!oldMain->isDeclaration()) {
779 // Rename it
780 oldMain->setName("llvm_bugpoint_old_main");
781 // Create a NEW `main' function with same type in the test module.
782 Function *newMain =
783 Function::Create(oldMain->getFunctionType(),
784 GlobalValue::ExternalLinkage, "main", Test.get());
785 // Create an `oldmain' prototype in the test module, which will
786 // corresponds to the real main function in the same module.
787 Function *oldMainProto = Function::Create(oldMain->getFunctionType(),
788 GlobalValue::ExternalLinkage,
789 oldMain->getName(), Test.get());
790 // Set up and remember the argument list for the main function.
791 std::vector<Value*> args;
792 for (Function::arg_iterator
793 I = newMain->arg_begin(), E = newMain->arg_end(),
794 OI = oldMain->arg_begin(); I != E; ++I, ++OI) {
795 I->setName(OI->getName()); // Copy argument names from oldMain
796 args.push_back(&*I);
797 }
798
799 // Call the old main function and return its result
800 BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain);
801 CallInst *call = CallInst::Create(oldMainProto, args, "", BB);
802
803 // If the type of old function wasn't void, return value of call
804 ReturnInst::Create(Safe->getContext(), call, BB);
805 }
806
807 // The second nasty issue we must deal with in the JIT is that the Safe
808 // module cannot directly reference any functions defined in the test
809 // module. Instead, we use a JIT API call to dynamically resolve the
810 // symbol.
811
812 // Add the resolver to the Safe module.
813 // Prototype: void *getPointerToNamedFunction(const char* Name)
814 Constant *resolverFunc =
815 Safe->getOrInsertFunction("getPointerToNamedFunction",
816 Type::getInt8PtrTy(Safe->getContext()),
817 Type::getInt8PtrTy(Safe->getContext()),
818 (Type *)nullptr);
819
820 // Use the function we just added to get addresses of functions we need.
821 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) {
822 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc &&
823 !F->isIntrinsic() /* ignore intrinsics */) {
824 Function *TestFn = Test->getFunction(F->getName());
825
826 // Don't forward functions which are external in the test module too.
827 if (TestFn && !TestFn->isDeclaration()) {
828 // 1. Add a string constant with its name to the global file
829 Constant *InitArray =
830 ConstantDataArray::getString(F->getContext(), F->getName());
831 GlobalVariable *funcName =
832 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/,
833 GlobalValue::InternalLinkage, InitArray,
834 F->getName() + "_name");
835
836 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an
837 // sbyte* so it matches the signature of the resolver function.
838
839 // GetElementPtr *funcName, ulong 0, ulong 0
840 std::vector<Constant*> GEPargs(2,
841 Constant::getNullValue(Type::getInt32Ty(F->getContext())));
842 Value *GEP = ConstantExpr::getGetElementPtr(InitArray->getType(),
843 funcName, GEPargs);
844 std::vector<Value*> ResolverArgs;
845 ResolverArgs.push_back(GEP);
846
847 // Rewrite uses of F in global initializers, etc. to uses of a wrapper
848 // function that dynamically resolves the calls to F via our JIT API
849 if (!F->use_empty()) {
850 // Create a new global to hold the cached function pointer.
851 Constant *NullPtr = ConstantPointerNull::get(F->getType());
852 GlobalVariable *Cache =
853 new GlobalVariable(*F->getParent(), F->getType(),
854 false, GlobalValue::InternalLinkage,
855 NullPtr,F->getName()+".fpcache");
856
857 // Construct a new stub function that will re-route calls to F
858 FunctionType *FuncTy = F->getFunctionType();
859 Function *FuncWrapper = Function::Create(FuncTy,
860 GlobalValue::InternalLinkage,
861 F->getName() + "_wrapper",
862 F->getParent());
863 BasicBlock *EntryBB = BasicBlock::Create(F->getContext(),
864 "entry", FuncWrapper);
865 BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(),
866 "usecache", FuncWrapper);
867 BasicBlock *LookupBB = BasicBlock::Create(F->getContext(),
868 "lookupfp", FuncWrapper);
869
870 // Check to see if we already looked up the value.
871 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB);
872 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal,
873 NullPtr, "isNull");
874 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB);
875
876 // Resolve the call to function F via the JIT API:
877 //
878 // call resolver(GetElementPtr...)
879 CallInst *Resolver =
880 CallInst::Create(resolverFunc, ResolverArgs, "resolver", LookupBB);
881
882 // Cast the result from the resolver to correctly-typed function.
883 CastInst *CastedResolver =
884 new BitCastInst(Resolver,
885 PointerType::getUnqual(F->getFunctionType()),
886 "resolverCast", LookupBB);
887
888 // Save the value in our cache.
889 new StoreInst(CastedResolver, Cache, LookupBB);
890 BranchInst::Create(DoCallBB, LookupBB);
891
892 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(), 2,
893 "fp", DoCallBB);
894 FuncPtr->addIncoming(CastedResolver, LookupBB);
895 FuncPtr->addIncoming(CachedVal, EntryBB);
896
897 // Save the argument list.
898 std::vector<Value*> Args;
899 for (Argument &A : FuncWrapper->args())
900 Args.push_back(&A);
901
902 // Pass on the arguments to the real function, return its result
903 if (F->getReturnType()->isVoidTy()) {
904 CallInst::Create(FuncPtr, Args, "", DoCallBB);
905 ReturnInst::Create(F->getContext(), DoCallBB);
906 } else {
907 CallInst *Call = CallInst::Create(FuncPtr, Args,
908 "retval", DoCallBB);
909 ReturnInst::Create(F->getContext(),Call, DoCallBB);
910 }
911
912 // Use the wrapper function instead of the old function
913 F->replaceAllUsesWith(FuncWrapper);
914 }
915 }
916 }
917 }
918
919 if (verifyModule(*Test) || verifyModule(*Safe)) {
920 errs() << "Bugpoint has a bug, which corrupted a module!!\n";
921 abort();
922 }
923 }
924
925 /// This is the predicate function used to check to see if the "Test" portion of
926 /// the program is miscompiled by the code generator under test. If so, return
927 /// true. In any case, both module arguments are deleted.
928 ///
TestCodeGenerator(BugDriver & BD,std::unique_ptr<Module> Test,std::unique_ptr<Module> Safe,std::string & Error)929 static bool TestCodeGenerator(BugDriver &BD, std::unique_ptr<Module> Test,
930 std::unique_ptr<Module> Safe,
931 std::string &Error) {
932 CleanupAndPrepareModules(BD, Test, Safe.get());
933
934 SmallString<128> TestModuleBC;
935 int TestModuleFD;
936 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
937 TestModuleFD, TestModuleBC);
938 if (EC) {
939 errs() << BD.getToolName() << "Error making unique filename: "
940 << EC.message() << "\n";
941 exit(1);
942 }
943 if (BD.writeProgramToFile(TestModuleBC.str(), TestModuleFD, Test.get())) {
944 errs() << "Error writing bitcode to `" << TestModuleBC.str()
945 << "'\nExiting.";
946 exit(1);
947 }
948
949 FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps);
950
951 // Make the shared library
952 SmallString<128> SafeModuleBC;
953 int SafeModuleFD;
954 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
955 SafeModuleBC);
956 if (EC) {
957 errs() << BD.getToolName() << "Error making unique filename: "
958 << EC.message() << "\n";
959 exit(1);
960 }
961
962 if (BD.writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, Safe.get())) {
963 errs() << "Error writing bitcode to `" << SafeModuleBC
964 << "'\nExiting.";
965 exit(1);
966 }
967
968 FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps);
969
970 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str(), Error);
971 if (!Error.empty())
972 return false;
973
974 FileRemover SharedObjectRemover(SharedObject, !SaveTemps);
975
976 // Run the code generator on the `Test' code, loading the shared library.
977 // The function returns whether or not the new output differs from reference.
978 bool Result = BD.diffProgram(BD.getProgram(), TestModuleBC.str(),
979 SharedObject, false, &Error);
980 if (!Error.empty())
981 return false;
982
983 if (Result)
984 errs() << ": still failing!\n";
985 else
986 errs() << ": didn't fail.\n";
987
988 return Result;
989 }
990
991 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE.
992 ///
debugCodeGenerator(std::string * Error)993 bool BugDriver::debugCodeGenerator(std::string *Error) {
994 if ((void*)SafeInterpreter == (void*)Interpreter) {
995 std::string Result = executeProgramSafely(Program, "bugpoint.safe.out",
996 Error);
997 if (Error->empty()) {
998 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match "
999 << "the reference diff. This may be due to a\n front-end "
1000 << "bug or a bug in the original program, but this can also "
1001 << "happen if bugpoint isn't running the program with the "
1002 << "right flags or input.\n I left the result of executing "
1003 << "the program with the \"safe\" backend in this file for "
1004 << "you: '"
1005 << Result << "'.\n";
1006 }
1007 return true;
1008 }
1009
1010 DisambiguateGlobalSymbols(Program);
1011
1012 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator,
1013 *Error);
1014 if (!Error->empty())
1015 return true;
1016
1017 // Split the module into the two halves of the program we want.
1018 ValueToValueMapTy VMap;
1019 std::unique_ptr<Module> ToNotCodeGen = CloneModule(getProgram(), VMap);
1020 std::unique_ptr<Module> ToCodeGen =
1021 SplitFunctionsOutOfModule(ToNotCodeGen.get(), Funcs, VMap);
1022
1023 // Condition the modules
1024 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen.get());
1025
1026 SmallString<128> TestModuleBC;
1027 int TestModuleFD;
1028 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc",
1029 TestModuleFD, TestModuleBC);
1030 if (EC) {
1031 errs() << getToolName() << "Error making unique filename: "
1032 << EC.message() << "\n";
1033 exit(1);
1034 }
1035
1036 if (writeProgramToFile(TestModuleBC.str(), TestModuleFD, ToCodeGen.get())) {
1037 errs() << "Error writing bitcode to `" << TestModuleBC
1038 << "'\nExiting.";
1039 exit(1);
1040 }
1041
1042 // Make the shared library
1043 SmallString<128> SafeModuleBC;
1044 int SafeModuleFD;
1045 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD,
1046 SafeModuleBC);
1047 if (EC) {
1048 errs() << getToolName() << "Error making unique filename: "
1049 << EC.message() << "\n";
1050 exit(1);
1051 }
1052
1053 if (writeProgramToFile(SafeModuleBC.str(), SafeModuleFD,
1054 ToNotCodeGen.get())) {
1055 errs() << "Error writing bitcode to `" << SafeModuleBC
1056 << "'\nExiting.";
1057 exit(1);
1058 }
1059 std::string SharedObject = compileSharedObject(SafeModuleBC.str(), *Error);
1060 if (!Error->empty())
1061 return true;
1062
1063 outs() << "You can reproduce the problem with the command line: \n";
1064 if (isExecutingJIT()) {
1065 outs() << " lli -load " << SharedObject << " " << TestModuleBC;
1066 } else {
1067 outs() << " llc " << TestModuleBC << " -o " << TestModuleBC
1068 << ".s\n";
1069 outs() << " cc " << SharedObject << " " << TestModuleBC.str()
1070 << ".s -o " << TestModuleBC << ".exe";
1071 #if defined (HAVE_LINK_R)
1072 outs() << " -Wl,-R.";
1073 #endif
1074 outs() << "\n";
1075 outs() << " " << TestModuleBC << ".exe";
1076 }
1077 for (unsigned i = 0, e = InputArgv.size(); i != e; ++i)
1078 outs() << " " << InputArgv[i];
1079 outs() << '\n';
1080 outs() << "The shared object was created with:\n llc -march=c "
1081 << SafeModuleBC.str() << " -o temporary.c\n"
1082 << " cc -xc temporary.c -O2 -o " << SharedObject;
1083 if (TargetTriple.getArch() == Triple::sparc)
1084 outs() << " -G"; // Compile a shared library, `-G' for Sparc
1085 else
1086 outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others
1087
1088 outs() << " -fno-strict-aliasing\n";
1089
1090 return false;
1091 }
1092