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: 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 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: 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 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 /// 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 /// 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 /// 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 /// 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: 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 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 /// 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 /// 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 *> 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 /// 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 /*AutoDebugCrashes*/ true); 702 outs() << "done.\n"; 703 704 outs() << " Checking to see if the merged program executes correctly: "; 705 bool Broken; 706 std::unique_ptr<Module> New = testMergedProgram( 707 BD, std::move(Optimized), std::move(Safe), Error, Broken); 708 if (New) { 709 outs() << (Broken ? " nope.\n" : " yup.\n"); 710 // Delete the original and set the new program. 711 delete BD.swapProgramIn(New.release()); 712 } 713 return Broken; 714 } 715 716 /// debugMiscompilation - This method is used when the passes selected are not 717 /// crashing, but the generated output is semantically different from the 718 /// input. 719 /// 720 void BugDriver::debugMiscompilation(std::string *Error) { 721 // Make sure something was miscompiled... 722 if (!BugpointIsInterrupted) 723 if (!ReduceMiscompilingPasses(*this).reduceList(PassesToRun, *Error)) { 724 if (Error->empty()) 725 errs() << "*** Optimized program matches reference output! No problem" 726 << " detected...\nbugpoint can't help you with your problem!\n"; 727 return; 728 } 729 730 outs() << "\n*** Found miscompiling pass" 731 << (getPassesToRun().size() == 1 ? "" : "es") << ": " 732 << getPassesString(getPassesToRun()) << '\n'; 733 EmitProgressBitcode(Program, "passinput"); 734 735 std::vector<Function *> MiscompiledFunctions = 736 DebugAMiscompilation(*this, TestOptimizer, *Error); 737 if (!Error->empty()) 738 return; 739 740 // Output a bunch of bitcode files for the user... 741 outs() << "Outputting reduced bitcode files which expose the problem:\n"; 742 ValueToValueMapTy VMap; 743 Module *ToNotOptimize = CloneModule(getProgram(), VMap).release(); 744 Module *ToOptimize = 745 SplitFunctionsOutOfModule(ToNotOptimize, MiscompiledFunctions, VMap) 746 .release(); 747 748 outs() << " Non-optimized portion: "; 749 EmitProgressBitcode(ToNotOptimize, "tonotoptimize", true); 750 delete ToNotOptimize; // Delete hacked module. 751 752 outs() << " Portion that is input to optimizer: "; 753 EmitProgressBitcode(ToOptimize, "tooptimize"); 754 delete ToOptimize; // Delete hacked module. 755 } 756 757 /// Get the specified modules ready for code generator testing. 758 /// 759 static void CleanupAndPrepareModules(BugDriver &BD, 760 std::unique_ptr<Module> &Test, 761 Module *Safe) { 762 // Clean up the modules, removing extra cruft that we don't need anymore... 763 Test = BD.performFinalCleanups(Test.get()); 764 765 // If we are executing the JIT, we have several nasty issues to take care of. 766 if (!BD.isExecutingJIT()) return; 767 768 // First, if the main function is in the Safe module, we must add a stub to 769 // the Test module to call into it. Thus, we create a new function `main' 770 // which just calls the old one. 771 if (Function *oldMain = Safe->getFunction("main")) 772 if (!oldMain->isDeclaration()) { 773 // Rename it 774 oldMain->setName("llvm_bugpoint_old_main"); 775 // Create a NEW `main' function with same type in the test module. 776 Function *newMain = 777 Function::Create(oldMain->getFunctionType(), 778 GlobalValue::ExternalLinkage, "main", Test.get()); 779 // Create an `oldmain' prototype in the test module, which will 780 // corresponds to the real main function in the same module. 781 Function *oldMainProto = Function::Create(oldMain->getFunctionType(), 782 GlobalValue::ExternalLinkage, 783 oldMain->getName(), Test.get()); 784 // Set up and remember the argument list for the main function. 785 std::vector<Value*> args; 786 for (Function::arg_iterator 787 I = newMain->arg_begin(), E = newMain->arg_end(), 788 OI = oldMain->arg_begin(); I != E; ++I, ++OI) { 789 I->setName(OI->getName()); // Copy argument names from oldMain 790 args.push_back(&*I); 791 } 792 793 // Call the old main function and return its result 794 BasicBlock *BB = BasicBlock::Create(Safe->getContext(), "entry", newMain); 795 CallInst *call = CallInst::Create(oldMainProto, args, "", BB); 796 797 // If the type of old function wasn't void, return value of call 798 ReturnInst::Create(Safe->getContext(), call, BB); 799 } 800 801 // The second nasty issue we must deal with in the JIT is that the Safe 802 // module cannot directly reference any functions defined in the test 803 // module. Instead, we use a JIT API call to dynamically resolve the 804 // symbol. 805 806 // Add the resolver to the Safe module. 807 // Prototype: void *getPointerToNamedFunction(const char* Name) 808 Constant *resolverFunc = 809 Safe->getOrInsertFunction("getPointerToNamedFunction", 810 Type::getInt8PtrTy(Safe->getContext()), 811 Type::getInt8PtrTy(Safe->getContext()), 812 (Type *)nullptr); 813 814 // Use the function we just added to get addresses of functions we need. 815 for (Module::iterator F = Safe->begin(), E = Safe->end(); F != E; ++F) { 816 if (F->isDeclaration() && !F->use_empty() && &*F != resolverFunc && 817 !F->isIntrinsic() /* ignore intrinsics */) { 818 Function *TestFn = Test->getFunction(F->getName()); 819 820 // Don't forward functions which are external in the test module too. 821 if (TestFn && !TestFn->isDeclaration()) { 822 // 1. Add a string constant with its name to the global file 823 Constant *InitArray = 824 ConstantDataArray::getString(F->getContext(), F->getName()); 825 GlobalVariable *funcName = 826 new GlobalVariable(*Safe, InitArray->getType(), true /*isConstant*/, 827 GlobalValue::InternalLinkage, InitArray, 828 F->getName() + "_name"); 829 830 // 2. Use `GetElementPtr *funcName, 0, 0' to convert the string to an 831 // sbyte* so it matches the signature of the resolver function. 832 833 // GetElementPtr *funcName, ulong 0, ulong 0 834 std::vector<Constant*> GEPargs(2, 835 Constant::getNullValue(Type::getInt32Ty(F->getContext()))); 836 Value *GEP = ConstantExpr::getGetElementPtr(InitArray->getType(), 837 funcName, GEPargs); 838 std::vector<Value*> ResolverArgs; 839 ResolverArgs.push_back(GEP); 840 841 // Rewrite uses of F in global initializers, etc. to uses of a wrapper 842 // function that dynamically resolves the calls to F via our JIT API 843 if (!F->use_empty()) { 844 // Create a new global to hold the cached function pointer. 845 Constant *NullPtr = ConstantPointerNull::get(F->getType()); 846 GlobalVariable *Cache = 847 new GlobalVariable(*F->getParent(), F->getType(), 848 false, GlobalValue::InternalLinkage, 849 NullPtr,F->getName()+".fpcache"); 850 851 // Construct a new stub function that will re-route calls to F 852 FunctionType *FuncTy = F->getFunctionType(); 853 Function *FuncWrapper = Function::Create(FuncTy, 854 GlobalValue::InternalLinkage, 855 F->getName() + "_wrapper", 856 F->getParent()); 857 BasicBlock *EntryBB = BasicBlock::Create(F->getContext(), 858 "entry", FuncWrapper); 859 BasicBlock *DoCallBB = BasicBlock::Create(F->getContext(), 860 "usecache", FuncWrapper); 861 BasicBlock *LookupBB = BasicBlock::Create(F->getContext(), 862 "lookupfp", FuncWrapper); 863 864 // Check to see if we already looked up the value. 865 Value *CachedVal = new LoadInst(Cache, "fpcache", EntryBB); 866 Value *IsNull = new ICmpInst(*EntryBB, ICmpInst::ICMP_EQ, CachedVal, 867 NullPtr, "isNull"); 868 BranchInst::Create(LookupBB, DoCallBB, IsNull, EntryBB); 869 870 // Resolve the call to function F via the JIT API: 871 // 872 // call resolver(GetElementPtr...) 873 CallInst *Resolver = 874 CallInst::Create(resolverFunc, ResolverArgs, "resolver", LookupBB); 875 876 // Cast the result from the resolver to correctly-typed function. 877 CastInst *CastedResolver = 878 new BitCastInst(Resolver, 879 PointerType::getUnqual(F->getFunctionType()), 880 "resolverCast", LookupBB); 881 882 // Save the value in our cache. 883 new StoreInst(CastedResolver, Cache, LookupBB); 884 BranchInst::Create(DoCallBB, LookupBB); 885 886 PHINode *FuncPtr = PHINode::Create(NullPtr->getType(), 2, 887 "fp", DoCallBB); 888 FuncPtr->addIncoming(CastedResolver, LookupBB); 889 FuncPtr->addIncoming(CachedVal, EntryBB); 890 891 // Save the argument list. 892 std::vector<Value*> Args; 893 for (Argument &A : FuncWrapper->args()) 894 Args.push_back(&A); 895 896 // Pass on the arguments to the real function, return its result 897 if (F->getReturnType()->isVoidTy()) { 898 CallInst::Create(FuncPtr, Args, "", DoCallBB); 899 ReturnInst::Create(F->getContext(), DoCallBB); 900 } else { 901 CallInst *Call = CallInst::Create(FuncPtr, Args, 902 "retval", DoCallBB); 903 ReturnInst::Create(F->getContext(),Call, DoCallBB); 904 } 905 906 // Use the wrapper function instead of the old function 907 F->replaceAllUsesWith(FuncWrapper); 908 } 909 } 910 } 911 } 912 913 if (verifyModule(*Test) || verifyModule(*Safe)) { 914 errs() << "Bugpoint has a bug, which corrupted a module!!\n"; 915 abort(); 916 } 917 } 918 919 /// This is the predicate function used to check to see if the "Test" portion of 920 /// the program is miscompiled by the code generator under test. If so, return 921 /// true. In any case, both module arguments are deleted. 922 /// 923 static bool TestCodeGenerator(BugDriver &BD, std::unique_ptr<Module> Test, 924 std::unique_ptr<Module> Safe, 925 std::string &Error) { 926 CleanupAndPrepareModules(BD, Test, Safe.get()); 927 928 SmallString<128> TestModuleBC; 929 int TestModuleFD; 930 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc", 931 TestModuleFD, TestModuleBC); 932 if (EC) { 933 errs() << BD.getToolName() << "Error making unique filename: " 934 << EC.message() << "\n"; 935 exit(1); 936 } 937 if (BD.writeProgramToFile(TestModuleBC.str(), TestModuleFD, Test.get())) { 938 errs() << "Error writing bitcode to `" << TestModuleBC.str() 939 << "'\nExiting."; 940 exit(1); 941 } 942 943 FileRemover TestModuleBCRemover(TestModuleBC.str(), !SaveTemps); 944 945 // Make the shared library 946 SmallString<128> SafeModuleBC; 947 int SafeModuleFD; 948 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD, 949 SafeModuleBC); 950 if (EC) { 951 errs() << BD.getToolName() << "Error making unique filename: " 952 << EC.message() << "\n"; 953 exit(1); 954 } 955 956 if (BD.writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, Safe.get())) { 957 errs() << "Error writing bitcode to `" << SafeModuleBC 958 << "'\nExiting."; 959 exit(1); 960 } 961 962 FileRemover SafeModuleBCRemover(SafeModuleBC.str(), !SaveTemps); 963 964 std::string SharedObject = BD.compileSharedObject(SafeModuleBC.str(), Error); 965 if (!Error.empty()) 966 return false; 967 968 FileRemover SharedObjectRemover(SharedObject, !SaveTemps); 969 970 // Run the code generator on the `Test' code, loading the shared library. 971 // The function returns whether or not the new output differs from reference. 972 bool Result = BD.diffProgram(BD.getProgram(), TestModuleBC.str(), 973 SharedObject, false, &Error); 974 if (!Error.empty()) 975 return false; 976 977 if (Result) 978 errs() << ": still failing!\n"; 979 else 980 errs() << ": didn't fail.\n"; 981 982 return Result; 983 } 984 985 /// debugCodeGenerator - debug errors in LLC, LLI, or CBE. 986 /// 987 bool BugDriver::debugCodeGenerator(std::string *Error) { 988 if ((void*)SafeInterpreter == (void*)Interpreter) { 989 std::string Result = executeProgramSafely(Program, "bugpoint.safe.out", 990 Error); 991 if (Error->empty()) { 992 outs() << "\n*** The \"safe\" i.e. 'known good' backend cannot match " 993 << "the reference diff. This may be due to a\n front-end " 994 << "bug or a bug in the original program, but this can also " 995 << "happen if bugpoint isn't running the program with the " 996 << "right flags or input.\n I left the result of executing " 997 << "the program with the \"safe\" backend in this file for " 998 << "you: '" 999 << Result << "'.\n"; 1000 } 1001 return true; 1002 } 1003 1004 DisambiguateGlobalSymbols(Program); 1005 1006 std::vector<Function*> Funcs = DebugAMiscompilation(*this, TestCodeGenerator, 1007 *Error); 1008 if (!Error->empty()) 1009 return true; 1010 1011 // Split the module into the two halves of the program we want. 1012 ValueToValueMapTy VMap; 1013 std::unique_ptr<Module> ToNotCodeGen = CloneModule(getProgram(), VMap); 1014 std::unique_ptr<Module> ToCodeGen = 1015 SplitFunctionsOutOfModule(ToNotCodeGen.get(), Funcs, VMap); 1016 1017 // Condition the modules 1018 CleanupAndPrepareModules(*this, ToCodeGen, ToNotCodeGen.get()); 1019 1020 SmallString<128> TestModuleBC; 1021 int TestModuleFD; 1022 std::error_code EC = sys::fs::createTemporaryFile("bugpoint.test", "bc", 1023 TestModuleFD, TestModuleBC); 1024 if (EC) { 1025 errs() << getToolName() << "Error making unique filename: " 1026 << EC.message() << "\n"; 1027 exit(1); 1028 } 1029 1030 if (writeProgramToFile(TestModuleBC.str(), TestModuleFD, ToCodeGen.get())) { 1031 errs() << "Error writing bitcode to `" << TestModuleBC 1032 << "'\nExiting."; 1033 exit(1); 1034 } 1035 1036 // Make the shared library 1037 SmallString<128> SafeModuleBC; 1038 int SafeModuleFD; 1039 EC = sys::fs::createTemporaryFile("bugpoint.safe", "bc", SafeModuleFD, 1040 SafeModuleBC); 1041 if (EC) { 1042 errs() << getToolName() << "Error making unique filename: " 1043 << EC.message() << "\n"; 1044 exit(1); 1045 } 1046 1047 if (writeProgramToFile(SafeModuleBC.str(), SafeModuleFD, 1048 ToNotCodeGen.get())) { 1049 errs() << "Error writing bitcode to `" << SafeModuleBC 1050 << "'\nExiting."; 1051 exit(1); 1052 } 1053 std::string SharedObject = compileSharedObject(SafeModuleBC.str(), *Error); 1054 if (!Error->empty()) 1055 return true; 1056 1057 outs() << "You can reproduce the problem with the command line: \n"; 1058 if (isExecutingJIT()) { 1059 outs() << " lli -load " << SharedObject << " " << TestModuleBC; 1060 } else { 1061 outs() << " llc " << TestModuleBC << " -o " << TestModuleBC 1062 << ".s\n"; 1063 outs() << " cc " << SharedObject << " " << TestModuleBC.str() 1064 << ".s -o " << TestModuleBC << ".exe"; 1065 #if defined (HAVE_LINK_R) 1066 outs() << " -Wl,-R."; 1067 #endif 1068 outs() << "\n"; 1069 outs() << " " << TestModuleBC << ".exe"; 1070 } 1071 for (unsigned i = 0, e = InputArgv.size(); i != e; ++i) 1072 outs() << " " << InputArgv[i]; 1073 outs() << '\n'; 1074 outs() << "The shared object was created with:\n llc -march=c " 1075 << SafeModuleBC.str() << " -o temporary.c\n" 1076 << " cc -xc temporary.c -O2 -o " << SharedObject; 1077 if (TargetTriple.getArch() == Triple::sparc) 1078 outs() << " -G"; // Compile a shared library, `-G' for Sparc 1079 else 1080 outs() << " -fPIC -shared"; // `-shared' for Linux/X86, maybe others 1081 1082 outs() << " -fno-strict-aliasing\n"; 1083 1084 return false; 1085 } 1086