Debian Codegraph @

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 "../lib/IR/LLVMContextImpl.h"
11 #include "llvm/ADT/APSInt.h"
12 #include "llvm/AsmParser/Parser.h"
13 #include "llvm/IR/DIBuilder.h"
14 #include "llvm/IR/DebugInfoMetadata.h"
15 #include "llvm/IR/DebugProgramInstruction.h"
16 #include "llvm/IR/IRBuilder.h"
17 #include "llvm/IR/IntrinsicInst.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/IR/Metadata.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IR/Verifier.h"
22 #include "llvm/Support/Compiler.h"
23 #include "llvm/Support/SourceMgr.h"
24 #include "llvm/Transforms/Utils/Local.h"
25
26 #include "gtest/gtest.h"
27
28 using namespace llvm;
29
30 static std::unique_ptr<Module> parseIR(LLVMContext &C, const char *IR) {
31 SMDiagnostic Err;
32 std::unique_ptr<Module> Mod = parseAssemblyString(IR, Err, C);
33 if (!Mod)
34 Err.print("DebugInfoTest", errs());
35 return Mod;
36 }
37
38 namespace {
39
40 TEST(DINodeTest, getFlag) {
41 // Some valid flags.
42 EXPECT_EQ(DINode::FlagPublic, DINode::getFlag("DIFlagPublic"));
43 EXPECT_EQ(DINode::FlagProtected, DINode::getFlag("DIFlagProtected"));
44 EXPECT_EQ(DINode::FlagPrivate, DINode::getFlag("DIFlagPrivate"));
45 EXPECT_EQ(DINode::FlagVector, DINode::getFlag("DIFlagVector"));
46 EXPECT_EQ(DINode::FlagRValueReference,
47 DINode::getFlag("DIFlagRValueReference"));
48
49 // FlagAccessibility shouldn't work.
50 EXPECT_EQ(0u, DINode::getFlag("DIFlagAccessibility"));
51
52 // Some other invalid strings.
53 EXPECT_EQ(0u, DINode::getFlag("FlagVector"));
54 EXPECT_EQ(0u, DINode::getFlag("Vector"));
55 EXPECT_EQ(0u, DINode::getFlag("other things"));
56 EXPECT_EQ(0u, DINode::getFlag("DIFlagOther"));
57 }
58
59 TEST(DINodeTest, getFlagString) {
60 // Some valid flags.
61 EXPECT_EQ(StringRef("DIFlagPublic"),
62 DINode::getFlagString(DINode::FlagPublic));
63 EXPECT_EQ(StringRef("DIFlagProtected"),
64 DINode::getFlagString(DINode::FlagProtected));
65 EXPECT_EQ(StringRef("DIFlagPrivate"),
66 DINode::getFlagString(DINode::FlagPrivate));
67 EXPECT_EQ(StringRef("DIFlagVector"),
68 DINode::getFlagString(DINode::FlagVector));
69 EXPECT_EQ(StringRef("DIFlagRValueReference"),
70 DINode::getFlagString(DINode::FlagRValueReference));
71
72 // FlagAccessibility actually equals FlagPublic.
73 EXPECT_EQ(StringRef("DIFlagPublic"),
74 DINode::getFlagString(DINode::FlagAccessibility));
75
76 // Some other invalid flags.
77 EXPECT_EQ(StringRef(),
78 DINode::getFlagString(DINode::FlagPublic | DINode::FlagVector));
79 EXPECT_EQ(StringRef(), DINode::getFlagString(DINode::FlagFwdDecl |
80 DINode::FlagArtificial));
81 EXPECT_EQ(StringRef(),
82 DINode::getFlagString(static_cast<DINode::DIFlags>(0xffff)));
83 }
84
85 TEST(DINodeTest, splitFlags) {
86 // Some valid flags.
87 #define CHECK_SPLIT(FLAGS, VECTOR, REMAINDER) \
88 { \
89 SmallVector<DINode::DIFlags, 8> V; \
90 EXPECT_EQ(REMAINDER, DINode::splitFlags(FLAGS, V)); \
91 EXPECT_TRUE(ArrayRef(V).equals(VECTOR)); \
92 }
93 CHECK_SPLIT(DINode::FlagPublic, {DINode::FlagPublic}, DINode::FlagZero);
94 CHECK_SPLIT(DINode::FlagProtected, {DINode::FlagProtected}, DINode::FlagZero);
95 CHECK_SPLIT(DINode::FlagPrivate, {DINode::FlagPrivate}, DINode::FlagZero);
96 CHECK_SPLIT(DINode::FlagVector, {DINode::FlagVector}, DINode::FlagZero);
97 CHECK_SPLIT(DINode::FlagRValueReference, {DINode::FlagRValueReference},
98 DINode::FlagZero);
99 DINode::DIFlags Flags[] = {DINode::FlagFwdDecl, DINode::FlagVector};
100 CHECK_SPLIT(DINode::FlagFwdDecl | DINode::FlagVector, Flags,
101 DINode::FlagZero);
102 CHECK_SPLIT(DINode::FlagZero, {}, DINode::FlagZero);
103 #undef CHECK_SPLIT
104 }
105
106 TEST(StripTest, LoopMetadata) {
107 LLVMContext C;
108 std::unique_ptr<Module> M = parseIR(C, R"(
109 define void @f() !dbg !5 {
110 ret void, !dbg !10, !llvm.loop !11
111 }
112
113 !llvm.dbg.cu = !{!0}
114 !llvm.debugify = !{!3, !3}
115 !llvm.module.flags = !{!4}
116
117 !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
118 !1 = !DIFile(filename: "loop.ll", directory: "/")
119 !2 = !{}
120 !3 = !{i32 1}
121 !4 = !{i32 2, !"Debug Info Version", i32 3}
122 !5 = distinct !DISubprogram(name: "f", linkageName: "f", scope: null, file: !1, line: 1, type: !6, scopeLine: 1, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !7)
123 !6 = !DISubroutineType(types: !2)
124 !7 = !{!8}
125 !8 = !DILocalVariable(name: "1", scope: !5, file: !1, line: 1, type: !9)
126 !9 = !DIBasicType(name: "ty32", size: 32, encoding: DW_ATE_unsigned)
127 !10 = !DILocation(line: 1, column: 1, scope: !5)
128 !11 = distinct !{!11, !10, !10}
129 )");
130
131 // Look up the debug info emission kind for the CU via the loop metadata
132 // attached to the terminator. If, when stripping non-line table debug info,
133 // we update the terminator's metadata correctly, we should be able to
134 // observe the change in emission kind for the CU.
135 auto getEmissionKind = [&]() {
136 Instruction &I = *M->getFunction("f")->getEntryBlock().getFirstNonPHIIt();
137 MDNode *LoopMD = I.getMetadata(LLVMContext::MD_loop);
138 return cast<DILocation>(LoopMD->getOperand(1))
139 ->getScope()
140 ->getSubprogram()
141 ->getUnit()
142 ->getEmissionKind();
143 };
144
145 EXPECT_EQ(getEmissionKind(), DICompileUnit::FullDebug);
146
147 bool Changed = stripNonLineTableDebugInfo(*M);
148 EXPECT_TRUE(Changed);
149
150 EXPECT_EQ(getEmissionKind(), DICompileUnit::LineTablesOnly);
151
152 bool BrokenDebugInfo = false;
153 bool HardError = verifyModule(*M, &errs(), &BrokenDebugInfo);
154 EXPECT_FALSE(HardError);
155 EXPECT_FALSE(BrokenDebugInfo);
156 }
157
158 TEST(MetadataTest, DeleteInstUsedByDbgRecord) {
159 LLVMContext C;
160 std::unique_ptr<Module> M = parseIR(C, R"(
161 define i16 @f(i16 %a) !dbg !6 {
162 %b = add i16 %a, 1, !dbg !11
163 call void @llvm.dbg.value(metadata i16 %b, metadata !9, metadata !DIExpression()), !dbg !11
164 ret i16 0, !dbg !11
165 }
166 declare void @llvm.dbg.value(metadata, metadata, metadata) #0
167 attributes #0 = { nounwind readnone speculatable willreturn }
168
169 !llvm.dbg.cu = !{!0}
170 !llvm.module.flags = !{!5}
171
172 !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
173 !1 = !DIFile(filename: "t.ll", directory: "/")
174 !2 = !{}
175 !5 = !{i32 2, !"Debug Info Version", i32 3}
176 !6 = distinct !DISubprogram(name: "foo", linkageName: "foo", scope: null, file: !1, line: 1, type: !7, scopeLine: 1, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !8)
177 !7 = !DISubroutineType(types: !2)
178 !8 = !{!9}
179 !9 = !DILocalVariable(name: "1", scope: !6, file: !1, line: 1, type: !10)
180 !10 = !DIBasicType(name: "ty16", size: 16, encoding: DW_ATE_unsigned)
181 !11 = !DILocation(line: 1, column: 1, scope: !6)
182 )");
183
184 // Find %b = add ...
185 Instruction &I = *M->getFunction("f")->getEntryBlock().getFirstNonPHIIt();
186
187 // Find the dbg.value using %b.
188 SmallVector<DbgValueInst *, 1> DVIs;
189 SmallVector<DbgVariableRecord *, 1> DVRs;
190 findDbgValues(DVIs, &I, &DVRs);
191
192 // Delete %b. The dbg.value should now point to undef.
193 I.eraseFromParent();
194 EXPECT_EQ(DVRs[0]->getNumVariableLocationOps(), 1u);
195 EXPECT_TRUE(isa<UndefValue>(DVRs[0]->getValue(0)));
196 }
197
198 TEST(MetadataTest, GlobalConstantMetadataUsedByDbgRecord) {
199 LLVMContext C;
200 std::unique_ptr<Module> M = parseIR(C, R"(
201 @x = dso_local global i32 0, align 4
202 declare void @llvm.dbg.value(metadata, metadata, metadata) #0
203
204 define i16 @f(i16 %a) !dbg !6 {
205 %b = add i16 %a, 1, !dbg !11
206 call void @llvm.dbg.declare(metadata ptr @x, metadata !9, metadata !DIExpression()), !dbg !11
207 call void @llvm.dbg.value(metadata ptr @x, metadata !9, metadata !DIExpression()), !dbg !11
208 ret i16 0, !dbg !11
209 }
210
211 attributes #0 = { nounwind readnone speculatable willreturn }
212
213 !llvm.dbg.cu = !{!0}
214 !llvm.module.flags = !{!5}
215
216 !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
217 !1 = !DIFile(filename: "t.ll", directory: "/")
218 !2 = !{}
219 !5 = !{i32 2, !"Debug Info Version", i32 3}
220 !6 = distinct !DISubprogram(name: "foo", linkageName: "foo", scope: null, file: !1, line: 1, type: !7, scopeLine: 1, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !8)
221 !7 = !DISubroutineType(types: !2)
222 !8 = !{!9}
223 !9 = !DILocalVariable(name: "1", scope: !6, file: !1, line: 1, type: !10)
224 !10 = !DIBasicType(name: "ty16", size: 16, encoding: DW_ATE_unsigned)
225 !11 = !DILocation(line: 1, column: 1, scope: !6)
226 )");
227
228 // Find the global @x
229 Value *V = M->getNamedValue("x");
230
231 // Find the dbg.value
232 auto DVIs = findDbgDeclares(V);
233 auto DVRs = findDVRDeclares(V);
234 auto DVRVs = findDVRValues(V);
235
236 EXPECT_EQ(DVRs[0]->getNumVariableLocationOps(), 1u);
237 EXPECT_TRUE(DVRVs.size() == 1);
238 EXPECT_FALSE(isa<UndefValue>(DVRs[0]->getValue(0)));
239 }
240
241 TEST(DbgVariableIntrinsic, EmptyMDIsKillLocation) {
242 LLVMContext Ctx;
243 std::unique_ptr<Module> M = parseIR(Ctx, R"(
244 define dso_local void @fun() local_unnamed_addr #0 !dbg !9 {
245 entry:
246 call void @llvm.dbg.declare(metadata !{}, metadata !13, metadata !DIExpression()), !dbg !16
247 ret void, !dbg !16
248 }
249
250 declare void @llvm.dbg.declare(metadata, metadata, metadata)
251
252 !llvm.dbg.cu = !{!0}
253 !llvm.module.flags = !{!2, !3}
254 !llvm.ident = !{!8}
255
256 !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)
257 !1 = !DIFile(filename: "test.c", directory: "/")
258 !2 = !{i32 7, !"Dwarf Version", i32 5}
259 !3 = !{i32 2, !"Debug Info Version", i32 3}
260 !8 = !{!"clang version 16.0.0"}
261 !9 = distinct !DISubprogram(name: "fun", scope: !1, file: !1, line: 1, type: !10, scopeLine: 1, flags: DIFlagAllCallsDescribed, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !12)
262 !10 = !DISubroutineType(types: !11)
263 !11 = !{null}
264 !12 = !{!13}
265 !13 = !DILocalVariable(name: "a", scope: !9, file: !1, line: 1, type: !14)
266 !14 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
267 !16 = !DILocation(line: 1, column: 21, scope: !9)
268 )");
269
270 bool BrokenDebugInfo = true;
271 verifyModule(*M, &errs(), &BrokenDebugInfo);
272 ASSERT_FALSE(BrokenDebugInfo);
273
274 // Get the dbg.declare.
275 Function &F = *cast<Function>(M->getNamedValue("fun"));
276 DbgVariableRecord *DbgDeclare =
277 cast<DbgVariableRecord>(&*F.front().front().getDbgRecordRange().begin());
278 // Check that this form counts as a "no location" marker.
279 EXPECT_TRUE(DbgDeclare->isKillLocation());
280 }
281
282 // Duplicate of above test, but in DbgVariableRecord representation.
283 TEST(MetadataTest, DeleteInstUsedByDbgVariableRecord) {
284 LLVMContext C;
285
286 std::unique_ptr<Module> M = parseIR(C, R"(
287 define i16 @f(i16 %a) !dbg !6 {
288 %b = add i16 %a, 1, !dbg !11
289 call void @llvm.dbg.value(metadata i16 %b, metadata !9, metadata !DIExpression()), !dbg !11
290 call void @llvm.dbg.value(metadata !DIArgList(i16 %a, i16 %b), metadata !9, metadata !DIExpression(DW_OP_LLVM_arg, 0, DW_OP_LLVM_arg, 1, DW_OP_plus)), !dbg !11
291 ret i16 0, !dbg !11
292 }
293 declare void @llvm.dbg.value(metadata, metadata, metadata) #0
294 attributes #0 = { nounwind readnone speculatable willreturn }
295
296 !llvm.dbg.cu = !{!0}
297 !llvm.module.flags = !{!5}
298
299 !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
300 !1 = !DIFile(filename: "t.ll", directory: "/")
301 !2 = !{}
302 !5 = !{i32 2, !"Debug Info Version", i32 3}
303 !6 = distinct !DISubprogram(name: "foo", linkageName: "foo", scope: null, file: !1, line: 1, type: !7, scopeLine: 1, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !8)
304 !7 = !DISubroutineType(types: !2)
305 !8 = !{!9}
306 !9 = !DILocalVariable(name: "1", scope: !6, file: !1, line: 1, type: !10)
307 !10 = !DIBasicType(name: "ty16", size: 16, encoding: DW_ATE_unsigned)
308 !11 = !DILocation(line: 1, column: 1, scope: !6)
309 )");
310
311 Instruction &I = *M->getFunction("f")->getEntryBlock().getFirstNonPHIIt();
312
313 // Find the DbgVariableRecords using %b.
314 SmallVector<DbgValueInst *, 2> DVIs;
315 SmallVector<DbgVariableRecord *, 2> DVRs;
316 findDbgValues(DVIs, &I, &DVRs);
317 ASSERT_EQ(DVRs.size(), 2u);
318
319 // Delete %b. The DbgVariableRecord should now point to undef.
320 I.eraseFromParent();
321 EXPECT_EQ(DVRs[0]->getNumVariableLocationOps(), 1u);
322 EXPECT_TRUE(isa<UndefValue>(DVRs[0]->getVariableLocationOp(0)));
323 EXPECT_TRUE(DVRs[0]->isKillLocation());
324 EXPECT_EQ(DVRs[1]->getNumVariableLocationOps(), 2u);
325 EXPECT_TRUE(isa<UndefValue>(DVRs[1]->getVariableLocationOp(1)));
326 EXPECT_TRUE(DVRs[1]->isKillLocation());
327 }
328
329 // Ensure that the order of dbg.value intrinsics returned by findDbgValues, and
330 // their corresponding DbgVariableRecord representation, are consistent.
331 TEST(MetadataTest, OrderingOfDbgVariableRecords) {
332 LLVMContext C;
333 std::unique_ptr<Module> M = parseIR(C, R"(
334 define i16 @f(i16 %a) !dbg !6 {
335 %b = add i16 %a, 1, !dbg !11
336 #dbg_value(i16 %b, !9, !DIExpression(), !11)
337 #dbg_value(i16 %b, !12, !DIExpression(), !11)
338 ret i16 0, !dbg !11
339 }
340 attributes #0 = { nounwind readnone speculatable willreturn }
341
342 !llvm.dbg.cu = !{!0}
343 !llvm.module.flags = !{!5}
344
345 !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
346 !1 = !DIFile(filename: "t.ll", directory: "/")
347 !2 = !{}
348 !5 = !{i32 2, !"Debug Info Version", i32 3}
349 !6 = distinct !DISubprogram(name: "foo", linkageName: "foo", scope: null, file: !1, line: 1, type: !7, scopeLine: 1, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !8)
350 !7 = !DISubroutineType(types: !2)
351 !8 = !{!9}
352 !9 = !DILocalVariable(name: "foo", scope: !6, file: !1, line: 1, type: !10)
353 !10 = !DIBasicType(name: "ty16", size: 16, encoding: DW_ATE_unsigned)
354 !11 = !DILocation(line: 1, column: 1, scope: !6)
355 !12 = !DILocalVariable(name: "bar", scope: !6, file: !1, line: 1, type: !10)
356 )");
357
358 Instruction &I = *M->getFunction("f")->getEntryBlock().getFirstNonPHIIt();
359
360 SmallVector<DbgValueInst *, 2> DVIs;
361 SmallVector<DbgVariableRecord *, 2> DVRs;
362
363 findDbgValues(DVIs, &I, &DVRs);
364 ASSERT_EQ(DVIs.size(), 0u);
365 ASSERT_EQ(DVRs.size(), 2u);
366
367 // The correct order of dbg.values is given by their use-list, which becomes
368 // the reverse order of creation. Thus the dbg.values should come out as
369 // "bar" and then "foo".
370 const DILocalVariable *Var0 = DVRs[0]->getVariable();
371 EXPECT_TRUE(Var0->getName() == "bar");
372 const DILocalVariable *Var1 = DVRs[1]->getVariable();
373 EXPECT_TRUE(Var1->getName() == "foo");
374
375 M->convertFromNewDbgValues();
376 }
377
378 TEST(DIBuilder, CreateFile) {
379 LLVMContext Ctx;
380 std::unique_ptr<Module> M(new Module("MyModule", Ctx));
381 DIBuilder DIB(*M);
382
383 DIFile *F = DIB.createFile("main.c", "/");
384 EXPECT_EQ(std::nullopt, F->getSource());
385
386 std::optional<DIFile::ChecksumInfo<StringRef>> Checksum;
387 std::optional<StringRef> Source;
388 F = DIB.createFile("main.c", "/", Checksum, Source);
389 EXPECT_EQ(Source, F->getSource());
390
391 Source = "";
392 F = DIB.createFile("main.c", "/", Checksum, Source);
393 EXPECT_EQ(Source, F->getSource());
394 }
395
396 TEST(DIBuilder, CreateFortranArrayTypeWithAttributes) {
397 LLVMContext Ctx;
398 std::unique_ptr<Module> M(new Module("MyModule", Ctx));
399 DIBuilder DIB(*M);
400
401 DISubrange *Subrange = DIB.getOrCreateSubrange(1,1);
402 SmallVector<Metadata*, 4> Subranges;
403 Subranges.push_back(Subrange);
404 DINodeArray Subscripts = DIB.getOrCreateArray(Subranges);
405
406 auto getDIExpression = [&DIB](int offset) {
407 SmallVector<uint64_t, 4> ops;
408 ops.push_back(llvm::dwarf::DW_OP_push_object_address);
409 DIExpression::appendOffset(ops, offset);
410 ops.push_back(llvm::dwarf::DW_OP_deref);
411
412 return DIB.createExpression(ops);
413 };
414
415 DIFile *F = DIB.createFile("main.c", "/");
416 DICompileUnit *CU = DIB.createCompileUnit(
417 dwarf::DW_LANG_C, DIB.createFile("main.c", "/"), "llvm-c", true, "", 0);
418
419 DIVariable *DataLocation =
420 DIB.createTempGlobalVariableFwdDecl(CU, "dl", "_dl", F, 1, nullptr, true);
421 DIExpression *Associated = getDIExpression(1);
422 DIExpression *Allocated = getDIExpression(2);
423 DIExpression *Rank = DIB.createConstantValueExpression(3);
424
425 DICompositeType *ArrayType = DIB.createArrayType(0, 0, nullptr, Subscripts,
426 DataLocation, Associated,
427 Allocated, Rank);
428
429 EXPECT_TRUE(isa_and_nonnull<DICompositeType>(ArrayType));
430 EXPECT_EQ(ArrayType->getRawDataLocation(), DataLocation);
431 EXPECT_EQ(ArrayType->getRawAssociated(), Associated);
432 EXPECT_EQ(ArrayType->getRawAllocated(), Allocated);
433 EXPECT_EQ(ArrayType->getRawRank(), Rank);
434
435 // Avoid memory leak.
436 DIVariable::deleteTemporary(DataLocation);
437 }
438
439 TEST(DIBuilder, CreateArrayWithBitStride) {
440 LLVMContext Ctx;
441 std::unique_ptr<Module> M(new Module("MyModule", Ctx));
442 DIBuilder DIB(*M);
443
444 Type *Int32Ty = Type::getInt32Ty(Ctx);
445 Constant *Ci = ConstantInt::get(Int32Ty, 7);
446 Metadata *CM = ConstantAsMetadata::get(Ci);
447
448 StringRef ArrayNameExp = "AnArray";
449 DICompositeType *NamedArray =
450 DIB.createArrayType(nullptr, ArrayNameExp, nullptr, 0, 8, 8, nullptr, {},
451 nullptr, nullptr, nullptr, nullptr, CM);
452 EXPECT_EQ(NamedArray->getTag(), dwarf::DW_TAG_array_type);
453 EXPECT_EQ(NamedArray->getRawBitStride(), CM);
454 EXPECT_EQ(NamedArray->getBitStrideConst(), Ci);
455 }
456
457 TEST(DIBuilder, CreateSetType) {
458 LLVMContext Ctx;
459 std::unique_ptr<Module> M(new Module("MyModule", Ctx));
460 DIBuilder DIB(*M);
461 DIScope *Scope = DISubprogram::getDistinct(
462 Ctx, nullptr, "", "", nullptr, 0, nullptr, 0, nullptr, 0, 0,
463 DINode::FlagZero, DISubprogram::SPFlagZero, nullptr);
464 DIType *Type = DIB.createBasicType("Int", 64, dwarf::DW_ATE_signed);
465 DIFile *F = DIB.createFile("main.c", "/");
466
467 DIDerivedType *SetType = DIB.createSetType(Scope, "set1", F, 1, 64, 64, Type);
468 EXPECT_TRUE(isa_and_nonnull<DIDerivedType>(SetType));
469 }
470
471 TEST(DIBuilder, CreateStringType) {
472 LLVMContext Ctx;
473 std::unique_ptr<Module> M(new Module("MyModule", Ctx));
474 DIBuilder DIB(*M);
475 DIScope *Scope = DISubprogram::getDistinct(
476 Ctx, nullptr, "", "", nullptr, 0, nullptr, 0, nullptr, 0, 0,
477 DINode::FlagZero, DISubprogram::SPFlagZero, nullptr);
478 DIFile *F = DIB.createFile("main.c", "/");
479 StringRef StrName = "string";
480 DIVariable *StringLen = DIB.createAutoVariable(Scope, StrName, F, 0, nullptr,
481 false, DINode::FlagZero, 0);
482 auto getDIExpression = [&DIB](int offset) {
483 SmallVector<uint64_t, 4> ops;
484 ops.push_back(llvm::dwarf::DW_OP_push_object_address);
485 DIExpression::appendOffset(ops, offset);
486 ops.push_back(llvm::dwarf::DW_OP_deref);
487
488 return DIB.createExpression(ops);
489 };
490 DIExpression *StringLocationExp = getDIExpression(1);
491 DIStringType *StringType =
492 DIB.createStringType(StrName, StringLen, StringLocationExp);
493
494 EXPECT_TRUE(isa_and_nonnull<DIStringType>(StringType));
495 EXPECT_EQ(StringType->getName(), StrName);
496 EXPECT_EQ(StringType->getStringLength(), StringLen);
497 EXPECT_EQ(StringType->getStringLocationExp(), StringLocationExp);
498
499 StringRef StrNameExp = "stringexp";
500 DIExpression *StringLengthExp = getDIExpression(2);
501 DIStringType *StringTypeExp =
502 DIB.createStringType(StrNameExp, StringLengthExp, StringLocationExp);
503
504 EXPECT_TRUE(isa_and_nonnull<DIStringType>(StringTypeExp));
505 EXPECT_EQ(StringTypeExp->getName(), StrNameExp);
506 EXPECT_EQ(StringTypeExp->getStringLocationExp(), StringLocationExp);
507 EXPECT_EQ(StringTypeExp->getStringLengthExp(), StringLengthExp);
508 }
509
510 TEST(DIBuilder, DIEnumerator) {
511 LLVMContext Ctx;
512 std::unique_ptr<Module> M(new Module("MyModule", Ctx));
513 DIBuilder DIB(*M);
514 APSInt I1(APInt(32, 1));
515 APSInt I2(APInt(33, 1));
516
517 auto *E = DIEnumerator::get(Ctx, I1, I1.isSigned(), "name");
518 EXPECT_TRUE(E);
519
520 auto *E1 = DIEnumerator::getIfExists(Ctx, I1, I1.isSigned(), "name");
521 EXPECT_TRUE(E1);
522
523 auto *E2 = DIEnumerator::getIfExists(Ctx, I2, I1.isSigned(), "name");
524 EXPECT_FALSE(E2);
525 }
526
527 TEST(DIBuilder, FixedPointType) {
528 LLVMContext Ctx;
529 std::unique_ptr<Module> M(new Module("MyModule", Ctx));
530 DIBuilder DIB(*M);
531
532 DIFixedPointType *Ty = DIB.createBinaryFixedPointType(
533 {}, 32, 0, dwarf::DW_ATE_signed_fixed, DINode::FlagZero, -4);
534 EXPECT_TRUE(Ty);
535 EXPECT_TRUE(Ty->getKind() == DIFixedPointType::FixedPointBinary);
536 EXPECT_TRUE(Ty->getFactor() == -4);
537 EXPECT_TRUE(Ty->getEncoding() == dwarf::DW_ATE_signed_fixed);
538 EXPECT_TRUE(Ty->getTag() == dwarf::DW_TAG_base_type);
539
540 Ty = DIB.createDecimalFixedPointType({}, 32, 0, dwarf::DW_ATE_unsigned_fixed,
541 DINode::FlagZero, -7);
542 EXPECT_TRUE(Ty);
543 EXPECT_TRUE(Ty->getKind() == DIFixedPointType::FixedPointDecimal);
544 EXPECT_TRUE(Ty->getFactor() == -7);
545 EXPECT_TRUE(Ty->getEncoding() == dwarf::DW_ATE_unsigned_fixed);
546 EXPECT_TRUE(Ty->getTag() == dwarf::DW_TAG_base_type);
547
548 APSInt Num(APInt(32, 1));
549 APSInt Denom(APInt(33, 72));
550 Ty = DIB.createRationalFixedPointType({}, 32, 0, dwarf::DW_ATE_unsigned_fixed,
551 DINode::FlagZero, Num, Denom);
552 EXPECT_TRUE(Ty);
553 EXPECT_TRUE(Ty->getKind() == DIFixedPointType::FixedPointRational);
554 EXPECT_TRUE(Ty->getFactorRaw() == 0);
555 EXPECT_TRUE(Ty->getNumerator() == Num);
556 EXPECT_TRUE(Ty->getDenominator() == Denom);
557 EXPECT_TRUE(Ty->getEncoding() == dwarf::DW_ATE_unsigned_fixed);
558 EXPECT_TRUE(Ty->getTag() == dwarf::DW_TAG_base_type);
559 }
560
561 TEST(DbgAssignIntrinsicTest, replaceVariableLocationOp) {
562 LLVMContext C;
563 std::unique_ptr<Module> M = parseIR(C, R"(
564 define dso_local void @fun(i32 %v1, ptr %p1, ptr %p2) !dbg !7 {
565 entry:
566 call void @llvm.dbg.assign(metadata i32 %v1, metadata !14, metadata !DIExpression(), metadata !17, metadata ptr %p1, metadata !DIExpression()), !dbg !16
567 ret void
568 }
569
570 declare void @llvm.dbg.assign(metadata, metadata, metadata, metadata, metadata, metadata)
571
572 !llvm.dbg.cu = !{!0}
573 !llvm.module.flags = !{!3}
574
575 !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)
576 !1 = !DIFile(filename: "test.cpp", directory: "/")
577 !3 = !{i32 2, !"Debug Info Version", i32 3}
578 !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)
579 !8 = !DISubroutineType(types: !9)
580 !9 = !{null}
581 !10 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
582 !11 = !{}
583 !14 = !DILocalVariable(name: "Local", scope: !7, file: !1, line: 3, type: !10)
584 !16 = !DILocation(line: 0, scope: !7)
585 !17 = distinct !DIAssignID()
586 )");
587 // Check the test IR isn't malformed.
588 ASSERT_TRUE(M);
589
590 Function &Fun = *M->getFunction("fun");
591 Value *V1 = Fun.getArg(0);
592 Value *P1 = Fun.getArg(1);
593 Value *P2 = Fun.getArg(2);
594 DbgVariableRecord *DbgAssign = cast<DbgVariableRecord>(
595 &*Fun.front().front().getDbgRecordRange().begin());
596 ASSERT_TRUE(V1 == DbgAssign->getVariableLocationOp(0));
597 ASSERT_TRUE(P1 == DbgAssign->getAddress());
598
599 #define TEST_REPLACE(Old, New, ExpectedValue, ExpectedAddr) \
600 DbgAssign->replaceVariableLocationOp(Old, New); \
601 EXPECT_EQ(DbgAssign->getVariableLocationOp(0), ExpectedValue); \
602 EXPECT_EQ(DbgAssign->getAddress(), ExpectedAddr);
603
604 // Replace address only.
605 TEST_REPLACE(/*Old*/ P1, /*New*/ P2, /*Value*/ V1, /*Address*/ P2);
606 // Replace value only.
607 TEST_REPLACE(/*Old*/ V1, /*New*/ P2, /*Value*/ P2, /*Address*/ P2);
608 // Replace both.
609 TEST_REPLACE(/*Old*/ P2, /*New*/ P1, /*Value*/ P1, /*Address*/ P1);
610
611 // Replace address only, value uses a DIArgList.
612 // Value = {DIArgList(V1)}, Addr = P1.
613 DbgAssign->setRawLocation(DIArgList::get(C, ValueAsMetadata::get(V1)));
614 DbgAssign->setExpression(DIExpression::get(
615 C, {dwarf::DW_OP_LLVM_arg, 0, dwarf::DW_OP_stack_value}));
616 TEST_REPLACE(/*Old*/ P1, /*New*/ P2, /*Value*/ V1, /*Address*/ P2);
617 #undef TEST_REPLACE
618 }
619
620 TEST(AssignmentTrackingTest, Utils) {
621 // Test the assignment tracking utils defined in DebugInfo.h namespace at {}.
622 // This includes:
623 // getAssignmentInsts
624 // getAssignmentMarkers
625 // RAUW
626 // deleteAll
627 //
628 // The input IR includes two functions, fun1 and fun2. Both contain an alloca
629 // with a DIAssignID tag. fun1's alloca is linked to two llvm.dbg.assign
630 // intrinsics, one of which is for an inlined variable and appears before the
631 // alloca.
632
633 LLVMContext C;
634 std::unique_ptr<Module> M = parseIR(C, R"(
635 define dso_local void @fun1() !dbg !7 {
636 entry:
637 call void @llvm.dbg.assign(metadata i32 undef, metadata !10, metadata !DIExpression(), metadata !12, metadata i32 undef, metadata !DIExpression()), !dbg !13
638 %local = alloca i32, align 4, !DIAssignID !12
639 call void @llvm.dbg.assign(metadata i32 undef, metadata !16, metadata !DIExpression(), metadata !12, metadata i32 undef, metadata !DIExpression()), !dbg !15
640 ret void, !dbg !15
641 }
642
643 define dso_local void @fun2() !dbg !17 {
644 entry:
645 %local = alloca i32, align 4, !DIAssignID !20
646 call void @llvm.dbg.assign(metadata i32 undef, metadata !18, metadata !DIExpression(), metadata !20, metadata i32 undef, metadata !DIExpression()), !dbg !19
647 ret void, !dbg !19
648 }
649
650 define dso_local void @fun3() !dbg !21 {
651 entry:
652 %local = alloca i32, align 4, !DIAssignID !24
653 call void @llvm.dbg.assign(metadata i32 undef, metadata !22, metadata !DIExpression(), metadata !24, metadata i32* undef, metadata !DIExpression()), !dbg !23
654 ret void
655 }
656
657 declare void @llvm.dbg.assign(metadata, metadata, metadata, metadata, metadata, metadata)
658
659 !llvm.dbg.cu = !{!0}
660 !llvm.module.flags = !{!3, !4, !5}
661 !llvm.ident = !{!6}
662
663 !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)
664 !1 = !DIFile(filename: "test.c", directory: "/")
665 !2 = !{}
666 !3 = !{i32 7, !"Dwarf Version", i32 4}
667 !4 = !{i32 2, !"Debug Info Version", i32 3}
668 !5 = !{i32 1, !"wchar_size", i32 4}
669 !6 = !{!"clang version 14.0.0"}
670 !7 = distinct !DISubprogram(name: "fun1", scope: !1, file: !1, line: 1, type: !8, scopeLine: 1, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
671 !8 = !DISubroutineType(types: !9)
672 !9 = !{null}
673 !10 = !DILocalVariable(name: "local3", scope: !14, file: !1, line: 2, type: !11)
674 !11 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
675 !12 = distinct !DIAssignID()
676 !13 = !DILocation(line: 5, column: 1, scope: !14, inlinedAt: !15)
677 !14 = distinct !DISubprogram(name: "inline", scope: !1, file: !1, line: 1, type: !8, scopeLine: 1, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
678 !15 = !DILocation(line: 3, column: 1, scope: !7)
679 !16 = !DILocalVariable(name: "local1", scope: !7, file: !1, line: 2, type: !11)
680 !17 = distinct !DISubprogram(name: "fun2", scope: !1, file: !1, line: 1, type: !8, scopeLine: 1, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
681 !18 = !DILocalVariable(name: "local2", scope: !17, file: !1, line: 2, type: !11)
682 !19 = !DILocation(line: 4, column: 1, scope: !17)
683 !20 = distinct !DIAssignID()
684 !21 = distinct !DISubprogram(name: "fun3", scope: !1, file: !1, line: 1, type: !8, scopeLine: 1, spFlags: DISPFlagDefinition, unit: !0, retainedNodes: !2)
685 !22 = !DILocalVariable(name: "local4", scope: !21, file: !1, line: 2, type: !11)
686 !23 = !DILocation(line: 4, column: 1, scope: !21)
687 !24 = distinct !DIAssignID()
688 )");
689
690 // Check the test IR isn't malformed.
691 ASSERT_TRUE(M);
692
693 Function &Fun1 = *M->getFunction("fun1");
694 Instruction &Alloca = *Fun1.getEntryBlock().getFirstNonPHIOrDbg();
695
696 // 1. Check the Instruction <-> Intrinsic mappings work in fun1.
697 //
698 // Check there are two llvm.dbg.assign intrinsics linked to Alloca.
699 auto CheckFun1Mapping = [&Alloca]() {
700 auto Markers = at::getDVRAssignmentMarkers(&Alloca);
701 EXPECT_TRUE(std::distance(Markers.begin(), Markers.end()) == 2);
702 // Check those two entries are distinct.
703 DbgVariableRecord *First = *Markers.begin();
704 DbgVariableRecord *Second = *std::next(Markers.begin());
705 EXPECT_NE(First, Second);
706
707 // Check that we can get back to Alloca from each llvm.dbg.assign.
708 for (auto *DAI : Markers) {
709 auto Insts = at::getAssignmentInsts(DAI);
710 // Check there is exactly one instruction linked to each intrinsic. Use
711 // ASSERT_TRUE because we're going to dereference the begin iterator.
712 ASSERT_TRUE(std::distance(Insts.begin(), Insts.end()) == 1);
713 EXPECT_FALSE(Insts.empty());
714 // Check the linked instruction is Alloca.
715 Instruction *LinkedInst = *Insts.begin();
716 EXPECT_EQ(LinkedInst, &Alloca);
717 }
718 };
719 CheckFun1Mapping();
720
721 // 2. Check DIAssignID RAUW replaces attachments and uses.
722 //
723 DIAssignID *Old =
724 cast_or_null<DIAssignID>(Alloca.getMetadata(LLVMContext::MD_DIAssignID));
725 DIAssignID *New = DIAssignID::getDistinct(C);
726 ASSERT_TRUE(Old && New && New != Old);
727 at::RAUW(Old, New);
728 // Check fun1's alloca and intrinsics have been updated and the mapping still
729 // works.
730 EXPECT_EQ(New, cast_or_null<DIAssignID>(
731 Alloca.getMetadata(LLVMContext::MD_DIAssignID)));
732 CheckFun1Mapping();
733
734 // Check that fun2's alloca and intrinsic have not not been updated.
735 Instruction &Fun2Alloca =
736 *M->getFunction("fun2")->getEntryBlock().getFirstNonPHIOrDbg();
737 DIAssignID *Fun2ID = cast_or_null<DIAssignID>(
738 Fun2Alloca.getMetadata(LLVMContext::MD_DIAssignID));
739 EXPECT_NE(New, Fun2ID);
740 auto Fun2Markers = at::getDVRAssignmentMarkers(&Fun2Alloca);
741 ASSERT_TRUE(std::distance(Fun2Markers.begin(), Fun2Markers.end()) == 1);
742 auto Fun2Insts = at::getAssignmentInsts(*Fun2Markers.begin());
743 ASSERT_TRUE(std::distance(Fun2Insts.begin(), Fun2Insts.end()) == 1);
744 EXPECT_EQ(*Fun2Insts.begin(), &Fun2Alloca);
745
746 // 3. Check that deleting dbg.assigns from a specific instruction works.
747 Instruction &Fun3Alloca =
748 *M->getFunction("fun3")->getEntryBlock().getFirstNonPHIOrDbg();
749 auto Fun3Markers = at::getDVRAssignmentMarkers(&Fun3Alloca);
750 ASSERT_TRUE(std::distance(Fun3Markers.begin(), Fun3Markers.end()) == 1);
751 at::deleteAssignmentMarkers(&Fun3Alloca);
752 Fun3Markers = at::getDVRAssignmentMarkers(&Fun3Alloca);
753 EXPECT_EQ(Fun3Markers.empty(), true);
754
755 // 4. Check that deleting works and applies only to the target function.
756 at::deleteAll(&Fun1);
757 // There should now only be the alloca and ret in fun1.
758 EXPECT_EQ(Fun1.begin()->size(), 2u);
759 // fun2's alloca should have the same DIAssignID and remain linked to its
760 // llvm.dbg.assign.
761 EXPECT_EQ(Fun2ID, cast_or_null<DIAssignID>(
762 Fun2Alloca.getMetadata(LLVMContext::MD_DIAssignID)));
763 EXPECT_FALSE(at::getDVRAssignmentMarkers(&Fun2Alloca).empty());
764 }
765
766 TEST(IRBuilder, GetSetInsertionPointWithEmptyBasicBlock) {
767 LLVMContext C;
768 std::unique_ptr<BasicBlock> BB(BasicBlock::Create(C, "start"));
769 Module *M = new Module("module", C);
770 IRBuilder<> Builder(BB.get());
771 Function *DbgDeclare =
772 Intrinsic::getOrInsertDeclaration(M, Intrinsic::dbg_declare);
773 Value *DIV = MetadataAsValue::get(C, (Metadata *)nullptr);
774 SmallVector<Value *, 3> Args = {DIV, DIV, DIV};
775 Builder.CreateCall(DbgDeclare, Args);
776 auto IP = BB->getFirstInsertionPt();
777 Builder.SetInsertPoint(BB.get(), IP);
778 }
779
780 TEST(AssignmentTrackingTest, InstrMethods) {
781 // Test the assignment tracking Instruction methods.
782 // This includes:
783 // Instruction::mergeDIAssignID
784
785 LLVMContext C;
786 std::unique_ptr<Module> M = parseIR(C, R"(
787 define dso_local void @fun() #0 !dbg !8 {
788 entry:
789 %Local = alloca [2 x i32], align 4, !DIAssignID !12
790 call void @llvm.dbg.assign(metadata i1 undef, metadata !13, metadata !DIExpression(), metadata !12, metadata [2 x i32]* %Local, metadata !DIExpression()), !dbg !18
791 %arrayidx = getelementptr inbounds [2 x i32], [2 x i32]* %Local, i64 0, i64 0, !dbg !19
792 store i32 5, i32* %arrayidx, align 4, !dbg !20, !DIAssignID !21
793 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
794 %arrayidx1 = getelementptr inbounds [2 x i32], [2 x i32]* %Local, i64 0, i64 1, !dbg !22
795 store i32 6, i32* %arrayidx1, align 4, !dbg !23, !DIAssignID !24
796 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
797 ret void, !dbg !25
798 }
799
800 declare void @llvm.dbg.assign(metadata, metadata, metadata, metadata, metadata, metadata) #1
801
802 !llvm.dbg.cu = !{!0}
803 !llvm.module.flags = !{!2, !3, !4, !5, !6}
804 !llvm.ident = !{!7}
805
806 !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)
807 !1 = !DIFile(filename: "test.cpp", directory: "/")
808 !2 = !{i32 7, !"Dwarf Version", i32 5}
809 !3 = !{i32 2, !"Debug Info Version", i32 3}
810 !4 = !{i32 1, !"wchar_size", i32 4}
811 !5 = !{i32 7, !"uwtable", i32 1}
812 !6 = !{i32 7, !"frame-pointer", i32 2}
813 !7 = !{!"clang version 14.0.0"}
814 !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)
815 !9 = !DISubroutineType(types: !10)
816 !10 = !{null}
817 !11 = !{}
818 !12 = distinct !DIAssignID()
819 !13 = !DILocalVariable(name: "Local", scope: !8, file: !1, line: 2, type: !14)
820 !14 = !DICompositeType(tag: DW_TAG_array_type, baseType: !15, size: 64, elements: !16)
821 !15 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
822 !16 = !{!17}
823 !17 = !DISubrange(count: 2)
824 !18 = !DILocation(line: 0, scope: !8)
825 !19 = !DILocation(line: 3, column: 3, scope: !8)
826 !20 = !DILocation(line: 3, column: 12, scope: !8)
827 !21 = distinct !DIAssignID()
828 !22 = !DILocation(line: 4, column: 3, scope: !8)
829 !23 = !DILocation(line: 4, column: 12, scope: !8)
830 !24 = distinct !DIAssignID()
831 !25 = !DILocation(line: 5, column: 1, scope: !8)
832 )");
833
834 // Check the test IR isn't malformed.
835 ASSERT_TRUE(M);
836 Function &Fun = *M->getFunction("fun");
837 SmallVector<Instruction *> Stores;
838 for (auto &BB : Fun) {
839 for (auto &I : BB) {
840 if (isa<StoreInst>(&I))
841 Stores.push_back(&I);
842 }
843 }
844
845 // The test requires (at least) 2 stores.
846 ASSERT_TRUE(Stores.size() == 2);
847 // Use SetVectors to check that the attachments and markers are unique
848 // (another test requirement).
849 SetVector<Metadata *> OrigIDs;
850 SetVector<DbgVariableRecord *> Markers;
851 for (const Instruction *SI : Stores) {
852 Metadata *ID = SI->getMetadata(LLVMContext::MD_DIAssignID);
853 ASSERT_TRUE(OrigIDs.insert(ID));
854 ASSERT_TRUE(ID != nullptr);
855 auto Range = at::getDVRAssignmentMarkers(SI);
856 ASSERT_TRUE(std::distance(Range.begin(), Range.end()) == 1);
857 ASSERT_TRUE(Markers.insert(*Range.begin()));
858 }
859
860 // Test 1 - mergeDIAssignID.
861 //
862 // Input store0->mergeDIAssignID(store1)
863 // ----- -------------------------
864 // store0 !x store0 !x
865 // dbg.assign0 !x dbg.assign !x
866 // store1 !y store1 !x
867 // dbg.assign1 !y dbg.assign1 !x
868 {
869 Stores[0]->mergeDIAssignID(Stores[1]);
870 // Check that the stores share the same ID.
871 Metadata *NewID0 = Stores[0]->getMetadata(LLVMContext::MD_DIAssignID);
872 Metadata *NewID1 = Stores[1]->getMetadata(LLVMContext::MD_DIAssignID);
873 EXPECT_NE(NewID0, nullptr);
874 EXPECT_EQ(NewID0, NewID1);
875 EXPECT_EQ(Markers[0]->getAssignID(), NewID0);
876 EXPECT_EQ(Markers[1]->getAssignID(), NewID0);
877 }
878
879 // Test 2 - mergeDIAssignID.
880 //
881 // Input store0->mergeDIAssignID(store1)
882 // ----- -------------------------
883 // store0 !x store0 !x
884 // dbg.assign0 !x dbg.assign !x
885 // store1 store1
886 {
887 Stores[1]->setMetadata(LLVMContext::MD_DIAssignID, nullptr);
888 Stores[0]->mergeDIAssignID(Stores[1]);
889 // Check that store1 doesn't get a new ID.
890 Metadata *NewID0 = Stores[0]->getMetadata(LLVMContext::MD_DIAssignID);
891 Metadata *NewID1 = Stores[1]->getMetadata(LLVMContext::MD_DIAssignID);
892 EXPECT_NE(NewID0, nullptr);
893 EXPECT_EQ(NewID1, nullptr);
894 EXPECT_EQ(Markers[0]->getAssignID(), NewID0);
895 }
896
897 // Test 3 - mergeDIAssignID.
898 //
899 // Input store1->mergeDIAssignID(store0)
900 // ----- -------------------------
901 // store0 !x store0 !x
902 // dbg.assign0 !x dbg.assign !x
903 // store1 store1 !x
904 {
905 Stores[1]->setMetadata(LLVMContext::MD_DIAssignID, nullptr);
906 Stores[1]->mergeDIAssignID(Stores[0]);
907 // Check that the stores share the same ID (note store1 starts with none).
908 Metadata *NewID0 = Stores[0]->getMetadata(LLVMContext::MD_DIAssignID);
909 Metadata *NewID1 = Stores[1]->getMetadata(LLVMContext::MD_DIAssignID);
910 EXPECT_NE(NewID0, nullptr);
911 EXPECT_EQ(NewID0, NewID1);
912 EXPECT_EQ(Markers[0]->getAssignID(), NewID0);
913 }
914
915 // Test 4 - mergeDIAssignID.
916 //
917 // Input store1->mergeDIAssignID(store0)
918 // ----- -------------------------
919 // store0 !x store0 !x
920 // dbg.assign0 !x dbg.assign !x
921 // store1 !x store1 !x
922 {
923 Stores[0]->mergeDIAssignID(Stores[1]);
924 // Check that the stores share the same ID.
925 Metadata *NewID0 = Stores[0]->getMetadata(LLVMContext::MD_DIAssignID);
926 Metadata *NewID1 = Stores[1]->getMetadata(LLVMContext::MD_DIAssignID);
927 EXPECT_NE(NewID0, nullptr);
928 EXPECT_EQ(NewID0, NewID1);
929 EXPECT_EQ(Markers[0]->getAssignID(), NewID0);
930 }
931
932 // Test 5 - dropUnknownNonDebugMetadata.
933 //
934 // Input store0->dropUnknownNonDebugMetadata()
935 // ----- -------------------------
936 // store0 !x store0 !x
937 {
938 Stores[0]->dropUnknownNonDebugMetadata();
939 Metadata *NewID0 = Stores[0]->getMetadata(LLVMContext::MD_DIAssignID);
940 EXPECT_NE(NewID0, nullptr);
941 }
942 }
943
944 // Test some very straight-forward operations on DbgVariableRecords -- these are
945 // dbg.values that have been converted to a non-instruction format.
946 TEST(MetadataTest, ConvertDbgToDbgVariableRecord) {
947 LLVMContext C;
948 std::unique_ptr<Module> M = parseIR(C, R"(
949 define i16 @f(i16 %a) !dbg !6 {
950 call void @llvm.dbg.value(metadata i16 %a, metadata !9, metadata !DIExpression()), !dbg !11
951 %b = add i16 %a, 1, !dbg !11
952 call void @llvm.dbg.value(metadata i16 %b, metadata !9, metadata !DIExpression()), !dbg !11
953 ret i16 0, !dbg !11
954
955 exit:
956 %c = add i16 %b, 1, !dbg !11
957 ret i16 0, !dbg !11
958 }
959 declare void @llvm.dbg.value(metadata, metadata, metadata) #0
960 attributes #0 = { nounwind readnone speculatable willreturn }
961
962 !llvm.dbg.cu = !{!0}
963 !llvm.module.flags = !{!5}
964
965 !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
966 !1 = !DIFile(filename: "t.ll", directory: "/")
967 !2 = !{}
968 !5 = !{i32 2, !"Debug Info Version", i32 3}
969 !6 = distinct !DISubprogram(name: "foo", linkageName: "foo", scope: null, file: !1, line: 1, type: !7, scopeLine: 1, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !8)
970 !7 = !DISubroutineType(types: !2)
971 !8 = !{!9}
972 !9 = !DILocalVariable(name: "1", scope: !6, file: !1, line: 1, type: !10)
973 !10 = !DIBasicType(name: "ty16", size: 16, encoding: DW_ATE_unsigned)
974 !11 = !DILocation(line: 1, column: 1, scope: !6)
975 )");
976
977 // The IR above will be autoupgraded to debug records: but this test is about
978 // the conversion routines, so convert it back. This test will have value
979 // going forwards for the purpose of testing the conversion routine, which
980 // some compatibility tools (DXIL?) wish to use.
981 M->convertFromNewDbgValues();
982
983 // Find the first dbg.value,
984 Instruction &I = *M->getFunction("f")->getEntryBlock().getFirstNonPHIIt();
985 const DILocalVariable *Var = nullptr;
986 const DIExpression *Expr = nullptr;
987 const DILocation *Loc = nullptr;
988 const Metadata *MLoc = nullptr;
989 DbgVariableRecord *DVR1 = nullptr;
990 {
991 DbgValueInst *DPI = dyn_cast<DbgValueInst>(&I);
992 ASSERT_TRUE(DPI);
993 Var = DPI->getVariable();
994 Expr = DPI->getExpression();
995 Loc = DPI->getDebugLoc().get();
996 MLoc = DPI->getRawLocation();
997
998 // Test the creation of a DbgVariableRecord and it's conversion back to a
999 // dbg.value.
1000 DVR1 = new DbgVariableRecord(DPI);
1001 EXPECT_EQ(DVR1->getVariable(), Var);
1002 EXPECT_EQ(DVR1->getExpression(), Expr);
1003 EXPECT_EQ(DVR1->getDebugLoc().get(), Loc);
1004 EXPECT_EQ(DVR1->getRawLocation(), MLoc);
1005
1006 // Erase dbg.value,
1007 DPI->eraseFromParent();
1008 // Re-create from DVR1, inserting at front.
1009 DVR1->createDebugIntrinsic(&*M,
1010 &M->getFunction("f")->getEntryBlock().front());
1011
1012 Instruction *NewDPI = &M->getFunction("f")->getEntryBlock().front();
1013 DbgValueInst *DPI2 = dyn_cast<DbgValueInst>(NewDPI);
1014 ASSERT_TRUE(DPI2);
1015 EXPECT_EQ(DPI2->getVariable(), Var);
1016 EXPECT_EQ(DPI2->getExpression(), Expr);
1017 EXPECT_EQ(DPI2->getDebugLoc().get(), Loc);
1018 EXPECT_EQ(DPI2->getRawLocation(), MLoc);
1019 }
1020
1021 // Fetch the second dbg.value, convert it to a DbgVariableRecord,
1022 BasicBlock::iterator It = M->getFunction("f")->getEntryBlock().begin();
1023 It = std::next(std::next(It));
1024 DbgValueInst *DPI3 = dyn_cast<DbgValueInst>(It);
1025 ASSERT_TRUE(DPI3);
1026 DbgVariableRecord *DVR2 = new DbgVariableRecord(DPI3);
1027
1028 // These dbg.values are supposed to refer to different values.
1029 EXPECT_NE(DVR1->getRawLocation(), DVR2->getRawLocation());
1030
1031 // Try manipulating DbgVariableRecords and markers in the exit block.
1032 BasicBlock *ExitBlock = &*std::next(M->getFunction("f")->getEntryBlock().getIterator());
1033 Instruction *FirstInst = &ExitBlock->front();
1034 Instruction *RetInst = &*std::next(FirstInst->getIterator());
1035
1036 // Set-up DbgMarkers in this block.
1037 ExitBlock->createMarker(FirstInst);
1038 ExitBlock->createMarker(RetInst);
1039
1040 // Insert DbgRecords into markers, order should come out DVR2, DVR1.
1041 FirstInst->DebugMarker->insertDbgRecord(DVR1, false);
1042 FirstInst->DebugMarker->insertDbgRecord(DVR2, true);
1043 unsigned int ItCount = 0;
1044 for (DbgRecord &Item : FirstInst->DebugMarker->getDbgRecordRange()) {
1045 EXPECT_TRUE((&Item == DVR2 && ItCount == 0) ||
1046 (&Item == DVR1 && ItCount == 1));
1047 EXPECT_EQ(Item.getMarker(), FirstInst->DebugMarker);
1048 ++ItCount;
1049 }
1050
1051 // Clone them onto the second marker -- should allocate new DVRs.
1052 RetInst->DebugMarker->cloneDebugInfoFrom(FirstInst->DebugMarker, std::nullopt,
1053 false);
1054 EXPECT_EQ(RetInst->DebugMarker->StoredDbgRecords.size(), 2u);
1055 ItCount = 0;
1056 // Check these things store the same information; but that they're not the same
1057 // objects.
1058 for (DbgVariableRecord &Item :
1059 filterDbgVars(RetInst->DebugMarker->getDbgRecordRange())) {
1060 EXPECT_TRUE(
1061 (Item.getRawLocation() == DVR2->getRawLocation() && ItCount == 0) ||
1062 (Item.getRawLocation() == DVR1->getRawLocation() && ItCount == 1));
1063
1064 EXPECT_EQ(Item.getMarker(), RetInst->DebugMarker);
1065 EXPECT_NE(&Item, DVR1);
1066 EXPECT_NE(&Item, DVR2);
1067 ++ItCount;
1068 }
1069
1070 RetInst->DebugMarker->dropDbgRecords();
1071 EXPECT_EQ(RetInst->DebugMarker->StoredDbgRecords.size(), 0u);
1072
1073 // Try cloning one single DbgVariableRecord.
1074 auto DIIt = std::next(FirstInst->DebugMarker->getDbgRecordRange().begin());
1075 RetInst->DebugMarker->cloneDebugInfoFrom(FirstInst->DebugMarker, DIIt, false);
1076 EXPECT_EQ(RetInst->DebugMarker->StoredDbgRecords.size(), 1u);
1077 // The second DbgVariableRecord should have been cloned; it should have the
1078 // same values as DVR1.
1079 EXPECT_EQ(
1080 cast<DbgVariableRecord>(RetInst->DebugMarker->StoredDbgRecords.begin())
1081 ->getRawLocation(),
1082 DVR1->getRawLocation());
1083 // We should be able to drop individual DbgRecords.
1084 RetInst->DebugMarker->dropOneDbgRecord(
1085 &*RetInst->DebugMarker->StoredDbgRecords.begin());
1086
1087 // "Aborb" a DbgMarker: this means pretend that the instruction it's attached
1088 // to is disappearing so it needs to be transferred into "this" marker.
1089 RetInst->DebugMarker->absorbDebugValues(*FirstInst->DebugMarker, true);
1090 EXPECT_EQ(RetInst->DebugMarker->StoredDbgRecords.size(), 2u);
1091 // Should be the DVR1 and DVR2 objects.
1092 ItCount = 0;
1093 for (DbgRecord &Item : RetInst->DebugMarker->getDbgRecordRange()) {
1094 EXPECT_TRUE((&Item == DVR2 && ItCount == 0) ||
1095 (&Item == DVR1 && ItCount == 1));
1096 EXPECT_EQ(Item.getMarker(), RetInst->DebugMarker);
1097 ++ItCount;
1098 }
1099
1100 // Finally -- there are two DbgVariableRecords left over. If we remove
1101 // evrything in the basic block, then they should sink down into the
1102 // "TrailingDbgRecords" container for dangling debug-info. Future facilities
1103 // will restore them back when a terminator is inserted.
1104 FirstInst->DebugMarker->removeMarker();
1105 FirstInst->eraseFromParent();
1106 RetInst->DebugMarker->removeMarker();
1107 RetInst->eraseFromParent();
1108
1109 DbgMarker *EndMarker = ExitBlock->getTrailingDbgRecords();
1110 ASSERT_NE(EndMarker, nullptr);
1111 EXPECT_EQ(EndMarker->StoredDbgRecords.size(), 2u);
1112 // Test again that it's those two DbgVariableRecords, DVR1 and DVR2.
1113 ItCount = 0;
1114 for (DbgRecord &Item : EndMarker->getDbgRecordRange()) {
1115 EXPECT_TRUE((&Item == DVR2 && ItCount == 0) ||
1116 (&Item == DVR1 && ItCount == 1));
1117 EXPECT_EQ(Item.getMarker(), EndMarker);
1118 ++ItCount;
1119 }
1120
1121 // Cleanup the trailing DbgVariableRecord records and marker.
1122 EndMarker->eraseFromParent();
1123
1124 // The record of those trailing DbgVariableRecords would dangle and cause an
1125 // assertion failure if it lived until the end of the LLVMContext.
1126 ExitBlock->deleteTrailingDbgRecords();
1127 }
1128
1129 TEST(MetadataTest, DbgVariableRecordConversionRoutines) {
1130 LLVMContext C;
1131
1132 std::unique_ptr<Module> M = parseIR(C, R"(
1133 define i16 @f(i16 %a) !dbg !6 {
1134 call void @llvm.dbg.value(metadata i16 %a, metadata !9, metadata !DIExpression()), !dbg !11
1135 %b = add i16 %a, 1, !dbg !11
1136 call void @llvm.dbg.value(metadata i16 %b, metadata !9, metadata !DIExpression()), !dbg !11
1137 ret i16 0, !dbg !11
1138
1139 exit:
1140 %c = add i16 %b, 1, !dbg !11
1141 ret i16 0, !dbg !11
1142 }
1143 declare void @llvm.dbg.value(metadata, metadata, metadata) #0
1144 attributes #0 = { nounwind readnone speculatable willreturn }
1145
1146 !llvm.dbg.cu = !{!0}
1147 !llvm.module.flags = !{!5}
1148
1149 !0 = distinct !DICompileUnit(language: DW_LANG_C, file: !1, producer: "debugify", isOptimized: true, runtimeVersion: 0, emissionKind: FullDebug, enums: !2)
1150 !1 = !DIFile(filename: "t.ll", directory: "/")
1151 !2 = !{}
1152 !5 = !{i32 2, !"Debug Info Version", i32 3}
1153 !6 = distinct !DISubprogram(name: "foo", linkageName: "foo", scope: null, file: !1, line: 1, type: !7, scopeLine: 1, spFlags: DISPFlagDefinition | DISPFlagOptimized, unit: !0, retainedNodes: !8)
1154 !7 = !DISubroutineType(types: !2)
1155 !8 = !{!9}
1156 !9 = !DILocalVariable(name: "1", scope: !6, file: !1, line: 1, type: !10)
1157 !10 = !DIBasicType(name: "ty16", size: 16, encoding: DW_ATE_unsigned)
1158 !11 = !DILocation(line: 1, column: 1, scope: !6)
1159 )");
1160
1161 // This test exists to check we can convert back and forth between old and new
1162 // debug info formats (dbg.value intrinsics versus #dbg_value records).
1163 // We're ripping out support for debug intrinsics, but the conversions will
1164 // live on in bitcode autoupgrade and possibly DXIL autodowngrade. Thus, this
1165 // test is still valuable. Begin by starting in the intrinsic format:
1166 M->convertFromNewDbgValues();
1167
1168 Function *F = M->getFunction("f");
1169 BasicBlock *BB1 = &F->getEntryBlock();
1170 // First instruction should be a dbg.value.
1171 EXPECT_TRUE(isa<DbgValueInst>(BB1->front()));
1172 // Validating the block for DbgVariableRecords / DbgMarkers shouldn't fail --
1173 // there's no data stored right now.
1174 bool BrokenDebugInfo = false;
1175 bool Error = verifyModule(*M, &errs(), &BrokenDebugInfo);
1176 EXPECT_FALSE(Error);
1177 EXPECT_FALSE(BrokenDebugInfo);
1178
1179 // Now convert.
1180 M->convertToNewDbgValues();
1181
1182 // There should now be no dbg.value instructions!
1183 // Ensure the first instruction exists, the test all of them.
1184 EXPECT_FALSE(isa<DbgValueInst>(BB1->front()));
1185 for (auto &BB : *F)
1186 for (auto &I : BB)
1187 EXPECT_FALSE(isa<DbgValueInst>(I));
1188
1189 // There should be a DbgMarker on each of the two instructions in the entry
1190 // block, each containing one DbgVariableRecord.
1191 EXPECT_EQ(BB1->size(), 2u);
1192 Instruction *FirstInst = &BB1->front();
1193 Instruction *SecondInst = FirstInst->getNextNode();
1194 ASSERT_TRUE(FirstInst->DebugMarker);
1195 ASSERT_TRUE(SecondInst->DebugMarker);
1196 EXPECT_NE(FirstInst->DebugMarker, SecondInst->DebugMarker);
1197 EXPECT_EQ(FirstInst, FirstInst->DebugMarker->MarkedInstr);
1198 EXPECT_EQ(SecondInst, SecondInst->DebugMarker->MarkedInstr);
1199
1200 EXPECT_EQ(FirstInst->DebugMarker->StoredDbgRecords.size(), 1u);
1201 DbgVariableRecord *DVR1 = cast<DbgVariableRecord>(
1202 &*FirstInst->DebugMarker->getDbgRecordRange().begin());
1203 EXPECT_EQ(DVR1->getMarker(), FirstInst->DebugMarker);
1204 // Should point at %a, an argument.
1205 EXPECT_TRUE(isa<Argument>(DVR1->getVariableLocationOp(0)));
1206
1207 EXPECT_EQ(SecondInst->DebugMarker->StoredDbgRecords.size(), 1u);
1208 DbgVariableRecord *DVR2 = cast<DbgVariableRecord>(
1209 &*SecondInst->DebugMarker->getDbgRecordRange().begin());
1210 EXPECT_EQ(DVR2->getMarker(), SecondInst->DebugMarker);
1211 // Should point at FirstInst.
1212 EXPECT_EQ(DVR2->getVariableLocationOp(0), FirstInst);
1213
1214 // There should be no DbgVariableRecords / DbgMarkers in the second block, but
1215 // it should be marked as being in the new format.
1216 BasicBlock *BB2 = BB1->getNextNode();
1217 for (auto &Inst : *BB2)
1218 // Either there should be no marker, or it should be empty.
1219 EXPECT_TRUE(!Inst.DebugMarker ||
1220 Inst.DebugMarker->StoredDbgRecords.empty());
1221
1222 // Validating the first block should continue to not be a problem,
1223 Error = verifyModule(*M, &errs(), &BrokenDebugInfo);
1224 EXPECT_FALSE(Error);
1225 EXPECT_FALSE(BrokenDebugInfo);
1226 // But if we were to break something, it should be able to fire. Don't attempt
1227 // to comprehensively test the validator, it's a smoke-test rather than a
1228 // "proper" verification pass.
1229 DVR1->setMarker(nullptr);
1230 // A marker pointing the wrong way should be an error.
1231 Error = verifyModule(*M, &errs(), &BrokenDebugInfo);
1232 EXPECT_FALSE(Error);
1233 EXPECT_TRUE(BrokenDebugInfo);
1234 DVR1->setMarker(FirstInst->DebugMarker);
1235
1236 DILocalVariable *DLV1 = DVR1->getVariable();
1237 DIExpression *Expr1 = DVR1->getExpression();
1238 DILocalVariable *DLV2 = DVR2->getVariable();
1239 DIExpression *Expr2 = DVR2->getExpression();
1240
1241 // Convert everything back to the "old" format and ensure it's right.
1242 M->convertFromNewDbgValues();
1243
1244 EXPECT_EQ(BB1->size(), 4u);
1245 ASSERT_TRUE(isa<DbgValueInst>(BB1->front()));
1246 DbgValueInst *DVI1 = cast<DbgValueInst>(&BB1->front());
1247 // These dbg.values should still point at the same places.
1248 EXPECT_TRUE(isa<Argument>(DVI1->getVariableLocationOp(0)));
1249 DbgValueInst *DVI2 = cast<DbgValueInst>(DVI1->getNextNode()->getNextNode());
1250 EXPECT_EQ(DVI2->getVariableLocationOp(0), FirstInst);
1251
1252 // Check a few fields too,
1253 EXPECT_EQ(DVI1->getVariable(), DLV1);
1254 EXPECT_EQ(DVI1->getExpression(), Expr1);
1255 EXPECT_EQ(DVI2->getVariable(), DLV2);
1256 EXPECT_EQ(DVI2->getExpression(), Expr2);
1257 }
1258
1259 // Test that the hashing function for DISubprograms representing methods produce
1260 // the same result after replacing their scope (the type containing the
1261 // subprogram) from a temporary DIType with the permanent one.
1262 TEST(DIBuilder, HashingDISubprogram) {
1263 LLVMContext Ctx;
1264 std::unique_ptr<Module> M = std::make_unique<Module>("MyModule", Ctx);
1265 DIBuilder DIB(*M);
1266
1267 DIFile *F = DIB.createFile("main.c", "/");
1268 DICompileUnit *CU =
1269 DIB.createCompileUnit(dwarf::DW_LANG_C, F, "Test", false, "", 0);
1270
1271 llvm::TempDIType ForwardDeclaredType =
1272 llvm::TempDIType(DIB.createReplaceableCompositeType(
1273 llvm::dwarf::DW_TAG_structure_type, "MyType", CU, F, 0, 0, 8, 8, {},
1274 "UniqueIdentifier"));
1275
1276 // The hashing function is different for declarations and definitions, so
1277 // create one of each.
1278 DISubprogram *Declaration =
1279 DIB.createMethod(ForwardDeclaredType.get(), "MethodName", "LinkageName",
1280 F, 0, DIB.createSubroutineType({}));
1281
1282 DISubprogram *Definition = DIB.createFunction(
1283 ForwardDeclaredType.get(), "MethodName", "LinkageName", F, 0,
1284 DIB.createSubroutineType({}), 0, DINode::FlagZero,
1285 llvm::DISubprogram::SPFlagDefinition, nullptr, Declaration);
1286
1287 // Produce the hash with the temporary scope.
1288 unsigned HashDeclaration =
1289 MDNodeKeyImpl<DISubprogram>(Declaration).getHashValue();
1290 unsigned HashDefinition =
1291 MDNodeKeyImpl<DISubprogram>(Definition).getHashValue();
1292
1293 // Instantiate the real scope and replace the temporary one with it.
1294 DICompositeType *Type = DIB.createStructType(CU, "MyType", F, 0, 8, 8, {}, {},
1295 {}, 0, {}, "UniqueIdentifier");
1296 DIB.replaceTemporary(std::move(ForwardDeclaredType), Type);
1297
1298 // Now make sure the hashing is consistent.
1299 unsigned HashDeclarationAfter =
1300 MDNodeKeyImpl<DISubprogram>(Declaration).getHashValue();
1301 unsigned HashDefinitionAfter =
1302 MDNodeKeyImpl<DISubprogram>(Definition).getHashValue();
1303
1304 EXPECT_EQ(HashDeclaration, HashDeclarationAfter);
1305 EXPECT_EQ(HashDefinition, HashDefinitionAfter);
1306 }
1307
1308 TEST(DIBuilder, CompositeTypes) {
1309 LLVMContext Ctx;
1310 std::unique_ptr<Module> M = std::make_unique<Module>("MyModule", Ctx);
1311 DIBuilder DIB(*M);
1312
1313 DIFile *F = DIB.createFile("main.c", "/");
1314 DICompileUnit *CU =
1315 DIB.createCompileUnit(dwarf::DW_LANG_C, F, "Test", false, "", 0);
1316
1317 DICompositeType *Class =
1318 DIB.createClassType(CU, "MyClass", F, 0, 8, 8, 0, {}, nullptr, {}, 0,
1319 nullptr, nullptr, "ClassUniqueIdentifier");
1320 EXPECT_EQ(Class->getTag(), dwarf::DW_TAG_class_type);
1321
1322 DICompositeType *Struct = DIB.createStructType(
1323 CU, "MyStruct", F, 0, 8, 8, {}, {}, {}, 0, {}, "StructUniqueIdentifier");
1324 EXPECT_EQ(Struct->getTag(), dwarf::DW_TAG_structure_type);
1325
1326 DICompositeType *Union = DIB.createUnionType(CU, "MyUnion", F, 0, 8, 8, {},
1327 {}, 0, "UnionUniqueIdentifier");
1328 EXPECT_EQ(Union->getTag(), dwarf::DW_TAG_union_type);
1329
1330 DICompositeType *Array = DIB.createArrayType(8, 8, nullptr, {});
1331 EXPECT_EQ(Array->getTag(), dwarf::DW_TAG_array_type);
1332
1333 StringRef ArrayNameExp = "AnArray";
1334 DICompositeType *NamedArray =
1335 DIB.createArrayType(nullptr, ArrayNameExp, nullptr, 0, 8, 8, nullptr, {});
1336 EXPECT_EQ(NamedArray->getTag(), dwarf::DW_TAG_array_type);
1337 EXPECT_EQ(NamedArray->getName(), ArrayNameExp);
1338
1339 DICompositeType *Vector = DIB.createVectorType(8, 8, nullptr, {});
1340 EXPECT_EQ(Vector->getTag(), dwarf::DW_TAG_array_type);
1341
1342 DICompositeType *Enum = DIB.createEnumerationType(
1343 CU, "MyEnum", F, 0, 8, 8, {}, nullptr, 0, "EnumUniqueIdentifier");
1344 EXPECT_EQ(Enum->getTag(), dwarf::DW_TAG_enumeration_type);
1345 }
1346
1347 TEST(DIBuilder, DynamicOffsetAndSize) {
1348 LLVMContext Ctx;
1349 auto M = std::make_unique<Module>("MyModule", Ctx);
1350 DIBuilder DIB(*M);
1351 DIScope *Scope = DISubprogram::getDistinct(
1352 Ctx, nullptr, "", "", nullptr, 0, nullptr, 0, nullptr, 0, 0,
1353 DINode::FlagZero, DISubprogram::SPFlagZero, nullptr);
1354 DIFile *F = DIB.createFile("main.adb", "/");
1355
1356 DIVariable *Len = DIB.createAutoVariable(Scope, "length", F, 0, nullptr,
1357 false, DINode::FlagZero, 0);
1358
1359 DICompositeType *Struct = DIB.createStructType(
1360 Scope, "some_record", F, 18, Len, 8, DINode::FlagZero, nullptr, {});
1361 EXPECT_EQ(Struct->getTag(), dwarf::DW_TAG_structure_type);
1362
1363 SmallVector<uint64_t, 4> ops;
1364 ops.push_back(llvm::dwarf::DW_OP_push_object_address);
1365 DIExpression::appendOffset(ops, 3);
1366 ops.push_back(llvm::dwarf::DW_OP_deref);
1367 DIExpression *Expr = DIB.createExpression(ops);
1368
1369 DIDerivedType *Field = DIB.createMemberType(Scope, "field", F, 23, Len, 0,
1370 Expr, DINode::FlagZero, Struct);
1371
1372 EXPECT_EQ(Field->getRawOffsetInBits(), Expr);
1373 EXPECT_EQ(Field->getRawSizeInBits(), Len);
1374 }
1375
1376 } // end namespace