1 //===- unittests/IR/MetadataTest.cpp - Metadata unit tests ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/IR/Constants.h"
12 #include "llvm/IR/DebugInfo.h"
13 #include "llvm/IR/DebugInfoMetadata.h"
14 #include "llvm/IR/Function.h"
15 #include "llvm/IR/Instructions.h"
16 #include "llvm/IR/LLVMContext.h"
17 #include "llvm/IR/Metadata.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/IR/ModuleSlotTracker.h"
20 #include "llvm/IR/Type.h"
21 #include "llvm/IR/Verifier.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "gtest/gtest.h"
24 using namespace llvm;
25 
26 namespace {
27 
28 TEST(ContextAndReplaceableUsesTest, FromContext) {
29   LLVMContext Context;
30   ContextAndReplaceableUses CRU(Context);
31   EXPECT_EQ(&Context, &CRU.getContext());
32   EXPECT_FALSE(CRU.hasReplaceableUses());
33   EXPECT_FALSE(CRU.getReplaceableUses());
34 }
35 
36 TEST(ContextAndReplaceableUsesTest, FromReplaceableUses) {
37   LLVMContext Context;
38   ContextAndReplaceableUses CRU(make_unique<ReplaceableMetadataImpl>(Context));
39   EXPECT_EQ(&Context, &CRU.getContext());
40   EXPECT_TRUE(CRU.hasReplaceableUses());
41   EXPECT_TRUE(CRU.getReplaceableUses());
42 }
43 
44 TEST(ContextAndReplaceableUsesTest, makeReplaceable) {
45   LLVMContext Context;
46   ContextAndReplaceableUses CRU(Context);
47   CRU.makeReplaceable(make_unique<ReplaceableMetadataImpl>(Context));
48   EXPECT_EQ(&Context, &CRU.getContext());
49   EXPECT_TRUE(CRU.hasReplaceableUses());
50   EXPECT_TRUE(CRU.getReplaceableUses());
51 }
52 
53 TEST(ContextAndReplaceableUsesTest, takeReplaceableUses) {
54   LLVMContext Context;
55   auto ReplaceableUses = make_unique<ReplaceableMetadataImpl>(Context);
56   auto *Ptr = ReplaceableUses.get();
57   ContextAndReplaceableUses CRU(std::move(ReplaceableUses));
58   ReplaceableUses = CRU.takeReplaceableUses();
59   EXPECT_EQ(&Context, &CRU.getContext());
60   EXPECT_FALSE(CRU.hasReplaceableUses());
61   EXPECT_FALSE(CRU.getReplaceableUses());
62   EXPECT_EQ(Ptr, ReplaceableUses.get());
63 }
64 
65 class MetadataTest : public testing::Test {
66 public:
67   MetadataTest() : M("test", Context), Counter(0) {}
68 
69 protected:
70   LLVMContext Context;
71   Module M;
72   int Counter;
73 
74   MDNode *getNode() { return MDNode::get(Context, None); }
75   MDNode *getNode(Metadata *MD) { return MDNode::get(Context, MD); }
76   MDNode *getNode(Metadata *MD1, Metadata *MD2) {
77     Metadata *MDs[] = {MD1, MD2};
78     return MDNode::get(Context, MDs);
79   }
80 
81   MDTuple *getTuple() { return MDTuple::getDistinct(Context, None); }
82   DISubroutineType *getSubroutineType() {
83     return DISubroutineType::getDistinct(Context, 0, 0, getNode(nullptr));
84   }
85   DISubprogram *getSubprogram() {
86     return DISubprogram::getDistinct(Context, nullptr, "", "", nullptr, 0,
87                                      nullptr, false, false, 0, nullptr,
88                                      0, 0, 0, false, nullptr);
89   }
90   DIFile *getFile() {
91     return DIFile::getDistinct(Context, "file.c", "/path/to/dir");
92   }
93   DICompileUnit *getUnit() {
94     return DICompileUnit::getDistinct(Context, 1, getFile(), "clang", false,
95                                       "-g", 2, "", DICompileUnit::FullDebug,
96                                       getTuple(), getTuple(), getTuple(),
97                                       getTuple(), getTuple(), 0);
98   }
99   DIType *getBasicType(StringRef Name) {
100     return DIBasicType::get(Context, dwarf::DW_TAG_unspecified_type, Name);
101   }
102   DIType *getDerivedType() {
103     return DIDerivedType::getDistinct(Context, dwarf::DW_TAG_pointer_type, "",
104                                       nullptr, 0, nullptr,
105                                       getBasicType("basictype"), 1, 2, 0, 0);
106   }
107   Constant *getConstant() {
108     return ConstantInt::get(Type::getInt32Ty(Context), Counter++);
109   }
110   ConstantAsMetadata *getConstantAsMetadata() {
111     return ConstantAsMetadata::get(getConstant());
112   }
113   DIType *getCompositeType() {
114     return DICompositeType::getDistinct(
115         Context, dwarf::DW_TAG_structure_type, "", nullptr, 0, nullptr, nullptr,
116         32, 32, 0, 0, nullptr, 0, nullptr, nullptr, "");
117   }
118   Function *getFunction(StringRef Name) {
119     return cast<Function>(M.getOrInsertFunction(
120         Name, FunctionType::get(Type::getVoidTy(Context), None, false)));
121   }
122 };
123 typedef MetadataTest MDStringTest;
124 
125 // Test that construction of MDString with different value produces different
126 // MDString objects, even with the same string pointer and nulls in the string.
127 TEST_F(MDStringTest, CreateDifferent) {
128   char x[3] = { 'f', 0, 'A' };
129   MDString *s1 = MDString::get(Context, StringRef(&x[0], 3));
130   x[2] = 'B';
131   MDString *s2 = MDString::get(Context, StringRef(&x[0], 3));
132   EXPECT_NE(s1, s2);
133 }
134 
135 // Test that creation of MDStrings with the same string contents produces the
136 // same MDString object, even with different pointers.
137 TEST_F(MDStringTest, CreateSame) {
138   char x[4] = { 'a', 'b', 'c', 'X' };
139   char y[4] = { 'a', 'b', 'c', 'Y' };
140 
141   MDString *s1 = MDString::get(Context, StringRef(&x[0], 3));
142   MDString *s2 = MDString::get(Context, StringRef(&y[0], 3));
143   EXPECT_EQ(s1, s2);
144 }
145 
146 // Test that MDString prints out the string we fed it.
147 TEST_F(MDStringTest, PrintingSimple) {
148   char *str = new char[13];
149   strncpy(str, "testing 1 2 3", 13);
150   MDString *s = MDString::get(Context, StringRef(str, 13));
151   strncpy(str, "aaaaaaaaaaaaa", 13);
152   delete[] str;
153 
154   std::string Str;
155   raw_string_ostream oss(Str);
156   s->print(oss);
157   EXPECT_STREQ("!\"testing 1 2 3\"", oss.str().c_str());
158 }
159 
160 // Test printing of MDString with non-printable characters.
161 TEST_F(MDStringTest, PrintingComplex) {
162   char str[5] = {0, '\n', '"', '\\', (char)-1};
163   MDString *s = MDString::get(Context, StringRef(str+0, 5));
164   std::string Str;
165   raw_string_ostream oss(Str);
166   s->print(oss);
167   EXPECT_STREQ("!\"\\00\\0A\\22\\5C\\FF\"", oss.str().c_str());
168 }
169 
170 typedef MetadataTest MDNodeTest;
171 
172 // Test the two constructors, and containing other Constants.
173 TEST_F(MDNodeTest, Simple) {
174   char x[3] = { 'a', 'b', 'c' };
175   char y[3] = { '1', '2', '3' };
176 
177   MDString *s1 = MDString::get(Context, StringRef(&x[0], 3));
178   MDString *s2 = MDString::get(Context, StringRef(&y[0], 3));
179   ConstantAsMetadata *CI =
180       ConstantAsMetadata::get(ConstantInt::get(Context, APInt(8, 0)));
181 
182   std::vector<Metadata *> V;
183   V.push_back(s1);
184   V.push_back(CI);
185   V.push_back(s2);
186 
187   MDNode *n1 = MDNode::get(Context, V);
188   Metadata *const c1 = n1;
189   MDNode *n2 = MDNode::get(Context, c1);
190   Metadata *const c2 = n2;
191   MDNode *n3 = MDNode::get(Context, V);
192   MDNode *n4 = MDNode::getIfExists(Context, V);
193   MDNode *n5 = MDNode::getIfExists(Context, c1);
194   MDNode *n6 = MDNode::getIfExists(Context, c2);
195   EXPECT_NE(n1, n2);
196   EXPECT_EQ(n1, n3);
197   EXPECT_EQ(n4, n1);
198   EXPECT_EQ(n5, n2);
199   EXPECT_EQ(n6, (Metadata *)nullptr);
200 
201   EXPECT_EQ(3u, n1->getNumOperands());
202   EXPECT_EQ(s1, n1->getOperand(0));
203   EXPECT_EQ(CI, n1->getOperand(1));
204   EXPECT_EQ(s2, n1->getOperand(2));
205 
206   EXPECT_EQ(1u, n2->getNumOperands());
207   EXPECT_EQ(n1, n2->getOperand(0));
208 }
209 
210 TEST_F(MDNodeTest, Delete) {
211   Constant *C = ConstantInt::get(Type::getInt32Ty(Context), 1);
212   Instruction *I = new BitCastInst(C, Type::getInt32Ty(Context));
213 
214   Metadata *const V = LocalAsMetadata::get(I);
215   MDNode *n = MDNode::get(Context, V);
216   TrackingMDRef wvh(n);
217 
218   EXPECT_EQ(n, wvh);
219 
220   delete I;
221 }
222 
223 TEST_F(MDNodeTest, SelfReference) {
224   // !0 = !{!0}
225   // !1 = !{!0}
226   {
227     auto Temp = MDNode::getTemporary(Context, None);
228     Metadata *Args[] = {Temp.get()};
229     MDNode *Self = MDNode::get(Context, Args);
230     Self->replaceOperandWith(0, Self);
231     ASSERT_EQ(Self, Self->getOperand(0));
232 
233     // Self-references should be distinct, so MDNode::get() should grab a
234     // uniqued node that references Self, not Self.
235     Args[0] = Self;
236     MDNode *Ref1 = MDNode::get(Context, Args);
237     MDNode *Ref2 = MDNode::get(Context, Args);
238     EXPECT_NE(Self, Ref1);
239     EXPECT_EQ(Ref1, Ref2);
240   }
241 
242   // !0 = !{!0, !{}}
243   // !1 = !{!0, !{}}
244   {
245     auto Temp = MDNode::getTemporary(Context, None);
246     Metadata *Args[] = {Temp.get(), MDNode::get(Context, None)};
247     MDNode *Self = MDNode::get(Context, Args);
248     Self->replaceOperandWith(0, Self);
249     ASSERT_EQ(Self, Self->getOperand(0));
250 
251     // Self-references should be distinct, so MDNode::get() should grab a
252     // uniqued node that references Self, not Self itself.
253     Args[0] = Self;
254     MDNode *Ref1 = MDNode::get(Context, Args);
255     MDNode *Ref2 = MDNode::get(Context, Args);
256     EXPECT_NE(Self, Ref1);
257     EXPECT_EQ(Ref1, Ref2);
258   }
259 }
260 
261 TEST_F(MDNodeTest, Print) {
262   Constant *C = ConstantInt::get(Type::getInt32Ty(Context), 7);
263   MDString *S = MDString::get(Context, "foo");
264   MDNode *N0 = getNode();
265   MDNode *N1 = getNode(N0);
266   MDNode *N2 = getNode(N0, N1);
267 
268   Metadata *Args[] = {ConstantAsMetadata::get(C), S, nullptr, N0, N1, N2};
269   MDNode *N = MDNode::get(Context, Args);
270 
271   std::string Expected;
272   {
273     raw_string_ostream OS(Expected);
274     OS << "<" << (void *)N << "> = !{";
275     C->printAsOperand(OS);
276     OS << ", ";
277     S->printAsOperand(OS);
278     OS << ", null";
279     MDNode *Nodes[] = {N0, N1, N2};
280     for (auto *Node : Nodes)
281       OS << ", <" << (void *)Node << ">";
282     OS << "}";
283   }
284 
285   std::string Actual;
286   {
287     raw_string_ostream OS(Actual);
288     N->print(OS);
289   }
290 
291   EXPECT_EQ(Expected, Actual);
292 }
293 
294 #define EXPECT_PRINTER_EQ(EXPECTED, PRINT)                                     \
295   do {                                                                         \
296     std::string Actual_;                                                       \
297     raw_string_ostream OS(Actual_);                                            \
298     PRINT;                                                                     \
299     OS.flush();                                                                \
300     std::string Expected_(EXPECTED);                                           \
301     EXPECT_EQ(Expected_, Actual_);                                             \
302   } while (false)
303 
304 TEST_F(MDNodeTest, PrintTemporary) {
305   MDNode *Arg = getNode();
306   TempMDNode Temp = MDNode::getTemporary(Context, Arg);
307   MDNode *N = getNode(Temp.get());
308   Module M("test", Context);
309   NamedMDNode *NMD = M.getOrInsertNamedMetadata("named");
310   NMD->addOperand(N);
311 
312   EXPECT_PRINTER_EQ("!0 = !{!1}", N->print(OS, &M));
313   EXPECT_PRINTER_EQ("!1 = <temporary!> !{!2}", Temp->print(OS, &M));
314   EXPECT_PRINTER_EQ("!2 = !{}", Arg->print(OS, &M));
315 
316   // Cleanup.
317   Temp->replaceAllUsesWith(Arg);
318 }
319 
320 TEST_F(MDNodeTest, PrintFromModule) {
321   Constant *C = ConstantInt::get(Type::getInt32Ty(Context), 7);
322   MDString *S = MDString::get(Context, "foo");
323   MDNode *N0 = getNode();
324   MDNode *N1 = getNode(N0);
325   MDNode *N2 = getNode(N0, N1);
326 
327   Metadata *Args[] = {ConstantAsMetadata::get(C), S, nullptr, N0, N1, N2};
328   MDNode *N = MDNode::get(Context, Args);
329   Module M("test", Context);
330   NamedMDNode *NMD = M.getOrInsertNamedMetadata("named");
331   NMD->addOperand(N);
332 
333   std::string Expected;
334   {
335     raw_string_ostream OS(Expected);
336     OS << "!0 = !{";
337     C->printAsOperand(OS);
338     OS << ", ";
339     S->printAsOperand(OS);
340     OS << ", null, !1, !2, !3}";
341   }
342 
343   EXPECT_PRINTER_EQ(Expected, N->print(OS, &M));
344 }
345 
346 TEST_F(MDNodeTest, PrintFromFunction) {
347   Module M("test", Context);
348   auto *FTy = FunctionType::get(Type::getVoidTy(Context), false);
349   auto *F0 = Function::Create(FTy, GlobalValue::ExternalLinkage, "F0", &M);
350   auto *F1 = Function::Create(FTy, GlobalValue::ExternalLinkage, "F1", &M);
351   auto *BB0 = BasicBlock::Create(Context, "entry", F0);
352   auto *BB1 = BasicBlock::Create(Context, "entry", F1);
353   auto *R0 = ReturnInst::Create(Context, BB0);
354   auto *R1 = ReturnInst::Create(Context, BB1);
355   auto *N0 = MDNode::getDistinct(Context, None);
356   auto *N1 = MDNode::getDistinct(Context, None);
357   R0->setMetadata("md", N0);
358   R1->setMetadata("md", N1);
359 
360   EXPECT_PRINTER_EQ("!0 = distinct !{}", N0->print(OS, &M));
361   EXPECT_PRINTER_EQ("!1 = distinct !{}", N1->print(OS, &M));
362 
363   ModuleSlotTracker MST(&M);
364   EXPECT_PRINTER_EQ("!0 = distinct !{}", N0->print(OS, MST));
365   EXPECT_PRINTER_EQ("!1 = distinct !{}", N1->print(OS, MST));
366 }
367 
368 TEST_F(MDNodeTest, PrintFromMetadataAsValue) {
369   Module M("test", Context);
370 
371   auto *Intrinsic =
372       Function::Create(FunctionType::get(Type::getVoidTy(Context),
373                                          Type::getMetadataTy(Context), false),
374                        GlobalValue::ExternalLinkage, "llvm.intrinsic", &M);
375 
376   auto *FTy = FunctionType::get(Type::getVoidTy(Context), false);
377   auto *F0 = Function::Create(FTy, GlobalValue::ExternalLinkage, "F0", &M);
378   auto *F1 = Function::Create(FTy, GlobalValue::ExternalLinkage, "F1", &M);
379   auto *BB0 = BasicBlock::Create(Context, "entry", F0);
380   auto *BB1 = BasicBlock::Create(Context, "entry", F1);
381   auto *N0 = MDNode::getDistinct(Context, None);
382   auto *N1 = MDNode::getDistinct(Context, None);
383   auto *MAV0 = MetadataAsValue::get(Context, N0);
384   auto *MAV1 = MetadataAsValue::get(Context, N1);
385   CallInst::Create(Intrinsic, MAV0, "", BB0);
386   CallInst::Create(Intrinsic, MAV1, "", BB1);
387 
388   EXPECT_PRINTER_EQ("!0 = distinct !{}", MAV0->print(OS));
389   EXPECT_PRINTER_EQ("!1 = distinct !{}", MAV1->print(OS));
390   EXPECT_PRINTER_EQ("!0", MAV0->printAsOperand(OS, false));
391   EXPECT_PRINTER_EQ("!1", MAV1->printAsOperand(OS, false));
392   EXPECT_PRINTER_EQ("metadata !0", MAV0->printAsOperand(OS, true));
393   EXPECT_PRINTER_EQ("metadata !1", MAV1->printAsOperand(OS, true));
394 
395   ModuleSlotTracker MST(&M);
396   EXPECT_PRINTER_EQ("!0 = distinct !{}", MAV0->print(OS, MST));
397   EXPECT_PRINTER_EQ("!1 = distinct !{}", MAV1->print(OS, MST));
398   EXPECT_PRINTER_EQ("!0", MAV0->printAsOperand(OS, false, MST));
399   EXPECT_PRINTER_EQ("!1", MAV1->printAsOperand(OS, false, MST));
400   EXPECT_PRINTER_EQ("metadata !0", MAV0->printAsOperand(OS, true, MST));
401   EXPECT_PRINTER_EQ("metadata !1", MAV1->printAsOperand(OS, true, MST));
402 }
403 #undef EXPECT_PRINTER_EQ
404 
405 TEST_F(MDNodeTest, NullOperand) {
406   // metadata !{}
407   MDNode *Empty = MDNode::get(Context, None);
408 
409   // metadata !{metadata !{}}
410   Metadata *Ops[] = {Empty};
411   MDNode *N = MDNode::get(Context, Ops);
412   ASSERT_EQ(Empty, N->getOperand(0));
413 
414   // metadata !{metadata !{}} => metadata !{null}
415   N->replaceOperandWith(0, nullptr);
416   ASSERT_EQ(nullptr, N->getOperand(0));
417 
418   // metadata !{null}
419   Ops[0] = nullptr;
420   MDNode *NullOp = MDNode::get(Context, Ops);
421   ASSERT_EQ(nullptr, NullOp->getOperand(0));
422   EXPECT_EQ(N, NullOp);
423 }
424 
425 TEST_F(MDNodeTest, DistinctOnUniquingCollision) {
426   // !{}
427   MDNode *Empty = MDNode::get(Context, None);
428   ASSERT_TRUE(Empty->isResolved());
429   EXPECT_FALSE(Empty->isDistinct());
430 
431   // !{!{}}
432   Metadata *Wrapped1Ops[] = {Empty};
433   MDNode *Wrapped1 = MDNode::get(Context, Wrapped1Ops);
434   ASSERT_EQ(Empty, Wrapped1->getOperand(0));
435   ASSERT_TRUE(Wrapped1->isResolved());
436   EXPECT_FALSE(Wrapped1->isDistinct());
437 
438   // !{!{!{}}}
439   Metadata *Wrapped2Ops[] = {Wrapped1};
440   MDNode *Wrapped2 = MDNode::get(Context, Wrapped2Ops);
441   ASSERT_EQ(Wrapped1, Wrapped2->getOperand(0));
442   ASSERT_TRUE(Wrapped2->isResolved());
443   EXPECT_FALSE(Wrapped2->isDistinct());
444 
445   // !{!{!{}}} => !{!{}}
446   Wrapped2->replaceOperandWith(0, Empty);
447   ASSERT_EQ(Empty, Wrapped2->getOperand(0));
448   EXPECT_TRUE(Wrapped2->isDistinct());
449   EXPECT_FALSE(Wrapped1->isDistinct());
450 }
451 
452 TEST_F(MDNodeTest, getDistinct) {
453   // !{}
454   MDNode *Empty = MDNode::get(Context, None);
455   ASSERT_TRUE(Empty->isResolved());
456   ASSERT_FALSE(Empty->isDistinct());
457   ASSERT_EQ(Empty, MDNode::get(Context, None));
458 
459   // distinct !{}
460   MDNode *Distinct1 = MDNode::getDistinct(Context, None);
461   MDNode *Distinct2 = MDNode::getDistinct(Context, None);
462   EXPECT_TRUE(Distinct1->isResolved());
463   EXPECT_TRUE(Distinct2->isDistinct());
464   EXPECT_NE(Empty, Distinct1);
465   EXPECT_NE(Empty, Distinct2);
466   EXPECT_NE(Distinct1, Distinct2);
467 
468   // !{}
469   ASSERT_EQ(Empty, MDNode::get(Context, None));
470 }
471 
472 TEST_F(MDNodeTest, isUniqued) {
473   MDNode *U = MDTuple::get(Context, None);
474   MDNode *D = MDTuple::getDistinct(Context, None);
475   auto T = MDTuple::getTemporary(Context, None);
476   EXPECT_TRUE(U->isUniqued());
477   EXPECT_FALSE(D->isUniqued());
478   EXPECT_FALSE(T->isUniqued());
479 }
480 
481 TEST_F(MDNodeTest, isDistinct) {
482   MDNode *U = MDTuple::get(Context, None);
483   MDNode *D = MDTuple::getDistinct(Context, None);
484   auto T = MDTuple::getTemporary(Context, None);
485   EXPECT_FALSE(U->isDistinct());
486   EXPECT_TRUE(D->isDistinct());
487   EXPECT_FALSE(T->isDistinct());
488 }
489 
490 TEST_F(MDNodeTest, isTemporary) {
491   MDNode *U = MDTuple::get(Context, None);
492   MDNode *D = MDTuple::getDistinct(Context, None);
493   auto T = MDTuple::getTemporary(Context, None);
494   EXPECT_FALSE(U->isTemporary());
495   EXPECT_FALSE(D->isTemporary());
496   EXPECT_TRUE(T->isTemporary());
497 }
498 
499 TEST_F(MDNodeTest, getDistinctWithUnresolvedOperands) {
500   // temporary !{}
501   auto Temp = MDTuple::getTemporary(Context, None);
502   ASSERT_FALSE(Temp->isResolved());
503 
504   // distinct !{temporary !{}}
505   Metadata *Ops[] = {Temp.get()};
506   MDNode *Distinct = MDNode::getDistinct(Context, Ops);
507   EXPECT_TRUE(Distinct->isResolved());
508   EXPECT_EQ(Temp.get(), Distinct->getOperand(0));
509 
510   // temporary !{} => !{}
511   MDNode *Empty = MDNode::get(Context, None);
512   Temp->replaceAllUsesWith(Empty);
513   EXPECT_EQ(Empty, Distinct->getOperand(0));
514 }
515 
516 TEST_F(MDNodeTest, handleChangedOperandRecursion) {
517   // !0 = !{}
518   MDNode *N0 = MDNode::get(Context, None);
519 
520   // !1 = !{!3, null}
521   auto Temp3 = MDTuple::getTemporary(Context, None);
522   Metadata *Ops1[] = {Temp3.get(), nullptr};
523   MDNode *N1 = MDNode::get(Context, Ops1);
524 
525   // !2 = !{!3, !0}
526   Metadata *Ops2[] = {Temp3.get(), N0};
527   MDNode *N2 = MDNode::get(Context, Ops2);
528 
529   // !3 = !{!2}
530   Metadata *Ops3[] = {N2};
531   MDNode *N3 = MDNode::get(Context, Ops3);
532   Temp3->replaceAllUsesWith(N3);
533 
534   // !4 = !{!1}
535   Metadata *Ops4[] = {N1};
536   MDNode *N4 = MDNode::get(Context, Ops4);
537 
538   // Confirm that the cycle prevented RAUW from getting dropped.
539   EXPECT_TRUE(N0->isResolved());
540   EXPECT_FALSE(N1->isResolved());
541   EXPECT_FALSE(N2->isResolved());
542   EXPECT_FALSE(N3->isResolved());
543   EXPECT_FALSE(N4->isResolved());
544 
545   // Create a couple of distinct nodes to observe what's going on.
546   //
547   // !5 = distinct !{!2}
548   // !6 = distinct !{!3}
549   Metadata *Ops5[] = {N2};
550   MDNode *N5 = MDNode::getDistinct(Context, Ops5);
551   Metadata *Ops6[] = {N3};
552   MDNode *N6 = MDNode::getDistinct(Context, Ops6);
553 
554   // Mutate !2 to look like !1, causing a uniquing collision (and an RAUW).
555   // This will ripple up, with !3 colliding with !4, and RAUWing.  Since !2
556   // references !3, this can cause a re-entry of handleChangedOperand() when !3
557   // is not ready for it.
558   //
559   // !2->replaceOperandWith(1, nullptr)
560   // !2: !{!3, !0} => !{!3, null}
561   // !2->replaceAllUsesWith(!1)
562   // !3: !{!2] => !{!1}
563   // !3->replaceAllUsesWith(!4)
564   N2->replaceOperandWith(1, nullptr);
565 
566   // If all has gone well, N2 and N3 will have been RAUW'ed and deleted from
567   // under us.  Just check that the other nodes are sane.
568   //
569   // !1 = !{!4, null}
570   // !4 = !{!1}
571   // !5 = distinct !{!1}
572   // !6 = distinct !{!4}
573   EXPECT_EQ(N4, N1->getOperand(0));
574   EXPECT_EQ(N1, N4->getOperand(0));
575   EXPECT_EQ(N1, N5->getOperand(0));
576   EXPECT_EQ(N4, N6->getOperand(0));
577 }
578 
579 TEST_F(MDNodeTest, replaceResolvedOperand) {
580   // Check code for replacing one resolved operand with another.  If doing this
581   // directly (via replaceOperandWith()) becomes illegal, change the operand to
582   // a global value that gets RAUW'ed.
583   //
584   // Use a temporary node to keep N from being resolved.
585   auto Temp = MDTuple::getTemporary(Context, None);
586   Metadata *Ops[] = {nullptr, Temp.get()};
587 
588   MDNode *Empty = MDTuple::get(Context, ArrayRef<Metadata *>());
589   MDNode *N = MDTuple::get(Context, Ops);
590   EXPECT_EQ(nullptr, N->getOperand(0));
591   ASSERT_FALSE(N->isResolved());
592 
593   // Check code for replacing resolved nodes.
594   N->replaceOperandWith(0, Empty);
595   EXPECT_EQ(Empty, N->getOperand(0));
596 
597   // Check code for adding another unresolved operand.
598   N->replaceOperandWith(0, Temp.get());
599   EXPECT_EQ(Temp.get(), N->getOperand(0));
600 
601   // Remove the references to Temp; required for teardown.
602   Temp->replaceAllUsesWith(nullptr);
603 }
604 
605 TEST_F(MDNodeTest, replaceWithUniqued) {
606   auto *Empty = MDTuple::get(Context, None);
607   MDTuple *FirstUniqued;
608   {
609     Metadata *Ops[] = {Empty};
610     auto Temp = MDTuple::getTemporary(Context, Ops);
611     EXPECT_TRUE(Temp->isTemporary());
612 
613     // Don't expect a collision.
614     auto *Current = Temp.get();
615     FirstUniqued = MDNode::replaceWithUniqued(std::move(Temp));
616     EXPECT_TRUE(FirstUniqued->isUniqued());
617     EXPECT_TRUE(FirstUniqued->isResolved());
618     EXPECT_EQ(Current, FirstUniqued);
619   }
620   {
621     Metadata *Ops[] = {Empty};
622     auto Temp = MDTuple::getTemporary(Context, Ops);
623     EXPECT_TRUE(Temp->isTemporary());
624 
625     // Should collide with Uniqued above this time.
626     auto *Uniqued = MDNode::replaceWithUniqued(std::move(Temp));
627     EXPECT_TRUE(Uniqued->isUniqued());
628     EXPECT_TRUE(Uniqued->isResolved());
629     EXPECT_EQ(FirstUniqued, Uniqued);
630   }
631   {
632     auto Unresolved = MDTuple::getTemporary(Context, None);
633     Metadata *Ops[] = {Unresolved.get()};
634     auto Temp = MDTuple::getTemporary(Context, Ops);
635     EXPECT_TRUE(Temp->isTemporary());
636 
637     // Shouldn't be resolved.
638     auto *Uniqued = MDNode::replaceWithUniqued(std::move(Temp));
639     EXPECT_TRUE(Uniqued->isUniqued());
640     EXPECT_FALSE(Uniqued->isResolved());
641 
642     // Should be a different node.
643     EXPECT_NE(FirstUniqued, Uniqued);
644 
645     // Should resolve when we update its node (note: be careful to avoid a
646     // collision with any other nodes above).
647     Uniqued->replaceOperandWith(0, nullptr);
648     EXPECT_TRUE(Uniqued->isResolved());
649   }
650 }
651 
652 TEST_F(MDNodeTest, replaceWithUniquedResolvingOperand) {
653   // temp !{}
654   MDTuple *Op = MDTuple::getTemporary(Context, None).release();
655   EXPECT_FALSE(Op->isResolved());
656 
657   // temp !{temp !{}}
658   Metadata *Ops[] = {Op};
659   MDTuple *N = MDTuple::getTemporary(Context, Ops).release();
660   EXPECT_FALSE(N->isResolved());
661 
662   // temp !{temp !{}} => !{temp !{}}
663   ASSERT_EQ(N, MDNode::replaceWithUniqued(TempMDTuple(N)));
664   EXPECT_FALSE(N->isResolved());
665 
666   // !{temp !{}} => !{!{}}
667   ASSERT_EQ(Op, MDNode::replaceWithUniqued(TempMDTuple(Op)));
668   EXPECT_TRUE(Op->isResolved());
669   EXPECT_TRUE(N->isResolved());
670 }
671 
672 TEST_F(MDNodeTest, replaceWithUniquedChangingOperand) {
673   // i1* @GV
674   Type *Ty = Type::getInt1PtrTy(Context);
675   std::unique_ptr<GlobalVariable> GV(
676       new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage));
677   ConstantAsMetadata *Op = ConstantAsMetadata::get(GV.get());
678 
679   // temp !{i1* @GV}
680   Metadata *Ops[] = {Op};
681   MDTuple *N = MDTuple::getTemporary(Context, Ops).release();
682 
683   // temp !{i1* @GV} => !{i1* @GV}
684   ASSERT_EQ(N, MDNode::replaceWithUniqued(TempMDTuple(N)));
685   ASSERT_TRUE(N->isUniqued());
686 
687   // !{i1* @GV} => !{null}
688   GV.reset();
689   ASSERT_TRUE(N->isUniqued());
690   Metadata *NullOps[] = {nullptr};
691   ASSERT_EQ(N, MDTuple::get(Context, NullOps));
692 }
693 
694 TEST_F(MDNodeTest, replaceWithDistinct) {
695   {
696     auto *Empty = MDTuple::get(Context, None);
697     Metadata *Ops[] = {Empty};
698     auto Temp = MDTuple::getTemporary(Context, Ops);
699     EXPECT_TRUE(Temp->isTemporary());
700 
701     // Don't expect a collision.
702     auto *Current = Temp.get();
703     auto *Distinct = MDNode::replaceWithDistinct(std::move(Temp));
704     EXPECT_TRUE(Distinct->isDistinct());
705     EXPECT_TRUE(Distinct->isResolved());
706     EXPECT_EQ(Current, Distinct);
707   }
708   {
709     auto Unresolved = MDTuple::getTemporary(Context, None);
710     Metadata *Ops[] = {Unresolved.get()};
711     auto Temp = MDTuple::getTemporary(Context, Ops);
712     EXPECT_TRUE(Temp->isTemporary());
713 
714     // Don't expect a collision.
715     auto *Current = Temp.get();
716     auto *Distinct = MDNode::replaceWithDistinct(std::move(Temp));
717     EXPECT_TRUE(Distinct->isDistinct());
718     EXPECT_TRUE(Distinct->isResolved());
719     EXPECT_EQ(Current, Distinct);
720 
721     // Cleanup; required for teardown.
722     Unresolved->replaceAllUsesWith(nullptr);
723   }
724 }
725 
726 TEST_F(MDNodeTest, replaceWithPermanent) {
727   Metadata *Ops[] = {nullptr};
728   auto Temp = MDTuple::getTemporary(Context, Ops);
729   auto *T = Temp.get();
730 
731   // U is a normal, uniqued node that references T.
732   auto *U = MDTuple::get(Context, T);
733   EXPECT_TRUE(U->isUniqued());
734 
735   // Make Temp self-referencing.
736   Temp->replaceOperandWith(0, T);
737 
738   // Try to uniquify Temp.  This should, despite the name in the API, give a
739   // 'distinct' node, since self-references aren't allowed to be uniqued.
740   //
741   // Since it's distinct, N should have the same address as when it was a
742   // temporary (i.e., be equal to T not U).
743   auto *N = MDNode::replaceWithPermanent(std::move(Temp));
744   EXPECT_EQ(N, T);
745   EXPECT_TRUE(N->isDistinct());
746 
747   // U should be the canonical unique node with N as the argument.
748   EXPECT_EQ(U, MDTuple::get(Context, N));
749   EXPECT_TRUE(U->isUniqued());
750 
751   // This temporary should collide with U when replaced, but it should still be
752   // uniqued.
753   EXPECT_EQ(U, MDNode::replaceWithPermanent(MDTuple::getTemporary(Context, N)));
754   EXPECT_TRUE(U->isUniqued());
755 
756   // This temporary should become a new uniqued node.
757   auto Temp2 = MDTuple::getTemporary(Context, U);
758   auto *V = Temp2.get();
759   EXPECT_EQ(V, MDNode::replaceWithPermanent(std::move(Temp2)));
760   EXPECT_TRUE(V->isUniqued());
761   EXPECT_EQ(U, V->getOperand(0));
762 }
763 
764 TEST_F(MDNodeTest, deleteTemporaryWithTrackingRef) {
765   TrackingMDRef Ref;
766   EXPECT_EQ(nullptr, Ref.get());
767   {
768     auto Temp = MDTuple::getTemporary(Context, None);
769     Ref.reset(Temp.get());
770     EXPECT_EQ(Temp.get(), Ref.get());
771   }
772   EXPECT_EQ(nullptr, Ref.get());
773 }
774 
775 typedef MetadataTest DILocationTest;
776 
777 TEST_F(DILocationTest, Overflow) {
778   DISubprogram *N = getSubprogram();
779   {
780     DILocation *L = DILocation::get(Context, 2, 7, N);
781     EXPECT_EQ(2u, L->getLine());
782     EXPECT_EQ(7u, L->getColumn());
783   }
784   unsigned U16 = 1u << 16;
785   {
786     DILocation *L = DILocation::get(Context, UINT32_MAX, U16 - 1, N);
787     EXPECT_EQ(UINT32_MAX, L->getLine());
788     EXPECT_EQ(U16 - 1, L->getColumn());
789   }
790   {
791     DILocation *L = DILocation::get(Context, UINT32_MAX, U16, N);
792     EXPECT_EQ(UINT32_MAX, L->getLine());
793     EXPECT_EQ(0u, L->getColumn());
794   }
795   {
796     DILocation *L = DILocation::get(Context, UINT32_MAX, U16 + 1, N);
797     EXPECT_EQ(UINT32_MAX, L->getLine());
798     EXPECT_EQ(0u, L->getColumn());
799   }
800 }
801 
802 TEST_F(DILocationTest, getDistinct) {
803   MDNode *N = getSubprogram();
804   DILocation *L0 = DILocation::getDistinct(Context, 2, 7, N);
805   EXPECT_TRUE(L0->isDistinct());
806   DILocation *L1 = DILocation::get(Context, 2, 7, N);
807   EXPECT_FALSE(L1->isDistinct());
808   EXPECT_EQ(L1, DILocation::get(Context, 2, 7, N));
809 }
810 
811 TEST_F(DILocationTest, getTemporary) {
812   MDNode *N = MDNode::get(Context, None);
813   auto L = DILocation::getTemporary(Context, 2, 7, N);
814   EXPECT_TRUE(L->isTemporary());
815   EXPECT_FALSE(L->isResolved());
816 }
817 
818 TEST_F(DILocationTest, cloneTemporary) {
819   MDNode *N = MDNode::get(Context, None);
820   auto L = DILocation::getTemporary(Context, 2, 7, N);
821   EXPECT_TRUE(L->isTemporary());
822   auto L2 = L->clone();
823   EXPECT_TRUE(L2->isTemporary());
824 }
825 
826 typedef MetadataTest GenericDINodeTest;
827 
828 TEST_F(GenericDINodeTest, get) {
829   StringRef Header = "header";
830   auto *Empty = MDNode::get(Context, None);
831   Metadata *Ops1[] = {Empty};
832   auto *N = GenericDINode::get(Context, 15, Header, Ops1);
833   EXPECT_EQ(15u, N->getTag());
834   EXPECT_EQ(2u, N->getNumOperands());
835   EXPECT_EQ(Header, N->getHeader());
836   EXPECT_EQ(MDString::get(Context, Header), N->getOperand(0));
837   EXPECT_EQ(1u, N->getNumDwarfOperands());
838   EXPECT_EQ(Empty, N->getDwarfOperand(0));
839   EXPECT_EQ(Empty, N->getOperand(1));
840   ASSERT_TRUE(N->isUniqued());
841 
842   EXPECT_EQ(N, GenericDINode::get(Context, 15, Header, Ops1));
843 
844   N->replaceOperandWith(1, nullptr);
845   EXPECT_EQ(15u, N->getTag());
846   EXPECT_EQ(Header, N->getHeader());
847   EXPECT_EQ(nullptr, N->getDwarfOperand(0));
848   ASSERT_TRUE(N->isUniqued());
849 
850   Metadata *Ops2[] = {nullptr};
851   EXPECT_EQ(N, GenericDINode::get(Context, 15, Header, Ops2));
852 
853   N->replaceDwarfOperandWith(0, Empty);
854   EXPECT_EQ(15u, N->getTag());
855   EXPECT_EQ(Header, N->getHeader());
856   EXPECT_EQ(Empty, N->getDwarfOperand(0));
857   ASSERT_TRUE(N->isUniqued());
858   EXPECT_EQ(N, GenericDINode::get(Context, 15, Header, Ops1));
859 
860   TempGenericDINode Temp = N->clone();
861   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
862 }
863 
864 TEST_F(GenericDINodeTest, getEmptyHeader) {
865   // Canonicalize !"" to null.
866   auto *N = GenericDINode::get(Context, 15, StringRef(), None);
867   EXPECT_EQ(StringRef(), N->getHeader());
868   EXPECT_EQ(nullptr, N->getOperand(0));
869 }
870 
871 typedef MetadataTest DISubrangeTest;
872 
873 TEST_F(DISubrangeTest, get) {
874   auto *N = DISubrange::get(Context, 5, 7);
875   EXPECT_EQ(dwarf::DW_TAG_subrange_type, N->getTag());
876   EXPECT_EQ(5, N->getCount());
877   EXPECT_EQ(7, N->getLowerBound());
878   EXPECT_EQ(N, DISubrange::get(Context, 5, 7));
879   EXPECT_EQ(DISubrange::get(Context, 5, 0), DISubrange::get(Context, 5));
880 
881   TempDISubrange Temp = N->clone();
882   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
883 }
884 
885 TEST_F(DISubrangeTest, getEmptyArray) {
886   auto *N = DISubrange::get(Context, -1, 0);
887   EXPECT_EQ(dwarf::DW_TAG_subrange_type, N->getTag());
888   EXPECT_EQ(-1, N->getCount());
889   EXPECT_EQ(0, N->getLowerBound());
890   EXPECT_EQ(N, DISubrange::get(Context, -1, 0));
891 }
892 
893 typedef MetadataTest DIEnumeratorTest;
894 
895 TEST_F(DIEnumeratorTest, get) {
896   auto *N = DIEnumerator::get(Context, 7, "name");
897   EXPECT_EQ(dwarf::DW_TAG_enumerator, N->getTag());
898   EXPECT_EQ(7, N->getValue());
899   EXPECT_EQ("name", N->getName());
900   EXPECT_EQ(N, DIEnumerator::get(Context, 7, "name"));
901 
902   EXPECT_NE(N, DIEnumerator::get(Context, 8, "name"));
903   EXPECT_NE(N, DIEnumerator::get(Context, 7, "nam"));
904 
905   TempDIEnumerator Temp = N->clone();
906   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
907 }
908 
909 typedef MetadataTest DIBasicTypeTest;
910 
911 TEST_F(DIBasicTypeTest, get) {
912   auto *N =
913       DIBasicType::get(Context, dwarf::DW_TAG_base_type, "special", 33, 26, 7);
914   EXPECT_EQ(dwarf::DW_TAG_base_type, N->getTag());
915   EXPECT_EQ("special", N->getName());
916   EXPECT_EQ(33u, N->getSizeInBits());
917   EXPECT_EQ(26u, N->getAlignInBits());
918   EXPECT_EQ(7u, N->getEncoding());
919   EXPECT_EQ(0u, N->getLine());
920   EXPECT_EQ(N, DIBasicType::get(Context, dwarf::DW_TAG_base_type, "special", 33,
921                                 26, 7));
922 
923   EXPECT_NE(N, DIBasicType::get(Context, dwarf::DW_TAG_unspecified_type,
924                                 "special", 33, 26, 7));
925   EXPECT_NE(N,
926             DIBasicType::get(Context, dwarf::DW_TAG_base_type, "s", 33, 26, 7));
927   EXPECT_NE(N, DIBasicType::get(Context, dwarf::DW_TAG_base_type, "special", 32,
928                                 26, 7));
929   EXPECT_NE(N, DIBasicType::get(Context, dwarf::DW_TAG_base_type, "special", 33,
930                                 25, 7));
931   EXPECT_NE(N, DIBasicType::get(Context, dwarf::DW_TAG_base_type, "special", 33,
932                                 26, 6));
933 
934   TempDIBasicType Temp = N->clone();
935   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
936 }
937 
938 TEST_F(DIBasicTypeTest, getWithLargeValues) {
939   auto *N = DIBasicType::get(Context, dwarf::DW_TAG_base_type, "special",
940                              UINT64_MAX, UINT64_MAX - 1, 7);
941   EXPECT_EQ(UINT64_MAX, N->getSizeInBits());
942   EXPECT_EQ(UINT64_MAX - 1, N->getAlignInBits());
943 }
944 
945 TEST_F(DIBasicTypeTest, getUnspecified) {
946   auto *N =
947       DIBasicType::get(Context, dwarf::DW_TAG_unspecified_type, "unspecified");
948   EXPECT_EQ(dwarf::DW_TAG_unspecified_type, N->getTag());
949   EXPECT_EQ("unspecified", N->getName());
950   EXPECT_EQ(0u, N->getSizeInBits());
951   EXPECT_EQ(0u, N->getAlignInBits());
952   EXPECT_EQ(0u, N->getEncoding());
953   EXPECT_EQ(0u, N->getLine());
954 }
955 
956 typedef MetadataTest DITypeTest;
957 
958 TEST_F(DITypeTest, clone) {
959   // Check that DIType has a specialized clone that returns TempDIType.
960   DIType *N = DIBasicType::get(Context, dwarf::DW_TAG_base_type, "int", 32, 32,
961                                dwarf::DW_ATE_signed);
962 
963   TempDIType Temp = N->clone();
964   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
965 }
966 
967 TEST_F(DITypeTest, setFlags) {
968   // void (void)
969   Metadata *TypesOps[] = {nullptr};
970   Metadata *Types = MDTuple::get(Context, TypesOps);
971 
972   DIType *D = DISubroutineType::getDistinct(Context, 0u, 0, Types);
973   EXPECT_EQ(0u, D->getFlags());
974   D->setFlags(DINode::FlagRValueReference);
975   EXPECT_EQ(DINode::FlagRValueReference, D->getFlags());
976   D->setFlags(0u);
977   EXPECT_EQ(0u, D->getFlags());
978 
979   TempDIType T = DISubroutineType::getTemporary(Context, 0u, 0, Types);
980   EXPECT_EQ(0u, T->getFlags());
981   T->setFlags(DINode::FlagRValueReference);
982   EXPECT_EQ(DINode::FlagRValueReference, T->getFlags());
983   T->setFlags(0u);
984   EXPECT_EQ(0u, T->getFlags());
985 }
986 
987 typedef MetadataTest DIDerivedTypeTest;
988 
989 TEST_F(DIDerivedTypeTest, get) {
990   DIFile *File = getFile();
991   DIScope *Scope = getSubprogram();
992   DIType *BaseType = getBasicType("basic");
993   MDTuple *ExtraData = getTuple();
994 
995   auto *N = DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "something",
996                                File, 1, Scope, BaseType, 2, 3, 4, 5, ExtraData);
997   EXPECT_EQ(dwarf::DW_TAG_pointer_type, N->getTag());
998   EXPECT_EQ("something", N->getName());
999   EXPECT_EQ(File, N->getFile());
1000   EXPECT_EQ(1u, N->getLine());
1001   EXPECT_EQ(Scope, N->getScope());
1002   EXPECT_EQ(BaseType, N->getBaseType());
1003   EXPECT_EQ(2u, N->getSizeInBits());
1004   EXPECT_EQ(3u, N->getAlignInBits());
1005   EXPECT_EQ(4u, N->getOffsetInBits());
1006   EXPECT_EQ(5u, N->getFlags());
1007   EXPECT_EQ(ExtraData, N->getExtraData());
1008   EXPECT_EQ(N, DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
1009                                   "something", File, 1, Scope, BaseType, 2, 3,
1010                                   4, 5, ExtraData));
1011 
1012   EXPECT_NE(N, DIDerivedType::get(Context, dwarf::DW_TAG_reference_type,
1013                                   "something", File, 1, Scope, BaseType, 2, 3,
1014                                   4, 5, ExtraData));
1015   EXPECT_NE(N, DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "else",
1016                                   File, 1, Scope, BaseType, 2, 3, 4, 5,
1017                                   ExtraData));
1018   EXPECT_NE(N, DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
1019                                   "something", getFile(), 1, Scope, BaseType, 2,
1020                                   3, 4, 5, ExtraData));
1021   EXPECT_NE(N, DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
1022                                   "something", File, 2, Scope, BaseType, 2, 3,
1023                                   4, 5, ExtraData));
1024   EXPECT_NE(N, DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
1025                                   "something", File, 1, getSubprogram(),
1026                                   BaseType, 2, 3, 4, 5, ExtraData));
1027   EXPECT_NE(N, DIDerivedType::get(
1028                    Context, dwarf::DW_TAG_pointer_type, "something", File, 1,
1029                    Scope, getBasicType("basic2"), 2, 3, 4, 5, ExtraData));
1030   EXPECT_NE(N, DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
1031                                   "something", File, 1, Scope, BaseType, 3, 3,
1032                                   4, 5, ExtraData));
1033   EXPECT_NE(N, DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
1034                                   "something", File, 1, Scope, BaseType, 2, 2,
1035                                   4, 5, ExtraData));
1036   EXPECT_NE(N, DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
1037                                   "something", File, 1, Scope, BaseType, 2, 3,
1038                                   5, 5, ExtraData));
1039   EXPECT_NE(N, DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
1040                                   "something", File, 1, Scope, BaseType, 2, 3,
1041                                   4, 4, ExtraData));
1042   EXPECT_NE(N, DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type,
1043                                   "something", File, 1, Scope, BaseType, 2, 3,
1044                                   4, 5, getTuple()));
1045 
1046   TempDIDerivedType Temp = N->clone();
1047   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1048 }
1049 
1050 TEST_F(DIDerivedTypeTest, getWithLargeValues) {
1051   DIFile *File = getFile();
1052   DIScope *Scope = getSubprogram();
1053   DIType *BaseType = getBasicType("basic");
1054   MDTuple *ExtraData = getTuple();
1055 
1056   auto *N = DIDerivedType::get(Context, dwarf::DW_TAG_pointer_type, "something",
1057                                File, 1, Scope, BaseType, UINT64_MAX,
1058                                UINT64_MAX - 1, UINT64_MAX - 2, 5, ExtraData);
1059   EXPECT_EQ(UINT64_MAX, N->getSizeInBits());
1060   EXPECT_EQ(UINT64_MAX - 1, N->getAlignInBits());
1061   EXPECT_EQ(UINT64_MAX - 2, N->getOffsetInBits());
1062 }
1063 
1064 typedef MetadataTest DICompositeTypeTest;
1065 
1066 TEST_F(DICompositeTypeTest, get) {
1067   unsigned Tag = dwarf::DW_TAG_structure_type;
1068   StringRef Name = "some name";
1069   DIFile *File = getFile();
1070   unsigned Line = 1;
1071   DIScope *Scope = getSubprogram();
1072   DIType *BaseType = getCompositeType();
1073   uint64_t SizeInBits = 2;
1074   uint64_t AlignInBits = 3;
1075   uint64_t OffsetInBits = 4;
1076   unsigned Flags = 5;
1077   MDTuple *Elements = getTuple();
1078   unsigned RuntimeLang = 6;
1079   DIType *VTableHolder = getCompositeType();
1080   MDTuple *TemplateParams = getTuple();
1081   StringRef Identifier = "some id";
1082 
1083   auto *N = DICompositeType::get(Context, Tag, Name, File, Line, Scope,
1084                                  BaseType, SizeInBits, AlignInBits,
1085                                  OffsetInBits, Flags, Elements, RuntimeLang,
1086                                  VTableHolder, TemplateParams, Identifier);
1087   EXPECT_EQ(Tag, N->getTag());
1088   EXPECT_EQ(Name, N->getName());
1089   EXPECT_EQ(File, N->getFile());
1090   EXPECT_EQ(Line, N->getLine());
1091   EXPECT_EQ(Scope, N->getScope());
1092   EXPECT_EQ(BaseType, N->getBaseType());
1093   EXPECT_EQ(SizeInBits, N->getSizeInBits());
1094   EXPECT_EQ(AlignInBits, N->getAlignInBits());
1095   EXPECT_EQ(OffsetInBits, N->getOffsetInBits());
1096   EXPECT_EQ(Flags, N->getFlags());
1097   EXPECT_EQ(Elements, N->getElements().get());
1098   EXPECT_EQ(RuntimeLang, N->getRuntimeLang());
1099   EXPECT_EQ(VTableHolder, N->getVTableHolder());
1100   EXPECT_EQ(TemplateParams, N->getTemplateParams().get());
1101   EXPECT_EQ(Identifier, N->getIdentifier());
1102 
1103   EXPECT_EQ(N, DICompositeType::get(Context, Tag, Name, File, Line, Scope,
1104                                     BaseType, SizeInBits, AlignInBits,
1105                                     OffsetInBits, Flags, Elements, RuntimeLang,
1106                                     VTableHolder, TemplateParams, Identifier));
1107 
1108   EXPECT_NE(N, DICompositeType::get(Context, Tag + 1, Name, File, Line, Scope,
1109                                     BaseType, SizeInBits, AlignInBits,
1110                                     OffsetInBits, Flags, Elements, RuntimeLang,
1111                                     VTableHolder, TemplateParams, Identifier));
1112   EXPECT_NE(N, DICompositeType::get(Context, Tag, "abc", File, Line, Scope,
1113                                     BaseType, SizeInBits, AlignInBits,
1114                                     OffsetInBits, Flags, Elements, RuntimeLang,
1115                                     VTableHolder, TemplateParams, Identifier));
1116   EXPECT_NE(N, DICompositeType::get(Context, Tag, Name, getFile(), Line, Scope,
1117                                     BaseType, SizeInBits, AlignInBits,
1118                                     OffsetInBits, Flags, Elements, RuntimeLang,
1119                                     VTableHolder, TemplateParams, Identifier));
1120   EXPECT_NE(N, DICompositeType::get(Context, Tag, Name, File, Line + 1, Scope,
1121                                     BaseType, SizeInBits, AlignInBits,
1122                                     OffsetInBits, Flags, Elements, RuntimeLang,
1123                                     VTableHolder, TemplateParams, Identifier));
1124   EXPECT_NE(N, DICompositeType::get(
1125                    Context, Tag, Name, File, Line, getSubprogram(), BaseType,
1126                    SizeInBits, AlignInBits, OffsetInBits, Flags, Elements,
1127                    RuntimeLang, VTableHolder, TemplateParams, Identifier));
1128   EXPECT_NE(N, DICompositeType::get(
1129                    Context, Tag, Name, File, Line, Scope, getBasicType("other"),
1130                    SizeInBits, AlignInBits, OffsetInBits, Flags, Elements,
1131                    RuntimeLang, VTableHolder, TemplateParams, Identifier));
1132   EXPECT_NE(N, DICompositeType::get(Context, Tag, Name, File, Line, Scope,
1133                                     BaseType, SizeInBits + 1, AlignInBits,
1134                                     OffsetInBits, Flags, Elements, RuntimeLang,
1135                                     VTableHolder, TemplateParams, Identifier));
1136   EXPECT_NE(N, DICompositeType::get(Context, Tag, Name, File, Line, Scope,
1137                                     BaseType, SizeInBits, AlignInBits + 1,
1138                                     OffsetInBits, Flags, Elements, RuntimeLang,
1139                                     VTableHolder, TemplateParams, Identifier));
1140   EXPECT_NE(N, DICompositeType::get(
1141                    Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1142                    AlignInBits, OffsetInBits + 1, Flags, Elements, RuntimeLang,
1143                    VTableHolder, TemplateParams, Identifier));
1144   EXPECT_NE(N, DICompositeType::get(
1145                    Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1146                    AlignInBits, OffsetInBits, Flags + 1, Elements, RuntimeLang,
1147                    VTableHolder, TemplateParams, Identifier));
1148   EXPECT_NE(N, DICompositeType::get(
1149                    Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1150                    AlignInBits, OffsetInBits, Flags, getTuple(), RuntimeLang,
1151                    VTableHolder, TemplateParams, Identifier));
1152   EXPECT_NE(N, DICompositeType::get(
1153                    Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1154                    AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang + 1,
1155                    VTableHolder, TemplateParams, Identifier));
1156   EXPECT_NE(N, DICompositeType::get(
1157                    Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits,
1158                    AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
1159                    getCompositeType(), TemplateParams, Identifier));
1160   EXPECT_NE(N, DICompositeType::get(Context, Tag, Name, File, Line, Scope,
1161                                     BaseType, SizeInBits, AlignInBits,
1162                                     OffsetInBits, Flags, Elements, RuntimeLang,
1163                                     VTableHolder, getTuple(), Identifier));
1164   EXPECT_NE(N, DICompositeType::get(Context, Tag, Name, File, Line, Scope,
1165                                     BaseType, SizeInBits, AlignInBits,
1166                                     OffsetInBits, Flags, Elements, RuntimeLang,
1167                                     VTableHolder, TemplateParams, "other"));
1168 
1169   // Be sure that missing identifiers get null pointers.
1170   EXPECT_FALSE(DICompositeType::get(Context, Tag, Name, File, Line, Scope,
1171                                     BaseType, SizeInBits, AlignInBits,
1172                                     OffsetInBits, Flags, Elements, RuntimeLang,
1173                                     VTableHolder, TemplateParams, "")
1174                    ->getRawIdentifier());
1175   EXPECT_FALSE(DICompositeType::get(Context, Tag, Name, File, Line, Scope,
1176                                     BaseType, SizeInBits, AlignInBits,
1177                                     OffsetInBits, Flags, Elements, RuntimeLang,
1178                                     VTableHolder, TemplateParams)
1179                    ->getRawIdentifier());
1180 
1181   TempDICompositeType Temp = N->clone();
1182   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1183 }
1184 
1185 TEST_F(DICompositeTypeTest, getWithLargeValues) {
1186   unsigned Tag = dwarf::DW_TAG_structure_type;
1187   StringRef Name = "some name";
1188   DIFile *File = getFile();
1189   unsigned Line = 1;
1190   DIScope *Scope = getSubprogram();
1191   DIType *BaseType = getCompositeType();
1192   uint64_t SizeInBits = UINT64_MAX;
1193   uint64_t AlignInBits = UINT64_MAX - 1;
1194   uint64_t OffsetInBits = UINT64_MAX - 2;
1195   unsigned Flags = 5;
1196   MDTuple *Elements = getTuple();
1197   unsigned RuntimeLang = 6;
1198   DIType *VTableHolder = getCompositeType();
1199   MDTuple *TemplateParams = getTuple();
1200   StringRef Identifier = "some id";
1201 
1202   auto *N = DICompositeType::get(Context, Tag, Name, File, Line, Scope,
1203                                  BaseType, SizeInBits, AlignInBits,
1204                                  OffsetInBits, Flags, Elements, RuntimeLang,
1205                                  VTableHolder, TemplateParams, Identifier);
1206   EXPECT_EQ(SizeInBits, N->getSizeInBits());
1207   EXPECT_EQ(AlignInBits, N->getAlignInBits());
1208   EXPECT_EQ(OffsetInBits, N->getOffsetInBits());
1209 }
1210 
1211 TEST_F(DICompositeTypeTest, replaceOperands) {
1212   unsigned Tag = dwarf::DW_TAG_structure_type;
1213   StringRef Name = "some name";
1214   DIFile *File = getFile();
1215   unsigned Line = 1;
1216   DIScope *Scope = getSubprogram();
1217   DIType *BaseType = getCompositeType();
1218   uint64_t SizeInBits = 2;
1219   uint64_t AlignInBits = 3;
1220   uint64_t OffsetInBits = 4;
1221   unsigned Flags = 5;
1222   unsigned RuntimeLang = 6;
1223   StringRef Identifier = "some id";
1224 
1225   auto *N = DICompositeType::get(
1226       Context, Tag, Name, File, Line, Scope, BaseType, SizeInBits, AlignInBits,
1227       OffsetInBits, Flags, nullptr, RuntimeLang, nullptr, nullptr, Identifier);
1228 
1229   auto *Elements = MDTuple::getDistinct(Context, None);
1230   EXPECT_EQ(nullptr, N->getElements().get());
1231   N->replaceElements(Elements);
1232   EXPECT_EQ(Elements, N->getElements().get());
1233   N->replaceElements(nullptr);
1234   EXPECT_EQ(nullptr, N->getElements().get());
1235 
1236   DIType *VTableHolder = getCompositeType();
1237   EXPECT_EQ(nullptr, N->getVTableHolder());
1238   N->replaceVTableHolder(VTableHolder);
1239   EXPECT_EQ(VTableHolder, N->getVTableHolder());
1240   N->replaceVTableHolder(nullptr);
1241   EXPECT_EQ(nullptr, N->getVTableHolder());
1242 
1243   auto *TemplateParams = MDTuple::getDistinct(Context, None);
1244   EXPECT_EQ(nullptr, N->getTemplateParams().get());
1245   N->replaceTemplateParams(TemplateParams);
1246   EXPECT_EQ(TemplateParams, N->getTemplateParams().get());
1247   N->replaceTemplateParams(nullptr);
1248   EXPECT_EQ(nullptr, N->getTemplateParams().get());
1249 }
1250 
1251 typedef MetadataTest DISubroutineTypeTest;
1252 
1253 TEST_F(DISubroutineTypeTest, get) {
1254   unsigned Flags = 1;
1255   MDTuple *TypeArray = getTuple();
1256 
1257   auto *N = DISubroutineType::get(Context, Flags, 0, TypeArray);
1258   EXPECT_EQ(dwarf::DW_TAG_subroutine_type, N->getTag());
1259   EXPECT_EQ(Flags, N->getFlags());
1260   EXPECT_EQ(TypeArray, N->getTypeArray().get());
1261   EXPECT_EQ(N, DISubroutineType::get(Context, Flags, 0, TypeArray));
1262 
1263   EXPECT_NE(N, DISubroutineType::get(Context, Flags + 1, 0, TypeArray));
1264   EXPECT_NE(N, DISubroutineType::get(Context, Flags, 0, getTuple()));
1265 
1266   // Test the hashing of calling conventions.
1267   auto *Fast = DISubroutineType::get(
1268       Context, Flags, dwarf::DW_CC_BORLAND_msfastcall, TypeArray);
1269   auto *Std = DISubroutineType::get(Context, Flags,
1270                                     dwarf::DW_CC_BORLAND_stdcall, TypeArray);
1271   EXPECT_EQ(Fast,
1272             DISubroutineType::get(Context, Flags,
1273                                   dwarf::DW_CC_BORLAND_msfastcall, TypeArray));
1274   EXPECT_EQ(Std, DISubroutineType::get(
1275                      Context, Flags, dwarf::DW_CC_BORLAND_stdcall, TypeArray));
1276 
1277   EXPECT_NE(N, Fast);
1278   EXPECT_NE(N, Std);
1279   EXPECT_NE(Fast, Std);
1280 
1281   TempDISubroutineType Temp = N->clone();
1282   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1283 
1284   // Test always-empty operands.
1285   EXPECT_EQ(nullptr, N->getScope());
1286   EXPECT_EQ(nullptr, N->getFile());
1287   EXPECT_EQ("", N->getName());
1288 }
1289 
1290 typedef MetadataTest DIFileTest;
1291 
1292 TEST_F(DIFileTest, get) {
1293   StringRef Filename = "file";
1294   StringRef Directory = "dir";
1295   auto *N = DIFile::get(Context, Filename, Directory);
1296 
1297   EXPECT_EQ(dwarf::DW_TAG_file_type, N->getTag());
1298   EXPECT_EQ(Filename, N->getFilename());
1299   EXPECT_EQ(Directory, N->getDirectory());
1300   EXPECT_EQ(N, DIFile::get(Context, Filename, Directory));
1301 
1302   EXPECT_NE(N, DIFile::get(Context, "other", Directory));
1303   EXPECT_NE(N, DIFile::get(Context, Filename, "other"));
1304 
1305   TempDIFile Temp = N->clone();
1306   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1307 }
1308 
1309 TEST_F(DIFileTest, ScopeGetFile) {
1310   // Ensure that DIScope::getFile() returns itself.
1311   DIScope *N = DIFile::get(Context, "file", "dir");
1312   EXPECT_EQ(N, N->getFile());
1313 }
1314 
1315 typedef MetadataTest DICompileUnitTest;
1316 
1317 TEST_F(DICompileUnitTest, get) {
1318   unsigned SourceLanguage = 1;
1319   DIFile *File = getFile();
1320   StringRef Producer = "some producer";
1321   bool IsOptimized = false;
1322   StringRef Flags = "flag after flag";
1323   unsigned RuntimeVersion = 2;
1324   StringRef SplitDebugFilename = "another/file";
1325   auto EmissionKind = DICompileUnit::FullDebug;
1326   MDTuple *EnumTypes = getTuple();
1327   MDTuple *RetainedTypes = getTuple();
1328   MDTuple *GlobalVariables = getTuple();
1329   MDTuple *ImportedEntities = getTuple();
1330   uint64_t DWOId = 0x10000000c0ffee;
1331   MDTuple *Macros = getTuple();
1332   auto *N = DICompileUnit::getDistinct(
1333       Context, SourceLanguage, File, Producer, IsOptimized, Flags,
1334       RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes,
1335       RetainedTypes, GlobalVariables, ImportedEntities, Macros,
1336       DWOId);
1337 
1338   EXPECT_EQ(dwarf::DW_TAG_compile_unit, N->getTag());
1339   EXPECT_EQ(SourceLanguage, N->getSourceLanguage());
1340   EXPECT_EQ(File, N->getFile());
1341   EXPECT_EQ(Producer, N->getProducer());
1342   EXPECT_EQ(IsOptimized, N->isOptimized());
1343   EXPECT_EQ(Flags, N->getFlags());
1344   EXPECT_EQ(RuntimeVersion, N->getRuntimeVersion());
1345   EXPECT_EQ(SplitDebugFilename, N->getSplitDebugFilename());
1346   EXPECT_EQ(EmissionKind, N->getEmissionKind());
1347   EXPECT_EQ(EnumTypes, N->getEnumTypes().get());
1348   EXPECT_EQ(RetainedTypes, N->getRetainedTypes().get());
1349   EXPECT_EQ(GlobalVariables, N->getGlobalVariables().get());
1350   EXPECT_EQ(ImportedEntities, N->getImportedEntities().get());
1351   EXPECT_EQ(Macros, N->getMacros().get());
1352   EXPECT_EQ(DWOId, N->getDWOId());
1353 
1354   TempDICompileUnit Temp = N->clone();
1355   EXPECT_EQ(dwarf::DW_TAG_compile_unit, Temp->getTag());
1356   EXPECT_EQ(SourceLanguage, Temp->getSourceLanguage());
1357   EXPECT_EQ(File, Temp->getFile());
1358   EXPECT_EQ(Producer, Temp->getProducer());
1359   EXPECT_EQ(IsOptimized, Temp->isOptimized());
1360   EXPECT_EQ(Flags, Temp->getFlags());
1361   EXPECT_EQ(RuntimeVersion, Temp->getRuntimeVersion());
1362   EXPECT_EQ(SplitDebugFilename, Temp->getSplitDebugFilename());
1363   EXPECT_EQ(EmissionKind, Temp->getEmissionKind());
1364   EXPECT_EQ(EnumTypes, Temp->getEnumTypes().get());
1365   EXPECT_EQ(RetainedTypes, Temp->getRetainedTypes().get());
1366   EXPECT_EQ(GlobalVariables, Temp->getGlobalVariables().get());
1367   EXPECT_EQ(ImportedEntities, Temp->getImportedEntities().get());
1368   EXPECT_EQ(Macros, Temp->getMacros().get());
1369   EXPECT_EQ(DWOId, Temp->getDWOId());
1370 
1371   auto *TempAddress = Temp.get();
1372   auto *Clone = MDNode::replaceWithPermanent(std::move(Temp));
1373   EXPECT_TRUE(Clone->isDistinct());
1374   EXPECT_EQ(TempAddress, Clone);
1375 }
1376 
1377 TEST_F(DICompileUnitTest, replaceArrays) {
1378   unsigned SourceLanguage = 1;
1379   DIFile *File = getFile();
1380   StringRef Producer = "some producer";
1381   bool IsOptimized = false;
1382   StringRef Flags = "flag after flag";
1383   unsigned RuntimeVersion = 2;
1384   StringRef SplitDebugFilename = "another/file";
1385   auto EmissionKind = DICompileUnit::FullDebug;
1386   MDTuple *EnumTypes = MDTuple::getDistinct(Context, None);
1387   MDTuple *RetainedTypes = MDTuple::getDistinct(Context, None);
1388   MDTuple *ImportedEntities = MDTuple::getDistinct(Context, None);
1389   uint64_t DWOId = 0xc0ffee;
1390   auto *N = DICompileUnit::getDistinct(
1391       Context, SourceLanguage, File, Producer, IsOptimized, Flags,
1392       RuntimeVersion, SplitDebugFilename, EmissionKind, EnumTypes,
1393       RetainedTypes, nullptr, ImportedEntities, nullptr, DWOId);
1394 
1395   auto *GlobalVariables = MDTuple::getDistinct(Context, None);
1396   EXPECT_EQ(nullptr, N->getGlobalVariables().get());
1397   N->replaceGlobalVariables(GlobalVariables);
1398   EXPECT_EQ(GlobalVariables, N->getGlobalVariables().get());
1399   N->replaceGlobalVariables(nullptr);
1400   EXPECT_EQ(nullptr, N->getGlobalVariables().get());
1401 
1402   auto *Macros = MDTuple::getDistinct(Context, None);
1403   EXPECT_EQ(nullptr, N->getMacros().get());
1404   N->replaceMacros(Macros);
1405   EXPECT_EQ(Macros, N->getMacros().get());
1406   N->replaceMacros(nullptr);
1407   EXPECT_EQ(nullptr, N->getMacros().get());
1408 }
1409 
1410 typedef MetadataTest DISubprogramTest;
1411 
1412 TEST_F(DISubprogramTest, get) {
1413   DIScope *Scope = getCompositeType();
1414   StringRef Name = "name";
1415   StringRef LinkageName = "linkage";
1416   DIFile *File = getFile();
1417   unsigned Line = 2;
1418   DISubroutineType *Type = getSubroutineType();
1419   bool IsLocalToUnit = false;
1420   bool IsDefinition = true;
1421   unsigned ScopeLine = 3;
1422   DIType *ContainingType = getCompositeType();
1423   unsigned Virtuality = 2;
1424   unsigned VirtualIndex = 5;
1425   unsigned Flags = 6;
1426   unsigned NotFlags = (~Flags) & ((1 << 27) - 1);
1427   bool IsOptimized = false;
1428   MDTuple *TemplateParams = getTuple();
1429   DISubprogram *Declaration = getSubprogram();
1430   MDTuple *Variables = getTuple();
1431   DICompileUnit *Unit = getUnit();
1432 
1433   auto *N = DISubprogram::get(
1434       Context, Scope, Name, LinkageName, File, Line, Type, IsLocalToUnit,
1435       IsDefinition, ScopeLine, ContainingType, Virtuality, VirtualIndex, Flags,
1436       IsOptimized, Unit, TemplateParams, Declaration, Variables);
1437 
1438   EXPECT_EQ(dwarf::DW_TAG_subprogram, N->getTag());
1439   EXPECT_EQ(Scope, N->getScope());
1440   EXPECT_EQ(Name, N->getName());
1441   EXPECT_EQ(LinkageName, N->getLinkageName());
1442   EXPECT_EQ(File, N->getFile());
1443   EXPECT_EQ(Line, N->getLine());
1444   EXPECT_EQ(Type, N->getType());
1445   EXPECT_EQ(IsLocalToUnit, N->isLocalToUnit());
1446   EXPECT_EQ(IsDefinition, N->isDefinition());
1447   EXPECT_EQ(ScopeLine, N->getScopeLine());
1448   EXPECT_EQ(ContainingType, N->getContainingType());
1449   EXPECT_EQ(Virtuality, N->getVirtuality());
1450   EXPECT_EQ(VirtualIndex, N->getVirtualIndex());
1451   EXPECT_EQ(Flags, N->getFlags());
1452   EXPECT_EQ(IsOptimized, N->isOptimized());
1453   EXPECT_EQ(Unit, N->getUnit());
1454   EXPECT_EQ(TemplateParams, N->getTemplateParams().get());
1455   EXPECT_EQ(Declaration, N->getDeclaration());
1456   EXPECT_EQ(Variables, N->getVariables().get());
1457   EXPECT_EQ(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1458                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1459                                  ContainingType, Virtuality, VirtualIndex,
1460                                  Flags, IsOptimized, Unit, TemplateParams,
1461                                  Declaration, Variables));
1462 
1463   EXPECT_NE(N, DISubprogram::get(Context, getCompositeType(), Name, LinkageName,
1464                                  File, Line, Type, IsLocalToUnit, IsDefinition,
1465                                  ScopeLine, ContainingType, Virtuality,
1466                                  VirtualIndex, Flags, IsOptimized, Unit,
1467                                  TemplateParams, Declaration, Variables));
1468   EXPECT_NE(N, DISubprogram::get(Context, Scope, "other", LinkageName, File,
1469                                  Line, Type, IsLocalToUnit, IsDefinition,
1470                                  ScopeLine, ContainingType, Virtuality,
1471                                  VirtualIndex, Flags, IsOptimized, Unit,
1472                                  TemplateParams, Declaration, Variables));
1473   EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, "other", File, Line,
1474                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1475                                  ContainingType, Virtuality, VirtualIndex,
1476                                  Flags, IsOptimized, Unit, TemplateParams,
1477                                  Declaration, Variables));
1478   EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, getFile(),
1479                                  Line, Type, IsLocalToUnit, IsDefinition,
1480                                  ScopeLine, ContainingType, Virtuality,
1481                                  VirtualIndex, Flags, IsOptimized, Unit,
1482                                  TemplateParams, Declaration, Variables));
1483   EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File,
1484                                  Line + 1, Type, IsLocalToUnit, IsDefinition,
1485                                  ScopeLine, ContainingType, Virtuality,
1486                                  VirtualIndex, Flags, IsOptimized, Unit,
1487                                  TemplateParams, Declaration, Variables));
1488   EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1489                                  getSubroutineType(), IsLocalToUnit,
1490                                  IsDefinition, ScopeLine, ContainingType,
1491                                  Virtuality, VirtualIndex, Flags, IsOptimized,
1492                                  Unit, TemplateParams, Declaration, Variables));
1493   EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1494                                  Type, !IsLocalToUnit, IsDefinition, ScopeLine,
1495                                  ContainingType, Virtuality, VirtualIndex,
1496                                  Flags, IsOptimized, Unit, TemplateParams,
1497                                  Declaration, Variables));
1498   EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1499                                  Type, IsLocalToUnit, !IsDefinition, ScopeLine,
1500                                  ContainingType, Virtuality, VirtualIndex,
1501                                  Flags, IsOptimized, Unit, TemplateParams,
1502                                  Declaration, Variables));
1503   EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1504                                  Type, IsLocalToUnit, IsDefinition,
1505                                  ScopeLine + 1, ContainingType, Virtuality,
1506                                  VirtualIndex, Flags, IsOptimized, Unit,
1507                                  TemplateParams, Declaration, Variables));
1508   EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1509                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1510                                  getCompositeType(), Virtuality, VirtualIndex,
1511                                  Flags, IsOptimized, Unit, TemplateParams,
1512                                  Declaration, Variables));
1513   EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1514                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1515                                  ContainingType, Virtuality + 1, VirtualIndex,
1516                                  Flags, IsOptimized, Unit, TemplateParams,
1517                                  Declaration, Variables));
1518   EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1519                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1520                                  ContainingType, Virtuality, VirtualIndex + 1,
1521                                  Flags, IsOptimized, Unit, TemplateParams,
1522                                  Declaration, Variables));
1523   EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1524                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1525                                  ContainingType, Virtuality, VirtualIndex,
1526                                  NotFlags, IsOptimized, Unit, TemplateParams,
1527                                  Declaration, Variables));
1528   EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1529                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1530                                  ContainingType, Virtuality, VirtualIndex,
1531                                  Flags, !IsOptimized, Unit, TemplateParams,
1532                                  Declaration, Variables));
1533   EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1534                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1535                                  ContainingType, Virtuality, VirtualIndex,
1536                                  Flags, IsOptimized, nullptr, TemplateParams,
1537                                  Declaration, Variables));
1538   EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1539                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1540                                  ContainingType, Virtuality, VirtualIndex,
1541                                  Flags, IsOptimized, Unit, getTuple(),
1542                                  Declaration, Variables));
1543   EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1544                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1545                                  ContainingType, Virtuality, VirtualIndex,
1546                                  Flags, IsOptimized, Unit, TemplateParams,
1547                                  getSubprogram(), Variables));
1548   EXPECT_NE(N, DISubprogram::get(Context, Scope, Name, LinkageName, File, Line,
1549                                  Type, IsLocalToUnit, IsDefinition, ScopeLine,
1550                                  ContainingType, Virtuality, VirtualIndex,
1551                                  Flags, IsOptimized, Unit, TemplateParams,
1552                                  Declaration, getTuple()));
1553 
1554   TempDISubprogram Temp = N->clone();
1555   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1556 }
1557 
1558 typedef MetadataTest DILexicalBlockTest;
1559 
1560 TEST_F(DILexicalBlockTest, get) {
1561   DILocalScope *Scope = getSubprogram();
1562   DIFile *File = getFile();
1563   unsigned Line = 5;
1564   unsigned Column = 8;
1565 
1566   auto *N = DILexicalBlock::get(Context, Scope, File, Line, Column);
1567 
1568   EXPECT_EQ(dwarf::DW_TAG_lexical_block, N->getTag());
1569   EXPECT_EQ(Scope, N->getScope());
1570   EXPECT_EQ(File, N->getFile());
1571   EXPECT_EQ(Line, N->getLine());
1572   EXPECT_EQ(Column, N->getColumn());
1573   EXPECT_EQ(N, DILexicalBlock::get(Context, Scope, File, Line, Column));
1574 
1575   EXPECT_NE(N,
1576             DILexicalBlock::get(Context, getSubprogram(), File, Line, Column));
1577   EXPECT_NE(N, DILexicalBlock::get(Context, Scope, getFile(), Line, Column));
1578   EXPECT_NE(N, DILexicalBlock::get(Context, Scope, File, Line + 1, Column));
1579   EXPECT_NE(N, DILexicalBlock::get(Context, Scope, File, Line, Column + 1));
1580 
1581   TempDILexicalBlock Temp = N->clone();
1582   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1583 }
1584 
1585 TEST_F(DILexicalBlockTest, Overflow) {
1586   DISubprogram *SP = getSubprogram();
1587   DIFile *F = getFile();
1588   {
1589     auto *LB = DILexicalBlock::get(Context, SP, F, 2, 7);
1590     EXPECT_EQ(2u, LB->getLine());
1591     EXPECT_EQ(7u, LB->getColumn());
1592   }
1593   unsigned U16 = 1u << 16;
1594   {
1595     auto *LB = DILexicalBlock::get(Context, SP, F, UINT32_MAX, U16 - 1);
1596     EXPECT_EQ(UINT32_MAX, LB->getLine());
1597     EXPECT_EQ(U16 - 1, LB->getColumn());
1598   }
1599   {
1600     auto *LB = DILexicalBlock::get(Context, SP, F, UINT32_MAX, U16);
1601     EXPECT_EQ(UINT32_MAX, LB->getLine());
1602     EXPECT_EQ(0u, LB->getColumn());
1603   }
1604   {
1605     auto *LB = DILexicalBlock::get(Context, SP, F, UINT32_MAX, U16 + 1);
1606     EXPECT_EQ(UINT32_MAX, LB->getLine());
1607     EXPECT_EQ(0u, LB->getColumn());
1608   }
1609 }
1610 
1611 typedef MetadataTest DILexicalBlockFileTest;
1612 
1613 TEST_F(DILexicalBlockFileTest, get) {
1614   DILocalScope *Scope = getSubprogram();
1615   DIFile *File = getFile();
1616   unsigned Discriminator = 5;
1617 
1618   auto *N = DILexicalBlockFile::get(Context, Scope, File, Discriminator);
1619 
1620   EXPECT_EQ(dwarf::DW_TAG_lexical_block, N->getTag());
1621   EXPECT_EQ(Scope, N->getScope());
1622   EXPECT_EQ(File, N->getFile());
1623   EXPECT_EQ(Discriminator, N->getDiscriminator());
1624   EXPECT_EQ(N, DILexicalBlockFile::get(Context, Scope, File, Discriminator));
1625 
1626   EXPECT_NE(N, DILexicalBlockFile::get(Context, getSubprogram(), File,
1627                                        Discriminator));
1628   EXPECT_NE(N,
1629             DILexicalBlockFile::get(Context, Scope, getFile(), Discriminator));
1630   EXPECT_NE(N,
1631             DILexicalBlockFile::get(Context, Scope, File, Discriminator + 1));
1632 
1633   TempDILexicalBlockFile Temp = N->clone();
1634   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1635 }
1636 
1637 typedef MetadataTest DINamespaceTest;
1638 
1639 TEST_F(DINamespaceTest, get) {
1640   DIScope *Scope = getFile();
1641   DIFile *File = getFile();
1642   StringRef Name = "namespace";
1643   unsigned Line = 5;
1644 
1645   auto *N = DINamespace::get(Context, Scope, File, Name, Line);
1646 
1647   EXPECT_EQ(dwarf::DW_TAG_namespace, N->getTag());
1648   EXPECT_EQ(Scope, N->getScope());
1649   EXPECT_EQ(File, N->getFile());
1650   EXPECT_EQ(Name, N->getName());
1651   EXPECT_EQ(Line, N->getLine());
1652   EXPECT_EQ(N, DINamespace::get(Context, Scope, File, Name, Line));
1653 
1654   EXPECT_NE(N, DINamespace::get(Context, getFile(), File, Name, Line));
1655   EXPECT_NE(N, DINamespace::get(Context, Scope, getFile(), Name, Line));
1656   EXPECT_NE(N, DINamespace::get(Context, Scope, File, "other", Line));
1657   EXPECT_NE(N, DINamespace::get(Context, Scope, File, Name, Line + 1));
1658 
1659   TempDINamespace Temp = N->clone();
1660   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1661 }
1662 
1663 typedef MetadataTest DIModuleTest;
1664 
1665 TEST_F(DIModuleTest, get) {
1666   DIScope *Scope = getFile();
1667   StringRef Name = "module";
1668   StringRef ConfigMacro = "-DNDEBUG";
1669   StringRef Includes = "-I.";
1670   StringRef Sysroot = "/";
1671 
1672   auto *N = DIModule::get(Context, Scope, Name, ConfigMacro, Includes, Sysroot);
1673 
1674   EXPECT_EQ(dwarf::DW_TAG_module, N->getTag());
1675   EXPECT_EQ(Scope, N->getScope());
1676   EXPECT_EQ(Name, N->getName());
1677   EXPECT_EQ(ConfigMacro, N->getConfigurationMacros());
1678   EXPECT_EQ(Includes, N->getIncludePath());
1679   EXPECT_EQ(Sysroot, N->getISysRoot());
1680   EXPECT_EQ(N, DIModule::get(Context, Scope, Name,
1681                              ConfigMacro, Includes, Sysroot));
1682   EXPECT_NE(N, DIModule::get(Context, getFile(), Name,
1683                              ConfigMacro, Includes, Sysroot));
1684   EXPECT_NE(N, DIModule::get(Context, Scope, "other",
1685                              ConfigMacro, Includes, Sysroot));
1686   EXPECT_NE(N, DIModule::get(Context, Scope, Name,
1687                              "other", Includes, Sysroot));
1688   EXPECT_NE(N, DIModule::get(Context, Scope, Name,
1689                              ConfigMacro, "other", Sysroot));
1690   EXPECT_NE(N, DIModule::get(Context, Scope, Name,
1691                              ConfigMacro, Includes, "other"));
1692 
1693   TempDIModule Temp = N->clone();
1694   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1695 }
1696 
1697 typedef MetadataTest DITemplateTypeParameterTest;
1698 
1699 TEST_F(DITemplateTypeParameterTest, get) {
1700   StringRef Name = "template";
1701   DIType *Type = getBasicType("basic");
1702 
1703   auto *N = DITemplateTypeParameter::get(Context, Name, Type);
1704 
1705   EXPECT_EQ(dwarf::DW_TAG_template_type_parameter, N->getTag());
1706   EXPECT_EQ(Name, N->getName());
1707   EXPECT_EQ(Type, N->getType());
1708   EXPECT_EQ(N, DITemplateTypeParameter::get(Context, Name, Type));
1709 
1710   EXPECT_NE(N, DITemplateTypeParameter::get(Context, "other", Type));
1711   EXPECT_NE(N,
1712             DITemplateTypeParameter::get(Context, Name, getBasicType("other")));
1713 
1714   TempDITemplateTypeParameter Temp = N->clone();
1715   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1716 }
1717 
1718 typedef MetadataTest DITemplateValueParameterTest;
1719 
1720 TEST_F(DITemplateValueParameterTest, get) {
1721   unsigned Tag = dwarf::DW_TAG_template_value_parameter;
1722   StringRef Name = "template";
1723   DIType *Type = getBasicType("basic");
1724   Metadata *Value = getConstantAsMetadata();
1725 
1726   auto *N = DITemplateValueParameter::get(Context, Tag, Name, Type, Value);
1727   EXPECT_EQ(Tag, N->getTag());
1728   EXPECT_EQ(Name, N->getName());
1729   EXPECT_EQ(Type, N->getType());
1730   EXPECT_EQ(Value, N->getValue());
1731   EXPECT_EQ(N, DITemplateValueParameter::get(Context, Tag, Name, Type, Value));
1732 
1733   EXPECT_NE(N, DITemplateValueParameter::get(
1734                    Context, dwarf::DW_TAG_GNU_template_template_param, Name,
1735                    Type, Value));
1736   EXPECT_NE(N,
1737             DITemplateValueParameter::get(Context, Tag, "other", Type, Value));
1738   EXPECT_NE(N, DITemplateValueParameter::get(Context, Tag, Name,
1739                                              getBasicType("other"), Value));
1740   EXPECT_NE(N, DITemplateValueParameter::get(Context, Tag, Name, Type,
1741                                              getConstantAsMetadata()));
1742 
1743   TempDITemplateValueParameter Temp = N->clone();
1744   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1745 }
1746 
1747 typedef MetadataTest DIGlobalVariableTest;
1748 
1749 TEST_F(DIGlobalVariableTest, get) {
1750   DIScope *Scope = getSubprogram();
1751   StringRef Name = "name";
1752   StringRef LinkageName = "linkage";
1753   DIFile *File = getFile();
1754   unsigned Line = 5;
1755   DIType *Type = getDerivedType();
1756   bool IsLocalToUnit = false;
1757   bool IsDefinition = true;
1758   Constant *Variable = getConstant();
1759   DIDerivedType *StaticDataMemberDeclaration =
1760       cast<DIDerivedType>(getDerivedType());
1761 
1762   auto *N = DIGlobalVariable::get(Context, Scope, Name, LinkageName, File, Line,
1763                                   Type, IsLocalToUnit, IsDefinition, Variable,
1764                                   StaticDataMemberDeclaration);
1765   EXPECT_EQ(dwarf::DW_TAG_variable, N->getTag());
1766   EXPECT_EQ(Scope, N->getScope());
1767   EXPECT_EQ(Name, N->getName());
1768   EXPECT_EQ(LinkageName, N->getLinkageName());
1769   EXPECT_EQ(File, N->getFile());
1770   EXPECT_EQ(Line, N->getLine());
1771   EXPECT_EQ(Type, N->getType());
1772   EXPECT_EQ(IsLocalToUnit, N->isLocalToUnit());
1773   EXPECT_EQ(IsDefinition, N->isDefinition());
1774   EXPECT_EQ(Variable, N->getVariable());
1775   EXPECT_EQ(StaticDataMemberDeclaration, N->getStaticDataMemberDeclaration());
1776   EXPECT_EQ(N, DIGlobalVariable::get(Context, Scope, Name, LinkageName, File,
1777                                      Line, Type, IsLocalToUnit, IsDefinition,
1778                                      Variable, StaticDataMemberDeclaration));
1779 
1780   EXPECT_NE(N,
1781             DIGlobalVariable::get(Context, getSubprogram(), Name, LinkageName,
1782                                   File, Line, Type, IsLocalToUnit, IsDefinition,
1783                                   Variable, StaticDataMemberDeclaration));
1784   EXPECT_NE(N, DIGlobalVariable::get(Context, Scope, "other", LinkageName, File,
1785                                      Line, Type, IsLocalToUnit, IsDefinition,
1786                                      Variable, StaticDataMemberDeclaration));
1787   EXPECT_NE(N, DIGlobalVariable::get(Context, Scope, Name, "other", File, Line,
1788                                      Type, IsLocalToUnit, IsDefinition,
1789                                      Variable, StaticDataMemberDeclaration));
1790   EXPECT_NE(N,
1791             DIGlobalVariable::get(Context, Scope, Name, LinkageName, getFile(),
1792                                   Line, Type, IsLocalToUnit, IsDefinition,
1793                                   Variable, StaticDataMemberDeclaration));
1794   EXPECT_NE(N,
1795             DIGlobalVariable::get(Context, Scope, Name, LinkageName, File,
1796                                   Line + 1, Type, IsLocalToUnit, IsDefinition,
1797                                   Variable, StaticDataMemberDeclaration));
1798   EXPECT_NE(N,
1799             DIGlobalVariable::get(Context, Scope, Name, LinkageName, File, Line,
1800                                   getDerivedType(), IsLocalToUnit, IsDefinition,
1801                                   Variable, StaticDataMemberDeclaration));
1802   EXPECT_NE(N, DIGlobalVariable::get(Context, Scope, Name, LinkageName, File,
1803                                      Line, Type, !IsLocalToUnit, IsDefinition,
1804                                      Variable, StaticDataMemberDeclaration));
1805   EXPECT_NE(N, DIGlobalVariable::get(Context, Scope, Name, LinkageName, File,
1806                                      Line, Type, IsLocalToUnit, !IsDefinition,
1807                                      Variable, StaticDataMemberDeclaration));
1808   EXPECT_NE(N,
1809             DIGlobalVariable::get(Context, Scope, Name, LinkageName, File, Line,
1810                                   Type, IsLocalToUnit, IsDefinition,
1811                                   getConstant(), StaticDataMemberDeclaration));
1812   EXPECT_NE(N,
1813             DIGlobalVariable::get(Context, Scope, Name, LinkageName, File, Line,
1814                                   Type, IsLocalToUnit, IsDefinition, Variable,
1815                                   cast<DIDerivedType>(getDerivedType())));
1816 
1817   TempDIGlobalVariable Temp = N->clone();
1818   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1819 }
1820 
1821 typedef MetadataTest DILocalVariableTest;
1822 
1823 TEST_F(DILocalVariableTest, get) {
1824   DILocalScope *Scope = getSubprogram();
1825   StringRef Name = "name";
1826   DIFile *File = getFile();
1827   unsigned Line = 5;
1828   DIType *Type = getDerivedType();
1829   unsigned Arg = 6;
1830   unsigned Flags = 7;
1831   unsigned NotFlags = (~Flags) & ((1 << 16) - 1);
1832 
1833   auto *N =
1834       DILocalVariable::get(Context, Scope, Name, File, Line, Type, Arg, Flags);
1835   EXPECT_TRUE(N->isParameter());
1836   EXPECT_EQ(Scope, N->getScope());
1837   EXPECT_EQ(Name, N->getName());
1838   EXPECT_EQ(File, N->getFile());
1839   EXPECT_EQ(Line, N->getLine());
1840   EXPECT_EQ(Type, N->getType());
1841   EXPECT_EQ(Arg, N->getArg());
1842   EXPECT_EQ(Flags, N->getFlags());
1843   EXPECT_EQ(N, DILocalVariable::get(Context, Scope, Name, File, Line, Type, Arg,
1844                                     Flags));
1845 
1846   EXPECT_FALSE(
1847       DILocalVariable::get(Context, Scope, Name, File, Line, Type, 0, Flags)
1848           ->isParameter());
1849   EXPECT_NE(N, DILocalVariable::get(Context, getSubprogram(), Name, File, Line,
1850                                     Type, Arg, Flags));
1851   EXPECT_NE(N, DILocalVariable::get(Context, Scope, "other", File, Line, Type,
1852                                     Arg, Flags));
1853   EXPECT_NE(N, DILocalVariable::get(Context, Scope, Name, getFile(), Line, Type,
1854                                     Arg, Flags));
1855   EXPECT_NE(N, DILocalVariable::get(Context, Scope, Name, File, Line + 1, Type,
1856                                     Arg, Flags));
1857   EXPECT_NE(N, DILocalVariable::get(Context, Scope, Name, File, Line,
1858                                     getDerivedType(), Arg, Flags));
1859   EXPECT_NE(N, DILocalVariable::get(Context, Scope, Name, File, Line, Type,
1860                                     Arg + 1, Flags));
1861   EXPECT_NE(N, DILocalVariable::get(Context, Scope, Name, File, Line, Type, Arg,
1862                                     NotFlags));
1863 
1864   TempDILocalVariable Temp = N->clone();
1865   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1866 }
1867 
1868 TEST_F(DILocalVariableTest, getArg256) {
1869   EXPECT_EQ(255u, DILocalVariable::get(Context, getSubprogram(), "", getFile(),
1870                                        0, nullptr, 255, 0)
1871                       ->getArg());
1872   EXPECT_EQ(256u, DILocalVariable::get(Context, getSubprogram(), "", getFile(),
1873                                        0, nullptr, 256, 0)
1874                       ->getArg());
1875   EXPECT_EQ(257u, DILocalVariable::get(Context, getSubprogram(), "", getFile(),
1876                                        0, nullptr, 257, 0)
1877                       ->getArg());
1878   unsigned Max = UINT16_MAX;
1879   EXPECT_EQ(Max, DILocalVariable::get(Context, getSubprogram(), "", getFile(),
1880                                       0, nullptr, Max, 0)
1881                      ->getArg());
1882 }
1883 
1884 typedef MetadataTest DIExpressionTest;
1885 
1886 TEST_F(DIExpressionTest, get) {
1887   uint64_t Elements[] = {2, 6, 9, 78, 0};
1888   auto *N = DIExpression::get(Context, Elements);
1889   EXPECT_EQ(makeArrayRef(Elements), N->getElements());
1890   EXPECT_EQ(N, DIExpression::get(Context, Elements));
1891 
1892   EXPECT_EQ(5u, N->getNumElements());
1893   EXPECT_EQ(2u, N->getElement(0));
1894   EXPECT_EQ(6u, N->getElement(1));
1895   EXPECT_EQ(9u, N->getElement(2));
1896   EXPECT_EQ(78u, N->getElement(3));
1897   EXPECT_EQ(0u, N->getElement(4));
1898 
1899   TempDIExpression Temp = N->clone();
1900   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1901 }
1902 
1903 TEST_F(DIExpressionTest, isValid) {
1904 #define EXPECT_VALID(...)                                                      \
1905   do {                                                                         \
1906     uint64_t Elements[] = {__VA_ARGS__};                                       \
1907     EXPECT_TRUE(DIExpression::get(Context, Elements)->isValid());              \
1908   } while (false)
1909 #define EXPECT_INVALID(...)                                                    \
1910   do {                                                                         \
1911     uint64_t Elements[] = {__VA_ARGS__};                                       \
1912     EXPECT_FALSE(DIExpression::get(Context, Elements)->isValid());             \
1913   } while (false)
1914 
1915   // Empty expression should be valid.
1916   EXPECT_TRUE(DIExpression::get(Context, None));
1917 
1918   // Valid constructions.
1919   EXPECT_VALID(dwarf::DW_OP_plus, 6);
1920   EXPECT_VALID(dwarf::DW_OP_deref);
1921   EXPECT_VALID(dwarf::DW_OP_bit_piece, 3, 7);
1922   EXPECT_VALID(dwarf::DW_OP_plus, 6, dwarf::DW_OP_deref);
1923   EXPECT_VALID(dwarf::DW_OP_deref, dwarf::DW_OP_plus, 6);
1924   EXPECT_VALID(dwarf::DW_OP_deref, dwarf::DW_OP_bit_piece, 3, 7);
1925   EXPECT_VALID(dwarf::DW_OP_deref, dwarf::DW_OP_plus, 6, dwarf::DW_OP_bit_piece, 3, 7);
1926 
1927   // Invalid constructions.
1928   EXPECT_INVALID(~0u);
1929   EXPECT_INVALID(dwarf::DW_OP_plus);
1930   EXPECT_INVALID(dwarf::DW_OP_bit_piece);
1931   EXPECT_INVALID(dwarf::DW_OP_bit_piece, 3);
1932   EXPECT_INVALID(dwarf::DW_OP_bit_piece, 3, 7, dwarf::DW_OP_plus, 3);
1933   EXPECT_INVALID(dwarf::DW_OP_bit_piece, 3, 7, dwarf::DW_OP_deref);
1934 
1935 #undef EXPECT_VALID
1936 #undef EXPECT_INVALID
1937 }
1938 
1939 typedef MetadataTest DIObjCPropertyTest;
1940 
1941 TEST_F(DIObjCPropertyTest, get) {
1942   StringRef Name = "name";
1943   DIFile *File = getFile();
1944   unsigned Line = 5;
1945   StringRef GetterName = "getter";
1946   StringRef SetterName = "setter";
1947   unsigned Attributes = 7;
1948   DIType *Type = getBasicType("basic");
1949 
1950   auto *N = DIObjCProperty::get(Context, Name, File, Line, GetterName,
1951                                 SetterName, Attributes, Type);
1952 
1953   EXPECT_EQ(dwarf::DW_TAG_APPLE_property, N->getTag());
1954   EXPECT_EQ(Name, N->getName());
1955   EXPECT_EQ(File, N->getFile());
1956   EXPECT_EQ(Line, N->getLine());
1957   EXPECT_EQ(GetterName, N->getGetterName());
1958   EXPECT_EQ(SetterName, N->getSetterName());
1959   EXPECT_EQ(Attributes, N->getAttributes());
1960   EXPECT_EQ(Type, N->getType());
1961   EXPECT_EQ(N, DIObjCProperty::get(Context, Name, File, Line, GetterName,
1962                                    SetterName, Attributes, Type));
1963 
1964   EXPECT_NE(N, DIObjCProperty::get(Context, "other", File, Line, GetterName,
1965                                    SetterName, Attributes, Type));
1966   EXPECT_NE(N, DIObjCProperty::get(Context, Name, getFile(), Line, GetterName,
1967                                    SetterName, Attributes, Type));
1968   EXPECT_NE(N, DIObjCProperty::get(Context, Name, File, Line + 1, GetterName,
1969                                    SetterName, Attributes, Type));
1970   EXPECT_NE(N, DIObjCProperty::get(Context, Name, File, Line, "other",
1971                                    SetterName, Attributes, Type));
1972   EXPECT_NE(N, DIObjCProperty::get(Context, Name, File, Line, GetterName,
1973                                    "other", Attributes, Type));
1974   EXPECT_NE(N, DIObjCProperty::get(Context, Name, File, Line, GetterName,
1975                                    SetterName, Attributes + 1, Type));
1976   EXPECT_NE(N, DIObjCProperty::get(Context, Name, File, Line, GetterName,
1977                                    SetterName, Attributes,
1978                                    getBasicType("other")));
1979 
1980   TempDIObjCProperty Temp = N->clone();
1981   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
1982 }
1983 
1984 typedef MetadataTest DIImportedEntityTest;
1985 
1986 TEST_F(DIImportedEntityTest, get) {
1987   unsigned Tag = dwarf::DW_TAG_imported_module;
1988   DIScope *Scope = getSubprogram();
1989   DINode *Entity = getCompositeType();
1990   unsigned Line = 5;
1991   StringRef Name = "name";
1992 
1993   auto *N = DIImportedEntity::get(Context, Tag, Scope, Entity, Line, Name);
1994 
1995   EXPECT_EQ(Tag, N->getTag());
1996   EXPECT_EQ(Scope, N->getScope());
1997   EXPECT_EQ(Entity, N->getEntity());
1998   EXPECT_EQ(Line, N->getLine());
1999   EXPECT_EQ(Name, N->getName());
2000   EXPECT_EQ(N, DIImportedEntity::get(Context, Tag, Scope, Entity, Line, Name));
2001 
2002   EXPECT_NE(N,
2003             DIImportedEntity::get(Context, dwarf::DW_TAG_imported_declaration,
2004                                   Scope, Entity, Line, Name));
2005   EXPECT_NE(N, DIImportedEntity::get(Context, Tag, getSubprogram(), Entity,
2006                                      Line, Name));
2007   EXPECT_NE(N, DIImportedEntity::get(Context, Tag, Scope, getCompositeType(),
2008                                      Line, Name));
2009   EXPECT_NE(N,
2010             DIImportedEntity::get(Context, Tag, Scope, Entity, Line + 1, Name));
2011   EXPECT_NE(N,
2012             DIImportedEntity::get(Context, Tag, Scope, Entity, Line, "other"));
2013 
2014   TempDIImportedEntity Temp = N->clone();
2015   EXPECT_EQ(N, MDNode::replaceWithUniqued(std::move(Temp)));
2016 }
2017 
2018 typedef MetadataTest MetadataAsValueTest;
2019 
2020 TEST_F(MetadataAsValueTest, MDNode) {
2021   MDNode *N = MDNode::get(Context, None);
2022   auto *V = MetadataAsValue::get(Context, N);
2023   EXPECT_TRUE(V->getType()->isMetadataTy());
2024   EXPECT_EQ(N, V->getMetadata());
2025 
2026   auto *V2 = MetadataAsValue::get(Context, N);
2027   EXPECT_EQ(V, V2);
2028 }
2029 
2030 TEST_F(MetadataAsValueTest, MDNodeMDNode) {
2031   MDNode *N = MDNode::get(Context, None);
2032   Metadata *Ops[] = {N};
2033   MDNode *N2 = MDNode::get(Context, Ops);
2034   auto *V = MetadataAsValue::get(Context, N2);
2035   EXPECT_TRUE(V->getType()->isMetadataTy());
2036   EXPECT_EQ(N2, V->getMetadata());
2037 
2038   auto *V2 = MetadataAsValue::get(Context, N2);
2039   EXPECT_EQ(V, V2);
2040 
2041   auto *V3 = MetadataAsValue::get(Context, N);
2042   EXPECT_TRUE(V3->getType()->isMetadataTy());
2043   EXPECT_NE(V, V3);
2044   EXPECT_EQ(N, V3->getMetadata());
2045 }
2046 
2047 TEST_F(MetadataAsValueTest, MDNodeConstant) {
2048   auto *C = ConstantInt::getTrue(Context);
2049   auto *MD = ConstantAsMetadata::get(C);
2050   Metadata *Ops[] = {MD};
2051   auto *N = MDNode::get(Context, Ops);
2052 
2053   auto *V = MetadataAsValue::get(Context, MD);
2054   EXPECT_TRUE(V->getType()->isMetadataTy());
2055   EXPECT_EQ(MD, V->getMetadata());
2056 
2057   auto *V2 = MetadataAsValue::get(Context, N);
2058   EXPECT_EQ(MD, V2->getMetadata());
2059   EXPECT_EQ(V, V2);
2060 }
2061 
2062 typedef MetadataTest ValueAsMetadataTest;
2063 
2064 TEST_F(ValueAsMetadataTest, UpdatesOnRAUW) {
2065   Type *Ty = Type::getInt1PtrTy(Context);
2066   std::unique_ptr<GlobalVariable> GV0(
2067       new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage));
2068   auto *MD = ValueAsMetadata::get(GV0.get());
2069   EXPECT_TRUE(MD->getValue() == GV0.get());
2070   ASSERT_TRUE(GV0->use_empty());
2071 
2072   std::unique_ptr<GlobalVariable> GV1(
2073       new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage));
2074   GV0->replaceAllUsesWith(GV1.get());
2075   EXPECT_TRUE(MD->getValue() == GV1.get());
2076 }
2077 
2078 TEST_F(ValueAsMetadataTest, TempTempReplacement) {
2079   // Create a constant.
2080   ConstantAsMetadata *CI =
2081       ConstantAsMetadata::get(ConstantInt::get(Context, APInt(8, 0)));
2082 
2083   auto Temp1 = MDTuple::getTemporary(Context, None);
2084   auto Temp2 = MDTuple::getTemporary(Context, {CI});
2085   auto *N = MDTuple::get(Context, {Temp1.get()});
2086 
2087   // Test replacing a temporary node with another temporary node.
2088   Temp1->replaceAllUsesWith(Temp2.get());
2089   EXPECT_EQ(N->getOperand(0), Temp2.get());
2090 
2091   // Clean up Temp2 for teardown.
2092   Temp2->replaceAllUsesWith(nullptr);
2093 }
2094 
2095 TEST_F(ValueAsMetadataTest, CollidingDoubleUpdates) {
2096   // Create a constant.
2097   ConstantAsMetadata *CI =
2098       ConstantAsMetadata::get(ConstantInt::get(Context, APInt(8, 0)));
2099 
2100   // Create a temporary to prevent nodes from resolving.
2101   auto Temp = MDTuple::getTemporary(Context, None);
2102 
2103   // When the first operand of N1 gets reset to nullptr, it'll collide with N2.
2104   Metadata *Ops1[] = {CI, CI, Temp.get()};
2105   Metadata *Ops2[] = {nullptr, CI, Temp.get()};
2106 
2107   auto *N1 = MDTuple::get(Context, Ops1);
2108   auto *N2 = MDTuple::get(Context, Ops2);
2109   ASSERT_NE(N1, N2);
2110 
2111   // Tell metadata that the constant is getting deleted.
2112   //
2113   // After this, N1 will be invalid, so don't touch it.
2114   ValueAsMetadata::handleDeletion(CI->getValue());
2115   EXPECT_EQ(nullptr, N2->getOperand(0));
2116   EXPECT_EQ(nullptr, N2->getOperand(1));
2117   EXPECT_EQ(Temp.get(), N2->getOperand(2));
2118 
2119   // Clean up Temp for teardown.
2120   Temp->replaceAllUsesWith(nullptr);
2121 }
2122 
2123 typedef MetadataTest TrackingMDRefTest;
2124 
2125 TEST_F(TrackingMDRefTest, UpdatesOnRAUW) {
2126   Type *Ty = Type::getInt1PtrTy(Context);
2127   std::unique_ptr<GlobalVariable> GV0(
2128       new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage));
2129   TypedTrackingMDRef<ValueAsMetadata> MD(ValueAsMetadata::get(GV0.get()));
2130   EXPECT_TRUE(MD->getValue() == GV0.get());
2131   ASSERT_TRUE(GV0->use_empty());
2132 
2133   std::unique_ptr<GlobalVariable> GV1(
2134       new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage));
2135   GV0->replaceAllUsesWith(GV1.get());
2136   EXPECT_TRUE(MD->getValue() == GV1.get());
2137 
2138   // Reset it, so we don't inadvertently test deletion.
2139   MD.reset();
2140 }
2141 
2142 TEST_F(TrackingMDRefTest, UpdatesOnDeletion) {
2143   Type *Ty = Type::getInt1PtrTy(Context);
2144   std::unique_ptr<GlobalVariable> GV(
2145       new GlobalVariable(Ty, false, GlobalValue::ExternalLinkage));
2146   TypedTrackingMDRef<ValueAsMetadata> MD(ValueAsMetadata::get(GV.get()));
2147   EXPECT_TRUE(MD->getValue() == GV.get());
2148   ASSERT_TRUE(GV->use_empty());
2149 
2150   GV.reset();
2151   EXPECT_TRUE(!MD);
2152 }
2153 
2154 TEST(NamedMDNodeTest, Search) {
2155   LLVMContext Context;
2156   ConstantAsMetadata *C =
2157       ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), 1));
2158   ConstantAsMetadata *C2 =
2159       ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), 2));
2160 
2161   Metadata *const V = C;
2162   Metadata *const V2 = C2;
2163   MDNode *n = MDNode::get(Context, V);
2164   MDNode *n2 = MDNode::get(Context, V2);
2165 
2166   Module M("MyModule", Context);
2167   const char *Name = "llvm.NMD1";
2168   NamedMDNode *NMD = M.getOrInsertNamedMetadata(Name);
2169   NMD->addOperand(n);
2170   NMD->addOperand(n2);
2171 
2172   std::string Str;
2173   raw_string_ostream oss(Str);
2174   NMD->print(oss);
2175   EXPECT_STREQ("!llvm.NMD1 = !{!0, !1}\n",
2176                oss.str().c_str());
2177 }
2178 
2179 typedef MetadataTest FunctionAttachmentTest;
2180 TEST_F(FunctionAttachmentTest, setMetadata) {
2181   Function *F = getFunction("foo");
2182   ASSERT_FALSE(F->hasMetadata());
2183   EXPECT_EQ(nullptr, F->getMetadata(LLVMContext::MD_dbg));
2184   EXPECT_EQ(nullptr, F->getMetadata("dbg"));
2185   EXPECT_EQ(nullptr, F->getMetadata("other"));
2186 
2187   DISubprogram *SP1 = getSubprogram();
2188   DISubprogram *SP2 = getSubprogram();
2189   ASSERT_NE(SP1, SP2);
2190 
2191   F->setMetadata("dbg", SP1);
2192   EXPECT_TRUE(F->hasMetadata());
2193   EXPECT_EQ(SP1, F->getMetadata(LLVMContext::MD_dbg));
2194   EXPECT_EQ(SP1, F->getMetadata("dbg"));
2195   EXPECT_EQ(nullptr, F->getMetadata("other"));
2196 
2197   F->setMetadata(LLVMContext::MD_dbg, SP2);
2198   EXPECT_TRUE(F->hasMetadata());
2199   EXPECT_EQ(SP2, F->getMetadata(LLVMContext::MD_dbg));
2200   EXPECT_EQ(SP2, F->getMetadata("dbg"));
2201   EXPECT_EQ(nullptr, F->getMetadata("other"));
2202 
2203   F->setMetadata("dbg", nullptr);
2204   EXPECT_FALSE(F->hasMetadata());
2205   EXPECT_EQ(nullptr, F->getMetadata(LLVMContext::MD_dbg));
2206   EXPECT_EQ(nullptr, F->getMetadata("dbg"));
2207   EXPECT_EQ(nullptr, F->getMetadata("other"));
2208 
2209   MDTuple *T1 = getTuple();
2210   MDTuple *T2 = getTuple();
2211   ASSERT_NE(T1, T2);
2212 
2213   F->setMetadata("other1", T1);
2214   F->setMetadata("other2", T2);
2215   EXPECT_TRUE(F->hasMetadata());
2216   EXPECT_EQ(T1, F->getMetadata("other1"));
2217   EXPECT_EQ(T2, F->getMetadata("other2"));
2218   EXPECT_EQ(nullptr, F->getMetadata("dbg"));
2219 
2220   F->setMetadata("other1", T2);
2221   F->setMetadata("other2", T1);
2222   EXPECT_EQ(T2, F->getMetadata("other1"));
2223   EXPECT_EQ(T1, F->getMetadata("other2"));
2224 
2225   F->setMetadata("other1", nullptr);
2226   F->setMetadata("other2", nullptr);
2227   EXPECT_FALSE(F->hasMetadata());
2228   EXPECT_EQ(nullptr, F->getMetadata("other1"));
2229   EXPECT_EQ(nullptr, F->getMetadata("other2"));
2230 }
2231 
2232 TEST_F(FunctionAttachmentTest, getAll) {
2233   Function *F = getFunction("foo");
2234 
2235   MDTuple *T1 = getTuple();
2236   MDTuple *T2 = getTuple();
2237   MDTuple *P = getTuple();
2238   DISubprogram *SP = getSubprogram();
2239 
2240   F->setMetadata("other1", T2);
2241   F->setMetadata(LLVMContext::MD_dbg, SP);
2242   F->setMetadata("other2", T1);
2243   F->setMetadata(LLVMContext::MD_prof, P);
2244   F->setMetadata("other2", T2);
2245   F->setMetadata("other1", T1);
2246 
2247   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
2248   F->getAllMetadata(MDs);
2249   ASSERT_EQ(4u, MDs.size());
2250   EXPECT_EQ(LLVMContext::MD_dbg, MDs[0].first);
2251   EXPECT_EQ(LLVMContext::MD_prof, MDs[1].first);
2252   EXPECT_EQ(Context.getMDKindID("other1"), MDs[2].first);
2253   EXPECT_EQ(Context.getMDKindID("other2"), MDs[3].first);
2254   EXPECT_EQ(SP, MDs[0].second);
2255   EXPECT_EQ(P, MDs[1].second);
2256   EXPECT_EQ(T1, MDs[2].second);
2257   EXPECT_EQ(T2, MDs[3].second);
2258 }
2259 
2260 TEST_F(FunctionAttachmentTest, Verifier) {
2261   Function *F = getFunction("foo");
2262   F->setMetadata("attach", getTuple());
2263 
2264   // Confirm this has no body.
2265   ASSERT_TRUE(F->empty());
2266 
2267   // Functions without a body cannot have metadata attachments (they also can't
2268   // be verified directly, so check that the module fails to verify).
2269   EXPECT_TRUE(verifyModule(*F->getParent()));
2270 
2271   // Nor can materializable functions.
2272   F->setIsMaterializable(true);
2273   EXPECT_TRUE(verifyModule(*F->getParent()));
2274 
2275   // Functions with a body can.
2276   F->setIsMaterializable(false);
2277   (void)new UnreachableInst(Context, BasicBlock::Create(Context, "bb", F));
2278   EXPECT_FALSE(verifyModule(*F->getParent()));
2279   EXPECT_FALSE(verifyFunction(*F));
2280 }
2281 
2282 TEST_F(FunctionAttachmentTest, EntryCount) {
2283   Function *F = getFunction("foo");
2284   EXPECT_FALSE(F->getEntryCount().hasValue());
2285   F->setEntryCount(12304);
2286   EXPECT_TRUE(F->getEntryCount().hasValue());
2287   EXPECT_EQ(12304u, *F->getEntryCount());
2288 }
2289 
2290 TEST_F(FunctionAttachmentTest, SubprogramAttachment) {
2291   Function *F = getFunction("foo");
2292   DISubprogram *SP = getSubprogram();
2293   F->setSubprogram(SP);
2294 
2295   // Note that the static_cast confirms that F->getSubprogram() actually
2296   // returns an DISubprogram.
2297   EXPECT_EQ(SP, static_cast<DISubprogram *>(F->getSubprogram()));
2298   EXPECT_EQ(SP, F->getMetadata("dbg"));
2299   EXPECT_EQ(SP, F->getMetadata(LLVMContext::MD_dbg));
2300 }
2301 
2302 typedef MetadataTest DistinctMDOperandPlaceholderTest;
2303 TEST_F(DistinctMDOperandPlaceholderTest, getID) {
2304   EXPECT_EQ(7u, DistinctMDOperandPlaceholder(7).getID());
2305 }
2306 
2307 TEST_F(DistinctMDOperandPlaceholderTest, replaceUseWith) {
2308   // Set up some placeholders.
2309   DistinctMDOperandPlaceholder PH0(7);
2310   DistinctMDOperandPlaceholder PH1(3);
2311   DistinctMDOperandPlaceholder PH2(0);
2312   Metadata *Ops[] = {&PH0, &PH1, &PH2};
2313   auto *D = MDTuple::getDistinct(Context, Ops);
2314   ASSERT_EQ(&PH0, D->getOperand(0));
2315   ASSERT_EQ(&PH1, D->getOperand(1));
2316   ASSERT_EQ(&PH2, D->getOperand(2));
2317 
2318   // Replace them.
2319   auto *N0 = MDTuple::get(Context, None);
2320   auto *N1 = MDTuple::get(Context, N0);
2321   PH0.replaceUseWith(N0);
2322   PH1.replaceUseWith(N1);
2323   PH2.replaceUseWith(nullptr);
2324   EXPECT_EQ(N0, D->getOperand(0));
2325   EXPECT_EQ(N1, D->getOperand(1));
2326   EXPECT_EQ(nullptr, D->getOperand(2));
2327 }
2328 
2329 TEST_F(DistinctMDOperandPlaceholderTest, replaceUseWithNoUser) {
2330   // There is no user, but we can still call replace.
2331   DistinctMDOperandPlaceholder(7).replaceUseWith(MDTuple::get(Context, None));
2332 }
2333 
2334 #ifndef NDEBUG
2335 #ifdef GTEST_HAS_DEATH_TEST
2336 TEST_F(DistinctMDOperandPlaceholderTest, MetadataAsValue) {
2337   // This shouldn't crash.
2338   DistinctMDOperandPlaceholder PH(7);
2339   EXPECT_DEATH(MetadataAsValue::get(Context, &PH),
2340                "Unexpected callback to owner");
2341 }
2342 
2343 TEST_F(DistinctMDOperandPlaceholderTest, UniquedMDNode) {
2344   // This shouldn't crash.
2345   DistinctMDOperandPlaceholder PH(7);
2346   EXPECT_DEATH(MDTuple::get(Context, &PH), "Unexpected callback to owner");
2347 }
2348 
2349 TEST_F(DistinctMDOperandPlaceholderTest, SecondDistinctMDNode) {
2350   // This shouldn't crash.
2351   DistinctMDOperandPlaceholder PH(7);
2352   MDTuple::getDistinct(Context, &PH);
2353   EXPECT_DEATH(MDTuple::getDistinct(Context, &PH),
2354                "Placeholders can only be used once");
2355 }
2356 
2357 TEST_F(DistinctMDOperandPlaceholderTest, TrackingMDRefAndDistinctMDNode) {
2358   // TrackingMDRef doesn't install an owner callback, so it can't be detected
2359   // as an invalid use.  However, using a placeholder in a TrackingMDRef *and*
2360   // a distinct node isn't possible and we should assert.
2361   //
2362   // (There's no positive test for using TrackingMDRef because it's not a
2363   // useful thing to do.)
2364   {
2365     DistinctMDOperandPlaceholder PH(7);
2366     MDTuple::getDistinct(Context, &PH);
2367     EXPECT_DEATH(TrackingMDRef Ref(&PH), "Placeholders can only be used once");
2368   }
2369   {
2370     DistinctMDOperandPlaceholder PH(7);
2371     TrackingMDRef Ref(&PH);
2372     EXPECT_DEATH(MDTuple::getDistinct(Context, &PH),
2373                  "Placeholders can only be used once");
2374   }
2375 }
2376 #endif
2377 #endif
2378 
2379 } // end namespace
2380