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   D = D->getCanonicalDecl();
472   auto Result = DeclMap.insert(std::make_pair(D, DeclMap.size()));
473   ID.AddInteger(Result.first->second);
474   // On first encounter of a Decl pointer, process it.  Every time afterwards,
475   // only the index value is needed.
476   if (!Result.second) {
477     return;
478   }
479 
480   ID.AddInteger(D->getKind());
481 
482   if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
483     AddDeclarationName(ND->getDeclName());
484   }
485 }
486 
487 namespace {
488 // Process a Type pointer.  Add* methods call back into ODRHash while Visit*
489 // methods process the relevant parts of the Type.
490 class ODRTypeVisitor : public TypeVisitor<ODRTypeVisitor> {
491   typedef TypeVisitor<ODRTypeVisitor> Inherited;
492   llvm::FoldingSetNodeID &ID;
493   ODRHash &Hash;
494 
495 public:
496   ODRTypeVisitor(llvm::FoldingSetNodeID &ID, ODRHash &Hash)
497       : ID(ID), Hash(Hash) {}
498 
499   void AddStmt(Stmt *S) {
500     Hash.AddBoolean(S);
501     if (S) {
502       Hash.AddStmt(S);
503     }
504   }
505 
506   void AddDecl(Decl *D) {
507     Hash.AddBoolean(D);
508     if (D) {
509       Hash.AddDecl(D);
510     }
511   }
512 
513   void AddQualType(QualType T) {
514     Hash.AddQualType(T);
515   }
516 
517   void AddType(const Type *T) {
518     Hash.AddBoolean(T);
519     if (T) {
520       Hash.AddType(T);
521     }
522   }
523 
524   void AddNestedNameSpecifier(const NestedNameSpecifier *NNS) {
525     Hash.AddBoolean(NNS);
526     if (NNS) {
527       Hash.AddNestedNameSpecifier(NNS);
528     }
529   }
530 
531   void AddIdentifierInfo(const IdentifierInfo *II) {
532     Hash.AddBoolean(II);
533     if (II) {
534       Hash.AddIdentifierInfo(II);
535     }
536   }
537 
538   void VisitQualifiers(Qualifiers Quals) {
539     ID.AddInteger(Quals.getAsOpaqueValue());
540   }
541 
542   void Visit(const Type *T) {
543     ID.AddInteger(T->getTypeClass());
544     Inherited::Visit(T);
545   }
546 
547   void VisitType(const Type *T) {}
548 
549   void VisitAdjustedType(const AdjustedType *T) {
550     AddQualType(T->getOriginalType());
551     AddQualType(T->getAdjustedType());
552     VisitType(T);
553   }
554 
555   void VisitDecayedType(const DecayedType *T) {
556     AddQualType(T->getDecayedType());
557     AddQualType(T->getPointeeType());
558     VisitAdjustedType(T);
559   }
560 
561   void VisitArrayType(const ArrayType *T) {
562     AddQualType(T->getElementType());
563     ID.AddInteger(T->getSizeModifier());
564     VisitQualifiers(T->getIndexTypeQualifiers());
565     VisitType(T);
566   }
567   void VisitConstantArrayType(const ConstantArrayType *T) {
568     T->getSize().Profile(ID);
569     VisitArrayType(T);
570   }
571 
572   void VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
573     AddStmt(T->getSizeExpr());
574     VisitArrayType(T);
575   }
576 
577   void VisitIncompleteArrayType(const IncompleteArrayType *T) {
578     VisitArrayType(T);
579   }
580 
581   void VisitVariableArrayType(const VariableArrayType *T) {
582     AddStmt(T->getSizeExpr());
583     VisitArrayType(T);
584   }
585 
586   void VisitBuiltinType(const BuiltinType *T) {
587     ID.AddInteger(T->getKind());
588     VisitType(T);
589   }
590 
591   void VisitFunctionType(const FunctionType *T) {
592     AddQualType(T->getReturnType());
593     T->getExtInfo().Profile(ID);
594     Hash.AddBoolean(T->isConst());
595     Hash.AddBoolean(T->isVolatile());
596     Hash.AddBoolean(T->isRestrict());
597     VisitType(T);
598   }
599 
600   void VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
601     VisitFunctionType(T);
602   }
603 
604   void VisitFunctionProtoType(const FunctionProtoType *T) {
605     ID.AddInteger(T->getNumParams());
606     for (auto ParamType : T->getParamTypes())
607       AddQualType(ParamType);
608 
609     VisitFunctionType(T);
610   }
611 
612   void VisitTypedefType(const TypedefType *T) {
613     AddDecl(T->getDecl());
614     QualType UnderlyingType = T->getDecl()->getUnderlyingType();
615     VisitQualifiers(UnderlyingType.getQualifiers());
616     while (const TypedefType *Underlying =
617                dyn_cast<TypedefType>(UnderlyingType.getTypePtr())) {
618       UnderlyingType = Underlying->getDecl()->getUnderlyingType();
619     }
620     AddType(UnderlyingType.getTypePtr());
621     VisitType(T);
622   }
623 
624   void VisitTagType(const TagType *T) {
625     AddDecl(T->getDecl());
626     VisitType(T);
627   }
628 
629   void VisitRecordType(const RecordType *T) { VisitTagType(T); }
630   void VisitEnumType(const EnumType *T) { VisitTagType(T); }
631 
632   void VisitTypeWithKeyword(const TypeWithKeyword *T) {
633     ID.AddInteger(T->getKeyword());
634     VisitType(T);
635   };
636 
637   void VisitDependentNameType(const DependentNameType *T) {
638     AddNestedNameSpecifier(T->getQualifier());
639     AddIdentifierInfo(T->getIdentifier());
640     VisitTypeWithKeyword(T);
641   }
642 
643   void VisitDependentTemplateSpecializationType(
644       const DependentTemplateSpecializationType *T) {
645     AddIdentifierInfo(T->getIdentifier());
646     AddNestedNameSpecifier(T->getQualifier());
647     ID.AddInteger(T->getNumArgs());
648     for (const auto &TA : T->template_arguments()) {
649       Hash.AddTemplateArgument(TA);
650     }
651     VisitTypeWithKeyword(T);
652   }
653 
654   void VisitElaboratedType(const ElaboratedType *T) {
655     AddNestedNameSpecifier(T->getQualifier());
656     AddQualType(T->getNamedType());
657     VisitTypeWithKeyword(T);
658   }
659 
660   void VisitTemplateSpecializationType(const TemplateSpecializationType *T) {
661     ID.AddInteger(T->getNumArgs());
662     for (const auto &TA : T->template_arguments()) {
663       Hash.AddTemplateArgument(TA);
664     }
665     Hash.AddTemplateName(T->getTemplateName());
666     VisitType(T);
667   }
668 
669   void VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
670     ID.AddInteger(T->getDepth());
671     ID.AddInteger(T->getIndex());
672     Hash.AddBoolean(T->isParameterPack());
673     AddDecl(T->getDecl());
674   }
675 };
676 } // namespace
677 
678 void ODRHash::AddType(const Type *T) {
679   assert(T && "Expecting non-null pointer.");
680   auto Result = TypeMap.insert(std::make_pair(T, TypeMap.size()));
681   ID.AddInteger(Result.first->second);
682   // On first encounter of a Type pointer, process it.  Every time afterwards,
683   // only the index value is needed.
684   if (!Result.second) {
685     return;
686   }
687 
688   ODRTypeVisitor(ID, *this).Visit(T);
689 }
690 
691 void ODRHash::AddQualType(QualType T) {
692   AddBoolean(T.isNull());
693   if (T.isNull())
694     return;
695   SplitQualType split = T.split();
696   ID.AddInteger(split.Quals.getAsOpaqueValue());
697   AddType(split.Ty);
698 }
699 
700 void ODRHash::AddBoolean(bool Value) {
701   Bools.push_back(Value);
702 }
703