1 //===- Local.cpp - Unit tests for Local -----------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "llvm/Transforms/Utils/Local.h" 10 #include "llvm/ADT/ScopeExit.h" 11 #include "llvm/Analysis/DomTreeUpdater.h" 12 #include "llvm/Analysis/InstructionSimplify.h" 13 #include "llvm/Analysis/PostDominators.h" 14 #include "llvm/Analysis/TargetTransformInfo.h" 15 #include "llvm/AsmParser/Parser.h" 16 #include "llvm/IR/BasicBlock.h" 17 #include "llvm/IR/DIBuilder.h" 18 #include "llvm/IR/DebugInfo.h" 19 #include "llvm/IR/DebugProgramInstruction.h" 20 #include "llvm/IR/IRBuilder.h" 21 #include "llvm/IR/Instructions.h" 22 #include "llvm/IR/IntrinsicInst.h" 23 #include "llvm/IR/LLVMContext.h" 24 #include "llvm/IR/Verifier.h" 25 #include "llvm/Support/SourceMgr.h" 26 #include "gtest/gtest.h" 27 28 using namespace llvm; 29 30 extern llvm::cl::opt<bool> UseNewDbgInfoFormat; 31 extern cl::opt<cl::boolOrDefault> PreserveInputDbgFormat; 32 extern bool WriteNewDbgInfoFormatToBitcode; 33 extern cl::opt<bool> WriteNewDbgInfoFormat; 34 35 // Backup all of the existing settings that may be modified when 36 // PreserveInputDbgFormat=true, so that when the test is finished we return them 37 // (and the "preserve" setting) to their original values. 38 static auto SaveDbgInfoFormat() { 39 return make_scope_exit( 40 [OldPreserveInputDbgFormat = PreserveInputDbgFormat.getValue(), 41 OldUseNewDbgInfoFormat = UseNewDbgInfoFormat.getValue(), 42 OldWriteNewDbgInfoFormatToBitcode = WriteNewDbgInfoFormatToBitcode, 43 OldWriteNewDbgInfoFormat = WriteNewDbgInfoFormat.getValue()] { 44 PreserveInputDbgFormat = OldPreserveInputDbgFormat; 45 UseNewDbgInfoFormat = OldUseNewDbgInfoFormat; 46 WriteNewDbgInfoFormatToBitcode = OldWriteNewDbgInfoFormatToBitcode; 47 WriteNewDbgInfoFormat = OldWriteNewDbgInfoFormat; 48 }); 49 } 50 51 TEST(Local, RecursivelyDeleteDeadPHINodes) { 52 LLVMContext C; 53 54 IRBuilder<> builder(C); 55 56 // Make blocks 57 BasicBlock *bb0 = BasicBlock::Create(C); 58 BasicBlock *bb1 = BasicBlock::Create(C); 59 60 builder.SetInsertPoint(bb0); 61 PHINode *phi = builder.CreatePHI(Type::getInt32Ty(C), 2); 62 BranchInst *br0 = builder.CreateCondBr(builder.getTrue(), bb0, bb1); 63 64 builder.SetInsertPoint(bb1); 65 BranchInst *br1 = builder.CreateBr(bb0); 66 67 phi->addIncoming(phi, bb0); 68 phi->addIncoming(phi, bb1); 69 70 // The PHI will be removed 71 EXPECT_TRUE(RecursivelyDeleteDeadPHINode(phi)); 72 73 // Make sure the blocks only contain the branches 74 EXPECT_EQ(&bb0->front(), br0); 75 EXPECT_EQ(&bb1->front(), br1); 76 77 builder.SetInsertPoint(bb0); 78 phi = builder.CreatePHI(Type::getInt32Ty(C), 0); 79 80 EXPECT_TRUE(RecursivelyDeleteDeadPHINode(phi)); 81 82 builder.SetInsertPoint(bb0); 83 phi = builder.CreatePHI(Type::getInt32Ty(C), 0); 84 builder.CreateAdd(phi, phi); 85 86 EXPECT_TRUE(RecursivelyDeleteDeadPHINode(phi)); 87 88 bb0->dropAllReferences(); 89 bb1->dropAllReferences(); 90 delete bb0; 91 delete bb1; 92 } 93 94 TEST(Local, RemoveDuplicatePHINodes) { 95 LLVMContext C; 96 IRBuilder<> B(C); 97 98 std::unique_ptr<Function> F( 99 Function::Create(FunctionType::get(B.getVoidTy(), false), 100 GlobalValue::ExternalLinkage, "F")); 101 BasicBlock *Entry(BasicBlock::Create(C, "", F.get())); 102 BasicBlock *BB(BasicBlock::Create(C, "", F.get())); 103 BranchInst::Create(BB, Entry); 104 105 B.SetInsertPoint(BB); 106 107 AssertingVH<PHINode> P1 = B.CreatePHI(Type::getInt32Ty(C), 2); 108 P1->addIncoming(B.getInt32(42), Entry); 109 110 PHINode *P2 = B.CreatePHI(Type::getInt32Ty(C), 2); 111 P2->addIncoming(B.getInt32(42), Entry); 112 113 AssertingVH<PHINode> P3 = B.CreatePHI(Type::getInt32Ty(C), 2); 114 P3->addIncoming(B.getInt32(42), Entry); 115 P3->addIncoming(B.getInt32(23), BB); 116 117 PHINode *P4 = B.CreatePHI(Type::getInt32Ty(C), 2); 118 P4->addIncoming(B.getInt32(42), Entry); 119 P4->addIncoming(B.getInt32(23), BB); 120 121 P1->addIncoming(P3, BB); 122 P2->addIncoming(P4, BB); 123 BranchInst::Create(BB, BB); 124 125 // Verify that we can eliminate PHIs that become duplicates after chaning PHIs 126 // downstream. 127 EXPECT_TRUE(EliminateDuplicatePHINodes(BB)); 128 EXPECT_EQ(3U, BB->size()); 129 } 130 131 static std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) { 132 SMDiagnostic Err; 133 std::unique_ptr<Module> Mod = parseAssemblyString(IR, Err, C); 134 if (!Mod) 135 Err.print("UtilsTests", errs()); 136 return Mod; 137 } 138 139 TEST(Local, ReplaceDbgDeclare) { 140 LLVMContext C; 141 // FIXME: PreserveInputDbgFormat is set to true because this test has 142 // been written to expect debug intrinsics rather than debug records; use the 143 // intrinsic format until we update the test checks. 144 auto SettingGuard = SaveDbgInfoFormat(); 145 PreserveInputDbgFormat = cl::boolOrDefault::BOU_TRUE; 146 147 // Original C source to get debug info for a local variable: 148 // void f() { int x; } 149 std::unique_ptr<Module> M = parseIR(C, 150 R"( 151 define void @f() !dbg !8 { 152 entry: 153 %x = alloca i32, align 4 154 call void @llvm.dbg.declare(metadata i32* %x, metadata !11, metadata !DIExpression()), !dbg !13 155 call void @llvm.dbg.declare(metadata i32* %x, metadata !11, metadata !DIExpression()), !dbg !13 156 ret void, !dbg !14 157 } 158 declare void @llvm.dbg.declare(metadata, metadata, metadata) 159 !llvm.dbg.cu = !{!0} 160 !llvm.module.flags = !{!3, !4} 161 !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 6.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2) 162 !1 = !DIFile(filename: "t2.c", directory: "foo") 163 !2 = !{} 164 !3 = !{i32 2, !"Dwarf Version", i32 4} 165 !4 = !{i32 2, !"Debug Info Version", i32 3} 166 !8 = distinct !DISubprogram(name: "f", scope: !1, file: !1, line: 1, type: !9, isLocal: false, isDefinition: true, scopeLine: 1, isOptimized: false, unit: !0, retainedNodes: !2) 167 !9 = !DISubroutineType(types: !10) 168 !10 = !{null} 169 !11 = !DILocalVariable(name: "x", scope: !8, file: !1, line: 2, type: !12) 170 !12 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) 171 !13 = !DILocation(line: 2, column: 7, scope: !8) 172 !14 = !DILocation(line: 3, column: 1, scope: !8) 173 )"); 174 auto *GV = M->getNamedValue("f"); 175 ASSERT_TRUE(GV); 176 auto *F = dyn_cast<Function>(GV); 177 ASSERT_TRUE(F); 178 Instruction *Inst = &F->front().front(); 179 auto *AI = dyn_cast<AllocaInst>(Inst); 180 ASSERT_TRUE(AI); 181 Inst = Inst->getNextNode()->getNextNode(); 182 ASSERT_TRUE(Inst); 183 auto *DII = dyn_cast<DbgDeclareInst>(Inst); 184 ASSERT_TRUE(DII); 185 Value *NewBase = Constant::getNullValue(PointerType::getUnqual(C)); 186 DIBuilder DIB(*M); 187 replaceDbgDeclare(AI, NewBase, DIB, DIExpression::ApplyOffset, 0); 188 189 // There should be exactly two dbg.declares. 190 int Declares = 0; 191 for (const Instruction &I : F->front()) 192 if (isa<DbgDeclareInst>(I)) 193 Declares++; 194 EXPECT_EQ(2, Declares); 195 } 196 197 /// Build the dominator tree for the function and run the Test. 198 static void runWithDomTree( 199 Module &M, StringRef FuncName, 200 function_ref<void(Function &F, DominatorTree *DT)> Test) { 201 auto *F = M.getFunction(FuncName); 202 ASSERT_NE(F, nullptr) << "Could not find " << FuncName; 203 // Compute the dominator tree for the function. 204 DominatorTree DT(*F); 205 Test(*F, &DT); 206 } 207 208 TEST(Local, MergeBasicBlockIntoOnlyPred) { 209 LLVMContext C; 210 std::unique_ptr<Module> M; 211 auto resetIR = [&]() { 212 M = parseIR(C, 213 R"( 214 define i32 @f(i8* %str) { 215 entry: 216 br label %bb2.i 217 bb2.i: ; preds = %bb4.i, %entry 218 br i1 false, label %bb4.i, label %base2flt.exit204 219 bb4.i: ; preds = %bb2.i 220 br i1 false, label %base2flt.exit204, label %bb2.i 221 bb10.i196.bb7.i197_crit_edge: ; No predecessors! 222 br label %bb7.i197 223 bb7.i197: ; preds = %bb10.i196.bb7.i197_crit_edge 224 %.reg2mem.0 = phi i32 [ %.reg2mem.0, %bb10.i196.bb7.i197_crit_edge ] 225 br i1 undef, label %base2flt.exit204, label %base2flt.exit204 226 base2flt.exit204: ; preds = %bb7.i197, %bb7.i197, %bb2.i, %bb4.i 227 ret i32 0 228 } 229 )"); 230 }; 231 232 auto resetIRReplaceEntry = [&]() { 233 M = parseIR(C, 234 R"( 235 define i32 @f() { 236 entry: 237 br label %bb2.i 238 bb2.i: ; preds = %entry 239 ret i32 0 240 } 241 )"); 242 }; 243 244 auto Test = [&](Function &F, DomTreeUpdater &DTU) { 245 for (Function::iterator I = F.begin(), E = F.end(); I != E;) { 246 BasicBlock *BB = &*I++; 247 BasicBlock *SinglePred = BB->getSinglePredecessor(); 248 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) 249 continue; 250 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator()); 251 if (Term && !Term->isConditional()) 252 MergeBasicBlockIntoOnlyPred(BB, &DTU); 253 } 254 if (DTU.hasDomTree()) { 255 EXPECT_TRUE(DTU.getDomTree().verify()); 256 } 257 if (DTU.hasPostDomTree()) { 258 EXPECT_TRUE(DTU.getPostDomTree().verify()); 259 } 260 }; 261 262 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with 263 // both DT and PDT. 264 resetIR(); 265 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 266 PostDominatorTree PDT = PostDominatorTree(F); 267 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager); 268 Test(F, DTU); 269 }); 270 271 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with 272 // DT. 273 resetIR(); 274 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 275 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Eager); 276 Test(F, DTU); 277 }); 278 279 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with 280 // PDT. 281 resetIR(); 282 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 283 PostDominatorTree PDT = PostDominatorTree(F); 284 DomTreeUpdater DTU(PDT, DomTreeUpdater::UpdateStrategy::Eager); 285 Test(F, DTU); 286 }); 287 288 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with 289 // both DT and PDT. 290 resetIR(); 291 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 292 PostDominatorTree PDT = PostDominatorTree(F); 293 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy); 294 Test(F, DTU); 295 }); 296 297 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with 298 // PDT. 299 resetIR(); 300 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 301 PostDominatorTree PDT = PostDominatorTree(F); 302 DomTreeUpdater DTU(PDT, DomTreeUpdater::UpdateStrategy::Lazy); 303 Test(F, DTU); 304 }); 305 306 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with DT. 307 resetIR(); 308 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 309 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy); 310 Test(F, DTU); 311 }); 312 313 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with 314 // both DT and PDT. 315 resetIRReplaceEntry(); 316 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 317 PostDominatorTree PDT = PostDominatorTree(F); 318 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager); 319 Test(F, DTU); 320 }); 321 322 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with 323 // DT. 324 resetIRReplaceEntry(); 325 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 326 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Eager); 327 Test(F, DTU); 328 }); 329 330 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with 331 // PDT. 332 resetIRReplaceEntry(); 333 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 334 PostDominatorTree PDT = PostDominatorTree(F); 335 DomTreeUpdater DTU(PDT, DomTreeUpdater::UpdateStrategy::Eager); 336 Test(F, DTU); 337 }); 338 339 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with 340 // both DT and PDT. 341 resetIRReplaceEntry(); 342 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 343 PostDominatorTree PDT = PostDominatorTree(F); 344 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy); 345 Test(F, DTU); 346 }); 347 348 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with 349 // PDT. 350 resetIRReplaceEntry(); 351 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 352 PostDominatorTree PDT = PostDominatorTree(F); 353 DomTreeUpdater DTU(PDT, DomTreeUpdater::UpdateStrategy::Lazy); 354 Test(F, DTU); 355 }); 356 357 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with DT. 358 resetIRReplaceEntry(); 359 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 360 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy); 361 Test(F, DTU); 362 }); 363 } 364 365 TEST(Local, ConstantFoldTerminator) { 366 LLVMContext C; 367 368 std::unique_ptr<Module> M = parseIR(C, 369 R"( 370 define void @br_same_dest() { 371 entry: 372 br i1 false, label %bb0, label %bb0 373 bb0: 374 ret void 375 } 376 377 define void @br_different_dest() { 378 entry: 379 br i1 true, label %bb0, label %bb1 380 bb0: 381 br label %exit 382 bb1: 383 br label %exit 384 exit: 385 ret void 386 } 387 388 define void @switch_2_different_dest() { 389 entry: 390 switch i32 0, label %default [ i32 0, label %bb0 ] 391 default: 392 ret void 393 bb0: 394 ret void 395 } 396 define void @switch_2_different_dest_default() { 397 entry: 398 switch i32 1, label %default [ i32 0, label %bb0 ] 399 default: 400 ret void 401 bb0: 402 ret void 403 } 404 define void @switch_3_different_dest() { 405 entry: 406 switch i32 0, label %default [ i32 0, label %bb0 407 i32 1, label %bb1 ] 408 default: 409 ret void 410 bb0: 411 ret void 412 bb1: 413 ret void 414 } 415 416 define void @switch_variable_2_default_dest(i32 %arg) { 417 entry: 418 switch i32 %arg, label %default [ i32 0, label %default ] 419 default: 420 ret void 421 } 422 423 define void @switch_constant_2_default_dest() { 424 entry: 425 switch i32 1, label %default [ i32 0, label %default ] 426 default: 427 ret void 428 } 429 430 define void @switch_constant_3_repeated_dest() { 431 entry: 432 switch i32 0, label %default [ i32 0, label %bb0 433 i32 1, label %bb0 ] 434 bb0: 435 ret void 436 default: 437 ret void 438 } 439 440 define void @indirectbr() { 441 entry: 442 indirectbr i8* blockaddress(@indirectbr, %bb0), [label %bb0, label %bb1] 443 bb0: 444 ret void 445 bb1: 446 ret void 447 } 448 449 define void @indirectbr_repeated() { 450 entry: 451 indirectbr i8* blockaddress(@indirectbr_repeated, %bb0), [label %bb0, label %bb0] 452 bb0: 453 ret void 454 } 455 456 define void @indirectbr_unreachable() { 457 entry: 458 indirectbr i8* blockaddress(@indirectbr_unreachable, %bb0), [label %bb1] 459 bb0: 460 ret void 461 bb1: 462 ret void 463 } 464 )"); 465 466 auto CFAllTerminatorsEager = [&](Function &F, DominatorTree *DT) { 467 PostDominatorTree PDT = PostDominatorTree(F); 468 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager); 469 for (Function::iterator I = F.begin(), E = F.end(); I != E;) { 470 BasicBlock *BB = &*I++; 471 ConstantFoldTerminator(BB, true, nullptr, &DTU); 472 } 473 474 EXPECT_TRUE(DTU.getDomTree().verify()); 475 EXPECT_TRUE(DTU.getPostDomTree().verify()); 476 }; 477 478 auto CFAllTerminatorsLazy = [&](Function &F, DominatorTree *DT) { 479 PostDominatorTree PDT = PostDominatorTree(F); 480 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy); 481 for (Function::iterator I = F.begin(), E = F.end(); I != E;) { 482 BasicBlock *BB = &*I++; 483 ConstantFoldTerminator(BB, true, nullptr, &DTU); 484 } 485 486 EXPECT_TRUE(DTU.getDomTree().verify()); 487 EXPECT_TRUE(DTU.getPostDomTree().verify()); 488 }; 489 490 // Test ConstantFoldTerminator under Eager UpdateStrategy. 491 runWithDomTree(*M, "br_same_dest", CFAllTerminatorsEager); 492 runWithDomTree(*M, "br_different_dest", CFAllTerminatorsEager); 493 runWithDomTree(*M, "switch_2_different_dest", CFAllTerminatorsEager); 494 runWithDomTree(*M, "switch_2_different_dest_default", CFAllTerminatorsEager); 495 runWithDomTree(*M, "switch_3_different_dest", CFAllTerminatorsEager); 496 runWithDomTree(*M, "switch_variable_2_default_dest", CFAllTerminatorsEager); 497 runWithDomTree(*M, "switch_constant_2_default_dest", CFAllTerminatorsEager); 498 runWithDomTree(*M, "switch_constant_3_repeated_dest", CFAllTerminatorsEager); 499 runWithDomTree(*M, "indirectbr", CFAllTerminatorsEager); 500 runWithDomTree(*M, "indirectbr_repeated", CFAllTerminatorsEager); 501 runWithDomTree(*M, "indirectbr_unreachable", CFAllTerminatorsEager); 502 503 // Test ConstantFoldTerminator under Lazy UpdateStrategy. 504 runWithDomTree(*M, "br_same_dest", CFAllTerminatorsLazy); 505 runWithDomTree(*M, "br_different_dest", CFAllTerminatorsLazy); 506 runWithDomTree(*M, "switch_2_different_dest", CFAllTerminatorsLazy); 507 runWithDomTree(*M, "switch_2_different_dest_default", CFAllTerminatorsLazy); 508 runWithDomTree(*M, "switch_3_different_dest", CFAllTerminatorsLazy); 509 runWithDomTree(*M, "switch_variable_2_default_dest", CFAllTerminatorsLazy); 510 runWithDomTree(*M, "switch_constant_2_default_dest", CFAllTerminatorsLazy); 511 runWithDomTree(*M, "switch_constant_3_repeated_dest", CFAllTerminatorsLazy); 512 runWithDomTree(*M, "indirectbr", CFAllTerminatorsLazy); 513 runWithDomTree(*M, "indirectbr_repeated", CFAllTerminatorsLazy); 514 runWithDomTree(*M, "indirectbr_unreachable", CFAllTerminatorsLazy); 515 } 516 517 struct SalvageDebugInfoTest : ::testing::Test { 518 LLVMContext C; 519 std::unique_ptr<Module> M; 520 Function *F = nullptr; 521 522 void SetUp() override { 523 // FIXME: PreserveInputDbgFormat is set to true because this test has 524 // been written to expect debug intrinsics rather than debug records; use 525 // the intrinsic format until we update the test checks. Note that the 526 // temporary setting of this flag only needs to cover the parsing step, not 527 // the test body itself. 528 auto SettingGuard = SaveDbgInfoFormat(); 529 PreserveInputDbgFormat = cl::boolOrDefault::BOU_TRUE; 530 531 M = parseIR(C, 532 R"( 533 define void @f() !dbg !8 { 534 entry: 535 %x = add i32 0, 1 536 %y = add i32 %x, 2 537 call void @llvm.dbg.value(metadata i32 %x, metadata !11, metadata !DIExpression()), !dbg !13 538 call void @llvm.dbg.value(metadata i32 %y, metadata !11, metadata !DIExpression()), !dbg !13 539 ret void, !dbg !14 540 } 541 declare void @llvm.dbg.value(metadata, metadata, metadata) 542 !llvm.dbg.cu = !{!0} 543 !llvm.module.flags = !{!3, !4} 544 !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 6.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2) 545 !1 = !DIFile(filename: "t2.c", directory: "foo") 546 !2 = !{} 547 !3 = !{i32 2, !"Dwarf Version", i32 4} 548 !4 = !{i32 2, !"Debug Info Version", i32 3} 549 !8 = distinct !DISubprogram(name: "f", scope: !1, file: !1, line: 1, type: !9, isLocal: false, isDefinition: true, scopeLine: 1, isOptimized: false, unit: !0, retainedNodes: !2) 550 !9 = !DISubroutineType(types: !10) 551 !10 = !{null} 552 !11 = !DILocalVariable(name: "x", scope: !8, file: !1, line: 2, type: !12) 553 !12 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) 554 !13 = !DILocation(line: 2, column: 7, scope: !8) 555 !14 = !DILocation(line: 3, column: 1, scope: !8) 556 )"); 557 558 auto *GV = M->getNamedValue("f"); 559 ASSERT_TRUE(GV); 560 F = dyn_cast<Function>(GV); 561 ASSERT_TRUE(F); 562 } 563 564 bool doesDebugValueDescribeX(const DbgValueInst &DI) { 565 if (DI.getNumVariableLocationOps() != 1u) 566 return false; 567 const auto &CI = *cast<ConstantInt>(DI.getValue(0)); 568 if (CI.isZero()) 569 return DI.getExpression()->getElements().equals( 570 {dwarf::DW_OP_plus_uconst, 1, dwarf::DW_OP_stack_value}); 571 else if (CI.isOneValue()) 572 return DI.getExpression()->getElements().empty(); 573 return false; 574 } 575 576 bool doesDebugValueDescribeY(const DbgValueInst &DI) { 577 if (DI.getNumVariableLocationOps() != 1u) 578 return false; 579 const auto &CI = *cast<ConstantInt>(DI.getVariableLocationOp(0)); 580 if (CI.isZero()) 581 return DI.getExpression()->getElements().equals( 582 {dwarf::DW_OP_plus_uconst, 1, dwarf::DW_OP_plus_uconst, 2, 583 dwarf::DW_OP_stack_value}); 584 else if (CI.isOneValue()) 585 return DI.getExpression()->getElements().equals( 586 {dwarf::DW_OP_plus_uconst, 2, dwarf::DW_OP_stack_value}); 587 return false; 588 } 589 590 void verifyDebugValuesAreSalvaged() { 591 // Check that the debug values for %x and %y are preserved. 592 bool FoundX = false; 593 bool FoundY = false; 594 for (const Instruction &I : F->front()) { 595 auto DI = dyn_cast<DbgValueInst>(&I); 596 if (!DI) { 597 // The function should only contain debug values and a terminator. 598 ASSERT_TRUE(I.isTerminator()); 599 continue; 600 } 601 EXPECT_EQ(DI->getVariable()->getName(), "x"); 602 FoundX |= doesDebugValueDescribeX(*DI); 603 FoundY |= doesDebugValueDescribeY(*DI); 604 } 605 ASSERT_TRUE(FoundX); 606 ASSERT_TRUE(FoundY); 607 } 608 }; 609 610 TEST_F(SalvageDebugInfoTest, RecursiveInstDeletion) { 611 Instruction *Inst = &F->front().front(); 612 Inst = Inst->getNextNode(); // Get %y = add ... 613 ASSERT_TRUE(Inst); 614 bool Deleted = RecursivelyDeleteTriviallyDeadInstructions(Inst); 615 ASSERT_TRUE(Deleted); 616 verifyDebugValuesAreSalvaged(); 617 } 618 619 TEST_F(SalvageDebugInfoTest, RecursiveBlockSimplification) { 620 BasicBlock *BB = &F->front(); 621 ASSERT_TRUE(BB); 622 bool Deleted = SimplifyInstructionsInBlock(BB); 623 ASSERT_TRUE(Deleted); 624 verifyDebugValuesAreSalvaged(); 625 } 626 627 TEST(Local, wouldInstructionBeTriviallyDead) { 628 LLVMContext Ctx; 629 // FIXME: PreserveInputDbgFormat is set to true because this test has 630 // been written to expect debug intrinsics rather than debug records. 631 // TODO: This test doesn't have a DbgRecord equivalent form so delete 632 // it when debug intrinsics are removed. 633 auto SettingGuard = SaveDbgInfoFormat(); 634 PreserveInputDbgFormat = cl::boolOrDefault::BOU_TRUE; 635 std::unique_ptr<Module> M = parseIR(Ctx, 636 R"( 637 define dso_local void @fun() local_unnamed_addr #0 !dbg !9 { 638 entry: 639 call void @llvm.dbg.declare(metadata !{}, metadata !13, metadata !DIExpression()), !dbg !16 640 ret void, !dbg !16 641 } 642 643 declare void @llvm.dbg.declare(metadata, metadata, metadata) 644 645 !llvm.dbg.cu = !{!0} 646 !llvm.module.flags = !{!2, !3} 647 !llvm.ident = !{!8} 648 649 !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 16.0.0", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, splitDebugInlining: false, nameTableKind: None) 650 !1 = !DIFile(filename: "test.c", directory: "/") 651 !2 = !{i32 7, !"Dwarf Version", i32 5} 652 !3 = !{i32 2, !"Debug Info Version", i32 3} 653 !8 = !{!"clang version 16.0.0"} 654 !9 = distinct !DISubprogram(name: "fun", scope: !1, file: !1, line: 1, type: !10, scopeLine: 1, flags: DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !12) 655 !10 = !DISubroutineType(types: !11) 656 !11 = !{null} 657 !12 = !{!13} 658 !13 = !DILocalVariable(name: "a", scope: !9, file: !1, line: 1, type: !14) 659 !14 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) 660 !16 = !DILocation(line: 1, column: 21, scope: !9) 661 )"); 662 bool BrokenDebugInfo = true; 663 verifyModule(*M, &errs(), &BrokenDebugInfo); 664 ASSERT_FALSE(BrokenDebugInfo); 665 666 // Get the dbg.declare. 667 Function &F = *cast<Function>(M->getNamedValue("fun")); 668 Instruction *DbgDeclare = &F.front().front(); 669 ASSERT_TRUE(isa<DbgDeclareInst>(DbgDeclare)); 670 // Debug intrinsics with empty metadata arguments are not dead. 671 EXPECT_FALSE(wouldInstructionBeTriviallyDead(DbgDeclare)); 672 } 673 674 TEST(Local, ChangeToUnreachable) { 675 LLVMContext Ctx; 676 677 std::unique_ptr<Module> M = parseIR(Ctx, 678 R"( 679 define internal void @foo() !dbg !6 { 680 entry: 681 ret void, !dbg !8 682 } 683 684 !llvm.dbg.cu = !{!0} 685 !llvm.debugify = !{!3, !4} 686 !llvm.module.flags = !{!5} 687 688 !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2) 689 !1 = !DIFile(filename: "test.ll", directory: "/") 690 !2 = !{} 691 !3 = !{i32 1} 692 !4 = !{i32 0} 693 !5 = !{i32 2, !"Debug Info Version", i32 3} 694 !6 = distinct !DISubprogram(name: "foo", linkageName: "foo", scope: null, file: !1, line: 1, type: !7, isLocal: true, isDefinition: true, scopeLine: 1, isOptimized: true, unit: !0, retainedNodes: !2) 695 !7 = !DISubroutineType(types: !2) 696 !8 = !DILocation(line: 1, column: 1, scope: !6) 697 )"); 698 699 bool BrokenDebugInfo = true; 700 verifyModule(*M, &errs(), &BrokenDebugInfo); 701 ASSERT_FALSE(BrokenDebugInfo); 702 703 Function &F = *cast<Function>(M->getNamedValue("foo")); 704 705 BasicBlock &BB = F.front(); 706 Instruction &A = BB.front(); 707 DebugLoc DLA = A.getDebugLoc(); 708 709 ASSERT_TRUE(isa<ReturnInst>(&A)); 710 // One instruction should be affected. 711 EXPECT_EQ(changeToUnreachable(&A), 1U); 712 713 Instruction &B = BB.front(); 714 715 // There should be an uncreachable instruction. 716 ASSERT_TRUE(isa<UnreachableInst>(&B)); 717 718 DebugLoc DLB = B.getDebugLoc(); 719 EXPECT_EQ(DLA, DLB); 720 } 721 722 TEST(Local, FindDbgUsers) { 723 LLVMContext Ctx; 724 // FIXME: PreserveInputDbgFormat is set to true because this test has 725 // been written to expect debug intrinsics rather than debug records; use the 726 // intrinsic format until we update the test checks. 727 auto SettingGuard = SaveDbgInfoFormat(); 728 PreserveInputDbgFormat = cl::boolOrDefault::BOU_TRUE; 729 std::unique_ptr<Module> M = parseIR(Ctx, 730 R"( 731 define dso_local void @fun(ptr %a) #0 !dbg !11 { 732 entry: 733 call void @llvm.dbg.assign(metadata ptr %a, metadata !16, metadata !DIExpression(), metadata !15, metadata ptr %a, metadata !DIExpression()), !dbg !19 734 ret void 735 } 736 737 declare void @llvm.dbg.assign(metadata, metadata, metadata, metadata, metadata, metadata) 738 739 !llvm.dbg.cu = !{!0} 740 !llvm.module.flags = !{!2, !3, !9} 741 !llvm.ident = !{!10} 742 743 !0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus_14, file: !1, producer: "clang version 17.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, splitDebugInlining: false, nameTableKind: None) 744 !1 = !DIFile(filename: "test.cpp", directory: "/") 745 !2 = !{i32 7, !"Dwarf Version", i32 5} 746 !3 = !{i32 2, !"Debug Info Version", i32 3} 747 !4 = !{i32 1, !"wchar_size", i32 4} 748 !9 = !{i32 7, !"debug-info-assignment-tracking", i1 true} 749 !10 = !{!"clang version 17.0.0"} 750 !11 = distinct !DISubprogram(name: "fun", linkageName: "fun", scope: !1, file: !1, line: 1, type: !12, scopeLine: 1, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !14) 751 !12 = !DISubroutineType(types: !13) 752 !13 = !{null} 753 !14 = !{} 754 !15 = distinct !DIAssignID() 755 !16 = !DILocalVariable(name: "x", scope: !11, file: !1, line: 2, type: !17) 756 !17 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !18, size: 64) 757 !18 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) 758 !19 = !DILocation(line: 0, scope: !11) 759 )"); 760 761 bool BrokenDebugInfo = true; 762 verifyModule(*M, &errs(), &BrokenDebugInfo); 763 ASSERT_FALSE(BrokenDebugInfo); 764 765 Function &Fun = *cast<Function>(M->getNamedValue("fun")); 766 Value *Arg = Fun.getArg(0); 767 768 SmallVector<DbgVariableIntrinsic *> Users; 769 // Arg (%a) is used twice by a single dbg.assign. Check findDbgUsers returns 770 // only 1 pointer to it rather than 2. 771 findDbgUsers(Users, Arg); 772 EXPECT_EQ(Users.size(), 1u); 773 774 SmallVector<DbgValueInst *> Vals; 775 // Arg (%a) is used twice by a single dbg.assign. Check findDbgValues returns 776 // only 1 pointer to it rather than 2. 777 findDbgValues(Vals, Arg); 778 EXPECT_EQ(Vals.size(), 1u); 779 } 780 781 TEST(Local, FindDbgRecords) { 782 // DbgRecord copy of the FindDbgUsers test above. 783 LLVMContext Ctx; 784 std::unique_ptr<Module> M = parseIR(Ctx, 785 R"( 786 define dso_local void @fun(ptr %a) #0 !dbg !11 { 787 entry: 788 call void @llvm.dbg.assign(metadata ptr %a, metadata !16, metadata !DIExpression(), metadata !15, metadata ptr %a, metadata !DIExpression()), !dbg !19 789 ret void 790 } 791 792 !llvm.dbg.cu = !{!0} 793 !llvm.module.flags = !{!2, !3, !9} 794 !llvm.ident = !{!10} 795 796 !0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus_14, file: !1, producer: "clang version 17.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, splitDebugInlining: false, nameTableKind: None) 797 !1 = !DIFile(filename: "test.cpp", directory: "/") 798 !2 = !{i32 7, !"Dwarf Version", i32 5} 799 !3 = !{i32 2, !"Debug Info Version", i32 3} 800 !4 = !{i32 1, !"wchar_size", i32 4} 801 !9 = !{i32 7, !"debug-info-assignment-tracking", i1 true} 802 !10 = !{!"clang version 17.0.0"} 803 !11 = distinct !DISubprogram(name: "fun", linkageName: "fun", scope: !1, file: !1, line: 1, type: !12, scopeLine: 1, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !14) 804 !12 = !DISubroutineType(types: !13) 805 !13 = !{null} 806 !14 = !{} 807 !15 = distinct !DIAssignID() 808 !16 = !DILocalVariable(name: "x", scope: !11, file: !1, line: 2, type: !17) 809 !17 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !18, size: 64) 810 !18 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) 811 !19 = !DILocation(line: 0, scope: !11) 812 )"); 813 814 bool BrokenDebugInfo = true; 815 verifyModule(*M, &errs(), &BrokenDebugInfo); 816 ASSERT_FALSE(BrokenDebugInfo); 817 818 Function &Fun = *cast<Function>(M->getNamedValue("fun")); 819 Value *Arg = Fun.getArg(0); 820 821 SmallVector<DbgVariableIntrinsic *> Users; 822 SmallVector<DbgVariableRecord *> Records; 823 // Arg (%a) is used twice by a single dbg_assign. Check findDbgUsers returns 824 // only 1 pointer to it rather than 2. 825 findDbgUsers(Users, Arg, &Records); 826 EXPECT_EQ(Users.size(), 0u); 827 EXPECT_EQ(Records.size(), 1u); 828 829 SmallVector<DbgValueInst *> Vals; 830 Records.clear(); 831 // Arg (%a) is used twice by a single dbg_assign. Check findDbgValues returns 832 // only 1 pointer to it rather than 2. 833 findDbgValues(Vals, Arg, &Records); 834 EXPECT_EQ(Vals.size(), 0u); 835 EXPECT_EQ(Records.size(), 1u); 836 } 837 838 TEST(Local, ReplaceAllDbgUsesWith) { 839 using namespace llvm::dwarf; 840 841 LLVMContext Ctx; 842 // FIXME: PreserveInputDbgFormat is set to true because this test has 843 // been written to expect debug intrinsics rather than debug records; use the 844 // intrinsic format until we update the test checks. 845 auto SettingGuard = SaveDbgInfoFormat(); 846 PreserveInputDbgFormat = cl::boolOrDefault::BOU_TRUE; 847 848 // Note: The datalayout simulates Darwin/x86_64. 849 std::unique_ptr<Module> M = parseIR(Ctx, 850 R"( 851 target datalayout = "e-m:o-i63:64-f80:128-n8:16:32:64-S128" 852 853 declare i32 @escape(i32) 854 855 define void @f() !dbg !6 { 856 entry: 857 %a = add i32 0, 1, !dbg !15 858 call void @llvm.dbg.value(metadata i32 %a, metadata !9, metadata !DIExpression()), !dbg !15 859 860 %b = add i64 0, 1, !dbg !16 861 call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression()), !dbg !16 862 call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_lit0, DW_OP_mul)), !dbg !16 863 call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_lit0, DW_OP_mul, DW_OP_stack_value)), !dbg !16 864 call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_LLVM_fragment, 0, 8)), !dbg !16 865 call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_lit0, DW_OP_mul, DW_OP_LLVM_fragment, 0, 8)), !dbg !16 866 call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_lit0, DW_OP_mul, DW_OP_stack_value, DW_OP_LLVM_fragment, 0, 8)), !dbg !16 867 868 %c = inttoptr i64 0 to i64*, !dbg !17 869 call void @llvm.dbg.declare(metadata i64* %c, metadata !13, metadata !DIExpression()), !dbg !17 870 871 %d = inttoptr i64 0 to i32*, !dbg !18 872 call void @llvm.dbg.declare(metadata i32* %d, metadata !20, metadata !DIExpression()), !dbg !18 873 874 %e = add <2 x i16> zeroinitializer, zeroinitializer 875 call void @llvm.dbg.value(metadata <2 x i16> %e, metadata !14, metadata !DIExpression()), !dbg !18 876 877 %f = call i32 @escape(i32 0) 878 call void @llvm.dbg.value(metadata i32 %f, metadata !9, metadata !DIExpression()), !dbg !15 879 880 %barrier = call i32 @escape(i32 0) 881 882 %g = call i32 @escape(i32 %f) 883 call void @llvm.dbg.value(metadata i32 %g, metadata !9, metadata !DIExpression()), !dbg !15 884 885 ret void, !dbg !19 886 } 887 888 declare void @llvm.dbg.declare(metadata, metadata, metadata) 889 declare void @llvm.dbg.value(metadata, metadata, metadata) 890 891 !llvm.dbg.cu = !{!0} 892 !llvm.module.flags = !{!5} 893 894 !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2) 895 !1 = !DIFile(filename: "/Users/vsk/Desktop/foo.ll", directory: "/") 896 !2 = !{} 897 !5 = !{i32 2, !"Debug Info Version", i32 3} 898 !6 = distinct !DISubprogram(name: "f", linkageName: "f", scope: null, file: !1, line: 1, type: !7, isLocal: false, isDefinition: true, scopeLine: 1, isOptimized: true, unit: !0, retainedNodes: !8) 899 !7 = !DISubroutineType(types: !2) 900 !8 = !{!9, !11, !13, !14} 901 !9 = !DILocalVariable(name: "1", scope: !6, file: !1, line: 1, type: !10) 902 !10 = !DIBasicType(name: "ty32", size: 32, encoding: DW_ATE_signed) 903 !11 = !DILocalVariable(name: "2", scope: !6, file: !1, line: 2, type: !12) 904 !12 = !DIBasicType(name: "ty64", size: 64, encoding: DW_ATE_signed) 905 !13 = !DILocalVariable(name: "3", scope: !6, file: !1, line: 3, type: !12) 906 !14 = !DILocalVariable(name: "4", scope: !6, file: !1, line: 4, type: !10) 907 !15 = !DILocation(line: 1, column: 1, scope: !6) 908 !16 = !DILocation(line: 2, column: 1, scope: !6) 909 !17 = !DILocation(line: 3, column: 1, scope: !6) 910 !18 = !DILocation(line: 4, column: 1, scope: !6) 911 !19 = !DILocation(line: 5, column: 1, scope: !6) 912 !20 = !DILocalVariable(name: "5", scope: !6, file: !1, line: 5, type: !10) 913 )"); 914 915 bool BrokenDebugInfo = true; 916 verifyModule(*M, &errs(), &BrokenDebugInfo); 917 ASSERT_FALSE(BrokenDebugInfo); 918 919 Function &F = *cast<Function>(M->getNamedValue("f")); 920 DominatorTree DT{F}; 921 922 BasicBlock &BB = F.front(); 923 Instruction &A = BB.front(); 924 Instruction &B = *A.getNextNonDebugInstruction(); 925 Instruction &C = *B.getNextNonDebugInstruction(); 926 Instruction &D = *C.getNextNonDebugInstruction(); 927 Instruction &E = *D.getNextNonDebugInstruction(); 928 Instruction &F_ = *E.getNextNonDebugInstruction(); 929 Instruction &Barrier = *F_.getNextNonDebugInstruction(); 930 Instruction &G = *Barrier.getNextNonDebugInstruction(); 931 932 // Simulate i32 <-> i64* conversion. Expect no updates: the datalayout says 933 // pointers are 64 bits, so the conversion would be lossy. 934 EXPECT_FALSE(replaceAllDbgUsesWith(A, C, C, DT)); 935 EXPECT_FALSE(replaceAllDbgUsesWith(C, A, A, DT)); 936 937 // Simulate i32 <-> <2 x i16> conversion. This is unsupported. 938 EXPECT_FALSE(replaceAllDbgUsesWith(E, A, A, DT)); 939 EXPECT_FALSE(replaceAllDbgUsesWith(A, E, E, DT)); 940 941 // Simulate i32* <-> i64* conversion. 942 EXPECT_TRUE(replaceAllDbgUsesWith(D, C, C, DT)); 943 944 SmallVector<DbgVariableIntrinsic *, 2> CDbgVals; 945 findDbgUsers(CDbgVals, &C); 946 EXPECT_EQ(2U, CDbgVals.size()); 947 EXPECT_TRUE(all_of(CDbgVals, [](DbgVariableIntrinsic *DII) { 948 return isa<DbgDeclareInst>(DII); 949 })); 950 951 EXPECT_TRUE(replaceAllDbgUsesWith(C, D, D, DT)); 952 953 SmallVector<DbgVariableIntrinsic *, 2> DDbgVals; 954 findDbgUsers(DDbgVals, &D); 955 EXPECT_EQ(2U, DDbgVals.size()); 956 EXPECT_TRUE(all_of(DDbgVals, [](DbgVariableIntrinsic *DII) { 957 return isa<DbgDeclareInst>(DII); 958 })); 959 960 // Introduce a use-before-def. Check that the dbg.value for %a is salvaged. 961 EXPECT_TRUE(replaceAllDbgUsesWith(A, F_, F_, DT)); 962 963 auto *ADbgVal = cast<DbgValueInst>(A.getNextNode()); 964 EXPECT_EQ(ADbgVal->getNumVariableLocationOps(), 1u); 965 EXPECT_EQ(ConstantInt::get(A.getType(), 0), ADbgVal->getVariableLocationOp(0)); 966 967 // Introduce a use-before-def. Check that the dbg.values for %f become undef. 968 EXPECT_TRUE(replaceAllDbgUsesWith(F_, G, G, DT)); 969 970 auto *FDbgVal = cast<DbgValueInst>(F_.getNextNode()); 971 EXPECT_EQ(FDbgVal->getNumVariableLocationOps(), 1u); 972 EXPECT_TRUE(FDbgVal->isKillLocation()); 973 974 SmallVector<DbgValueInst *, 1> FDbgVals; 975 findDbgValues(FDbgVals, &F_); 976 EXPECT_EQ(0U, FDbgVals.size()); 977 978 // Simulate i32 -> i64 conversion to test sign-extension. Here are some 979 // interesting cases to handle: 980 // 1) debug user has empty DIExpression 981 // 2) debug user has non-empty, non-stack-value'd DIExpression 982 // 3) debug user has non-empty, stack-value'd DIExpression 983 // 4-6) like (1-3), but with a fragment 984 EXPECT_TRUE(replaceAllDbgUsesWith(B, A, A, DT)); 985 986 SmallVector<DbgValueInst *, 8> ADbgVals; 987 findDbgValues(ADbgVals, &A); 988 EXPECT_EQ(6U, ADbgVals.size()); 989 990 // Check that %a has a dbg.value with a DIExpression matching \p Ops. 991 auto hasADbgVal = [&](ArrayRef<uint64_t> Ops) { 992 return any_of(ADbgVals, [&](DbgValueInst *DVI) { 993 assert(DVI->getVariable()->getName() == "2"); 994 return DVI->getExpression()->getElements() == Ops; 995 }); 996 }; 997 998 // Case 1: The original expr is empty, so no deref is needed. 999 EXPECT_TRUE(hasADbgVal({DW_OP_LLVM_convert, 32, DW_ATE_signed, 1000 DW_OP_LLVM_convert, 64, DW_ATE_signed, 1001 DW_OP_stack_value})); 1002 1003 // Case 2: Perform an address calculation with the original expr, deref it, 1004 // then sign-extend the result. 1005 EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_deref, 1006 DW_OP_LLVM_convert, 32, DW_ATE_signed, 1007 DW_OP_LLVM_convert, 64, DW_ATE_signed, 1008 DW_OP_stack_value})); 1009 1010 // Case 3: Insert the sign-extension logic before the DW_OP_stack_value. 1011 EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_LLVM_convert, 32, 1012 DW_ATE_signed, DW_OP_LLVM_convert, 64, DW_ATE_signed, 1013 DW_OP_stack_value})); 1014 1015 // Cases 4-6: Just like cases 1-3, but preserve the fragment at the end. 1016 EXPECT_TRUE(hasADbgVal({DW_OP_LLVM_convert, 32, DW_ATE_signed, 1017 DW_OP_LLVM_convert, 64, DW_ATE_signed, 1018 DW_OP_stack_value, DW_OP_LLVM_fragment, 0, 8})); 1019 1020 EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_deref, 1021 DW_OP_LLVM_convert, 32, DW_ATE_signed, 1022 DW_OP_LLVM_convert, 64, DW_ATE_signed, 1023 DW_OP_stack_value, DW_OP_LLVM_fragment, 0, 8})); 1024 1025 EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_LLVM_convert, 32, 1026 DW_ATE_signed, DW_OP_LLVM_convert, 64, DW_ATE_signed, 1027 DW_OP_stack_value, DW_OP_LLVM_fragment, 0, 8})); 1028 1029 verifyModule(*M, &errs(), &BrokenDebugInfo); 1030 ASSERT_FALSE(BrokenDebugInfo); 1031 } 1032 1033 TEST(Local, RemoveUnreachableBlocks) { 1034 LLVMContext C; 1035 1036 std::unique_ptr<Module> M = parseIR(C, 1037 R"( 1038 define void @br_simple() { 1039 entry: 1040 br label %bb0 1041 bb0: 1042 ret void 1043 bb1: 1044 ret void 1045 } 1046 1047 define void @br_self_loop() { 1048 entry: 1049 br label %bb0 1050 bb0: 1051 br i1 true, label %bb1, label %bb0 1052 bb1: 1053 br i1 true, label %bb0, label %bb2 1054 bb2: 1055 br label %bb2 1056 } 1057 1058 define void @br_constant() { 1059 entry: 1060 br label %bb0 1061 bb0: 1062 br i1 true, label %bb1, label %bb2 1063 bb1: 1064 br i1 true, label %bb0, label %bb2 1065 bb2: 1066 br label %bb2 1067 } 1068 1069 define void @br_loop() { 1070 entry: 1071 br label %bb0 1072 bb0: 1073 br label %bb0 1074 bb1: 1075 br label %bb2 1076 bb2: 1077 br label %bb1 1078 } 1079 1080 declare i32 @__gxx_personality_v0(...) 1081 1082 define void @invoke_terminator() personality i8* bitcast (i32 (...)* @__gxx_personality_v0 to i8*) { 1083 entry: 1084 br i1 undef, label %invoke.block, label %exit 1085 1086 invoke.block: 1087 %cond = invoke zeroext i1 @invokable() 1088 to label %continue.block unwind label %lpad.block 1089 1090 continue.block: 1091 br i1 %cond, label %if.then, label %if.end 1092 1093 if.then: 1094 unreachable 1095 1096 if.end: 1097 unreachable 1098 1099 lpad.block: 1100 %lp = landingpad { i8*, i32 } 1101 catch i8* null 1102 br label %exit 1103 1104 exit: 1105 ret void 1106 } 1107 1108 declare i1 @invokable() 1109 )"); 1110 1111 auto runEager = [&](Function &F, DominatorTree *DT) { 1112 PostDominatorTree PDT = PostDominatorTree(F); 1113 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager); 1114 removeUnreachableBlocks(F, &DTU); 1115 EXPECT_TRUE(DTU.getDomTree().verify()); 1116 EXPECT_TRUE(DTU.getPostDomTree().verify()); 1117 }; 1118 1119 auto runLazy = [&](Function &F, DominatorTree *DT) { 1120 PostDominatorTree PDT = PostDominatorTree(F); 1121 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy); 1122 removeUnreachableBlocks(F, &DTU); 1123 EXPECT_TRUE(DTU.getDomTree().verify()); 1124 EXPECT_TRUE(DTU.getPostDomTree().verify()); 1125 }; 1126 1127 // Test removeUnreachableBlocks under Eager UpdateStrategy. 1128 runWithDomTree(*M, "br_simple", runEager); 1129 runWithDomTree(*M, "br_self_loop", runEager); 1130 runWithDomTree(*M, "br_constant", runEager); 1131 runWithDomTree(*M, "br_loop", runEager); 1132 runWithDomTree(*M, "invoke_terminator", runEager); 1133 1134 // Test removeUnreachableBlocks under Lazy UpdateStrategy. 1135 runWithDomTree(*M, "br_simple", runLazy); 1136 runWithDomTree(*M, "br_self_loop", runLazy); 1137 runWithDomTree(*M, "br_constant", runLazy); 1138 runWithDomTree(*M, "br_loop", runLazy); 1139 runWithDomTree(*M, "invoke_terminator", runLazy); 1140 1141 M = parseIR(C, 1142 R"( 1143 define void @f() { 1144 entry: 1145 ret void 1146 bb0: 1147 ret void 1148 } 1149 )"); 1150 1151 auto checkRUBlocksRetVal = [&](Function &F, DominatorTree *DT) { 1152 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy); 1153 EXPECT_TRUE(removeUnreachableBlocks(F, &DTU)); 1154 EXPECT_FALSE(removeUnreachableBlocks(F, &DTU)); 1155 EXPECT_TRUE(DTU.getDomTree().verify()); 1156 }; 1157 1158 runWithDomTree(*M, "f", checkRUBlocksRetVal); 1159 } 1160 1161 TEST(Local, SimplifyCFGWithNullAC) { 1162 LLVMContext Ctx; 1163 1164 std::unique_ptr<Module> M = parseIR(Ctx, R"( 1165 declare void @true_path() 1166 declare void @false_path() 1167 declare void @llvm.assume(i1 %cond); 1168 1169 define i32 @foo(i1, i32) { 1170 entry: 1171 %cmp = icmp sgt i32 %1, 0 1172 br i1 %cmp, label %if.bb1, label %then.bb1 1173 if.bb1: 1174 call void @true_path() 1175 br label %test.bb 1176 then.bb1: 1177 call void @false_path() 1178 br label %test.bb 1179 test.bb: 1180 %phi = phi i1 [1, %if.bb1], [%0, %then.bb1] 1181 call void @llvm.assume(i1 %0) 1182 br i1 %phi, label %if.bb2, label %then.bb2 1183 if.bb2: 1184 ret i32 %1 1185 then.bb2: 1186 ret i32 0 1187 } 1188 )"); 1189 1190 Function &F = *cast<Function>(M->getNamedValue("foo")); 1191 TargetTransformInfo TTI(M->getDataLayout()); 1192 1193 SimplifyCFGOptions Options{}; 1194 Options.setAssumptionCache(nullptr); 1195 1196 // Obtain BasicBlock of interest to this test, %test.bb. 1197 BasicBlock *TestBB = nullptr; 1198 for (BasicBlock &BB : F) { 1199 if (BB.getName().equals("test.bb")) { 1200 TestBB = &BB; 1201 break; 1202 } 1203 } 1204 ASSERT_TRUE(TestBB); 1205 1206 DominatorTree DT(F); 1207 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 1208 1209 // %test.bb is expected to be simplified by FoldCondBranchOnPHI. 1210 EXPECT_TRUE(simplifyCFG(TestBB, TTI, 1211 RequireAndPreserveDomTree ? &DTU : nullptr, Options)); 1212 } 1213 1214 TEST(Local, CanReplaceOperandWithVariable) { 1215 LLVMContext Ctx; 1216 Module M("test_module", Ctx); 1217 IRBuilder<> B(Ctx); 1218 1219 FunctionType *FnType = 1220 FunctionType::get(Type::getVoidTy(Ctx), {}, false); 1221 1222 FunctionType *VarArgFnType = 1223 FunctionType::get(Type::getVoidTy(Ctx), {B.getInt32Ty()}, true); 1224 1225 Function *TestBody = Function::Create(FnType, GlobalValue::ExternalLinkage, 1226 0, "", &M); 1227 1228 BasicBlock *BB0 = BasicBlock::Create(Ctx, "", TestBody); 1229 B.SetInsertPoint(BB0); 1230 1231 FunctionCallee Intrin = M.getOrInsertFunction("llvm.foo", FnType); 1232 FunctionCallee Func = M.getOrInsertFunction("foo", FnType); 1233 FunctionCallee VarArgFunc 1234 = M.getOrInsertFunction("foo.vararg", VarArgFnType); 1235 FunctionCallee VarArgIntrin 1236 = M.getOrInsertFunction("llvm.foo.vararg", VarArgFnType); 1237 1238 auto *CallToIntrin = B.CreateCall(Intrin); 1239 auto *CallToFunc = B.CreateCall(Func); 1240 1241 // Test if it's valid to replace the callee operand. 1242 EXPECT_FALSE(canReplaceOperandWithVariable(CallToIntrin, 0)); 1243 EXPECT_TRUE(canReplaceOperandWithVariable(CallToFunc, 0)); 1244 1245 // That it's invalid to replace an argument in the variadic argument list for 1246 // an intrinsic, but OK for a normal function. 1247 auto *CallToVarArgFunc = B.CreateCall( 1248 VarArgFunc, {B.getInt32(0), B.getInt32(1), B.getInt32(2)}); 1249 EXPECT_TRUE(canReplaceOperandWithVariable(CallToVarArgFunc, 0)); 1250 EXPECT_TRUE(canReplaceOperandWithVariable(CallToVarArgFunc, 1)); 1251 EXPECT_TRUE(canReplaceOperandWithVariable(CallToVarArgFunc, 2)); 1252 EXPECT_TRUE(canReplaceOperandWithVariable(CallToVarArgFunc, 3)); 1253 1254 auto *CallToVarArgIntrin = B.CreateCall( 1255 VarArgIntrin, {B.getInt32(0), B.getInt32(1), B.getInt32(2)}); 1256 EXPECT_TRUE(canReplaceOperandWithVariable(CallToVarArgIntrin, 0)); 1257 EXPECT_FALSE(canReplaceOperandWithVariable(CallToVarArgIntrin, 1)); 1258 EXPECT_FALSE(canReplaceOperandWithVariable(CallToVarArgIntrin, 2)); 1259 EXPECT_FALSE(canReplaceOperandWithVariable(CallToVarArgIntrin, 3)); 1260 1261 // Test that it's invalid to replace gcroot operands, even though it can't use 1262 // immarg. 1263 Type *PtrPtr = B.getPtrTy(0); 1264 Value *Alloca = B.CreateAlloca(PtrPtr, (unsigned)0); 1265 CallInst *GCRoot = B.CreateIntrinsic(Intrinsic::gcroot, {}, 1266 {Alloca, Constant::getNullValue(PtrPtr)}); 1267 EXPECT_TRUE(canReplaceOperandWithVariable(GCRoot, 0)); // Alloca 1268 EXPECT_FALSE(canReplaceOperandWithVariable(GCRoot, 1)); 1269 EXPECT_FALSE(canReplaceOperandWithVariable(GCRoot, 2)); 1270 1271 BB0->dropAllReferences(); 1272 } 1273 1274 TEST(Local, ExpressionForConstant) { 1275 LLVMContext Context; 1276 Module M("test_module", Context); 1277 DIBuilder DIB(M); 1278 DIExpression *Expr = nullptr; 1279 1280 auto createExpression = [&](Constant *C, Type *Ty) -> DIExpression * { 1281 EXPECT_NE(C, nullptr); 1282 EXPECT_NE(Ty, nullptr); 1283 EXPECT_EQ(C->getType(), Ty); 1284 std::unique_ptr<GlobalVariable> GV = std::make_unique<GlobalVariable>( 1285 Ty, false, GlobalValue::ExternalLinkage, C, "GV"); 1286 EXPECT_NE(GV, nullptr); 1287 1288 DIExpression *Expr = getExpressionForConstant(DIB, *GV->getInitializer(), 1289 *GV->getValueType()); 1290 if (Expr) { 1291 EXPECT_EQ(Expr->getNumElements(), 3u); 1292 EXPECT_EQ(Expr->getElement(0), dwarf::DW_OP_constu); 1293 EXPECT_EQ(Expr->getElement(2), dwarf::DW_OP_stack_value); 1294 } 1295 return Expr; 1296 }; 1297 1298 // Integer. 1299 IntegerType *Int1Ty = Type::getInt1Ty(Context); 1300 Expr = createExpression(ConstantInt::getTrue(Context), Int1Ty); 1301 EXPECT_NE(Expr, nullptr); 1302 EXPECT_EQ(Expr->getElement(1), 18446744073709551615U); 1303 1304 Expr = createExpression(ConstantInt::getFalse(Context), Int1Ty); 1305 EXPECT_NE(Expr, nullptr); 1306 EXPECT_EQ(Expr->getElement(1), 0U); 1307 1308 IntegerType *Int8Ty = Type::getInt8Ty(Context); 1309 Expr = createExpression(ConstantInt::get(Int8Ty, 100), Int8Ty); 1310 EXPECT_NE(Expr, nullptr); 1311 EXPECT_EQ(Expr->getElement(1), 100U); 1312 1313 IntegerType *Int16Ty = Type::getInt16Ty(Context); 1314 Expr = createExpression(ConstantInt::getSigned(Int16Ty, -50), Int16Ty); 1315 EXPECT_NE(Expr, nullptr); 1316 EXPECT_EQ(Expr->getElement(1), -50ULL); 1317 1318 IntegerType *Int32Ty = Type::getInt32Ty(Context); 1319 Expr = createExpression(ConstantInt::get(Int32Ty, 0x7FFFFFFF), Int32Ty); 1320 EXPECT_NE(Expr, nullptr); 1321 EXPECT_EQ(Expr->getElement(1), 0x7FFFFFFFU); 1322 1323 IntegerType *Int64Ty = Type::getInt64Ty(Context); 1324 Expr = 1325 createExpression(ConstantInt::get(Int64Ty, 0x7FFFFFFFFFFFFFFF), Int64Ty); 1326 EXPECT_NE(Expr, nullptr); 1327 EXPECT_EQ(Expr->getElement(1), 0x7FFFFFFFFFFFFFFFU); 1328 1329 IntegerType *Int128Ty = Type::getInt128Ty(Context); 1330 Expr = createExpression(ConstantInt::get(Int128Ty, 0x7FFFFFFFFFFFFFFF), 1331 Int128Ty); 1332 EXPECT_NE(Expr, nullptr); 1333 EXPECT_EQ(Expr->getElement(1), 0x7FFFFFFFFFFFFFFFU); 1334 1335 GlobalVariable *String = 1336 IRBuilder<>(Context).CreateGlobalString("hello", "hello", 0, &M); 1337 Expr = createExpression(ConstantExpr::getPtrToInt(String, Int32Ty), Int32Ty); 1338 EXPECT_EQ(Expr, nullptr); 1339 1340 // Float. 1341 Type *FloatTy = Type::getFloatTy(Context); 1342 Expr = createExpression(ConstantFP::get(FloatTy, 5.55), FloatTy); 1343 EXPECT_NE(Expr, nullptr); 1344 EXPECT_EQ(Expr->getElement(1), 1085381018U); 1345 1346 // Double. 1347 Type *DoubleTy = Type::getDoubleTy(Context); 1348 Expr = createExpression(ConstantFP::get(DoubleTy, -5.55), DoubleTy); 1349 EXPECT_NE(Expr, nullptr); 1350 EXPECT_EQ(Expr->getElement(1), 13841306799765140275U); 1351 1352 // Half. 1353 Type *HalfTy = Type::getHalfTy(Context); 1354 Expr = createExpression(ConstantFP::get(HalfTy, 5.55), HalfTy); 1355 EXPECT_NE(Expr, nullptr); 1356 EXPECT_EQ(Expr->getElement(1), 17805U); 1357 1358 // BFloat. 1359 Type *BFloatTy = Type::getBFloatTy(Context); 1360 Expr = createExpression(ConstantFP::get(BFloatTy, -5.55), BFloatTy); 1361 EXPECT_NE(Expr, nullptr); 1362 EXPECT_EQ(Expr->getElement(1), 49330U); 1363 1364 // Pointer. 1365 PointerType *PtrTy = PointerType::get(Context, 0); 1366 Expr = createExpression(ConstantPointerNull::get(PtrTy), PtrTy); 1367 EXPECT_NE(Expr, nullptr); 1368 EXPECT_EQ(Expr->getElement(1), 0U); 1369 1370 ConstantInt *K1 = ConstantInt::get(Type::getInt32Ty(Context), 1234); 1371 Expr = createExpression(ConstantExpr::getIntToPtr(K1, PtrTy), PtrTy); 1372 EXPECT_NE(Expr, nullptr); 1373 EXPECT_EQ(Expr->getElement(1), 1234U); 1374 1375 ConstantInt *K2 = ConstantInt::get(Type::getInt64Ty(Context), 5678); 1376 Expr = createExpression(ConstantExpr::getIntToPtr(K2, PtrTy), PtrTy); 1377 EXPECT_NE(Expr, nullptr); 1378 EXPECT_EQ(Expr->getElement(1), 5678U); 1379 1380 Type *FP128Ty = Type::getFP128Ty(Context); 1381 Expr = createExpression(ConstantFP::get(FP128Ty, 32), FP128Ty); 1382 EXPECT_EQ(Expr, nullptr); 1383 1384 Type *X86_FP80Ty = Type::getX86_FP80Ty(Context); 1385 Expr = createExpression(ConstantFP::get(X86_FP80Ty, 32), X86_FP80Ty); 1386 EXPECT_EQ(Expr, nullptr); 1387 1388 Type *PPC_FP128Ty = Type::getPPC_FP128Ty(Context); 1389 Expr = createExpression(ConstantFP::get(PPC_FP128Ty, 32), PPC_FP128Ty); 1390 EXPECT_EQ(Expr, nullptr); 1391 } 1392 1393 TEST(Local, ReplaceDbgVariableRecord) { 1394 LLVMContext C; 1395 // FIXME: PreserveInputDbgFormat is set to true because this test has 1396 // been written to expect debug intrinsics rather than debug records; use the 1397 // intrinsic format until we update the test checks. 1398 auto SettingGuard = SaveDbgInfoFormat(); 1399 PreserveInputDbgFormat = cl::boolOrDefault::BOU_TRUE; 1400 1401 // Test that RAUW also replaces the operands of DbgVariableRecord objects, 1402 // i.e. non-instruction stored debugging information. 1403 std::unique_ptr<Module> M = parseIR(C, 1404 R"( 1405 declare void @llvm.dbg.value(metadata, metadata, metadata) 1406 define void @f(i32 %a) !dbg !8 { 1407 entry: 1408 %foo = add i32 %a, 1, !dbg !13 1409 %bar = add i32 %foo, 0, !dbg !13 1410 call void @llvm.dbg.value(metadata i32 %bar, metadata !11, metadata !DIExpression()), !dbg !13 1411 ret void, !dbg !14 1412 } 1413 !llvm.dbg.cu = !{!0} 1414 !llvm.module.flags = !{!3, !4} 1415 !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 6.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2) 1416 !1 = !DIFile(filename: "t2.c", directory: "foo") 1417 !2 = !{} 1418 !3 = !{i32 2, !"Dwarf Version", i32 4} 1419 !4 = !{i32 2, !"Debug Info Version", i32 3} 1420 !8 = distinct !DISubprogram(name: "f", scope: !1, file: !1, line: 1, type: !9, isLocal: false, isDefinition: true, scopeLine: 1, isOptimized: false, unit: !0, retainedNodes: !2) 1421 !9 = !DISubroutineType(types: !10) 1422 !10 = !{null} 1423 !11 = !DILocalVariable(name: "x", scope: !8, file: !1, line: 2, type: !12) 1424 !12 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) 1425 !13 = !DILocation(line: 2, column: 7, scope: !8) 1426 !14 = !DILocation(line: 3, column: 1, scope: !8) 1427 )"); 1428 auto *GV = M->getNamedValue("f"); 1429 ASSERT_TRUE(GV); 1430 auto *F = dyn_cast<Function>(GV); 1431 ASSERT_TRUE(F); 1432 BasicBlock::iterator It = F->front().begin(); 1433 Instruction *FooInst = &*It; 1434 It = std::next(It); 1435 Instruction *BarInst = &*It; 1436 It = std::next(It); 1437 DbgValueInst *DVI = dyn_cast<DbgValueInst>(It); 1438 ASSERT_TRUE(DVI); 1439 It = std::next(It); 1440 Instruction *RetInst = &*It; 1441 1442 // Convert DVI into a DbgVariableRecord. 1443 RetInst->DebugMarker = new DbgMarker(); 1444 RetInst->DebugMarker->MarkedInstr = RetInst; 1445 DbgVariableRecord *DVR = new DbgVariableRecord(DVI); 1446 RetInst->DebugMarker->insertDbgRecord(DVR, false); 1447 // ... and erase the dbg.value. 1448 DVI->eraseFromParent(); 1449 1450 // DVR should originally refer to %bar, 1451 EXPECT_EQ(DVR->getVariableLocationOp(0), BarInst); 1452 1453 // Now try to replace the computation of %bar with %foo -- this should cause 1454 // the DbgVariableRecord's to have it's operand updated beneath it. 1455 BarInst->replaceAllUsesWith(FooInst); 1456 // Check DVR now points at %foo. 1457 EXPECT_EQ(DVR->getVariableLocationOp(0), FooInst); 1458 1459 // Teardown. 1460 RetInst->DebugMarker->eraseFromParent(); 1461 } 1462