ASTStructuralEquivalence.cpp 88 KB

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