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