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