1 //===-- ODRHash.cpp - Hashing to diagnose ODR failures ----------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// This file implements the ODRHash class, which calculates a hash based
12 /// on AST nodes, which is stable across different runs.
13 ///
14 //===----------------------------------------------------------------------===//
15 
16 #include "clang/AST/ODRHash.h"
17 
18 #include "clang/AST/DeclVisitor.h"
19 #include "clang/AST/NestedNameSpecifier.h"
20 #include "clang/AST/StmtVisitor.h"
21 #include "clang/AST/TypeVisitor.h"
22 
23 using namespace clang;
24 
25 void ODRHash::AddStmt(const Stmt *S) {
26   assert(S && "Expecting non-null pointer.");
27   S->ProcessODRHash(ID, *this);
28 }
29 
30 void ODRHash::AddIdentifierInfo(const IdentifierInfo *II) {
31   assert(II && "Expecting non-null pointer.");
32   ID.AddString(II->getName());
33 }
34 
35 void ODRHash::AddDeclarationName(DeclarationName Name) {
36   AddBoolean(Name.isEmpty());
37   if (Name.isEmpty())
38     return;
39 
40   auto Kind = Name.getNameKind();
41   ID.AddInteger(Kind);
42   switch (Kind) {
43   case DeclarationName::Identifier:
44     AddIdentifierInfo(Name.getAsIdentifierInfo());
45     break;
46   case DeclarationName::ObjCZeroArgSelector:
47   case DeclarationName::ObjCOneArgSelector:
48   case DeclarationName::ObjCMultiArgSelector: {
49     Selector S = Name.getObjCSelector();
50     AddBoolean(S.isNull());
51     AddBoolean(S.isKeywordSelector());
52     AddBoolean(S.isUnarySelector());
53     unsigned NumArgs = S.getNumArgs();
54     for (unsigned i = 0; i < NumArgs; ++i) {
55       AddIdentifierInfo(S.getIdentifierInfoForSlot(i));
56     }
57     break;
58   }
59   case DeclarationName::CXXConstructorName:
60   case DeclarationName::CXXDestructorName:
61     AddQualType(Name.getCXXNameType());
62     break;
63   case DeclarationName::CXXOperatorName:
64     ID.AddInteger(Name.getCXXOverloadedOperator());
65     break;
66   case DeclarationName::CXXLiteralOperatorName:
67     AddIdentifierInfo(Name.getCXXLiteralIdentifier());
68     break;
69   case DeclarationName::CXXConversionFunctionName:
70     AddQualType(Name.getCXXNameType());
71     break;
72   case DeclarationName::CXXUsingDirective:
73     break;
74   case DeclarationName::CXXDeductionGuideName: {
75     auto *Template = Name.getCXXDeductionGuideTemplate();
76     AddBoolean(Template);
77     if (Template) {
78       AddDecl(Template);
79     }
80   }
81   }
82 }
83 
84 void ODRHash::AddNestedNameSpecifier(const NestedNameSpecifier *NNS) {
85   assert(NNS && "Expecting non-null pointer.");
86   const auto *Prefix = NNS->getPrefix();
87   AddBoolean(Prefix);
88   if (Prefix) {
89     AddNestedNameSpecifier(Prefix);
90   }
91   auto Kind = NNS->getKind();
92   ID.AddInteger(Kind);
93   switch (Kind) {
94   case NestedNameSpecifier::Identifier:
95     AddIdentifierInfo(NNS->getAsIdentifier());
96     break;
97   case NestedNameSpecifier::Namespace:
98     AddDecl(NNS->getAsNamespace());
99     break;
100   case NestedNameSpecifier::NamespaceAlias:
101     AddDecl(NNS->getAsNamespaceAlias());
102     break;
103   case NestedNameSpecifier::TypeSpec:
104   case NestedNameSpecifier::TypeSpecWithTemplate:
105     AddType(NNS->getAsType());
106     break;
107   case NestedNameSpecifier::Global:
108   case NestedNameSpecifier::Super:
109     break;
110   }
111 }
112 
113 void ODRHash::AddTemplateName(TemplateName Name) {
114   auto Kind = Name.getKind();
115   ID.AddInteger(Kind);
116 
117   switch (Kind) {
118   case TemplateName::Template:
119     AddDecl(Name.getAsTemplateDecl());
120     break;
121   // TODO: Support these cases.
122   case TemplateName::OverloadedTemplate:
123   case TemplateName::QualifiedTemplate:
124   case TemplateName::DependentTemplate:
125   case TemplateName::SubstTemplateTemplateParm:
126   case TemplateName::SubstTemplateTemplateParmPack:
127     break;
128   }
129 }
130 
131 void ODRHash::AddTemplateArgument(TemplateArgument TA) {
132   const auto Kind = TA.getKind();
133   ID.AddInteger(Kind);
134 
135   switch (Kind) {
136     case TemplateArgument::Null:
137       llvm_unreachable("Expected valid TemplateArgument");
138     case TemplateArgument::Type:
139       AddQualType(TA.getAsType());
140       break;
141     case TemplateArgument::Declaration:
142     case TemplateArgument::NullPtr:
143     case TemplateArgument::Integral:
144       break;
145     case TemplateArgument::Template:
146     case TemplateArgument::TemplateExpansion:
147       AddTemplateName(TA.getAsTemplateOrTemplatePattern());
148       break;
149     case TemplateArgument::Expression:
150       AddStmt(TA.getAsExpr());
151       break;
152     case TemplateArgument::Pack:
153       ID.AddInteger(TA.pack_size());
154       for (auto SubTA : TA.pack_elements()) {
155         AddTemplateArgument(SubTA);
156       }
157       break;
158   }
159 }
160 
161 void ODRHash::AddTemplateParameterList(const TemplateParameterList *TPL) {
162   assert(TPL && "Expecting non-null pointer.");
163 
164   ID.AddInteger(TPL->size());
165   for (auto *ND : TPL->asArray()) {
166     AddSubDecl(ND);
167   }
168 }
169 
170 void ODRHash::clear() {
171   DeclMap.clear();
172   TypeMap.clear();
173   Bools.clear();
174   ID.clear();
175 }
176 
177 unsigned ODRHash::CalculateHash() {
178   // Append the bools to the end of the data segment backwards.  This allows
179   // for the bools data to be compressed 32 times smaller compared to using
180   // ID.AddBoolean
181   const unsigned unsigned_bits = sizeof(unsigned) * CHAR_BIT;
182   const unsigned size = Bools.size();
183   const unsigned remainder = size % unsigned_bits;
184   const unsigned loops = size / unsigned_bits;
185   auto I = Bools.rbegin();
186   unsigned value = 0;
187   for (unsigned i = 0; i < remainder; ++i) {
188     value <<= 1;
189     value |= *I;
190     ++I;
191   }
192   ID.AddInteger(value);
193 
194   for (unsigned i = 0; i < loops; ++i) {
195     value = 0;
196     for (unsigned j = 0; j < unsigned_bits; ++j) {
197       value <<= 1;
198       value |= *I;
199       ++I;
200     }
201     ID.AddInteger(value);
202   }
203 
204   assert(I == Bools.rend());
205   Bools.clear();
206   return ID.ComputeHash();
207 }
208 
209 namespace {
210 // Process a Decl pointer.  Add* methods call back into ODRHash while Visit*
211 // methods process the relevant parts of the Decl.
212 class ODRDeclVisitor : public ConstDeclVisitor<ODRDeclVisitor> {
213   typedef ConstDeclVisitor<ODRDeclVisitor> Inherited;
214   llvm::FoldingSetNodeID &ID;
215   ODRHash &Hash;
216 
217 public:
218   ODRDeclVisitor(llvm::FoldingSetNodeID &ID, ODRHash &Hash)
219       : ID(ID), Hash(Hash) {}
220 
221   void AddStmt(const Stmt *S) {
222     Hash.AddBoolean(S);
223     if (S) {
224       Hash.AddStmt(S);
225     }
226   }
227 
228   void AddIdentifierInfo(const IdentifierInfo *II) {
229     Hash.AddBoolean(II);
230     if (II) {
231       Hash.AddIdentifierInfo(II);
232     }
233   }
234 
235   void AddQualType(QualType T) {
236     Hash.AddQualType(T);
237   }
238 
239   void AddDecl(const Decl *D) {
240     Hash.AddBoolean(D);
241     if (D) {
242       Hash.AddDecl(D);
243     }
244   }
245 
246   void AddTemplateArgument(TemplateArgument TA) {
247     Hash.AddTemplateArgument(TA);
248   }
249 
250   void Visit(const Decl *D) {
251     ID.AddInteger(D->getKind());
252     Inherited::Visit(D);
253   }
254 
255   void VisitNamedDecl(const NamedDecl *D) {
256     Hash.AddDeclarationName(D->getDeclName());
257     Inherited::VisitNamedDecl(D);
258   }
259 
260   void VisitValueDecl(const ValueDecl *D) {
261     if (!isa<FunctionDecl>(D)) {
262       AddQualType(D->getType());
263     }
264     Inherited::VisitValueDecl(D);
265   }
266 
267   void VisitVarDecl(const VarDecl *D) {
268     Hash.AddBoolean(D->isStaticLocal());
269     Hash.AddBoolean(D->isConstexpr());
270     const bool HasInit = D->hasInit();
271     Hash.AddBoolean(HasInit);
272     if (HasInit) {
273       AddStmt(D->getInit());
274     }
275     Inherited::VisitVarDecl(D);
276   }
277 
278   void VisitParmVarDecl(const ParmVarDecl *D) {
279     // TODO: Handle default arguments.
280     Inherited::VisitParmVarDecl(D);
281   }
282 
283   void VisitAccessSpecDecl(const AccessSpecDecl *D) {
284     ID.AddInteger(D->getAccess());
285     Inherited::VisitAccessSpecDecl(D);
286   }
287 
288   void VisitStaticAssertDecl(const StaticAssertDecl *D) {
289     AddStmt(D->getAssertExpr());
290     AddStmt(D->getMessage());
291 
292     Inherited::VisitStaticAssertDecl(D);
293   }
294 
295   void VisitFieldDecl(const FieldDecl *D) {
296     const bool IsBitfield = D->isBitField();
297     Hash.AddBoolean(IsBitfield);
298 
299     if (IsBitfield) {
300       AddStmt(D->getBitWidth());
301     }
302 
303     Hash.AddBoolean(D->isMutable());
304     AddStmt(D->getInClassInitializer());
305 
306     Inherited::VisitFieldDecl(D);
307   }
308 
309   void VisitFunctionDecl(const FunctionDecl *D) {
310     ID.AddInteger(D->getStorageClass());
311     Hash.AddBoolean(D->isInlineSpecified());
312     Hash.AddBoolean(D->isVirtualAsWritten());
313     Hash.AddBoolean(D->isPure());
314     Hash.AddBoolean(D->isDeletedAsWritten());
315 
316     ID.AddInteger(D->param_size());
317 
318     for (auto *Param : D->parameters()) {
319       Hash.AddSubDecl(Param);
320     }
321 
322     AddQualType(D->getReturnType());
323 
324     Inherited::VisitFunctionDecl(D);
325   }
326 
327   void VisitCXXMethodDecl(const CXXMethodDecl *D) {
328     Hash.AddBoolean(D->isConst());
329     Hash.AddBoolean(D->isVolatile());
330 
331     Inherited::VisitCXXMethodDecl(D);
332   }
333 
334   void VisitTypedefNameDecl(const TypedefNameDecl *D) {
335     AddQualType(D->getUnderlyingType());
336 
337     Inherited::VisitTypedefNameDecl(D);
338   }
339 
340   void VisitTypedefDecl(const TypedefDecl *D) {
341     Inherited::VisitTypedefDecl(D);
342   }
343 
344   void VisitTypeAliasDecl(const TypeAliasDecl *D) {
345     Inherited::VisitTypeAliasDecl(D);
346   }
347 
348   void VisitFriendDecl(const FriendDecl *D) {
349     TypeSourceInfo *TSI = D->getFriendType();
350     Hash.AddBoolean(TSI);
351     if (TSI) {
352       AddQualType(TSI->getType());
353     } else {
354       AddDecl(D->getFriendDecl());
355     }
356   }
357 
358   void VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D) {
359     // Only care about default arguments as part of the definition.
360     const bool hasDefaultArgument =
361         D->hasDefaultArgument() && !D->defaultArgumentWasInherited();
362     Hash.AddBoolean(hasDefaultArgument);
363     if (hasDefaultArgument) {
364       AddTemplateArgument(D->getDefaultArgument());
365     }
366 
367     Inherited::VisitTemplateTypeParmDecl(D);
368   }
369 
370   void VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D) {
371     // Only care about default arguments as part of the definition.
372     const bool hasDefaultArgument =
373         D->hasDefaultArgument() && !D->defaultArgumentWasInherited();
374     Hash.AddBoolean(hasDefaultArgument);
375     if (hasDefaultArgument) {
376       AddStmt(D->getDefaultArgument());
377     }
378 
379     Inherited::VisitNonTypeTemplateParmDecl(D);
380   }
381 
382   void VisitTemplateTemplateParmDecl(const TemplateTemplateParmDecl *D) {
383     // Only care about default arguments as part of the definition.
384     const bool hasDefaultArgument =
385         D->hasDefaultArgument() && !D->defaultArgumentWasInherited();
386     Hash.AddBoolean(hasDefaultArgument);
387     if (hasDefaultArgument) {
388       AddTemplateArgument(D->getDefaultArgument().getArgument());
389     }
390 
391     Inherited::VisitTemplateTemplateParmDecl(D);
392   }
393 };
394 } // namespace
395 
396 // Only allow a small portion of Decl's to be processed.  Remove this once
397 // all Decl's can be handled.
398 bool ODRHash::isWhitelistedDecl(const Decl *D, const CXXRecordDecl *Parent) {
399   if (D->isImplicit()) return false;
400   if (D->getDeclContext() != Parent) return false;
401 
402   switch (D->getKind()) {
403     default:
404       return false;
405     case Decl::AccessSpec:
406     case Decl::CXXConstructor:
407     case Decl::CXXDestructor:
408     case Decl::CXXMethod:
409     case Decl::Field:
410     case Decl::Friend:
411     case Decl::StaticAssert:
412     case Decl::TypeAlias:
413     case Decl::Typedef:
414     case Decl::Var:
415       return true;
416   }
417 }
418 
419 void ODRHash::AddSubDecl(const Decl *D) {
420   assert(D && "Expecting non-null pointer.");
421   AddDecl(D);
422 
423   ODRDeclVisitor(ID, *this).Visit(D);
424 }
425 
426 void ODRHash::AddCXXRecordDecl(const CXXRecordDecl *Record) {
427   assert(Record && Record->hasDefinition() &&
428          "Expected non-null record to be a definition.");
429 
430   const DeclContext *DC = Record;
431   while (DC) {
432     if (isa<ClassTemplateSpecializationDecl>(DC)) {
433       return;
434     }
435     DC = DC->getParent();
436   }
437 
438   AddDecl(Record);
439 
440   // Filter out sub-Decls which will not be processed in order to get an
441   // accurate count of Decl's.
442   llvm::SmallVector<const Decl *, 16> Decls;
443   for (const Decl *SubDecl : Record->decls()) {
444     if (isWhitelistedDecl(SubDecl, Record)) {
445       Decls.push_back(SubDecl);
446     }
447   }
448 
449   ID.AddInteger(Decls.size());
450   for (auto SubDecl : Decls) {
451     AddSubDecl(SubDecl);
452   }
453 
454   const ClassTemplateDecl *TD = Record->getDescribedClassTemplate();
455   AddBoolean(TD);
456   if (TD) {
457     AddTemplateParameterList(TD->getTemplateParameters());
458   }
459 
460   ID.AddInteger(Record->getNumBases());
461   auto Bases = Record->bases();
462   for (auto Base : Bases) {
463     AddQualType(Base.getType());
464     ID.AddInteger(Base.isVirtual());
465     ID.AddInteger(Base.getAccessSpecifierAsWritten());
466   }
467 }
468 
469 void ODRHash::AddDecl(const Decl *D) {
470   assert(D && "Expecting non-null pointer.");
471   auto Result = DeclMap.insert(std::make_pair(D, DeclMap.size()));
472   ID.AddInteger(Result.first->second);
473   // On first encounter of a Decl pointer, process it.  Every time afterwards,
474   // only the index value is needed.
475   if (!Result.second) {
476     return;
477   }
478 
479   ID.AddInteger(D->getKind());
480 
481   if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
482     AddDeclarationName(ND->getDeclName());
483   }
484 }
485 
486 namespace {
487 // Process a Type pointer.  Add* methods call back into ODRHash while Visit*
488 // methods process the relevant parts of the Type.
489 class ODRTypeVisitor : public TypeVisitor<ODRTypeVisitor> {
490   typedef TypeVisitor<ODRTypeVisitor> Inherited;
491   llvm::FoldingSetNodeID &ID;
492   ODRHash &Hash;
493 
494 public:
495   ODRTypeVisitor(llvm::FoldingSetNodeID &ID, ODRHash &Hash)
496       : ID(ID), Hash(Hash) {}
497 
498   void AddStmt(Stmt *S) {
499     Hash.AddBoolean(S);
500     if (S) {
501       Hash.AddStmt(S);
502     }
503   }
504 
505   void AddDecl(Decl *D) {
506     Hash.AddBoolean(D);
507     if (D) {
508       Hash.AddDecl(D);
509     }
510   }
511 
512   void AddQualType(QualType T) {
513     Hash.AddQualType(T);
514   }
515 
516   void AddType(const Type *T) {
517     Hash.AddBoolean(T);
518     if (T) {
519       Hash.AddType(T);
520     }
521   }
522 
523   void AddNestedNameSpecifier(const NestedNameSpecifier *NNS) {
524     Hash.AddBoolean(NNS);
525     if (NNS) {
526       Hash.AddNestedNameSpecifier(NNS);
527     }
528   }
529 
530   void AddIdentifierInfo(const IdentifierInfo *II) {
531     Hash.AddBoolean(II);
532     if (II) {
533       Hash.AddIdentifierInfo(II);
534     }
535   }
536 
537   void VisitQualifiers(Qualifiers Quals) {
538     ID.AddInteger(Quals.getAsOpaqueValue());
539   }
540 
541   void Visit(const Type *T) {
542     ID.AddInteger(T->getTypeClass());
543     Inherited::Visit(T);
544   }
545 
546   void VisitType(const Type *T) {}
547 
548   void VisitAdjustedType(const AdjustedType *T) {
549     AddQualType(T->getOriginalType());
550     AddQualType(T->getAdjustedType());
551     VisitType(T);
552   }
553 
554   void VisitDecayedType(const DecayedType *T) {
555     AddQualType(T->getDecayedType());
556     AddQualType(T->getPointeeType());
557     VisitAdjustedType(T);
558   }
559 
560   void VisitArrayType(const ArrayType *T) {
561     AddQualType(T->getElementType());
562     ID.AddInteger(T->getSizeModifier());
563     VisitQualifiers(T->getIndexTypeQualifiers());
564     VisitType(T);
565   }
566   void VisitConstantArrayType(const ConstantArrayType *T) {
567     T->getSize().Profile(ID);
568     VisitArrayType(T);
569   }
570 
571   void VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
572     AddStmt(T->getSizeExpr());
573     VisitArrayType(T);
574   }
575 
576   void VisitIncompleteArrayType(const IncompleteArrayType *T) {
577     VisitArrayType(T);
578   }
579 
580   void VisitVariableArrayType(const VariableArrayType *T) {
581     AddStmt(T->getSizeExpr());
582     VisitArrayType(T);
583   }
584 
585   void VisitBuiltinType(const BuiltinType *T) {
586     ID.AddInteger(T->getKind());
587     VisitType(T);
588   }
589 
590   void VisitFunctionType(const FunctionType *T) {
591     AddQualType(T->getReturnType());
592     T->getExtInfo().Profile(ID);
593     Hash.AddBoolean(T->isConst());
594     Hash.AddBoolean(T->isVolatile());
595     Hash.AddBoolean(T->isRestrict());
596     VisitType(T);
597   }
598 
599   void VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
600     VisitFunctionType(T);
601   }
602 
603   void VisitFunctionProtoType(const FunctionProtoType *T) {
604     ID.AddInteger(T->getNumParams());
605     for (auto ParamType : T->getParamTypes())
606       AddQualType(ParamType);
607 
608     VisitFunctionType(T);
609   }
610 
611   void VisitTypedefType(const TypedefType *T) {
612     AddDecl(T->getDecl());
613     QualType UnderlyingType = T->getDecl()->getUnderlyingType();
614     VisitQualifiers(UnderlyingType.getQualifiers());
615     while (const TypedefType *Underlying =
616                dyn_cast<TypedefType>(UnderlyingType.getTypePtr())) {
617       UnderlyingType = Underlying->getDecl()->getUnderlyingType();
618     }
619     AddType(UnderlyingType.getTypePtr());
620     VisitType(T);
621   }
622 
623   void VisitTagType(const TagType *T) {
624     AddDecl(T->getDecl());
625     VisitType(T);
626   }
627 
628   void VisitRecordType(const RecordType *T) { VisitTagType(T); }
629   void VisitEnumType(const EnumType *T) { VisitTagType(T); }
630 
631   void VisitTypeWithKeyword(const TypeWithKeyword *T) {
632     ID.AddInteger(T->getKeyword());
633     VisitType(T);
634   };
635 
636   void VisitDependentNameType(const DependentNameType *T) {
637     AddNestedNameSpecifier(T->getQualifier());
638     AddIdentifierInfo(T->getIdentifier());
639     VisitTypeWithKeyword(T);
640   }
641 
642   void VisitDependentTemplateSpecializationType(
643       const DependentTemplateSpecializationType *T) {
644     AddIdentifierInfo(T->getIdentifier());
645     AddNestedNameSpecifier(T->getQualifier());
646     ID.AddInteger(T->getNumArgs());
647     for (const auto &TA : T->template_arguments()) {
648       Hash.AddTemplateArgument(TA);
649     }
650     VisitTypeWithKeyword(T);
651   }
652 
653   void VisitElaboratedType(const ElaboratedType *T) {
654     AddNestedNameSpecifier(T->getQualifier());
655     AddQualType(T->getNamedType());
656     VisitTypeWithKeyword(T);
657   }
658 
659   void VisitTemplateSpecializationType(const TemplateSpecializationType *T) {
660     ID.AddInteger(T->getNumArgs());
661     for (const auto &TA : T->template_arguments()) {
662       Hash.AddTemplateArgument(TA);
663     }
664     Hash.AddTemplateName(T->getTemplateName());
665     VisitType(T);
666   }
667 
668   void VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
669     ID.AddInteger(T->getDepth());
670     ID.AddInteger(T->getIndex());
671     Hash.AddBoolean(T->isParameterPack());
672     AddDecl(T->getDecl());
673   }
674 };
675 } // namespace
676 
677 void ODRHash::AddType(const Type *T) {
678   assert(T && "Expecting non-null pointer.");
679   auto Result = TypeMap.insert(std::make_pair(T, TypeMap.size()));
680   ID.AddInteger(Result.first->second);
681   // On first encounter of a Type pointer, process it.  Every time afterwards,
682   // only the index value is needed.
683   if (!Result.second) {
684     return;
685   }
686 
687   ODRTypeVisitor(ID, *this).Visit(T);
688 }
689 
690 void ODRHash::AddQualType(QualType T) {
691   AddBoolean(T.isNull());
692   if (T.isNull())
693     return;
694   SplitQualType split = T.split();
695   ID.AddInteger(split.Quals.getAsOpaqueValue());
696   AddType(split.Ty);
697 }
698 
699 void ODRHash::AddBoolean(bool Value) {
700   Bools.push_back(Value);
701 }
702