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