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/Analysis/DomTreeUpdater.h" 11 #include "llvm/Analysis/InstructionSimplify.h" 12 #include "llvm/Analysis/PostDominators.h" 13 #include "llvm/Analysis/TargetTransformInfo.h" 14 #include "llvm/AsmParser/Parser.h" 15 #include "llvm/IR/BasicBlock.h" 16 #include "llvm/IR/DIBuilder.h" 17 #include "llvm/IR/DebugInfo.h" 18 #include "llvm/IR/IRBuilder.h" 19 #include "llvm/IR/Instructions.h" 20 #include "llvm/IR/IntrinsicInst.h" 21 #include "llvm/IR/LLVMContext.h" 22 #include "llvm/IR/Verifier.h" 23 #include "llvm/Support/SourceMgr.h" 24 #include "gtest/gtest.h" 25 26 using namespace llvm; 27 28 TEST(Local, RecursivelyDeleteDeadPHINodes) { 29 LLVMContext C; 30 31 IRBuilder<> builder(C); 32 33 // Make blocks 34 BasicBlock *bb0 = BasicBlock::Create(C); 35 BasicBlock *bb1 = BasicBlock::Create(C); 36 37 builder.SetInsertPoint(bb0); 38 PHINode *phi = builder.CreatePHI(Type::getInt32Ty(C), 2); 39 BranchInst *br0 = builder.CreateCondBr(builder.getTrue(), bb0, bb1); 40 41 builder.SetInsertPoint(bb1); 42 BranchInst *br1 = builder.CreateBr(bb0); 43 44 phi->addIncoming(phi, bb0); 45 phi->addIncoming(phi, bb1); 46 47 // The PHI will be removed 48 EXPECT_TRUE(RecursivelyDeleteDeadPHINode(phi)); 49 50 // Make sure the blocks only contain the branches 51 EXPECT_EQ(&bb0->front(), br0); 52 EXPECT_EQ(&bb1->front(), br1); 53 54 builder.SetInsertPoint(bb0); 55 phi = builder.CreatePHI(Type::getInt32Ty(C), 0); 56 57 EXPECT_TRUE(RecursivelyDeleteDeadPHINode(phi)); 58 59 builder.SetInsertPoint(bb0); 60 phi = builder.CreatePHI(Type::getInt32Ty(C), 0); 61 builder.CreateAdd(phi, phi); 62 63 EXPECT_TRUE(RecursivelyDeleteDeadPHINode(phi)); 64 65 bb0->dropAllReferences(); 66 bb1->dropAllReferences(); 67 delete bb0; 68 delete bb1; 69 } 70 71 TEST(Local, RemoveDuplicatePHINodes) { 72 LLVMContext C; 73 IRBuilder<> B(C); 74 75 std::unique_ptr<Function> F( 76 Function::Create(FunctionType::get(B.getVoidTy(), false), 77 GlobalValue::ExternalLinkage, "F")); 78 BasicBlock *Entry(BasicBlock::Create(C, "", F.get())); 79 BasicBlock *BB(BasicBlock::Create(C, "", F.get())); 80 BranchInst::Create(BB, Entry); 81 82 B.SetInsertPoint(BB); 83 84 AssertingVH<PHINode> P1 = B.CreatePHI(Type::getInt32Ty(C), 2); 85 P1->addIncoming(B.getInt32(42), Entry); 86 87 PHINode *P2 = B.CreatePHI(Type::getInt32Ty(C), 2); 88 P2->addIncoming(B.getInt32(42), Entry); 89 90 AssertingVH<PHINode> P3 = B.CreatePHI(Type::getInt32Ty(C), 2); 91 P3->addIncoming(B.getInt32(42), Entry); 92 P3->addIncoming(B.getInt32(23), BB); 93 94 PHINode *P4 = B.CreatePHI(Type::getInt32Ty(C), 2); 95 P4->addIncoming(B.getInt32(42), Entry); 96 P4->addIncoming(B.getInt32(23), BB); 97 98 P1->addIncoming(P3, BB); 99 P2->addIncoming(P4, BB); 100 BranchInst::Create(BB, BB); 101 102 // Verify that we can eliminate PHIs that become duplicates after chaning PHIs 103 // downstream. 104 EXPECT_TRUE(EliminateDuplicatePHINodes(BB)); 105 EXPECT_EQ(3U, BB->size()); 106 } 107 108 static std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) { 109 SMDiagnostic Err; 110 std::unique_ptr<Module> Mod = parseAssemblyString(IR, Err, C); 111 if (!Mod) 112 Err.print("UtilsTests", errs()); 113 return Mod; 114 } 115 116 TEST(Local, ReplaceDbgDeclare) { 117 LLVMContext C; 118 119 // Original C source to get debug info for a local variable: 120 // void f() { int x; } 121 std::unique_ptr<Module> M = parseIR(C, 122 R"( 123 define void @f() !dbg !8 { 124 entry: 125 %x = alloca i32, align 4 126 call void @llvm.dbg.declare(metadata i32* %x, metadata !11, metadata !DIExpression()), !dbg !13 127 call void @llvm.dbg.declare(metadata i32* %x, metadata !11, metadata !DIExpression()), !dbg !13 128 ret void, !dbg !14 129 } 130 declare void @llvm.dbg.declare(metadata, metadata, metadata) 131 !llvm.dbg.cu = !{!0} 132 !llvm.module.flags = !{!3, !4} 133 !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 6.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2) 134 !1 = !DIFile(filename: "t2.c", directory: "foo") 135 !2 = !{} 136 !3 = !{i32 2, !"Dwarf Version", i32 4} 137 !4 = !{i32 2, !"Debug Info Version", i32 3} 138 !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) 139 !9 = !DISubroutineType(types: !10) 140 !10 = !{null} 141 !11 = !DILocalVariable(name: "x", scope: !8, file: !1, line: 2, type: !12) 142 !12 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) 143 !13 = !DILocation(line: 2, column: 7, scope: !8) 144 !14 = !DILocation(line: 3, column: 1, scope: !8) 145 )"); 146 auto *GV = M->getNamedValue("f"); 147 ASSERT_TRUE(GV); 148 auto *F = dyn_cast<Function>(GV); 149 ASSERT_TRUE(F); 150 Instruction *Inst = &F->front().front(); 151 auto *AI = dyn_cast<AllocaInst>(Inst); 152 ASSERT_TRUE(AI); 153 Inst = Inst->getNextNode()->getNextNode(); 154 ASSERT_TRUE(Inst); 155 auto *DII = dyn_cast<DbgDeclareInst>(Inst); 156 ASSERT_TRUE(DII); 157 Value *NewBase = Constant::getNullValue(Type::getInt32PtrTy(C)); 158 DIBuilder DIB(*M); 159 replaceDbgDeclare(AI, NewBase, DIB, DIExpression::ApplyOffset, 0); 160 161 // There should be exactly two dbg.declares. 162 int Declares = 0; 163 for (const Instruction &I : F->front()) 164 if (isa<DbgDeclareInst>(I)) 165 Declares++; 166 EXPECT_EQ(2, Declares); 167 } 168 169 /// Build the dominator tree for the function and run the Test. 170 static void runWithDomTree( 171 Module &M, StringRef FuncName, 172 function_ref<void(Function &F, DominatorTree *DT)> Test) { 173 auto *F = M.getFunction(FuncName); 174 ASSERT_NE(F, nullptr) << "Could not find " << FuncName; 175 // Compute the dominator tree for the function. 176 DominatorTree DT(*F); 177 Test(*F, &DT); 178 } 179 180 TEST(Local, MergeBasicBlockIntoOnlyPred) { 181 LLVMContext C; 182 std::unique_ptr<Module> M; 183 auto resetIR = [&]() { 184 M = parseIR(C, 185 R"( 186 define i32 @f(i8* %str) { 187 entry: 188 br label %bb2.i 189 bb2.i: ; preds = %bb4.i, %entry 190 br i1 false, label %bb4.i, label %base2flt.exit204 191 bb4.i: ; preds = %bb2.i 192 br i1 false, label %base2flt.exit204, label %bb2.i 193 bb10.i196.bb7.i197_crit_edge: ; No predecessors! 194 br label %bb7.i197 195 bb7.i197: ; preds = %bb10.i196.bb7.i197_crit_edge 196 %.reg2mem.0 = phi i32 [ %.reg2mem.0, %bb10.i196.bb7.i197_crit_edge ] 197 br i1 undef, label %base2flt.exit204, label %base2flt.exit204 198 base2flt.exit204: ; preds = %bb7.i197, %bb7.i197, %bb2.i, %bb4.i 199 ret i32 0 200 } 201 )"); 202 }; 203 204 auto resetIRReplaceEntry = [&]() { 205 M = parseIR(C, 206 R"( 207 define i32 @f() { 208 entry: 209 br label %bb2.i 210 bb2.i: ; preds = %entry 211 ret i32 0 212 } 213 )"); 214 }; 215 216 auto Test = [&](Function &F, DomTreeUpdater &DTU) { 217 for (Function::iterator I = F.begin(), E = F.end(); I != E;) { 218 BasicBlock *BB = &*I++; 219 BasicBlock *SinglePred = BB->getSinglePredecessor(); 220 if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) 221 continue; 222 BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator()); 223 if (Term && !Term->isConditional()) 224 MergeBasicBlockIntoOnlyPred(BB, &DTU); 225 } 226 if (DTU.hasDomTree()) { 227 EXPECT_TRUE(DTU.getDomTree().verify()); 228 } 229 if (DTU.hasPostDomTree()) { 230 EXPECT_TRUE(DTU.getPostDomTree().verify()); 231 } 232 }; 233 234 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with 235 // both DT and PDT. 236 resetIR(); 237 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 238 PostDominatorTree PDT = PostDominatorTree(F); 239 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager); 240 Test(F, DTU); 241 }); 242 243 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with 244 // DT. 245 resetIR(); 246 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 247 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Eager); 248 Test(F, DTU); 249 }); 250 251 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with 252 // PDT. 253 resetIR(); 254 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 255 PostDominatorTree PDT = PostDominatorTree(F); 256 DomTreeUpdater DTU(PDT, DomTreeUpdater::UpdateStrategy::Eager); 257 Test(F, DTU); 258 }); 259 260 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with 261 // both DT and PDT. 262 resetIR(); 263 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 264 PostDominatorTree PDT = PostDominatorTree(F); 265 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy); 266 Test(F, DTU); 267 }); 268 269 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with 270 // PDT. 271 resetIR(); 272 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 273 PostDominatorTree PDT = PostDominatorTree(F); 274 DomTreeUpdater DTU(PDT, DomTreeUpdater::UpdateStrategy::Lazy); 275 Test(F, DTU); 276 }); 277 278 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with DT. 279 resetIR(); 280 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 281 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy); 282 Test(F, DTU); 283 }); 284 285 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with 286 // both DT and PDT. 287 resetIRReplaceEntry(); 288 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 289 PostDominatorTree PDT = PostDominatorTree(F); 290 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager); 291 Test(F, DTU); 292 }); 293 294 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with 295 // DT. 296 resetIRReplaceEntry(); 297 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 298 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Eager); 299 Test(F, DTU); 300 }); 301 302 // Test MergeBasicBlockIntoOnlyPred working under Eager UpdateStrategy with 303 // PDT. 304 resetIRReplaceEntry(); 305 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 306 PostDominatorTree PDT = PostDominatorTree(F); 307 DomTreeUpdater DTU(PDT, DomTreeUpdater::UpdateStrategy::Eager); 308 Test(F, DTU); 309 }); 310 311 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with 312 // both DT and PDT. 313 resetIRReplaceEntry(); 314 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 315 PostDominatorTree PDT = PostDominatorTree(F); 316 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy); 317 Test(F, DTU); 318 }); 319 320 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with 321 // PDT. 322 resetIRReplaceEntry(); 323 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 324 PostDominatorTree PDT = PostDominatorTree(F); 325 DomTreeUpdater DTU(PDT, DomTreeUpdater::UpdateStrategy::Lazy); 326 Test(F, DTU); 327 }); 328 329 // Test MergeBasicBlockIntoOnlyPred working under Lazy UpdateStrategy with DT. 330 resetIRReplaceEntry(); 331 runWithDomTree(*M, "f", [&](Function &F, DominatorTree *DT) { 332 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Lazy); 333 Test(F, DTU); 334 }); 335 } 336 337 TEST(Local, ConstantFoldTerminator) { 338 LLVMContext C; 339 340 std::unique_ptr<Module> M = parseIR(C, 341 R"( 342 define void @br_same_dest() { 343 entry: 344 br i1 false, label %bb0, label %bb0 345 bb0: 346 ret void 347 } 348 349 define void @br_different_dest() { 350 entry: 351 br i1 true, label %bb0, label %bb1 352 bb0: 353 br label %exit 354 bb1: 355 br label %exit 356 exit: 357 ret void 358 } 359 360 define void @switch_2_different_dest() { 361 entry: 362 switch i32 0, label %default [ i32 0, label %bb0 ] 363 default: 364 ret void 365 bb0: 366 ret void 367 } 368 define void @switch_2_different_dest_default() { 369 entry: 370 switch i32 1, label %default [ i32 0, label %bb0 ] 371 default: 372 ret void 373 bb0: 374 ret void 375 } 376 define void @switch_3_different_dest() { 377 entry: 378 switch i32 0, label %default [ i32 0, label %bb0 379 i32 1, label %bb1 ] 380 default: 381 ret void 382 bb0: 383 ret void 384 bb1: 385 ret void 386 } 387 388 define void @switch_variable_2_default_dest(i32 %arg) { 389 entry: 390 switch i32 %arg, label %default [ i32 0, label %default ] 391 default: 392 ret void 393 } 394 395 define void @switch_constant_2_default_dest() { 396 entry: 397 switch i32 1, label %default [ i32 0, label %default ] 398 default: 399 ret void 400 } 401 402 define void @switch_constant_3_repeated_dest() { 403 entry: 404 switch i32 0, label %default [ i32 0, label %bb0 405 i32 1, label %bb0 ] 406 bb0: 407 ret void 408 default: 409 ret void 410 } 411 412 define void @indirectbr() { 413 entry: 414 indirectbr i8* blockaddress(@indirectbr, %bb0), [label %bb0, label %bb1] 415 bb0: 416 ret void 417 bb1: 418 ret void 419 } 420 421 define void @indirectbr_repeated() { 422 entry: 423 indirectbr i8* blockaddress(@indirectbr_repeated, %bb0), [label %bb0, label %bb0] 424 bb0: 425 ret void 426 } 427 428 define void @indirectbr_unreachable() { 429 entry: 430 indirectbr i8* blockaddress(@indirectbr_unreachable, %bb0), [label %bb1] 431 bb0: 432 ret void 433 bb1: 434 ret void 435 } 436 )"); 437 438 auto CFAllTerminatorsEager = [&](Function &F, DominatorTree *DT) { 439 PostDominatorTree PDT = PostDominatorTree(F); 440 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager); 441 for (Function::iterator I = F.begin(), E = F.end(); I != E;) { 442 BasicBlock *BB = &*I++; 443 ConstantFoldTerminator(BB, true, nullptr, &DTU); 444 } 445 446 EXPECT_TRUE(DTU.getDomTree().verify()); 447 EXPECT_TRUE(DTU.getPostDomTree().verify()); 448 }; 449 450 auto CFAllTerminatorsLazy = [&](Function &F, DominatorTree *DT) { 451 PostDominatorTree PDT = PostDominatorTree(F); 452 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy); 453 for (Function::iterator I = F.begin(), E = F.end(); I != E;) { 454 BasicBlock *BB = &*I++; 455 ConstantFoldTerminator(BB, true, nullptr, &DTU); 456 } 457 458 EXPECT_TRUE(DTU.getDomTree().verify()); 459 EXPECT_TRUE(DTU.getPostDomTree().verify()); 460 }; 461 462 // Test ConstantFoldTerminator under Eager UpdateStrategy. 463 runWithDomTree(*M, "br_same_dest", CFAllTerminatorsEager); 464 runWithDomTree(*M, "br_different_dest", CFAllTerminatorsEager); 465 runWithDomTree(*M, "switch_2_different_dest", CFAllTerminatorsEager); 466 runWithDomTree(*M, "switch_2_different_dest_default", CFAllTerminatorsEager); 467 runWithDomTree(*M, "switch_3_different_dest", CFAllTerminatorsEager); 468 runWithDomTree(*M, "switch_variable_2_default_dest", CFAllTerminatorsEager); 469 runWithDomTree(*M, "switch_constant_2_default_dest", CFAllTerminatorsEager); 470 runWithDomTree(*M, "switch_constant_3_repeated_dest", CFAllTerminatorsEager); 471 runWithDomTree(*M, "indirectbr", CFAllTerminatorsEager); 472 runWithDomTree(*M, "indirectbr_repeated", CFAllTerminatorsEager); 473 runWithDomTree(*M, "indirectbr_unreachable", CFAllTerminatorsEager); 474 475 // Test ConstantFoldTerminator under Lazy UpdateStrategy. 476 runWithDomTree(*M, "br_same_dest", CFAllTerminatorsLazy); 477 runWithDomTree(*M, "br_different_dest", CFAllTerminatorsLazy); 478 runWithDomTree(*M, "switch_2_different_dest", CFAllTerminatorsLazy); 479 runWithDomTree(*M, "switch_2_different_dest_default", CFAllTerminatorsLazy); 480 runWithDomTree(*M, "switch_3_different_dest", CFAllTerminatorsLazy); 481 runWithDomTree(*M, "switch_variable_2_default_dest", CFAllTerminatorsLazy); 482 runWithDomTree(*M, "switch_constant_2_default_dest", CFAllTerminatorsLazy); 483 runWithDomTree(*M, "switch_constant_3_repeated_dest", CFAllTerminatorsLazy); 484 runWithDomTree(*M, "indirectbr", CFAllTerminatorsLazy); 485 runWithDomTree(*M, "indirectbr_repeated", CFAllTerminatorsLazy); 486 runWithDomTree(*M, "indirectbr_unreachable", CFAllTerminatorsLazy); 487 } 488 489 struct SalvageDebugInfoTest : ::testing::Test { 490 LLVMContext C; 491 std::unique_ptr<Module> M; 492 Function *F = nullptr; 493 494 void SetUp() override { 495 M = parseIR(C, 496 R"( 497 define void @f() !dbg !8 { 498 entry: 499 %x = add i32 0, 1 500 %y = add i32 %x, 2 501 call void @llvm.dbg.value(metadata i32 %x, metadata !11, metadata !DIExpression()), !dbg !13 502 call void @llvm.dbg.value(metadata i32 %y, metadata !11, metadata !DIExpression()), !dbg !13 503 ret void, !dbg !14 504 } 505 declare void @llvm.dbg.value(metadata, metadata, metadata) 506 !llvm.dbg.cu = !{!0} 507 !llvm.module.flags = !{!3, !4} 508 !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 6.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2) 509 !1 = !DIFile(filename: "t2.c", directory: "foo") 510 !2 = !{} 511 !3 = !{i32 2, !"Dwarf Version", i32 4} 512 !4 = !{i32 2, !"Debug Info Version", i32 3} 513 !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) 514 !9 = !DISubroutineType(types: !10) 515 !10 = !{null} 516 !11 = !DILocalVariable(name: "x", scope: !8, file: !1, line: 2, type: !12) 517 !12 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) 518 !13 = !DILocation(line: 2, column: 7, scope: !8) 519 !14 = !DILocation(line: 3, column: 1, scope: !8) 520 )"); 521 522 auto *GV = M->getNamedValue("f"); 523 ASSERT_TRUE(GV); 524 F = dyn_cast<Function>(GV); 525 ASSERT_TRUE(F); 526 } 527 528 bool doesDebugValueDescribeX(const DbgValueInst &DI) { 529 if (DI.getNumVariableLocationOps() != 1u) 530 return false; 531 const auto &CI = *cast<ConstantInt>(DI.getValue(0)); 532 if (CI.isZero()) 533 return DI.getExpression()->getElements().equals( 534 {dwarf::DW_OP_plus_uconst, 1, dwarf::DW_OP_stack_value}); 535 else if (CI.isOneValue()) 536 return DI.getExpression()->getElements().empty(); 537 return false; 538 } 539 540 bool doesDebugValueDescribeY(const DbgValueInst &DI) { 541 if (DI.getNumVariableLocationOps() != 1u) 542 return false; 543 const auto &CI = *cast<ConstantInt>(DI.getVariableLocationOp(0)); 544 if (CI.isZero()) 545 return DI.getExpression()->getElements().equals( 546 {dwarf::DW_OP_plus_uconst, 1, dwarf::DW_OP_plus_uconst, 2, 547 dwarf::DW_OP_stack_value}); 548 else if (CI.isOneValue()) 549 return DI.getExpression()->getElements().equals( 550 {dwarf::DW_OP_plus_uconst, 2, dwarf::DW_OP_stack_value}); 551 return false; 552 } 553 554 void verifyDebugValuesAreSalvaged() { 555 // Check that the debug values for %x and %y are preserved. 556 bool FoundX = false; 557 bool FoundY = false; 558 for (const Instruction &I : F->front()) { 559 auto DI = dyn_cast<DbgValueInst>(&I); 560 if (!DI) { 561 // The function should only contain debug values and a terminator. 562 ASSERT_TRUE(I.isTerminator()); 563 continue; 564 } 565 EXPECT_EQ(DI->getVariable()->getName(), "x"); 566 FoundX |= doesDebugValueDescribeX(*DI); 567 FoundY |= doesDebugValueDescribeY(*DI); 568 } 569 ASSERT_TRUE(FoundX); 570 ASSERT_TRUE(FoundY); 571 } 572 }; 573 574 TEST_F(SalvageDebugInfoTest, RecursiveInstDeletion) { 575 Instruction *Inst = &F->front().front(); 576 Inst = Inst->getNextNode(); // Get %y = add ... 577 ASSERT_TRUE(Inst); 578 bool Deleted = RecursivelyDeleteTriviallyDeadInstructions(Inst); 579 ASSERT_TRUE(Deleted); 580 verifyDebugValuesAreSalvaged(); 581 } 582 583 TEST_F(SalvageDebugInfoTest, RecursiveBlockSimplification) { 584 BasicBlock *BB = &F->front(); 585 ASSERT_TRUE(BB); 586 bool Deleted = SimplifyInstructionsInBlock(BB); 587 ASSERT_TRUE(Deleted); 588 verifyDebugValuesAreSalvaged(); 589 } 590 591 TEST(Local, SimplifyVScaleWithRange) { 592 LLVMContext C; 593 Module M("Module", C); 594 595 IntegerType *Ty = Type::getInt32Ty(C); 596 Function *VScale = Intrinsic::getDeclaration(&M, Intrinsic::vscale, {Ty}); 597 auto *CI = CallInst::Create(VScale, {}, "vscale"); 598 599 // Test that simplifyCall won't try to query it's parent function for 600 // vscale_range attributes in order to simplify llvm.vscale -> constant. 601 EXPECT_EQ(simplifyCall(CI, VScale, {}, SimplifyQuery(M.getDataLayout())), 602 nullptr); 603 delete CI; 604 } 605 606 TEST(Local, wouldInstructionBeTriviallyDead) { 607 LLVMContext Ctx; 608 std::unique_ptr<Module> M = parseIR(Ctx, 609 R"( 610 define dso_local void @fun() local_unnamed_addr #0 !dbg !9 { 611 entry: 612 call void @llvm.dbg.declare(metadata !{}, metadata !13, metadata !DIExpression()), !dbg !16 613 ret void, !dbg !16 614 } 615 616 declare void @llvm.dbg.declare(metadata, metadata, metadata) 617 618 !llvm.dbg.cu = !{!0} 619 !llvm.module.flags = !{!2, !3} 620 !llvm.ident = !{!8} 621 622 !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) 623 !1 = !DIFile(filename: "test.c", directory: "/") 624 !2 = !{i32 7, !"Dwarf Version", i32 5} 625 !3 = !{i32 2, !"Debug Info Version", i32 3} 626 !8 = !{!"clang version 16.0.0"} 627 !9 = distinct !DISubprogram(name: "fun", scope: !1, file: !1, line: 1, type: !10, scopeLine: 1, flags: DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !12) 628 !10 = !DISubroutineType(types: !11) 629 !11 = !{null} 630 !12 = !{!13} 631 !13 = !DILocalVariable(name: "a", scope: !9, file: !1, line: 1, type: !14) 632 !14 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) 633 !16 = !DILocation(line: 1, column: 21, scope: !9) 634 )"); 635 bool BrokenDebugInfo = true; 636 verifyModule(*M, &errs(), &BrokenDebugInfo); 637 ASSERT_FALSE(BrokenDebugInfo); 638 639 // Get the dbg.declare. 640 Function &F = *cast<Function>(M->getNamedValue("fun")); 641 Instruction *DbgDeclare = &F.front().front(); 642 ASSERT_TRUE(isa<DbgDeclareInst>(DbgDeclare)); 643 // Debug intrinsics with empty metadata arguments are not dead. 644 EXPECT_FALSE(wouldInstructionBeTriviallyDead(DbgDeclare)); 645 } 646 647 TEST(Local, ChangeToUnreachable) { 648 LLVMContext Ctx; 649 650 std::unique_ptr<Module> M = parseIR(Ctx, 651 R"( 652 define internal void @foo() !dbg !6 { 653 entry: 654 ret void, !dbg !8 655 } 656 657 !llvm.dbg.cu = !{!0} 658 !llvm.debugify = !{!3, !4} 659 !llvm.module.flags = !{!5} 660 661 !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2) 662 !1 = !DIFile(filename: "test.ll", directory: "/") 663 !2 = !{} 664 !3 = !{i32 1} 665 !4 = !{i32 0} 666 !5 = !{i32 2, !"Debug Info Version", i32 3} 667 !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) 668 !7 = !DISubroutineType(types: !2) 669 !8 = !DILocation(line: 1, column: 1, scope: !6) 670 )"); 671 672 bool BrokenDebugInfo = true; 673 verifyModule(*M, &errs(), &BrokenDebugInfo); 674 ASSERT_FALSE(BrokenDebugInfo); 675 676 Function &F = *cast<Function>(M->getNamedValue("foo")); 677 678 BasicBlock &BB = F.front(); 679 Instruction &A = BB.front(); 680 DebugLoc DLA = A.getDebugLoc(); 681 682 ASSERT_TRUE(isa<ReturnInst>(&A)); 683 // One instruction should be affected. 684 EXPECT_EQ(changeToUnreachable(&A), 1U); 685 686 Instruction &B = BB.front(); 687 688 // There should be an uncreachable instruction. 689 ASSERT_TRUE(isa<UnreachableInst>(&B)); 690 691 DebugLoc DLB = B.getDebugLoc(); 692 EXPECT_EQ(DLA, DLB); 693 } 694 695 TEST(Local, FindDbgUsers) { 696 LLVMContext Ctx; 697 std::unique_ptr<Module> M = parseIR(Ctx, 698 R"( 699 define dso_local void @fun(ptr %a) #0 !dbg !11 { 700 entry: 701 call void @llvm.dbg.assign(metadata ptr %a, metadata !16, metadata !DIExpression(), metadata !15, metadata ptr %a, metadata !DIExpression()), !dbg !19 702 ret void 703 } 704 705 declare void @llvm.dbg.assign(metadata, metadata, metadata, metadata, metadata, metadata) 706 707 !llvm.dbg.cu = !{!0} 708 !llvm.module.flags = !{!2, !3, !9} 709 !llvm.ident = !{!10} 710 711 !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) 712 !1 = !DIFile(filename: "test.cpp", directory: "/") 713 !2 = !{i32 7, !"Dwarf Version", i32 5} 714 !3 = !{i32 2, !"Debug Info Version", i32 3} 715 !4 = !{i32 1, !"wchar_size", i32 4} 716 !9 = !{i32 7, !"debug-info-assignment-tracking", i1 true} 717 !10 = !{!"clang version 17.0.0"} 718 !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) 719 !12 = !DISubroutineType(types: !13) 720 !13 = !{null} 721 !14 = !{} 722 !15 = distinct !DIAssignID() 723 !16 = !DILocalVariable(name: "x", scope: !11, file: !1, line: 2, type: !17) 724 !17 = !DIDerivedType(tag: DW_TAG_pointer_type, baseType: !18, size: 64) 725 !18 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed) 726 !19 = !DILocation(line: 0, scope: !11) 727 )"); 728 729 bool BrokenDebugInfo = true; 730 verifyModule(*M, &errs(), &BrokenDebugInfo); 731 ASSERT_FALSE(BrokenDebugInfo); 732 733 Function &Fun = *cast<Function>(M->getNamedValue("fun")); 734 Value *Arg = Fun.getArg(0); 735 736 SmallVector<DbgVariableIntrinsic *> Users; 737 // Arg (%a) is used twice by a single dbg.assign. Check findDbgUsers returns 738 // only 1 pointer to it rather than 2. 739 findDbgUsers(Users, Arg); 740 EXPECT_EQ(Users.size(), 1u); 741 742 SmallVector<DbgValueInst *> Vals; 743 // Arg (%a) is used twice by a single dbg.assign. Check findDbgValues returns 744 // only 1 pointer to it rather than 2. 745 findDbgValues(Vals, Arg); 746 EXPECT_EQ(Vals.size(), 1u); 747 } 748 749 TEST(Local, ReplaceAllDbgUsesWith) { 750 using namespace llvm::dwarf; 751 752 LLVMContext Ctx; 753 754 // Note: The datalayout simulates Darwin/x86_64. 755 std::unique_ptr<Module> M = parseIR(Ctx, 756 R"( 757 target datalayout = "e-m:o-i63:64-f80:128-n8:16:32:64-S128" 758 759 declare i32 @escape(i32) 760 761 define void @f() !dbg !6 { 762 entry: 763 %a = add i32 0, 1, !dbg !15 764 call void @llvm.dbg.value(metadata i32 %a, metadata !9, metadata !DIExpression()), !dbg !15 765 766 %b = add i64 0, 1, !dbg !16 767 call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression()), !dbg !16 768 call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_lit0, DW_OP_mul)), !dbg !16 769 call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_lit0, DW_OP_mul, DW_OP_stack_value)), !dbg !16 770 call void @llvm.dbg.value(metadata i64 %b, metadata !11, metadata !DIExpression(DW_OP_LLVM_fragment, 0, 8)), !dbg !16 771 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 772 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 773 774 %c = inttoptr i64 0 to i64*, !dbg !17 775 call void @llvm.dbg.declare(metadata i64* %c, metadata !13, metadata !DIExpression()), !dbg !17 776 777 %d = inttoptr i64 0 to i32*, !dbg !18 778 call void @llvm.dbg.declare(metadata i32* %d, metadata !20, metadata !DIExpression()), !dbg !18 779 780 %e = add <2 x i16> zeroinitializer, zeroinitializer 781 call void @llvm.dbg.value(metadata <2 x i16> %e, metadata !14, metadata !DIExpression()), !dbg !18 782 783 %f = call i32 @escape(i32 0) 784 call void @llvm.dbg.value(metadata i32 %f, metadata !9, metadata !DIExpression()), !dbg !15 785 786 %barrier = call i32 @escape(i32 0) 787 788 %g = call i32 @escape(i32 %f) 789 call void @llvm.dbg.value(metadata i32 %g, metadata !9, metadata !DIExpression()), !dbg !15 790 791 ret void, !dbg !19 792 } 793 794 declare void @llvm.dbg.declare(metadata, metadata, metadata) 795 declare void @llvm.dbg.value(metadata, metadata, metadata) 796 797 !llvm.dbg.cu = !{!0} 798 !llvm.module.flags = !{!5} 799 800 !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2) 801 !1 = !DIFile(filename: "/Users/vsk/Desktop/foo.ll", directory: "/") 802 !2 = !{} 803 !5 = !{i32 2, !"Debug Info Version", i32 3} 804 !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) 805 !7 = !DISubroutineType(types: !2) 806 !8 = !{!9, !11, !13, !14} 807 !9 = !DILocalVariable(name: "1", scope: !6, file: !1, line: 1, type: !10) 808 !10 = !DIBasicType(name: "ty32", size: 32, encoding: DW_ATE_signed) 809 !11 = !DILocalVariable(name: "2", scope: !6, file: !1, line: 2, type: !12) 810 !12 = !DIBasicType(name: "ty64", size: 64, encoding: DW_ATE_signed) 811 !13 = !DILocalVariable(name: "3", scope: !6, file: !1, line: 3, type: !12) 812 !14 = !DILocalVariable(name: "4", scope: !6, file: !1, line: 4, type: !10) 813 !15 = !DILocation(line: 1, column: 1, scope: !6) 814 !16 = !DILocation(line: 2, column: 1, scope: !6) 815 !17 = !DILocation(line: 3, column: 1, scope: !6) 816 !18 = !DILocation(line: 4, column: 1, scope: !6) 817 !19 = !DILocation(line: 5, column: 1, scope: !6) 818 !20 = !DILocalVariable(name: "5", scope: !6, file: !1, line: 5, type: !10) 819 )"); 820 821 bool BrokenDebugInfo = true; 822 verifyModule(*M, &errs(), &BrokenDebugInfo); 823 ASSERT_FALSE(BrokenDebugInfo); 824 825 Function &F = *cast<Function>(M->getNamedValue("f")); 826 DominatorTree DT{F}; 827 828 BasicBlock &BB = F.front(); 829 Instruction &A = BB.front(); 830 Instruction &B = *A.getNextNonDebugInstruction(); 831 Instruction &C = *B.getNextNonDebugInstruction(); 832 Instruction &D = *C.getNextNonDebugInstruction(); 833 Instruction &E = *D.getNextNonDebugInstruction(); 834 Instruction &F_ = *E.getNextNonDebugInstruction(); 835 Instruction &Barrier = *F_.getNextNonDebugInstruction(); 836 Instruction &G = *Barrier.getNextNonDebugInstruction(); 837 838 // Simulate i32 <-> i64* conversion. Expect no updates: the datalayout says 839 // pointers are 64 bits, so the conversion would be lossy. 840 EXPECT_FALSE(replaceAllDbgUsesWith(A, C, C, DT)); 841 EXPECT_FALSE(replaceAllDbgUsesWith(C, A, A, DT)); 842 843 // Simulate i32 <-> <2 x i16> conversion. This is unsupported. 844 EXPECT_FALSE(replaceAllDbgUsesWith(E, A, A, DT)); 845 EXPECT_FALSE(replaceAllDbgUsesWith(A, E, E, DT)); 846 847 // Simulate i32* <-> i64* conversion. 848 EXPECT_TRUE(replaceAllDbgUsesWith(D, C, C, DT)); 849 850 SmallVector<DbgVariableIntrinsic *, 2> CDbgVals; 851 findDbgUsers(CDbgVals, &C); 852 EXPECT_EQ(2U, CDbgVals.size()); 853 EXPECT_TRUE(all_of(CDbgVals, [](DbgVariableIntrinsic *DII) { 854 return isa<DbgDeclareInst>(DII); 855 })); 856 857 EXPECT_TRUE(replaceAllDbgUsesWith(C, D, D, DT)); 858 859 SmallVector<DbgVariableIntrinsic *, 2> DDbgVals; 860 findDbgUsers(DDbgVals, &D); 861 EXPECT_EQ(2U, DDbgVals.size()); 862 EXPECT_TRUE(all_of(DDbgVals, [](DbgVariableIntrinsic *DII) { 863 return isa<DbgDeclareInst>(DII); 864 })); 865 866 // Introduce a use-before-def. Check that the dbg.value for %a is salvaged. 867 EXPECT_TRUE(replaceAllDbgUsesWith(A, F_, F_, DT)); 868 869 auto *ADbgVal = cast<DbgValueInst>(A.getNextNode()); 870 EXPECT_EQ(ADbgVal->getNumVariableLocationOps(), 1u); 871 EXPECT_EQ(ConstantInt::get(A.getType(), 0), ADbgVal->getVariableLocationOp(0)); 872 873 // Introduce a use-before-def. Check that the dbg.values for %f become undef. 874 EXPECT_TRUE(replaceAllDbgUsesWith(F_, G, G, DT)); 875 876 auto *FDbgVal = cast<DbgValueInst>(F_.getNextNode()); 877 EXPECT_EQ(FDbgVal->getNumVariableLocationOps(), 1u); 878 EXPECT_TRUE(FDbgVal->isKillLocation()); 879 880 SmallVector<DbgValueInst *, 1> FDbgVals; 881 findDbgValues(FDbgVals, &F_); 882 EXPECT_EQ(0U, FDbgVals.size()); 883 884 // Simulate i32 -> i64 conversion to test sign-extension. Here are some 885 // interesting cases to handle: 886 // 1) debug user has empty DIExpression 887 // 2) debug user has non-empty, non-stack-value'd DIExpression 888 // 3) debug user has non-empty, stack-value'd DIExpression 889 // 4-6) like (1-3), but with a fragment 890 EXPECT_TRUE(replaceAllDbgUsesWith(B, A, A, DT)); 891 892 SmallVector<DbgValueInst *, 8> ADbgVals; 893 findDbgValues(ADbgVals, &A); 894 EXPECT_EQ(6U, ADbgVals.size()); 895 896 // Check that %a has a dbg.value with a DIExpression matching \p Ops. 897 auto hasADbgVal = [&](ArrayRef<uint64_t> Ops) { 898 return any_of(ADbgVals, [&](DbgValueInst *DVI) { 899 assert(DVI->getVariable()->getName() == "2"); 900 return DVI->getExpression()->getElements() == Ops; 901 }); 902 }; 903 904 // Case 1: The original expr is empty, so no deref is needed. 905 EXPECT_TRUE(hasADbgVal({DW_OP_LLVM_convert, 32, DW_ATE_signed, 906 DW_OP_LLVM_convert, 64, DW_ATE_signed, 907 DW_OP_stack_value})); 908 909 // Case 2: Perform an address calculation with the original expr, deref it, 910 // then sign-extend the result. 911 EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_deref, 912 DW_OP_LLVM_convert, 32, DW_ATE_signed, 913 DW_OP_LLVM_convert, 64, DW_ATE_signed, 914 DW_OP_stack_value})); 915 916 // Case 3: Insert the sign-extension logic before the DW_OP_stack_value. 917 EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_LLVM_convert, 32, 918 DW_ATE_signed, DW_OP_LLVM_convert, 64, DW_ATE_signed, 919 DW_OP_stack_value})); 920 921 // Cases 4-6: Just like cases 1-3, but preserve the fragment at the end. 922 EXPECT_TRUE(hasADbgVal({DW_OP_LLVM_convert, 32, DW_ATE_signed, 923 DW_OP_LLVM_convert, 64, DW_ATE_signed, 924 DW_OP_stack_value, DW_OP_LLVM_fragment, 0, 8})); 925 926 EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_deref, 927 DW_OP_LLVM_convert, 32, DW_ATE_signed, 928 DW_OP_LLVM_convert, 64, DW_ATE_signed, 929 DW_OP_stack_value, DW_OP_LLVM_fragment, 0, 8})); 930 931 EXPECT_TRUE(hasADbgVal({DW_OP_lit0, DW_OP_mul, DW_OP_LLVM_convert, 32, 932 DW_ATE_signed, DW_OP_LLVM_convert, 64, DW_ATE_signed, 933 DW_OP_stack_value, DW_OP_LLVM_fragment, 0, 8})); 934 935 verifyModule(*M, &errs(), &BrokenDebugInfo); 936 ASSERT_FALSE(BrokenDebugInfo); 937 } 938 939 TEST(Local, RemoveUnreachableBlocks) { 940 LLVMContext C; 941 942 std::unique_ptr<Module> M = parseIR(C, 943 R"( 944 define void @br_simple() { 945 entry: 946 br label %bb0 947 bb0: 948 ret void 949 bb1: 950 ret void 951 } 952 953 define void @br_self_loop() { 954 entry: 955 br label %bb0 956 bb0: 957 br i1 true, label %bb1, label %bb0 958 bb1: 959 br i1 true, label %bb0, label %bb2 960 bb2: 961 br label %bb2 962 } 963 964 define void @br_constant() { 965 entry: 966 br label %bb0 967 bb0: 968 br i1 true, label %bb1, label %bb2 969 bb1: 970 br i1 true, label %bb0, label %bb2 971 bb2: 972 br label %bb2 973 } 974 975 define void @br_loop() { 976 entry: 977 br label %bb0 978 bb0: 979 br label %bb0 980 bb1: 981 br label %bb2 982 bb2: 983 br label %bb1 984 } 985 986 declare i32 @__gxx_personality_v0(...) 987 988 define void @invoke_terminator() personality i8* bitcast (i32 (...)* @__gxx_personality_v0 to i8*) { 989 entry: 990 br i1 undef, label %invoke.block, label %exit 991 992 invoke.block: 993 %cond = invoke zeroext i1 @invokable() 994 to label %continue.block unwind label %lpad.block 995 996 continue.block: 997 br i1 %cond, label %if.then, label %if.end 998 999 if.then: 1000 unreachable 1001 1002 if.end: 1003 unreachable 1004 1005 lpad.block: 1006 %lp = landingpad { i8*, i32 } 1007 catch i8* null 1008 br label %exit 1009 1010 exit: 1011 ret void 1012 } 1013 1014 declare i1 @invokable() 1015 )"); 1016 1017 auto runEager = [&](Function &F, DominatorTree *DT) { 1018 PostDominatorTree PDT = PostDominatorTree(F); 1019 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Eager); 1020 removeUnreachableBlocks(F, &DTU); 1021 EXPECT_TRUE(DTU.getDomTree().verify()); 1022 EXPECT_TRUE(DTU.getPostDomTree().verify()); 1023 }; 1024 1025 auto runLazy = [&](Function &F, DominatorTree *DT) { 1026 PostDominatorTree PDT = PostDominatorTree(F); 1027 DomTreeUpdater DTU(*DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy); 1028 removeUnreachableBlocks(F, &DTU); 1029 EXPECT_TRUE(DTU.getDomTree().verify()); 1030 EXPECT_TRUE(DTU.getPostDomTree().verify()); 1031 }; 1032 1033 // Test removeUnreachableBlocks under Eager UpdateStrategy. 1034 runWithDomTree(*M, "br_simple", runEager); 1035 runWithDomTree(*M, "br_self_loop", runEager); 1036 runWithDomTree(*M, "br_constant", runEager); 1037 runWithDomTree(*M, "br_loop", runEager); 1038 runWithDomTree(*M, "invoke_terminator", runEager); 1039 1040 // Test removeUnreachableBlocks under Lazy UpdateStrategy. 1041 runWithDomTree(*M, "br_simple", runLazy); 1042 runWithDomTree(*M, "br_self_loop", runLazy); 1043 runWithDomTree(*M, "br_constant", runLazy); 1044 runWithDomTree(*M, "br_loop", runLazy); 1045 runWithDomTree(*M, "invoke_terminator", runLazy); 1046 1047 M = parseIR(C, 1048 R"( 1049 define void @f() { 1050 entry: 1051 ret void 1052 bb0: 1053 ret void 1054 } 1055 )"); 1056 1057 auto checkRUBlocksRetVal = [&](Function &F, DominatorTree *DT) { 1058 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy); 1059 EXPECT_TRUE(removeUnreachableBlocks(F, &DTU)); 1060 EXPECT_FALSE(removeUnreachableBlocks(F, &DTU)); 1061 EXPECT_TRUE(DTU.getDomTree().verify()); 1062 }; 1063 1064 runWithDomTree(*M, "f", checkRUBlocksRetVal); 1065 } 1066 1067 TEST(Local, SimplifyCFGWithNullAC) { 1068 LLVMContext Ctx; 1069 1070 std::unique_ptr<Module> M = parseIR(Ctx, R"( 1071 declare void @true_path() 1072 declare void @false_path() 1073 declare void @llvm.assume(i1 %cond); 1074 1075 define i32 @foo(i1, i32) { 1076 entry: 1077 %cmp = icmp sgt i32 %1, 0 1078 br i1 %cmp, label %if.bb1, label %then.bb1 1079 if.bb1: 1080 call void @true_path() 1081 br label %test.bb 1082 then.bb1: 1083 call void @false_path() 1084 br label %test.bb 1085 test.bb: 1086 %phi = phi i1 [1, %if.bb1], [%0, %then.bb1] 1087 call void @llvm.assume(i1 %0) 1088 br i1 %phi, label %if.bb2, label %then.bb2 1089 if.bb2: 1090 ret i32 %1 1091 then.bb2: 1092 ret i32 0 1093 } 1094 )"); 1095 1096 Function &F = *cast<Function>(M->getNamedValue("foo")); 1097 TargetTransformInfo TTI(M->getDataLayout()); 1098 1099 SimplifyCFGOptions Options{}; 1100 Options.setAssumptionCache(nullptr); 1101 1102 // Obtain BasicBlock of interest to this test, %test.bb. 1103 BasicBlock *TestBB = nullptr; 1104 for (BasicBlock &BB : F) { 1105 if (BB.getName().equals("test.bb")) { 1106 TestBB = &BB; 1107 break; 1108 } 1109 } 1110 ASSERT_TRUE(TestBB); 1111 1112 DominatorTree DT(F); 1113 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); 1114 1115 // %test.bb is expected to be simplified by FoldCondBranchOnPHI. 1116 EXPECT_TRUE(simplifyCFG(TestBB, TTI, 1117 RequireAndPreserveDomTree ? &DTU : nullptr, Options)); 1118 } 1119 1120 TEST(Local, CanReplaceOperandWithVariable) { 1121 LLVMContext Ctx; 1122 Module M("test_module", Ctx); 1123 IRBuilder<> B(Ctx); 1124 1125 FunctionType *FnType = 1126 FunctionType::get(Type::getVoidTy(Ctx), {}, false); 1127 1128 FunctionType *VarArgFnType = 1129 FunctionType::get(Type::getVoidTy(Ctx), {B.getInt32Ty()}, true); 1130 1131 Function *TestBody = Function::Create(FnType, GlobalValue::ExternalLinkage, 1132 0, "", &M); 1133 1134 BasicBlock *BB0 = BasicBlock::Create(Ctx, "", TestBody); 1135 B.SetInsertPoint(BB0); 1136 1137 FunctionCallee Intrin = M.getOrInsertFunction("llvm.foo", FnType); 1138 FunctionCallee Func = M.getOrInsertFunction("foo", FnType); 1139 FunctionCallee VarArgFunc 1140 = M.getOrInsertFunction("foo.vararg", VarArgFnType); 1141 FunctionCallee VarArgIntrin 1142 = M.getOrInsertFunction("llvm.foo.vararg", VarArgFnType); 1143 1144 auto *CallToIntrin = B.CreateCall(Intrin); 1145 auto *CallToFunc = B.CreateCall(Func); 1146 1147 // Test if it's valid to replace the callee operand. 1148 EXPECT_FALSE(canReplaceOperandWithVariable(CallToIntrin, 0)); 1149 EXPECT_TRUE(canReplaceOperandWithVariable(CallToFunc, 0)); 1150 1151 // That it's invalid to replace an argument in the variadic argument list for 1152 // an intrinsic, but OK for a normal function. 1153 auto *CallToVarArgFunc = B.CreateCall( 1154 VarArgFunc, {B.getInt32(0), B.getInt32(1), B.getInt32(2)}); 1155 EXPECT_TRUE(canReplaceOperandWithVariable(CallToVarArgFunc, 0)); 1156 EXPECT_TRUE(canReplaceOperandWithVariable(CallToVarArgFunc, 1)); 1157 EXPECT_TRUE(canReplaceOperandWithVariable(CallToVarArgFunc, 2)); 1158 EXPECT_TRUE(canReplaceOperandWithVariable(CallToVarArgFunc, 3)); 1159 1160 auto *CallToVarArgIntrin = B.CreateCall( 1161 VarArgIntrin, {B.getInt32(0), B.getInt32(1), B.getInt32(2)}); 1162 EXPECT_TRUE(canReplaceOperandWithVariable(CallToVarArgIntrin, 0)); 1163 EXPECT_FALSE(canReplaceOperandWithVariable(CallToVarArgIntrin, 1)); 1164 EXPECT_FALSE(canReplaceOperandWithVariable(CallToVarArgIntrin, 2)); 1165 EXPECT_FALSE(canReplaceOperandWithVariable(CallToVarArgIntrin, 3)); 1166 1167 // Test that it's invalid to replace gcroot operands, even though it can't use 1168 // immarg. 1169 Type *PtrPtr = B.getInt8Ty()->getPointerTo(0); 1170 Value *Alloca = B.CreateAlloca(PtrPtr, (unsigned)0); 1171 CallInst *GCRoot = B.CreateIntrinsic(Intrinsic::gcroot, {}, 1172 {Alloca, Constant::getNullValue(PtrPtr)}); 1173 EXPECT_TRUE(canReplaceOperandWithVariable(GCRoot, 0)); // Alloca 1174 EXPECT_FALSE(canReplaceOperandWithVariable(GCRoot, 1)); 1175 EXPECT_FALSE(canReplaceOperandWithVariable(GCRoot, 2)); 1176 1177 BB0->dropAllReferences(); 1178 } 1179