1 //===- ASTStructuralEquivalence.cpp ---------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implement StructuralEquivalenceContext class and helper functions
10 //  for layout matching.
11 //
12 // The structural equivalence check could have been implemented as a parallel
13 // BFS on a pair of graphs.  That must have been the original approach at the
14 // beginning.
15 // Let's consider this simple BFS algorithm from the `s` source:
16 // ```
17 // void bfs(Graph G, int s)
18 // {
19 //   Queue<Integer> queue = new Queue<Integer>();
20 //   marked[s] = true; // Mark the source
21 //   queue.enqueue(s); // and put it on the queue.
22 //   while (!q.isEmpty()) {
23 //     int v = queue.dequeue(); // Remove next vertex from the queue.
24 //     for (int w : G.adj(v))
25 //       if (!marked[w]) // For every unmarked adjacent vertex,
26 //       {
27 //         marked[w] = true;
28 //         queue.enqueue(w);
29 //       }
30 //   }
31 // }
32 // ```
33 // Indeed, it has it's queue, which holds pairs of nodes, one from each graph,
34 // this is the `DeclsToCheck` member. `VisitedDecls` plays the role of the
35 // marking (`marked`) functionality above, we use it to check whether we've
36 // already seen a pair of nodes.
37 //
38 // We put in the elements into the queue only in the toplevel decl check
39 // function:
40 // ```
41 // static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
42 //                                      Decl *D1, Decl *D2);
43 // ```
44 // The `while` loop where we iterate over the children is implemented in
45 // `Finish()`.  And `Finish` is called only from the two **member** functions
46 // which check the equivalency of two Decls or two Types. ASTImporter (and
47 // other clients) call only these functions.
48 //
49 // The `static` implementation functions are called from `Finish`, these push
50 // the children nodes to the queue via `static bool
51 // IsStructurallyEquivalent(StructuralEquivalenceContext &Context, Decl *D1,
52 // Decl *D2)`.  So far so good, this is almost like the BFS.  However, if we
53 // let a static implementation function to call `Finish` via another **member**
54 // function that means we end up with two nested while loops each of them
55 // working on the same queue. This is wrong and nobody can reason about it's
56 // doing. Thus, static implementation functions must not call the **member**
57 // functions.
58 //
59 //===----------------------------------------------------------------------===//
60 
61 #include "clang/AST/ASTStructuralEquivalence.h"
62 #include "clang/AST/ASTContext.h"
63 #include "clang/AST/ASTDiagnostic.h"
64 #include "clang/AST/Decl.h"
65 #include "clang/AST/DeclBase.h"
66 #include "clang/AST/DeclCXX.h"
67 #include "clang/AST/DeclFriend.h"
68 #include "clang/AST/DeclObjC.h"
69 #include "clang/AST/DeclOpenMP.h"
70 #include "clang/AST/DeclTemplate.h"
71 #include "clang/AST/ExprCXX.h"
72 #include "clang/AST/ExprConcepts.h"
73 #include "clang/AST/ExprObjC.h"
74 #include "clang/AST/ExprOpenMP.h"
75 #include "clang/AST/NestedNameSpecifier.h"
76 #include "clang/AST/StmtObjC.h"
77 #include "clang/AST/StmtOpenMP.h"
78 #include "clang/AST/TemplateBase.h"
79 #include "clang/AST/TemplateName.h"
80 #include "clang/AST/Type.h"
81 #include "clang/Basic/ExceptionSpecificationType.h"
82 #include "clang/Basic/IdentifierTable.h"
83 #include "clang/Basic/LLVM.h"
84 #include "clang/Basic/SourceLocation.h"
85 #include "llvm/ADT/APInt.h"
86 #include "llvm/ADT/APSInt.h"
87 #include "llvm/ADT/None.h"
88 #include "llvm/ADT/Optional.h"
89 #include "llvm/Support/Casting.h"
90 #include "llvm/Support/Compiler.h"
91 #include "llvm/Support/ErrorHandling.h"
92 #include <cassert>
93 #include <utility>
94 
95 using namespace clang;
96 
97 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
98                                      QualType T1, QualType T2);
99 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
100                                      Decl *D1, Decl *D2);
101 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
102                                      const TemplateArgument &Arg1,
103                                      const TemplateArgument &Arg2);
104 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
105                                      NestedNameSpecifier *NNS1,
106                                      NestedNameSpecifier *NNS2);
107 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1,
108                                      const IdentifierInfo *Name2);
109 
110 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
111                                      const DeclarationName Name1,
112                                      const DeclarationName Name2) {
113   if (Name1.getNameKind() != Name2.getNameKind())
114     return false;
115 
116   switch (Name1.getNameKind()) {
117 
118   case DeclarationName::Identifier:
119     return IsStructurallyEquivalent(Name1.getAsIdentifierInfo(),
120                                     Name2.getAsIdentifierInfo());
121 
122   case DeclarationName::CXXConstructorName:
123   case DeclarationName::CXXDestructorName:
124   case DeclarationName::CXXConversionFunctionName:
125     return IsStructurallyEquivalent(Context, Name1.getCXXNameType(),
126                                     Name2.getCXXNameType());
127 
128   case DeclarationName::CXXDeductionGuideName: {
129     if (!IsStructurallyEquivalent(
130             Context, Name1.getCXXDeductionGuideTemplate()->getDeclName(),
131             Name2.getCXXDeductionGuideTemplate()->getDeclName()))
132       return false;
133     return IsStructurallyEquivalent(Context,
134                                     Name1.getCXXDeductionGuideTemplate(),
135                                     Name2.getCXXDeductionGuideTemplate());
136   }
137 
138   case DeclarationName::CXXOperatorName:
139     return Name1.getCXXOverloadedOperator() == Name2.getCXXOverloadedOperator();
140 
141   case DeclarationName::CXXLiteralOperatorName:
142     return IsStructurallyEquivalent(Name1.getCXXLiteralIdentifier(),
143                                     Name2.getCXXLiteralIdentifier());
144 
145   case DeclarationName::CXXUsingDirective:
146     return true; // FIXME When do we consider two using directives equal?
147 
148   case DeclarationName::ObjCZeroArgSelector:
149   case DeclarationName::ObjCOneArgSelector:
150   case DeclarationName::ObjCMultiArgSelector:
151     return true; // FIXME
152   }
153 
154   llvm_unreachable("Unhandled kind of DeclarationName");
155   return true;
156 }
157 
158 namespace {
159 /// Encapsulates Stmt comparison logic.
160 class StmtComparer {
161   StructuralEquivalenceContext &Context;
162 
163   // IsStmtEquivalent overloads. Each overload compares a specific statement
164   // and only has to compare the data that is specific to the specific statement
165   // class. Should only be called from TraverseStmt.
166 
167   bool IsStmtEquivalent(const AddrLabelExpr *E1, const AddrLabelExpr *E2) {
168     return IsStructurallyEquivalent(Context, E1->getLabel(), E2->getLabel());
169   }
170 
171   bool IsStmtEquivalent(const AtomicExpr *E1, const AtomicExpr *E2) {
172     return E1->getOp() == E2->getOp();
173   }
174 
175   bool IsStmtEquivalent(const BinaryOperator *E1, const BinaryOperator *E2) {
176     return E1->getOpcode() == E2->getOpcode();
177   }
178 
179   bool IsStmtEquivalent(const CallExpr *E1, const CallExpr *E2) {
180     // FIXME: IsStructurallyEquivalent requires non-const Decls.
181     Decl *Callee1 = const_cast<Decl *>(E1->getCalleeDecl());
182     Decl *Callee2 = const_cast<Decl *>(E2->getCalleeDecl());
183 
184     // Compare whether both calls know their callee.
185     if (static_cast<bool>(Callee1) != static_cast<bool>(Callee2))
186       return false;
187 
188     // Both calls have no callee, so nothing to do.
189     if (!static_cast<bool>(Callee1))
190       return true;
191 
192     assert(Callee2);
193     return IsStructurallyEquivalent(Context, Callee1, Callee2);
194   }
195 
196   bool IsStmtEquivalent(const CharacterLiteral *E1,
197                         const CharacterLiteral *E2) {
198     return E1->getValue() == E2->getValue() && E1->getKind() == E2->getKind();
199   }
200 
201   bool IsStmtEquivalent(const ChooseExpr *E1, const ChooseExpr *E2) {
202     return true; // Semantics only depend on children.
203   }
204 
205   bool IsStmtEquivalent(const CompoundStmt *E1, const CompoundStmt *E2) {
206     // Number of children is actually checked by the generic children comparison
207     // code, but a CompoundStmt is one of the few statements where the number of
208     // children frequently differs and the number of statements is also always
209     // precomputed. Directly comparing the number of children here is thus
210     // just an optimization.
211     return E1->size() == E2->size();
212   }
213 
214   bool IsStmtEquivalent(const DependentScopeDeclRefExpr *DE1,
215                         const DependentScopeDeclRefExpr *DE2) {
216     if (!IsStructurallyEquivalent(Context, DE1->getDeclName(),
217                                   DE2->getDeclName()))
218       return false;
219     return IsStructurallyEquivalent(Context, DE1->getQualifier(),
220                                     DE2->getQualifier());
221   }
222 
223   bool IsStmtEquivalent(const Expr *E1, const Expr *E2) {
224     return IsStructurallyEquivalent(Context, E1->getType(), E2->getType());
225   }
226 
227   bool IsStmtEquivalent(const ExpressionTraitExpr *E1,
228                         const ExpressionTraitExpr *E2) {
229     return E1->getTrait() == E2->getTrait() && E1->getValue() == E2->getValue();
230   }
231 
232   bool IsStmtEquivalent(const FloatingLiteral *E1, const FloatingLiteral *E2) {
233     return E1->isExact() == E2->isExact() && E1->getValue() == E2->getValue();
234   }
235 
236   bool IsStmtEquivalent(const ImplicitCastExpr *CastE1,
237                         const ImplicitCastExpr *CastE2) {
238     return IsStructurallyEquivalent(Context, CastE1->getType(),
239                                     CastE2->getType());
240   }
241 
242   bool IsStmtEquivalent(const IntegerLiteral *E1, const IntegerLiteral *E2) {
243     return E1->getValue() == E2->getValue();
244   }
245 
246   bool IsStmtEquivalent(const MemberExpr *E1, const MemberExpr *E2) {
247     return IsStructurallyEquivalent(Context, E1->getFoundDecl(),
248                                     E2->getFoundDecl());
249   }
250 
251   bool IsStmtEquivalent(const ObjCStringLiteral *E1,
252                         const ObjCStringLiteral *E2) {
253     // Just wraps a StringLiteral child.
254     return true;
255   }
256 
257   bool IsStmtEquivalent(const Stmt *S1, const Stmt *S2) { return true; }
258 
259   bool IsStmtEquivalent(const SourceLocExpr *E1, const SourceLocExpr *E2) {
260     return E1->getIdentKind() == E2->getIdentKind();
261   }
262 
263   bool IsStmtEquivalent(const StmtExpr *E1, const StmtExpr *E2) {
264     return E1->getTemplateDepth() == E2->getTemplateDepth();
265   }
266 
267   bool IsStmtEquivalent(const StringLiteral *E1, const StringLiteral *E2) {
268     return E1->getBytes() == E2->getBytes();
269   }
270 
271   bool IsStmtEquivalent(const SubstNonTypeTemplateParmExpr *E1,
272                         const SubstNonTypeTemplateParmExpr *E2) {
273     return IsStructurallyEquivalent(Context, E1->getParameter(),
274                                     E2->getParameter());
275   }
276 
277   bool IsStmtEquivalent(const SubstNonTypeTemplateParmPackExpr *E1,
278                         const SubstNonTypeTemplateParmPackExpr *E2) {
279     return IsStructurallyEquivalent(Context, E1->getArgumentPack(),
280                                     E2->getArgumentPack());
281   }
282 
283   bool IsStmtEquivalent(const TypeTraitExpr *E1, const TypeTraitExpr *E2) {
284     if (E1->getTrait() != E2->getTrait())
285       return false;
286 
287     for (auto Pair : zip_longest(E1->getArgs(), E2->getArgs())) {
288       Optional<TypeSourceInfo *> Child1 = std::get<0>(Pair);
289       Optional<TypeSourceInfo *> Child2 = std::get<1>(Pair);
290       // Different number of args.
291       if (!Child1 || !Child2)
292         return false;
293 
294       if (!IsStructurallyEquivalent(Context, (*Child1)->getType(),
295                                     (*Child2)->getType()))
296         return false;
297     }
298     return true;
299   }
300 
301   bool IsStmtEquivalent(const UnaryExprOrTypeTraitExpr *E1,
302                         const UnaryExprOrTypeTraitExpr *E2) {
303     if (E1->getKind() != E2->getKind())
304       return false;
305     return IsStructurallyEquivalent(Context, E1->getTypeOfArgument(),
306                                     E2->getTypeOfArgument());
307   }
308 
309   bool IsStmtEquivalent(const UnaryOperator *E1, const UnaryOperator *E2) {
310     return E1->getOpcode() == E2->getOpcode();
311   }
312 
313   bool IsStmtEquivalent(const VAArgExpr *E1, const VAArgExpr *E2) {
314     // Semantics only depend on children.
315     return true;
316   }
317 
318   /// End point of the traversal chain.
319   bool TraverseStmt(const Stmt *S1, const Stmt *S2) { return true; }
320 
321   // Create traversal methods that traverse the class hierarchy and return
322   // the accumulated result of the comparison. Each TraverseStmt overload
323   // calls the TraverseStmt overload of the parent class. For example,
324   // the TraverseStmt overload for 'BinaryOperator' calls the TraverseStmt
325   // overload of 'Expr' which then calls the overload for 'Stmt'.
326 #define STMT(CLASS, PARENT)                                                    \
327   bool TraverseStmt(const CLASS *S1, const CLASS *S2) {                        \
328     if (!TraverseStmt(static_cast<const PARENT *>(S1),                         \
329                       static_cast<const PARENT *>(S2)))                        \
330       return false;                                                            \
331     return IsStmtEquivalent(S1, S2);                                           \
332   }
333 #include "clang/AST/StmtNodes.inc"
334 
335 public:
336   StmtComparer(StructuralEquivalenceContext &C) : Context(C) {}
337 
338   /// Determine whether two statements are equivalent. The statements have to
339   /// be of the same kind. The children of the statements and their properties
340   /// are not compared by this function.
341   bool IsEquivalent(const Stmt *S1, const Stmt *S2) {
342     if (S1->getStmtClass() != S2->getStmtClass())
343       return false;
344 
345     // Each TraverseStmt walks the class hierarchy from the leaf class to
346     // the root class 'Stmt' (e.g. 'BinaryOperator' -> 'Expr' -> 'Stmt'). Cast
347     // the Stmt we have here to its specific subclass so that we call the
348     // overload that walks the whole class hierarchy from leaf to root (e.g.,
349     // cast to 'BinaryOperator' so that 'Expr' and 'Stmt' is traversed).
350     switch (S1->getStmtClass()) {
351     case Stmt::NoStmtClass:
352       llvm_unreachable("Can't traverse NoStmtClass");
353 #define STMT(CLASS, PARENT)                                                    \
354   case Stmt::StmtClass::CLASS##Class:                                          \
355     return TraverseStmt(static_cast<const CLASS *>(S1),                        \
356                         static_cast<const CLASS *>(S2));
357 #define ABSTRACT_STMT(S)
358 #include "clang/AST/StmtNodes.inc"
359     }
360     llvm_unreachable("Invalid statement kind");
361   }
362 };
363 } // namespace
364 
365 /// Determine structural equivalence of two statements.
366 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
367                                      const Stmt *S1, const Stmt *S2) {
368   if (!S1 || !S2)
369     return S1 == S2;
370 
371   // Compare the statements itself.
372   StmtComparer Comparer(Context);
373   if (!Comparer.IsEquivalent(S1, S2))
374     return false;
375 
376   // Iterate over the children of both statements and also compare them.
377   for (auto Pair : zip_longest(S1->children(), S2->children())) {
378     Optional<const Stmt *> Child1 = std::get<0>(Pair);
379     Optional<const Stmt *> Child2 = std::get<1>(Pair);
380     // One of the statements has a different amount of children than the other,
381     // so the statements can't be equivalent.
382     if (!Child1 || !Child2)
383       return false;
384     if (!IsStructurallyEquivalent(Context, *Child1, *Child2))
385       return false;
386   }
387   return true;
388 }
389 
390 /// Determine whether two identifiers are equivalent.
391 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1,
392                                      const IdentifierInfo *Name2) {
393   if (!Name1 || !Name2)
394     return Name1 == Name2;
395 
396   return Name1->getName() == Name2->getName();
397 }
398 
399 /// Determine whether two nested-name-specifiers are equivalent.
400 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
401                                      NestedNameSpecifier *NNS1,
402                                      NestedNameSpecifier *NNS2) {
403   if (NNS1->getKind() != NNS2->getKind())
404     return false;
405 
406   NestedNameSpecifier *Prefix1 = NNS1->getPrefix(),
407                       *Prefix2 = NNS2->getPrefix();
408   if ((bool)Prefix1 != (bool)Prefix2)
409     return false;
410 
411   if (Prefix1)
412     if (!IsStructurallyEquivalent(Context, Prefix1, Prefix2))
413       return false;
414 
415   switch (NNS1->getKind()) {
416   case NestedNameSpecifier::Identifier:
417     return IsStructurallyEquivalent(NNS1->getAsIdentifier(),
418                                     NNS2->getAsIdentifier());
419   case NestedNameSpecifier::Namespace:
420     return IsStructurallyEquivalent(Context, NNS1->getAsNamespace(),
421                                     NNS2->getAsNamespace());
422   case NestedNameSpecifier::NamespaceAlias:
423     return IsStructurallyEquivalent(Context, NNS1->getAsNamespaceAlias(),
424                                     NNS2->getAsNamespaceAlias());
425   case NestedNameSpecifier::TypeSpec:
426   case NestedNameSpecifier::TypeSpecWithTemplate:
427     return IsStructurallyEquivalent(Context, QualType(NNS1->getAsType(), 0),
428                                     QualType(NNS2->getAsType(), 0));
429   case NestedNameSpecifier::Global:
430     return true;
431   case NestedNameSpecifier::Super:
432     return IsStructurallyEquivalent(Context, NNS1->getAsRecordDecl(),
433                                     NNS2->getAsRecordDecl());
434   }
435   return false;
436 }
437 
438 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
439                                      const TemplateName &N1,
440                                      const TemplateName &N2) {
441   TemplateDecl *TemplateDeclN1 = N1.getAsTemplateDecl();
442   TemplateDecl *TemplateDeclN2 = N2.getAsTemplateDecl();
443   if (TemplateDeclN1 && TemplateDeclN2) {
444     if (!IsStructurallyEquivalent(Context, TemplateDeclN1, TemplateDeclN2))
445       return false;
446     // If the kind is different we compare only the template decl.
447     if (N1.getKind() != N2.getKind())
448       return true;
449   } else if (TemplateDeclN1 || TemplateDeclN2)
450     return false;
451   else if (N1.getKind() != N2.getKind())
452     return false;
453 
454   // Check for special case incompatibilities.
455   switch (N1.getKind()) {
456 
457   case TemplateName::OverloadedTemplate: {
458     OverloadedTemplateStorage *OS1 = N1.getAsOverloadedTemplate(),
459                               *OS2 = N2.getAsOverloadedTemplate();
460     OverloadedTemplateStorage::iterator I1 = OS1->begin(), I2 = OS2->begin(),
461                                         E1 = OS1->end(), E2 = OS2->end();
462     for (; I1 != E1 && I2 != E2; ++I1, ++I2)
463       if (!IsStructurallyEquivalent(Context, *I1, *I2))
464         return false;
465     return I1 == E1 && I2 == E2;
466   }
467 
468   case TemplateName::AssumedTemplate: {
469     AssumedTemplateStorage *TN1 = N1.getAsAssumedTemplateName(),
470                            *TN2 = N1.getAsAssumedTemplateName();
471     return TN1->getDeclName() == TN2->getDeclName();
472   }
473 
474   case TemplateName::DependentTemplate: {
475     DependentTemplateName *DN1 = N1.getAsDependentTemplateName(),
476                           *DN2 = N2.getAsDependentTemplateName();
477     if (!IsStructurallyEquivalent(Context, DN1->getQualifier(),
478                                   DN2->getQualifier()))
479       return false;
480     if (DN1->isIdentifier() && DN2->isIdentifier())
481       return IsStructurallyEquivalent(DN1->getIdentifier(),
482                                       DN2->getIdentifier());
483     else if (DN1->isOverloadedOperator() && DN2->isOverloadedOperator())
484       return DN1->getOperator() == DN2->getOperator();
485     return false;
486   }
487 
488   case TemplateName::SubstTemplateTemplateParmPack: {
489     SubstTemplateTemplateParmPackStorage
490         *P1 = N1.getAsSubstTemplateTemplateParmPack(),
491         *P2 = N2.getAsSubstTemplateTemplateParmPack();
492     return IsStructurallyEquivalent(Context, P1->getArgumentPack(),
493                                     P2->getArgumentPack()) &&
494            IsStructurallyEquivalent(Context, P1->getParameterPack(),
495                                     P2->getParameterPack());
496   }
497 
498    case TemplateName::Template:
499    case TemplateName::QualifiedTemplate:
500    case TemplateName::SubstTemplateTemplateParm:
501      // It is sufficient to check value of getAsTemplateDecl.
502      break;
503 
504   }
505 
506   return true;
507 }
508 
509 /// Determine whether two template arguments are equivalent.
510 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
511                                      const TemplateArgument &Arg1,
512                                      const TemplateArgument &Arg2) {
513   if (Arg1.getKind() != Arg2.getKind())
514     return false;
515 
516   switch (Arg1.getKind()) {
517   case TemplateArgument::Null:
518     return true;
519 
520   case TemplateArgument::Type:
521     return IsStructurallyEquivalent(Context, Arg1.getAsType(), Arg2.getAsType());
522 
523   case TemplateArgument::Integral:
524     if (!IsStructurallyEquivalent(Context, Arg1.getIntegralType(),
525                                           Arg2.getIntegralType()))
526       return false;
527 
528     return llvm::APSInt::isSameValue(Arg1.getAsIntegral(),
529                                      Arg2.getAsIntegral());
530 
531   case TemplateArgument::Declaration:
532     return IsStructurallyEquivalent(Context, Arg1.getAsDecl(), Arg2.getAsDecl());
533 
534   case TemplateArgument::NullPtr:
535     return true; // FIXME: Is this correct?
536 
537   case TemplateArgument::Template:
538     return IsStructurallyEquivalent(Context, Arg1.getAsTemplate(),
539                                     Arg2.getAsTemplate());
540 
541   case TemplateArgument::TemplateExpansion:
542     return IsStructurallyEquivalent(Context,
543                                     Arg1.getAsTemplateOrTemplatePattern(),
544                                     Arg2.getAsTemplateOrTemplatePattern());
545 
546   case TemplateArgument::Expression:
547     return IsStructurallyEquivalent(Context, Arg1.getAsExpr(),
548                                     Arg2.getAsExpr());
549 
550   case TemplateArgument::Pack:
551     if (Arg1.pack_size() != Arg2.pack_size())
552       return false;
553 
554     for (unsigned I = 0, N = Arg1.pack_size(); I != N; ++I)
555       if (!IsStructurallyEquivalent(Context, Arg1.pack_begin()[I],
556                                     Arg2.pack_begin()[I]))
557         return false;
558 
559     return true;
560   }
561 
562   llvm_unreachable("Invalid template argument kind");
563 }
564 
565 /// Determine structural equivalence for the common part of array
566 /// types.
567 static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context,
568                                           const ArrayType *Array1,
569                                           const ArrayType *Array2) {
570   if (!IsStructurallyEquivalent(Context, Array1->getElementType(),
571                                 Array2->getElementType()))
572     return false;
573   if (Array1->getSizeModifier() != Array2->getSizeModifier())
574     return false;
575   if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers())
576     return false;
577 
578   return true;
579 }
580 
581 /// Determine structural equivalence based on the ExtInfo of functions. This
582 /// is inspired by ASTContext::mergeFunctionTypes(), we compare calling
583 /// conventions bits but must not compare some other bits.
584 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
585                                      FunctionType::ExtInfo EI1,
586                                      FunctionType::ExtInfo EI2) {
587   // Compatible functions must have compatible calling conventions.
588   if (EI1.getCC() != EI2.getCC())
589     return false;
590 
591   // Regparm is part of the calling convention.
592   if (EI1.getHasRegParm() != EI2.getHasRegParm())
593     return false;
594   if (EI1.getRegParm() != EI2.getRegParm())
595     return false;
596 
597   if (EI1.getProducesResult() != EI2.getProducesResult())
598     return false;
599   if (EI1.getNoCallerSavedRegs() != EI2.getNoCallerSavedRegs())
600     return false;
601   if (EI1.getNoCfCheck() != EI2.getNoCfCheck())
602     return false;
603 
604   return true;
605 }
606 
607 /// Check the equivalence of exception specifications.
608 static bool IsEquivalentExceptionSpec(StructuralEquivalenceContext &Context,
609                                       const FunctionProtoType *Proto1,
610                                       const FunctionProtoType *Proto2) {
611 
612   auto Spec1 = Proto1->getExceptionSpecType();
613   auto Spec2 = Proto2->getExceptionSpecType();
614 
615   if (isUnresolvedExceptionSpec(Spec1) || isUnresolvedExceptionSpec(Spec2))
616     return true;
617 
618   if (Spec1 != Spec2)
619     return false;
620   if (Spec1 == EST_Dynamic) {
621     if (Proto1->getNumExceptions() != Proto2->getNumExceptions())
622       return false;
623     for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) {
624       if (!IsStructurallyEquivalent(Context, Proto1->getExceptionType(I),
625                                     Proto2->getExceptionType(I)))
626         return false;
627     }
628   } else if (isComputedNoexcept(Spec1)) {
629     if (!IsStructurallyEquivalent(Context, Proto1->getNoexceptExpr(),
630                                   Proto2->getNoexceptExpr()))
631       return false;
632   }
633 
634   return true;
635 }
636 
637 /// Determine structural equivalence of two types.
638 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
639                                      QualType T1, QualType T2) {
640   if (T1.isNull() || T2.isNull())
641     return T1.isNull() && T2.isNull();
642 
643   QualType OrigT1 = T1;
644   QualType OrigT2 = T2;
645 
646   if (!Context.StrictTypeSpelling) {
647     // We aren't being strict about token-to-token equivalence of types,
648     // so map down to the canonical type.
649     T1 = Context.FromCtx.getCanonicalType(T1);
650     T2 = Context.ToCtx.getCanonicalType(T2);
651   }
652 
653   if (T1.getQualifiers() != T2.getQualifiers())
654     return false;
655 
656   Type::TypeClass TC = T1->getTypeClass();
657 
658   if (T1->getTypeClass() != T2->getTypeClass()) {
659     // Compare function types with prototypes vs. without prototypes as if
660     // both did not have prototypes.
661     if (T1->getTypeClass() == Type::FunctionProto &&
662         T2->getTypeClass() == Type::FunctionNoProto)
663       TC = Type::FunctionNoProto;
664     else if (T1->getTypeClass() == Type::FunctionNoProto &&
665              T2->getTypeClass() == Type::FunctionProto)
666       TC = Type::FunctionNoProto;
667     else
668       return false;
669   }
670 
671   switch (TC) {
672   case Type::Builtin:
673     // FIXME: Deal with Char_S/Char_U.
674     if (cast<BuiltinType>(T1)->getKind() != cast<BuiltinType>(T2)->getKind())
675       return false;
676     break;
677 
678   case Type::Complex:
679     if (!IsStructurallyEquivalent(Context,
680                                   cast<ComplexType>(T1)->getElementType(),
681                                   cast<ComplexType>(T2)->getElementType()))
682       return false;
683     break;
684 
685   case Type::Adjusted:
686   case Type::Decayed:
687     if (!IsStructurallyEquivalent(Context,
688                                   cast<AdjustedType>(T1)->getOriginalType(),
689                                   cast<AdjustedType>(T2)->getOriginalType()))
690       return false;
691     break;
692 
693   case Type::Pointer:
694     if (!IsStructurallyEquivalent(Context,
695                                   cast<PointerType>(T1)->getPointeeType(),
696                                   cast<PointerType>(T2)->getPointeeType()))
697       return false;
698     break;
699 
700   case Type::BlockPointer:
701     if (!IsStructurallyEquivalent(Context,
702                                   cast<BlockPointerType>(T1)->getPointeeType(),
703                                   cast<BlockPointerType>(T2)->getPointeeType()))
704       return false;
705     break;
706 
707   case Type::LValueReference:
708   case Type::RValueReference: {
709     const auto *Ref1 = cast<ReferenceType>(T1);
710     const auto *Ref2 = cast<ReferenceType>(T2);
711     if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue())
712       return false;
713     if (Ref1->isInnerRef() != Ref2->isInnerRef())
714       return false;
715     if (!IsStructurallyEquivalent(Context, Ref1->getPointeeTypeAsWritten(),
716                                   Ref2->getPointeeTypeAsWritten()))
717       return false;
718     break;
719   }
720 
721   case Type::MemberPointer: {
722     const auto *MemPtr1 = cast<MemberPointerType>(T1);
723     const auto *MemPtr2 = cast<MemberPointerType>(T2);
724     if (!IsStructurallyEquivalent(Context, MemPtr1->getPointeeType(),
725                                   MemPtr2->getPointeeType()))
726       return false;
727     if (!IsStructurallyEquivalent(Context, QualType(MemPtr1->getClass(), 0),
728                                   QualType(MemPtr2->getClass(), 0)))
729       return false;
730     break;
731   }
732 
733   case Type::ConstantArray: {
734     const auto *Array1 = cast<ConstantArrayType>(T1);
735     const auto *Array2 = cast<ConstantArrayType>(T2);
736     if (!llvm::APInt::isSameValue(Array1->getSize(), Array2->getSize()))
737       return false;
738 
739     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
740       return false;
741     break;
742   }
743 
744   case Type::IncompleteArray:
745     if (!IsArrayStructurallyEquivalent(Context, cast<ArrayType>(T1),
746                                        cast<ArrayType>(T2)))
747       return false;
748     break;
749 
750   case Type::VariableArray: {
751     const auto *Array1 = cast<VariableArrayType>(T1);
752     const auto *Array2 = cast<VariableArrayType>(T2);
753     if (!IsStructurallyEquivalent(Context, Array1->getSizeExpr(),
754                                   Array2->getSizeExpr()))
755       return false;
756 
757     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
758       return false;
759 
760     break;
761   }
762 
763   case Type::DependentSizedArray: {
764     const auto *Array1 = cast<DependentSizedArrayType>(T1);
765     const auto *Array2 = cast<DependentSizedArrayType>(T2);
766     if (!IsStructurallyEquivalent(Context, Array1->getSizeExpr(),
767                                   Array2->getSizeExpr()))
768       return false;
769 
770     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
771       return false;
772 
773     break;
774   }
775 
776   case Type::DependentAddressSpace: {
777     const auto *DepAddressSpace1 = cast<DependentAddressSpaceType>(T1);
778     const auto *DepAddressSpace2 = cast<DependentAddressSpaceType>(T2);
779     if (!IsStructurallyEquivalent(Context, DepAddressSpace1->getAddrSpaceExpr(),
780                                   DepAddressSpace2->getAddrSpaceExpr()))
781       return false;
782     if (!IsStructurallyEquivalent(Context, DepAddressSpace1->getPointeeType(),
783                                   DepAddressSpace2->getPointeeType()))
784       return false;
785 
786     break;
787   }
788 
789   case Type::DependentSizedExtVector: {
790     const auto *Vec1 = cast<DependentSizedExtVectorType>(T1);
791     const auto *Vec2 = cast<DependentSizedExtVectorType>(T2);
792     if (!IsStructurallyEquivalent(Context, Vec1->getSizeExpr(),
793                                   Vec2->getSizeExpr()))
794       return false;
795     if (!IsStructurallyEquivalent(Context, Vec1->getElementType(),
796                                   Vec2->getElementType()))
797       return false;
798     break;
799   }
800 
801   case Type::DependentVector: {
802     const auto *Vec1 = cast<DependentVectorType>(T1);
803     const auto *Vec2 = cast<DependentVectorType>(T2);
804     if (Vec1->getVectorKind() != Vec2->getVectorKind())
805       return false;
806     if (!IsStructurallyEquivalent(Context, Vec1->getSizeExpr(),
807                                   Vec2->getSizeExpr()))
808       return false;
809     if (!IsStructurallyEquivalent(Context, Vec1->getElementType(),
810                                   Vec2->getElementType()))
811       return false;
812     break;
813   }
814 
815   case Type::Vector:
816   case Type::ExtVector: {
817     const auto *Vec1 = cast<VectorType>(T1);
818     const auto *Vec2 = cast<VectorType>(T2);
819     if (!IsStructurallyEquivalent(Context, Vec1->getElementType(),
820                                   Vec2->getElementType()))
821       return false;
822     if (Vec1->getNumElements() != Vec2->getNumElements())
823       return false;
824     if (Vec1->getVectorKind() != Vec2->getVectorKind())
825       return false;
826     break;
827   }
828 
829   case Type::DependentSizedMatrix: {
830     const DependentSizedMatrixType *Mat1 = cast<DependentSizedMatrixType>(T1);
831     const DependentSizedMatrixType *Mat2 = cast<DependentSizedMatrixType>(T2);
832     // The element types, row and column expressions must be structurally
833     // equivalent.
834     if (!IsStructurallyEquivalent(Context, Mat1->getRowExpr(),
835                                   Mat2->getRowExpr()) ||
836         !IsStructurallyEquivalent(Context, Mat1->getColumnExpr(),
837                                   Mat2->getColumnExpr()) ||
838         !IsStructurallyEquivalent(Context, Mat1->getElementType(),
839                                   Mat2->getElementType()))
840       return false;
841     break;
842   }
843 
844   case Type::ConstantMatrix: {
845     const ConstantMatrixType *Mat1 = cast<ConstantMatrixType>(T1);
846     const ConstantMatrixType *Mat2 = cast<ConstantMatrixType>(T2);
847     // The element types must be structurally equivalent and the number of rows
848     // and columns must match.
849     if (!IsStructurallyEquivalent(Context, Mat1->getElementType(),
850                                   Mat2->getElementType()) ||
851         Mat1->getNumRows() != Mat2->getNumRows() ||
852         Mat1->getNumColumns() != Mat2->getNumColumns())
853       return false;
854     break;
855   }
856 
857   case Type::FunctionProto: {
858     const auto *Proto1 = cast<FunctionProtoType>(T1);
859     const auto *Proto2 = cast<FunctionProtoType>(T2);
860 
861     if (Proto1->getNumParams() != Proto2->getNumParams())
862       return false;
863     for (unsigned I = 0, N = Proto1->getNumParams(); I != N; ++I) {
864       if (!IsStructurallyEquivalent(Context, Proto1->getParamType(I),
865                                     Proto2->getParamType(I)))
866         return false;
867     }
868     if (Proto1->isVariadic() != Proto2->isVariadic())
869       return false;
870 
871     if (Proto1->getMethodQuals() != Proto2->getMethodQuals())
872       return false;
873 
874     // Check exceptions, this information is lost in canonical type.
875     const auto *OrigProto1 =
876         cast<FunctionProtoType>(OrigT1.getDesugaredType(Context.FromCtx));
877     const auto *OrigProto2 =
878         cast<FunctionProtoType>(OrigT2.getDesugaredType(Context.ToCtx));
879     if (!IsEquivalentExceptionSpec(Context, OrigProto1, OrigProto2))
880       return false;
881 
882     // Fall through to check the bits common with FunctionNoProtoType.
883     LLVM_FALLTHROUGH;
884   }
885 
886   case Type::FunctionNoProto: {
887     const auto *Function1 = cast<FunctionType>(T1);
888     const auto *Function2 = cast<FunctionType>(T2);
889     if (!IsStructurallyEquivalent(Context, Function1->getReturnType(),
890                                   Function2->getReturnType()))
891       return false;
892     if (!IsStructurallyEquivalent(Context, Function1->getExtInfo(),
893                                   Function2->getExtInfo()))
894       return false;
895     break;
896   }
897 
898   case Type::UnresolvedUsing:
899     if (!IsStructurallyEquivalent(Context,
900                                   cast<UnresolvedUsingType>(T1)->getDecl(),
901                                   cast<UnresolvedUsingType>(T2)->getDecl()))
902       return false;
903     break;
904 
905   case Type::Attributed:
906     if (!IsStructurallyEquivalent(Context,
907                                   cast<AttributedType>(T1)->getModifiedType(),
908                                   cast<AttributedType>(T2)->getModifiedType()))
909       return false;
910     if (!IsStructurallyEquivalent(
911             Context, cast<AttributedType>(T1)->getEquivalentType(),
912             cast<AttributedType>(T2)->getEquivalentType()))
913       return false;
914     break;
915 
916   case Type::Paren:
917     if (!IsStructurallyEquivalent(Context, cast<ParenType>(T1)->getInnerType(),
918                                   cast<ParenType>(T2)->getInnerType()))
919       return false;
920     break;
921 
922   case Type::MacroQualified:
923     if (!IsStructurallyEquivalent(
924             Context, cast<MacroQualifiedType>(T1)->getUnderlyingType(),
925             cast<MacroQualifiedType>(T2)->getUnderlyingType()))
926       return false;
927     break;
928 
929   case Type::Typedef:
930     if (!IsStructurallyEquivalent(Context, cast<TypedefType>(T1)->getDecl(),
931                                   cast<TypedefType>(T2)->getDecl()))
932       return false;
933     break;
934 
935   case Type::TypeOfExpr:
936     if (!IsStructurallyEquivalent(
937             Context, cast<TypeOfExprType>(T1)->getUnderlyingExpr(),
938             cast<TypeOfExprType>(T2)->getUnderlyingExpr()))
939       return false;
940     break;
941 
942   case Type::TypeOf:
943     if (!IsStructurallyEquivalent(Context,
944                                   cast<TypeOfType>(T1)->getUnderlyingType(),
945                                   cast<TypeOfType>(T2)->getUnderlyingType()))
946       return false;
947     break;
948 
949   case Type::UnaryTransform:
950     if (!IsStructurallyEquivalent(
951             Context, cast<UnaryTransformType>(T1)->getUnderlyingType(),
952             cast<UnaryTransformType>(T2)->getUnderlyingType()))
953       return false;
954     break;
955 
956   case Type::Decltype:
957     if (!IsStructurallyEquivalent(Context,
958                                   cast<DecltypeType>(T1)->getUnderlyingExpr(),
959                                   cast<DecltypeType>(T2)->getUnderlyingExpr()))
960       return false;
961     break;
962 
963   case Type::Auto: {
964     auto *Auto1 = cast<AutoType>(T1);
965     auto *Auto2 = cast<AutoType>(T2);
966     if (!IsStructurallyEquivalent(Context, Auto1->getDeducedType(),
967                                   Auto2->getDeducedType()))
968       return false;
969     if (Auto1->isConstrained() != Auto2->isConstrained())
970       return false;
971     if (Auto1->isConstrained()) {
972       if (Auto1->getTypeConstraintConcept() !=
973           Auto2->getTypeConstraintConcept())
974         return false;
975       ArrayRef<TemplateArgument> Auto1Args =
976           Auto1->getTypeConstraintArguments();
977       ArrayRef<TemplateArgument> Auto2Args =
978           Auto2->getTypeConstraintArguments();
979       if (Auto1Args.size() != Auto2Args.size())
980         return false;
981       for (unsigned I = 0, N = Auto1Args.size(); I != N; ++I) {
982         if (!IsStructurallyEquivalent(Context, Auto1Args[I], Auto2Args[I]))
983           return false;
984       }
985     }
986     break;
987   }
988 
989   case Type::DeducedTemplateSpecialization: {
990     const auto *DT1 = cast<DeducedTemplateSpecializationType>(T1);
991     const auto *DT2 = cast<DeducedTemplateSpecializationType>(T2);
992     if (!IsStructurallyEquivalent(Context, DT1->getTemplateName(),
993                                   DT2->getTemplateName()))
994       return false;
995     if (!IsStructurallyEquivalent(Context, DT1->getDeducedType(),
996                                   DT2->getDeducedType()))
997       return false;
998     break;
999   }
1000 
1001   case Type::Record:
1002   case Type::Enum:
1003     if (!IsStructurallyEquivalent(Context, cast<TagType>(T1)->getDecl(),
1004                                   cast<TagType>(T2)->getDecl()))
1005       return false;
1006     break;
1007 
1008   case Type::TemplateTypeParm: {
1009     const auto *Parm1 = cast<TemplateTypeParmType>(T1);
1010     const auto *Parm2 = cast<TemplateTypeParmType>(T2);
1011     if (Parm1->getDepth() != Parm2->getDepth())
1012       return false;
1013     if (Parm1->getIndex() != Parm2->getIndex())
1014       return false;
1015     if (Parm1->isParameterPack() != Parm2->isParameterPack())
1016       return false;
1017 
1018     // Names of template type parameters are never significant.
1019     break;
1020   }
1021 
1022   case Type::SubstTemplateTypeParm: {
1023     const auto *Subst1 = cast<SubstTemplateTypeParmType>(T1);
1024     const auto *Subst2 = cast<SubstTemplateTypeParmType>(T2);
1025     if (!IsStructurallyEquivalent(Context,
1026                                   QualType(Subst1->getReplacedParameter(), 0),
1027                                   QualType(Subst2->getReplacedParameter(), 0)))
1028       return false;
1029     if (!IsStructurallyEquivalent(Context, Subst1->getReplacementType(),
1030                                   Subst2->getReplacementType()))
1031       return false;
1032     break;
1033   }
1034 
1035   case Type::SubstTemplateTypeParmPack: {
1036     const auto *Subst1 = cast<SubstTemplateTypeParmPackType>(T1);
1037     const auto *Subst2 = cast<SubstTemplateTypeParmPackType>(T2);
1038     if (!IsStructurallyEquivalent(Context,
1039                                   QualType(Subst1->getReplacedParameter(), 0),
1040                                   QualType(Subst2->getReplacedParameter(), 0)))
1041       return false;
1042     if (!IsStructurallyEquivalent(Context, Subst1->getArgumentPack(),
1043                                   Subst2->getArgumentPack()))
1044       return false;
1045     break;
1046   }
1047 
1048   case Type::TemplateSpecialization: {
1049     const auto *Spec1 = cast<TemplateSpecializationType>(T1);
1050     const auto *Spec2 = cast<TemplateSpecializationType>(T2);
1051     if (!IsStructurallyEquivalent(Context, Spec1->getTemplateName(),
1052                                   Spec2->getTemplateName()))
1053       return false;
1054     if (Spec1->getNumArgs() != Spec2->getNumArgs())
1055       return false;
1056     for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
1057       if (!IsStructurallyEquivalent(Context, Spec1->getArg(I),
1058                                     Spec2->getArg(I)))
1059         return false;
1060     }
1061     break;
1062   }
1063 
1064   case Type::Elaborated: {
1065     const auto *Elab1 = cast<ElaboratedType>(T1);
1066     const auto *Elab2 = cast<ElaboratedType>(T2);
1067     // CHECKME: what if a keyword is ETK_None or ETK_typename ?
1068     if (Elab1->getKeyword() != Elab2->getKeyword())
1069       return false;
1070     if (!IsStructurallyEquivalent(Context, Elab1->getQualifier(),
1071                                   Elab2->getQualifier()))
1072       return false;
1073     if (!IsStructurallyEquivalent(Context, Elab1->getNamedType(),
1074                                   Elab2->getNamedType()))
1075       return false;
1076     break;
1077   }
1078 
1079   case Type::InjectedClassName: {
1080     const auto *Inj1 = cast<InjectedClassNameType>(T1);
1081     const auto *Inj2 = cast<InjectedClassNameType>(T2);
1082     if (!IsStructurallyEquivalent(Context,
1083                                   Inj1->getInjectedSpecializationType(),
1084                                   Inj2->getInjectedSpecializationType()))
1085       return false;
1086     break;
1087   }
1088 
1089   case Type::DependentName: {
1090     const auto *Typename1 = cast<DependentNameType>(T1);
1091     const auto *Typename2 = cast<DependentNameType>(T2);
1092     if (!IsStructurallyEquivalent(Context, Typename1->getQualifier(),
1093                                   Typename2->getQualifier()))
1094       return false;
1095     if (!IsStructurallyEquivalent(Typename1->getIdentifier(),
1096                                   Typename2->getIdentifier()))
1097       return false;
1098 
1099     break;
1100   }
1101 
1102   case Type::DependentTemplateSpecialization: {
1103     const auto *Spec1 = cast<DependentTemplateSpecializationType>(T1);
1104     const auto *Spec2 = cast<DependentTemplateSpecializationType>(T2);
1105     if (!IsStructurallyEquivalent(Context, Spec1->getQualifier(),
1106                                   Spec2->getQualifier()))
1107       return false;
1108     if (!IsStructurallyEquivalent(Spec1->getIdentifier(),
1109                                   Spec2->getIdentifier()))
1110       return false;
1111     if (Spec1->getNumArgs() != Spec2->getNumArgs())
1112       return false;
1113     for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
1114       if (!IsStructurallyEquivalent(Context, Spec1->getArg(I),
1115                                     Spec2->getArg(I)))
1116         return false;
1117     }
1118     break;
1119   }
1120 
1121   case Type::PackExpansion:
1122     if (!IsStructurallyEquivalent(Context,
1123                                   cast<PackExpansionType>(T1)->getPattern(),
1124                                   cast<PackExpansionType>(T2)->getPattern()))
1125       return false;
1126     break;
1127 
1128   case Type::ObjCInterface: {
1129     const auto *Iface1 = cast<ObjCInterfaceType>(T1);
1130     const auto *Iface2 = cast<ObjCInterfaceType>(T2);
1131     if (!IsStructurallyEquivalent(Context, Iface1->getDecl(),
1132                                   Iface2->getDecl()))
1133       return false;
1134     break;
1135   }
1136 
1137   case Type::ObjCTypeParam: {
1138     const auto *Obj1 = cast<ObjCTypeParamType>(T1);
1139     const auto *Obj2 = cast<ObjCTypeParamType>(T2);
1140     if (!IsStructurallyEquivalent(Context, Obj1->getDecl(), Obj2->getDecl()))
1141       return false;
1142 
1143     if (Obj1->getNumProtocols() != Obj2->getNumProtocols())
1144       return false;
1145     for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) {
1146       if (!IsStructurallyEquivalent(Context, Obj1->getProtocol(I),
1147                                     Obj2->getProtocol(I)))
1148         return false;
1149     }
1150     break;
1151   }
1152 
1153   case Type::ObjCObject: {
1154     const auto *Obj1 = cast<ObjCObjectType>(T1);
1155     const auto *Obj2 = cast<ObjCObjectType>(T2);
1156     if (!IsStructurallyEquivalent(Context, Obj1->getBaseType(),
1157                                   Obj2->getBaseType()))
1158       return false;
1159     if (Obj1->getNumProtocols() != Obj2->getNumProtocols())
1160       return false;
1161     for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) {
1162       if (!IsStructurallyEquivalent(Context, Obj1->getProtocol(I),
1163                                     Obj2->getProtocol(I)))
1164         return false;
1165     }
1166     break;
1167   }
1168 
1169   case Type::ObjCObjectPointer: {
1170     const auto *Ptr1 = cast<ObjCObjectPointerType>(T1);
1171     const auto *Ptr2 = cast<ObjCObjectPointerType>(T2);
1172     if (!IsStructurallyEquivalent(Context, Ptr1->getPointeeType(),
1173                                   Ptr2->getPointeeType()))
1174       return false;
1175     break;
1176   }
1177 
1178   case Type::Atomic:
1179     if (!IsStructurallyEquivalent(Context, cast<AtomicType>(T1)->getValueType(),
1180                                   cast<AtomicType>(T2)->getValueType()))
1181       return false;
1182     break;
1183 
1184   case Type::Pipe:
1185     if (!IsStructurallyEquivalent(Context, cast<PipeType>(T1)->getElementType(),
1186                                   cast<PipeType>(T2)->getElementType()))
1187       return false;
1188     break;
1189   case Type::ExtInt: {
1190     const auto *Int1 = cast<ExtIntType>(T1);
1191     const auto *Int2 = cast<ExtIntType>(T2);
1192 
1193     if (Int1->isUnsigned() != Int2->isUnsigned() ||
1194         Int1->getNumBits() != Int2->getNumBits())
1195       return false;
1196     break;
1197   }
1198   case Type::DependentExtInt: {
1199     const auto *Int1 = cast<DependentExtIntType>(T1);
1200     const auto *Int2 = cast<DependentExtIntType>(T2);
1201 
1202     if (Int1->isUnsigned() != Int2->isUnsigned() ||
1203         !IsStructurallyEquivalent(Context, Int1->getNumBitsExpr(),
1204                                   Int2->getNumBitsExpr()))
1205       return false;
1206   }
1207   } // end switch
1208 
1209   return true;
1210 }
1211 
1212 /// Determine structural equivalence of two fields.
1213 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1214                                      FieldDecl *Field1, FieldDecl *Field2) {
1215   const auto *Owner2 = cast<RecordDecl>(Field2->getDeclContext());
1216 
1217   // For anonymous structs/unions, match up the anonymous struct/union type
1218   // declarations directly, so that we don't go off searching for anonymous
1219   // types
1220   if (Field1->isAnonymousStructOrUnion() &&
1221       Field2->isAnonymousStructOrUnion()) {
1222     RecordDecl *D1 = Field1->getType()->castAs<RecordType>()->getDecl();
1223     RecordDecl *D2 = Field2->getType()->castAs<RecordType>()->getDecl();
1224     return IsStructurallyEquivalent(Context, D1, D2);
1225   }
1226 
1227   // Check for equivalent field names.
1228   IdentifierInfo *Name1 = Field1->getIdentifier();
1229   IdentifierInfo *Name2 = Field2->getIdentifier();
1230   if (!::IsStructurallyEquivalent(Name1, Name2)) {
1231     if (Context.Complain) {
1232       Context.Diag2(
1233           Owner2->getLocation(),
1234           Context.getApplicableDiagnostic(diag::err_odr_tag_type_inconsistent))
1235           << Context.ToCtx.getTypeDeclType(Owner2);
1236       Context.Diag2(Field2->getLocation(), diag::note_odr_field_name)
1237           << Field2->getDeclName();
1238       Context.Diag1(Field1->getLocation(), diag::note_odr_field_name)
1239           << Field1->getDeclName();
1240     }
1241     return false;
1242   }
1243 
1244   if (!IsStructurallyEquivalent(Context, Field1->getType(),
1245                                 Field2->getType())) {
1246     if (Context.Complain) {
1247       Context.Diag2(
1248           Owner2->getLocation(),
1249           Context.getApplicableDiagnostic(diag::err_odr_tag_type_inconsistent))
1250           << Context.ToCtx.getTypeDeclType(Owner2);
1251       Context.Diag2(Field2->getLocation(), diag::note_odr_field)
1252           << Field2->getDeclName() << Field2->getType();
1253       Context.Diag1(Field1->getLocation(), diag::note_odr_field)
1254           << Field1->getDeclName() << Field1->getType();
1255     }
1256     return false;
1257   }
1258 
1259   if (Field1->isBitField() != Field2->isBitField()) {
1260     if (Context.Complain) {
1261       Context.Diag2(
1262           Owner2->getLocation(),
1263           Context.getApplicableDiagnostic(diag::err_odr_tag_type_inconsistent))
1264           << Context.ToCtx.getTypeDeclType(Owner2);
1265       if (Field1->isBitField()) {
1266         Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
1267             << Field1->getDeclName() << Field1->getType()
1268             << Field1->getBitWidthValue(Context.FromCtx);
1269         Context.Diag2(Field2->getLocation(), diag::note_odr_not_bit_field)
1270             << Field2->getDeclName();
1271       } else {
1272         Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
1273             << Field2->getDeclName() << Field2->getType()
1274             << Field2->getBitWidthValue(Context.ToCtx);
1275         Context.Diag1(Field1->getLocation(), diag::note_odr_not_bit_field)
1276             << Field1->getDeclName();
1277       }
1278     }
1279     return false;
1280   }
1281 
1282   if (Field1->isBitField()) {
1283     // Make sure that the bit-fields are the same length.
1284     unsigned Bits1 = Field1->getBitWidthValue(Context.FromCtx);
1285     unsigned Bits2 = Field2->getBitWidthValue(Context.ToCtx);
1286 
1287     if (Bits1 != Bits2) {
1288       if (Context.Complain) {
1289         Context.Diag2(Owner2->getLocation(),
1290                       Context.getApplicableDiagnostic(
1291                           diag::err_odr_tag_type_inconsistent))
1292             << Context.ToCtx.getTypeDeclType(Owner2);
1293         Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
1294             << Field2->getDeclName() << Field2->getType() << Bits2;
1295         Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
1296             << Field1->getDeclName() << Field1->getType() << Bits1;
1297       }
1298       return false;
1299     }
1300   }
1301 
1302   return true;
1303 }
1304 
1305 /// Determine structural equivalence of two methods.
1306 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1307                                      CXXMethodDecl *Method1,
1308                                      CXXMethodDecl *Method2) {
1309   bool PropertiesEqual =
1310       Method1->getDeclKind() == Method2->getDeclKind() &&
1311       Method1->getRefQualifier() == Method2->getRefQualifier() &&
1312       Method1->getAccess() == Method2->getAccess() &&
1313       Method1->getOverloadedOperator() == Method2->getOverloadedOperator() &&
1314       Method1->isStatic() == Method2->isStatic() &&
1315       Method1->isConst() == Method2->isConst() &&
1316       Method1->isVolatile() == Method2->isVolatile() &&
1317       Method1->isVirtual() == Method2->isVirtual() &&
1318       Method1->isPure() == Method2->isPure() &&
1319       Method1->isDefaulted() == Method2->isDefaulted() &&
1320       Method1->isDeleted() == Method2->isDeleted();
1321   if (!PropertiesEqual)
1322     return false;
1323   // FIXME: Check for 'final'.
1324 
1325   if (auto *Constructor1 = dyn_cast<CXXConstructorDecl>(Method1)) {
1326     auto *Constructor2 = cast<CXXConstructorDecl>(Method2);
1327     if (!Constructor1->getExplicitSpecifier().isEquivalent(
1328             Constructor2->getExplicitSpecifier()))
1329       return false;
1330   }
1331 
1332   if (auto *Conversion1 = dyn_cast<CXXConversionDecl>(Method1)) {
1333     auto *Conversion2 = cast<CXXConversionDecl>(Method2);
1334     if (!Conversion1->getExplicitSpecifier().isEquivalent(
1335             Conversion2->getExplicitSpecifier()))
1336       return false;
1337     if (!IsStructurallyEquivalent(Context, Conversion1->getConversionType(),
1338                                   Conversion2->getConversionType()))
1339       return false;
1340   }
1341 
1342   const IdentifierInfo *Name1 = Method1->getIdentifier();
1343   const IdentifierInfo *Name2 = Method2->getIdentifier();
1344   if (!::IsStructurallyEquivalent(Name1, Name2)) {
1345     return false;
1346     // TODO: Names do not match, add warning like at check for FieldDecl.
1347   }
1348 
1349   // Check the prototypes.
1350   if (!::IsStructurallyEquivalent(Context,
1351                                   Method1->getType(), Method2->getType()))
1352     return false;
1353 
1354   return true;
1355 }
1356 
1357 /// Determine structural equivalence of two lambda classes.
1358 static bool
1359 IsStructurallyEquivalentLambdas(StructuralEquivalenceContext &Context,
1360                                 CXXRecordDecl *D1, CXXRecordDecl *D2) {
1361   assert(D1->isLambda() && D2->isLambda() &&
1362          "Must be called on lambda classes");
1363   if (!IsStructurallyEquivalent(Context, D1->getLambdaCallOperator(),
1364                                 D2->getLambdaCallOperator()))
1365     return false;
1366 
1367   return true;
1368 }
1369 
1370 /// Determine structural equivalence of two records.
1371 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1372                                      RecordDecl *D1, RecordDecl *D2) {
1373 
1374   // Check for equivalent structure names.
1375   IdentifierInfo *Name1 = D1->getIdentifier();
1376   if (!Name1 && D1->getTypedefNameForAnonDecl())
1377     Name1 = D1->getTypedefNameForAnonDecl()->getIdentifier();
1378   IdentifierInfo *Name2 = D2->getIdentifier();
1379   if (!Name2 && D2->getTypedefNameForAnonDecl())
1380     Name2 = D2->getTypedefNameForAnonDecl()->getIdentifier();
1381   if (!IsStructurallyEquivalent(Name1, Name2))
1382     return false;
1383 
1384   if (D1->isUnion() != D2->isUnion()) {
1385     if (Context.Complain) {
1386       Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic(
1387                                            diag::err_odr_tag_type_inconsistent))
1388           << Context.ToCtx.getTypeDeclType(D2);
1389       Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here)
1390           << D1->getDeclName() << (unsigned)D1->getTagKind();
1391     }
1392     return false;
1393   }
1394 
1395   if (!D1->getDeclName() && !D2->getDeclName()) {
1396     // If both anonymous structs/unions are in a record context, make sure
1397     // they occur in the same location in the context records.
1398     if (Optional<unsigned> Index1 =
1399             StructuralEquivalenceContext::findUntaggedStructOrUnionIndex(D1)) {
1400       if (Optional<unsigned> Index2 =
1401               StructuralEquivalenceContext::findUntaggedStructOrUnionIndex(
1402                   D2)) {
1403         if (*Index1 != *Index2)
1404           return false;
1405       }
1406     }
1407   }
1408 
1409   // If both declarations are class template specializations, we know
1410   // the ODR applies, so check the template and template arguments.
1411   const auto *Spec1 = dyn_cast<ClassTemplateSpecializationDecl>(D1);
1412   const auto *Spec2 = dyn_cast<ClassTemplateSpecializationDecl>(D2);
1413   if (Spec1 && Spec2) {
1414     // Check that the specialized templates are the same.
1415     if (!IsStructurallyEquivalent(Context, Spec1->getSpecializedTemplate(),
1416                                   Spec2->getSpecializedTemplate()))
1417       return false;
1418 
1419     // Check that the template arguments are the same.
1420     if (Spec1->getTemplateArgs().size() != Spec2->getTemplateArgs().size())
1421       return false;
1422 
1423     for (unsigned I = 0, N = Spec1->getTemplateArgs().size(); I != N; ++I)
1424       if (!IsStructurallyEquivalent(Context, Spec1->getTemplateArgs().get(I),
1425                                     Spec2->getTemplateArgs().get(I)))
1426         return false;
1427   }
1428   // If one is a class template specialization and the other is not, these
1429   // structures are different.
1430   else if (Spec1 || Spec2)
1431     return false;
1432 
1433   // Compare the definitions of these two records. If either or both are
1434   // incomplete (i.e. it is a forward decl), we assume that they are
1435   // equivalent.
1436   D1 = D1->getDefinition();
1437   D2 = D2->getDefinition();
1438   if (!D1 || !D2)
1439     return true;
1440 
1441   // If any of the records has external storage and we do a minimal check (or
1442   // AST import) we assume they are equivalent. (If we didn't have this
1443   // assumption then `RecordDecl::LoadFieldsFromExternalStorage` could trigger
1444   // another AST import which in turn would call the structural equivalency
1445   // check again and finally we'd have an improper result.)
1446   if (Context.EqKind == StructuralEquivalenceKind::Minimal)
1447     if (D1->hasExternalLexicalStorage() || D2->hasExternalLexicalStorage())
1448       return true;
1449 
1450   // If one definition is currently being defined, we do not compare for
1451   // equality and we assume that the decls are equal.
1452   if (D1->isBeingDefined() || D2->isBeingDefined())
1453     return true;
1454 
1455   if (auto *D1CXX = dyn_cast<CXXRecordDecl>(D1)) {
1456     if (auto *D2CXX = dyn_cast<CXXRecordDecl>(D2)) {
1457       if (D1CXX->hasExternalLexicalStorage() &&
1458           !D1CXX->isCompleteDefinition()) {
1459         D1CXX->getASTContext().getExternalSource()->CompleteType(D1CXX);
1460       }
1461 
1462       if (D1CXX->isLambda() != D2CXX->isLambda())
1463         return false;
1464       if (D1CXX->isLambda()) {
1465         if (!IsStructurallyEquivalentLambdas(Context, D1CXX, D2CXX))
1466           return false;
1467       }
1468 
1469       if (D1CXX->getNumBases() != D2CXX->getNumBases()) {
1470         if (Context.Complain) {
1471           Context.Diag2(D2->getLocation(),
1472                         Context.getApplicableDiagnostic(
1473                             diag::err_odr_tag_type_inconsistent))
1474               << Context.ToCtx.getTypeDeclType(D2);
1475           Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases)
1476               << D2CXX->getNumBases();
1477           Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases)
1478               << D1CXX->getNumBases();
1479         }
1480         return false;
1481       }
1482 
1483       // Check the base classes.
1484       for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(),
1485                                               BaseEnd1 = D1CXX->bases_end(),
1486                                               Base2 = D2CXX->bases_begin();
1487            Base1 != BaseEnd1; ++Base1, ++Base2) {
1488         if (!IsStructurallyEquivalent(Context, Base1->getType(),
1489                                       Base2->getType())) {
1490           if (Context.Complain) {
1491             Context.Diag2(D2->getLocation(),
1492                           Context.getApplicableDiagnostic(
1493                               diag::err_odr_tag_type_inconsistent))
1494                 << Context.ToCtx.getTypeDeclType(D2);
1495             Context.Diag2(Base2->getBeginLoc(), diag::note_odr_base)
1496                 << Base2->getType() << Base2->getSourceRange();
1497             Context.Diag1(Base1->getBeginLoc(), diag::note_odr_base)
1498                 << Base1->getType() << Base1->getSourceRange();
1499           }
1500           return false;
1501         }
1502 
1503         // Check virtual vs. non-virtual inheritance mismatch.
1504         if (Base1->isVirtual() != Base2->isVirtual()) {
1505           if (Context.Complain) {
1506             Context.Diag2(D2->getLocation(),
1507                           Context.getApplicableDiagnostic(
1508                               diag::err_odr_tag_type_inconsistent))
1509                 << Context.ToCtx.getTypeDeclType(D2);
1510             Context.Diag2(Base2->getBeginLoc(), diag::note_odr_virtual_base)
1511                 << Base2->isVirtual() << Base2->getSourceRange();
1512             Context.Diag1(Base1->getBeginLoc(), diag::note_odr_base)
1513                 << Base1->isVirtual() << Base1->getSourceRange();
1514           }
1515           return false;
1516         }
1517       }
1518 
1519       // Check the friends for consistency.
1520       CXXRecordDecl::friend_iterator Friend2 = D2CXX->friend_begin(),
1521                                      Friend2End = D2CXX->friend_end();
1522       for (CXXRecordDecl::friend_iterator Friend1 = D1CXX->friend_begin(),
1523                                           Friend1End = D1CXX->friend_end();
1524            Friend1 != Friend1End; ++Friend1, ++Friend2) {
1525         if (Friend2 == Friend2End) {
1526           if (Context.Complain) {
1527             Context.Diag2(D2->getLocation(),
1528                           Context.getApplicableDiagnostic(
1529                               diag::err_odr_tag_type_inconsistent))
1530                 << Context.ToCtx.getTypeDeclType(D2CXX);
1531             Context.Diag1((*Friend1)->getFriendLoc(), diag::note_odr_friend);
1532             Context.Diag2(D2->getLocation(), diag::note_odr_missing_friend);
1533           }
1534           return false;
1535         }
1536 
1537         if (!IsStructurallyEquivalent(Context, *Friend1, *Friend2)) {
1538           if (Context.Complain) {
1539             Context.Diag2(D2->getLocation(),
1540                           Context.getApplicableDiagnostic(
1541                               diag::err_odr_tag_type_inconsistent))
1542                 << Context.ToCtx.getTypeDeclType(D2CXX);
1543             Context.Diag1((*Friend1)->getFriendLoc(), diag::note_odr_friend);
1544             Context.Diag2((*Friend2)->getFriendLoc(), diag::note_odr_friend);
1545           }
1546           return false;
1547         }
1548       }
1549 
1550       if (Friend2 != Friend2End) {
1551         if (Context.Complain) {
1552           Context.Diag2(D2->getLocation(),
1553                         Context.getApplicableDiagnostic(
1554                             diag::err_odr_tag_type_inconsistent))
1555               << Context.ToCtx.getTypeDeclType(D2);
1556           Context.Diag2((*Friend2)->getFriendLoc(), diag::note_odr_friend);
1557           Context.Diag1(D1->getLocation(), diag::note_odr_missing_friend);
1558         }
1559         return false;
1560       }
1561     } else if (D1CXX->getNumBases() > 0) {
1562       if (Context.Complain) {
1563         Context.Diag2(D2->getLocation(),
1564                       Context.getApplicableDiagnostic(
1565                           diag::err_odr_tag_type_inconsistent))
1566             << Context.ToCtx.getTypeDeclType(D2);
1567         const CXXBaseSpecifier *Base1 = D1CXX->bases_begin();
1568         Context.Diag1(Base1->getBeginLoc(), diag::note_odr_base)
1569             << Base1->getType() << Base1->getSourceRange();
1570         Context.Diag2(D2->getLocation(), diag::note_odr_missing_base);
1571       }
1572       return false;
1573     }
1574   }
1575 
1576   // Check the fields for consistency.
1577   RecordDecl::field_iterator Field2 = D2->field_begin(),
1578                              Field2End = D2->field_end();
1579   for (RecordDecl::field_iterator Field1 = D1->field_begin(),
1580                                   Field1End = D1->field_end();
1581        Field1 != Field1End; ++Field1, ++Field2) {
1582     if (Field2 == Field2End) {
1583       if (Context.Complain) {
1584         Context.Diag2(D2->getLocation(),
1585                       Context.getApplicableDiagnostic(
1586                           diag::err_odr_tag_type_inconsistent))
1587             << Context.ToCtx.getTypeDeclType(D2);
1588         Context.Diag1(Field1->getLocation(), diag::note_odr_field)
1589             << Field1->getDeclName() << Field1->getType();
1590         Context.Diag2(D2->getLocation(), diag::note_odr_missing_field);
1591       }
1592       return false;
1593     }
1594 
1595     if (!IsStructurallyEquivalent(Context, *Field1, *Field2))
1596       return false;
1597   }
1598 
1599   if (Field2 != Field2End) {
1600     if (Context.Complain) {
1601       Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic(
1602                                            diag::err_odr_tag_type_inconsistent))
1603           << Context.ToCtx.getTypeDeclType(D2);
1604       Context.Diag2(Field2->getLocation(), diag::note_odr_field)
1605           << Field2->getDeclName() << Field2->getType();
1606       Context.Diag1(D1->getLocation(), diag::note_odr_missing_field);
1607     }
1608     return false;
1609   }
1610 
1611   return true;
1612 }
1613 
1614 /// Determine structural equivalence of two enums.
1615 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1616                                      EnumDecl *D1, EnumDecl *D2) {
1617 
1618   // Check for equivalent enum names.
1619   IdentifierInfo *Name1 = D1->getIdentifier();
1620   if (!Name1 && D1->getTypedefNameForAnonDecl())
1621     Name1 = D1->getTypedefNameForAnonDecl()->getIdentifier();
1622   IdentifierInfo *Name2 = D2->getIdentifier();
1623   if (!Name2 && D2->getTypedefNameForAnonDecl())
1624     Name2 = D2->getTypedefNameForAnonDecl()->getIdentifier();
1625   if (!IsStructurallyEquivalent(Name1, Name2))
1626     return false;
1627 
1628   // Compare the definitions of these two enums. If either or both are
1629   // incomplete (i.e. forward declared), we assume that they are equivalent.
1630   D1 = D1->getDefinition();
1631   D2 = D2->getDefinition();
1632   if (!D1 || !D2)
1633     return true;
1634 
1635   EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(),
1636                                 EC2End = D2->enumerator_end();
1637   for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(),
1638                                      EC1End = D1->enumerator_end();
1639        EC1 != EC1End; ++EC1, ++EC2) {
1640     if (EC2 == EC2End) {
1641       if (Context.Complain) {
1642         Context.Diag2(D2->getLocation(),
1643                       Context.getApplicableDiagnostic(
1644                           diag::err_odr_tag_type_inconsistent))
1645             << Context.ToCtx.getTypeDeclType(D2);
1646         Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1647             << EC1->getDeclName() << EC1->getInitVal().toString(10);
1648         Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator);
1649       }
1650       return false;
1651     }
1652 
1653     llvm::APSInt Val1 = EC1->getInitVal();
1654     llvm::APSInt Val2 = EC2->getInitVal();
1655     if (!llvm::APSInt::isSameValue(Val1, Val2) ||
1656         !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) {
1657       if (Context.Complain) {
1658         Context.Diag2(D2->getLocation(),
1659                       Context.getApplicableDiagnostic(
1660                           diag::err_odr_tag_type_inconsistent))
1661             << Context.ToCtx.getTypeDeclType(D2);
1662         Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1663             << EC2->getDeclName() << EC2->getInitVal().toString(10);
1664         Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1665             << EC1->getDeclName() << EC1->getInitVal().toString(10);
1666       }
1667       return false;
1668     }
1669   }
1670 
1671   if (EC2 != EC2End) {
1672     if (Context.Complain) {
1673       Context.Diag2(D2->getLocation(), Context.getApplicableDiagnostic(
1674                                            diag::err_odr_tag_type_inconsistent))
1675           << Context.ToCtx.getTypeDeclType(D2);
1676       Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1677           << EC2->getDeclName() << EC2->getInitVal().toString(10);
1678       Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator);
1679     }
1680     return false;
1681   }
1682 
1683   return true;
1684 }
1685 
1686 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1687                                      TemplateParameterList *Params1,
1688                                      TemplateParameterList *Params2) {
1689   if (Params1->size() != Params2->size()) {
1690     if (Context.Complain) {
1691       Context.Diag2(Params2->getTemplateLoc(),
1692                     Context.getApplicableDiagnostic(
1693                         diag::err_odr_different_num_template_parameters))
1694           << Params1->size() << Params2->size();
1695       Context.Diag1(Params1->getTemplateLoc(),
1696                     diag::note_odr_template_parameter_list);
1697     }
1698     return false;
1699   }
1700 
1701   for (unsigned I = 0, N = Params1->size(); I != N; ++I) {
1702     if (Params1->getParam(I)->getKind() != Params2->getParam(I)->getKind()) {
1703       if (Context.Complain) {
1704         Context.Diag2(Params2->getParam(I)->getLocation(),
1705                       Context.getApplicableDiagnostic(
1706                           diag::err_odr_different_template_parameter_kind));
1707         Context.Diag1(Params1->getParam(I)->getLocation(),
1708                       diag::note_odr_template_parameter_here);
1709       }
1710       return false;
1711     }
1712 
1713     if (!IsStructurallyEquivalent(Context, Params1->getParam(I),
1714                                   Params2->getParam(I)))
1715       return false;
1716   }
1717 
1718   return true;
1719 }
1720 
1721 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1722                                      TemplateTypeParmDecl *D1,
1723                                      TemplateTypeParmDecl *D2) {
1724   if (D1->isParameterPack() != D2->isParameterPack()) {
1725     if (Context.Complain) {
1726       Context.Diag2(D2->getLocation(),
1727                     Context.getApplicableDiagnostic(
1728                         diag::err_odr_parameter_pack_non_pack))
1729           << D2->isParameterPack();
1730       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1731           << D1->isParameterPack();
1732     }
1733     return false;
1734   }
1735 
1736   return true;
1737 }
1738 
1739 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1740                                      NonTypeTemplateParmDecl *D1,
1741                                      NonTypeTemplateParmDecl *D2) {
1742   if (D1->isParameterPack() != D2->isParameterPack()) {
1743     if (Context.Complain) {
1744       Context.Diag2(D2->getLocation(),
1745                     Context.getApplicableDiagnostic(
1746                         diag::err_odr_parameter_pack_non_pack))
1747           << D2->isParameterPack();
1748       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1749           << D1->isParameterPack();
1750     }
1751     return false;
1752   }
1753 
1754   // Check types.
1755   if (!IsStructurallyEquivalent(Context, D1->getType(), D2->getType())) {
1756     if (Context.Complain) {
1757       Context.Diag2(D2->getLocation(),
1758                     Context.getApplicableDiagnostic(
1759                         diag::err_odr_non_type_parameter_type_inconsistent))
1760           << D2->getType() << D1->getType();
1761       Context.Diag1(D1->getLocation(), diag::note_odr_value_here)
1762           << D1->getType();
1763     }
1764     return false;
1765   }
1766 
1767   return true;
1768 }
1769 
1770 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1771                                      TemplateTemplateParmDecl *D1,
1772                                      TemplateTemplateParmDecl *D2) {
1773   if (D1->isParameterPack() != D2->isParameterPack()) {
1774     if (Context.Complain) {
1775       Context.Diag2(D2->getLocation(),
1776                     Context.getApplicableDiagnostic(
1777                         diag::err_odr_parameter_pack_non_pack))
1778           << D2->isParameterPack();
1779       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1780           << D1->isParameterPack();
1781     }
1782     return false;
1783   }
1784 
1785   // Check template parameter lists.
1786   return IsStructurallyEquivalent(Context, D1->getTemplateParameters(),
1787                                   D2->getTemplateParameters());
1788 }
1789 
1790 static bool IsTemplateDeclCommonStructurallyEquivalent(
1791     StructuralEquivalenceContext &Ctx, TemplateDecl *D1, TemplateDecl *D2) {
1792   if (!IsStructurallyEquivalent(D1->getIdentifier(), D2->getIdentifier()))
1793     return false;
1794   if (!D1->getIdentifier()) // Special name
1795     if (D1->getNameAsString() != D2->getNameAsString())
1796       return false;
1797   return IsStructurallyEquivalent(Ctx, D1->getTemplateParameters(),
1798                                   D2->getTemplateParameters());
1799 }
1800 
1801 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1802                                      ClassTemplateDecl *D1,
1803                                      ClassTemplateDecl *D2) {
1804   // Check template parameters.
1805   if (!IsTemplateDeclCommonStructurallyEquivalent(Context, D1, D2))
1806     return false;
1807 
1808   // Check the templated declaration.
1809   return IsStructurallyEquivalent(Context, D1->getTemplatedDecl(),
1810                                   D2->getTemplatedDecl());
1811 }
1812 
1813 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1814                                      FunctionTemplateDecl *D1,
1815                                      FunctionTemplateDecl *D2) {
1816   // Check template parameters.
1817   if (!IsTemplateDeclCommonStructurallyEquivalent(Context, D1, D2))
1818     return false;
1819 
1820   // Check the templated declaration.
1821   return IsStructurallyEquivalent(Context, D1->getTemplatedDecl()->getType(),
1822                                   D2->getTemplatedDecl()->getType());
1823 }
1824 
1825 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1826                                      ConceptDecl *D1,
1827                                      ConceptDecl *D2) {
1828   // Check template parameters.
1829   if (!IsTemplateDeclCommonStructurallyEquivalent(Context, D1, D2))
1830     return false;
1831 
1832   // Check the constraint expression.
1833   return IsStructurallyEquivalent(Context, D1->getConstraintExpr(),
1834                                   D2->getConstraintExpr());
1835 }
1836 
1837 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1838                                      FriendDecl *D1, FriendDecl *D2) {
1839   if ((D1->getFriendType() && D2->getFriendDecl()) ||
1840       (D1->getFriendDecl() && D2->getFriendType())) {
1841       return false;
1842   }
1843   if (D1->getFriendType() && D2->getFriendType())
1844     return IsStructurallyEquivalent(Context,
1845                                     D1->getFriendType()->getType(),
1846                                     D2->getFriendType()->getType());
1847   if (D1->getFriendDecl() && D2->getFriendDecl())
1848     return IsStructurallyEquivalent(Context, D1->getFriendDecl(),
1849                                     D2->getFriendDecl());
1850   return false;
1851 }
1852 
1853 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1854                                      TypedefNameDecl *D1, TypedefNameDecl *D2) {
1855   if (!IsStructurallyEquivalent(D1->getIdentifier(), D2->getIdentifier()))
1856     return false;
1857 
1858   return IsStructurallyEquivalent(Context, D1->getUnderlyingType(),
1859                                   D2->getUnderlyingType());
1860 }
1861 
1862 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1863                                      FunctionDecl *D1, FunctionDecl *D2) {
1864   if (!IsStructurallyEquivalent(D1->getIdentifier(), D2->getIdentifier()))
1865     return false;
1866 
1867   if (D1->isOverloadedOperator()) {
1868     if (!D2->isOverloadedOperator())
1869       return false;
1870     if (D1->getOverloadedOperator() != D2->getOverloadedOperator())
1871       return false;
1872   }
1873 
1874   // FIXME: Consider checking for function attributes as well.
1875   if (!IsStructurallyEquivalent(Context, D1->getType(), D2->getType()))
1876     return false;
1877 
1878   return true;
1879 }
1880 
1881 /// Determine structural equivalence of two declarations.
1882 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1883                                      Decl *D1, Decl *D2) {
1884   // FIXME: Check for known structural equivalences via a callback of some sort.
1885 
1886   D1 = D1->getCanonicalDecl();
1887   D2 = D2->getCanonicalDecl();
1888   std::pair<Decl *, Decl *> P{D1, D2};
1889 
1890   // Check whether we already know that these two declarations are not
1891   // structurally equivalent.
1892   if (Context.NonEquivalentDecls.count(P))
1893     return false;
1894 
1895   // Check if a check for these declarations is already pending.
1896   // If yes D1 and D2 will be checked later (from DeclsToCheck),
1897   // or these are already checked (and equivalent).
1898   bool Inserted = Context.VisitedDecls.insert(P).second;
1899   if (!Inserted)
1900     return true;
1901 
1902   Context.DeclsToCheck.push(P);
1903 
1904   return true;
1905 }
1906 
1907 DiagnosticBuilder StructuralEquivalenceContext::Diag1(SourceLocation Loc,
1908                                                       unsigned DiagID) {
1909   assert(Complain && "Not allowed to complain");
1910   if (LastDiagFromC2)
1911     FromCtx.getDiagnostics().notePriorDiagnosticFrom(ToCtx.getDiagnostics());
1912   LastDiagFromC2 = false;
1913   return FromCtx.getDiagnostics().Report(Loc, DiagID);
1914 }
1915 
1916 DiagnosticBuilder StructuralEquivalenceContext::Diag2(SourceLocation Loc,
1917                                                       unsigned DiagID) {
1918   assert(Complain && "Not allowed to complain");
1919   if (!LastDiagFromC2)
1920     ToCtx.getDiagnostics().notePriorDiagnosticFrom(FromCtx.getDiagnostics());
1921   LastDiagFromC2 = true;
1922   return ToCtx.getDiagnostics().Report(Loc, DiagID);
1923 }
1924 
1925 Optional<unsigned>
1926 StructuralEquivalenceContext::findUntaggedStructOrUnionIndex(RecordDecl *Anon) {
1927   ASTContext &Context = Anon->getASTContext();
1928   QualType AnonTy = Context.getRecordType(Anon);
1929 
1930   const auto *Owner = dyn_cast<RecordDecl>(Anon->getDeclContext());
1931   if (!Owner)
1932     return None;
1933 
1934   unsigned Index = 0;
1935   for (const auto *D : Owner->noload_decls()) {
1936     const auto *F = dyn_cast<FieldDecl>(D);
1937     if (!F)
1938       continue;
1939 
1940     if (F->isAnonymousStructOrUnion()) {
1941       if (Context.hasSameType(F->getType(), AnonTy))
1942         break;
1943       ++Index;
1944       continue;
1945     }
1946 
1947     // If the field looks like this:
1948     // struct { ... } A;
1949     QualType FieldType = F->getType();
1950     // In case of nested structs.
1951     while (const auto *ElabType = dyn_cast<ElaboratedType>(FieldType))
1952       FieldType = ElabType->getNamedType();
1953 
1954     if (const auto *RecType = dyn_cast<RecordType>(FieldType)) {
1955       const RecordDecl *RecDecl = RecType->getDecl();
1956       if (RecDecl->getDeclContext() == Owner && !RecDecl->getIdentifier()) {
1957         if (Context.hasSameType(FieldType, AnonTy))
1958           break;
1959         ++Index;
1960         continue;
1961       }
1962     }
1963   }
1964 
1965   return Index;
1966 }
1967 
1968 unsigned StructuralEquivalenceContext::getApplicableDiagnostic(
1969     unsigned ErrorDiagnostic) {
1970   if (ErrorOnTagTypeMismatch)
1971     return ErrorDiagnostic;
1972 
1973   switch (ErrorDiagnostic) {
1974   case diag::err_odr_variable_type_inconsistent:
1975     return diag::warn_odr_variable_type_inconsistent;
1976   case diag::err_odr_variable_multiple_def:
1977     return diag::warn_odr_variable_multiple_def;
1978   case diag::err_odr_function_type_inconsistent:
1979     return diag::warn_odr_function_type_inconsistent;
1980   case diag::err_odr_tag_type_inconsistent:
1981     return diag::warn_odr_tag_type_inconsistent;
1982   case diag::err_odr_field_type_inconsistent:
1983     return diag::warn_odr_field_type_inconsistent;
1984   case diag::err_odr_ivar_type_inconsistent:
1985     return diag::warn_odr_ivar_type_inconsistent;
1986   case diag::err_odr_objc_superclass_inconsistent:
1987     return diag::warn_odr_objc_superclass_inconsistent;
1988   case diag::err_odr_objc_method_result_type_inconsistent:
1989     return diag::warn_odr_objc_method_result_type_inconsistent;
1990   case diag::err_odr_objc_method_num_params_inconsistent:
1991     return diag::warn_odr_objc_method_num_params_inconsistent;
1992   case diag::err_odr_objc_method_param_type_inconsistent:
1993     return diag::warn_odr_objc_method_param_type_inconsistent;
1994   case diag::err_odr_objc_method_variadic_inconsistent:
1995     return diag::warn_odr_objc_method_variadic_inconsistent;
1996   case diag::err_odr_objc_property_type_inconsistent:
1997     return diag::warn_odr_objc_property_type_inconsistent;
1998   case diag::err_odr_objc_property_impl_kind_inconsistent:
1999     return diag::warn_odr_objc_property_impl_kind_inconsistent;
2000   case diag::err_odr_objc_synthesize_ivar_inconsistent:
2001     return diag::warn_odr_objc_synthesize_ivar_inconsistent;
2002   case diag::err_odr_different_num_template_parameters:
2003     return diag::warn_odr_different_num_template_parameters;
2004   case diag::err_odr_different_template_parameter_kind:
2005     return diag::warn_odr_different_template_parameter_kind;
2006   case diag::err_odr_parameter_pack_non_pack:
2007     return diag::warn_odr_parameter_pack_non_pack;
2008   case diag::err_odr_non_type_parameter_type_inconsistent:
2009     return diag::warn_odr_non_type_parameter_type_inconsistent;
2010   }
2011   llvm_unreachable("Diagnostic kind not handled in preceding switch");
2012 }
2013 
2014 bool StructuralEquivalenceContext::IsEquivalent(Decl *D1, Decl *D2) {
2015 
2016   // Ensure that the implementation functions (all static functions in this TU)
2017   // never call the public ASTStructuralEquivalence::IsEquivalent() functions,
2018   // because that will wreak havoc the internal state (DeclsToCheck and
2019   // VisitedDecls members) and can cause faulty behaviour.
2020   // In other words: Do not start a graph search from a new node with the
2021   // internal data of another search in progress.
2022   // FIXME: Better encapsulation and separation of internal and public
2023   // functionality.
2024   assert(DeclsToCheck.empty());
2025   assert(VisitedDecls.empty());
2026 
2027   if (!::IsStructurallyEquivalent(*this, D1, D2))
2028     return false;
2029 
2030   return !Finish();
2031 }
2032 
2033 bool StructuralEquivalenceContext::IsEquivalent(QualType T1, QualType T2) {
2034   assert(DeclsToCheck.empty());
2035   assert(VisitedDecls.empty());
2036   if (!::IsStructurallyEquivalent(*this, T1, T2))
2037     return false;
2038 
2039   return !Finish();
2040 }
2041 
2042 bool StructuralEquivalenceContext::IsEquivalent(Stmt *S1, Stmt *S2) {
2043   assert(DeclsToCheck.empty());
2044   assert(VisitedDecls.empty());
2045   if (!::IsStructurallyEquivalent(*this, S1, S2))
2046     return false;
2047 
2048   return !Finish();
2049 }
2050 
2051 bool StructuralEquivalenceContext::CheckCommonEquivalence(Decl *D1, Decl *D2) {
2052   // Check for equivalent described template.
2053   TemplateDecl *Template1 = D1->getDescribedTemplate();
2054   TemplateDecl *Template2 = D2->getDescribedTemplate();
2055   if ((Template1 != nullptr) != (Template2 != nullptr))
2056     return false;
2057   if (Template1 && !IsStructurallyEquivalent(*this, Template1, Template2))
2058     return false;
2059 
2060   // FIXME: Move check for identifier names into this function.
2061 
2062   return true;
2063 }
2064 
2065 bool StructuralEquivalenceContext::CheckKindSpecificEquivalence(
2066     Decl *D1, Decl *D2) {
2067 
2068   // Kind mismatch.
2069   if (D1->getKind() != D2->getKind())
2070     return false;
2071 
2072   // Cast the Decls to their actual subclass so that the right overload of
2073   // IsStructurallyEquivalent is called.
2074   switch (D1->getKind()) {
2075 #define ABSTRACT_DECL(DECL)
2076 #define DECL(DERIVED, BASE)                                                    \
2077   case Decl::Kind::DERIVED:                                                    \
2078     return ::IsStructurallyEquivalent(*this, static_cast<DERIVED##Decl *>(D1), \
2079                                       static_cast<DERIVED##Decl *>(D2));
2080 #include "clang/AST/DeclNodes.inc"
2081   }
2082   return true;
2083 }
2084 
2085 bool StructuralEquivalenceContext::Finish() {
2086   while (!DeclsToCheck.empty()) {
2087     // Check the next declaration.
2088     std::pair<Decl *, Decl *> P = DeclsToCheck.front();
2089     DeclsToCheck.pop();
2090 
2091     Decl *D1 = P.first;
2092     Decl *D2 = P.second;
2093 
2094     bool Equivalent =
2095         CheckCommonEquivalence(D1, D2) && CheckKindSpecificEquivalence(D1, D2);
2096 
2097     if (!Equivalent) {
2098       // Note that these two declarations are not equivalent (and we already
2099       // know about it).
2100       NonEquivalentDecls.insert(P);
2101 
2102       return true;
2103     }
2104   }
2105 
2106   return false;
2107 }
2108