Debian Codegraph @

llvm-project/llvm/unittests/IR/DebugInfoTest.cpp

raw
1 //===- llvm/unittest/IR/DebugInfo.cpp - DebugInfo tests -------------------===//
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/IR/DebugInfo.h"
10 #include "llvm/ADT/APSInt.h"
11 #include "llvm/AsmParser/Parser.h"
12 #include "llvm/IR/DIBuilder.h"
13 #include "llvm/IR/DebugInfoMetadata.h"
14 #include "llvm/IR/IRBuilder.h"
15 #include "llvm/IR/IntrinsicInst.h"
16 #include "llvm/IR/LLVMContext.h"
17 #include "llvm/IR/Metadata.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/IR/Verifier.h"
20 #include "llvm/Support/SourceMgr.h"
21 #include "llvm/Transforms/Utils/Local.h"
22 #include "gtest/gtest.h"
23
24 using namespace llvm;
25
26 static std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) {
27 SMDiagnostic Err;
28 std::unique_ptr<Module> Mod = parseAssemblyString(IR, Err, C);
29 if (!Mod)
30 Err.print("DebugInfoTest", errs());
31 return Mod;
32 }
33
34 namespace {
35
36 TEST(DINodeTest, getFlag) {
37 // Some valid flags.
38 EXPECT_EQ(DINode::FlagPublic, DINode::getFlag("DIFlagPublic"));
39 EXPECT_EQ(DINode::FlagProtected, DINode::getFlag("DIFlagProtected"));
40 EXPECT_EQ(DINode::FlagPrivate, DINode::getFlag("DIFlagPrivate"));
41 EXPECT_EQ(DINode::FlagVector, DINode::getFlag("DIFlagVector"));
42 EXPECT_EQ(DINode::FlagRValueReference,
43 DINode::getFlag("DIFlagRValueReference"));
44
45 // FlagAccessibility shouldn't work.
46 EXPECT_EQ(0u, DINode::getFlag("DIFlagAccessibility"));
47
48 // Some other invalid strings.
49 EXPECT_EQ(0u, DINode::getFlag("FlagVector"));
50 EXPECT_EQ(0u, DINode::getFlag("Vector"));
51 EXPECT_EQ(0u, DINode::getFlag("other things"));
52 EXPECT_EQ(0u, DINode::getFlag("DIFlagOther"));
53 }
54
55 TEST(DINodeTest, getFlagString) {
56 // Some valid flags.
57 EXPECT_EQ(StringRef("DIFlagPublic"),
58 DINode::getFlagString(DINode::FlagPublic));
59 EXPECT_EQ(StringRef("DIFlagProtected"),
60 DINode::getFlagString(DINode::FlagProtected));
61 EXPECT_EQ(StringRef("DIFlagPrivate"),
62 DINode::getFlagString(DINode::FlagPrivate));
63 EXPECT_EQ(StringRef("DIFlagVector"),
64 DINode::getFlagString(DINode::FlagVector));
65 EXPECT_EQ(StringRef("DIFlagRValueReference"),
66 DINode::getFlagString(DINode::FlagRValueReference));
67
68 // FlagAccessibility actually equals FlagPublic.
69 EXPECT_EQ(StringRef("DIFlagPublic"),
70 DINode::getFlagString(DINode::FlagAccessibility));
71
72 // Some other invalid flags.
73 EXPECT_EQ(StringRef(),
74 DINode::getFlagString(DINode::FlagPublic | DINode::FlagVector));
75 EXPECT_EQ(StringRef(), DINode::getFlagString(DINode::FlagFwdDecl |
76 DINode::FlagArtificial));
77 EXPECT_EQ(StringRef(),
78 DINode::getFlagString(static_cast<DINode::DIFlags>(0xffff)));
79 }
80
81 TEST(DINodeTest, splitFlags) {
82 // Some valid flags.
83 #define CHECK_SPLIT(FLAGS, VECTOR, REMAINDER) \
84 { \
85 SmallVector<DINode::DIFlags, 8> V; \
86 EXPECT_EQ(REMAINDER, DINode::splitFlags(FLAGS, V)); \
87 EXPECT_TRUE(ArrayRef(V).equals(VECTOR)); \
88 }
89 CHECK_SPLIT(DINode::FlagPublic, {DINode::FlagPublic}, DINode::FlagZero);
90 CHECK_SPLIT(DINode::FlagProtected, {DINode::FlagProtected}, DINode::FlagZero);
91 CHECK_SPLIT(DINode::FlagPrivate, {DINode::FlagPrivate}, DINode::FlagZero);
92 CHECK_SPLIT(DINode::FlagVector, {DINode::FlagVector}, DINode::FlagZero);
93 CHECK_SPLIT(DINode::FlagRValueReference, {DINode::FlagRValueReference},
94 DINode::FlagZero);
95 DINode::DIFlags Flags[] = {DINode::FlagFwdDecl, DINode::FlagVector};
96 CHECK_SPLIT(DINode::FlagFwdDecl | DINode::FlagVector, Flags,
97 DINode::FlagZero);
98 CHECK_SPLIT(DINode::FlagZero, {}, DINode::FlagZero);
99 #undef CHECK_SPLIT
100 }
101
102 TEST(StripTest, LoopMetadata) {
103 LLVMContext C;
104 std::unique_ptr<Module> M = parseIR(C, R"(
105 define void @f() !dbg !5 {
106 ret void, !dbg !10, !llvm.loop !11
107 }
108
109 !llvm.dbg.cu = !{!0}
110 !llvm.debugify = !{!3, !3}
111 !llvm.module.flags = !{!4}
112
113 !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
114 !1 = !DIFile(filename: "loop.ll", directory: "/")
115 !2 = !{}
116 !3 = !{i32 1}
117 !4 = !{i32 2, !"Debug Info Version", i32 3}
118 !5 = distinct !DISubprogram(name: "f", linkageName: "f", scope: null, file: !1, line: 1, type: !6, scopeLine: 1, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !7)
119 !6 = !DISubroutineType(types: !2)
120 !7 = !{!8}
121 !8 = !DILocalVariable(name: "1", scope: !5, file: !1, line: 1, type: !9)
122 !9 = !DIBasicType(name: "ty32", size: 32, encoding: DW_ATE_unsigned)
123 !10 = !DILocation(line: 1, column: 1, scope: !5)
124 !11 = distinct !{!11, !10, !10}
125 )");
126
127 // Look up the debug info emission kind for the CU via the loop metadata
128 // attached to the terminator. If, when stripping non-line table debug info,
129 // we update the terminator's metadata correctly, we should be able to
130 // observe the change in emission kind for the CU.
131 auto getEmissionKind = [&]() {
132 Instruction &I = *M->getFunction("f")->getEntryBlock().getFirstNonPHI();
133 MDNode *LoopMD = I.getMetadata(LLVMContext::MD_loop);
134 return cast<DILocation>(LoopMD->getOperand(1))
135 ->getScope()
136 ->getSubprogram()
137 ->getUnit()
138 ->getEmissionKind();
139 };
140
141 EXPECT_EQ(getEmissionKind(), DICompileUnit::FullDebug);
142
143 bool Changed = stripNonLineTableDebugInfo(*M);
144 EXPECT_TRUE(Changed);
145
146 EXPECT_EQ(getEmissionKind(), DICompileUnit::LineTablesOnly);
147
148 bool BrokenDebugInfo = false;
149 bool HardError = verifyModule(*M, &errs(), &BrokenDebugInfo);
150 EXPECT_FALSE(HardError);
151 EXPECT_FALSE(BrokenDebugInfo);
152 }
153
154 TEST(MetadataTest, DeleteInstUsedByDbgValue) {
155 LLVMContext C;
156 std::unique_ptr<Module> M = parseIR(C, R"(
157 define i16 @f(i16 %a) !dbg !6 {
158 %b = add i16 %a, 1, !dbg !11
159 call void @llvm.dbg.value(metadata i16 %b, metadata !9, metadata !DIExpression()), !dbg !11
160 ret i16 0, !dbg !11
161 }
162 declare void @llvm.dbg.value(metadata, metadata, metadata) #0
163 attributes #0 = { nounwind readnone speculatable willreturn }
164
165 !llvm.dbg.cu = !{!0}
166 !llvm.module.flags = !{!5}
167
168 !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
169 !1 = !DIFile(filename: "t.ll", directory: "/")
170 !2 = !{}
171 !5 = !{i32 2, !"Debug Info Version", i32 3}
172 !6 = distinct !DISubprogram(name: "foo", linkageName: "foo", scope: null, file: !1, line: 1, type: !7, scopeLine: 1, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !8)
173 !7 = !DISubroutineType(types: !2)
174 !8 = !{!9}
175 !9 = !DILocalVariable(name: "1", scope: !6, file: !1, line: 1, type: !10)
176 !10 = !DIBasicType(name: "ty16", size: 16, encoding: DW_ATE_unsigned)
177 !11 = !DILocation(line: 1, column: 1, scope: !6)
178 )");
179
180 // Find %b = add ...
181 Instruction &I = *M->getFunction("f")->getEntryBlock().getFirstNonPHI();
182
183 // Find the dbg.value using %b.
184 SmallVector<DbgValueInst *, 1> DVIs;
185 findDbgValues(DVIs, &I);
186
187 // Delete %b. The dbg.value should now point to undef.
188 I.eraseFromParent();
189 EXPECT_EQ(DVIs[0]->getNumVariableLocationOps(), 1u);
190 EXPECT_TRUE(isa<UndefValue>(DVIs[0]->getValue(0)));
191 }
192
193 TEST(DIBuiler, CreateFile) {
194 LLVMContext Ctx;
195 std::unique_ptr<Module> M(new Module("MyModule", Ctx));
196 DIBuilder DIB(*M);
197
198 DIFile *F = DIB.createFile("main.c", "/");
199 EXPECT_EQ(std::nullopt, F->getSource());
200
201 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum;
202 std::optional<StringRef> Source;
203 F = DIB.createFile("main.c", "/", Checksum, Source);
204 EXPECT_EQ(Source, F->getSource());
205
206 Source = "";
207 F = DIB.createFile("main.c", "/", Checksum, Source);
208 EXPECT_EQ(Source, F->getSource());
209 }
210
211 TEST(DIBuilder, CreateFortranArrayTypeWithAttributes) {
212 LLVMContext Ctx;
213 std::unique_ptr<Module> M(new Module("MyModule", Ctx));
214 DIBuilder DIB(*M);
215
216 DISubrange *Subrange = DIB.getOrCreateSubrange(1,1);
217 SmallVector<Metadata*, 4> Subranges;
218 Subranges.push_back(Subrange);
219 DINodeArray Subscripts = DIB.getOrCreateArray(Subranges);
220
221 auto getDIExpression = [&DIB](int offset) {
222 SmallVector<uint64_t, 4> ops;
223 ops.push_back(llvm::dwarf::DW_OP_push_object_address);
224 DIExpression::appendOffset(ops, offset);
225 ops.push_back(llvm::dwarf::DW_OP_deref);
226
227 return DIB.createExpression(ops);
228 };
229
230 DIFile *F = DIB.createFile("main.c", "/");
231 DICompileUnit *CU = DIB.createCompileUnit(
232 dwarf::DW_LANG_C, DIB.createFile("main.c", "/"), "llvm-c", true, "", 0);
233
234 DIVariable *DataLocation =
235 DIB.createTempGlobalVariableFwdDecl(CU, "dl", "_dl", F, 1, nullptr, true);
236 DIExpression *Associated = getDIExpression(1);
237 DIExpression *Allocated = getDIExpression(2);
238 DIExpression *Rank = DIB.createConstantValueExpression(3);
239
240 DICompositeType *ArrayType = DIB.createArrayType(0, 0, nullptr, Subscripts,
241 DataLocation, Associated,
242 Allocated, Rank);
243
244 EXPECT_TRUE(isa_and_nonnull<DICompositeType>(ArrayType));
245 EXPECT_EQ(ArrayType->getRawDataLocation(), DataLocation);
246 EXPECT_EQ(ArrayType->getRawAssociated(), Associated);
247 EXPECT_EQ(ArrayType->getRawAllocated(), Allocated);
248 EXPECT_EQ(ArrayType->getRawRank(), Rank);
249
250 // Avoid memory leak.
251 DIVariable::deleteTemporary(DataLocation);
252 }
253
254 TEST(DIBuilder, CreateSetType) {
255 LLVMContext Ctx;
256 std::unique_ptr<Module> M(new Module("MyModule", Ctx));
257 DIBuilder DIB(*M);
258 DIScope *Scope = DISubprogram::getDistinct(
259 Ctx, nullptr, "", "", nullptr, 0, nullptr, 0, nullptr, 0, 0,
260 DINode::FlagZero, DISubprogram::SPFlagZero, nullptr);
261 DIType *Type = DIB.createBasicType("Int", 64, dwarf::DW_ATE_signed);
262 DIFile *F = DIB.createFile("main.c", "/");
263
264 DIDerivedType *SetType = DIB.createSetType(Scope, "set1", F, 1, 64, 64, Type);
265 EXPECT_TRUE(isa_and_nonnull<DIDerivedType>(SetType));
266 }
267
268 TEST(DIBuilder, CreateStringType) {
269 LLVMContext Ctx;
270 std::unique_ptr<Module> M(new Module("MyModule", Ctx));
271 DIBuilder DIB(*M);
272 DIScope *Scope = DISubprogram::getDistinct(
273 Ctx, nullptr, "", "", nullptr, 0, nullptr, 0, nullptr, 0, 0,
274 DINode::FlagZero, DISubprogram::SPFlagZero, nullptr);
275 DIFile *F = DIB.createFile("main.c", "/");
276 StringRef StrName = "string";
277 DIVariable *StringLen = DIB.createAutoVariable(Scope, StrName, F, 0, nullptr,
278 false, DINode::FlagZero, 0);
279 auto getDIExpression = [&DIB](int offset) {
280 SmallVector<uint64_t, 4> ops;
281 ops.push_back(llvm::dwarf::DW_OP_push_object_address);
282 DIExpression::appendOffset(ops, offset);
283 ops.push_back(llvm::dwarf::DW_OP_deref);
284
285 return DIB.createExpression(ops);
286 };
287 DIExpression *StringLocationExp = getDIExpression(1);
288 DIStringType *StringType =
289 DIB.createStringType(StrName, StringLen, StringLocationExp);
290
291 EXPECT_TRUE(isa_and_nonnull<DIStringType>(StringType));
292 EXPECT_EQ(StringType->getName(), StrName);
293 EXPECT_EQ(StringType->getStringLength(), StringLen);
294 EXPECT_EQ(StringType->getStringLocationExp(), StringLocationExp);
295
296 StringRef StrNameExp = "stringexp";
297 DIExpression *StringLengthExp = getDIExpression(2);
298 DIStringType *StringTypeExp =
299 DIB.createStringType(StrNameExp, StringLengthExp, StringLocationExp);
300
301 EXPECT_TRUE(isa_and_nonnull<DIStringType>(StringTypeExp));
302 EXPECT_EQ(StringTypeExp->getName(), StrNameExp);
303 EXPECT_EQ(StringTypeExp->getStringLocationExp(), StringLocationExp);
304 EXPECT_EQ(StringTypeExp->getStringLengthExp(), StringLengthExp);
305 }
306
307 TEST(DIBuilder, DIEnumerator) {
308 LLVMContext Ctx;
309 std::unique_ptr<Module> M(new Module("MyModule", Ctx));
310 DIBuilder DIB(*M);
311 APSInt I1(APInt(32, 1));
312 APSInt I2(APInt(33, 1));
313
314 auto *E = DIEnumerator::get(Ctx, I1, I1.isSigned(), "name");
315 EXPECT_TRUE(E);
316
317 auto *E1 = DIEnumerator::getIfExists(Ctx, I1, I1.isSigned(), "name");
318 EXPECT_TRUE(E1);
319
320 auto *E2 = DIEnumerator::getIfExists(Ctx, I2, I1.isSigned(), "name");
321 EXPECT_FALSE(E2);
322 }
323
324 TEST(DIBuilder, createDbgAddr) {
325 LLVMContext C;
326 std::unique_ptr<Module> M = parseIR(C, R"(
327 define void @f() !dbg !6 {
328 %a = alloca i16, align 8
329 ;; It is important that we put the debug marker on the return.
330 ;; We take advantage of that to conjure up a debug loc without
331 ;; having to synthesize one programatically.
332 ret void, !dbg !11
333 }
334 declare void @llvm.dbg.value(metadata, metadata, metadata) #0
335 attributes #0 = { nounwind readnone speculatable willreturn }
336
337 !llvm.dbg.cu = !{!0}
338 !llvm.module.flags = !{!5}
339
340 !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
341 !1 = !DIFile(filename: "t.ll", directory: "/")
342 !2 = !{}
343 !5 = !{i32 2, !"Debug Info Version", i32 3}
344 !6 = distinct !DISubprogram(name: "foo", linkageName: "foo", scope: null, file: !1, line: 1, type: !7, scopeLine: 1, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !8)
345 !7 = !DISubroutineType(types: !2)
346 !8 = !{!9}
347 !9 = !DILocalVariable(name: "1", scope: !6, file: !1, line: 1, type: !10)
348 !10 = !DIBasicType(name: "ty16", size: 16, encoding: DW_ATE_unsigned)
349 !11 = !DILocation(line: 1, column: 1, scope: !6)
350 )");
351 auto *F = M->getFunction("f");
352 auto *EntryBlock = &F->getEntryBlock();
353
354 auto *CU =
355 cast<DICompileUnit>(M->getNamedMetadata("llvm.dbg.cu")->getOperand(0));
356 auto *Alloca = &*EntryBlock->begin();
357 auto *Ret = EntryBlock->getTerminator();
358
359 auto *SP = cast<DISubprogram>(F->getMetadata(LLVMContext::MD_dbg));
360 auto *File = SP->getFile();
361 std::string Name = "myName";
362 const auto *Loc = Ret->getDebugLoc().get();
363
364 IRBuilder<> Builder(EntryBlock);
365 DIBuilder DIB(*M, true, CU);
366 DIType *DT = DIB.createBasicType("ty16", 16, dwarf::DW_ATE_unsigned);
367
368 DILocalVariable *LocalVar =
369 DIB.createAutoVariable(SP, Name, File, 5 /*line*/, DT,
370 /*AlwaysPreserve=*/true);
371
372 auto *Inst = DIB.insertDbgAddrIntrinsic(Alloca, LocalVar,
373 DIB.createExpression(), Loc, Ret);
374
375 DIB.finalize();
376
377 EXPECT_EQ(Inst->getDebugLoc().get(), Loc);
378
379 auto *MD0 = cast<MetadataAsValue>(Inst->getOperand(0))->getMetadata();
380 auto *MD0Local = cast<LocalAsMetadata>(MD0);
381 EXPECT_EQ(MD0Local->getValue(), Alloca);
382 auto *MD1 = cast<MetadataAsValue>(Inst->getOperand(1))->getMetadata();
383 EXPECT_EQ(MD1->getMetadataID(), Metadata::MetadataKind::DILocalVariableKind);
384 auto *MD2 = cast<MetadataAsValue>(Inst->getOperand(2))->getMetadata();
385 auto *MDExp = cast<DIExpression>(MD2);
386 EXPECT_EQ(MDExp->getNumElements(), 0u);
387 }
388
389 TEST(DbgAssignIntrinsicTest, replaceVariableLocationOp) {
390 LLVMContext C;
391 std::unique_ptr<Module> M = parseIR(C, R"(
392 define dso_local void @fun(i32 %v1, ptr %p1, ptr %p2) !dbg !7 {
393 entry:
394 call void @llvm.dbg.assign(metadata i32 %v1, metadata !14, metadata !DIExpression(), metadata !17, metadata ptr %p1, metadata !DIExpression()), !dbg !16
395 ret void
396 }
397
398 declare void @llvm.dbg.assign(metadata, metadata, metadata, metadata, metadata, metadata)
399
400 !llvm.dbg.cu = !{!0}
401 !llvm.module.flags = !{!3}
402
403 !0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus_14, file: !1, producer: "clang version 14.0.0", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, splitDebugInlining: false, nameTableKind: None)
404 !1 = !DIFile(filename: "test.cpp", directory: "/")
405 !3 = !{i32 2, !"Debug Info Version", i32 3}
406 !7 = distinct !DISubprogram(name: "fun", linkageName: "fun", scope: !1, file: !1, line: 2, type: !8, scopeLine: 2, flags: DIFlagPrototyped | DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !11)
407 !8 = !DISubroutineType(types: !9)
408 !9 = !{null}
409 !10 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
410 !11 = !{}
411 !14 = !DILocalVariable(name: "Local", scope: !7, file: !1, line: 3, type: !10)
412 !16 = !DILocation(line: 0, scope: !7)
413 !17 = distinct !DIAssignID()
414 )");
415 // Check the test IR isn't malformed.
416 ASSERT_TRUE(M);
417
418 Function &Fun = *M->getFunction("fun");
419 Value *V1 = Fun.getArg(0);
420 Value *P1 = Fun.getArg(1);
421 Value *P2 = Fun.getArg(2);
422 DbgAssignIntrinsic *DAI = cast<DbgAssignIntrinsic>(Fun.begin()->begin());
423 ASSERT_TRUE(V1 == DAI->getVariableLocationOp(0));
424 ASSERT_TRUE(P1 == DAI->getAddress());
425
426 #define TEST_REPLACE(Old, New, ExpectedValue, ExpectedAddr) \
427 DAI->replaceVariableLocationOp(Old, New); \
428 EXPECT_EQ(DAI->getVariableLocationOp(0), ExpectedValue); \
429 EXPECT_EQ(DAI->getAddress(), ExpectedAddr);
430
431 // Replace address only.
432 TEST_REPLACE(/*Old*/ P1, /*New*/ P2, /*Value*/ V1, /*Address*/ P2);
433 // Replace value only.
434 TEST_REPLACE(/*Old*/ V1, /*New*/ P2, /*Value*/ P2, /*Address*/ P2);
435 // Replace both.
436 TEST_REPLACE(/*Old*/ P2, /*New*/ P1, /*Value*/ P1, /*Address*/ P1);
437
438 #undef TEST_REPLACE
439 }
440
441 TEST(AssignmentTrackingTest, Utils) {
442 // Test the assignment tracking utils defined in DebugInfo.h namespace at {}.
443 // This includes:
444 // getAssignmentInsts
445 // getAssignmentMarkers
446 // RAUW
447 // deleteAll
448 //
449 // The input IR includes two functions, fun1 and fun2. Both contain an alloca
450 // with a DIAssignID tag. fun1's alloca is linked to two llvm.dbg.assign
451 // intrinsics, one of which is for an inlined variable and appears before the
452 // alloca.
453
454 LLVMContext C;
455 std::unique_ptr<Module> M = parseIR(C, R"(
456 define dso_local void @fun1() !dbg !7 {
457 entry:
458 call void @llvm.dbg.assign(metadata i32 undef, metadata !10, metadata !DIExpression(), metadata !12, metadata i32 undef, metadata !DIExpression()), !dbg !13
459 %local = alloca i32, align 4, !DIAssignID !12
460 call void @llvm.dbg.assign(metadata i32 undef, metadata !16, metadata !DIExpression(), metadata !12, metadata i32 undef, metadata !DIExpression()), !dbg !15
461 ret void, !dbg !15
462 }
463
464 define dso_local void @fun2() !dbg !17 {
465 entry:
466 %local = alloca i32, align 4, !DIAssignID !20
467 call void @llvm.dbg.assign(metadata i32 undef, metadata !18, metadata !DIExpression(), metadata !20, metadata i32 undef, metadata !DIExpression()), !dbg !19
468 ret void, !dbg !19
469 }
470
471 define dso_local void @fun3() !dbg !21 {
472 entry:
473 %local = alloca i32, align 4, !DIAssignID !24
474 call void @llvm.dbg.assign(metadata i32 undef, metadata !22, metadata !DIExpression(), metadata !24, metadata i32* undef, metadata !DIExpression()), !dbg !23
475 ret void
476 }
477
478 declare void @llvm.dbg.assign(metadata, metadata, metadata, metadata, metadata, metadata)
479
480 !llvm.dbg.cu = !{!0}
481 !llvm.module.flags = !{!3, !4, !5}
482 !llvm.ident = !{!6}
483
484 !0 = distinct !DICompileUnit(language: DW_LANG_C99, file: !1, producer: "clang version 14.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !2, splitDebugInlining: false, nameTableKind: None)
485 !1 = !DIFile(filename: "test.c", directory: "/")
486 !2 = !{}
487 !3 = !{i32 7, !"Dwarf Version", i32 4}
488 !4 = !{i32 2, !"Debug Info Version", i32 3}
489 !5 = !{i32 1, !"wchar_size", i32 4}
490 !6 = !{!"clang version 14.0.0"}
491 !7 = distinct !DISubprogram(name: "fun1", scope: !1, file: !1, line: 1, type: !8, scopeLine: 1, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
492 !8 = !DISubroutineType(types: !9)
493 !9 = !{null}
494 !10 = !DILocalVariable(name: "local3", scope: !14, file: !1, line: 2, type: !11)
495 !11 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
496 !12 = distinct !DIAssignID()
497 !13 = !DILocation(line: 5, column: 1, scope: !14, inlinedAt: !15)
498 !14 = distinct !DISubprogram(name: "inline", scope: !1, file: !1, line: 1, type: !8, scopeLine: 1, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
499 !15 = !DILocation(line: 3, column: 1, scope: !7)
500 !16 = !DILocalVariable(name: "local1", scope: !7, file: !1, line: 2, type: !11)
501 !17 = distinct !DISubprogram(name: "fun2", scope: !1, file: !1, line: 1, type: !8, scopeLine: 1, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
502 !18 = !DILocalVariable(name: "local2", scope: !17, file: !1, line: 2, type: !11)
503 !19 = !DILocation(line: 4, column: 1, scope: !17)
504 !20 = distinct !DIAssignID()
505 !21 = distinct !DISubprogram(name: "fun3", scope: !1, file: !1, line: 1, type: !8, scopeLine: 1, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
506 !22 = !DILocalVariable(name: "local4", scope: !21, file: !1, line: 2, type: !11)
507 !23 = !DILocation(line: 4, column: 1, scope: !21)
508 !24 = distinct !DIAssignID()
509 )");
510
511 // Check the test IR isn't malformed.
512 ASSERT_TRUE(M);
513
514 Function &Fun1 = *M->getFunction("fun1");
515 Instruction &Alloca = *Fun1.getEntryBlock().getFirstNonPHIOrDbg();
516
517 // 1. Check the Instruction <-> Intrinsic mappings work in fun1.
518 //
519 // Check there are two llvm.dbg.assign intrinsics linked to Alloca.
520 auto CheckFun1Mapping = [&Alloca]() {
521 auto Markers = at::getAssignmentMarkers(&Alloca);
522 EXPECT_TRUE(std::distance(Markers.begin(), Markers.end()) == 2);
523 // Check those two entries are distinct.
524 DbgAssignIntrinsic *First = *Markers.begin();
525 DbgAssignIntrinsic *Second = *std::next(Markers.begin());
526 EXPECT_NE(First, Second);
527
528 // Check that we can get back to Alloca from each llvm.dbg.assign.
529 for (auto *DAI : Markers) {
530 auto Insts = at::getAssignmentInsts(DAI);
531 // Check there is exactly one instruction linked to each intrinsic. Use
532 // ASSERT_TRUE because we're going to dereference the begin iterator.
533 ASSERT_TRUE(std::distance(Insts.begin(), Insts.end()) == 1);
534 EXPECT_FALSE(Insts.empty());
535 // Check the linked instruction is Alloca.
536 Instruction *LinkedInst = *Insts.begin();
537 EXPECT_EQ(LinkedInst, &Alloca);
538 }
539 };
540 CheckFun1Mapping();
541
542 // 2. Check DIAssignID RAUW replaces attachments and uses.
543 //
544 DIAssignID *Old =
545 cast_or_null<DIAssignID>(Alloca.getMetadata(LLVMContext::MD_DIAssignID));
546 DIAssignID *New = DIAssignID::getDistinct(C);
547 ASSERT_TRUE(Old && New && New != Old);
548 at::RAUW(Old, New);
549 // Check fun1's alloca and intrinsics have been updated and the mapping still
550 // works.
551 EXPECT_EQ(New, cast_or_null<DIAssignID>(
552 Alloca.getMetadata(LLVMContext::MD_DIAssignID)));
553 CheckFun1Mapping();
554
555 // Check that fun2's alloca and intrinsic have not not been updated.
556 Instruction &Fun2Alloca =
557 *M->getFunction("fun2")->getEntryBlock().getFirstNonPHIOrDbg();
558 DIAssignID *Fun2ID = cast_or_null<DIAssignID>(
559 Fun2Alloca.getMetadata(LLVMContext::MD_DIAssignID));
560 EXPECT_NE(New, Fun2ID);
561 auto Fun2Markers = at::getAssignmentMarkers(&Fun2Alloca);
562 ASSERT_TRUE(std::distance(Fun2Markers.begin(), Fun2Markers.end()) == 1);
563 auto Fun2Insts = at::getAssignmentInsts(*Fun2Markers.begin());
564 ASSERT_TRUE(std::distance(Fun2Insts.begin(), Fun2Insts.end()) == 1);
565 EXPECT_EQ(*Fun2Insts.begin(), &Fun2Alloca);
566
567 // 3. Check that deleting dbg.assigns from a specific instruction works.
568 Instruction &Fun3Alloca =
569 *M->getFunction("fun3")->getEntryBlock().getFirstNonPHIOrDbg();
570 auto Fun3Markers = at::getAssignmentMarkers(&Fun3Alloca);
571 ASSERT_TRUE(std::distance(Fun3Markers.begin(), Fun3Markers.end()) == 1);
572 at::deleteAssignmentMarkers(&Fun3Alloca);
573 Fun3Markers = at::getAssignmentMarkers(&Fun3Alloca);
574 EXPECT_EQ(Fun3Markers.empty(), true);
575
576 // 4. Check that deleting works and applies only to the target function.
577 at::deleteAll(&Fun1);
578 // There should now only be the alloca and ret in fun1.
579 EXPECT_EQ(Fun1.begin()->size(), 2u);
580 // fun2's alloca should have the same DIAssignID and remain linked to its
581 // llvm.dbg.assign.
582 EXPECT_EQ(Fun2ID, cast_or_null<DIAssignID>(
583 Fun2Alloca.getMetadata(LLVMContext::MD_DIAssignID)));
584 EXPECT_FALSE(at::getAssignmentMarkers(&Fun2Alloca).empty());
585 }
586
587 TEST(AssignmentTrackingTest, InstrMethods) {
588 // Test the assignment tracking Instruction methods.
589 // This includes:
590 // Instruction::mergeDIAssignID
591
592 LLVMContext C;
593 std::unique_ptr<Module> M = parseIR(C, R"(
594 define dso_local void @fun() #0 !dbg !8 {
595 entry:
596 %Local = alloca [2 x i32], align 4, !DIAssignID !12
597 call void @llvm.dbg.assign(metadata i1 undef, metadata !13, metadata !DIExpression(), metadata !12, metadata [2 x i32]* %Local, metadata !DIExpression()), !dbg !18
598 %arrayidx = getelementptr inbounds [2 x i32], [2 x i32]* %Local, i64 0, i64 0, !dbg !19
599 store i32 5, i32* %arrayidx, align 4, !dbg !20, !DIAssignID !21
600 call void @llvm.dbg.assign(metadata i32 5, metadata !13, metadata !DIExpression(DW_OP_LLVM_fragment, 0, 32), metadata !21, metadata i32* %arrayidx, metadata !DIExpression()), !dbg !18
601 %arrayidx1 = getelementptr inbounds [2 x i32], [2 x i32]* %Local, i64 0, i64 1, !dbg !22
602 store i32 6, i32* %arrayidx1, align 4, !dbg !23, !DIAssignID !24
603 call void @llvm.dbg.assign(metadata i32 6, metadata !13, metadata !DIExpression(DW_OP_LLVM_fragment, 32, 32), metadata !24, metadata i32* %arrayidx1, metadata !DIExpression()), !dbg !18
604 ret void, !dbg !25
605 }
606
607 declare void @llvm.dbg.assign(metadata, metadata, metadata, metadata, metadata, metadata) #1
608
609 !llvm.dbg.cu = !{!0}
610 !llvm.module.flags = !{!2, !3, !4, !5, !6}
611 !llvm.ident = !{!7}
612
613 !0 = distinct !DICompileUnit(language: DW_LANG_C_plus_plus_14, file: !1, producer: "clang version 14.0.0", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, splitDebugInlining: false, nameTableKind: None)
614 !1 = !DIFile(filename: "test.cpp", directory: "/")
615 !2 = !{i32 7, !"Dwarf Version", i32 5}
616 !3 = !{i32 2, !"Debug Info Version", i32 3}
617 !4 = !{i32 1, !"wchar_size", i32 4}
618 !5 = !{i32 7, !"uwtable", i32 1}
619 !6 = !{i32 7, !"frame-pointer", i32 2}
620 !7 = !{!"clang version 14.0.0"}
621 !8 = distinct !DISubprogram(name: "fun", linkageName: "fun", scope: !1, file: !1, line: 1, type: !9, scopeLine: 1, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !11)
622 !9 = !DISubroutineType(types: !10)
623 !10 = !{null}
624 !11 = !{}
625 !12 = distinct !DIAssignID()
626 !13 = !DILocalVariable(name: "Local", scope: !8, file: !1, line: 2, type: !14)
627 !14 = !DICompositeType(tag: DW_TAG_array_type, baseType: !15, size: 64, elements: !16)
628 !15 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
629 !16 = !{!17}
630 !17 = !DISubrange(count: 2)
631 !18 = !DILocation(line: 0, scope: !8)
632 !19 = !DILocation(line: 3, column: 3, scope: !8)
633 !20 = !DILocation(line: 3, column: 12, scope: !8)
634 !21 = distinct !DIAssignID()
635 !22 = !DILocation(line: 4, column: 3, scope: !8)
636 !23 = !DILocation(line: 4, column: 12, scope: !8)
637 !24 = distinct !DIAssignID()
638 !25 = !DILocation(line: 5, column: 1, scope: !8)
639 )");
640
641 // Check the test IR isn't malformed.
642 ASSERT_TRUE(M);
643 Function &Fun = *M->getFunction("fun");
644 SmallVector<Instruction *> Stores;
645 for (auto &BB : Fun) {
646 for (auto &I : BB) {
647 if (isa<StoreInst>(&I))
648 Stores.push_back(&I);
649 }
650 }
651
652 // The test requires (at least) 2 stores.
653 ASSERT_TRUE(Stores.size() == 2);
654 // Use SetVectors to check that the attachments and markers are unique
655 // (another test requirement).
656 SetVector<Metadata *> OrigIDs;
657 SetVector<DbgAssignIntrinsic *> Markers;
658 for (const Instruction *SI : Stores) {
659 Metadata *ID = SI->getMetadata(LLVMContext::MD_DIAssignID);
660 ASSERT_TRUE(OrigIDs.insert(ID));
661 ASSERT_TRUE(ID != nullptr);
662 auto Range = at::getAssignmentMarkers(SI);
663 ASSERT_TRUE(std::distance(Range.begin(), Range.end()) == 1);
664 ASSERT_TRUE(Markers.insert(*Range.begin()));
665 }
666
667 // Test 1 - mergeDIAssignID.
668 //
669 // Input store0->mergeDIAssignID(store1)
670 // ----- -------------------------
671 // store0 !x store0 !x
672 // dbg.assign0 !x dbg.assign !x
673 // store1 !y store1 !x
674 // dbg.assign1 !y dbg.assign1 !x
675 {
676 Stores[0]->mergeDIAssignID(Stores[1]);
677 // Check that the stores share the same ID.
678 Metadata *NewID0 = Stores[0]->getMetadata(LLVMContext::MD_DIAssignID);
679 Metadata *NewID1 = Stores[1]->getMetadata(LLVMContext::MD_DIAssignID);
680 EXPECT_NE(NewID0, nullptr);
681 EXPECT_EQ(NewID0, NewID1);
682 EXPECT_EQ(Markers[0]->getAssignID(), NewID0);
683 EXPECT_EQ(Markers[1]->getAssignID(), NewID0);
684 }
685
686 // Test 2 - mergeDIAssignID.
687 //
688 // Input store0->mergeDIAssignID(store1)
689 // ----- -------------------------
690 // store0 !x store0 !x
691 // dbg.assign0 !x dbg.assign !x
692 // store1 store1
693 {
694 Stores[1]->setMetadata(LLVMContext::MD_DIAssignID, nullptr);
695 Stores[0]->mergeDIAssignID(Stores[1]);
696 // Check that store1 doesn't get a new ID.
697 Metadata *NewID0 = Stores[0]->getMetadata(LLVMContext::MD_DIAssignID);
698 Metadata *NewID1 = Stores[1]->getMetadata(LLVMContext::MD_DIAssignID);
699 EXPECT_NE(NewID0, nullptr);
700 EXPECT_EQ(NewID1, nullptr);
701 EXPECT_EQ(Markers[0]->getAssignID(), NewID0);
702 }
703
704 // Test 3 - mergeDIAssignID.
705 //
706 // Input store1->mergeDIAssignID(store0)
707 // ----- -------------------------
708 // store0 !x store0 !x
709 // dbg.assign0 !x dbg.assign !x
710 // store1 store1 !x
711 {
712 Stores[1]->setMetadata(LLVMContext::MD_DIAssignID, nullptr);
713 Stores[1]->mergeDIAssignID(Stores[0]);
714 // Check that the stores share the same ID (note store1 starts with none).
715 Metadata *NewID0 = Stores[0]->getMetadata(LLVMContext::MD_DIAssignID);
716 Metadata *NewID1 = Stores[1]->getMetadata(LLVMContext::MD_DIAssignID);
717 EXPECT_NE(NewID0, nullptr);
718 EXPECT_EQ(NewID0, NewID1);
719 EXPECT_EQ(Markers[0]->getAssignID(), NewID0);
720 }
721
722 // Test 4 - mergeDIAssignID.
723 //
724 // Input store1->mergeDIAssignID(store0)
725 // ----- -------------------------
726 // store0 !x store0 !x
727 // dbg.assign0 !x dbg.assign !x
728 // store1 !x store1 !x
729 {
730 Stores[0]->mergeDIAssignID(Stores[1]);
731 // Check that the stores share the same ID.
732 Metadata *NewID0 = Stores[0]->getMetadata(LLVMContext::MD_DIAssignID);
733 Metadata *NewID1 = Stores[1]->getMetadata(LLVMContext::MD_DIAssignID);
734 EXPECT_NE(NewID0, nullptr);
735 EXPECT_EQ(NewID0, NewID1);
736 EXPECT_EQ(Markers[0]->getAssignID(), NewID0);
737 }
738
739 // Test 5 - dropUnknownNonDebugMetadata.
740 //
741 // Input store0->dropUnknownNonDebugMetadata()
742 // ----- -------------------------
743 // store0 !x store0 !x
744 {
745 Stores[0]->dropUnknownNonDebugMetadata();
746 Metadata *NewID0 = Stores[0]->getMetadata(LLVMContext::MD_DIAssignID);
747 EXPECT_NE(NewID0, nullptr);
748 }
749 }
750
751 } // end namespace