xref: /NextBSD/contrib/llvm/tools/clang/lib/AST/ASTContext.cpp (revision 84d351007654069f9643c8e4b4802a7f5f08ee42)
1 //===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===//
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 //  This file implements the ASTContext interface.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTContext.h"
15 #include "CXXABI.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Comment.h"
20 #include "clang/AST/CommentCommandTraits.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExternalASTSource.h"
27 #include "clang/AST/Mangle.h"
28 #include "clang/AST/MangleNumberingContext.h"
29 #include "clang/AST/RecordLayout.h"
30 #include "clang/AST/RecursiveASTVisitor.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/AST/VTableBuilder.h"
33 #include "clang/Basic/Builtins.h"
34 #include "clang/Basic/SourceManager.h"
35 #include "clang/Basic/TargetInfo.h"
36 #include "llvm/ADT/SmallString.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/ADT/Triple.h"
39 #include "llvm/Support/Capacity.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include <map>
43 
44 using namespace clang;
45 
46 unsigned ASTContext::NumImplicitDefaultConstructors;
47 unsigned ASTContext::NumImplicitDefaultConstructorsDeclared;
48 unsigned ASTContext::NumImplicitCopyConstructors;
49 unsigned ASTContext::NumImplicitCopyConstructorsDeclared;
50 unsigned ASTContext::NumImplicitMoveConstructors;
51 unsigned ASTContext::NumImplicitMoveConstructorsDeclared;
52 unsigned ASTContext::NumImplicitCopyAssignmentOperators;
53 unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
54 unsigned ASTContext::NumImplicitMoveAssignmentOperators;
55 unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
56 unsigned ASTContext::NumImplicitDestructors;
57 unsigned ASTContext::NumImplicitDestructorsDeclared;
58 
59 enum FloatingRank {
60   HalfRank, FloatRank, DoubleRank, LongDoubleRank
61 };
62 
getRawCommentForDeclNoCache(const Decl * D) const63 RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
64   if (!CommentsLoaded && ExternalSource) {
65     ExternalSource->ReadComments();
66 
67 #ifndef NDEBUG
68     ArrayRef<RawComment *> RawComments = Comments.getComments();
69     assert(std::is_sorted(RawComments.begin(), RawComments.end(),
70                           BeforeThanCompare<RawComment>(SourceMgr)));
71 #endif
72 
73     CommentsLoaded = true;
74   }
75 
76   assert(D);
77 
78   // User can not attach documentation to implicit declarations.
79   if (D->isImplicit())
80     return nullptr;
81 
82   // User can not attach documentation to implicit instantiations.
83   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
84     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
85       return nullptr;
86   }
87 
88   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
89     if (VD->isStaticDataMember() &&
90         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
91       return nullptr;
92   }
93 
94   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
95     if (CRD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
96       return nullptr;
97   }
98 
99   if (const ClassTemplateSpecializationDecl *CTSD =
100           dyn_cast<ClassTemplateSpecializationDecl>(D)) {
101     TemplateSpecializationKind TSK = CTSD->getSpecializationKind();
102     if (TSK == TSK_ImplicitInstantiation ||
103         TSK == TSK_Undeclared)
104       return nullptr;
105   }
106 
107   if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
108     if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
109       return nullptr;
110   }
111   if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
112     // When tag declaration (but not definition!) is part of the
113     // decl-specifier-seq of some other declaration, it doesn't get comment
114     if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
115       return nullptr;
116   }
117   // TODO: handle comments for function parameters properly.
118   if (isa<ParmVarDecl>(D))
119     return nullptr;
120 
121   // TODO: we could look up template parameter documentation in the template
122   // documentation.
123   if (isa<TemplateTypeParmDecl>(D) ||
124       isa<NonTypeTemplateParmDecl>(D) ||
125       isa<TemplateTemplateParmDecl>(D))
126     return nullptr;
127 
128   ArrayRef<RawComment *> RawComments = Comments.getComments();
129 
130   // If there are no comments anywhere, we won't find anything.
131   if (RawComments.empty())
132     return nullptr;
133 
134   // Find declaration location.
135   // For Objective-C declarations we generally don't expect to have multiple
136   // declarators, thus use declaration starting location as the "declaration
137   // location".
138   // For all other declarations multiple declarators are used quite frequently,
139   // so we use the location of the identifier as the "declaration location".
140   SourceLocation DeclLoc;
141   if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) ||
142       isa<ObjCPropertyDecl>(D) ||
143       isa<RedeclarableTemplateDecl>(D) ||
144       isa<ClassTemplateSpecializationDecl>(D))
145     DeclLoc = D->getLocStart();
146   else {
147     DeclLoc = D->getLocation();
148     if (DeclLoc.isMacroID()) {
149       if (isa<TypedefDecl>(D)) {
150         // If location of the typedef name is in a macro, it is because being
151         // declared via a macro. Try using declaration's starting location as
152         // the "declaration location".
153         DeclLoc = D->getLocStart();
154       } else if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
155         // If location of the tag decl is inside a macro, but the spelling of
156         // the tag name comes from a macro argument, it looks like a special
157         // macro like NS_ENUM is being used to define the tag decl.  In that
158         // case, adjust the source location to the expansion loc so that we can
159         // attach the comment to the tag decl.
160         if (SourceMgr.isMacroArgExpansion(DeclLoc) &&
161             TD->isCompleteDefinition())
162           DeclLoc = SourceMgr.getExpansionLoc(DeclLoc);
163       }
164     }
165   }
166 
167   // If the declaration doesn't map directly to a location in a file, we
168   // can't find the comment.
169   if (DeclLoc.isInvalid() || !DeclLoc.isFileID())
170     return nullptr;
171 
172   // Find the comment that occurs just after this declaration.
173   ArrayRef<RawComment *>::iterator Comment;
174   {
175     // When searching for comments during parsing, the comment we are looking
176     // for is usually among the last two comments we parsed -- check them
177     // first.
178     RawComment CommentAtDeclLoc(
179         SourceMgr, SourceRange(DeclLoc), false,
180         LangOpts.CommentOpts.ParseAllComments);
181     BeforeThanCompare<RawComment> Compare(SourceMgr);
182     ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
183     bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
184     if (!Found && RawComments.size() >= 2) {
185       MaybeBeforeDecl--;
186       Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
187     }
188 
189     if (Found) {
190       Comment = MaybeBeforeDecl + 1;
191       assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(),
192                                          &CommentAtDeclLoc, Compare));
193     } else {
194       // Slow path.
195       Comment = std::lower_bound(RawComments.begin(), RawComments.end(),
196                                  &CommentAtDeclLoc, Compare);
197     }
198   }
199 
200   // Decompose the location for the declaration and find the beginning of the
201   // file buffer.
202   std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc);
203 
204   // First check whether we have a trailing comment.
205   if (Comment != RawComments.end() &&
206       (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() &&
207       (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D) ||
208        isa<ObjCMethodDecl>(D) || isa<ObjCPropertyDecl>(D))) {
209     std::pair<FileID, unsigned> CommentBeginDecomp
210       = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin());
211     // Check that Doxygen trailing comment comes after the declaration, starts
212     // on the same line and in the same file as the declaration.
213     if (DeclLocDecomp.first == CommentBeginDecomp.first &&
214         SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second)
215           == SourceMgr.getLineNumber(CommentBeginDecomp.first,
216                                      CommentBeginDecomp.second)) {
217       return *Comment;
218     }
219   }
220 
221   // The comment just after the declaration was not a trailing comment.
222   // Let's look at the previous comment.
223   if (Comment == RawComments.begin())
224     return nullptr;
225   --Comment;
226 
227   // Check that we actually have a non-member Doxygen comment.
228   if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment())
229     return nullptr;
230 
231   // Decompose the end of the comment.
232   std::pair<FileID, unsigned> CommentEndDecomp
233     = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd());
234 
235   // If the comment and the declaration aren't in the same file, then they
236   // aren't related.
237   if (DeclLocDecomp.first != CommentEndDecomp.first)
238     return nullptr;
239 
240   // Get the corresponding buffer.
241   bool Invalid = false;
242   const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first,
243                                                &Invalid).data();
244   if (Invalid)
245     return nullptr;
246 
247   // Extract text between the comment and declaration.
248   StringRef Text(Buffer + CommentEndDecomp.second,
249                  DeclLocDecomp.second - CommentEndDecomp.second);
250 
251   // There should be no other declarations or preprocessor directives between
252   // comment and declaration.
253   if (Text.find_first_of(";{}#@") != StringRef::npos)
254     return nullptr;
255 
256   return *Comment;
257 }
258 
259 namespace {
260 /// If we have a 'templated' declaration for a template, adjust 'D' to
261 /// refer to the actual template.
262 /// If we have an implicit instantiation, adjust 'D' to refer to template.
adjustDeclToTemplate(const Decl * D)263 const Decl *adjustDeclToTemplate(const Decl *D) {
264   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
265     // Is this function declaration part of a function template?
266     if (const FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
267       return FTD;
268 
269     // Nothing to do if function is not an implicit instantiation.
270     if (FD->getTemplateSpecializationKind() != TSK_ImplicitInstantiation)
271       return D;
272 
273     // Function is an implicit instantiation of a function template?
274     if (const FunctionTemplateDecl *FTD = FD->getPrimaryTemplate())
275       return FTD;
276 
277     // Function is instantiated from a member definition of a class template?
278     if (const FunctionDecl *MemberDecl =
279             FD->getInstantiatedFromMemberFunction())
280       return MemberDecl;
281 
282     return D;
283   }
284   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
285     // Static data member is instantiated from a member definition of a class
286     // template?
287     if (VD->isStaticDataMember())
288       if (const VarDecl *MemberDecl = VD->getInstantiatedFromStaticDataMember())
289         return MemberDecl;
290 
291     return D;
292   }
293   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
294     // Is this class declaration part of a class template?
295     if (const ClassTemplateDecl *CTD = CRD->getDescribedClassTemplate())
296       return CTD;
297 
298     // Class is an implicit instantiation of a class template or partial
299     // specialization?
300     if (const ClassTemplateSpecializationDecl *CTSD =
301             dyn_cast<ClassTemplateSpecializationDecl>(CRD)) {
302       if (CTSD->getSpecializationKind() != TSK_ImplicitInstantiation)
303         return D;
304       llvm::PointerUnion<ClassTemplateDecl *,
305                          ClassTemplatePartialSpecializationDecl *>
306           PU = CTSD->getSpecializedTemplateOrPartial();
307       return PU.is<ClassTemplateDecl*>() ?
308           static_cast<const Decl*>(PU.get<ClassTemplateDecl *>()) :
309           static_cast<const Decl*>(
310               PU.get<ClassTemplatePartialSpecializationDecl *>());
311     }
312 
313     // Class is instantiated from a member definition of a class template?
314     if (const MemberSpecializationInfo *Info =
315                    CRD->getMemberSpecializationInfo())
316       return Info->getInstantiatedFrom();
317 
318     return D;
319   }
320   if (const EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
321     // Enum is instantiated from a member definition of a class template?
322     if (const EnumDecl *MemberDecl = ED->getInstantiatedFromMemberEnum())
323       return MemberDecl;
324 
325     return D;
326   }
327   // FIXME: Adjust alias templates?
328   return D;
329 }
330 } // unnamed namespace
331 
getRawCommentForAnyRedecl(const Decl * D,const Decl ** OriginalDecl) const332 const RawComment *ASTContext::getRawCommentForAnyRedecl(
333                                                 const Decl *D,
334                                                 const Decl **OriginalDecl) const {
335   D = adjustDeclToTemplate(D);
336 
337   // Check whether we have cached a comment for this declaration already.
338   {
339     llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
340         RedeclComments.find(D);
341     if (Pos != RedeclComments.end()) {
342       const RawCommentAndCacheFlags &Raw = Pos->second;
343       if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
344         if (OriginalDecl)
345           *OriginalDecl = Raw.getOriginalDecl();
346         return Raw.getRaw();
347       }
348     }
349   }
350 
351   // Search for comments attached to declarations in the redeclaration chain.
352   const RawComment *RC = nullptr;
353   const Decl *OriginalDeclForRC = nullptr;
354   for (auto I : D->redecls()) {
355     llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos =
356         RedeclComments.find(I);
357     if (Pos != RedeclComments.end()) {
358       const RawCommentAndCacheFlags &Raw = Pos->second;
359       if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) {
360         RC = Raw.getRaw();
361         OriginalDeclForRC = Raw.getOriginalDecl();
362         break;
363       }
364     } else {
365       RC = getRawCommentForDeclNoCache(I);
366       OriginalDeclForRC = I;
367       RawCommentAndCacheFlags Raw;
368       if (RC) {
369         Raw.setRaw(RC);
370         Raw.setKind(RawCommentAndCacheFlags::FromDecl);
371       } else
372         Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl);
373       Raw.setOriginalDecl(I);
374       RedeclComments[I] = Raw;
375       if (RC)
376         break;
377     }
378   }
379 
380   // If we found a comment, it should be a documentation comment.
381   assert(!RC || RC->isDocumentation());
382 
383   if (OriginalDecl)
384     *OriginalDecl = OriginalDeclForRC;
385 
386   // Update cache for every declaration in the redeclaration chain.
387   RawCommentAndCacheFlags Raw;
388   Raw.setRaw(RC);
389   Raw.setKind(RawCommentAndCacheFlags::FromRedecl);
390   Raw.setOriginalDecl(OriginalDeclForRC);
391 
392   for (auto I : D->redecls()) {
393     RawCommentAndCacheFlags &R = RedeclComments[I];
394     if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl)
395       R = Raw;
396   }
397 
398   return RC;
399 }
400 
addRedeclaredMethods(const ObjCMethodDecl * ObjCMethod,SmallVectorImpl<const NamedDecl * > & Redeclared)401 static void addRedeclaredMethods(const ObjCMethodDecl *ObjCMethod,
402                    SmallVectorImpl<const NamedDecl *> &Redeclared) {
403   const DeclContext *DC = ObjCMethod->getDeclContext();
404   if (const ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(DC)) {
405     const ObjCInterfaceDecl *ID = IMD->getClassInterface();
406     if (!ID)
407       return;
408     // Add redeclared method here.
409     for (const auto *Ext : ID->known_extensions()) {
410       if (ObjCMethodDecl *RedeclaredMethod =
411             Ext->getMethod(ObjCMethod->getSelector(),
412                                   ObjCMethod->isInstanceMethod()))
413         Redeclared.push_back(RedeclaredMethod);
414     }
415   }
416 }
417 
cloneFullComment(comments::FullComment * FC,const Decl * D) const418 comments::FullComment *ASTContext::cloneFullComment(comments::FullComment *FC,
419                                                     const Decl *D) const {
420   comments::DeclInfo *ThisDeclInfo = new (*this) comments::DeclInfo;
421   ThisDeclInfo->CommentDecl = D;
422   ThisDeclInfo->IsFilled = false;
423   ThisDeclInfo->fill();
424   ThisDeclInfo->CommentDecl = FC->getDecl();
425   if (!ThisDeclInfo->TemplateParameters)
426     ThisDeclInfo->TemplateParameters = FC->getDeclInfo()->TemplateParameters;
427   comments::FullComment *CFC =
428     new (*this) comments::FullComment(FC->getBlocks(),
429                                       ThisDeclInfo);
430   return CFC;
431 
432 }
433 
getLocalCommentForDeclUncached(const Decl * D) const434 comments::FullComment *ASTContext::getLocalCommentForDeclUncached(const Decl *D) const {
435   const RawComment *RC = getRawCommentForDeclNoCache(D);
436   return RC ? RC->parse(*this, nullptr, D) : nullptr;
437 }
438 
getCommentForDecl(const Decl * D,const Preprocessor * PP) const439 comments::FullComment *ASTContext::getCommentForDecl(
440                                               const Decl *D,
441                                               const Preprocessor *PP) const {
442   if (D->isInvalidDecl())
443     return nullptr;
444   D = adjustDeclToTemplate(D);
445 
446   const Decl *Canonical = D->getCanonicalDecl();
447   llvm::DenseMap<const Decl *, comments::FullComment *>::iterator Pos =
448       ParsedComments.find(Canonical);
449 
450   if (Pos != ParsedComments.end()) {
451     if (Canonical != D) {
452       comments::FullComment *FC = Pos->second;
453       comments::FullComment *CFC = cloneFullComment(FC, D);
454       return CFC;
455     }
456     return Pos->second;
457   }
458 
459   const Decl *OriginalDecl;
460 
461   const RawComment *RC = getRawCommentForAnyRedecl(D, &OriginalDecl);
462   if (!RC) {
463     if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) {
464       SmallVector<const NamedDecl*, 8> Overridden;
465       const ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(D);
466       if (OMD && OMD->isPropertyAccessor())
467         if (const ObjCPropertyDecl *PDecl = OMD->findPropertyDecl())
468           if (comments::FullComment *FC = getCommentForDecl(PDecl, PP))
469             return cloneFullComment(FC, D);
470       if (OMD)
471         addRedeclaredMethods(OMD, Overridden);
472       getOverriddenMethods(dyn_cast<NamedDecl>(D), Overridden);
473       for (unsigned i = 0, e = Overridden.size(); i < e; i++)
474         if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
475           return cloneFullComment(FC, D);
476     }
477     else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
478       // Attach any tag type's documentation to its typedef if latter
479       // does not have one of its own.
480       QualType QT = TD->getUnderlyingType();
481       if (const TagType *TT = QT->getAs<TagType>())
482         if (const Decl *TD = TT->getDecl())
483           if (comments::FullComment *FC = getCommentForDecl(TD, PP))
484             return cloneFullComment(FC, D);
485     }
486     else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
487       while (IC->getSuperClass()) {
488         IC = IC->getSuperClass();
489         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
490           return cloneFullComment(FC, D);
491       }
492     }
493     else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
494       if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
495         if (comments::FullComment *FC = getCommentForDecl(IC, PP))
496           return cloneFullComment(FC, D);
497     }
498     else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
499       if (!(RD = RD->getDefinition()))
500         return nullptr;
501       // Check non-virtual bases.
502       for (const auto &I : RD->bases()) {
503         if (I.isVirtual() || (I.getAccessSpecifier() != AS_public))
504           continue;
505         QualType Ty = I.getType();
506         if (Ty.isNull())
507           continue;
508         if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
509           if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
510             continue;
511 
512           if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
513             return cloneFullComment(FC, D);
514         }
515       }
516       // Check virtual bases.
517       for (const auto &I : RD->vbases()) {
518         if (I.getAccessSpecifier() != AS_public)
519           continue;
520         QualType Ty = I.getType();
521         if (Ty.isNull())
522           continue;
523         if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
524           if (!(VirtualBase= VirtualBase->getDefinition()))
525             continue;
526           if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
527             return cloneFullComment(FC, D);
528         }
529       }
530     }
531     return nullptr;
532   }
533 
534   // If the RawComment was attached to other redeclaration of this Decl, we
535   // should parse the comment in context of that other Decl.  This is important
536   // because comments can contain references to parameter names which can be
537   // different across redeclarations.
538   if (D != OriginalDecl)
539     return getCommentForDecl(OriginalDecl, PP);
540 
541   comments::FullComment *FC = RC->parse(*this, PP, D);
542   ParsedComments[Canonical] = FC;
543   return FC;
544 }
545 
546 void
Profile(llvm::FoldingSetNodeID & ID,TemplateTemplateParmDecl * Parm)547 ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID,
548                                                TemplateTemplateParmDecl *Parm) {
549   ID.AddInteger(Parm->getDepth());
550   ID.AddInteger(Parm->getPosition());
551   ID.AddBoolean(Parm->isParameterPack());
552 
553   TemplateParameterList *Params = Parm->getTemplateParameters();
554   ID.AddInteger(Params->size());
555   for (TemplateParameterList::const_iterator P = Params->begin(),
556                                           PEnd = Params->end();
557        P != PEnd; ++P) {
558     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) {
559       ID.AddInteger(0);
560       ID.AddBoolean(TTP->isParameterPack());
561       continue;
562     }
563 
564     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
565       ID.AddInteger(1);
566       ID.AddBoolean(NTTP->isParameterPack());
567       ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr());
568       if (NTTP->isExpandedParameterPack()) {
569         ID.AddBoolean(true);
570         ID.AddInteger(NTTP->getNumExpansionTypes());
571         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
572           QualType T = NTTP->getExpansionType(I);
573           ID.AddPointer(T.getCanonicalType().getAsOpaquePtr());
574         }
575       } else
576         ID.AddBoolean(false);
577       continue;
578     }
579 
580     TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
581     ID.AddInteger(2);
582     Profile(ID, TTP);
583   }
584 }
585 
586 TemplateTemplateParmDecl *
getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl * TTP) const587 ASTContext::getCanonicalTemplateTemplateParmDecl(
588                                           TemplateTemplateParmDecl *TTP) const {
589   // Check if we already have a canonical template template parameter.
590   llvm::FoldingSetNodeID ID;
591   CanonicalTemplateTemplateParm::Profile(ID, TTP);
592   void *InsertPos = nullptr;
593   CanonicalTemplateTemplateParm *Canonical
594     = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
595   if (Canonical)
596     return Canonical->getParam();
597 
598   // Build a canonical template parameter list.
599   TemplateParameterList *Params = TTP->getTemplateParameters();
600   SmallVector<NamedDecl *, 4> CanonParams;
601   CanonParams.reserve(Params->size());
602   for (TemplateParameterList::const_iterator P = Params->begin(),
603                                           PEnd = Params->end();
604        P != PEnd; ++P) {
605     if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P))
606       CanonParams.push_back(
607                   TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(),
608                                                SourceLocation(),
609                                                SourceLocation(),
610                                                TTP->getDepth(),
611                                                TTP->getIndex(), nullptr, false,
612                                                TTP->isParameterPack()));
613     else if (NonTypeTemplateParmDecl *NTTP
614              = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
615       QualType T = getCanonicalType(NTTP->getType());
616       TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
617       NonTypeTemplateParmDecl *Param;
618       if (NTTP->isExpandedParameterPack()) {
619         SmallVector<QualType, 2> ExpandedTypes;
620         SmallVector<TypeSourceInfo *, 2> ExpandedTInfos;
621         for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
622           ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I)));
623           ExpandedTInfos.push_back(
624                                 getTrivialTypeSourceInfo(ExpandedTypes.back()));
625         }
626 
627         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
628                                                 SourceLocation(),
629                                                 SourceLocation(),
630                                                 NTTP->getDepth(),
631                                                 NTTP->getPosition(), nullptr,
632                                                 T,
633                                                 TInfo,
634                                                 ExpandedTypes.data(),
635                                                 ExpandedTypes.size(),
636                                                 ExpandedTInfos.data());
637       } else {
638         Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
639                                                 SourceLocation(),
640                                                 SourceLocation(),
641                                                 NTTP->getDepth(),
642                                                 NTTP->getPosition(), nullptr,
643                                                 T,
644                                                 NTTP->isParameterPack(),
645                                                 TInfo);
646       }
647       CanonParams.push_back(Param);
648 
649     } else
650       CanonParams.push_back(getCanonicalTemplateTemplateParmDecl(
651                                            cast<TemplateTemplateParmDecl>(*P)));
652   }
653 
654   TemplateTemplateParmDecl *CanonTTP
655     = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(),
656                                        SourceLocation(), TTP->getDepth(),
657                                        TTP->getPosition(),
658                                        TTP->isParameterPack(),
659                                        nullptr,
660                          TemplateParameterList::Create(*this, SourceLocation(),
661                                                        SourceLocation(),
662                                                        CanonParams.data(),
663                                                        CanonParams.size(),
664                                                        SourceLocation()));
665 
666   // Get the new insert position for the node we care about.
667   Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos);
668   assert(!Canonical && "Shouldn't be in the map!");
669   (void)Canonical;
670 
671   // Create the canonical template template parameter entry.
672   Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP);
673   CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos);
674   return CanonTTP;
675 }
676 
createCXXABI(const TargetInfo & T)677 CXXABI *ASTContext::createCXXABI(const TargetInfo &T) {
678   if (!LangOpts.CPlusPlus) return nullptr;
679 
680   switch (T.getCXXABI().getKind()) {
681   case TargetCXXABI::GenericARM: // Same as Itanium at this level
682   case TargetCXXABI::iOS:
683   case TargetCXXABI::iOS64:
684   case TargetCXXABI::GenericAArch64:
685   case TargetCXXABI::GenericMIPS:
686   case TargetCXXABI::GenericItanium:
687     return CreateItaniumCXXABI(*this);
688   case TargetCXXABI::Microsoft:
689     return CreateMicrosoftCXXABI(*this);
690   }
691   llvm_unreachable("Invalid CXXABI type!");
692 }
693 
getAddressSpaceMap(const TargetInfo & T,const LangOptions & LOpts)694 static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T,
695                                              const LangOptions &LOpts) {
696   if (LOpts.FakeAddressSpaceMap) {
697     // The fake address space map must have a distinct entry for each
698     // language-specific address space.
699     static const unsigned FakeAddrSpaceMap[] = {
700       1, // opencl_global
701       2, // opencl_local
702       3, // opencl_constant
703       4, // opencl_generic
704       5, // cuda_device
705       6, // cuda_constant
706       7  // cuda_shared
707     };
708     return &FakeAddrSpaceMap;
709   } else {
710     return &T.getAddressSpaceMap();
711   }
712 }
713 
isAddrSpaceMapManglingEnabled(const TargetInfo & TI,const LangOptions & LangOpts)714 static bool isAddrSpaceMapManglingEnabled(const TargetInfo &TI,
715                                           const LangOptions &LangOpts) {
716   switch (LangOpts.getAddressSpaceMapMangling()) {
717   case LangOptions::ASMM_Target:
718     return TI.useAddressSpaceMapMangling();
719   case LangOptions::ASMM_On:
720     return true;
721   case LangOptions::ASMM_Off:
722     return false;
723   }
724   llvm_unreachable("getAddressSpaceMapMangling() doesn't cover anything.");
725 }
726 
ASTContext(LangOptions & LOpts,SourceManager & SM,IdentifierTable & idents,SelectorTable & sels,Builtin::Context & builtins)727 ASTContext::ASTContext(LangOptions &LOpts, SourceManager &SM,
728                        IdentifierTable &idents, SelectorTable &sels,
729                        Builtin::Context &builtins)
730     : FunctionProtoTypes(this_()), TemplateSpecializationTypes(this_()),
731       DependentTemplateSpecializationTypes(this_()),
732       SubstTemplateTemplateParmPacks(this_()),
733       GlobalNestedNameSpecifier(nullptr), Int128Decl(nullptr),
734       UInt128Decl(nullptr), Float128StubDecl(nullptr),
735       BuiltinVaListDecl(nullptr), ObjCIdDecl(nullptr), ObjCSelDecl(nullptr),
736       ObjCClassDecl(nullptr), ObjCProtocolClassDecl(nullptr), BOOLDecl(nullptr),
737       CFConstantStringTypeDecl(nullptr), ObjCInstanceTypeDecl(nullptr),
738       FILEDecl(nullptr), jmp_bufDecl(nullptr), sigjmp_bufDecl(nullptr),
739       ucontext_tDecl(nullptr), BlockDescriptorType(nullptr),
740       BlockDescriptorExtendedType(nullptr), cudaConfigureCallDecl(nullptr),
741       FirstLocalImport(), LastLocalImport(), ExternCContext(nullptr),
742       SourceMgr(SM), LangOpts(LOpts),
743       SanitizerBL(new SanitizerBlacklist(LangOpts.SanitizerBlacklistFiles, SM)),
744       AddrSpaceMap(nullptr), Target(nullptr), PrintingPolicy(LOpts),
745       Idents(idents), Selectors(sels), BuiltinInfo(builtins),
746       DeclarationNames(*this), ExternalSource(nullptr), Listener(nullptr),
747       Comments(SM), CommentsLoaded(false),
748       CommentCommandTraits(BumpAlloc, LOpts.CommentOpts), LastSDM(nullptr, 0) {
749   TUDecl = TranslationUnitDecl::Create(*this);
750 }
751 
~ASTContext()752 ASTContext::~ASTContext() {
753   ReleaseParentMapEntries();
754 
755   // Release the DenseMaps associated with DeclContext objects.
756   // FIXME: Is this the ideal solution?
757   ReleaseDeclContextMaps();
758 
759   // Call all of the deallocation functions on all of their targets.
760   for (DeallocationMap::const_iterator I = Deallocations.begin(),
761            E = Deallocations.end(); I != E; ++I)
762     for (unsigned J = 0, N = I->second.size(); J != N; ++J)
763       (I->first)((I->second)[J]);
764 
765   // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed
766   // because they can contain DenseMaps.
767   for (llvm::DenseMap<const ObjCContainerDecl*,
768        const ASTRecordLayout*>::iterator
769        I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; )
770     // Increment in loop to prevent using deallocated memory.
771     if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
772       R->Destroy(*this);
773 
774   for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator
775        I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) {
776     // Increment in loop to prevent using deallocated memory.
777     if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second))
778       R->Destroy(*this);
779   }
780 
781   for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(),
782                                                     AEnd = DeclAttrs.end();
783        A != AEnd; ++A)
784     A->second->~AttrVec();
785 
786   llvm::DeleteContainerSeconds(MangleNumberingContexts);
787 }
788 
ReleaseParentMapEntries()789 void ASTContext::ReleaseParentMapEntries() {
790   if (!AllParents) return;
791   for (const auto &Entry : *AllParents) {
792     if (Entry.second.is<ast_type_traits::DynTypedNode *>()) {
793       delete Entry.second.get<ast_type_traits::DynTypedNode *>();
794     } else {
795       assert(Entry.second.is<ParentVector *>());
796       delete Entry.second.get<ParentVector *>();
797     }
798   }
799 }
800 
AddDeallocation(void (* Callback)(void *),void * Data)801 void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) {
802   Deallocations[Callback].push_back(Data);
803 }
804 
805 void
setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source)806 ASTContext::setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source) {
807   ExternalSource = Source;
808 }
809 
PrintStats() const810 void ASTContext::PrintStats() const {
811   llvm::errs() << "\n*** AST Context Stats:\n";
812   llvm::errs() << "  " << Types.size() << " types total.\n";
813 
814   unsigned counts[] = {
815 #define TYPE(Name, Parent) 0,
816 #define ABSTRACT_TYPE(Name, Parent)
817 #include "clang/AST/TypeNodes.def"
818     0 // Extra
819   };
820 
821   for (unsigned i = 0, e = Types.size(); i != e; ++i) {
822     Type *T = Types[i];
823     counts[(unsigned)T->getTypeClass()]++;
824   }
825 
826   unsigned Idx = 0;
827   unsigned TotalBytes = 0;
828 #define TYPE(Name, Parent)                                              \
829   if (counts[Idx])                                                      \
830     llvm::errs() << "    " << counts[Idx] << " " << #Name               \
831                  << " types\n";                                         \
832   TotalBytes += counts[Idx] * sizeof(Name##Type);                       \
833   ++Idx;
834 #define ABSTRACT_TYPE(Name, Parent)
835 #include "clang/AST/TypeNodes.def"
836 
837   llvm::errs() << "Total bytes = " << TotalBytes << "\n";
838 
839   // Implicit special member functions.
840   llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/"
841                << NumImplicitDefaultConstructors
842                << " implicit default constructors created\n";
843   llvm::errs() << NumImplicitCopyConstructorsDeclared << "/"
844                << NumImplicitCopyConstructors
845                << " implicit copy constructors created\n";
846   if (getLangOpts().CPlusPlus)
847     llvm::errs() << NumImplicitMoveConstructorsDeclared << "/"
848                  << NumImplicitMoveConstructors
849                  << " implicit move constructors created\n";
850   llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/"
851                << NumImplicitCopyAssignmentOperators
852                << " implicit copy assignment operators created\n";
853   if (getLangOpts().CPlusPlus)
854     llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/"
855                  << NumImplicitMoveAssignmentOperators
856                  << " implicit move assignment operators created\n";
857   llvm::errs() << NumImplicitDestructorsDeclared << "/"
858                << NumImplicitDestructors
859                << " implicit destructors created\n";
860 
861   if (ExternalSource) {
862     llvm::errs() << "\n";
863     ExternalSource->PrintStats();
864   }
865 
866   BumpAlloc.PrintStats();
867 }
868 
mergeDefinitionIntoModule(NamedDecl * ND,Module * M,bool NotifyListeners)869 void ASTContext::mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
870                                            bool NotifyListeners) {
871   if (NotifyListeners)
872     if (auto *Listener = getASTMutationListener())
873       Listener->RedefinedHiddenDefinition(ND, M);
874 
875   if (getLangOpts().ModulesLocalVisibility)
876     MergedDefModules[ND].push_back(M);
877   else
878     ND->setHidden(false);
879 }
880 
deduplicateMergedDefinitonsFor(NamedDecl * ND)881 void ASTContext::deduplicateMergedDefinitonsFor(NamedDecl *ND) {
882   auto It = MergedDefModules.find(ND);
883   if (It == MergedDefModules.end())
884     return;
885 
886   auto &Merged = It->second;
887   llvm::DenseSet<Module*> Found;
888   for (Module *&M : Merged)
889     if (!Found.insert(M).second)
890       M = nullptr;
891   Merged.erase(std::remove(Merged.begin(), Merged.end(), nullptr), Merged.end());
892 }
893 
getExternCContextDecl() const894 ExternCContextDecl *ASTContext::getExternCContextDecl() const {
895   if (!ExternCContext)
896     ExternCContext = ExternCContextDecl::Create(*this, getTranslationUnitDecl());
897 
898   return ExternCContext;
899 }
900 
buildImplicitRecord(StringRef Name,RecordDecl::TagKind TK) const901 RecordDecl *ASTContext::buildImplicitRecord(StringRef Name,
902                                             RecordDecl::TagKind TK) const {
903   SourceLocation Loc;
904   RecordDecl *NewDecl;
905   if (getLangOpts().CPlusPlus)
906     NewDecl = CXXRecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc,
907                                     Loc, &Idents.get(Name));
908   else
909     NewDecl = RecordDecl::Create(*this, TK, getTranslationUnitDecl(), Loc, Loc,
910                                  &Idents.get(Name));
911   NewDecl->setImplicit();
912   NewDecl->addAttr(TypeVisibilityAttr::CreateImplicit(
913       const_cast<ASTContext &>(*this), TypeVisibilityAttr::Default));
914   return NewDecl;
915 }
916 
buildImplicitTypedef(QualType T,StringRef Name) const917 TypedefDecl *ASTContext::buildImplicitTypedef(QualType T,
918                                               StringRef Name) const {
919   TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T);
920   TypedefDecl *NewDecl = TypedefDecl::Create(
921       const_cast<ASTContext &>(*this), getTranslationUnitDecl(),
922       SourceLocation(), SourceLocation(), &Idents.get(Name), TInfo);
923   NewDecl->setImplicit();
924   return NewDecl;
925 }
926 
getInt128Decl() const927 TypedefDecl *ASTContext::getInt128Decl() const {
928   if (!Int128Decl)
929     Int128Decl = buildImplicitTypedef(Int128Ty, "__int128_t");
930   return Int128Decl;
931 }
932 
getUInt128Decl() const933 TypedefDecl *ASTContext::getUInt128Decl() const {
934   if (!UInt128Decl)
935     UInt128Decl = buildImplicitTypedef(UnsignedInt128Ty, "__uint128_t");
936   return UInt128Decl;
937 }
938 
getFloat128StubType() const939 TypeDecl *ASTContext::getFloat128StubType() const {
940   assert(LangOpts.CPlusPlus && "should only be called for c++");
941   if (!Float128StubDecl)
942     Float128StubDecl = buildImplicitRecord("__float128");
943 
944   return Float128StubDecl;
945 }
946 
InitBuiltinType(CanQualType & R,BuiltinType::Kind K)947 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) {
948   BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K);
949   R = CanQualType::CreateUnsafe(QualType(Ty, 0));
950   Types.push_back(Ty);
951 }
952 
InitBuiltinTypes(const TargetInfo & Target)953 void ASTContext::InitBuiltinTypes(const TargetInfo &Target) {
954   assert((!this->Target || this->Target == &Target) &&
955          "Incorrect target reinitialization");
956   assert(VoidTy.isNull() && "Context reinitialized?");
957 
958   this->Target = &Target;
959 
960   ABI.reset(createCXXABI(Target));
961   AddrSpaceMap = getAddressSpaceMap(Target, LangOpts);
962   AddrSpaceMapMangling = isAddrSpaceMapManglingEnabled(Target, LangOpts);
963 
964   // C99 6.2.5p19.
965   InitBuiltinType(VoidTy,              BuiltinType::Void);
966 
967   // C99 6.2.5p2.
968   InitBuiltinType(BoolTy,              BuiltinType::Bool);
969   // C99 6.2.5p3.
970   if (LangOpts.CharIsSigned)
971     InitBuiltinType(CharTy,            BuiltinType::Char_S);
972   else
973     InitBuiltinType(CharTy,            BuiltinType::Char_U);
974   // C99 6.2.5p4.
975   InitBuiltinType(SignedCharTy,        BuiltinType::SChar);
976   InitBuiltinType(ShortTy,             BuiltinType::Short);
977   InitBuiltinType(IntTy,               BuiltinType::Int);
978   InitBuiltinType(LongTy,              BuiltinType::Long);
979   InitBuiltinType(LongLongTy,          BuiltinType::LongLong);
980 
981   // C99 6.2.5p6.
982   InitBuiltinType(UnsignedCharTy,      BuiltinType::UChar);
983   InitBuiltinType(UnsignedShortTy,     BuiltinType::UShort);
984   InitBuiltinType(UnsignedIntTy,       BuiltinType::UInt);
985   InitBuiltinType(UnsignedLongTy,      BuiltinType::ULong);
986   InitBuiltinType(UnsignedLongLongTy,  BuiltinType::ULongLong);
987 
988   // C99 6.2.5p10.
989   InitBuiltinType(FloatTy,             BuiltinType::Float);
990   InitBuiltinType(DoubleTy,            BuiltinType::Double);
991   InitBuiltinType(LongDoubleTy,        BuiltinType::LongDouble);
992 
993   // GNU extension, 128-bit integers.
994   InitBuiltinType(Int128Ty,            BuiltinType::Int128);
995   InitBuiltinType(UnsignedInt128Ty,    BuiltinType::UInt128);
996 
997   // C++ 3.9.1p5
998   if (TargetInfo::isTypeSigned(Target.getWCharType()))
999     InitBuiltinType(WCharTy,           BuiltinType::WChar_S);
1000   else  // -fshort-wchar makes wchar_t be unsigned.
1001     InitBuiltinType(WCharTy,           BuiltinType::WChar_U);
1002   if (LangOpts.CPlusPlus && LangOpts.WChar)
1003     WideCharTy = WCharTy;
1004   else {
1005     // C99 (or C++ using -fno-wchar).
1006     WideCharTy = getFromTargetType(Target.getWCharType());
1007   }
1008 
1009   WIntTy = getFromTargetType(Target.getWIntType());
1010 
1011   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1012     InitBuiltinType(Char16Ty,           BuiltinType::Char16);
1013   else // C99
1014     Char16Ty = getFromTargetType(Target.getChar16Type());
1015 
1016   if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++
1017     InitBuiltinType(Char32Ty,           BuiltinType::Char32);
1018   else // C99
1019     Char32Ty = getFromTargetType(Target.getChar32Type());
1020 
1021   // Placeholder type for type-dependent expressions whose type is
1022   // completely unknown. No code should ever check a type against
1023   // DependentTy and users should never see it; however, it is here to
1024   // help diagnose failures to properly check for type-dependent
1025   // expressions.
1026   InitBuiltinType(DependentTy,         BuiltinType::Dependent);
1027 
1028   // Placeholder type for functions.
1029   InitBuiltinType(OverloadTy,          BuiltinType::Overload);
1030 
1031   // Placeholder type for bound members.
1032   InitBuiltinType(BoundMemberTy,       BuiltinType::BoundMember);
1033 
1034   // Placeholder type for pseudo-objects.
1035   InitBuiltinType(PseudoObjectTy,      BuiltinType::PseudoObject);
1036 
1037   // "any" type; useful for debugger-like clients.
1038   InitBuiltinType(UnknownAnyTy,        BuiltinType::UnknownAny);
1039 
1040   // Placeholder type for unbridged ARC casts.
1041   InitBuiltinType(ARCUnbridgedCastTy,  BuiltinType::ARCUnbridgedCast);
1042 
1043   // Placeholder type for builtin functions.
1044   InitBuiltinType(BuiltinFnTy,  BuiltinType::BuiltinFn);
1045 
1046   // C99 6.2.5p11.
1047   FloatComplexTy      = getComplexType(FloatTy);
1048   DoubleComplexTy     = getComplexType(DoubleTy);
1049   LongDoubleComplexTy = getComplexType(LongDoubleTy);
1050 
1051   // Builtin types for 'id', 'Class', and 'SEL'.
1052   InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId);
1053   InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass);
1054   InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel);
1055 
1056   if (LangOpts.OpenCL) {
1057     InitBuiltinType(OCLImage1dTy, BuiltinType::OCLImage1d);
1058     InitBuiltinType(OCLImage1dArrayTy, BuiltinType::OCLImage1dArray);
1059     InitBuiltinType(OCLImage1dBufferTy, BuiltinType::OCLImage1dBuffer);
1060     InitBuiltinType(OCLImage2dTy, BuiltinType::OCLImage2d);
1061     InitBuiltinType(OCLImage2dArrayTy, BuiltinType::OCLImage2dArray);
1062     InitBuiltinType(OCLImage3dTy, BuiltinType::OCLImage3d);
1063 
1064     InitBuiltinType(OCLSamplerTy, BuiltinType::OCLSampler);
1065     InitBuiltinType(OCLEventTy, BuiltinType::OCLEvent);
1066   }
1067 
1068   // Builtin type for __objc_yes and __objc_no
1069   ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ?
1070                        SignedCharTy : BoolTy);
1071 
1072   ObjCConstantStringType = QualType();
1073 
1074   ObjCSuperType = QualType();
1075 
1076   // void * type
1077   VoidPtrTy = getPointerType(VoidTy);
1078 
1079   // nullptr type (C++0x 2.14.7)
1080   InitBuiltinType(NullPtrTy,           BuiltinType::NullPtr);
1081 
1082   // half type (OpenCL 6.1.1.1) / ARM NEON __fp16
1083   InitBuiltinType(HalfTy, BuiltinType::Half);
1084 
1085   // Builtin type used to help define __builtin_va_list.
1086   VaListTagTy = QualType();
1087 }
1088 
getDiagnostics() const1089 DiagnosticsEngine &ASTContext::getDiagnostics() const {
1090   return SourceMgr.getDiagnostics();
1091 }
1092 
getDeclAttrs(const Decl * D)1093 AttrVec& ASTContext::getDeclAttrs(const Decl *D) {
1094   AttrVec *&Result = DeclAttrs[D];
1095   if (!Result) {
1096     void *Mem = Allocate(sizeof(AttrVec));
1097     Result = new (Mem) AttrVec;
1098   }
1099 
1100   return *Result;
1101 }
1102 
1103 /// \brief Erase the attributes corresponding to the given declaration.
eraseDeclAttrs(const Decl * D)1104 void ASTContext::eraseDeclAttrs(const Decl *D) {
1105   llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D);
1106   if (Pos != DeclAttrs.end()) {
1107     Pos->second->~AttrVec();
1108     DeclAttrs.erase(Pos);
1109   }
1110 }
1111 
1112 // FIXME: Remove ?
1113 MemberSpecializationInfo *
getInstantiatedFromStaticDataMember(const VarDecl * Var)1114 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) {
1115   assert(Var->isStaticDataMember() && "Not a static data member");
1116   return getTemplateOrSpecializationInfo(Var)
1117       .dyn_cast<MemberSpecializationInfo *>();
1118 }
1119 
1120 ASTContext::TemplateOrSpecializationInfo
getTemplateOrSpecializationInfo(const VarDecl * Var)1121 ASTContext::getTemplateOrSpecializationInfo(const VarDecl *Var) {
1122   llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>::iterator Pos =
1123       TemplateOrInstantiation.find(Var);
1124   if (Pos == TemplateOrInstantiation.end())
1125     return TemplateOrSpecializationInfo();
1126 
1127   return Pos->second;
1128 }
1129 
1130 void
setInstantiatedFromStaticDataMember(VarDecl * Inst,VarDecl * Tmpl,TemplateSpecializationKind TSK,SourceLocation PointOfInstantiation)1131 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
1132                                                 TemplateSpecializationKind TSK,
1133                                           SourceLocation PointOfInstantiation) {
1134   assert(Inst->isStaticDataMember() && "Not a static data member");
1135   assert(Tmpl->isStaticDataMember() && "Not a static data member");
1136   setTemplateOrSpecializationInfo(Inst, new (*this) MemberSpecializationInfo(
1137                                             Tmpl, TSK, PointOfInstantiation));
1138 }
1139 
1140 void
setTemplateOrSpecializationInfo(VarDecl * Inst,TemplateOrSpecializationInfo TSI)1141 ASTContext::setTemplateOrSpecializationInfo(VarDecl *Inst,
1142                                             TemplateOrSpecializationInfo TSI) {
1143   assert(!TemplateOrInstantiation[Inst] &&
1144          "Already noted what the variable was instantiated from");
1145   TemplateOrInstantiation[Inst] = TSI;
1146 }
1147 
getClassScopeSpecializationPattern(const FunctionDecl * FD)1148 FunctionDecl *ASTContext::getClassScopeSpecializationPattern(
1149                                                      const FunctionDecl *FD){
1150   assert(FD && "Specialization is 0");
1151   llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos
1152     = ClassScopeSpecializationPattern.find(FD);
1153   if (Pos == ClassScopeSpecializationPattern.end())
1154     return nullptr;
1155 
1156   return Pos->second;
1157 }
1158 
setClassScopeSpecializationPattern(FunctionDecl * FD,FunctionDecl * Pattern)1159 void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD,
1160                                         FunctionDecl *Pattern) {
1161   assert(FD && "Specialization is 0");
1162   assert(Pattern && "Class scope specialization pattern is 0");
1163   ClassScopeSpecializationPattern[FD] = Pattern;
1164 }
1165 
1166 NamedDecl *
getInstantiatedFromUsingDecl(UsingDecl * UUD)1167 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) {
1168   llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos
1169     = InstantiatedFromUsingDecl.find(UUD);
1170   if (Pos == InstantiatedFromUsingDecl.end())
1171     return nullptr;
1172 
1173   return Pos->second;
1174 }
1175 
1176 void
setInstantiatedFromUsingDecl(UsingDecl * Inst,NamedDecl * Pattern)1177 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) {
1178   assert((isa<UsingDecl>(Pattern) ||
1179           isa<UnresolvedUsingValueDecl>(Pattern) ||
1180           isa<UnresolvedUsingTypenameDecl>(Pattern)) &&
1181          "pattern decl is not a using decl");
1182   assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists");
1183   InstantiatedFromUsingDecl[Inst] = Pattern;
1184 }
1185 
1186 UsingShadowDecl *
getInstantiatedFromUsingShadowDecl(UsingShadowDecl * Inst)1187 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) {
1188   llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos
1189     = InstantiatedFromUsingShadowDecl.find(Inst);
1190   if (Pos == InstantiatedFromUsingShadowDecl.end())
1191     return nullptr;
1192 
1193   return Pos->second;
1194 }
1195 
1196 void
setInstantiatedFromUsingShadowDecl(UsingShadowDecl * Inst,UsingShadowDecl * Pattern)1197 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
1198                                                UsingShadowDecl *Pattern) {
1199   assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists");
1200   InstantiatedFromUsingShadowDecl[Inst] = Pattern;
1201 }
1202 
getInstantiatedFromUnnamedFieldDecl(FieldDecl * Field)1203 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) {
1204   llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos
1205     = InstantiatedFromUnnamedFieldDecl.find(Field);
1206   if (Pos == InstantiatedFromUnnamedFieldDecl.end())
1207     return nullptr;
1208 
1209   return Pos->second;
1210 }
1211 
setInstantiatedFromUnnamedFieldDecl(FieldDecl * Inst,FieldDecl * Tmpl)1212 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst,
1213                                                      FieldDecl *Tmpl) {
1214   assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed");
1215   assert(!Tmpl->getDeclName() && "Template field decl is not unnamed");
1216   assert(!InstantiatedFromUnnamedFieldDecl[Inst] &&
1217          "Already noted what unnamed field was instantiated from");
1218 
1219   InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl;
1220 }
1221 
1222 ASTContext::overridden_cxx_method_iterator
overridden_methods_begin(const CXXMethodDecl * Method) const1223 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const {
1224   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1225     = OverriddenMethods.find(Method->getCanonicalDecl());
1226   if (Pos == OverriddenMethods.end())
1227     return nullptr;
1228 
1229   return Pos->second.begin();
1230 }
1231 
1232 ASTContext::overridden_cxx_method_iterator
overridden_methods_end(const CXXMethodDecl * Method) const1233 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const {
1234   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1235     = OverriddenMethods.find(Method->getCanonicalDecl());
1236   if (Pos == OverriddenMethods.end())
1237     return nullptr;
1238 
1239   return Pos->second.end();
1240 }
1241 
1242 unsigned
overridden_methods_size(const CXXMethodDecl * Method) const1243 ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const {
1244   llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos
1245     = OverriddenMethods.find(Method->getCanonicalDecl());
1246   if (Pos == OverriddenMethods.end())
1247     return 0;
1248 
1249   return Pos->second.size();
1250 }
1251 
addOverriddenMethod(const CXXMethodDecl * Method,const CXXMethodDecl * Overridden)1252 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method,
1253                                      const CXXMethodDecl *Overridden) {
1254   assert(Method->isCanonicalDecl() && Overridden->isCanonicalDecl());
1255   OverriddenMethods[Method].push_back(Overridden);
1256 }
1257 
getOverriddenMethods(const NamedDecl * D,SmallVectorImpl<const NamedDecl * > & Overridden) const1258 void ASTContext::getOverriddenMethods(
1259                       const NamedDecl *D,
1260                       SmallVectorImpl<const NamedDecl *> &Overridden) const {
1261   assert(D);
1262 
1263   if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
1264     Overridden.append(overridden_methods_begin(CXXMethod),
1265                       overridden_methods_end(CXXMethod));
1266     return;
1267   }
1268 
1269   const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
1270   if (!Method)
1271     return;
1272 
1273   SmallVector<const ObjCMethodDecl *, 8> OverDecls;
1274   Method->getOverriddenMethods(OverDecls);
1275   Overridden.append(OverDecls.begin(), OverDecls.end());
1276 }
1277 
addedLocalImportDecl(ImportDecl * Import)1278 void ASTContext::addedLocalImportDecl(ImportDecl *Import) {
1279   assert(!Import->NextLocalImport && "Import declaration already in the chain");
1280   assert(!Import->isFromASTFile() && "Non-local import declaration");
1281   if (!FirstLocalImport) {
1282     FirstLocalImport = Import;
1283     LastLocalImport = Import;
1284     return;
1285   }
1286 
1287   LastLocalImport->NextLocalImport = Import;
1288   LastLocalImport = Import;
1289 }
1290 
1291 //===----------------------------------------------------------------------===//
1292 //                         Type Sizing and Analysis
1293 //===----------------------------------------------------------------------===//
1294 
1295 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified
1296 /// scalar floating point type.
getFloatTypeSemantics(QualType T) const1297 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const {
1298   const BuiltinType *BT = T->getAs<BuiltinType>();
1299   assert(BT && "Not a floating point type!");
1300   switch (BT->getKind()) {
1301   default: llvm_unreachable("Not a floating point type!");
1302   case BuiltinType::Half:       return Target->getHalfFormat();
1303   case BuiltinType::Float:      return Target->getFloatFormat();
1304   case BuiltinType::Double:     return Target->getDoubleFormat();
1305   case BuiltinType::LongDouble: return Target->getLongDoubleFormat();
1306   }
1307 }
1308 
getDeclAlign(const Decl * D,bool ForAlignof) const1309 CharUnits ASTContext::getDeclAlign(const Decl *D, bool ForAlignof) const {
1310   unsigned Align = Target->getCharWidth();
1311 
1312   bool UseAlignAttrOnly = false;
1313   if (unsigned AlignFromAttr = D->getMaxAlignment()) {
1314     Align = AlignFromAttr;
1315 
1316     // __attribute__((aligned)) can increase or decrease alignment
1317     // *except* on a struct or struct member, where it only increases
1318     // alignment unless 'packed' is also specified.
1319     //
1320     // It is an error for alignas to decrease alignment, so we can
1321     // ignore that possibility;  Sema should diagnose it.
1322     if (isa<FieldDecl>(D)) {
1323       UseAlignAttrOnly = D->hasAttr<PackedAttr>() ||
1324         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1325     } else {
1326       UseAlignAttrOnly = true;
1327     }
1328   }
1329   else if (isa<FieldDecl>(D))
1330       UseAlignAttrOnly =
1331         D->hasAttr<PackedAttr>() ||
1332         cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>();
1333 
1334   // If we're using the align attribute only, just ignore everything
1335   // else about the declaration and its type.
1336   if (UseAlignAttrOnly) {
1337     // do nothing
1338 
1339   } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
1340     QualType T = VD->getType();
1341     if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
1342       if (ForAlignof)
1343         T = RT->getPointeeType();
1344       else
1345         T = getPointerType(RT->getPointeeType());
1346     }
1347     QualType BaseT = getBaseElementType(T);
1348     if (!BaseT->isIncompleteType() && !T->isFunctionType()) {
1349       // Adjust alignments of declarations with array type by the
1350       // large-array alignment on the target.
1351       if (const ArrayType *arrayType = getAsArrayType(T)) {
1352         unsigned MinWidth = Target->getLargeArrayMinWidth();
1353         if (!ForAlignof && MinWidth) {
1354           if (isa<VariableArrayType>(arrayType))
1355             Align = std::max(Align, Target->getLargeArrayAlign());
1356           else if (isa<ConstantArrayType>(arrayType) &&
1357                    MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType)))
1358             Align = std::max(Align, Target->getLargeArrayAlign());
1359         }
1360       }
1361       Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
1362       if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1363         if (VD->hasGlobalStorage() && !ForAlignof)
1364           Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
1365       }
1366     }
1367 
1368     // Fields can be subject to extra alignment constraints, like if
1369     // the field is packed, the struct is packed, or the struct has a
1370     // a max-field-alignment constraint (#pragma pack).  So calculate
1371     // the actual alignment of the field within the struct, and then
1372     // (as we're expected to) constrain that by the alignment of the type.
1373     if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
1374       const RecordDecl *Parent = Field->getParent();
1375       // We can only produce a sensible answer if the record is valid.
1376       if (!Parent->isInvalidDecl()) {
1377         const ASTRecordLayout &Layout = getASTRecordLayout(Parent);
1378 
1379         // Start with the record's overall alignment.
1380         unsigned FieldAlign = toBits(Layout.getAlignment());
1381 
1382         // Use the GCD of that and the offset within the record.
1383         uint64_t Offset = Layout.getFieldOffset(Field->getFieldIndex());
1384         if (Offset > 0) {
1385           // Alignment is always a power of 2, so the GCD will be a power of 2,
1386           // which means we get to do this crazy thing instead of Euclid's.
1387           uint64_t LowBitOfOffset = Offset & (~Offset + 1);
1388           if (LowBitOfOffset < FieldAlign)
1389             FieldAlign = static_cast<unsigned>(LowBitOfOffset);
1390         }
1391 
1392         Align = std::min(Align, FieldAlign);
1393       }
1394     }
1395   }
1396 
1397   return toCharUnitsFromBits(Align);
1398 }
1399 
1400 // getTypeInfoDataSizeInChars - Return the size of a type, in
1401 // chars. If the type is a record, its data size is returned.  This is
1402 // the size of the memcpy that's performed when assigning this type
1403 // using a trivial copy/move assignment operator.
1404 std::pair<CharUnits, CharUnits>
getTypeInfoDataSizeInChars(QualType T) const1405 ASTContext::getTypeInfoDataSizeInChars(QualType T) const {
1406   std::pair<CharUnits, CharUnits> sizeAndAlign = getTypeInfoInChars(T);
1407 
1408   // In C++, objects can sometimes be allocated into the tail padding
1409   // of a base-class subobject.  We decide whether that's possible
1410   // during class layout, so here we can just trust the layout results.
1411   if (getLangOpts().CPlusPlus) {
1412     if (const RecordType *RT = T->getAs<RecordType>()) {
1413       const ASTRecordLayout &layout = getASTRecordLayout(RT->getDecl());
1414       sizeAndAlign.first = layout.getDataSize();
1415     }
1416   }
1417 
1418   return sizeAndAlign;
1419 }
1420 
1421 /// getConstantArrayInfoInChars - Performing the computation in CharUnits
1422 /// instead of in bits prevents overflowing the uint64_t for some large arrays.
1423 std::pair<CharUnits, CharUnits>
getConstantArrayInfoInChars(const ASTContext & Context,const ConstantArrayType * CAT)1424 static getConstantArrayInfoInChars(const ASTContext &Context,
1425                                    const ConstantArrayType *CAT) {
1426   std::pair<CharUnits, CharUnits> EltInfo =
1427       Context.getTypeInfoInChars(CAT->getElementType());
1428   uint64_t Size = CAT->getSize().getZExtValue();
1429   assert((Size == 0 || static_cast<uint64_t>(EltInfo.first.getQuantity()) <=
1430               (uint64_t)(-1)/Size) &&
1431          "Overflow in array type char size evaluation");
1432   uint64_t Width = EltInfo.first.getQuantity() * Size;
1433   unsigned Align = EltInfo.second.getQuantity();
1434   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() ||
1435       Context.getTargetInfo().getPointerWidth(0) == 64)
1436     Width = llvm::RoundUpToAlignment(Width, Align);
1437   return std::make_pair(CharUnits::fromQuantity(Width),
1438                         CharUnits::fromQuantity(Align));
1439 }
1440 
1441 std::pair<CharUnits, CharUnits>
getTypeInfoInChars(const Type * T) const1442 ASTContext::getTypeInfoInChars(const Type *T) const {
1443   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T))
1444     return getConstantArrayInfoInChars(*this, CAT);
1445   TypeInfo Info = getTypeInfo(T);
1446   return std::make_pair(toCharUnitsFromBits(Info.Width),
1447                         toCharUnitsFromBits(Info.Align));
1448 }
1449 
1450 std::pair<CharUnits, CharUnits>
getTypeInfoInChars(QualType T) const1451 ASTContext::getTypeInfoInChars(QualType T) const {
1452   return getTypeInfoInChars(T.getTypePtr());
1453 }
1454 
isAlignmentRequired(const Type * T) const1455 bool ASTContext::isAlignmentRequired(const Type *T) const {
1456   return getTypeInfo(T).AlignIsRequired;
1457 }
1458 
isAlignmentRequired(QualType T) const1459 bool ASTContext::isAlignmentRequired(QualType T) const {
1460   return isAlignmentRequired(T.getTypePtr());
1461 }
1462 
getTypeInfo(const Type * T) const1463 TypeInfo ASTContext::getTypeInfo(const Type *T) const {
1464   TypeInfoMap::iterator I = MemoizedTypeInfo.find(T);
1465   if (I != MemoizedTypeInfo.end())
1466     return I->second;
1467 
1468   // This call can invalidate MemoizedTypeInfo[T], so we need a second lookup.
1469   TypeInfo TI = getTypeInfoImpl(T);
1470   MemoizedTypeInfo[T] = TI;
1471   return TI;
1472 }
1473 
1474 /// getTypeInfoImpl - Return the size of the specified type, in bits.  This
1475 /// method does not work on incomplete types.
1476 ///
1477 /// FIXME: Pointers into different addr spaces could have different sizes and
1478 /// alignment requirements: getPointerInfo should take an AddrSpace, this
1479 /// should take a QualType, &c.
getTypeInfoImpl(const Type * T) const1480 TypeInfo ASTContext::getTypeInfoImpl(const Type *T) const {
1481   uint64_t Width = 0;
1482   unsigned Align = 8;
1483   bool AlignIsRequired = false;
1484   switch (T->getTypeClass()) {
1485 #define TYPE(Class, Base)
1486 #define ABSTRACT_TYPE(Class, Base)
1487 #define NON_CANONICAL_TYPE(Class, Base)
1488 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
1489 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)                       \
1490   case Type::Class:                                                            \
1491   assert(!T->isDependentType() && "should not see dependent types here");      \
1492   return getTypeInfo(cast<Class##Type>(T)->desugar().getTypePtr());
1493 #include "clang/AST/TypeNodes.def"
1494     llvm_unreachable("Should not see dependent types");
1495 
1496   case Type::FunctionNoProto:
1497   case Type::FunctionProto:
1498     // GCC extension: alignof(function) = 32 bits
1499     Width = 0;
1500     Align = 32;
1501     break;
1502 
1503   case Type::IncompleteArray:
1504   case Type::VariableArray:
1505     Width = 0;
1506     Align = getTypeAlign(cast<ArrayType>(T)->getElementType());
1507     break;
1508 
1509   case Type::ConstantArray: {
1510     const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
1511 
1512     TypeInfo EltInfo = getTypeInfo(CAT->getElementType());
1513     uint64_t Size = CAT->getSize().getZExtValue();
1514     assert((Size == 0 || EltInfo.Width <= (uint64_t)(-1) / Size) &&
1515            "Overflow in array type bit size evaluation");
1516     Width = EltInfo.Width * Size;
1517     Align = EltInfo.Align;
1518     if (!getTargetInfo().getCXXABI().isMicrosoft() ||
1519         getTargetInfo().getPointerWidth(0) == 64)
1520       Width = llvm::RoundUpToAlignment(Width, Align);
1521     break;
1522   }
1523   case Type::ExtVector:
1524   case Type::Vector: {
1525     const VectorType *VT = cast<VectorType>(T);
1526     TypeInfo EltInfo = getTypeInfo(VT->getElementType());
1527     Width = EltInfo.Width * VT->getNumElements();
1528     Align = Width;
1529     // If the alignment is not a power of 2, round up to the next power of 2.
1530     // This happens for non-power-of-2 length vectors.
1531     if (Align & (Align-1)) {
1532       Align = llvm::NextPowerOf2(Align);
1533       Width = llvm::RoundUpToAlignment(Width, Align);
1534     }
1535     // Adjust the alignment based on the target max.
1536     uint64_t TargetVectorAlign = Target->getMaxVectorAlign();
1537     if (TargetVectorAlign && TargetVectorAlign < Align)
1538       Align = TargetVectorAlign;
1539     break;
1540   }
1541 
1542   case Type::Builtin:
1543     switch (cast<BuiltinType>(T)->getKind()) {
1544     default: llvm_unreachable("Unknown builtin type!");
1545     case BuiltinType::Void:
1546       // GCC extension: alignof(void) = 8 bits.
1547       Width = 0;
1548       Align = 8;
1549       break;
1550 
1551     case BuiltinType::Bool:
1552       Width = Target->getBoolWidth();
1553       Align = Target->getBoolAlign();
1554       break;
1555     case BuiltinType::Char_S:
1556     case BuiltinType::Char_U:
1557     case BuiltinType::UChar:
1558     case BuiltinType::SChar:
1559       Width = Target->getCharWidth();
1560       Align = Target->getCharAlign();
1561       break;
1562     case BuiltinType::WChar_S:
1563     case BuiltinType::WChar_U:
1564       Width = Target->getWCharWidth();
1565       Align = Target->getWCharAlign();
1566       break;
1567     case BuiltinType::Char16:
1568       Width = Target->getChar16Width();
1569       Align = Target->getChar16Align();
1570       break;
1571     case BuiltinType::Char32:
1572       Width = Target->getChar32Width();
1573       Align = Target->getChar32Align();
1574       break;
1575     case BuiltinType::UShort:
1576     case BuiltinType::Short:
1577       Width = Target->getShortWidth();
1578       Align = Target->getShortAlign();
1579       break;
1580     case BuiltinType::UInt:
1581     case BuiltinType::Int:
1582       Width = Target->getIntWidth();
1583       Align = Target->getIntAlign();
1584       break;
1585     case BuiltinType::ULong:
1586     case BuiltinType::Long:
1587       Width = Target->getLongWidth();
1588       Align = Target->getLongAlign();
1589       break;
1590     case BuiltinType::ULongLong:
1591     case BuiltinType::LongLong:
1592       Width = Target->getLongLongWidth();
1593       Align = Target->getLongLongAlign();
1594       break;
1595     case BuiltinType::Int128:
1596     case BuiltinType::UInt128:
1597       Width = 128;
1598       Align = 128; // int128_t is 128-bit aligned on all targets.
1599       break;
1600     case BuiltinType::Half:
1601       Width = Target->getHalfWidth();
1602       Align = Target->getHalfAlign();
1603       break;
1604     case BuiltinType::Float:
1605       Width = Target->getFloatWidth();
1606       Align = Target->getFloatAlign();
1607       break;
1608     case BuiltinType::Double:
1609       Width = Target->getDoubleWidth();
1610       Align = Target->getDoubleAlign();
1611       break;
1612     case BuiltinType::LongDouble:
1613       Width = Target->getLongDoubleWidth();
1614       Align = Target->getLongDoubleAlign();
1615       break;
1616     case BuiltinType::NullPtr:
1617       Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t)
1618       Align = Target->getPointerAlign(0); //   == sizeof(void*)
1619       break;
1620     case BuiltinType::ObjCId:
1621     case BuiltinType::ObjCClass:
1622     case BuiltinType::ObjCSel:
1623       Width = Target->getPointerWidth(0);
1624       Align = Target->getPointerAlign(0);
1625       break;
1626     case BuiltinType::OCLSampler:
1627       // Samplers are modeled as integers.
1628       Width = Target->getIntWidth();
1629       Align = Target->getIntAlign();
1630       break;
1631     case BuiltinType::OCLEvent:
1632     case BuiltinType::OCLImage1d:
1633     case BuiltinType::OCLImage1dArray:
1634     case BuiltinType::OCLImage1dBuffer:
1635     case BuiltinType::OCLImage2d:
1636     case BuiltinType::OCLImage2dArray:
1637     case BuiltinType::OCLImage3d:
1638       // Currently these types are pointers to opaque types.
1639       Width = Target->getPointerWidth(0);
1640       Align = Target->getPointerAlign(0);
1641       break;
1642     }
1643     break;
1644   case Type::ObjCObjectPointer:
1645     Width = Target->getPointerWidth(0);
1646     Align = Target->getPointerAlign(0);
1647     break;
1648   case Type::BlockPointer: {
1649     unsigned AS = getTargetAddressSpace(
1650         cast<BlockPointerType>(T)->getPointeeType());
1651     Width = Target->getPointerWidth(AS);
1652     Align = Target->getPointerAlign(AS);
1653     break;
1654   }
1655   case Type::LValueReference:
1656   case Type::RValueReference: {
1657     // alignof and sizeof should never enter this code path here, so we go
1658     // the pointer route.
1659     unsigned AS = getTargetAddressSpace(
1660         cast<ReferenceType>(T)->getPointeeType());
1661     Width = Target->getPointerWidth(AS);
1662     Align = Target->getPointerAlign(AS);
1663     break;
1664   }
1665   case Type::Pointer: {
1666     unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType());
1667     Width = Target->getPointerWidth(AS);
1668     Align = Target->getPointerAlign(AS);
1669     break;
1670   }
1671   case Type::MemberPointer: {
1672     const MemberPointerType *MPT = cast<MemberPointerType>(T);
1673     std::tie(Width, Align) = ABI->getMemberPointerWidthAndAlign(MPT);
1674     break;
1675   }
1676   case Type::Complex: {
1677     // Complex types have the same alignment as their elements, but twice the
1678     // size.
1679     TypeInfo EltInfo = getTypeInfo(cast<ComplexType>(T)->getElementType());
1680     Width = EltInfo.Width * 2;
1681     Align = EltInfo.Align;
1682     break;
1683   }
1684   case Type::ObjCObject:
1685     return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr());
1686   case Type::Adjusted:
1687   case Type::Decayed:
1688     return getTypeInfo(cast<AdjustedType>(T)->getAdjustedType().getTypePtr());
1689   case Type::ObjCInterface: {
1690     const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T);
1691     const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl());
1692     Width = toBits(Layout.getSize());
1693     Align = toBits(Layout.getAlignment());
1694     break;
1695   }
1696   case Type::Record:
1697   case Type::Enum: {
1698     const TagType *TT = cast<TagType>(T);
1699 
1700     if (TT->getDecl()->isInvalidDecl()) {
1701       Width = 8;
1702       Align = 8;
1703       break;
1704     }
1705 
1706     if (const EnumType *ET = dyn_cast<EnumType>(TT)) {
1707       const EnumDecl *ED = ET->getDecl();
1708       TypeInfo Info =
1709           getTypeInfo(ED->getIntegerType()->getUnqualifiedDesugaredType());
1710       if (unsigned AttrAlign = ED->getMaxAlignment()) {
1711         Info.Align = AttrAlign;
1712         Info.AlignIsRequired = true;
1713       }
1714       return Info;
1715     }
1716 
1717     const RecordType *RT = cast<RecordType>(TT);
1718     const RecordDecl *RD = RT->getDecl();
1719     const ASTRecordLayout &Layout = getASTRecordLayout(RD);
1720     Width = toBits(Layout.getSize());
1721     Align = toBits(Layout.getAlignment());
1722     AlignIsRequired = RD->hasAttr<AlignedAttr>();
1723     break;
1724   }
1725 
1726   case Type::SubstTemplateTypeParm:
1727     return getTypeInfo(cast<SubstTemplateTypeParmType>(T)->
1728                        getReplacementType().getTypePtr());
1729 
1730   case Type::Auto: {
1731     const AutoType *A = cast<AutoType>(T);
1732     assert(!A->getDeducedType().isNull() &&
1733            "cannot request the size of an undeduced or dependent auto type");
1734     return getTypeInfo(A->getDeducedType().getTypePtr());
1735   }
1736 
1737   case Type::Paren:
1738     return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr());
1739 
1740   case Type::Typedef: {
1741     const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl();
1742     TypeInfo Info = getTypeInfo(Typedef->getUnderlyingType().getTypePtr());
1743     // If the typedef has an aligned attribute on it, it overrides any computed
1744     // alignment we have.  This violates the GCC documentation (which says that
1745     // attribute(aligned) can only round up) but matches its implementation.
1746     if (unsigned AttrAlign = Typedef->getMaxAlignment()) {
1747       Align = AttrAlign;
1748       AlignIsRequired = true;
1749     } else {
1750       Align = Info.Align;
1751       AlignIsRequired = Info.AlignIsRequired;
1752     }
1753     Width = Info.Width;
1754     break;
1755   }
1756 
1757   case Type::Elaborated:
1758     return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr());
1759 
1760   case Type::Attributed:
1761     return getTypeInfo(
1762                   cast<AttributedType>(T)->getEquivalentType().getTypePtr());
1763 
1764   case Type::Atomic: {
1765     // Start with the base type information.
1766     TypeInfo Info = getTypeInfo(cast<AtomicType>(T)->getValueType());
1767     Width = Info.Width;
1768     Align = Info.Align;
1769 
1770     // If the size of the type doesn't exceed the platform's max
1771     // atomic promotion width, make the size and alignment more
1772     // favorable to atomic operations:
1773     if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth()) {
1774       // Round the size up to a power of 2.
1775       if (!llvm::isPowerOf2_64(Width))
1776         Width = llvm::NextPowerOf2(Width);
1777 
1778       // Set the alignment equal to the size.
1779       Align = static_cast<unsigned>(Width);
1780     }
1781   }
1782 
1783   }
1784 
1785   assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2");
1786   return TypeInfo(Width, Align, AlignIsRequired);
1787 }
1788 
getOpenMPDefaultSimdAlign(QualType T) const1789 unsigned ASTContext::getOpenMPDefaultSimdAlign(QualType T) const {
1790   unsigned SimdAlign = getTargetInfo().getSimdDefaultAlign();
1791   // Target ppc64 with QPX: simd default alignment for pointer to double is 32.
1792   if ((getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64 ||
1793        getTargetInfo().getTriple().getArch() == llvm::Triple::ppc64le) &&
1794       getTargetInfo().getABI() == "elfv1-qpx" &&
1795       T->isSpecificBuiltinType(BuiltinType::Double))
1796     SimdAlign = 256;
1797   return SimdAlign;
1798 }
1799 
1800 /// toCharUnitsFromBits - Convert a size in bits to a size in characters.
toCharUnitsFromBits(int64_t BitSize) const1801 CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const {
1802   return CharUnits::fromQuantity(BitSize / getCharWidth());
1803 }
1804 
1805 /// toBits - Convert a size in characters to a size in characters.
toBits(CharUnits CharSize) const1806 int64_t ASTContext::toBits(CharUnits CharSize) const {
1807   return CharSize.getQuantity() * getCharWidth();
1808 }
1809 
1810 /// getTypeSizeInChars - Return the size of the specified type, in characters.
1811 /// This method does not work on incomplete types.
getTypeSizeInChars(QualType T) const1812 CharUnits ASTContext::getTypeSizeInChars(QualType T) const {
1813   return getTypeInfoInChars(T).first;
1814 }
getTypeSizeInChars(const Type * T) const1815 CharUnits ASTContext::getTypeSizeInChars(const Type *T) const {
1816   return getTypeInfoInChars(T).first;
1817 }
1818 
1819 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in
1820 /// characters. This method does not work on incomplete types.
getTypeAlignInChars(QualType T) const1821 CharUnits ASTContext::getTypeAlignInChars(QualType T) const {
1822   return toCharUnitsFromBits(getTypeAlign(T));
1823 }
getTypeAlignInChars(const Type * T) const1824 CharUnits ASTContext::getTypeAlignInChars(const Type *T) const {
1825   return toCharUnitsFromBits(getTypeAlign(T));
1826 }
1827 
1828 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified
1829 /// type for the current target in bits.  This can be different than the ABI
1830 /// alignment in cases where it is beneficial for performance to overalign
1831 /// a data type.
getPreferredTypeAlign(const Type * T) const1832 unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
1833   TypeInfo TI = getTypeInfo(T);
1834   unsigned ABIAlign = TI.Align;
1835 
1836   T = T->getBaseElementTypeUnsafe();
1837 
1838   // The preferred alignment of member pointers is that of a pointer.
1839   if (T->isMemberPointerType())
1840     return getPreferredTypeAlign(getPointerDiffType().getTypePtr());
1841 
1842   if (Target->getTriple().getArch() == llvm::Triple::xcore)
1843     return ABIAlign;  // Never overalign on XCore.
1844 
1845   // Double and long long should be naturally aligned if possible.
1846   if (const ComplexType *CT = T->getAs<ComplexType>())
1847     T = CT->getElementType().getTypePtr();
1848   if (const EnumType *ET = T->getAs<EnumType>())
1849     T = ET->getDecl()->getIntegerType().getTypePtr();
1850   if (T->isSpecificBuiltinType(BuiltinType::Double) ||
1851       T->isSpecificBuiltinType(BuiltinType::LongLong) ||
1852       T->isSpecificBuiltinType(BuiltinType::ULongLong))
1853     // Don't increase the alignment if an alignment attribute was specified on a
1854     // typedef declaration.
1855     if (!TI.AlignIsRequired)
1856       return std::max(ABIAlign, (unsigned)getTypeSize(T));
1857 
1858   return ABIAlign;
1859 }
1860 
1861 /// getTargetDefaultAlignForAttributeAligned - Return the default alignment
1862 /// for __attribute__((aligned)) on this target, to be used if no alignment
1863 /// value is specified.
getTargetDefaultAlignForAttributeAligned(void) const1864 unsigned ASTContext::getTargetDefaultAlignForAttributeAligned(void) const {
1865   return getTargetInfo().getDefaultAlignForAttributeAligned();
1866 }
1867 
1868 /// getAlignOfGlobalVar - Return the alignment in bits that should be given
1869 /// to a global variable of the specified type.
getAlignOfGlobalVar(QualType T) const1870 unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
1871   return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
1872 }
1873 
1874 /// getAlignOfGlobalVarInChars - Return the alignment in characters that
1875 /// should be given to a global variable of the specified type.
getAlignOfGlobalVarInChars(QualType T) const1876 CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
1877   return toCharUnitsFromBits(getAlignOfGlobalVar(T));
1878 }
1879 
getOffsetOfBaseWithVBPtr(const CXXRecordDecl * RD) const1880 CharUnits ASTContext::getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const {
1881   CharUnits Offset = CharUnits::Zero();
1882   const ASTRecordLayout *Layout = &getASTRecordLayout(RD);
1883   while (const CXXRecordDecl *Base = Layout->getBaseSharingVBPtr()) {
1884     Offset += Layout->getBaseClassOffset(Base);
1885     Layout = &getASTRecordLayout(Base);
1886   }
1887   return Offset;
1888 }
1889 
1890 /// DeepCollectObjCIvars -
1891 /// This routine first collects all declared, but not synthesized, ivars in
1892 /// super class and then collects all ivars, including those synthesized for
1893 /// current class. This routine is used for implementation of current class
1894 /// when all ivars, declared and synthesized are known.
1895 ///
DeepCollectObjCIvars(const ObjCInterfaceDecl * OI,bool leafClass,SmallVectorImpl<const ObjCIvarDecl * > & Ivars) const1896 void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI,
1897                                       bool leafClass,
1898                             SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const {
1899   if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass())
1900     DeepCollectObjCIvars(SuperClass, false, Ivars);
1901   if (!leafClass) {
1902     for (const auto *I : OI->ivars())
1903       Ivars.push_back(I);
1904   } else {
1905     ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI);
1906     for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv;
1907          Iv= Iv->getNextIvar())
1908       Ivars.push_back(Iv);
1909   }
1910 }
1911 
1912 /// CollectInheritedProtocols - Collect all protocols in current class and
1913 /// those inherited by it.
CollectInheritedProtocols(const Decl * CDecl,llvm::SmallPtrSet<ObjCProtocolDecl *,8> & Protocols)1914 void ASTContext::CollectInheritedProtocols(const Decl *CDecl,
1915                           llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) {
1916   if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1917     // We can use protocol_iterator here instead of
1918     // all_referenced_protocol_iterator since we are walking all categories.
1919     for (auto *Proto : OI->all_referenced_protocols()) {
1920       CollectInheritedProtocols(Proto, Protocols);
1921     }
1922 
1923     // Categories of this Interface.
1924     for (const auto *Cat : OI->visible_categories())
1925       CollectInheritedProtocols(Cat, Protocols);
1926 
1927     if (ObjCInterfaceDecl *SD = OI->getSuperClass())
1928       while (SD) {
1929         CollectInheritedProtocols(SD, Protocols);
1930         SD = SD->getSuperClass();
1931       }
1932   } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1933     for (auto *Proto : OC->protocols()) {
1934       CollectInheritedProtocols(Proto, Protocols);
1935     }
1936   } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1937     // Insert the protocol.
1938     if (!Protocols.insert(
1939           const_cast<ObjCProtocolDecl *>(OP->getCanonicalDecl())).second)
1940       return;
1941 
1942     for (auto *Proto : OP->protocols())
1943       CollectInheritedProtocols(Proto, Protocols);
1944   }
1945 }
1946 
CountNonClassIvars(const ObjCInterfaceDecl * OI) const1947 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const {
1948   unsigned count = 0;
1949   // Count ivars declared in class extension.
1950   for (const auto *Ext : OI->known_extensions())
1951     count += Ext->ivar_size();
1952 
1953   // Count ivar defined in this class's implementation.  This
1954   // includes synthesized ivars.
1955   if (ObjCImplementationDecl *ImplDecl = OI->getImplementation())
1956     count += ImplDecl->ivar_size();
1957 
1958   return count;
1959 }
1960 
isSentinelNullExpr(const Expr * E)1961 bool ASTContext::isSentinelNullExpr(const Expr *E) {
1962   if (!E)
1963     return false;
1964 
1965   // nullptr_t is always treated as null.
1966   if (E->getType()->isNullPtrType()) return true;
1967 
1968   if (E->getType()->isAnyPointerType() &&
1969       E->IgnoreParenCasts()->isNullPointerConstant(*this,
1970                                                 Expr::NPC_ValueDependentIsNull))
1971     return true;
1972 
1973   // Unfortunately, __null has type 'int'.
1974   if (isa<GNUNullExpr>(E)) return true;
1975 
1976   return false;
1977 }
1978 
1979 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists.
getObjCImplementation(ObjCInterfaceDecl * D)1980 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) {
1981   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1982     I = ObjCImpls.find(D);
1983   if (I != ObjCImpls.end())
1984     return cast<ObjCImplementationDecl>(I->second);
1985   return nullptr;
1986 }
1987 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists.
getObjCImplementation(ObjCCategoryDecl * D)1988 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) {
1989   llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator
1990     I = ObjCImpls.find(D);
1991   if (I != ObjCImpls.end())
1992     return cast<ObjCCategoryImplDecl>(I->second);
1993   return nullptr;
1994 }
1995 
1996 /// \brief Set the implementation of ObjCInterfaceDecl.
setObjCImplementation(ObjCInterfaceDecl * IFaceD,ObjCImplementationDecl * ImplD)1997 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD,
1998                            ObjCImplementationDecl *ImplD) {
1999   assert(IFaceD && ImplD && "Passed null params");
2000   ObjCImpls[IFaceD] = ImplD;
2001 }
2002 /// \brief Set the implementation of ObjCCategoryDecl.
setObjCImplementation(ObjCCategoryDecl * CatD,ObjCCategoryImplDecl * ImplD)2003 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD,
2004                            ObjCCategoryImplDecl *ImplD) {
2005   assert(CatD && ImplD && "Passed null params");
2006   ObjCImpls[CatD] = ImplD;
2007 }
2008 
getObjContainingInterface(const NamedDecl * ND) const2009 const ObjCInterfaceDecl *ASTContext::getObjContainingInterface(
2010                                               const NamedDecl *ND) const {
2011   if (const ObjCInterfaceDecl *ID =
2012           dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext()))
2013     return ID;
2014   if (const ObjCCategoryDecl *CD =
2015           dyn_cast<ObjCCategoryDecl>(ND->getDeclContext()))
2016     return CD->getClassInterface();
2017   if (const ObjCImplDecl *IMD =
2018           dyn_cast<ObjCImplDecl>(ND->getDeclContext()))
2019     return IMD->getClassInterface();
2020 
2021   return nullptr;
2022 }
2023 
2024 /// \brief Get the copy initialization expression of VarDecl,or NULL if
2025 /// none exists.
getBlockVarCopyInits(const VarDecl * VD)2026 Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) {
2027   assert(VD && "Passed null params");
2028   assert(VD->hasAttr<BlocksAttr>() &&
2029          "getBlockVarCopyInits - not __block var");
2030   llvm::DenseMap<const VarDecl*, Expr*>::iterator
2031     I = BlockVarCopyInits.find(VD);
2032   return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : nullptr;
2033 }
2034 
2035 /// \brief Set the copy inialization expression of a block var decl.
setBlockVarCopyInits(VarDecl * VD,Expr * Init)2036 void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) {
2037   assert(VD && Init && "Passed null params");
2038   assert(VD->hasAttr<BlocksAttr>() &&
2039          "setBlockVarCopyInits - not __block var");
2040   BlockVarCopyInits[VD] = Init;
2041 }
2042 
CreateTypeSourceInfo(QualType T,unsigned DataSize) const2043 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T,
2044                                                  unsigned DataSize) const {
2045   if (!DataSize)
2046     DataSize = TypeLoc::getFullDataSizeForType(T);
2047   else
2048     assert(DataSize == TypeLoc::getFullDataSizeForType(T) &&
2049            "incorrect data size provided to CreateTypeSourceInfo!");
2050 
2051   TypeSourceInfo *TInfo =
2052     (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8);
2053   new (TInfo) TypeSourceInfo(T);
2054   return TInfo;
2055 }
2056 
getTrivialTypeSourceInfo(QualType T,SourceLocation L) const2057 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T,
2058                                                      SourceLocation L) const {
2059   TypeSourceInfo *DI = CreateTypeSourceInfo(T);
2060   DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L);
2061   return DI;
2062 }
2063 
2064 const ASTRecordLayout &
getASTObjCInterfaceLayout(const ObjCInterfaceDecl * D) const2065 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const {
2066   return getObjCLayout(D, nullptr);
2067 }
2068 
2069 const ASTRecordLayout &
getASTObjCImplementationLayout(const ObjCImplementationDecl * D) const2070 ASTContext::getASTObjCImplementationLayout(
2071                                         const ObjCImplementationDecl *D) const {
2072   return getObjCLayout(D->getClassInterface(), D);
2073 }
2074 
2075 //===----------------------------------------------------------------------===//
2076 //                   Type creation/memoization methods
2077 //===----------------------------------------------------------------------===//
2078 
2079 QualType
getExtQualType(const Type * baseType,Qualifiers quals) const2080 ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const {
2081   unsigned fastQuals = quals.getFastQualifiers();
2082   quals.removeFastQualifiers();
2083 
2084   // Check if we've already instantiated this type.
2085   llvm::FoldingSetNodeID ID;
2086   ExtQuals::Profile(ID, baseType, quals);
2087   void *insertPos = nullptr;
2088   if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) {
2089     assert(eq->getQualifiers() == quals);
2090     return QualType(eq, fastQuals);
2091   }
2092 
2093   // If the base type is not canonical, make the appropriate canonical type.
2094   QualType canon;
2095   if (!baseType->isCanonicalUnqualified()) {
2096     SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split();
2097     canonSplit.Quals.addConsistentQualifiers(quals);
2098     canon = getExtQualType(canonSplit.Ty, canonSplit.Quals);
2099 
2100     // Re-find the insert position.
2101     (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos);
2102   }
2103 
2104   ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals);
2105   ExtQualNodes.InsertNode(eq, insertPos);
2106   return QualType(eq, fastQuals);
2107 }
2108 
2109 QualType
getAddrSpaceQualType(QualType T,unsigned AddressSpace) const2110 ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const {
2111   QualType CanT = getCanonicalType(T);
2112   if (CanT.getAddressSpace() == AddressSpace)
2113     return T;
2114 
2115   // If we are composing extended qualifiers together, merge together
2116   // into one ExtQuals node.
2117   QualifierCollector Quals;
2118   const Type *TypeNode = Quals.strip(T);
2119 
2120   // If this type already has an address space specified, it cannot get
2121   // another one.
2122   assert(!Quals.hasAddressSpace() &&
2123          "Type cannot be in multiple addr spaces!");
2124   Quals.addAddressSpace(AddressSpace);
2125 
2126   return getExtQualType(TypeNode, Quals);
2127 }
2128 
getObjCGCQualType(QualType T,Qualifiers::GC GCAttr) const2129 QualType ASTContext::getObjCGCQualType(QualType T,
2130                                        Qualifiers::GC GCAttr) const {
2131   QualType CanT = getCanonicalType(T);
2132   if (CanT.getObjCGCAttr() == GCAttr)
2133     return T;
2134 
2135   if (const PointerType *ptr = T->getAs<PointerType>()) {
2136     QualType Pointee = ptr->getPointeeType();
2137     if (Pointee->isAnyPointerType()) {
2138       QualType ResultType = getObjCGCQualType(Pointee, GCAttr);
2139       return getPointerType(ResultType);
2140     }
2141   }
2142 
2143   // If we are composing extended qualifiers together, merge together
2144   // into one ExtQuals node.
2145   QualifierCollector Quals;
2146   const Type *TypeNode = Quals.strip(T);
2147 
2148   // If this type already has an ObjCGC specified, it cannot get
2149   // another one.
2150   assert(!Quals.hasObjCGCAttr() &&
2151          "Type cannot have multiple ObjCGCs!");
2152   Quals.addObjCGCAttr(GCAttr);
2153 
2154   return getExtQualType(TypeNode, Quals);
2155 }
2156 
adjustFunctionType(const FunctionType * T,FunctionType::ExtInfo Info)2157 const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
2158                                                    FunctionType::ExtInfo Info) {
2159   if (T->getExtInfo() == Info)
2160     return T;
2161 
2162   QualType Result;
2163   if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) {
2164     Result = getFunctionNoProtoType(FNPT->getReturnType(), Info);
2165   } else {
2166     const FunctionProtoType *FPT = cast<FunctionProtoType>(T);
2167     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2168     EPI.ExtInfo = Info;
2169     Result = getFunctionType(FPT->getReturnType(), FPT->getParamTypes(), EPI);
2170   }
2171 
2172   return cast<FunctionType>(Result.getTypePtr());
2173 }
2174 
adjustDeducedFunctionResultType(FunctionDecl * FD,QualType ResultType)2175 void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
2176                                                  QualType ResultType) {
2177   FD = FD->getMostRecentDecl();
2178   while (true) {
2179     const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
2180     FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
2181     FD->setType(getFunctionType(ResultType, FPT->getParamTypes(), EPI));
2182     if (FunctionDecl *Next = FD->getPreviousDecl())
2183       FD = Next;
2184     else
2185       break;
2186   }
2187   if (ASTMutationListener *L = getASTMutationListener())
2188     L->DeducedReturnType(FD, ResultType);
2189 }
2190 
2191 /// Get a function type and produce the equivalent function type with the
2192 /// specified exception specification. Type sugar that can be present on a
2193 /// declaration of a function with an exception specification is permitted
2194 /// and preserved. Other type sugar (for instance, typedefs) is not.
getFunctionTypeWithExceptionSpec(ASTContext & Context,QualType Orig,const FunctionProtoType::ExceptionSpecInfo & ESI)2195 static QualType getFunctionTypeWithExceptionSpec(
2196     ASTContext &Context, QualType Orig,
2197     const FunctionProtoType::ExceptionSpecInfo &ESI) {
2198   // Might have some parens.
2199   if (auto *PT = dyn_cast<ParenType>(Orig))
2200     return Context.getParenType(
2201         getFunctionTypeWithExceptionSpec(Context, PT->getInnerType(), ESI));
2202 
2203   // Might have a calling-convention attribute.
2204   if (auto *AT = dyn_cast<AttributedType>(Orig))
2205     return Context.getAttributedType(
2206         AT->getAttrKind(),
2207         getFunctionTypeWithExceptionSpec(Context, AT->getModifiedType(), ESI),
2208         getFunctionTypeWithExceptionSpec(Context, AT->getEquivalentType(),
2209                                          ESI));
2210 
2211   // Anything else must be a function type. Rebuild it with the new exception
2212   // specification.
2213   const FunctionProtoType *Proto = cast<FunctionProtoType>(Orig);
2214   return Context.getFunctionType(
2215       Proto->getReturnType(), Proto->getParamTypes(),
2216       Proto->getExtProtoInfo().withExceptionSpec(ESI));
2217 }
2218 
adjustExceptionSpec(FunctionDecl * FD,const FunctionProtoType::ExceptionSpecInfo & ESI,bool AsWritten)2219 void ASTContext::adjustExceptionSpec(
2220     FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI,
2221     bool AsWritten) {
2222   // Update the type.
2223   QualType Updated =
2224       getFunctionTypeWithExceptionSpec(*this, FD->getType(), ESI);
2225   FD->setType(Updated);
2226 
2227   if (!AsWritten)
2228     return;
2229 
2230   // Update the type in the type source information too.
2231   if (TypeSourceInfo *TSInfo = FD->getTypeSourceInfo()) {
2232     // If the type and the type-as-written differ, we may need to update
2233     // the type-as-written too.
2234     if (TSInfo->getType() != FD->getType())
2235       Updated = getFunctionTypeWithExceptionSpec(*this, TSInfo->getType(), ESI);
2236 
2237     // FIXME: When we get proper type location information for exceptions,
2238     // we'll also have to rebuild the TypeSourceInfo. For now, we just patch
2239     // up the TypeSourceInfo;
2240     assert(TypeLoc::getFullDataSizeForType(Updated) ==
2241                TypeLoc::getFullDataSizeForType(TSInfo->getType()) &&
2242            "TypeLoc size mismatch from updating exception specification");
2243     TSInfo->overrideType(Updated);
2244   }
2245 }
2246 
2247 /// getComplexType - Return the uniqued reference to the type for a complex
2248 /// number with the specified element type.
getComplexType(QualType T) const2249 QualType ASTContext::getComplexType(QualType T) const {
2250   // Unique pointers, to guarantee there is only one pointer of a particular
2251   // structure.
2252   llvm::FoldingSetNodeID ID;
2253   ComplexType::Profile(ID, T);
2254 
2255   void *InsertPos = nullptr;
2256   if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos))
2257     return QualType(CT, 0);
2258 
2259   // If the pointee type isn't canonical, this won't be a canonical type either,
2260   // so fill in the canonical type field.
2261   QualType Canonical;
2262   if (!T.isCanonical()) {
2263     Canonical = getComplexType(getCanonicalType(T));
2264 
2265     // Get the new insert position for the node we care about.
2266     ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos);
2267     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2268   }
2269   ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical);
2270   Types.push_back(New);
2271   ComplexTypes.InsertNode(New, InsertPos);
2272   return QualType(New, 0);
2273 }
2274 
2275 /// getPointerType - Return the uniqued reference to the type for a pointer to
2276 /// the specified type.
getPointerType(QualType T) const2277 QualType ASTContext::getPointerType(QualType T) const {
2278   // Unique pointers, to guarantee there is only one pointer of a particular
2279   // structure.
2280   llvm::FoldingSetNodeID ID;
2281   PointerType::Profile(ID, T);
2282 
2283   void *InsertPos = nullptr;
2284   if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2285     return QualType(PT, 0);
2286 
2287   // If the pointee type isn't canonical, this won't be a canonical type either,
2288   // so fill in the canonical type field.
2289   QualType Canonical;
2290   if (!T.isCanonical()) {
2291     Canonical = getPointerType(getCanonicalType(T));
2292 
2293     // Get the new insert position for the node we care about.
2294     PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2295     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2296   }
2297   PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical);
2298   Types.push_back(New);
2299   PointerTypes.InsertNode(New, InsertPos);
2300   return QualType(New, 0);
2301 }
2302 
getAdjustedType(QualType Orig,QualType New) const2303 QualType ASTContext::getAdjustedType(QualType Orig, QualType New) const {
2304   llvm::FoldingSetNodeID ID;
2305   AdjustedType::Profile(ID, Orig, New);
2306   void *InsertPos = nullptr;
2307   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2308   if (AT)
2309     return QualType(AT, 0);
2310 
2311   QualType Canonical = getCanonicalType(New);
2312 
2313   // Get the new insert position for the node we care about.
2314   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2315   assert(!AT && "Shouldn't be in the map!");
2316 
2317   AT = new (*this, TypeAlignment)
2318       AdjustedType(Type::Adjusted, Orig, New, Canonical);
2319   Types.push_back(AT);
2320   AdjustedTypes.InsertNode(AT, InsertPos);
2321   return QualType(AT, 0);
2322 }
2323 
getDecayedType(QualType T) const2324 QualType ASTContext::getDecayedType(QualType T) const {
2325   assert((T->isArrayType() || T->isFunctionType()) && "T does not decay");
2326 
2327   QualType Decayed;
2328 
2329   // C99 6.7.5.3p7:
2330   //   A declaration of a parameter as "array of type" shall be
2331   //   adjusted to "qualified pointer to type", where the type
2332   //   qualifiers (if any) are those specified within the [ and ] of
2333   //   the array type derivation.
2334   if (T->isArrayType())
2335     Decayed = getArrayDecayedType(T);
2336 
2337   // C99 6.7.5.3p8:
2338   //   A declaration of a parameter as "function returning type"
2339   //   shall be adjusted to "pointer to function returning type", as
2340   //   in 6.3.2.1.
2341   if (T->isFunctionType())
2342     Decayed = getPointerType(T);
2343 
2344   llvm::FoldingSetNodeID ID;
2345   AdjustedType::Profile(ID, T, Decayed);
2346   void *InsertPos = nullptr;
2347   AdjustedType *AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2348   if (AT)
2349     return QualType(AT, 0);
2350 
2351   QualType Canonical = getCanonicalType(Decayed);
2352 
2353   // Get the new insert position for the node we care about.
2354   AT = AdjustedTypes.FindNodeOrInsertPos(ID, InsertPos);
2355   assert(!AT && "Shouldn't be in the map!");
2356 
2357   AT = new (*this, TypeAlignment) DecayedType(T, Decayed, Canonical);
2358   Types.push_back(AT);
2359   AdjustedTypes.InsertNode(AT, InsertPos);
2360   return QualType(AT, 0);
2361 }
2362 
2363 /// getBlockPointerType - Return the uniqued reference to the type for
2364 /// a pointer to the specified block.
getBlockPointerType(QualType T) const2365 QualType ASTContext::getBlockPointerType(QualType T) const {
2366   assert(T->isFunctionType() && "block of function types only");
2367   // Unique pointers, to guarantee there is only one block of a particular
2368   // structure.
2369   llvm::FoldingSetNodeID ID;
2370   BlockPointerType::Profile(ID, T);
2371 
2372   void *InsertPos = nullptr;
2373   if (BlockPointerType *PT =
2374         BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2375     return QualType(PT, 0);
2376 
2377   // If the block pointee type isn't canonical, this won't be a canonical
2378   // type either so fill in the canonical type field.
2379   QualType Canonical;
2380   if (!T.isCanonical()) {
2381     Canonical = getBlockPointerType(getCanonicalType(T));
2382 
2383     // Get the new insert position for the node we care about.
2384     BlockPointerType *NewIP =
2385       BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2386     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2387   }
2388   BlockPointerType *New
2389     = new (*this, TypeAlignment) BlockPointerType(T, Canonical);
2390   Types.push_back(New);
2391   BlockPointerTypes.InsertNode(New, InsertPos);
2392   return QualType(New, 0);
2393 }
2394 
2395 /// getLValueReferenceType - Return the uniqued reference to the type for an
2396 /// lvalue reference to the specified type.
2397 QualType
getLValueReferenceType(QualType T,bool SpelledAsLValue) const2398 ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const {
2399   assert(getCanonicalType(T) != OverloadTy &&
2400          "Unresolved overloaded function type");
2401 
2402   // Unique pointers, to guarantee there is only one pointer of a particular
2403   // structure.
2404   llvm::FoldingSetNodeID ID;
2405   ReferenceType::Profile(ID, T, SpelledAsLValue);
2406 
2407   void *InsertPos = nullptr;
2408   if (LValueReferenceType *RT =
2409         LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2410     return QualType(RT, 0);
2411 
2412   const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2413 
2414   // If the referencee type isn't canonical, this won't be a canonical type
2415   // either, so fill in the canonical type field.
2416   QualType Canonical;
2417   if (!SpelledAsLValue || InnerRef || !T.isCanonical()) {
2418     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2419     Canonical = getLValueReferenceType(getCanonicalType(PointeeType));
2420 
2421     // Get the new insert position for the node we care about.
2422     LValueReferenceType *NewIP =
2423       LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2424     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2425   }
2426 
2427   LValueReferenceType *New
2428     = new (*this, TypeAlignment) LValueReferenceType(T, Canonical,
2429                                                      SpelledAsLValue);
2430   Types.push_back(New);
2431   LValueReferenceTypes.InsertNode(New, InsertPos);
2432 
2433   return QualType(New, 0);
2434 }
2435 
2436 /// getRValueReferenceType - Return the uniqued reference to the type for an
2437 /// rvalue reference to the specified type.
getRValueReferenceType(QualType T) const2438 QualType ASTContext::getRValueReferenceType(QualType T) const {
2439   // Unique pointers, to guarantee there is only one pointer of a particular
2440   // structure.
2441   llvm::FoldingSetNodeID ID;
2442   ReferenceType::Profile(ID, T, false);
2443 
2444   void *InsertPos = nullptr;
2445   if (RValueReferenceType *RT =
2446         RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos))
2447     return QualType(RT, 0);
2448 
2449   const ReferenceType *InnerRef = T->getAs<ReferenceType>();
2450 
2451   // If the referencee type isn't canonical, this won't be a canonical type
2452   // either, so fill in the canonical type field.
2453   QualType Canonical;
2454   if (InnerRef || !T.isCanonical()) {
2455     QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T);
2456     Canonical = getRValueReferenceType(getCanonicalType(PointeeType));
2457 
2458     // Get the new insert position for the node we care about.
2459     RValueReferenceType *NewIP =
2460       RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos);
2461     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2462   }
2463 
2464   RValueReferenceType *New
2465     = new (*this, TypeAlignment) RValueReferenceType(T, Canonical);
2466   Types.push_back(New);
2467   RValueReferenceTypes.InsertNode(New, InsertPos);
2468   return QualType(New, 0);
2469 }
2470 
2471 /// getMemberPointerType - Return the uniqued reference to the type for a
2472 /// member pointer to the specified type, in the specified class.
getMemberPointerType(QualType T,const Type * Cls) const2473 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const {
2474   // Unique pointers, to guarantee there is only one pointer of a particular
2475   // structure.
2476   llvm::FoldingSetNodeID ID;
2477   MemberPointerType::Profile(ID, T, Cls);
2478 
2479   void *InsertPos = nullptr;
2480   if (MemberPointerType *PT =
2481       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
2482     return QualType(PT, 0);
2483 
2484   // If the pointee or class type isn't canonical, this won't be a canonical
2485   // type either, so fill in the canonical type field.
2486   QualType Canonical;
2487   if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) {
2488     Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls));
2489 
2490     // Get the new insert position for the node we care about.
2491     MemberPointerType *NewIP =
2492       MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
2493     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2494   }
2495   MemberPointerType *New
2496     = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical);
2497   Types.push_back(New);
2498   MemberPointerTypes.InsertNode(New, InsertPos);
2499   return QualType(New, 0);
2500 }
2501 
2502 /// getConstantArrayType - Return the unique reference to the type for an
2503 /// array of the specified element type.
getConstantArrayType(QualType EltTy,const llvm::APInt & ArySizeIn,ArrayType::ArraySizeModifier ASM,unsigned IndexTypeQuals) const2504 QualType ASTContext::getConstantArrayType(QualType EltTy,
2505                                           const llvm::APInt &ArySizeIn,
2506                                           ArrayType::ArraySizeModifier ASM,
2507                                           unsigned IndexTypeQuals) const {
2508   assert((EltTy->isDependentType() ||
2509           EltTy->isIncompleteType() || EltTy->isConstantSizeType()) &&
2510          "Constant array of VLAs is illegal!");
2511 
2512   // Convert the array size into a canonical width matching the pointer size for
2513   // the target.
2514   llvm::APInt ArySize(ArySizeIn);
2515   ArySize =
2516     ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy)));
2517 
2518   llvm::FoldingSetNodeID ID;
2519   ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals);
2520 
2521   void *InsertPos = nullptr;
2522   if (ConstantArrayType *ATP =
2523       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos))
2524     return QualType(ATP, 0);
2525 
2526   // If the element type isn't canonical or has qualifiers, this won't
2527   // be a canonical type either, so fill in the canonical type field.
2528   QualType Canon;
2529   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2530     SplitQualType canonSplit = getCanonicalType(EltTy).split();
2531     Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize,
2532                                  ASM, IndexTypeQuals);
2533     Canon = getQualifiedType(Canon, canonSplit.Quals);
2534 
2535     // Get the new insert position for the node we care about.
2536     ConstantArrayType *NewIP =
2537       ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos);
2538     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2539   }
2540 
2541   ConstantArrayType *New = new(*this,TypeAlignment)
2542     ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals);
2543   ConstantArrayTypes.InsertNode(New, InsertPos);
2544   Types.push_back(New);
2545   return QualType(New, 0);
2546 }
2547 
2548 /// getVariableArrayDecayedType - Turns the given type, which may be
2549 /// variably-modified, into the corresponding type with all the known
2550 /// sizes replaced with [*].
getVariableArrayDecayedType(QualType type) const2551 QualType ASTContext::getVariableArrayDecayedType(QualType type) const {
2552   // Vastly most common case.
2553   if (!type->isVariablyModifiedType()) return type;
2554 
2555   QualType result;
2556 
2557   SplitQualType split = type.getSplitDesugaredType();
2558   const Type *ty = split.Ty;
2559   switch (ty->getTypeClass()) {
2560 #define TYPE(Class, Base)
2561 #define ABSTRACT_TYPE(Class, Base)
2562 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2563 #include "clang/AST/TypeNodes.def"
2564     llvm_unreachable("didn't desugar past all non-canonical types?");
2565 
2566   // These types should never be variably-modified.
2567   case Type::Builtin:
2568   case Type::Complex:
2569   case Type::Vector:
2570   case Type::ExtVector:
2571   case Type::DependentSizedExtVector:
2572   case Type::ObjCObject:
2573   case Type::ObjCInterface:
2574   case Type::ObjCObjectPointer:
2575   case Type::Record:
2576   case Type::Enum:
2577   case Type::UnresolvedUsing:
2578   case Type::TypeOfExpr:
2579   case Type::TypeOf:
2580   case Type::Decltype:
2581   case Type::UnaryTransform:
2582   case Type::DependentName:
2583   case Type::InjectedClassName:
2584   case Type::TemplateSpecialization:
2585   case Type::DependentTemplateSpecialization:
2586   case Type::TemplateTypeParm:
2587   case Type::SubstTemplateTypeParmPack:
2588   case Type::Auto:
2589   case Type::PackExpansion:
2590     llvm_unreachable("type should never be variably-modified");
2591 
2592   // These types can be variably-modified but should never need to
2593   // further decay.
2594   case Type::FunctionNoProto:
2595   case Type::FunctionProto:
2596   case Type::BlockPointer:
2597   case Type::MemberPointer:
2598     return type;
2599 
2600   // These types can be variably-modified.  All these modifications
2601   // preserve structure except as noted by comments.
2602   // TODO: if we ever care about optimizing VLAs, there are no-op
2603   // optimizations available here.
2604   case Type::Pointer:
2605     result = getPointerType(getVariableArrayDecayedType(
2606                               cast<PointerType>(ty)->getPointeeType()));
2607     break;
2608 
2609   case Type::LValueReference: {
2610     const LValueReferenceType *lv = cast<LValueReferenceType>(ty);
2611     result = getLValueReferenceType(
2612                  getVariableArrayDecayedType(lv->getPointeeType()),
2613                                     lv->isSpelledAsLValue());
2614     break;
2615   }
2616 
2617   case Type::RValueReference: {
2618     const RValueReferenceType *lv = cast<RValueReferenceType>(ty);
2619     result = getRValueReferenceType(
2620                  getVariableArrayDecayedType(lv->getPointeeType()));
2621     break;
2622   }
2623 
2624   case Type::Atomic: {
2625     const AtomicType *at = cast<AtomicType>(ty);
2626     result = getAtomicType(getVariableArrayDecayedType(at->getValueType()));
2627     break;
2628   }
2629 
2630   case Type::ConstantArray: {
2631     const ConstantArrayType *cat = cast<ConstantArrayType>(ty);
2632     result = getConstantArrayType(
2633                  getVariableArrayDecayedType(cat->getElementType()),
2634                                   cat->getSize(),
2635                                   cat->getSizeModifier(),
2636                                   cat->getIndexTypeCVRQualifiers());
2637     break;
2638   }
2639 
2640   case Type::DependentSizedArray: {
2641     const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty);
2642     result = getDependentSizedArrayType(
2643                  getVariableArrayDecayedType(dat->getElementType()),
2644                                         dat->getSizeExpr(),
2645                                         dat->getSizeModifier(),
2646                                         dat->getIndexTypeCVRQualifiers(),
2647                                         dat->getBracketsRange());
2648     break;
2649   }
2650 
2651   // Turn incomplete types into [*] types.
2652   case Type::IncompleteArray: {
2653     const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty);
2654     result = getVariableArrayType(
2655                  getVariableArrayDecayedType(iat->getElementType()),
2656                                   /*size*/ nullptr,
2657                                   ArrayType::Normal,
2658                                   iat->getIndexTypeCVRQualifiers(),
2659                                   SourceRange());
2660     break;
2661   }
2662 
2663   // Turn VLA types into [*] types.
2664   case Type::VariableArray: {
2665     const VariableArrayType *vat = cast<VariableArrayType>(ty);
2666     result = getVariableArrayType(
2667                  getVariableArrayDecayedType(vat->getElementType()),
2668                                   /*size*/ nullptr,
2669                                   ArrayType::Star,
2670                                   vat->getIndexTypeCVRQualifiers(),
2671                                   vat->getBracketsRange());
2672     break;
2673   }
2674   }
2675 
2676   // Apply the top-level qualifiers from the original.
2677   return getQualifiedType(result, split.Quals);
2678 }
2679 
2680 /// getVariableArrayType - Returns a non-unique reference to the type for a
2681 /// variable array of the specified element type.
getVariableArrayType(QualType EltTy,Expr * NumElts,ArrayType::ArraySizeModifier ASM,unsigned IndexTypeQuals,SourceRange Brackets) const2682 QualType ASTContext::getVariableArrayType(QualType EltTy,
2683                                           Expr *NumElts,
2684                                           ArrayType::ArraySizeModifier ASM,
2685                                           unsigned IndexTypeQuals,
2686                                           SourceRange Brackets) const {
2687   // Since we don't unique expressions, it isn't possible to unique VLA's
2688   // that have an expression provided for their size.
2689   QualType Canon;
2690 
2691   // Be sure to pull qualifiers off the element type.
2692   if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) {
2693     SplitQualType canonSplit = getCanonicalType(EltTy).split();
2694     Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM,
2695                                  IndexTypeQuals, Brackets);
2696     Canon = getQualifiedType(Canon, canonSplit.Quals);
2697   }
2698 
2699   VariableArrayType *New = new(*this, TypeAlignment)
2700     VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets);
2701 
2702   VariableArrayTypes.push_back(New);
2703   Types.push_back(New);
2704   return QualType(New, 0);
2705 }
2706 
2707 /// getDependentSizedArrayType - Returns a non-unique reference to
2708 /// the type for a dependently-sized array of the specified element
2709 /// type.
getDependentSizedArrayType(QualType elementType,Expr * numElements,ArrayType::ArraySizeModifier ASM,unsigned elementTypeQuals,SourceRange brackets) const2710 QualType ASTContext::getDependentSizedArrayType(QualType elementType,
2711                                                 Expr *numElements,
2712                                                 ArrayType::ArraySizeModifier ASM,
2713                                                 unsigned elementTypeQuals,
2714                                                 SourceRange brackets) const {
2715   assert((!numElements || numElements->isTypeDependent() ||
2716           numElements->isValueDependent()) &&
2717          "Size must be type- or value-dependent!");
2718 
2719   // Dependently-sized array types that do not have a specified number
2720   // of elements will have their sizes deduced from a dependent
2721   // initializer.  We do no canonicalization here at all, which is okay
2722   // because they can't be used in most locations.
2723   if (!numElements) {
2724     DependentSizedArrayType *newType
2725       = new (*this, TypeAlignment)
2726           DependentSizedArrayType(*this, elementType, QualType(),
2727                                   numElements, ASM, elementTypeQuals,
2728                                   brackets);
2729     Types.push_back(newType);
2730     return QualType(newType, 0);
2731   }
2732 
2733   // Otherwise, we actually build a new type every time, but we
2734   // also build a canonical type.
2735 
2736   SplitQualType canonElementType = getCanonicalType(elementType).split();
2737 
2738   void *insertPos = nullptr;
2739   llvm::FoldingSetNodeID ID;
2740   DependentSizedArrayType::Profile(ID, *this,
2741                                    QualType(canonElementType.Ty, 0),
2742                                    ASM, elementTypeQuals, numElements);
2743 
2744   // Look for an existing type with these properties.
2745   DependentSizedArrayType *canonTy =
2746     DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2747 
2748   // If we don't have one, build one.
2749   if (!canonTy) {
2750     canonTy = new (*this, TypeAlignment)
2751       DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0),
2752                               QualType(), numElements, ASM, elementTypeQuals,
2753                               brackets);
2754     DependentSizedArrayTypes.InsertNode(canonTy, insertPos);
2755     Types.push_back(canonTy);
2756   }
2757 
2758   // Apply qualifiers from the element type to the array.
2759   QualType canon = getQualifiedType(QualType(canonTy,0),
2760                                     canonElementType.Quals);
2761 
2762   // If we didn't need extra canonicalization for the element type,
2763   // then just use that as our result.
2764   if (QualType(canonElementType.Ty, 0) == elementType)
2765     return canon;
2766 
2767   // Otherwise, we need to build a type which follows the spelling
2768   // of the element type.
2769   DependentSizedArrayType *sugaredType
2770     = new (*this, TypeAlignment)
2771         DependentSizedArrayType(*this, elementType, canon, numElements,
2772                                 ASM, elementTypeQuals, brackets);
2773   Types.push_back(sugaredType);
2774   return QualType(sugaredType, 0);
2775 }
2776 
getIncompleteArrayType(QualType elementType,ArrayType::ArraySizeModifier ASM,unsigned elementTypeQuals) const2777 QualType ASTContext::getIncompleteArrayType(QualType elementType,
2778                                             ArrayType::ArraySizeModifier ASM,
2779                                             unsigned elementTypeQuals) const {
2780   llvm::FoldingSetNodeID ID;
2781   IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals);
2782 
2783   void *insertPos = nullptr;
2784   if (IncompleteArrayType *iat =
2785        IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos))
2786     return QualType(iat, 0);
2787 
2788   // If the element type isn't canonical, this won't be a canonical type
2789   // either, so fill in the canonical type field.  We also have to pull
2790   // qualifiers off the element type.
2791   QualType canon;
2792 
2793   if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) {
2794     SplitQualType canonSplit = getCanonicalType(elementType).split();
2795     canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0),
2796                                    ASM, elementTypeQuals);
2797     canon = getQualifiedType(canon, canonSplit.Quals);
2798 
2799     // Get the new insert position for the node we care about.
2800     IncompleteArrayType *existing =
2801       IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos);
2802     assert(!existing && "Shouldn't be in the map!"); (void) existing;
2803   }
2804 
2805   IncompleteArrayType *newType = new (*this, TypeAlignment)
2806     IncompleteArrayType(elementType, canon, ASM, elementTypeQuals);
2807 
2808   IncompleteArrayTypes.InsertNode(newType, insertPos);
2809   Types.push_back(newType);
2810   return QualType(newType, 0);
2811 }
2812 
2813 /// getVectorType - Return the unique reference to a vector type of
2814 /// the specified element type and size. VectorType must be a built-in type.
getVectorType(QualType vecType,unsigned NumElts,VectorType::VectorKind VecKind) const2815 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts,
2816                                    VectorType::VectorKind VecKind) const {
2817   assert(vecType->isBuiltinType());
2818 
2819   // Check if we've already instantiated a vector of this type.
2820   llvm::FoldingSetNodeID ID;
2821   VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind);
2822 
2823   void *InsertPos = nullptr;
2824   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2825     return QualType(VTP, 0);
2826 
2827   // If the element type isn't canonical, this won't be a canonical type either,
2828   // so fill in the canonical type field.
2829   QualType Canonical;
2830   if (!vecType.isCanonical()) {
2831     Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind);
2832 
2833     // Get the new insert position for the node we care about.
2834     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2835     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2836   }
2837   VectorType *New = new (*this, TypeAlignment)
2838     VectorType(vecType, NumElts, Canonical, VecKind);
2839   VectorTypes.InsertNode(New, InsertPos);
2840   Types.push_back(New);
2841   return QualType(New, 0);
2842 }
2843 
2844 /// getExtVectorType - Return the unique reference to an extended vector type of
2845 /// the specified element type and size. VectorType must be a built-in type.
2846 QualType
getExtVectorType(QualType vecType,unsigned NumElts) const2847 ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const {
2848   assert(vecType->isBuiltinType() || vecType->isDependentType());
2849 
2850   // Check if we've already instantiated a vector of this type.
2851   llvm::FoldingSetNodeID ID;
2852   VectorType::Profile(ID, vecType, NumElts, Type::ExtVector,
2853                       VectorType::GenericVector);
2854   void *InsertPos = nullptr;
2855   if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos))
2856     return QualType(VTP, 0);
2857 
2858   // If the element type isn't canonical, this won't be a canonical type either,
2859   // so fill in the canonical type field.
2860   QualType Canonical;
2861   if (!vecType.isCanonical()) {
2862     Canonical = getExtVectorType(getCanonicalType(vecType), NumElts);
2863 
2864     // Get the new insert position for the node we care about.
2865     VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2866     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2867   }
2868   ExtVectorType *New = new (*this, TypeAlignment)
2869     ExtVectorType(vecType, NumElts, Canonical);
2870   VectorTypes.InsertNode(New, InsertPos);
2871   Types.push_back(New);
2872   return QualType(New, 0);
2873 }
2874 
2875 QualType
getDependentSizedExtVectorType(QualType vecType,Expr * SizeExpr,SourceLocation AttrLoc) const2876 ASTContext::getDependentSizedExtVectorType(QualType vecType,
2877                                            Expr *SizeExpr,
2878                                            SourceLocation AttrLoc) const {
2879   llvm::FoldingSetNodeID ID;
2880   DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType),
2881                                        SizeExpr);
2882 
2883   void *InsertPos = nullptr;
2884   DependentSizedExtVectorType *Canon
2885     = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2886   DependentSizedExtVectorType *New;
2887   if (Canon) {
2888     // We already have a canonical version of this array type; use it as
2889     // the canonical type for a newly-built type.
2890     New = new (*this, TypeAlignment)
2891       DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0),
2892                                   SizeExpr, AttrLoc);
2893   } else {
2894     QualType CanonVecTy = getCanonicalType(vecType);
2895     if (CanonVecTy == vecType) {
2896       New = new (*this, TypeAlignment)
2897         DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr,
2898                                     AttrLoc);
2899 
2900       DependentSizedExtVectorType *CanonCheck
2901         = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos);
2902       assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken");
2903       (void)CanonCheck;
2904       DependentSizedExtVectorTypes.InsertNode(New, InsertPos);
2905     } else {
2906       QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr,
2907                                                       SourceLocation());
2908       New = new (*this, TypeAlignment)
2909         DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc);
2910     }
2911   }
2912 
2913   Types.push_back(New);
2914   return QualType(New, 0);
2915 }
2916 
2917 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'.
2918 ///
2919 QualType
getFunctionNoProtoType(QualType ResultTy,const FunctionType::ExtInfo & Info) const2920 ASTContext::getFunctionNoProtoType(QualType ResultTy,
2921                                    const FunctionType::ExtInfo &Info) const {
2922   const CallingConv CallConv = Info.getCC();
2923 
2924   // Unique functions, to guarantee there is only one function of a particular
2925   // structure.
2926   llvm::FoldingSetNodeID ID;
2927   FunctionNoProtoType::Profile(ID, ResultTy, Info);
2928 
2929   void *InsertPos = nullptr;
2930   if (FunctionNoProtoType *FT =
2931         FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2932     return QualType(FT, 0);
2933 
2934   QualType Canonical;
2935   if (!ResultTy.isCanonical()) {
2936     Canonical = getFunctionNoProtoType(getCanonicalType(ResultTy), Info);
2937 
2938     // Get the new insert position for the node we care about.
2939     FunctionNoProtoType *NewIP =
2940       FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
2941     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
2942   }
2943 
2944   FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv);
2945   FunctionNoProtoType *New = new (*this, TypeAlignment)
2946     FunctionNoProtoType(ResultTy, Canonical, newInfo);
2947   Types.push_back(New);
2948   FunctionNoProtoTypes.InsertNode(New, InsertPos);
2949   return QualType(New, 0);
2950 }
2951 
2952 /// \brief Determine whether \p T is canonical as the result type of a function.
isCanonicalResultType(QualType T)2953 static bool isCanonicalResultType(QualType T) {
2954   return T.isCanonical() &&
2955          (T.getObjCLifetime() == Qualifiers::OCL_None ||
2956           T.getObjCLifetime() == Qualifiers::OCL_ExplicitNone);
2957 }
2958 
2959 QualType
getFunctionType(QualType ResultTy,ArrayRef<QualType> ArgArray,const FunctionProtoType::ExtProtoInfo & EPI) const2960 ASTContext::getFunctionType(QualType ResultTy, ArrayRef<QualType> ArgArray,
2961                             const FunctionProtoType::ExtProtoInfo &EPI) const {
2962   size_t NumArgs = ArgArray.size();
2963 
2964   // Unique functions, to guarantee there is only one function of a particular
2965   // structure.
2966   llvm::FoldingSetNodeID ID;
2967   FunctionProtoType::Profile(ID, ResultTy, ArgArray.begin(), NumArgs, EPI,
2968                              *this);
2969 
2970   void *InsertPos = nullptr;
2971   if (FunctionProtoType *FTP =
2972         FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos))
2973     return QualType(FTP, 0);
2974 
2975   // Determine whether the type being created is already canonical or not.
2976   bool isCanonical =
2977     EPI.ExceptionSpec.Type == EST_None && isCanonicalResultType(ResultTy) &&
2978     !EPI.HasTrailingReturn;
2979   for (unsigned i = 0; i != NumArgs && isCanonical; ++i)
2980     if (!ArgArray[i].isCanonicalAsParam())
2981       isCanonical = false;
2982 
2983   // If this type isn't canonical, get the canonical version of it.
2984   // The exception spec is not part of the canonical type.
2985   QualType Canonical;
2986   if (!isCanonical) {
2987     SmallVector<QualType, 16> CanonicalArgs;
2988     CanonicalArgs.reserve(NumArgs);
2989     for (unsigned i = 0; i != NumArgs; ++i)
2990       CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i]));
2991 
2992     FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI;
2993     CanonicalEPI.HasTrailingReturn = false;
2994     CanonicalEPI.ExceptionSpec = FunctionProtoType::ExceptionSpecInfo();
2995 
2996     // Result types do not have ARC lifetime qualifiers.
2997     QualType CanResultTy = getCanonicalType(ResultTy);
2998     if (ResultTy.getQualifiers().hasObjCLifetime()) {
2999       Qualifiers Qs = CanResultTy.getQualifiers();
3000       Qs.removeObjCLifetime();
3001       CanResultTy = getQualifiedType(CanResultTy.getUnqualifiedType(), Qs);
3002     }
3003 
3004     Canonical = getFunctionType(CanResultTy, CanonicalArgs, CanonicalEPI);
3005 
3006     // Get the new insert position for the node we care about.
3007     FunctionProtoType *NewIP =
3008       FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos);
3009     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3010   }
3011 
3012   // FunctionProtoType objects are allocated with extra bytes after
3013   // them for three variable size arrays at the end:
3014   //  - parameter types
3015   //  - exception types
3016   //  - consumed-arguments flags
3017   // Instead of the exception types, there could be a noexcept
3018   // expression, or information used to resolve the exception
3019   // specification.
3020   size_t Size = sizeof(FunctionProtoType) +
3021                 NumArgs * sizeof(QualType);
3022   if (EPI.ExceptionSpec.Type == EST_Dynamic) {
3023     Size += EPI.ExceptionSpec.Exceptions.size() * sizeof(QualType);
3024   } else if (EPI.ExceptionSpec.Type == EST_ComputedNoexcept) {
3025     Size += sizeof(Expr*);
3026   } else if (EPI.ExceptionSpec.Type == EST_Uninstantiated) {
3027     Size += 2 * sizeof(FunctionDecl*);
3028   } else if (EPI.ExceptionSpec.Type == EST_Unevaluated) {
3029     Size += sizeof(FunctionDecl*);
3030   }
3031   if (EPI.ConsumedParameters)
3032     Size += NumArgs * sizeof(bool);
3033 
3034   FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment);
3035   FunctionProtoType::ExtProtoInfo newEPI = EPI;
3036   new (FTP) FunctionProtoType(ResultTy, ArgArray, Canonical, newEPI);
3037   Types.push_back(FTP);
3038   FunctionProtoTypes.InsertNode(FTP, InsertPos);
3039   return QualType(FTP, 0);
3040 }
3041 
3042 #ifndef NDEBUG
NeedsInjectedClassNameType(const RecordDecl * D)3043 static bool NeedsInjectedClassNameType(const RecordDecl *D) {
3044   if (!isa<CXXRecordDecl>(D)) return false;
3045   const CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
3046   if (isa<ClassTemplatePartialSpecializationDecl>(RD))
3047     return true;
3048   if (RD->getDescribedClassTemplate() &&
3049       !isa<ClassTemplateSpecializationDecl>(RD))
3050     return true;
3051   return false;
3052 }
3053 #endif
3054 
3055 /// getInjectedClassNameType - Return the unique reference to the
3056 /// injected class name type for the specified templated declaration.
getInjectedClassNameType(CXXRecordDecl * Decl,QualType TST) const3057 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl,
3058                                               QualType TST) const {
3059   assert(NeedsInjectedClassNameType(Decl));
3060   if (Decl->TypeForDecl) {
3061     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3062   } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) {
3063     assert(PrevDecl->TypeForDecl && "previous declaration has no type");
3064     Decl->TypeForDecl = PrevDecl->TypeForDecl;
3065     assert(isa<InjectedClassNameType>(Decl->TypeForDecl));
3066   } else {
3067     Type *newType =
3068       new (*this, TypeAlignment) InjectedClassNameType(Decl, TST);
3069     Decl->TypeForDecl = newType;
3070     Types.push_back(newType);
3071   }
3072   return QualType(Decl->TypeForDecl, 0);
3073 }
3074 
3075 /// getTypeDeclType - Return the unique reference to the type for the
3076 /// specified type declaration.
getTypeDeclTypeSlow(const TypeDecl * Decl) const3077 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const {
3078   assert(Decl && "Passed null for Decl param");
3079   assert(!Decl->TypeForDecl && "TypeForDecl present in slow case");
3080 
3081   if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl))
3082     return getTypedefType(Typedef);
3083 
3084   assert(!isa<TemplateTypeParmDecl>(Decl) &&
3085          "Template type parameter types are always available.");
3086 
3087   if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) {
3088     assert(Record->isFirstDecl() && "struct/union has previous declaration");
3089     assert(!NeedsInjectedClassNameType(Record));
3090     return getRecordType(Record);
3091   } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) {
3092     assert(Enum->isFirstDecl() && "enum has previous declaration");
3093     return getEnumType(Enum);
3094   } else if (const UnresolvedUsingTypenameDecl *Using =
3095                dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) {
3096     Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using);
3097     Decl->TypeForDecl = newType;
3098     Types.push_back(newType);
3099   } else
3100     llvm_unreachable("TypeDecl without a type?");
3101 
3102   return QualType(Decl->TypeForDecl, 0);
3103 }
3104 
3105 /// getTypedefType - Return the unique reference to the type for the
3106 /// specified typedef name decl.
3107 QualType
getTypedefType(const TypedefNameDecl * Decl,QualType Canonical) const3108 ASTContext::getTypedefType(const TypedefNameDecl *Decl,
3109                            QualType Canonical) const {
3110   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3111 
3112   if (Canonical.isNull())
3113     Canonical = getCanonicalType(Decl->getUnderlyingType());
3114   TypedefType *newType = new(*this, TypeAlignment)
3115     TypedefType(Type::Typedef, Decl, Canonical);
3116   Decl->TypeForDecl = newType;
3117   Types.push_back(newType);
3118   return QualType(newType, 0);
3119 }
3120 
getRecordType(const RecordDecl * Decl) const3121 QualType ASTContext::getRecordType(const RecordDecl *Decl) const {
3122   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3123 
3124   if (const RecordDecl *PrevDecl = Decl->getPreviousDecl())
3125     if (PrevDecl->TypeForDecl)
3126       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3127 
3128   RecordType *newType = new (*this, TypeAlignment) RecordType(Decl);
3129   Decl->TypeForDecl = newType;
3130   Types.push_back(newType);
3131   return QualType(newType, 0);
3132 }
3133 
getEnumType(const EnumDecl * Decl) const3134 QualType ASTContext::getEnumType(const EnumDecl *Decl) const {
3135   if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
3136 
3137   if (const EnumDecl *PrevDecl = Decl->getPreviousDecl())
3138     if (PrevDecl->TypeForDecl)
3139       return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0);
3140 
3141   EnumType *newType = new (*this, TypeAlignment) EnumType(Decl);
3142   Decl->TypeForDecl = newType;
3143   Types.push_back(newType);
3144   return QualType(newType, 0);
3145 }
3146 
getAttributedType(AttributedType::Kind attrKind,QualType modifiedType,QualType equivalentType)3147 QualType ASTContext::getAttributedType(AttributedType::Kind attrKind,
3148                                        QualType modifiedType,
3149                                        QualType equivalentType) {
3150   llvm::FoldingSetNodeID id;
3151   AttributedType::Profile(id, attrKind, modifiedType, equivalentType);
3152 
3153   void *insertPos = nullptr;
3154   AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos);
3155   if (type) return QualType(type, 0);
3156 
3157   QualType canon = getCanonicalType(equivalentType);
3158   type = new (*this, TypeAlignment)
3159            AttributedType(canon, attrKind, modifiedType, equivalentType);
3160 
3161   Types.push_back(type);
3162   AttributedTypes.InsertNode(type, insertPos);
3163 
3164   return QualType(type, 0);
3165 }
3166 
3167 
3168 /// \brief Retrieve a substitution-result type.
3169 QualType
getSubstTemplateTypeParmType(const TemplateTypeParmType * Parm,QualType Replacement) const3170 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm,
3171                                          QualType Replacement) const {
3172   assert(Replacement.isCanonical()
3173          && "replacement types must always be canonical");
3174 
3175   llvm::FoldingSetNodeID ID;
3176   SubstTemplateTypeParmType::Profile(ID, Parm, Replacement);
3177   void *InsertPos = nullptr;
3178   SubstTemplateTypeParmType *SubstParm
3179     = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3180 
3181   if (!SubstParm) {
3182     SubstParm = new (*this, TypeAlignment)
3183       SubstTemplateTypeParmType(Parm, Replacement);
3184     Types.push_back(SubstParm);
3185     SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3186   }
3187 
3188   return QualType(SubstParm, 0);
3189 }
3190 
3191 /// \brief Retrieve a
getSubstTemplateTypeParmPackType(const TemplateTypeParmType * Parm,const TemplateArgument & ArgPack)3192 QualType ASTContext::getSubstTemplateTypeParmPackType(
3193                                           const TemplateTypeParmType *Parm,
3194                                               const TemplateArgument &ArgPack) {
3195 #ifndef NDEBUG
3196   for (const auto &P : ArgPack.pack_elements()) {
3197     assert(P.getKind() == TemplateArgument::Type &&"Pack contains a non-type");
3198     assert(P.getAsType().isCanonical() && "Pack contains non-canonical type");
3199   }
3200 #endif
3201 
3202   llvm::FoldingSetNodeID ID;
3203   SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack);
3204   void *InsertPos = nullptr;
3205   if (SubstTemplateTypeParmPackType *SubstParm
3206         = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos))
3207     return QualType(SubstParm, 0);
3208 
3209   QualType Canon;
3210   if (!Parm->isCanonicalUnqualified()) {
3211     Canon = getCanonicalType(QualType(Parm, 0));
3212     Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon),
3213                                              ArgPack);
3214     SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos);
3215   }
3216 
3217   SubstTemplateTypeParmPackType *SubstParm
3218     = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon,
3219                                                                ArgPack);
3220   Types.push_back(SubstParm);
3221   SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos);
3222   return QualType(SubstParm, 0);
3223 }
3224 
3225 /// \brief Retrieve the template type parameter type for a template
3226 /// parameter or parameter pack with the given depth, index, and (optionally)
3227 /// name.
getTemplateTypeParmType(unsigned Depth,unsigned Index,bool ParameterPack,TemplateTypeParmDecl * TTPDecl) const3228 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index,
3229                                              bool ParameterPack,
3230                                              TemplateTypeParmDecl *TTPDecl) const {
3231   llvm::FoldingSetNodeID ID;
3232   TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl);
3233   void *InsertPos = nullptr;
3234   TemplateTypeParmType *TypeParm
3235     = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3236 
3237   if (TypeParm)
3238     return QualType(TypeParm, 0);
3239 
3240   if (TTPDecl) {
3241     QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack);
3242     TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon);
3243 
3244     TemplateTypeParmType *TypeCheck
3245       = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos);
3246     assert(!TypeCheck && "Template type parameter canonical type broken");
3247     (void)TypeCheck;
3248   } else
3249     TypeParm = new (*this, TypeAlignment)
3250       TemplateTypeParmType(Depth, Index, ParameterPack);
3251 
3252   Types.push_back(TypeParm);
3253   TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos);
3254 
3255   return QualType(TypeParm, 0);
3256 }
3257 
3258 TypeSourceInfo *
getTemplateSpecializationTypeInfo(TemplateName Name,SourceLocation NameLoc,const TemplateArgumentListInfo & Args,QualType Underlying) const3259 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name,
3260                                               SourceLocation NameLoc,
3261                                         const TemplateArgumentListInfo &Args,
3262                                               QualType Underlying) const {
3263   assert(!Name.getAsDependentTemplateName() &&
3264          "No dependent template names here!");
3265   QualType TST = getTemplateSpecializationType(Name, Args, Underlying);
3266 
3267   TypeSourceInfo *DI = CreateTypeSourceInfo(TST);
3268   TemplateSpecializationTypeLoc TL =
3269       DI->getTypeLoc().castAs<TemplateSpecializationTypeLoc>();
3270   TL.setTemplateKeywordLoc(SourceLocation());
3271   TL.setTemplateNameLoc(NameLoc);
3272   TL.setLAngleLoc(Args.getLAngleLoc());
3273   TL.setRAngleLoc(Args.getRAngleLoc());
3274   for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
3275     TL.setArgLocInfo(i, Args[i].getLocInfo());
3276   return DI;
3277 }
3278 
3279 QualType
getTemplateSpecializationType(TemplateName Template,const TemplateArgumentListInfo & Args,QualType Underlying) const3280 ASTContext::getTemplateSpecializationType(TemplateName Template,
3281                                           const TemplateArgumentListInfo &Args,
3282                                           QualType Underlying) const {
3283   assert(!Template.getAsDependentTemplateName() &&
3284          "No dependent template names here!");
3285 
3286   unsigned NumArgs = Args.size();
3287 
3288   SmallVector<TemplateArgument, 4> ArgVec;
3289   ArgVec.reserve(NumArgs);
3290   for (unsigned i = 0; i != NumArgs; ++i)
3291     ArgVec.push_back(Args[i].getArgument());
3292 
3293   return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs,
3294                                        Underlying);
3295 }
3296 
3297 #ifndef NDEBUG
hasAnyPackExpansions(const TemplateArgument * Args,unsigned NumArgs)3298 static bool hasAnyPackExpansions(const TemplateArgument *Args,
3299                                  unsigned NumArgs) {
3300   for (unsigned I = 0; I != NumArgs; ++I)
3301     if (Args[I].isPackExpansion())
3302       return true;
3303 
3304   return true;
3305 }
3306 #endif
3307 
3308 QualType
getTemplateSpecializationType(TemplateName Template,const TemplateArgument * Args,unsigned NumArgs,QualType Underlying) const3309 ASTContext::getTemplateSpecializationType(TemplateName Template,
3310                                           const TemplateArgument *Args,
3311                                           unsigned NumArgs,
3312                                           QualType Underlying) const {
3313   assert(!Template.getAsDependentTemplateName() &&
3314          "No dependent template names here!");
3315   // Look through qualified template names.
3316   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3317     Template = TemplateName(QTN->getTemplateDecl());
3318 
3319   bool IsTypeAlias =
3320     Template.getAsTemplateDecl() &&
3321     isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl());
3322   QualType CanonType;
3323   if (!Underlying.isNull())
3324     CanonType = getCanonicalType(Underlying);
3325   else {
3326     // We can get here with an alias template when the specialization contains
3327     // a pack expansion that does not match up with a parameter pack.
3328     assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) &&
3329            "Caller must compute aliased type");
3330     IsTypeAlias = false;
3331     CanonType = getCanonicalTemplateSpecializationType(Template, Args,
3332                                                        NumArgs);
3333   }
3334 
3335   // Allocate the (non-canonical) template specialization type, but don't
3336   // try to unique it: these types typically have location information that
3337   // we don't unique and don't want to lose.
3338   void *Mem = Allocate(sizeof(TemplateSpecializationType) +
3339                        sizeof(TemplateArgument) * NumArgs +
3340                        (IsTypeAlias? sizeof(QualType) : 0),
3341                        TypeAlignment);
3342   TemplateSpecializationType *Spec
3343     = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType,
3344                                          IsTypeAlias ? Underlying : QualType());
3345 
3346   Types.push_back(Spec);
3347   return QualType(Spec, 0);
3348 }
3349 
3350 QualType
getCanonicalTemplateSpecializationType(TemplateName Template,const TemplateArgument * Args,unsigned NumArgs) const3351 ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template,
3352                                                    const TemplateArgument *Args,
3353                                                    unsigned NumArgs) const {
3354   assert(!Template.getAsDependentTemplateName() &&
3355          "No dependent template names here!");
3356 
3357   // Look through qualified template names.
3358   if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
3359     Template = TemplateName(QTN->getTemplateDecl());
3360 
3361   // Build the canonical template specialization type.
3362   TemplateName CanonTemplate = getCanonicalTemplateName(Template);
3363   SmallVector<TemplateArgument, 4> CanonArgs;
3364   CanonArgs.reserve(NumArgs);
3365   for (unsigned I = 0; I != NumArgs; ++I)
3366     CanonArgs.push_back(getCanonicalTemplateArgument(Args[I]));
3367 
3368   // Determine whether this canonical template specialization type already
3369   // exists.
3370   llvm::FoldingSetNodeID ID;
3371   TemplateSpecializationType::Profile(ID, CanonTemplate,
3372                                       CanonArgs.data(), NumArgs, *this);
3373 
3374   void *InsertPos = nullptr;
3375   TemplateSpecializationType *Spec
3376     = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3377 
3378   if (!Spec) {
3379     // Allocate a new canonical template specialization type.
3380     void *Mem = Allocate((sizeof(TemplateSpecializationType) +
3381                           sizeof(TemplateArgument) * NumArgs),
3382                          TypeAlignment);
3383     Spec = new (Mem) TemplateSpecializationType(CanonTemplate,
3384                                                 CanonArgs.data(), NumArgs,
3385                                                 QualType(), QualType());
3386     Types.push_back(Spec);
3387     TemplateSpecializationTypes.InsertNode(Spec, InsertPos);
3388   }
3389 
3390   assert(Spec->isDependentType() &&
3391          "Non-dependent template-id type must have a canonical type");
3392   return QualType(Spec, 0);
3393 }
3394 
3395 QualType
getElaboratedType(ElaboratedTypeKeyword Keyword,NestedNameSpecifier * NNS,QualType NamedType) const3396 ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword,
3397                               NestedNameSpecifier *NNS,
3398                               QualType NamedType) const {
3399   llvm::FoldingSetNodeID ID;
3400   ElaboratedType::Profile(ID, Keyword, NNS, NamedType);
3401 
3402   void *InsertPos = nullptr;
3403   ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3404   if (T)
3405     return QualType(T, 0);
3406 
3407   QualType Canon = NamedType;
3408   if (!Canon.isCanonical()) {
3409     Canon = getCanonicalType(NamedType);
3410     ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos);
3411     assert(!CheckT && "Elaborated canonical type broken");
3412     (void)CheckT;
3413   }
3414 
3415   T = new (*this, TypeAlignment) ElaboratedType(Keyword, NNS, NamedType, Canon);
3416   Types.push_back(T);
3417   ElaboratedTypes.InsertNode(T, InsertPos);
3418   return QualType(T, 0);
3419 }
3420 
3421 QualType
getParenType(QualType InnerType) const3422 ASTContext::getParenType(QualType InnerType) const {
3423   llvm::FoldingSetNodeID ID;
3424   ParenType::Profile(ID, InnerType);
3425 
3426   void *InsertPos = nullptr;
3427   ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3428   if (T)
3429     return QualType(T, 0);
3430 
3431   QualType Canon = InnerType;
3432   if (!Canon.isCanonical()) {
3433     Canon = getCanonicalType(InnerType);
3434     ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos);
3435     assert(!CheckT && "Paren canonical type broken");
3436     (void)CheckT;
3437   }
3438 
3439   T = new (*this, TypeAlignment) ParenType(InnerType, Canon);
3440   Types.push_back(T);
3441   ParenTypes.InsertNode(T, InsertPos);
3442   return QualType(T, 0);
3443 }
3444 
getDependentNameType(ElaboratedTypeKeyword Keyword,NestedNameSpecifier * NNS,const IdentifierInfo * Name,QualType Canon) const3445 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword,
3446                                           NestedNameSpecifier *NNS,
3447                                           const IdentifierInfo *Name,
3448                                           QualType Canon) const {
3449   if (Canon.isNull()) {
3450     NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3451     ElaboratedTypeKeyword CanonKeyword = Keyword;
3452     if (Keyword == ETK_None)
3453       CanonKeyword = ETK_Typename;
3454 
3455     if (CanonNNS != NNS || CanonKeyword != Keyword)
3456       Canon = getDependentNameType(CanonKeyword, CanonNNS, Name);
3457   }
3458 
3459   llvm::FoldingSetNodeID ID;
3460   DependentNameType::Profile(ID, Keyword, NNS, Name);
3461 
3462   void *InsertPos = nullptr;
3463   DependentNameType *T
3464     = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos);
3465   if (T)
3466     return QualType(T, 0);
3467 
3468   T = new (*this, TypeAlignment) DependentNameType(Keyword, NNS, Name, Canon);
3469   Types.push_back(T);
3470   DependentNameTypes.InsertNode(T, InsertPos);
3471   return QualType(T, 0);
3472 }
3473 
3474 QualType
getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,NestedNameSpecifier * NNS,const IdentifierInfo * Name,const TemplateArgumentListInfo & Args) const3475 ASTContext::getDependentTemplateSpecializationType(
3476                                  ElaboratedTypeKeyword Keyword,
3477                                  NestedNameSpecifier *NNS,
3478                                  const IdentifierInfo *Name,
3479                                  const TemplateArgumentListInfo &Args) const {
3480   // TODO: avoid this copy
3481   SmallVector<TemplateArgument, 16> ArgCopy;
3482   for (unsigned I = 0, E = Args.size(); I != E; ++I)
3483     ArgCopy.push_back(Args[I].getArgument());
3484   return getDependentTemplateSpecializationType(Keyword, NNS, Name,
3485                                                 ArgCopy.size(),
3486                                                 ArgCopy.data());
3487 }
3488 
3489 QualType
getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,NestedNameSpecifier * NNS,const IdentifierInfo * Name,unsigned NumArgs,const TemplateArgument * Args) const3490 ASTContext::getDependentTemplateSpecializationType(
3491                                  ElaboratedTypeKeyword Keyword,
3492                                  NestedNameSpecifier *NNS,
3493                                  const IdentifierInfo *Name,
3494                                  unsigned NumArgs,
3495                                  const TemplateArgument *Args) const {
3496   assert((!NNS || NNS->isDependent()) &&
3497          "nested-name-specifier must be dependent");
3498 
3499   llvm::FoldingSetNodeID ID;
3500   DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS,
3501                                                Name, NumArgs, Args);
3502 
3503   void *InsertPos = nullptr;
3504   DependentTemplateSpecializationType *T
3505     = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3506   if (T)
3507     return QualType(T, 0);
3508 
3509   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
3510 
3511   ElaboratedTypeKeyword CanonKeyword = Keyword;
3512   if (Keyword == ETK_None) CanonKeyword = ETK_Typename;
3513 
3514   bool AnyNonCanonArgs = false;
3515   SmallVector<TemplateArgument, 16> CanonArgs(NumArgs);
3516   for (unsigned I = 0; I != NumArgs; ++I) {
3517     CanonArgs[I] = getCanonicalTemplateArgument(Args[I]);
3518     if (!CanonArgs[I].structurallyEquals(Args[I]))
3519       AnyNonCanonArgs = true;
3520   }
3521 
3522   QualType Canon;
3523   if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) {
3524     Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS,
3525                                                    Name, NumArgs,
3526                                                    CanonArgs.data());
3527 
3528     // Find the insert position again.
3529     DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos);
3530   }
3531 
3532   void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) +
3533                         sizeof(TemplateArgument) * NumArgs),
3534                        TypeAlignment);
3535   T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS,
3536                                                     Name, NumArgs, Args, Canon);
3537   Types.push_back(T);
3538   DependentTemplateSpecializationTypes.InsertNode(T, InsertPos);
3539   return QualType(T, 0);
3540 }
3541 
getPackExpansionType(QualType Pattern,Optional<unsigned> NumExpansions)3542 QualType ASTContext::getPackExpansionType(QualType Pattern,
3543                                           Optional<unsigned> NumExpansions) {
3544   llvm::FoldingSetNodeID ID;
3545   PackExpansionType::Profile(ID, Pattern, NumExpansions);
3546 
3547   assert(Pattern->containsUnexpandedParameterPack() &&
3548          "Pack expansions must expand one or more parameter packs");
3549   void *InsertPos = nullptr;
3550   PackExpansionType *T
3551     = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3552   if (T)
3553     return QualType(T, 0);
3554 
3555   QualType Canon;
3556   if (!Pattern.isCanonical()) {
3557     Canon = getCanonicalType(Pattern);
3558     // The canonical type might not contain an unexpanded parameter pack, if it
3559     // contains an alias template specialization which ignores one of its
3560     // parameters.
3561     if (Canon->containsUnexpandedParameterPack()) {
3562       Canon = getPackExpansionType(Canon, NumExpansions);
3563 
3564       // Find the insert position again, in case we inserted an element into
3565       // PackExpansionTypes and invalidated our insert position.
3566       PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos);
3567     }
3568   }
3569 
3570   T = new (*this, TypeAlignment)
3571       PackExpansionType(Pattern, Canon, NumExpansions);
3572   Types.push_back(T);
3573   PackExpansionTypes.InsertNode(T, InsertPos);
3574   return QualType(T, 0);
3575 }
3576 
3577 /// CmpProtocolNames - Comparison predicate for sorting protocols
3578 /// alphabetically.
CmpProtocolNames(ObjCProtocolDecl * const * LHS,ObjCProtocolDecl * const * RHS)3579 static int CmpProtocolNames(ObjCProtocolDecl *const *LHS,
3580                             ObjCProtocolDecl *const *RHS) {
3581   return DeclarationName::compare((*LHS)->getDeclName(), (*RHS)->getDeclName());
3582 }
3583 
areSortedAndUniqued(ObjCProtocolDecl * const * Protocols,unsigned NumProtocols)3584 static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols,
3585                                 unsigned NumProtocols) {
3586   if (NumProtocols == 0) return true;
3587 
3588   if (Protocols[0]->getCanonicalDecl() != Protocols[0])
3589     return false;
3590 
3591   for (unsigned i = 1; i != NumProtocols; ++i)
3592     if (CmpProtocolNames(&Protocols[i - 1], &Protocols[i]) >= 0 ||
3593         Protocols[i]->getCanonicalDecl() != Protocols[i])
3594       return false;
3595   return true;
3596 }
3597 
SortAndUniqueProtocols(ObjCProtocolDecl ** Protocols,unsigned & NumProtocols)3598 static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols,
3599                                    unsigned &NumProtocols) {
3600   ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols;
3601 
3602   // Sort protocols, keyed by name.
3603   llvm::array_pod_sort(Protocols, ProtocolsEnd, CmpProtocolNames);
3604 
3605   // Canonicalize.
3606   for (unsigned I = 0, N = NumProtocols; I != N; ++I)
3607     Protocols[I] = Protocols[I]->getCanonicalDecl();
3608 
3609   // Remove duplicates.
3610   ProtocolsEnd = std::unique(Protocols, ProtocolsEnd);
3611   NumProtocols = ProtocolsEnd-Protocols;
3612 }
3613 
getObjCObjectType(QualType BaseType,ObjCProtocolDecl * const * Protocols,unsigned NumProtocols) const3614 QualType ASTContext::getObjCObjectType(QualType BaseType,
3615                                        ObjCProtocolDecl * const *Protocols,
3616                                        unsigned NumProtocols) const {
3617   return getObjCObjectType(BaseType, { },
3618                            llvm::makeArrayRef(Protocols, NumProtocols),
3619                            /*isKindOf=*/false);
3620 }
3621 
getObjCObjectType(QualType baseType,ArrayRef<QualType> typeArgs,ArrayRef<ObjCProtocolDecl * > protocols,bool isKindOf) const3622 QualType ASTContext::getObjCObjectType(
3623            QualType baseType,
3624            ArrayRef<QualType> typeArgs,
3625            ArrayRef<ObjCProtocolDecl *> protocols,
3626            bool isKindOf) const {
3627   // If the base type is an interface and there aren't any protocols or
3628   // type arguments to add, then the interface type will do just fine.
3629   if (typeArgs.empty() && protocols.empty() && !isKindOf &&
3630       isa<ObjCInterfaceType>(baseType))
3631     return baseType;
3632 
3633   // Look in the folding set for an existing type.
3634   llvm::FoldingSetNodeID ID;
3635   ObjCObjectTypeImpl::Profile(ID, baseType, typeArgs, protocols, isKindOf);
3636   void *InsertPos = nullptr;
3637   if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos))
3638     return QualType(QT, 0);
3639 
3640   // Determine the type arguments to be used for canonicalization,
3641   // which may be explicitly specified here or written on the base
3642   // type.
3643   ArrayRef<QualType> effectiveTypeArgs = typeArgs;
3644   if (effectiveTypeArgs.empty()) {
3645     if (auto baseObject = baseType->getAs<ObjCObjectType>())
3646       effectiveTypeArgs = baseObject->getTypeArgs();
3647   }
3648 
3649   // Build the canonical type, which has the canonical base type and a
3650   // sorted-and-uniqued list of protocols and the type arguments
3651   // canonicalized.
3652   QualType canonical;
3653   bool typeArgsAreCanonical = std::all_of(effectiveTypeArgs.begin(),
3654                                           effectiveTypeArgs.end(),
3655                                           [&](QualType type) {
3656                                             return type.isCanonical();
3657                                           });
3658   bool protocolsSorted = areSortedAndUniqued(protocols.data(),
3659                                              protocols.size());
3660   if (!typeArgsAreCanonical || !protocolsSorted || !baseType.isCanonical()) {
3661     // Determine the canonical type arguments.
3662     ArrayRef<QualType> canonTypeArgs;
3663     SmallVector<QualType, 4> canonTypeArgsVec;
3664     if (!typeArgsAreCanonical) {
3665       canonTypeArgsVec.reserve(effectiveTypeArgs.size());
3666       for (auto typeArg : effectiveTypeArgs)
3667         canonTypeArgsVec.push_back(getCanonicalType(typeArg));
3668       canonTypeArgs = canonTypeArgsVec;
3669     } else {
3670       canonTypeArgs = effectiveTypeArgs;
3671     }
3672 
3673     ArrayRef<ObjCProtocolDecl *> canonProtocols;
3674     SmallVector<ObjCProtocolDecl*, 8> canonProtocolsVec;
3675     if (!protocolsSorted) {
3676       canonProtocolsVec.insert(canonProtocolsVec.begin(),
3677                                protocols.begin(),
3678                                protocols.end());
3679       unsigned uniqueCount = protocols.size();
3680       SortAndUniqueProtocols(&canonProtocolsVec[0], uniqueCount);
3681       canonProtocols = llvm::makeArrayRef(&canonProtocolsVec[0], uniqueCount);
3682     } else {
3683       canonProtocols = protocols;
3684     }
3685 
3686     canonical = getObjCObjectType(getCanonicalType(baseType), canonTypeArgs,
3687                                   canonProtocols, isKindOf);
3688 
3689     // Regenerate InsertPos.
3690     ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos);
3691   }
3692 
3693   unsigned size = sizeof(ObjCObjectTypeImpl);
3694   size += typeArgs.size() * sizeof(QualType);
3695   size += protocols.size() * sizeof(ObjCProtocolDecl *);
3696   void *mem = Allocate(size, TypeAlignment);
3697   ObjCObjectTypeImpl *T =
3698     new (mem) ObjCObjectTypeImpl(canonical, baseType, typeArgs, protocols,
3699                                  isKindOf);
3700 
3701   Types.push_back(T);
3702   ObjCObjectTypes.InsertNode(T, InsertPos);
3703   return QualType(T, 0);
3704 }
3705 
3706 /// ObjCObjectAdoptsQTypeProtocols - Checks that protocols in IC's
3707 /// protocol list adopt all protocols in QT's qualified-id protocol
3708 /// list.
ObjCObjectAdoptsQTypeProtocols(QualType QT,ObjCInterfaceDecl * IC)3709 bool ASTContext::ObjCObjectAdoptsQTypeProtocols(QualType QT,
3710                                                 ObjCInterfaceDecl *IC) {
3711   if (!QT->isObjCQualifiedIdType())
3712     return false;
3713 
3714   if (const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>()) {
3715     // If both the right and left sides have qualifiers.
3716     for (auto *Proto : OPT->quals()) {
3717       if (!IC->ClassImplementsProtocol(Proto, false))
3718         return false;
3719     }
3720     return true;
3721   }
3722   return false;
3723 }
3724 
3725 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
3726 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
3727 /// of protocols.
QIdProtocolsAdoptObjCObjectProtocols(QualType QT,ObjCInterfaceDecl * IDecl)3728 bool ASTContext::QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
3729                                                 ObjCInterfaceDecl *IDecl) {
3730   if (!QT->isObjCQualifiedIdType())
3731     return false;
3732   const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
3733   if (!OPT)
3734     return false;
3735   if (!IDecl->hasDefinition())
3736     return false;
3737   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocols;
3738   CollectInheritedProtocols(IDecl, InheritedProtocols);
3739   if (InheritedProtocols.empty())
3740     return false;
3741   // Check that if every protocol in list of id<plist> conforms to a protcol
3742   // of IDecl's, then bridge casting is ok.
3743   bool Conforms = false;
3744   for (auto *Proto : OPT->quals()) {
3745     Conforms = false;
3746     for (auto *PI : InheritedProtocols) {
3747       if (ProtocolCompatibleWithProtocol(Proto, PI)) {
3748         Conforms = true;
3749         break;
3750       }
3751     }
3752     if (!Conforms)
3753       break;
3754   }
3755   if (Conforms)
3756     return true;
3757 
3758   for (auto *PI : InheritedProtocols) {
3759     // If both the right and left sides have qualifiers.
3760     bool Adopts = false;
3761     for (auto *Proto : OPT->quals()) {
3762       // return 'true' if 'PI' is in the inheritance hierarchy of Proto
3763       if ((Adopts = ProtocolCompatibleWithProtocol(PI, Proto)))
3764         break;
3765     }
3766     if (!Adopts)
3767       return false;
3768   }
3769   return true;
3770 }
3771 
3772 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for
3773 /// the given object type.
getObjCObjectPointerType(QualType ObjectT) const3774 QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const {
3775   llvm::FoldingSetNodeID ID;
3776   ObjCObjectPointerType::Profile(ID, ObjectT);
3777 
3778   void *InsertPos = nullptr;
3779   if (ObjCObjectPointerType *QT =
3780               ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos))
3781     return QualType(QT, 0);
3782 
3783   // Find the canonical object type.
3784   QualType Canonical;
3785   if (!ObjectT.isCanonical()) {
3786     Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT));
3787 
3788     // Regenerate InsertPos.
3789     ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos);
3790   }
3791 
3792   // No match.
3793   void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment);
3794   ObjCObjectPointerType *QType =
3795     new (Mem) ObjCObjectPointerType(Canonical, ObjectT);
3796 
3797   Types.push_back(QType);
3798   ObjCObjectPointerTypes.InsertNode(QType, InsertPos);
3799   return QualType(QType, 0);
3800 }
3801 
3802 /// getObjCInterfaceType - Return the unique reference to the type for the
3803 /// specified ObjC interface decl. The list of protocols is optional.
getObjCInterfaceType(const ObjCInterfaceDecl * Decl,ObjCInterfaceDecl * PrevDecl) const3804 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
3805                                           ObjCInterfaceDecl *PrevDecl) const {
3806   if (Decl->TypeForDecl)
3807     return QualType(Decl->TypeForDecl, 0);
3808 
3809   if (PrevDecl) {
3810     assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
3811     Decl->TypeForDecl = PrevDecl->TypeForDecl;
3812     return QualType(PrevDecl->TypeForDecl, 0);
3813   }
3814 
3815   // Prefer the definition, if there is one.
3816   if (const ObjCInterfaceDecl *Def = Decl->getDefinition())
3817     Decl = Def;
3818 
3819   void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment);
3820   ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl);
3821   Decl->TypeForDecl = T;
3822   Types.push_back(T);
3823   return QualType(T, 0);
3824 }
3825 
3826 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique
3827 /// TypeOfExprType AST's (since expression's are never shared). For example,
3828 /// multiple declarations that refer to "typeof(x)" all contain different
3829 /// DeclRefExpr's. This doesn't effect the type checker, since it operates
3830 /// on canonical type's (which are always unique).
getTypeOfExprType(Expr * tofExpr) const3831 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const {
3832   TypeOfExprType *toe;
3833   if (tofExpr->isTypeDependent()) {
3834     llvm::FoldingSetNodeID ID;
3835     DependentTypeOfExprType::Profile(ID, *this, tofExpr);
3836 
3837     void *InsertPos = nullptr;
3838     DependentTypeOfExprType *Canon
3839       = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos);
3840     if (Canon) {
3841       // We already have a "canonical" version of an identical, dependent
3842       // typeof(expr) type. Use that as our canonical type.
3843       toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr,
3844                                           QualType((TypeOfExprType*)Canon, 0));
3845     } else {
3846       // Build a new, canonical typeof(expr) type.
3847       Canon
3848         = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr);
3849       DependentTypeOfExprTypes.InsertNode(Canon, InsertPos);
3850       toe = Canon;
3851     }
3852   } else {
3853     QualType Canonical = getCanonicalType(tofExpr->getType());
3854     toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical);
3855   }
3856   Types.push_back(toe);
3857   return QualType(toe, 0);
3858 }
3859 
3860 /// getTypeOfType -  Unlike many "get<Type>" functions, we don't unique
3861 /// TypeOfType nodes. The only motivation to unique these nodes would be
3862 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be
3863 /// an issue. This doesn't affect the type checker, since it operates
3864 /// on canonical types (which are always unique).
getTypeOfType(QualType tofType) const3865 QualType ASTContext::getTypeOfType(QualType tofType) const {
3866   QualType Canonical = getCanonicalType(tofType);
3867   TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical);
3868   Types.push_back(tot);
3869   return QualType(tot, 0);
3870 }
3871 
3872 
3873 /// \brief Unlike many "get<Type>" functions, we don't unique DecltypeType
3874 /// nodes. This would never be helpful, since each such type has its own
3875 /// expression, and would not give a significant memory saving, since there
3876 /// is an Expr tree under each such type.
getDecltypeType(Expr * e,QualType UnderlyingType) const3877 QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const {
3878   DecltypeType *dt;
3879 
3880   // C++11 [temp.type]p2:
3881   //   If an expression e involves a template parameter, decltype(e) denotes a
3882   //   unique dependent type. Two such decltype-specifiers refer to the same
3883   //   type only if their expressions are equivalent (14.5.6.1).
3884   if (e->isInstantiationDependent()) {
3885     llvm::FoldingSetNodeID ID;
3886     DependentDecltypeType::Profile(ID, *this, e);
3887 
3888     void *InsertPos = nullptr;
3889     DependentDecltypeType *Canon
3890       = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos);
3891     if (!Canon) {
3892       // Build a new, canonical typeof(expr) type.
3893       Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e);
3894       DependentDecltypeTypes.InsertNode(Canon, InsertPos);
3895     }
3896     dt = new (*this, TypeAlignment)
3897         DecltypeType(e, UnderlyingType, QualType((DecltypeType *)Canon, 0));
3898   } else {
3899     dt = new (*this, TypeAlignment)
3900         DecltypeType(e, UnderlyingType, getCanonicalType(UnderlyingType));
3901   }
3902   Types.push_back(dt);
3903   return QualType(dt, 0);
3904 }
3905 
3906 /// getUnaryTransformationType - We don't unique these, since the memory
3907 /// savings are minimal and these are rare.
getUnaryTransformType(QualType BaseType,QualType UnderlyingType,UnaryTransformType::UTTKind Kind) const3908 QualType ASTContext::getUnaryTransformType(QualType BaseType,
3909                                            QualType UnderlyingType,
3910                                            UnaryTransformType::UTTKind Kind)
3911     const {
3912   UnaryTransformType *Ty =
3913     new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType,
3914                                                    Kind,
3915                                  UnderlyingType->isDependentType() ?
3916                                  QualType() : getCanonicalType(UnderlyingType));
3917   Types.push_back(Ty);
3918   return QualType(Ty, 0);
3919 }
3920 
3921 /// getAutoType - Return the uniqued reference to the 'auto' type which has been
3922 /// deduced to the given type, or to the canonical undeduced 'auto' type, or the
3923 /// canonical deduced-but-dependent 'auto' type.
getAutoType(QualType DeducedType,bool IsDecltypeAuto,bool IsDependent) const3924 QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
3925                                  bool IsDependent) const {
3926   if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
3927     return getAutoDeductType();
3928 
3929   // Look in the folding set for an existing type.
3930   void *InsertPos = nullptr;
3931   llvm::FoldingSetNodeID ID;
3932   AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
3933   if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
3934     return QualType(AT, 0);
3935 
3936   AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
3937                                                      IsDecltypeAuto,
3938                                                      IsDependent);
3939   Types.push_back(AT);
3940   if (InsertPos)
3941     AutoTypes.InsertNode(AT, InsertPos);
3942   return QualType(AT, 0);
3943 }
3944 
3945 /// getAtomicType - Return the uniqued reference to the atomic type for
3946 /// the given value type.
getAtomicType(QualType T) const3947 QualType ASTContext::getAtomicType(QualType T) const {
3948   // Unique pointers, to guarantee there is only one pointer of a particular
3949   // structure.
3950   llvm::FoldingSetNodeID ID;
3951   AtomicType::Profile(ID, T);
3952 
3953   void *InsertPos = nullptr;
3954   if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos))
3955     return QualType(AT, 0);
3956 
3957   // If the atomic value type isn't canonical, this won't be a canonical type
3958   // either, so fill in the canonical type field.
3959   QualType Canonical;
3960   if (!T.isCanonical()) {
3961     Canonical = getAtomicType(getCanonicalType(T));
3962 
3963     // Get the new insert position for the node we care about.
3964     AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos);
3965     assert(!NewIP && "Shouldn't be in the map!"); (void)NewIP;
3966   }
3967   AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical);
3968   Types.push_back(New);
3969   AtomicTypes.InsertNode(New, InsertPos);
3970   return QualType(New, 0);
3971 }
3972 
3973 /// getAutoDeductType - Get type pattern for deducing against 'auto'.
getAutoDeductType() const3974 QualType ASTContext::getAutoDeductType() const {
3975   if (AutoDeductTy.isNull())
3976     AutoDeductTy = QualType(
3977       new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
3978                                           /*dependent*/false),
3979       0);
3980   return AutoDeductTy;
3981 }
3982 
3983 /// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'.
getAutoRRefDeductType() const3984 QualType ASTContext::getAutoRRefDeductType() const {
3985   if (AutoRRefDeductTy.isNull())
3986     AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType());
3987   assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern");
3988   return AutoRRefDeductTy;
3989 }
3990 
3991 /// getTagDeclType - Return the unique reference to the type for the
3992 /// specified TagDecl (struct/union/class/enum) decl.
getTagDeclType(const TagDecl * Decl) const3993 QualType ASTContext::getTagDeclType(const TagDecl *Decl) const {
3994   assert (Decl);
3995   // FIXME: What is the design on getTagDeclType when it requires casting
3996   // away const?  mutable?
3997   return getTypeDeclType(const_cast<TagDecl*>(Decl));
3998 }
3999 
4000 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result
4001 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and
4002 /// needs to agree with the definition in <stddef.h>.
getSizeType() const4003 CanQualType ASTContext::getSizeType() const {
4004   return getFromTargetType(Target->getSizeType());
4005 }
4006 
4007 /// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5).
getIntMaxType() const4008 CanQualType ASTContext::getIntMaxType() const {
4009   return getFromTargetType(Target->getIntMaxType());
4010 }
4011 
4012 /// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5).
getUIntMaxType() const4013 CanQualType ASTContext::getUIntMaxType() const {
4014   return getFromTargetType(Target->getUIntMaxType());
4015 }
4016 
4017 /// getSignedWCharType - Return the type of "signed wchar_t".
4018 /// Used when in C++, as a GCC extension.
getSignedWCharType() const4019 QualType ASTContext::getSignedWCharType() const {
4020   // FIXME: derive from "Target" ?
4021   return WCharTy;
4022 }
4023 
4024 /// getUnsignedWCharType - Return the type of "unsigned wchar_t".
4025 /// Used when in C++, as a GCC extension.
getUnsignedWCharType() const4026 QualType ASTContext::getUnsignedWCharType() const {
4027   // FIXME: derive from "Target" ?
4028   return UnsignedIntTy;
4029 }
4030 
getIntPtrType() const4031 QualType ASTContext::getIntPtrType() const {
4032   return getFromTargetType(Target->getIntPtrType());
4033 }
4034 
getUIntPtrType() const4035 QualType ASTContext::getUIntPtrType() const {
4036   return getCorrespondingUnsignedType(getIntPtrType());
4037 }
4038 
4039 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17)
4040 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
getPointerDiffType() const4041 QualType ASTContext::getPointerDiffType() const {
4042   return getFromTargetType(Target->getPtrDiffType(0));
4043 }
4044 
4045 /// \brief Return the unique type for "pid_t" defined in
4046 /// <sys/types.h>. We need this to compute the correct type for vfork().
getProcessIDType() const4047 QualType ASTContext::getProcessIDType() const {
4048   return getFromTargetType(Target->getProcessIDType());
4049 }
4050 
4051 //===----------------------------------------------------------------------===//
4052 //                              Type Operators
4053 //===----------------------------------------------------------------------===//
4054 
getCanonicalParamType(QualType T) const4055 CanQualType ASTContext::getCanonicalParamType(QualType T) const {
4056   // Push qualifiers into arrays, and then discard any remaining
4057   // qualifiers.
4058   T = getCanonicalType(T);
4059   T = getVariableArrayDecayedType(T);
4060   const Type *Ty = T.getTypePtr();
4061   QualType Result;
4062   if (isa<ArrayType>(Ty)) {
4063     Result = getArrayDecayedType(QualType(Ty,0));
4064   } else if (isa<FunctionType>(Ty)) {
4065     Result = getPointerType(QualType(Ty, 0));
4066   } else {
4067     Result = QualType(Ty, 0);
4068   }
4069 
4070   return CanQualType::CreateUnsafe(Result);
4071 }
4072 
getUnqualifiedArrayType(QualType type,Qualifiers & quals)4073 QualType ASTContext::getUnqualifiedArrayType(QualType type,
4074                                              Qualifiers &quals) {
4075   SplitQualType splitType = type.getSplitUnqualifiedType();
4076 
4077   // FIXME: getSplitUnqualifiedType() actually walks all the way to
4078   // the unqualified desugared type and then drops it on the floor.
4079   // We then have to strip that sugar back off with
4080   // getUnqualifiedDesugaredType(), which is silly.
4081   const ArrayType *AT =
4082     dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType());
4083 
4084   // If we don't have an array, just use the results in splitType.
4085   if (!AT) {
4086     quals = splitType.Quals;
4087     return QualType(splitType.Ty, 0);
4088   }
4089 
4090   // Otherwise, recurse on the array's element type.
4091   QualType elementType = AT->getElementType();
4092   QualType unqualElementType = getUnqualifiedArrayType(elementType, quals);
4093 
4094   // If that didn't change the element type, AT has no qualifiers, so we
4095   // can just use the results in splitType.
4096   if (elementType == unqualElementType) {
4097     assert(quals.empty()); // from the recursive call
4098     quals = splitType.Quals;
4099     return QualType(splitType.Ty, 0);
4100   }
4101 
4102   // Otherwise, add in the qualifiers from the outermost type, then
4103   // build the type back up.
4104   quals.addConsistentQualifiers(splitType.Quals);
4105 
4106   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
4107     return getConstantArrayType(unqualElementType, CAT->getSize(),
4108                                 CAT->getSizeModifier(), 0);
4109   }
4110 
4111   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
4112     return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0);
4113   }
4114 
4115   if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) {
4116     return getVariableArrayType(unqualElementType,
4117                                 VAT->getSizeExpr(),
4118                                 VAT->getSizeModifier(),
4119                                 VAT->getIndexTypeCVRQualifiers(),
4120                                 VAT->getBracketsRange());
4121   }
4122 
4123   const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT);
4124   return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(),
4125                                     DSAT->getSizeModifier(), 0,
4126                                     SourceRange());
4127 }
4128 
4129 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types  that
4130 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
4131 /// they point to and return true. If T1 and T2 aren't pointer types
4132 /// or pointer-to-member types, or if they are not similar at this
4133 /// level, returns false and leaves T1 and T2 unchanged. Top-level
4134 /// qualifiers on T1 and T2 are ignored. This function will typically
4135 /// be called in a loop that successively "unwraps" pointer and
4136 /// pointer-to-member types to compare them at each level.
UnwrapSimilarPointerTypes(QualType & T1,QualType & T2)4137 bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) {
4138   const PointerType *T1PtrType = T1->getAs<PointerType>(),
4139                     *T2PtrType = T2->getAs<PointerType>();
4140   if (T1PtrType && T2PtrType) {
4141     T1 = T1PtrType->getPointeeType();
4142     T2 = T2PtrType->getPointeeType();
4143     return true;
4144   }
4145 
4146   const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
4147                           *T2MPType = T2->getAs<MemberPointerType>();
4148   if (T1MPType && T2MPType &&
4149       hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0),
4150                              QualType(T2MPType->getClass(), 0))) {
4151     T1 = T1MPType->getPointeeType();
4152     T2 = T2MPType->getPointeeType();
4153     return true;
4154   }
4155 
4156   if (getLangOpts().ObjC1) {
4157     const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(),
4158                                 *T2OPType = T2->getAs<ObjCObjectPointerType>();
4159     if (T1OPType && T2OPType) {
4160       T1 = T1OPType->getPointeeType();
4161       T2 = T2OPType->getPointeeType();
4162       return true;
4163     }
4164   }
4165 
4166   // FIXME: Block pointers, too?
4167 
4168   return false;
4169 }
4170 
4171 DeclarationNameInfo
getNameForTemplate(TemplateName Name,SourceLocation NameLoc) const4172 ASTContext::getNameForTemplate(TemplateName Name,
4173                                SourceLocation NameLoc) const {
4174   switch (Name.getKind()) {
4175   case TemplateName::QualifiedTemplate:
4176   case TemplateName::Template:
4177     // DNInfo work in progress: CHECKME: what about DNLoc?
4178     return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(),
4179                                NameLoc);
4180 
4181   case TemplateName::OverloadedTemplate: {
4182     OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate();
4183     // DNInfo work in progress: CHECKME: what about DNLoc?
4184     return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc);
4185   }
4186 
4187   case TemplateName::DependentTemplate: {
4188     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4189     DeclarationName DName;
4190     if (DTN->isIdentifier()) {
4191       DName = DeclarationNames.getIdentifier(DTN->getIdentifier());
4192       return DeclarationNameInfo(DName, NameLoc);
4193     } else {
4194       DName = DeclarationNames.getCXXOperatorName(DTN->getOperator());
4195       // DNInfo work in progress: FIXME: source locations?
4196       DeclarationNameLoc DNLoc;
4197       DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding();
4198       DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding();
4199       return DeclarationNameInfo(DName, NameLoc, DNLoc);
4200     }
4201   }
4202 
4203   case TemplateName::SubstTemplateTemplateParm: {
4204     SubstTemplateTemplateParmStorage *subst
4205       = Name.getAsSubstTemplateTemplateParm();
4206     return DeclarationNameInfo(subst->getParameter()->getDeclName(),
4207                                NameLoc);
4208   }
4209 
4210   case TemplateName::SubstTemplateTemplateParmPack: {
4211     SubstTemplateTemplateParmPackStorage *subst
4212       = Name.getAsSubstTemplateTemplateParmPack();
4213     return DeclarationNameInfo(subst->getParameterPack()->getDeclName(),
4214                                NameLoc);
4215   }
4216   }
4217 
4218   llvm_unreachable("bad template name kind!");
4219 }
4220 
getCanonicalTemplateName(TemplateName Name) const4221 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const {
4222   switch (Name.getKind()) {
4223   case TemplateName::QualifiedTemplate:
4224   case TemplateName::Template: {
4225     TemplateDecl *Template = Name.getAsTemplateDecl();
4226     if (TemplateTemplateParmDecl *TTP
4227           = dyn_cast<TemplateTemplateParmDecl>(Template))
4228       Template = getCanonicalTemplateTemplateParmDecl(TTP);
4229 
4230     // The canonical template name is the canonical template declaration.
4231     return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl()));
4232   }
4233 
4234   case TemplateName::OverloadedTemplate:
4235     llvm_unreachable("cannot canonicalize overloaded template");
4236 
4237   case TemplateName::DependentTemplate: {
4238     DependentTemplateName *DTN = Name.getAsDependentTemplateName();
4239     assert(DTN && "Non-dependent template names must refer to template decls.");
4240     return DTN->CanonicalTemplateName;
4241   }
4242 
4243   case TemplateName::SubstTemplateTemplateParm: {
4244     SubstTemplateTemplateParmStorage *subst
4245       = Name.getAsSubstTemplateTemplateParm();
4246     return getCanonicalTemplateName(subst->getReplacement());
4247   }
4248 
4249   case TemplateName::SubstTemplateTemplateParmPack: {
4250     SubstTemplateTemplateParmPackStorage *subst
4251                                   = Name.getAsSubstTemplateTemplateParmPack();
4252     TemplateTemplateParmDecl *canonParameter
4253       = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack());
4254     TemplateArgument canonArgPack
4255       = getCanonicalTemplateArgument(subst->getArgumentPack());
4256     return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack);
4257   }
4258   }
4259 
4260   llvm_unreachable("bad template name!");
4261 }
4262 
hasSameTemplateName(TemplateName X,TemplateName Y)4263 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) {
4264   X = getCanonicalTemplateName(X);
4265   Y = getCanonicalTemplateName(Y);
4266   return X.getAsVoidPointer() == Y.getAsVoidPointer();
4267 }
4268 
4269 TemplateArgument
getCanonicalTemplateArgument(const TemplateArgument & Arg) const4270 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const {
4271   switch (Arg.getKind()) {
4272     case TemplateArgument::Null:
4273       return Arg;
4274 
4275     case TemplateArgument::Expression:
4276       return Arg;
4277 
4278     case TemplateArgument::Declaration: {
4279       ValueDecl *D = cast<ValueDecl>(Arg.getAsDecl()->getCanonicalDecl());
4280       return TemplateArgument(D, Arg.getParamTypeForDecl());
4281     }
4282 
4283     case TemplateArgument::NullPtr:
4284       return TemplateArgument(getCanonicalType(Arg.getNullPtrType()),
4285                               /*isNullPtr*/true);
4286 
4287     case TemplateArgument::Template:
4288       return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate()));
4289 
4290     case TemplateArgument::TemplateExpansion:
4291       return TemplateArgument(getCanonicalTemplateName(
4292                                          Arg.getAsTemplateOrTemplatePattern()),
4293                               Arg.getNumTemplateExpansions());
4294 
4295     case TemplateArgument::Integral:
4296       return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType()));
4297 
4298     case TemplateArgument::Type:
4299       return TemplateArgument(getCanonicalType(Arg.getAsType()));
4300 
4301     case TemplateArgument::Pack: {
4302       if (Arg.pack_size() == 0)
4303         return Arg;
4304 
4305       TemplateArgument *CanonArgs
4306         = new (*this) TemplateArgument[Arg.pack_size()];
4307       unsigned Idx = 0;
4308       for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
4309                                         AEnd = Arg.pack_end();
4310            A != AEnd; (void)++A, ++Idx)
4311         CanonArgs[Idx] = getCanonicalTemplateArgument(*A);
4312 
4313       return TemplateArgument(CanonArgs, Arg.pack_size());
4314     }
4315   }
4316 
4317   // Silence GCC warning
4318   llvm_unreachable("Unhandled template argument kind");
4319 }
4320 
4321 NestedNameSpecifier *
getCanonicalNestedNameSpecifier(NestedNameSpecifier * NNS) const4322 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const {
4323   if (!NNS)
4324     return nullptr;
4325 
4326   switch (NNS->getKind()) {
4327   case NestedNameSpecifier::Identifier:
4328     // Canonicalize the prefix but keep the identifier the same.
4329     return NestedNameSpecifier::Create(*this,
4330                          getCanonicalNestedNameSpecifier(NNS->getPrefix()),
4331                                        NNS->getAsIdentifier());
4332 
4333   case NestedNameSpecifier::Namespace:
4334     // A namespace is canonical; build a nested-name-specifier with
4335     // this namespace and no prefix.
4336     return NestedNameSpecifier::Create(*this, nullptr,
4337                                  NNS->getAsNamespace()->getOriginalNamespace());
4338 
4339   case NestedNameSpecifier::NamespaceAlias:
4340     // A namespace is canonical; build a nested-name-specifier with
4341     // this namespace and no prefix.
4342     return NestedNameSpecifier::Create(*this, nullptr,
4343                                     NNS->getAsNamespaceAlias()->getNamespace()
4344                                                       ->getOriginalNamespace());
4345 
4346   case NestedNameSpecifier::TypeSpec:
4347   case NestedNameSpecifier::TypeSpecWithTemplate: {
4348     QualType T = getCanonicalType(QualType(NNS->getAsType(), 0));
4349 
4350     // If we have some kind of dependent-named type (e.g., "typename T::type"),
4351     // break it apart into its prefix and identifier, then reconsititute those
4352     // as the canonical nested-name-specifier. This is required to canonicalize
4353     // a dependent nested-name-specifier involving typedefs of dependent-name
4354     // types, e.g.,
4355     //   typedef typename T::type T1;
4356     //   typedef typename T1::type T2;
4357     if (const DependentNameType *DNT = T->getAs<DependentNameType>())
4358       return NestedNameSpecifier::Create(*this, DNT->getQualifier(),
4359                            const_cast<IdentifierInfo *>(DNT->getIdentifier()));
4360 
4361     // Otherwise, just canonicalize the type, and force it to be a TypeSpec.
4362     // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the
4363     // first place?
4364     return NestedNameSpecifier::Create(*this, nullptr, false,
4365                                        const_cast<Type *>(T.getTypePtr()));
4366   }
4367 
4368   case NestedNameSpecifier::Global:
4369   case NestedNameSpecifier::Super:
4370     // The global specifier and __super specifer are canonical and unique.
4371     return NNS;
4372   }
4373 
4374   llvm_unreachable("Invalid NestedNameSpecifier::Kind!");
4375 }
4376 
4377 
getAsArrayType(QualType T) const4378 const ArrayType *ASTContext::getAsArrayType(QualType T) const {
4379   // Handle the non-qualified case efficiently.
4380   if (!T.hasLocalQualifiers()) {
4381     // Handle the common positive case fast.
4382     if (const ArrayType *AT = dyn_cast<ArrayType>(T))
4383       return AT;
4384   }
4385 
4386   // Handle the common negative case fast.
4387   if (!isa<ArrayType>(T.getCanonicalType()))
4388     return nullptr;
4389 
4390   // Apply any qualifiers from the array type to the element type.  This
4391   // implements C99 6.7.3p8: "If the specification of an array type includes
4392   // any type qualifiers, the element type is so qualified, not the array type."
4393 
4394   // If we get here, we either have type qualifiers on the type, or we have
4395   // sugar such as a typedef in the way.  If we have type qualifiers on the type
4396   // we must propagate them down into the element type.
4397 
4398   SplitQualType split = T.getSplitDesugaredType();
4399   Qualifiers qs = split.Quals;
4400 
4401   // If we have a simple case, just return now.
4402   const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty);
4403   if (!ATy || qs.empty())
4404     return ATy;
4405 
4406   // Otherwise, we have an array and we have qualifiers on it.  Push the
4407   // qualifiers into the array element type and return a new array type.
4408   QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs);
4409 
4410   if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy))
4411     return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(),
4412                                                 CAT->getSizeModifier(),
4413                                            CAT->getIndexTypeCVRQualifiers()));
4414   if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy))
4415     return cast<ArrayType>(getIncompleteArrayType(NewEltTy,
4416                                                   IAT->getSizeModifier(),
4417                                            IAT->getIndexTypeCVRQualifiers()));
4418 
4419   if (const DependentSizedArrayType *DSAT
4420         = dyn_cast<DependentSizedArrayType>(ATy))
4421     return cast<ArrayType>(
4422                      getDependentSizedArrayType(NewEltTy,
4423                                                 DSAT->getSizeExpr(),
4424                                                 DSAT->getSizeModifier(),
4425                                               DSAT->getIndexTypeCVRQualifiers(),
4426                                                 DSAT->getBracketsRange()));
4427 
4428   const VariableArrayType *VAT = cast<VariableArrayType>(ATy);
4429   return cast<ArrayType>(getVariableArrayType(NewEltTy,
4430                                               VAT->getSizeExpr(),
4431                                               VAT->getSizeModifier(),
4432                                               VAT->getIndexTypeCVRQualifiers(),
4433                                               VAT->getBracketsRange()));
4434 }
4435 
getAdjustedParameterType(QualType T) const4436 QualType ASTContext::getAdjustedParameterType(QualType T) const {
4437   if (T->isArrayType() || T->isFunctionType())
4438     return getDecayedType(T);
4439   return T;
4440 }
4441 
getSignatureParameterType(QualType T) const4442 QualType ASTContext::getSignatureParameterType(QualType T) const {
4443   T = getVariableArrayDecayedType(T);
4444   T = getAdjustedParameterType(T);
4445   return T.getUnqualifiedType();
4446 }
4447 
getExceptionObjectType(QualType T) const4448 QualType ASTContext::getExceptionObjectType(QualType T) const {
4449   // C++ [except.throw]p3:
4450   //   A throw-expression initializes a temporary object, called the exception
4451   //   object, the type of which is determined by removing any top-level
4452   //   cv-qualifiers from the static type of the operand of throw and adjusting
4453   //   the type from "array of T" or "function returning T" to "pointer to T"
4454   //   or "pointer to function returning T", [...]
4455   T = getVariableArrayDecayedType(T);
4456   if (T->isArrayType() || T->isFunctionType())
4457     T = getDecayedType(T);
4458   return T.getUnqualifiedType();
4459 }
4460 
4461 /// getArrayDecayedType - Return the properly qualified result of decaying the
4462 /// specified array type to a pointer.  This operation is non-trivial when
4463 /// handling typedefs etc.  The canonical type of "T" must be an array type,
4464 /// this returns a pointer to a properly qualified element of the array.
4465 ///
4466 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
getArrayDecayedType(QualType Ty) const4467 QualType ASTContext::getArrayDecayedType(QualType Ty) const {
4468   // Get the element type with 'getAsArrayType' so that we don't lose any
4469   // typedefs in the element type of the array.  This also handles propagation
4470   // of type qualifiers from the array type into the element type if present
4471   // (C99 6.7.3p8).
4472   const ArrayType *PrettyArrayType = getAsArrayType(Ty);
4473   assert(PrettyArrayType && "Not an array type!");
4474 
4475   QualType PtrTy = getPointerType(PrettyArrayType->getElementType());
4476 
4477   // int x[restrict 4] ->  int *restrict
4478   return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers());
4479 }
4480 
getBaseElementType(const ArrayType * array) const4481 QualType ASTContext::getBaseElementType(const ArrayType *array) const {
4482   return getBaseElementType(array->getElementType());
4483 }
4484 
getBaseElementType(QualType type) const4485 QualType ASTContext::getBaseElementType(QualType type) const {
4486   Qualifiers qs;
4487   while (true) {
4488     SplitQualType split = type.getSplitDesugaredType();
4489     const ArrayType *array = split.Ty->getAsArrayTypeUnsafe();
4490     if (!array) break;
4491 
4492     type = array->getElementType();
4493     qs.addConsistentQualifiers(split.Quals);
4494   }
4495 
4496   return getQualifiedType(type, qs);
4497 }
4498 
4499 /// getConstantArrayElementCount - Returns number of constant array elements.
4500 uint64_t
getConstantArrayElementCount(const ConstantArrayType * CA) const4501 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA)  const {
4502   uint64_t ElementCount = 1;
4503   do {
4504     ElementCount *= CA->getSize().getZExtValue();
4505     CA = dyn_cast_or_null<ConstantArrayType>(
4506       CA->getElementType()->getAsArrayTypeUnsafe());
4507   } while (CA);
4508   return ElementCount;
4509 }
4510 
4511 /// getFloatingRank - Return a relative rank for floating point types.
4512 /// This routine will assert if passed a built-in type that isn't a float.
getFloatingRank(QualType T)4513 static FloatingRank getFloatingRank(QualType T) {
4514   if (const ComplexType *CT = T->getAs<ComplexType>())
4515     return getFloatingRank(CT->getElementType());
4516 
4517   assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type");
4518   switch (T->getAs<BuiltinType>()->getKind()) {
4519   default: llvm_unreachable("getFloatingRank(): not a floating type");
4520   case BuiltinType::Half:       return HalfRank;
4521   case BuiltinType::Float:      return FloatRank;
4522   case BuiltinType::Double:     return DoubleRank;
4523   case BuiltinType::LongDouble: return LongDoubleRank;
4524   }
4525 }
4526 
4527 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating
4528 /// point or a complex type (based on typeDomain/typeSize).
4529 /// 'typeDomain' is a real floating point or complex type.
4530 /// 'typeSize' is a real floating point or complex type.
getFloatingTypeOfSizeWithinDomain(QualType Size,QualType Domain) const4531 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size,
4532                                                        QualType Domain) const {
4533   FloatingRank EltRank = getFloatingRank(Size);
4534   if (Domain->isComplexType()) {
4535     switch (EltRank) {
4536     case HalfRank: llvm_unreachable("Complex half is not supported");
4537     case FloatRank:      return FloatComplexTy;
4538     case DoubleRank:     return DoubleComplexTy;
4539     case LongDoubleRank: return LongDoubleComplexTy;
4540     }
4541   }
4542 
4543   assert(Domain->isRealFloatingType() && "Unknown domain!");
4544   switch (EltRank) {
4545   case HalfRank:       return HalfTy;
4546   case FloatRank:      return FloatTy;
4547   case DoubleRank:     return DoubleTy;
4548   case LongDoubleRank: return LongDoubleTy;
4549   }
4550   llvm_unreachable("getFloatingRank(): illegal value for rank");
4551 }
4552 
4553 /// getFloatingTypeOrder - Compare the rank of the two specified floating
4554 /// point types, ignoring the domain of the type (i.e. 'double' ==
4555 /// '_Complex double').  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
4556 /// LHS < RHS, return -1.
getFloatingTypeOrder(QualType LHS,QualType RHS) const4557 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const {
4558   FloatingRank LHSR = getFloatingRank(LHS);
4559   FloatingRank RHSR = getFloatingRank(RHS);
4560 
4561   if (LHSR == RHSR)
4562     return 0;
4563   if (LHSR > RHSR)
4564     return 1;
4565   return -1;
4566 }
4567 
4568 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This
4569 /// routine will assert if passed a built-in type that isn't an integer or enum,
4570 /// or if it is not canonicalized.
getIntegerRank(const Type * T) const4571 unsigned ASTContext::getIntegerRank(const Type *T) const {
4572   assert(T->isCanonicalUnqualified() && "T should be canonicalized");
4573 
4574   switch (cast<BuiltinType>(T)->getKind()) {
4575   default: llvm_unreachable("getIntegerRank(): not a built-in integer");
4576   case BuiltinType::Bool:
4577     return 1 + (getIntWidth(BoolTy) << 3);
4578   case BuiltinType::Char_S:
4579   case BuiltinType::Char_U:
4580   case BuiltinType::SChar:
4581   case BuiltinType::UChar:
4582     return 2 + (getIntWidth(CharTy) << 3);
4583   case BuiltinType::Short:
4584   case BuiltinType::UShort:
4585     return 3 + (getIntWidth(ShortTy) << 3);
4586   case BuiltinType::Int:
4587   case BuiltinType::UInt:
4588     return 4 + (getIntWidth(IntTy) << 3);
4589   case BuiltinType::Long:
4590   case BuiltinType::ULong:
4591     return 5 + (getIntWidth(LongTy) << 3);
4592   case BuiltinType::LongLong:
4593   case BuiltinType::ULongLong:
4594     return 6 + (getIntWidth(LongLongTy) << 3);
4595   case BuiltinType::Int128:
4596   case BuiltinType::UInt128:
4597     return 7 + (getIntWidth(Int128Ty) << 3);
4598   }
4599 }
4600 
4601 /// \brief Whether this is a promotable bitfield reference according
4602 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
4603 ///
4604 /// \returns the type this bit-field will promote to, or NULL if no
4605 /// promotion occurs.
isPromotableBitField(Expr * E) const4606 QualType ASTContext::isPromotableBitField(Expr *E) const {
4607   if (E->isTypeDependent() || E->isValueDependent())
4608     return QualType();
4609 
4610   // FIXME: We should not do this unless E->refersToBitField() is true. This
4611   // matters in C where getSourceBitField() will find bit-fields for various
4612   // cases where the source expression is not a bit-field designator.
4613 
4614   FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
4615   if (!Field)
4616     return QualType();
4617 
4618   QualType FT = Field->getType();
4619 
4620   uint64_t BitWidth = Field->getBitWidthValue(*this);
4621   uint64_t IntSize = getTypeSize(IntTy);
4622   // C++ [conv.prom]p5:
4623   //   A prvalue for an integral bit-field can be converted to a prvalue of type
4624   //   int if int can represent all the values of the bit-field; otherwise, it
4625   //   can be converted to unsigned int if unsigned int can represent all the
4626   //   values of the bit-field. If the bit-field is larger yet, no integral
4627   //   promotion applies to it.
4628   // C11 6.3.1.1/2:
4629   //   [For a bit-field of type _Bool, int, signed int, or unsigned int:]
4630   //   If an int can represent all values of the original type (as restricted by
4631   //   the width, for a bit-field), the value is converted to an int; otherwise,
4632   //   it is converted to an unsigned int.
4633   //
4634   // FIXME: C does not permit promotion of a 'long : 3' bitfield to int.
4635   //        We perform that promotion here to match GCC and C++.
4636   if (BitWidth < IntSize)
4637     return IntTy;
4638 
4639   if (BitWidth == IntSize)
4640     return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy;
4641 
4642   // Types bigger than int are not subject to promotions, and therefore act
4643   // like the base type. GCC has some weird bugs in this area that we
4644   // deliberately do not follow (GCC follows a pre-standard resolution to
4645   // C's DR315 which treats bit-width as being part of the type, and this leaks
4646   // into their semantics in some cases).
4647   return QualType();
4648 }
4649 
4650 /// getPromotedIntegerType - Returns the type that Promotable will
4651 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable
4652 /// integer type.
getPromotedIntegerType(QualType Promotable) const4653 QualType ASTContext::getPromotedIntegerType(QualType Promotable) const {
4654   assert(!Promotable.isNull());
4655   assert(Promotable->isPromotableIntegerType());
4656   if (const EnumType *ET = Promotable->getAs<EnumType>())
4657     return ET->getDecl()->getPromotionType();
4658 
4659   if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) {
4660     // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t
4661     // (3.9.1) can be converted to a prvalue of the first of the following
4662     // types that can represent all the values of its underlying type:
4663     // int, unsigned int, long int, unsigned long int, long long int, or
4664     // unsigned long long int [...]
4665     // FIXME: Is there some better way to compute this?
4666     if (BT->getKind() == BuiltinType::WChar_S ||
4667         BT->getKind() == BuiltinType::WChar_U ||
4668         BT->getKind() == BuiltinType::Char16 ||
4669         BT->getKind() == BuiltinType::Char32) {
4670       bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S;
4671       uint64_t FromSize = getTypeSize(BT);
4672       QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy,
4673                                   LongLongTy, UnsignedLongLongTy };
4674       for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) {
4675         uint64_t ToSize = getTypeSize(PromoteTypes[Idx]);
4676         if (FromSize < ToSize ||
4677             (FromSize == ToSize &&
4678              FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType()))
4679           return PromoteTypes[Idx];
4680       }
4681       llvm_unreachable("char type should fit into long long");
4682     }
4683   }
4684 
4685   // At this point, we should have a signed or unsigned integer type.
4686   if (Promotable->isSignedIntegerType())
4687     return IntTy;
4688   uint64_t PromotableSize = getIntWidth(Promotable);
4689   uint64_t IntSize = getIntWidth(IntTy);
4690   assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize);
4691   return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy;
4692 }
4693 
4694 /// \brief Recurses in pointer/array types until it finds an objc retainable
4695 /// type and returns its ownership.
getInnerObjCOwnership(QualType T) const4696 Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const {
4697   while (!T.isNull()) {
4698     if (T.getObjCLifetime() != Qualifiers::OCL_None)
4699       return T.getObjCLifetime();
4700     if (T->isArrayType())
4701       T = getBaseElementType(T);
4702     else if (const PointerType *PT = T->getAs<PointerType>())
4703       T = PT->getPointeeType();
4704     else if (const ReferenceType *RT = T->getAs<ReferenceType>())
4705       T = RT->getPointeeType();
4706     else
4707       break;
4708   }
4709 
4710   return Qualifiers::OCL_None;
4711 }
4712 
getIntegerTypeForEnum(const EnumType * ET)4713 static const Type *getIntegerTypeForEnum(const EnumType *ET) {
4714   // Incomplete enum types are not treated as integer types.
4715   // FIXME: In C++, enum types are never integer types.
4716   if (ET->getDecl()->isComplete() && !ET->getDecl()->isScoped())
4717     return ET->getDecl()->getIntegerType().getTypePtr();
4718   return nullptr;
4719 }
4720 
4721 /// getIntegerTypeOrder - Returns the highest ranked integer type:
4722 /// C99 6.3.1.8p1.  If LHS > RHS, return 1.  If LHS == RHS, return 0. If
4723 /// LHS < RHS, return -1.
getIntegerTypeOrder(QualType LHS,QualType RHS) const4724 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const {
4725   const Type *LHSC = getCanonicalType(LHS).getTypePtr();
4726   const Type *RHSC = getCanonicalType(RHS).getTypePtr();
4727 
4728   // Unwrap enums to their underlying type.
4729   if (const EnumType *ET = dyn_cast<EnumType>(LHSC))
4730     LHSC = getIntegerTypeForEnum(ET);
4731   if (const EnumType *ET = dyn_cast<EnumType>(RHSC))
4732     RHSC = getIntegerTypeForEnum(ET);
4733 
4734   if (LHSC == RHSC) return 0;
4735 
4736   bool LHSUnsigned = LHSC->isUnsignedIntegerType();
4737   bool RHSUnsigned = RHSC->isUnsignedIntegerType();
4738 
4739   unsigned LHSRank = getIntegerRank(LHSC);
4740   unsigned RHSRank = getIntegerRank(RHSC);
4741 
4742   if (LHSUnsigned == RHSUnsigned) {  // Both signed or both unsigned.
4743     if (LHSRank == RHSRank) return 0;
4744     return LHSRank > RHSRank ? 1 : -1;
4745   }
4746 
4747   // Otherwise, the LHS is signed and the RHS is unsigned or visa versa.
4748   if (LHSUnsigned) {
4749     // If the unsigned [LHS] type is larger, return it.
4750     if (LHSRank >= RHSRank)
4751       return 1;
4752 
4753     // If the signed type can represent all values of the unsigned type, it
4754     // wins.  Because we are dealing with 2's complement and types that are
4755     // powers of two larger than each other, this is always safe.
4756     return -1;
4757   }
4758 
4759   // If the unsigned [RHS] type is larger, return it.
4760   if (RHSRank >= LHSRank)
4761     return -1;
4762 
4763   // If the signed type can represent all values of the unsigned type, it
4764   // wins.  Because we are dealing with 2's complement and types that are
4765   // powers of two larger than each other, this is always safe.
4766   return 1;
4767 }
4768 
4769 // getCFConstantStringType - Return the type used for constant CFStrings.
getCFConstantStringType() const4770 QualType ASTContext::getCFConstantStringType() const {
4771   if (!CFConstantStringTypeDecl) {
4772     CFConstantStringTypeDecl = buildImplicitRecord("NSConstantString");
4773     CFConstantStringTypeDecl->startDefinition();
4774 
4775     QualType FieldTypes[4];
4776 
4777     // const int *isa;
4778     FieldTypes[0] = getPointerType(IntTy.withConst());
4779     // int flags;
4780     FieldTypes[1] = IntTy;
4781     // const char *str;
4782     FieldTypes[2] = getPointerType(CharTy.withConst());
4783     // long length;
4784     FieldTypes[3] = LongTy;
4785 
4786     // Create fields
4787     for (unsigned i = 0; i < 4; ++i) {
4788       FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl,
4789                                            SourceLocation(),
4790                                            SourceLocation(), nullptr,
4791                                            FieldTypes[i], /*TInfo=*/nullptr,
4792                                            /*BitWidth=*/nullptr,
4793                                            /*Mutable=*/false,
4794                                            ICIS_NoInit);
4795       Field->setAccess(AS_public);
4796       CFConstantStringTypeDecl->addDecl(Field);
4797     }
4798 
4799     CFConstantStringTypeDecl->completeDefinition();
4800   }
4801 
4802   return getTagDeclType(CFConstantStringTypeDecl);
4803 }
4804 
getObjCSuperType() const4805 QualType ASTContext::getObjCSuperType() const {
4806   if (ObjCSuperType.isNull()) {
4807     RecordDecl *ObjCSuperTypeDecl = buildImplicitRecord("objc_super");
4808     TUDecl->addDecl(ObjCSuperTypeDecl);
4809     ObjCSuperType = getTagDeclType(ObjCSuperTypeDecl);
4810   }
4811   return ObjCSuperType;
4812 }
4813 
setCFConstantStringType(QualType T)4814 void ASTContext::setCFConstantStringType(QualType T) {
4815   const RecordType *Rec = T->getAs<RecordType>();
4816   assert(Rec && "Invalid CFConstantStringType");
4817   CFConstantStringTypeDecl = Rec->getDecl();
4818 }
4819 
getBlockDescriptorType() const4820 QualType ASTContext::getBlockDescriptorType() const {
4821   if (BlockDescriptorType)
4822     return getTagDeclType(BlockDescriptorType);
4823 
4824   RecordDecl *RD;
4825   // FIXME: Needs the FlagAppleBlock bit.
4826   RD = buildImplicitRecord("__block_descriptor");
4827   RD->startDefinition();
4828 
4829   QualType FieldTypes[] = {
4830     UnsignedLongTy,
4831     UnsignedLongTy,
4832   };
4833 
4834   static const char *const FieldNames[] = {
4835     "reserved",
4836     "Size"
4837   };
4838 
4839   for (size_t i = 0; i < 2; ++i) {
4840     FieldDecl *Field = FieldDecl::Create(
4841         *this, RD, SourceLocation(), SourceLocation(),
4842         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4843         /*BitWidth=*/nullptr, /*Mutable=*/false, ICIS_NoInit);
4844     Field->setAccess(AS_public);
4845     RD->addDecl(Field);
4846   }
4847 
4848   RD->completeDefinition();
4849 
4850   BlockDescriptorType = RD;
4851 
4852   return getTagDeclType(BlockDescriptorType);
4853 }
4854 
getBlockDescriptorExtendedType() const4855 QualType ASTContext::getBlockDescriptorExtendedType() const {
4856   if (BlockDescriptorExtendedType)
4857     return getTagDeclType(BlockDescriptorExtendedType);
4858 
4859   RecordDecl *RD;
4860   // FIXME: Needs the FlagAppleBlock bit.
4861   RD = buildImplicitRecord("__block_descriptor_withcopydispose");
4862   RD->startDefinition();
4863 
4864   QualType FieldTypes[] = {
4865     UnsignedLongTy,
4866     UnsignedLongTy,
4867     getPointerType(VoidPtrTy),
4868     getPointerType(VoidPtrTy)
4869   };
4870 
4871   static const char *const FieldNames[] = {
4872     "reserved",
4873     "Size",
4874     "CopyFuncPtr",
4875     "DestroyFuncPtr"
4876   };
4877 
4878   for (size_t i = 0; i < 4; ++i) {
4879     FieldDecl *Field = FieldDecl::Create(
4880         *this, RD, SourceLocation(), SourceLocation(),
4881         &Idents.get(FieldNames[i]), FieldTypes[i], /*TInfo=*/nullptr,
4882         /*BitWidth=*/nullptr,
4883         /*Mutable=*/false, ICIS_NoInit);
4884     Field->setAccess(AS_public);
4885     RD->addDecl(Field);
4886   }
4887 
4888   RD->completeDefinition();
4889 
4890   BlockDescriptorExtendedType = RD;
4891   return getTagDeclType(BlockDescriptorExtendedType);
4892 }
4893 
4894 /// BlockRequiresCopying - Returns true if byref variable "D" of type "Ty"
4895 /// requires copy/dispose. Note that this must match the logic
4896 /// in buildByrefHelpers.
BlockRequiresCopying(QualType Ty,const VarDecl * D)4897 bool ASTContext::BlockRequiresCopying(QualType Ty,
4898                                       const VarDecl *D) {
4899   if (const CXXRecordDecl *record = Ty->getAsCXXRecordDecl()) {
4900     const Expr *copyExpr = getBlockVarCopyInits(D);
4901     if (!copyExpr && record->hasTrivialDestructor()) return false;
4902 
4903     return true;
4904   }
4905 
4906   if (!Ty->isObjCRetainableType()) return false;
4907 
4908   Qualifiers qs = Ty.getQualifiers();
4909 
4910   // If we have lifetime, that dominates.
4911   if (Qualifiers::ObjCLifetime lifetime = qs.getObjCLifetime()) {
4912     assert(getLangOpts().ObjCAutoRefCount);
4913 
4914     switch (lifetime) {
4915       case Qualifiers::OCL_None: llvm_unreachable("impossible");
4916 
4917       // These are just bits as far as the runtime is concerned.
4918       case Qualifiers::OCL_ExplicitNone:
4919       case Qualifiers::OCL_Autoreleasing:
4920         return false;
4921 
4922       // Tell the runtime that this is ARC __weak, called by the
4923       // byref routines.
4924       case Qualifiers::OCL_Weak:
4925       // ARC __strong __block variables need to be retained.
4926       case Qualifiers::OCL_Strong:
4927         return true;
4928     }
4929     llvm_unreachable("fell out of lifetime switch!");
4930   }
4931   return (Ty->isBlockPointerType() || isObjCNSObjectType(Ty) ||
4932           Ty->isObjCObjectPointerType());
4933 }
4934 
getByrefLifetime(QualType Ty,Qualifiers::ObjCLifetime & LifeTime,bool & HasByrefExtendedLayout) const4935 bool ASTContext::getByrefLifetime(QualType Ty,
4936                               Qualifiers::ObjCLifetime &LifeTime,
4937                               bool &HasByrefExtendedLayout) const {
4938 
4939   if (!getLangOpts().ObjC1 ||
4940       getLangOpts().getGC() != LangOptions::NonGC)
4941     return false;
4942 
4943   HasByrefExtendedLayout = false;
4944   if (Ty->isRecordType()) {
4945     HasByrefExtendedLayout = true;
4946     LifeTime = Qualifiers::OCL_None;
4947   }
4948   else if (getLangOpts().ObjCAutoRefCount)
4949     LifeTime = Ty.getObjCLifetime();
4950   // MRR.
4951   else if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
4952     LifeTime = Qualifiers::OCL_ExplicitNone;
4953   else
4954     LifeTime = Qualifiers::OCL_None;
4955   return true;
4956 }
4957 
getObjCInstanceTypeDecl()4958 TypedefDecl *ASTContext::getObjCInstanceTypeDecl() {
4959   if (!ObjCInstanceTypeDecl)
4960     ObjCInstanceTypeDecl =
4961         buildImplicitTypedef(getObjCIdType(), "instancetype");
4962   return ObjCInstanceTypeDecl;
4963 }
4964 
4965 // This returns true if a type has been typedefed to BOOL:
4966 // typedef <type> BOOL;
isTypeTypedefedAsBOOL(QualType T)4967 static bool isTypeTypedefedAsBOOL(QualType T) {
4968   if (const TypedefType *TT = dyn_cast<TypedefType>(T))
4969     if (IdentifierInfo *II = TT->getDecl()->getIdentifier())
4970       return II->isStr("BOOL");
4971 
4972   return false;
4973 }
4974 
4975 /// getObjCEncodingTypeSize returns size of type for objective-c encoding
4976 /// purpose.
getObjCEncodingTypeSize(QualType type) const4977 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const {
4978   if (!type->isIncompleteArrayType() && type->isIncompleteType())
4979     return CharUnits::Zero();
4980 
4981   CharUnits sz = getTypeSizeInChars(type);
4982 
4983   // Make all integer and enum types at least as large as an int
4984   if (sz.isPositive() && type->isIntegralOrEnumerationType())
4985     sz = std::max(sz, getTypeSizeInChars(IntTy));
4986   // Treat arrays as pointers, since that's how they're passed in.
4987   else if (type->isArrayType())
4988     sz = getTypeSizeInChars(VoidPtrTy);
4989   return sz;
4990 }
4991 
isMSStaticDataMemberInlineDefinition(const VarDecl * VD) const4992 bool ASTContext::isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const {
4993   return getLangOpts().MSVCCompat && VD->isStaticDataMember() &&
4994          VD->getType()->isIntegralOrEnumerationType() &&
4995          VD->isFirstDecl() && !VD->isOutOfLine() && VD->hasInit();
4996 }
4997 
4998 static inline
charUnitsToString(const CharUnits & CU)4999 std::string charUnitsToString(const CharUnits &CU) {
5000   return llvm::itostr(CU.getQuantity());
5001 }
5002 
5003 /// getObjCEncodingForBlock - Return the encoded type for this block
5004 /// declaration.
getObjCEncodingForBlock(const BlockExpr * Expr) const5005 std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const {
5006   std::string S;
5007 
5008   const BlockDecl *Decl = Expr->getBlockDecl();
5009   QualType BlockTy =
5010       Expr->getType()->getAs<BlockPointerType>()->getPointeeType();
5011   // Encode result type.
5012   if (getLangOpts().EncodeExtendedBlockSig)
5013     getObjCEncodingForMethodParameter(
5014         Decl::OBJC_TQ_None, BlockTy->getAs<FunctionType>()->getReturnType(), S,
5015         true /*Extended*/);
5016   else
5017     getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getReturnType(), S);
5018   // Compute size of all parameters.
5019   // Start with computing size of a pointer in number of bytes.
5020   // FIXME: There might(should) be a better way of doing this computation!
5021   SourceLocation Loc;
5022   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5023   CharUnits ParmOffset = PtrSize;
5024   for (auto PI : Decl->params()) {
5025     QualType PType = PI->getType();
5026     CharUnits sz = getObjCEncodingTypeSize(PType);
5027     if (sz.isZero())
5028       continue;
5029     assert (sz.isPositive() && "BlockExpr - Incomplete param type");
5030     ParmOffset += sz;
5031   }
5032   // Size of the argument frame
5033   S += charUnitsToString(ParmOffset);
5034   // Block pointer and offset.
5035   S += "@?0";
5036 
5037   // Argument types.
5038   ParmOffset = PtrSize;
5039   for (auto PVDecl : Decl->params()) {
5040     QualType PType = PVDecl->getOriginalType();
5041     if (const ArrayType *AT =
5042           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5043       // Use array's original type only if it has known number of
5044       // elements.
5045       if (!isa<ConstantArrayType>(AT))
5046         PType = PVDecl->getType();
5047     } else if (PType->isFunctionType())
5048       PType = PVDecl->getType();
5049     if (getLangOpts().EncodeExtendedBlockSig)
5050       getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, PType,
5051                                       S, true /*Extended*/);
5052     else
5053       getObjCEncodingForType(PType, S);
5054     S += charUnitsToString(ParmOffset);
5055     ParmOffset += getObjCEncodingTypeSize(PType);
5056   }
5057 
5058   return S;
5059 }
5060 
getObjCEncodingForFunctionDecl(const FunctionDecl * Decl,std::string & S)5061 bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl,
5062                                                 std::string& S) {
5063   // Encode result type.
5064   getObjCEncodingForType(Decl->getReturnType(), S);
5065   CharUnits ParmOffset;
5066   // Compute size of all parameters.
5067   for (auto PI : Decl->params()) {
5068     QualType PType = PI->getType();
5069     CharUnits sz = getObjCEncodingTypeSize(PType);
5070     if (sz.isZero())
5071       continue;
5072 
5073     assert (sz.isPositive() &&
5074         "getObjCEncodingForFunctionDecl - Incomplete param type");
5075     ParmOffset += sz;
5076   }
5077   S += charUnitsToString(ParmOffset);
5078   ParmOffset = CharUnits::Zero();
5079 
5080   // Argument types.
5081   for (auto PVDecl : Decl->params()) {
5082     QualType PType = PVDecl->getOriginalType();
5083     if (const ArrayType *AT =
5084           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5085       // Use array's original type only if it has known number of
5086       // elements.
5087       if (!isa<ConstantArrayType>(AT))
5088         PType = PVDecl->getType();
5089     } else if (PType->isFunctionType())
5090       PType = PVDecl->getType();
5091     getObjCEncodingForType(PType, S);
5092     S += charUnitsToString(ParmOffset);
5093     ParmOffset += getObjCEncodingTypeSize(PType);
5094   }
5095 
5096   return false;
5097 }
5098 
5099 /// getObjCEncodingForMethodParameter - Return the encoded type for a single
5100 /// method parameter or return type. If Extended, include class names and
5101 /// block object types.
getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,QualType T,std::string & S,bool Extended) const5102 void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
5103                                                    QualType T, std::string& S,
5104                                                    bool Extended) const {
5105   // Encode type qualifer, 'in', 'inout', etc. for the parameter.
5106   getObjCEncodingForTypeQualifier(QT, S);
5107   // Encode parameter type.
5108   getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5109                              true     /*OutermostType*/,
5110                              false    /*EncodingProperty*/,
5111                              false    /*StructField*/,
5112                              Extended /*EncodeBlockParameters*/,
5113                              Extended /*EncodeClassNames*/);
5114 }
5115 
5116 /// getObjCEncodingForMethodDecl - Return the encoded type for this method
5117 /// declaration.
getObjCEncodingForMethodDecl(const ObjCMethodDecl * Decl,std::string & S,bool Extended) const5118 bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
5119                                               std::string& S,
5120                                               bool Extended) const {
5121   // FIXME: This is not very efficient.
5122   // Encode return type.
5123   getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(),
5124                                     Decl->getReturnType(), S, Extended);
5125   // Compute size of all parameters.
5126   // Start with computing size of a pointer in number of bytes.
5127   // FIXME: There might(should) be a better way of doing this computation!
5128   SourceLocation Loc;
5129   CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy);
5130   // The first two arguments (self and _cmd) are pointers; account for
5131   // their size.
5132   CharUnits ParmOffset = 2 * PtrSize;
5133   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5134        E = Decl->sel_param_end(); PI != E; ++PI) {
5135     QualType PType = (*PI)->getType();
5136     CharUnits sz = getObjCEncodingTypeSize(PType);
5137     if (sz.isZero())
5138       continue;
5139 
5140     assert (sz.isPositive() &&
5141         "getObjCEncodingForMethodDecl - Incomplete param type");
5142     ParmOffset += sz;
5143   }
5144   S += charUnitsToString(ParmOffset);
5145   S += "@0:";
5146   S += charUnitsToString(PtrSize);
5147 
5148   // Argument types.
5149   ParmOffset = 2 * PtrSize;
5150   for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(),
5151        E = Decl->sel_param_end(); PI != E; ++PI) {
5152     const ParmVarDecl *PVDecl = *PI;
5153     QualType PType = PVDecl->getOriginalType();
5154     if (const ArrayType *AT =
5155           dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) {
5156       // Use array's original type only if it has known number of
5157       // elements.
5158       if (!isa<ConstantArrayType>(AT))
5159         PType = PVDecl->getType();
5160     } else if (PType->isFunctionType())
5161       PType = PVDecl->getType();
5162     getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(),
5163                                       PType, S, Extended);
5164     S += charUnitsToString(ParmOffset);
5165     ParmOffset += getObjCEncodingTypeSize(PType);
5166   }
5167 
5168   return false;
5169 }
5170 
5171 ObjCPropertyImplDecl *
getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl * PD,const Decl * Container) const5172 ASTContext::getObjCPropertyImplDeclForPropertyDecl(
5173                                       const ObjCPropertyDecl *PD,
5174                                       const Decl *Container) const {
5175   if (!Container)
5176     return nullptr;
5177   if (const ObjCCategoryImplDecl *CID =
5178       dyn_cast<ObjCCategoryImplDecl>(Container)) {
5179     for (auto *PID : CID->property_impls())
5180       if (PID->getPropertyDecl() == PD)
5181         return PID;
5182   } else {
5183     const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container);
5184     for (auto *PID : OID->property_impls())
5185       if (PID->getPropertyDecl() == PD)
5186         return PID;
5187   }
5188   return nullptr;
5189 }
5190 
5191 /// getObjCEncodingForPropertyDecl - Return the encoded type for this
5192 /// property declaration. If non-NULL, Container must be either an
5193 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be
5194 /// NULL when getting encodings for protocol properties.
5195 /// Property attributes are stored as a comma-delimited C string. The simple
5196 /// attributes readonly and bycopy are encoded as single characters. The
5197 /// parametrized attributes, getter=name, setter=name, and ivar=name, are
5198 /// encoded as single characters, followed by an identifier. Property types
5199 /// are also encoded as a parametrized attribute. The characters used to encode
5200 /// these attributes are defined by the following enumeration:
5201 /// @code
5202 /// enum PropertyAttributes {
5203 /// kPropertyReadOnly = 'R',   // property is read-only.
5204 /// kPropertyBycopy = 'C',     // property is a copy of the value last assigned
5205 /// kPropertyByref = '&',  // property is a reference to the value last assigned
5206 /// kPropertyDynamic = 'D',    // property is dynamic
5207 /// kPropertyGetter = 'G',     // followed by getter selector name
5208 /// kPropertySetter = 'S',     // followed by setter selector name
5209 /// kPropertyInstanceVariable = 'V'  // followed by instance variable  name
5210 /// kPropertyType = 'T'              // followed by old-style type encoding.
5211 /// kPropertyWeak = 'W'              // 'weak' property
5212 /// kPropertyStrong = 'P'            // property GC'able
5213 /// kPropertyNonAtomic = 'N'         // property non-atomic
5214 /// };
5215 /// @endcode
getObjCEncodingForPropertyDecl(const ObjCPropertyDecl * PD,const Decl * Container,std::string & S) const5216 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
5217                                                 const Decl *Container,
5218                                                 std::string& S) const {
5219   // Collect information from the property implementation decl(s).
5220   bool Dynamic = false;
5221   ObjCPropertyImplDecl *SynthesizePID = nullptr;
5222 
5223   if (ObjCPropertyImplDecl *PropertyImpDecl =
5224       getObjCPropertyImplDeclForPropertyDecl(PD, Container)) {
5225     if (PropertyImpDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5226       Dynamic = true;
5227     else
5228       SynthesizePID = PropertyImpDecl;
5229   }
5230 
5231   // FIXME: This is not very efficient.
5232   S = "T";
5233 
5234   // Encode result type.
5235   // GCC has some special rules regarding encoding of properties which
5236   // closely resembles encoding of ivars.
5237   getObjCEncodingForPropertyType(PD->getType(), S);
5238 
5239   if (PD->isReadOnly()) {
5240     S += ",R";
5241     if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_copy)
5242       S += ",C";
5243     if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_retain)
5244       S += ",&";
5245     if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
5246       S += ",W";
5247   } else {
5248     switch (PD->getSetterKind()) {
5249     case ObjCPropertyDecl::Assign: break;
5250     case ObjCPropertyDecl::Copy:   S += ",C"; break;
5251     case ObjCPropertyDecl::Retain: S += ",&"; break;
5252     case ObjCPropertyDecl::Weak:   S += ",W"; break;
5253     }
5254   }
5255 
5256   // It really isn't clear at all what this means, since properties
5257   // are "dynamic by default".
5258   if (Dynamic)
5259     S += ",D";
5260 
5261   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic)
5262     S += ",N";
5263 
5264   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) {
5265     S += ",G";
5266     S += PD->getGetterName().getAsString();
5267   }
5268 
5269   if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) {
5270     S += ",S";
5271     S += PD->getSetterName().getAsString();
5272   }
5273 
5274   if (SynthesizePID) {
5275     const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl();
5276     S += ",V";
5277     S += OID->getNameAsString();
5278   }
5279 
5280   // FIXME: OBJCGC: weak & strong
5281 }
5282 
5283 /// getLegacyIntegralTypeEncoding -
5284 /// Another legacy compatibility encoding: 32-bit longs are encoded as
5285 /// 'l' or 'L' , but not always.  For typedefs, we need to use
5286 /// 'i' or 'I' instead if encoding a struct field, or a pointer!
5287 ///
getLegacyIntegralTypeEncoding(QualType & PointeeTy) const5288 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const {
5289   if (isa<TypedefType>(PointeeTy.getTypePtr())) {
5290     if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) {
5291       if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32)
5292         PointeeTy = UnsignedIntTy;
5293       else
5294         if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32)
5295           PointeeTy = IntTy;
5296     }
5297   }
5298 }
5299 
getObjCEncodingForType(QualType T,std::string & S,const FieldDecl * Field,QualType * NotEncodedT) const5300 void ASTContext::getObjCEncodingForType(QualType T, std::string& S,
5301                                         const FieldDecl *Field,
5302                                         QualType *NotEncodedT) const {
5303   // We follow the behavior of gcc, expanding structures which are
5304   // directly pointed to, and expanding embedded structures. Note that
5305   // these rules are sufficient to prevent recursive encoding of the
5306   // same type.
5307   getObjCEncodingForTypeImpl(T, S, true, true, Field,
5308                              true /* outermost type */, false, false,
5309                              false, false, false, NotEncodedT);
5310 }
5311 
getObjCEncodingForPropertyType(QualType T,std::string & S) const5312 void ASTContext::getObjCEncodingForPropertyType(QualType T,
5313                                                 std::string& S) const {
5314   // Encode result type.
5315   // GCC has some special rules regarding encoding of properties which
5316   // closely resembles encoding of ivars.
5317   getObjCEncodingForTypeImpl(T, S, true, true, nullptr,
5318                              true /* outermost type */,
5319                              true /* encoding property */);
5320 }
5321 
getObjCEncodingForPrimitiveKind(const ASTContext * C,BuiltinType::Kind kind)5322 static char getObjCEncodingForPrimitiveKind(const ASTContext *C,
5323                                             BuiltinType::Kind kind) {
5324     switch (kind) {
5325     case BuiltinType::Void:       return 'v';
5326     case BuiltinType::Bool:       return 'B';
5327     case BuiltinType::Char_U:
5328     case BuiltinType::UChar:      return 'C';
5329     case BuiltinType::Char16:
5330     case BuiltinType::UShort:     return 'S';
5331     case BuiltinType::Char32:
5332     case BuiltinType::UInt:       return 'I';
5333     case BuiltinType::ULong:
5334         return C->getTargetInfo().getLongWidth() == 32 ? 'L' : 'Q';
5335     case BuiltinType::UInt128:    return 'T';
5336     case BuiltinType::ULongLong:  return 'Q';
5337     case BuiltinType::Char_S:
5338     case BuiltinType::SChar:      return 'c';
5339     case BuiltinType::Short:      return 's';
5340     case BuiltinType::WChar_S:
5341     case BuiltinType::WChar_U:
5342     case BuiltinType::Int:        return 'i';
5343     case BuiltinType::Long:
5344       return C->getTargetInfo().getLongWidth() == 32 ? 'l' : 'q';
5345     case BuiltinType::LongLong:   return 'q';
5346     case BuiltinType::Int128:     return 't';
5347     case BuiltinType::Float:      return 'f';
5348     case BuiltinType::Double:     return 'd';
5349     case BuiltinType::LongDouble: return 'D';
5350     case BuiltinType::NullPtr:    return '*'; // like char*
5351 
5352     case BuiltinType::Half:
5353       // FIXME: potentially need @encodes for these!
5354       return ' ';
5355 
5356     case BuiltinType::ObjCId:
5357     case BuiltinType::ObjCClass:
5358     case BuiltinType::ObjCSel:
5359       llvm_unreachable("@encoding ObjC primitive type");
5360 
5361     // OpenCL and placeholder types don't need @encodings.
5362     case BuiltinType::OCLImage1d:
5363     case BuiltinType::OCLImage1dArray:
5364     case BuiltinType::OCLImage1dBuffer:
5365     case BuiltinType::OCLImage2d:
5366     case BuiltinType::OCLImage2dArray:
5367     case BuiltinType::OCLImage3d:
5368     case BuiltinType::OCLEvent:
5369     case BuiltinType::OCLSampler:
5370     case BuiltinType::Dependent:
5371 #define BUILTIN_TYPE(KIND, ID)
5372 #define PLACEHOLDER_TYPE(KIND, ID) \
5373     case BuiltinType::KIND:
5374 #include "clang/AST/BuiltinTypes.def"
5375       llvm_unreachable("invalid builtin type for @encode");
5376     }
5377     llvm_unreachable("invalid BuiltinType::Kind value");
5378 }
5379 
ObjCEncodingForEnumType(const ASTContext * C,const EnumType * ET)5380 static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) {
5381   EnumDecl *Enum = ET->getDecl();
5382 
5383   // The encoding of an non-fixed enum type is always 'i', regardless of size.
5384   if (!Enum->isFixed())
5385     return 'i';
5386 
5387   // The encoding of a fixed enum type matches its fixed underlying type.
5388   const BuiltinType *BT = Enum->getIntegerType()->castAs<BuiltinType>();
5389   return getObjCEncodingForPrimitiveKind(C, BT->getKind());
5390 }
5391 
EncodeBitField(const ASTContext * Ctx,std::string & S,QualType T,const FieldDecl * FD)5392 static void EncodeBitField(const ASTContext *Ctx, std::string& S,
5393                            QualType T, const FieldDecl *FD) {
5394   assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl");
5395   S += 'b';
5396   // The NeXT runtime encodes bit fields as b followed by the number of bits.
5397   // The GNU runtime requires more information; bitfields are encoded as b,
5398   // then the offset (in bits) of the first element, then the type of the
5399   // bitfield, then the size in bits.  For example, in this structure:
5400   //
5401   // struct
5402   // {
5403   //    int integer;
5404   //    int flags:2;
5405   // };
5406   // On a 32-bit system, the encoding for flags would be b2 for the NeXT
5407   // runtime, but b32i2 for the GNU runtime.  The reason for this extra
5408   // information is not especially sensible, but we're stuck with it for
5409   // compatibility with GCC, although providing it breaks anything that
5410   // actually uses runtime introspection and wants to work on both runtimes...
5411   if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) {
5412     const RecordDecl *RD = FD->getParent();
5413     const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD);
5414     S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex()));
5415     if (const EnumType *ET = T->getAs<EnumType>())
5416       S += ObjCEncodingForEnumType(Ctx, ET);
5417     else {
5418       const BuiltinType *BT = T->castAs<BuiltinType>();
5419       S += getObjCEncodingForPrimitiveKind(Ctx, BT->getKind());
5420     }
5421   }
5422   S += llvm::utostr(FD->getBitWidthValue(*Ctx));
5423 }
5424 
5425 // FIXME: Use SmallString for accumulating string.
getObjCEncodingForTypeImpl(QualType T,std::string & S,bool ExpandPointedToStructures,bool ExpandStructures,const FieldDecl * FD,bool OutermostType,bool EncodingProperty,bool StructField,bool EncodeBlockParameters,bool EncodeClassNames,bool EncodePointerToObjCTypedef,QualType * NotEncodedT) const5426 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
5427                                             bool ExpandPointedToStructures,
5428                                             bool ExpandStructures,
5429                                             const FieldDecl *FD,
5430                                             bool OutermostType,
5431                                             bool EncodingProperty,
5432                                             bool StructField,
5433                                             bool EncodeBlockParameters,
5434                                             bool EncodeClassNames,
5435                                             bool EncodePointerToObjCTypedef,
5436                                             QualType *NotEncodedT) const {
5437   CanQualType CT = getCanonicalType(T);
5438   switch (CT->getTypeClass()) {
5439   case Type::Builtin:
5440   case Type::Enum:
5441     if (FD && FD->isBitField())
5442       return EncodeBitField(this, S, T, FD);
5443     if (const BuiltinType *BT = dyn_cast<BuiltinType>(CT))
5444       S += getObjCEncodingForPrimitiveKind(this, BT->getKind());
5445     else
5446       S += ObjCEncodingForEnumType(this, cast<EnumType>(CT));
5447     return;
5448 
5449   case Type::Complex: {
5450     const ComplexType *CT = T->castAs<ComplexType>();
5451     S += 'j';
5452     getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, nullptr);
5453     return;
5454   }
5455 
5456   case Type::Atomic: {
5457     const AtomicType *AT = T->castAs<AtomicType>();
5458     S += 'A';
5459     getObjCEncodingForTypeImpl(AT->getValueType(), S, false, false, nullptr);
5460     return;
5461   }
5462 
5463   // encoding for pointer or reference types.
5464   case Type::Pointer:
5465   case Type::LValueReference:
5466   case Type::RValueReference: {
5467     QualType PointeeTy;
5468     if (isa<PointerType>(CT)) {
5469       const PointerType *PT = T->castAs<PointerType>();
5470       if (PT->isObjCSelType()) {
5471         S += ':';
5472         return;
5473       }
5474       PointeeTy = PT->getPointeeType();
5475     } else {
5476       PointeeTy = T->castAs<ReferenceType>()->getPointeeType();
5477     }
5478 
5479     bool isReadOnly = false;
5480     // For historical/compatibility reasons, the read-only qualifier of the
5481     // pointee gets emitted _before_ the '^'.  The read-only qualifier of
5482     // the pointer itself gets ignored, _unless_ we are looking at a typedef!
5483     // Also, do not emit the 'r' for anything but the outermost type!
5484     if (isa<TypedefType>(T.getTypePtr())) {
5485       if (OutermostType && T.isConstQualified()) {
5486         isReadOnly = true;
5487         S += 'r';
5488       }
5489     } else if (OutermostType) {
5490       QualType P = PointeeTy;
5491       while (P->getAs<PointerType>())
5492         P = P->getAs<PointerType>()->getPointeeType();
5493       if (P.isConstQualified()) {
5494         isReadOnly = true;
5495         S += 'r';
5496       }
5497     }
5498     if (isReadOnly) {
5499       // Another legacy compatibility encoding. Some ObjC qualifier and type
5500       // combinations need to be rearranged.
5501       // Rewrite "in const" from "nr" to "rn"
5502       if (StringRef(S).endswith("nr"))
5503         S.replace(S.end()-2, S.end(), "rn");
5504     }
5505 
5506     if (PointeeTy->isCharType()) {
5507       // char pointer types should be encoded as '*' unless it is a
5508       // type that has been typedef'd to 'BOOL'.
5509       if (!isTypeTypedefedAsBOOL(PointeeTy)) {
5510         S += '*';
5511         return;
5512       }
5513     } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) {
5514       // GCC binary compat: Need to convert "struct objc_class *" to "#".
5515       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) {
5516         S += '#';
5517         return;
5518       }
5519       // GCC binary compat: Need to convert "struct objc_object *" to "@".
5520       if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) {
5521         S += '@';
5522         return;
5523       }
5524       // fall through...
5525     }
5526     S += '^';
5527     getLegacyIntegralTypeEncoding(PointeeTy);
5528 
5529     getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures,
5530                                nullptr, false, false, false, false, false, false,
5531                                NotEncodedT);
5532     return;
5533   }
5534 
5535   case Type::ConstantArray:
5536   case Type::IncompleteArray:
5537   case Type::VariableArray: {
5538     const ArrayType *AT = cast<ArrayType>(CT);
5539 
5540     if (isa<IncompleteArrayType>(AT) && !StructField) {
5541       // Incomplete arrays are encoded as a pointer to the array element.
5542       S += '^';
5543 
5544       getObjCEncodingForTypeImpl(AT->getElementType(), S,
5545                                  false, ExpandStructures, FD);
5546     } else {
5547       S += '[';
5548 
5549       if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
5550         S += llvm::utostr(CAT->getSize().getZExtValue());
5551       else {
5552         //Variable length arrays are encoded as a regular array with 0 elements.
5553         assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) &&
5554                "Unknown array type!");
5555         S += '0';
5556       }
5557 
5558       getObjCEncodingForTypeImpl(AT->getElementType(), S,
5559                                  false, ExpandStructures, FD,
5560                                  false, false, false, false, false, false,
5561                                  NotEncodedT);
5562       S += ']';
5563     }
5564     return;
5565   }
5566 
5567   case Type::FunctionNoProto:
5568   case Type::FunctionProto:
5569     S += '?';
5570     return;
5571 
5572   case Type::Record: {
5573     RecordDecl *RDecl = cast<RecordType>(CT)->getDecl();
5574     S += RDecl->isUnion() ? '(' : '{';
5575     // Anonymous structures print as '?'
5576     if (const IdentifierInfo *II = RDecl->getIdentifier()) {
5577       S += II->getName();
5578       if (ClassTemplateSpecializationDecl *Spec
5579           = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) {
5580         const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
5581         llvm::raw_string_ostream OS(S);
5582         TemplateSpecializationType::PrintTemplateArgumentList(OS,
5583                                             TemplateArgs.data(),
5584                                             TemplateArgs.size(),
5585                                             (*this).getPrintingPolicy());
5586       }
5587     } else {
5588       S += '?';
5589     }
5590     if (ExpandStructures) {
5591       S += '=';
5592       if (!RDecl->isUnion()) {
5593         getObjCEncodingForStructureImpl(RDecl, S, FD, true, NotEncodedT);
5594       } else {
5595         for (const auto *Field : RDecl->fields()) {
5596           if (FD) {
5597             S += '"';
5598             S += Field->getNameAsString();
5599             S += '"';
5600           }
5601 
5602           // Special case bit-fields.
5603           if (Field->isBitField()) {
5604             getObjCEncodingForTypeImpl(Field->getType(), S, false, true,
5605                                        Field);
5606           } else {
5607             QualType qt = Field->getType();
5608             getLegacyIntegralTypeEncoding(qt);
5609             getObjCEncodingForTypeImpl(qt, S, false, true,
5610                                        FD, /*OutermostType*/false,
5611                                        /*EncodingProperty*/false,
5612                                        /*StructField*/true,
5613                                        false, false, false, NotEncodedT);
5614           }
5615         }
5616       }
5617     }
5618     S += RDecl->isUnion() ? ')' : '}';
5619     return;
5620   }
5621 
5622   case Type::BlockPointer: {
5623     const BlockPointerType *BT = T->castAs<BlockPointerType>();
5624     S += "@?"; // Unlike a pointer-to-function, which is "^?".
5625     if (EncodeBlockParameters) {
5626       const FunctionType *FT = BT->getPointeeType()->castAs<FunctionType>();
5627 
5628       S += '<';
5629       // Block return type
5630       getObjCEncodingForTypeImpl(
5631           FT->getReturnType(), S, ExpandPointedToStructures, ExpandStructures,
5632           FD, false /* OutermostType */, EncodingProperty,
5633           false /* StructField */, EncodeBlockParameters, EncodeClassNames, false,
5634                                  NotEncodedT);
5635       // Block self
5636       S += "@?";
5637       // Block parameters
5638       if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) {
5639         for (const auto &I : FPT->param_types())
5640           getObjCEncodingForTypeImpl(
5641               I, S, ExpandPointedToStructures, ExpandStructures, FD,
5642               false /* OutermostType */, EncodingProperty,
5643               false /* StructField */, EncodeBlockParameters, EncodeClassNames,
5644                                      false, NotEncodedT);
5645       }
5646       S += '>';
5647     }
5648     return;
5649   }
5650 
5651   case Type::ObjCObject: {
5652     // hack to match legacy encoding of *id and *Class
5653     QualType Ty = getObjCObjectPointerType(CT);
5654     if (Ty->isObjCIdType()) {
5655       S += "{objc_object=}";
5656       return;
5657     }
5658     else if (Ty->isObjCClassType()) {
5659       S += "{objc_class=}";
5660       return;
5661     }
5662   }
5663 
5664   case Type::ObjCInterface: {
5665     // Ignore protocol qualifiers when mangling at this level.
5666     // @encode(class_name)
5667     ObjCInterfaceDecl *OI = T->castAs<ObjCObjectType>()->getInterface();
5668     S += '{';
5669     S += OI->getObjCRuntimeNameAsString();
5670     S += '=';
5671     SmallVector<const ObjCIvarDecl*, 32> Ivars;
5672     DeepCollectObjCIvars(OI, true, Ivars);
5673     for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5674       const FieldDecl *Field = cast<FieldDecl>(Ivars[i]);
5675       if (Field->isBitField())
5676         getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field);
5677       else
5678         getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD,
5679                                    false, false, false, false, false,
5680                                    EncodePointerToObjCTypedef,
5681                                    NotEncodedT);
5682     }
5683     S += '}';
5684     return;
5685   }
5686 
5687   case Type::ObjCObjectPointer: {
5688     const ObjCObjectPointerType *OPT = T->castAs<ObjCObjectPointerType>();
5689     if (OPT->isObjCIdType()) {
5690       S += '@';
5691       return;
5692     }
5693 
5694     if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) {
5695       // FIXME: Consider if we need to output qualifiers for 'Class<p>'.
5696       // Since this is a binary compatibility issue, need to consult with runtime
5697       // folks. Fortunately, this is a *very* obsure construct.
5698       S += '#';
5699       return;
5700     }
5701 
5702     if (OPT->isObjCQualifiedIdType()) {
5703       getObjCEncodingForTypeImpl(getObjCIdType(), S,
5704                                  ExpandPointedToStructures,
5705                                  ExpandStructures, FD);
5706       if (FD || EncodingProperty || EncodeClassNames) {
5707         // Note that we do extended encoding of protocol qualifer list
5708         // Only when doing ivar or property encoding.
5709         S += '"';
5710         for (const auto *I : OPT->quals()) {
5711           S += '<';
5712           S += I->getObjCRuntimeNameAsString();
5713           S += '>';
5714         }
5715         S += '"';
5716       }
5717       return;
5718     }
5719 
5720     QualType PointeeTy = OPT->getPointeeType();
5721     if (!EncodingProperty &&
5722         isa<TypedefType>(PointeeTy.getTypePtr()) &&
5723         !EncodePointerToObjCTypedef) {
5724       // Another historical/compatibility reason.
5725       // We encode the underlying type which comes out as
5726       // {...};
5727       S += '^';
5728       if (FD && OPT->getInterfaceDecl()) {
5729         // Prevent recursive encoding of fields in some rare cases.
5730         ObjCInterfaceDecl *OI = OPT->getInterfaceDecl();
5731         SmallVector<const ObjCIvarDecl*, 32> Ivars;
5732         DeepCollectObjCIvars(OI, true, Ivars);
5733         for (unsigned i = 0, e = Ivars.size(); i != e; ++i) {
5734           if (cast<FieldDecl>(Ivars[i]) == FD) {
5735             S += '{';
5736             S += OI->getObjCRuntimeNameAsString();
5737             S += '}';
5738             return;
5739           }
5740         }
5741       }
5742       getObjCEncodingForTypeImpl(PointeeTy, S,
5743                                  false, ExpandPointedToStructures,
5744                                  nullptr,
5745                                  false, false, false, false, false,
5746                                  /*EncodePointerToObjCTypedef*/true);
5747       return;
5748     }
5749 
5750     S += '@';
5751     if (OPT->getInterfaceDecl() &&
5752         (FD || EncodingProperty || EncodeClassNames)) {
5753       S += '"';
5754       S += OPT->getInterfaceDecl()->getObjCRuntimeNameAsString();
5755       for (const auto *I : OPT->quals()) {
5756         S += '<';
5757         S += I->getObjCRuntimeNameAsString();
5758         S += '>';
5759       }
5760       S += '"';
5761     }
5762     return;
5763   }
5764 
5765   // gcc just blithely ignores member pointers.
5766   // FIXME: we shoul do better than that.  'M' is available.
5767   case Type::MemberPointer:
5768   // This matches gcc's encoding, even though technically it is insufficient.
5769   //FIXME. We should do a better job than gcc.
5770   case Type::Vector:
5771   case Type::ExtVector:
5772   // Until we have a coherent encoding of these three types, issue warning.
5773     { if (NotEncodedT)
5774         *NotEncodedT = T;
5775       return;
5776     }
5777 
5778   // We could see an undeduced auto type here during error recovery.
5779   // Just ignore it.
5780   case Type::Auto:
5781     return;
5782 
5783 
5784 #define ABSTRACT_TYPE(KIND, BASE)
5785 #define TYPE(KIND, BASE)
5786 #define DEPENDENT_TYPE(KIND, BASE) \
5787   case Type::KIND:
5788 #define NON_CANONICAL_TYPE(KIND, BASE) \
5789   case Type::KIND:
5790 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(KIND, BASE) \
5791   case Type::KIND:
5792 #include "clang/AST/TypeNodes.def"
5793     llvm_unreachable("@encode for dependent type!");
5794   }
5795   llvm_unreachable("bad type kind!");
5796 }
5797 
getObjCEncodingForStructureImpl(RecordDecl * RDecl,std::string & S,const FieldDecl * FD,bool includeVBases,QualType * NotEncodedT) const5798 void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl,
5799                                                  std::string &S,
5800                                                  const FieldDecl *FD,
5801                                                  bool includeVBases,
5802                                                  QualType *NotEncodedT) const {
5803   assert(RDecl && "Expected non-null RecordDecl");
5804   assert(!RDecl->isUnion() && "Should not be called for unions");
5805   if (!RDecl->getDefinition())
5806     return;
5807 
5808   CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl);
5809   std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets;
5810   const ASTRecordLayout &layout = getASTRecordLayout(RDecl);
5811 
5812   if (CXXRec) {
5813     for (const auto &BI : CXXRec->bases()) {
5814       if (!BI.isVirtual()) {
5815         CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
5816         if (base->isEmpty())
5817           continue;
5818         uint64_t offs = toBits(layout.getBaseClassOffset(base));
5819         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5820                                   std::make_pair(offs, base));
5821       }
5822     }
5823   }
5824 
5825   unsigned i = 0;
5826   for (auto *Field : RDecl->fields()) {
5827     uint64_t offs = layout.getFieldOffset(i);
5828     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5829                               std::make_pair(offs, Field));
5830     ++i;
5831   }
5832 
5833   if (CXXRec && includeVBases) {
5834     for (const auto &BI : CXXRec->vbases()) {
5835       CXXRecordDecl *base = BI.getType()->getAsCXXRecordDecl();
5836       if (base->isEmpty())
5837         continue;
5838       uint64_t offs = toBits(layout.getVBaseClassOffset(base));
5839       if (offs >= uint64_t(toBits(layout.getNonVirtualSize())) &&
5840           FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end())
5841         FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(),
5842                                   std::make_pair(offs, base));
5843     }
5844   }
5845 
5846   CharUnits size;
5847   if (CXXRec) {
5848     size = includeVBases ? layout.getSize() : layout.getNonVirtualSize();
5849   } else {
5850     size = layout.getSize();
5851   }
5852 
5853 #ifndef NDEBUG
5854   uint64_t CurOffs = 0;
5855 #endif
5856   std::multimap<uint64_t, NamedDecl *>::iterator
5857     CurLayObj = FieldOrBaseOffsets.begin();
5858 
5859   if (CXXRec && CXXRec->isDynamicClass() &&
5860       (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) {
5861     if (FD) {
5862       S += "\"_vptr$";
5863       std::string recname = CXXRec->getNameAsString();
5864       if (recname.empty()) recname = "?";
5865       S += recname;
5866       S += '"';
5867     }
5868     S += "^^?";
5869 #ifndef NDEBUG
5870     CurOffs += getTypeSize(VoidPtrTy);
5871 #endif
5872   }
5873 
5874   if (!RDecl->hasFlexibleArrayMember()) {
5875     // Mark the end of the structure.
5876     uint64_t offs = toBits(size);
5877     FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs),
5878                               std::make_pair(offs, nullptr));
5879   }
5880 
5881   for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) {
5882 #ifndef NDEBUG
5883     assert(CurOffs <= CurLayObj->first);
5884     if (CurOffs < CurLayObj->first) {
5885       uint64_t padding = CurLayObj->first - CurOffs;
5886       // FIXME: There doesn't seem to be a way to indicate in the encoding that
5887       // packing/alignment of members is different that normal, in which case
5888       // the encoding will be out-of-sync with the real layout.
5889       // If the runtime switches to just consider the size of types without
5890       // taking into account alignment, we could make padding explicit in the
5891       // encoding (e.g. using arrays of chars). The encoding strings would be
5892       // longer then though.
5893       CurOffs += padding;
5894     }
5895 #endif
5896 
5897     NamedDecl *dcl = CurLayObj->second;
5898     if (!dcl)
5899       break; // reached end of structure.
5900 
5901     if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) {
5902       // We expand the bases without their virtual bases since those are going
5903       // in the initial structure. Note that this differs from gcc which
5904       // expands virtual bases each time one is encountered in the hierarchy,
5905       // making the encoding type bigger than it really is.
5906       getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false,
5907                                       NotEncodedT);
5908       assert(!base->isEmpty());
5909 #ifndef NDEBUG
5910       CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize());
5911 #endif
5912     } else {
5913       FieldDecl *field = cast<FieldDecl>(dcl);
5914       if (FD) {
5915         S += '"';
5916         S += field->getNameAsString();
5917         S += '"';
5918       }
5919 
5920       if (field->isBitField()) {
5921         EncodeBitField(this, S, field->getType(), field);
5922 #ifndef NDEBUG
5923         CurOffs += field->getBitWidthValue(*this);
5924 #endif
5925       } else {
5926         QualType qt = field->getType();
5927         getLegacyIntegralTypeEncoding(qt);
5928         getObjCEncodingForTypeImpl(qt, S, false, true, FD,
5929                                    /*OutermostType*/false,
5930                                    /*EncodingProperty*/false,
5931                                    /*StructField*/true,
5932                                    false, false, false, NotEncodedT);
5933 #ifndef NDEBUG
5934         CurOffs += getTypeSize(field->getType());
5935 #endif
5936       }
5937     }
5938   }
5939 }
5940 
getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,std::string & S) const5941 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
5942                                                  std::string& S) const {
5943   if (QT & Decl::OBJC_TQ_In)
5944     S += 'n';
5945   if (QT & Decl::OBJC_TQ_Inout)
5946     S += 'N';
5947   if (QT & Decl::OBJC_TQ_Out)
5948     S += 'o';
5949   if (QT & Decl::OBJC_TQ_Bycopy)
5950     S += 'O';
5951   if (QT & Decl::OBJC_TQ_Byref)
5952     S += 'R';
5953   if (QT & Decl::OBJC_TQ_Oneway)
5954     S += 'V';
5955 }
5956 
getObjCIdDecl() const5957 TypedefDecl *ASTContext::getObjCIdDecl() const {
5958   if (!ObjCIdDecl) {
5959     QualType T = getObjCObjectType(ObjCBuiltinIdTy, { }, { });
5960     T = getObjCObjectPointerType(T);
5961     ObjCIdDecl = buildImplicitTypedef(T, "id");
5962   }
5963   return ObjCIdDecl;
5964 }
5965 
getObjCSelDecl() const5966 TypedefDecl *ASTContext::getObjCSelDecl() const {
5967   if (!ObjCSelDecl) {
5968     QualType T = getPointerType(ObjCBuiltinSelTy);
5969     ObjCSelDecl = buildImplicitTypedef(T, "SEL");
5970   }
5971   return ObjCSelDecl;
5972 }
5973 
getObjCClassDecl() const5974 TypedefDecl *ASTContext::getObjCClassDecl() const {
5975   if (!ObjCClassDecl) {
5976     QualType T = getObjCObjectType(ObjCBuiltinClassTy, { }, { });
5977     T = getObjCObjectPointerType(T);
5978     ObjCClassDecl = buildImplicitTypedef(T, "Class");
5979   }
5980   return ObjCClassDecl;
5981 }
5982 
getObjCProtocolDecl() const5983 ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const {
5984   if (!ObjCProtocolClassDecl) {
5985     ObjCProtocolClassDecl
5986       = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(),
5987                                   SourceLocation(),
5988                                   &Idents.get("Protocol"),
5989                                   /*typeParamList=*/nullptr,
5990                                   /*PrevDecl=*/nullptr,
5991                                   SourceLocation(), true);
5992   }
5993 
5994   return ObjCProtocolClassDecl;
5995 }
5996 
5997 //===----------------------------------------------------------------------===//
5998 // __builtin_va_list Construction Functions
5999 //===----------------------------------------------------------------------===//
6000 
CreateCharPtrBuiltinVaListDecl(const ASTContext * Context)6001 static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) {
6002   // typedef char* __builtin_va_list;
6003   QualType T = Context->getPointerType(Context->CharTy);
6004   return Context->buildImplicitTypedef(T, "__builtin_va_list");
6005 }
6006 
CreateVoidPtrBuiltinVaListDecl(const ASTContext * Context)6007 static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) {
6008   // typedef void* __builtin_va_list;
6009   QualType T = Context->getPointerType(Context->VoidTy);
6010   return Context->buildImplicitTypedef(T, "__builtin_va_list");
6011 }
6012 
6013 static TypedefDecl *
CreateAArch64ABIBuiltinVaListDecl(const ASTContext * Context)6014 CreateAArch64ABIBuiltinVaListDecl(const ASTContext *Context) {
6015   // struct __va_list
6016   RecordDecl *VaListTagDecl = Context->buildImplicitRecord("__va_list");
6017   if (Context->getLangOpts().CPlusPlus) {
6018     // namespace std { struct __va_list {
6019     NamespaceDecl *NS;
6020     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6021                                Context->getTranslationUnitDecl(),
6022                                /*Inline*/ false, SourceLocation(),
6023                                SourceLocation(), &Context->Idents.get("std"),
6024                                /*PrevDecl*/ nullptr);
6025     NS->setImplicit();
6026     VaListTagDecl->setDeclContext(NS);
6027   }
6028 
6029   VaListTagDecl->startDefinition();
6030 
6031   const size_t NumFields = 5;
6032   QualType FieldTypes[NumFields];
6033   const char *FieldNames[NumFields];
6034 
6035   // void *__stack;
6036   FieldTypes[0] = Context->getPointerType(Context->VoidTy);
6037   FieldNames[0] = "__stack";
6038 
6039   // void *__gr_top;
6040   FieldTypes[1] = Context->getPointerType(Context->VoidTy);
6041   FieldNames[1] = "__gr_top";
6042 
6043   // void *__vr_top;
6044   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6045   FieldNames[2] = "__vr_top";
6046 
6047   // int __gr_offs;
6048   FieldTypes[3] = Context->IntTy;
6049   FieldNames[3] = "__gr_offs";
6050 
6051   // int __vr_offs;
6052   FieldTypes[4] = Context->IntTy;
6053   FieldNames[4] = "__vr_offs";
6054 
6055   // Create fields
6056   for (unsigned i = 0; i < NumFields; ++i) {
6057     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6058                                          VaListTagDecl,
6059                                          SourceLocation(),
6060                                          SourceLocation(),
6061                                          &Context->Idents.get(FieldNames[i]),
6062                                          FieldTypes[i], /*TInfo=*/nullptr,
6063                                          /*BitWidth=*/nullptr,
6064                                          /*Mutable=*/false,
6065                                          ICIS_NoInit);
6066     Field->setAccess(AS_public);
6067     VaListTagDecl->addDecl(Field);
6068   }
6069   VaListTagDecl->completeDefinition();
6070   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6071   Context->VaListTagTy = VaListTagType;
6072 
6073   // } __builtin_va_list;
6074   return Context->buildImplicitTypedef(VaListTagType, "__builtin_va_list");
6075 }
6076 
CreatePowerABIBuiltinVaListDecl(const ASTContext * Context)6077 static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) {
6078   // typedef struct __va_list_tag {
6079   RecordDecl *VaListTagDecl;
6080 
6081   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6082   VaListTagDecl->startDefinition();
6083 
6084   const size_t NumFields = 5;
6085   QualType FieldTypes[NumFields];
6086   const char *FieldNames[NumFields];
6087 
6088   //   unsigned char gpr;
6089   FieldTypes[0] = Context->UnsignedCharTy;
6090   FieldNames[0] = "gpr";
6091 
6092   //   unsigned char fpr;
6093   FieldTypes[1] = Context->UnsignedCharTy;
6094   FieldNames[1] = "fpr";
6095 
6096   //   unsigned short reserved;
6097   FieldTypes[2] = Context->UnsignedShortTy;
6098   FieldNames[2] = "reserved";
6099 
6100   //   void* overflow_arg_area;
6101   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6102   FieldNames[3] = "overflow_arg_area";
6103 
6104   //   void* reg_save_area;
6105   FieldTypes[4] = Context->getPointerType(Context->VoidTy);
6106   FieldNames[4] = "reg_save_area";
6107 
6108   // Create fields
6109   for (unsigned i = 0; i < NumFields; ++i) {
6110     FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl,
6111                                          SourceLocation(),
6112                                          SourceLocation(),
6113                                          &Context->Idents.get(FieldNames[i]),
6114                                          FieldTypes[i], /*TInfo=*/nullptr,
6115                                          /*BitWidth=*/nullptr,
6116                                          /*Mutable=*/false,
6117                                          ICIS_NoInit);
6118     Field->setAccess(AS_public);
6119     VaListTagDecl->addDecl(Field);
6120   }
6121   VaListTagDecl->completeDefinition();
6122   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6123   Context->VaListTagTy = VaListTagType;
6124 
6125   // } __va_list_tag;
6126   TypedefDecl *VaListTagTypedefDecl =
6127       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6128 
6129   QualType VaListTagTypedefType =
6130     Context->getTypedefType(VaListTagTypedefDecl);
6131 
6132   // typedef __va_list_tag __builtin_va_list[1];
6133   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6134   QualType VaListTagArrayType
6135     = Context->getConstantArrayType(VaListTagTypedefType,
6136                                     Size, ArrayType::Normal, 0);
6137   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6138 }
6139 
6140 static TypedefDecl *
CreateX86_64ABIBuiltinVaListDecl(const ASTContext * Context)6141 CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) {
6142   // typedef struct __va_list_tag {
6143   RecordDecl *VaListTagDecl;
6144   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6145   VaListTagDecl->startDefinition();
6146 
6147   const size_t NumFields = 4;
6148   QualType FieldTypes[NumFields];
6149   const char *FieldNames[NumFields];
6150 
6151   //   unsigned gp_offset;
6152   FieldTypes[0] = Context->UnsignedIntTy;
6153   FieldNames[0] = "gp_offset";
6154 
6155   //   unsigned fp_offset;
6156   FieldTypes[1] = Context->UnsignedIntTy;
6157   FieldNames[1] = "fp_offset";
6158 
6159   //   void* overflow_arg_area;
6160   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6161   FieldNames[2] = "overflow_arg_area";
6162 
6163   //   void* reg_save_area;
6164   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6165   FieldNames[3] = "reg_save_area";
6166 
6167   // Create fields
6168   for (unsigned i = 0; i < NumFields; ++i) {
6169     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6170                                          VaListTagDecl,
6171                                          SourceLocation(),
6172                                          SourceLocation(),
6173                                          &Context->Idents.get(FieldNames[i]),
6174                                          FieldTypes[i], /*TInfo=*/nullptr,
6175                                          /*BitWidth=*/nullptr,
6176                                          /*Mutable=*/false,
6177                                          ICIS_NoInit);
6178     Field->setAccess(AS_public);
6179     VaListTagDecl->addDecl(Field);
6180   }
6181   VaListTagDecl->completeDefinition();
6182   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6183   Context->VaListTagTy = VaListTagType;
6184 
6185   // } __va_list_tag;
6186   TypedefDecl *VaListTagTypedefDecl =
6187       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6188 
6189   QualType VaListTagTypedefType =
6190     Context->getTypedefType(VaListTagTypedefDecl);
6191 
6192   // typedef __va_list_tag __builtin_va_list[1];
6193   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6194   QualType VaListTagArrayType
6195     = Context->getConstantArrayType(VaListTagTypedefType,
6196                                       Size, ArrayType::Normal,0);
6197   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6198 }
6199 
CreatePNaClABIBuiltinVaListDecl(const ASTContext * Context)6200 static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) {
6201   // typedef int __builtin_va_list[4];
6202   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4);
6203   QualType IntArrayType
6204     = Context->getConstantArrayType(Context->IntTy,
6205 				    Size, ArrayType::Normal, 0);
6206   return Context->buildImplicitTypedef(IntArrayType, "__builtin_va_list");
6207 }
6208 
6209 static TypedefDecl *
CreateAAPCSABIBuiltinVaListDecl(const ASTContext * Context)6210 CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
6211   // struct __va_list
6212   RecordDecl *VaListDecl = Context->buildImplicitRecord("__va_list");
6213   if (Context->getLangOpts().CPlusPlus) {
6214     // namespace std { struct __va_list {
6215     NamespaceDecl *NS;
6216     NS = NamespaceDecl::Create(const_cast<ASTContext &>(*Context),
6217                                Context->getTranslationUnitDecl(),
6218                                /*Inline*/false, SourceLocation(),
6219                                SourceLocation(), &Context->Idents.get("std"),
6220                                /*PrevDecl*/ nullptr);
6221     NS->setImplicit();
6222     VaListDecl->setDeclContext(NS);
6223   }
6224 
6225   VaListDecl->startDefinition();
6226 
6227   // void * __ap;
6228   FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6229                                        VaListDecl,
6230                                        SourceLocation(),
6231                                        SourceLocation(),
6232                                        &Context->Idents.get("__ap"),
6233                                        Context->getPointerType(Context->VoidTy),
6234                                        /*TInfo=*/nullptr,
6235                                        /*BitWidth=*/nullptr,
6236                                        /*Mutable=*/false,
6237                                        ICIS_NoInit);
6238   Field->setAccess(AS_public);
6239   VaListDecl->addDecl(Field);
6240 
6241   // };
6242   VaListDecl->completeDefinition();
6243 
6244   // typedef struct __va_list __builtin_va_list;
6245   QualType T = Context->getRecordType(VaListDecl);
6246   return Context->buildImplicitTypedef(T, "__builtin_va_list");
6247 }
6248 
6249 static TypedefDecl *
CreateSystemZBuiltinVaListDecl(const ASTContext * Context)6250 CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
6251   // typedef struct __va_list_tag {
6252   RecordDecl *VaListTagDecl;
6253   VaListTagDecl = Context->buildImplicitRecord("__va_list_tag");
6254   VaListTagDecl->startDefinition();
6255 
6256   const size_t NumFields = 4;
6257   QualType FieldTypes[NumFields];
6258   const char *FieldNames[NumFields];
6259 
6260   //   long __gpr;
6261   FieldTypes[0] = Context->LongTy;
6262   FieldNames[0] = "__gpr";
6263 
6264   //   long __fpr;
6265   FieldTypes[1] = Context->LongTy;
6266   FieldNames[1] = "__fpr";
6267 
6268   //   void *__overflow_arg_area;
6269   FieldTypes[2] = Context->getPointerType(Context->VoidTy);
6270   FieldNames[2] = "__overflow_arg_area";
6271 
6272   //   void *__reg_save_area;
6273   FieldTypes[3] = Context->getPointerType(Context->VoidTy);
6274   FieldNames[3] = "__reg_save_area";
6275 
6276   // Create fields
6277   for (unsigned i = 0; i < NumFields; ++i) {
6278     FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
6279                                          VaListTagDecl,
6280                                          SourceLocation(),
6281                                          SourceLocation(),
6282                                          &Context->Idents.get(FieldNames[i]),
6283                                          FieldTypes[i], /*TInfo=*/nullptr,
6284                                          /*BitWidth=*/nullptr,
6285                                          /*Mutable=*/false,
6286                                          ICIS_NoInit);
6287     Field->setAccess(AS_public);
6288     VaListTagDecl->addDecl(Field);
6289   }
6290   VaListTagDecl->completeDefinition();
6291   QualType VaListTagType = Context->getRecordType(VaListTagDecl);
6292   Context->VaListTagTy = VaListTagType;
6293 
6294   // } __va_list_tag;
6295   TypedefDecl *VaListTagTypedefDecl =
6296       Context->buildImplicitTypedef(VaListTagType, "__va_list_tag");
6297   QualType VaListTagTypedefType =
6298     Context->getTypedefType(VaListTagTypedefDecl);
6299 
6300   // typedef __va_list_tag __builtin_va_list[1];
6301   llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
6302   QualType VaListTagArrayType
6303     = Context->getConstantArrayType(VaListTagTypedefType,
6304                                       Size, ArrayType::Normal,0);
6305 
6306   return Context->buildImplicitTypedef(VaListTagArrayType, "__builtin_va_list");
6307 }
6308 
CreateVaListDecl(const ASTContext * Context,TargetInfo::BuiltinVaListKind Kind)6309 static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
6310                                      TargetInfo::BuiltinVaListKind Kind) {
6311   switch (Kind) {
6312   case TargetInfo::CharPtrBuiltinVaList:
6313     return CreateCharPtrBuiltinVaListDecl(Context);
6314   case TargetInfo::VoidPtrBuiltinVaList:
6315     return CreateVoidPtrBuiltinVaListDecl(Context);
6316   case TargetInfo::AArch64ABIBuiltinVaList:
6317     return CreateAArch64ABIBuiltinVaListDecl(Context);
6318   case TargetInfo::PowerABIBuiltinVaList:
6319     return CreatePowerABIBuiltinVaListDecl(Context);
6320   case TargetInfo::X86_64ABIBuiltinVaList:
6321     return CreateX86_64ABIBuiltinVaListDecl(Context);
6322   case TargetInfo::PNaClABIBuiltinVaList:
6323     return CreatePNaClABIBuiltinVaListDecl(Context);
6324   case TargetInfo::AAPCSABIBuiltinVaList:
6325     return CreateAAPCSABIBuiltinVaListDecl(Context);
6326   case TargetInfo::SystemZBuiltinVaList:
6327     return CreateSystemZBuiltinVaListDecl(Context);
6328   }
6329 
6330   llvm_unreachable("Unhandled __builtin_va_list type kind");
6331 }
6332 
getBuiltinVaListDecl() const6333 TypedefDecl *ASTContext::getBuiltinVaListDecl() const {
6334   if (!BuiltinVaListDecl) {
6335     BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind());
6336     assert(BuiltinVaListDecl->isImplicit());
6337   }
6338 
6339   return BuiltinVaListDecl;
6340 }
6341 
getVaListTagType() const6342 QualType ASTContext::getVaListTagType() const {
6343   // Force the creation of VaListTagTy by building the __builtin_va_list
6344   // declaration.
6345   if (VaListTagTy.isNull())
6346     (void) getBuiltinVaListDecl();
6347 
6348   return VaListTagTy;
6349 }
6350 
setObjCConstantStringInterface(ObjCInterfaceDecl * Decl)6351 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) {
6352   assert(ObjCConstantStringType.isNull() &&
6353          "'NSConstantString' type already set!");
6354 
6355   ObjCConstantStringType = getObjCInterfaceType(Decl);
6356 }
6357 
6358 /// \brief Retrieve the template name that corresponds to a non-empty
6359 /// lookup.
6360 TemplateName
getOverloadedTemplateName(UnresolvedSetIterator Begin,UnresolvedSetIterator End) const6361 ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin,
6362                                       UnresolvedSetIterator End) const {
6363   unsigned size = End - Begin;
6364   assert(size > 1 && "set is not overloaded!");
6365 
6366   void *memory = Allocate(sizeof(OverloadedTemplateStorage) +
6367                           size * sizeof(FunctionTemplateDecl*));
6368   OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size);
6369 
6370   NamedDecl **Storage = OT->getStorage();
6371   for (UnresolvedSetIterator I = Begin; I != End; ++I) {
6372     NamedDecl *D = *I;
6373     assert(isa<FunctionTemplateDecl>(D) ||
6374            (isa<UsingShadowDecl>(D) &&
6375             isa<FunctionTemplateDecl>(D->getUnderlyingDecl())));
6376     *Storage++ = D;
6377   }
6378 
6379   return TemplateName(OT);
6380 }
6381 
6382 /// \brief Retrieve the template name that represents a qualified
6383 /// template name such as \c std::vector.
6384 TemplateName
getQualifiedTemplateName(NestedNameSpecifier * NNS,bool TemplateKeyword,TemplateDecl * Template) const6385 ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS,
6386                                      bool TemplateKeyword,
6387                                      TemplateDecl *Template) const {
6388   assert(NNS && "Missing nested-name-specifier in qualified template name");
6389 
6390   // FIXME: Canonicalization?
6391   llvm::FoldingSetNodeID ID;
6392   QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template);
6393 
6394   void *InsertPos = nullptr;
6395   QualifiedTemplateName *QTN =
6396     QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6397   if (!QTN) {
6398     QTN = new (*this, llvm::alignOf<QualifiedTemplateName>())
6399         QualifiedTemplateName(NNS, TemplateKeyword, Template);
6400     QualifiedTemplateNames.InsertNode(QTN, InsertPos);
6401   }
6402 
6403   return TemplateName(QTN);
6404 }
6405 
6406 /// \brief Retrieve the template name that represents a dependent
6407 /// template name such as \c MetaFun::template apply.
6408 TemplateName
getDependentTemplateName(NestedNameSpecifier * NNS,const IdentifierInfo * Name) const6409 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6410                                      const IdentifierInfo *Name) const {
6411   assert((!NNS || NNS->isDependent()) &&
6412          "Nested name specifier must be dependent");
6413 
6414   llvm::FoldingSetNodeID ID;
6415   DependentTemplateName::Profile(ID, NNS, Name);
6416 
6417   void *InsertPos = nullptr;
6418   DependentTemplateName *QTN =
6419     DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6420 
6421   if (QTN)
6422     return TemplateName(QTN);
6423 
6424   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6425   if (CanonNNS == NNS) {
6426     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6427         DependentTemplateName(NNS, Name);
6428   } else {
6429     TemplateName Canon = getDependentTemplateName(CanonNNS, Name);
6430     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6431         DependentTemplateName(NNS, Name, Canon);
6432     DependentTemplateName *CheckQTN =
6433       DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6434     assert(!CheckQTN && "Dependent type name canonicalization broken");
6435     (void)CheckQTN;
6436   }
6437 
6438   DependentTemplateNames.InsertNode(QTN, InsertPos);
6439   return TemplateName(QTN);
6440 }
6441 
6442 /// \brief Retrieve the template name that represents a dependent
6443 /// template name such as \c MetaFun::template operator+.
6444 TemplateName
getDependentTemplateName(NestedNameSpecifier * NNS,OverloadedOperatorKind Operator) const6445 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS,
6446                                      OverloadedOperatorKind Operator) const {
6447   assert((!NNS || NNS->isDependent()) &&
6448          "Nested name specifier must be dependent");
6449 
6450   llvm::FoldingSetNodeID ID;
6451   DependentTemplateName::Profile(ID, NNS, Operator);
6452 
6453   void *InsertPos = nullptr;
6454   DependentTemplateName *QTN
6455     = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6456 
6457   if (QTN)
6458     return TemplateName(QTN);
6459 
6460   NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS);
6461   if (CanonNNS == NNS) {
6462     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6463         DependentTemplateName(NNS, Operator);
6464   } else {
6465     TemplateName Canon = getDependentTemplateName(CanonNNS, Operator);
6466     QTN = new (*this, llvm::alignOf<DependentTemplateName>())
6467         DependentTemplateName(NNS, Operator, Canon);
6468 
6469     DependentTemplateName *CheckQTN
6470       = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos);
6471     assert(!CheckQTN && "Dependent template name canonicalization broken");
6472     (void)CheckQTN;
6473   }
6474 
6475   DependentTemplateNames.InsertNode(QTN, InsertPos);
6476   return TemplateName(QTN);
6477 }
6478 
6479 TemplateName
getSubstTemplateTemplateParm(TemplateTemplateParmDecl * param,TemplateName replacement) const6480 ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
6481                                          TemplateName replacement) const {
6482   llvm::FoldingSetNodeID ID;
6483   SubstTemplateTemplateParmStorage::Profile(ID, param, replacement);
6484 
6485   void *insertPos = nullptr;
6486   SubstTemplateTemplateParmStorage *subst
6487     = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos);
6488 
6489   if (!subst) {
6490     subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement);
6491     SubstTemplateTemplateParms.InsertNode(subst, insertPos);
6492   }
6493 
6494   return TemplateName(subst);
6495 }
6496 
6497 TemplateName
getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl * Param,const TemplateArgument & ArgPack) const6498 ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
6499                                        const TemplateArgument &ArgPack) const {
6500   ASTContext &Self = const_cast<ASTContext &>(*this);
6501   llvm::FoldingSetNodeID ID;
6502   SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack);
6503 
6504   void *InsertPos = nullptr;
6505   SubstTemplateTemplateParmPackStorage *Subst
6506     = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos);
6507 
6508   if (!Subst) {
6509     Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param,
6510                                                            ArgPack.pack_size(),
6511                                                          ArgPack.pack_begin());
6512     SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos);
6513   }
6514 
6515   return TemplateName(Subst);
6516 }
6517 
6518 /// getFromTargetType - Given one of the integer types provided by
6519 /// TargetInfo, produce the corresponding type. The unsigned @p Type
6520 /// is actually a value of type @c TargetInfo::IntType.
getFromTargetType(unsigned Type) const6521 CanQualType ASTContext::getFromTargetType(unsigned Type) const {
6522   switch (Type) {
6523   case TargetInfo::NoInt: return CanQualType();
6524   case TargetInfo::SignedChar: return SignedCharTy;
6525   case TargetInfo::UnsignedChar: return UnsignedCharTy;
6526   case TargetInfo::SignedShort: return ShortTy;
6527   case TargetInfo::UnsignedShort: return UnsignedShortTy;
6528   case TargetInfo::SignedInt: return IntTy;
6529   case TargetInfo::UnsignedInt: return UnsignedIntTy;
6530   case TargetInfo::SignedLong: return LongTy;
6531   case TargetInfo::UnsignedLong: return UnsignedLongTy;
6532   case TargetInfo::SignedLongLong: return LongLongTy;
6533   case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy;
6534   }
6535 
6536   llvm_unreachable("Unhandled TargetInfo::IntType value");
6537 }
6538 
6539 //===----------------------------------------------------------------------===//
6540 //                        Type Predicates.
6541 //===----------------------------------------------------------------------===//
6542 
6543 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's
6544 /// garbage collection attribute.
6545 ///
getObjCGCAttrKind(QualType Ty) const6546 Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const {
6547   if (getLangOpts().getGC() == LangOptions::NonGC)
6548     return Qualifiers::GCNone;
6549 
6550   assert(getLangOpts().ObjC1);
6551   Qualifiers::GC GCAttrs = Ty.getObjCGCAttr();
6552 
6553   // Default behaviour under objective-C's gc is for ObjC pointers
6554   // (or pointers to them) be treated as though they were declared
6555   // as __strong.
6556   if (GCAttrs == Qualifiers::GCNone) {
6557     if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType())
6558       return Qualifiers::Strong;
6559     else if (Ty->isPointerType())
6560       return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType());
6561   } else {
6562     // It's not valid to set GC attributes on anything that isn't a
6563     // pointer.
6564 #ifndef NDEBUG
6565     QualType CT = Ty->getCanonicalTypeInternal();
6566     while (const ArrayType *AT = dyn_cast<ArrayType>(CT))
6567       CT = AT->getElementType();
6568     assert(CT->isAnyPointerType() || CT->isBlockPointerType());
6569 #endif
6570   }
6571   return GCAttrs;
6572 }
6573 
6574 //===----------------------------------------------------------------------===//
6575 //                        Type Compatibility Testing
6576 //===----------------------------------------------------------------------===//
6577 
6578 /// areCompatVectorTypes - Return true if the two specified vector types are
6579 /// compatible.
areCompatVectorTypes(const VectorType * LHS,const VectorType * RHS)6580 static bool areCompatVectorTypes(const VectorType *LHS,
6581                                  const VectorType *RHS) {
6582   assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified());
6583   return LHS->getElementType() == RHS->getElementType() &&
6584          LHS->getNumElements() == RHS->getNumElements();
6585 }
6586 
areCompatibleVectorTypes(QualType FirstVec,QualType SecondVec)6587 bool ASTContext::areCompatibleVectorTypes(QualType FirstVec,
6588                                           QualType SecondVec) {
6589   assert(FirstVec->isVectorType() && "FirstVec should be a vector type");
6590   assert(SecondVec->isVectorType() && "SecondVec should be a vector type");
6591 
6592   if (hasSameUnqualifiedType(FirstVec, SecondVec))
6593     return true;
6594 
6595   // Treat Neon vector types and most AltiVec vector types as if they are the
6596   // equivalent GCC vector types.
6597   const VectorType *First = FirstVec->getAs<VectorType>();
6598   const VectorType *Second = SecondVec->getAs<VectorType>();
6599   if (First->getNumElements() == Second->getNumElements() &&
6600       hasSameType(First->getElementType(), Second->getElementType()) &&
6601       First->getVectorKind() != VectorType::AltiVecPixel &&
6602       First->getVectorKind() != VectorType::AltiVecBool &&
6603       Second->getVectorKind() != VectorType::AltiVecPixel &&
6604       Second->getVectorKind() != VectorType::AltiVecBool)
6605     return true;
6606 
6607   return false;
6608 }
6609 
6610 //===----------------------------------------------------------------------===//
6611 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
6612 //===----------------------------------------------------------------------===//
6613 
6614 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
6615 /// inheritance hierarchy of 'rProto'.
6616 bool
ProtocolCompatibleWithProtocol(ObjCProtocolDecl * lProto,ObjCProtocolDecl * rProto) const6617 ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
6618                                            ObjCProtocolDecl *rProto) const {
6619   if (declaresSameEntity(lProto, rProto))
6620     return true;
6621   for (auto *PI : rProto->protocols())
6622     if (ProtocolCompatibleWithProtocol(lProto, PI))
6623       return true;
6624   return false;
6625 }
6626 
6627 /// ObjCQualifiedClassTypesAreCompatible - compare  Class<pr,...> and
6628 /// Class<pr1, ...>.
ObjCQualifiedClassTypesAreCompatible(QualType lhs,QualType rhs)6629 bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs,
6630                                                       QualType rhs) {
6631   const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>();
6632   const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6633   assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible");
6634 
6635   for (auto *lhsProto : lhsQID->quals()) {
6636     bool match = false;
6637     for (auto *rhsProto : rhsOPT->quals()) {
6638       if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) {
6639         match = true;
6640         break;
6641       }
6642     }
6643     if (!match)
6644       return false;
6645   }
6646   return true;
6647 }
6648 
6649 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
6650 /// ObjCQualifiedIDType.
ObjCQualifiedIdTypesAreCompatible(QualType lhs,QualType rhs,bool compare)6651 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs,
6652                                                    bool compare) {
6653   // Allow id<P..> and an 'id' or void* type in all cases.
6654   if (lhs->isVoidPointerType() ||
6655       lhs->isObjCIdType() || lhs->isObjCClassType())
6656     return true;
6657   else if (rhs->isVoidPointerType() ||
6658            rhs->isObjCIdType() || rhs->isObjCClassType())
6659     return true;
6660 
6661   if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) {
6662     const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6663 
6664     if (!rhsOPT) return false;
6665 
6666     if (rhsOPT->qual_empty()) {
6667       // If the RHS is a unqualified interface pointer "NSString*",
6668       // make sure we check the class hierarchy.
6669       if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6670         for (auto *I : lhsQID->quals()) {
6671           // when comparing an id<P> on lhs with a static type on rhs,
6672           // see if static class implements all of id's protocols, directly or
6673           // through its super class and categories.
6674           if (!rhsID->ClassImplementsProtocol(I, true))
6675             return false;
6676         }
6677       }
6678       // If there are no qualifiers and no interface, we have an 'id'.
6679       return true;
6680     }
6681     // Both the right and left sides have qualifiers.
6682     for (auto *lhsProto : lhsQID->quals()) {
6683       bool match = false;
6684 
6685       // when comparing an id<P> on lhs with a static type on rhs,
6686       // see if static class implements all of id's protocols, directly or
6687       // through its super class and categories.
6688       for (auto *rhsProto : rhsOPT->quals()) {
6689         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6690             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6691           match = true;
6692           break;
6693         }
6694       }
6695       // If the RHS is a qualified interface pointer "NSString<P>*",
6696       // make sure we check the class hierarchy.
6697       if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) {
6698         for (auto *I : lhsQID->quals()) {
6699           // when comparing an id<P> on lhs with a static type on rhs,
6700           // see if static class implements all of id's protocols, directly or
6701           // through its super class and categories.
6702           if (rhsID->ClassImplementsProtocol(I, true)) {
6703             match = true;
6704             break;
6705           }
6706         }
6707       }
6708       if (!match)
6709         return false;
6710     }
6711 
6712     return true;
6713   }
6714 
6715   const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType();
6716   assert(rhsQID && "One of the LHS/RHS should be id<x>");
6717 
6718   if (const ObjCObjectPointerType *lhsOPT =
6719         lhs->getAsObjCInterfacePointerType()) {
6720     // If both the right and left sides have qualifiers.
6721     for (auto *lhsProto : lhsOPT->quals()) {
6722       bool match = false;
6723 
6724       // when comparing an id<P> on rhs with a static type on lhs,
6725       // see if static class implements all of id's protocols, directly or
6726       // through its super class and categories.
6727       // First, lhs protocols in the qualifier list must be found, direct
6728       // or indirect in rhs's qualifier list or it is a mismatch.
6729       for (auto *rhsProto : rhsQID->quals()) {
6730         if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6731             (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6732           match = true;
6733           break;
6734         }
6735       }
6736       if (!match)
6737         return false;
6738     }
6739 
6740     // Static class's protocols, or its super class or category protocols
6741     // must be found, direct or indirect in rhs's qualifier list or it is a mismatch.
6742     if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) {
6743       llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols;
6744       CollectInheritedProtocols(lhsID, LHSInheritedProtocols);
6745       // This is rather dubious but matches gcc's behavior. If lhs has
6746       // no type qualifier and its class has no static protocol(s)
6747       // assume that it is mismatch.
6748       if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty())
6749         return false;
6750       for (auto *lhsProto : LHSInheritedProtocols) {
6751         bool match = false;
6752         for (auto *rhsProto : rhsQID->quals()) {
6753           if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) ||
6754               (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) {
6755             match = true;
6756             break;
6757           }
6758         }
6759         if (!match)
6760           return false;
6761       }
6762     }
6763     return true;
6764   }
6765   return false;
6766 }
6767 
6768 /// canAssignObjCInterfaces - Return true if the two interface types are
6769 /// compatible for assignment from RHS to LHS.  This handles validation of any
6770 /// protocol qualifiers on the LHS or RHS.
6771 ///
canAssignObjCInterfaces(const ObjCObjectPointerType * LHSOPT,const ObjCObjectPointerType * RHSOPT)6772 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
6773                                          const ObjCObjectPointerType *RHSOPT) {
6774   const ObjCObjectType* LHS = LHSOPT->getObjectType();
6775   const ObjCObjectType* RHS = RHSOPT->getObjectType();
6776 
6777   // If either type represents the built-in 'id' or 'Class' types, return true.
6778   if (LHS->isObjCUnqualifiedIdOrClass() ||
6779       RHS->isObjCUnqualifiedIdOrClass())
6780     return true;
6781 
6782   // Function object that propagates a successful result or handles
6783   // __kindof types.
6784   auto finish = [&](bool succeeded) -> bool {
6785     if (succeeded)
6786       return true;
6787 
6788     if (!RHS->isKindOfType())
6789       return false;
6790 
6791     // Strip off __kindof and protocol qualifiers, then check whether
6792     // we can assign the other way.
6793     return canAssignObjCInterfaces(RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6794                                    LHSOPT->stripObjCKindOfTypeAndQuals(*this));
6795   };
6796 
6797   if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) {
6798     return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6799                                                     QualType(RHSOPT,0),
6800                                                     false));
6801   }
6802 
6803   if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) {
6804     return finish(ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0),
6805                                                        QualType(RHSOPT,0)));
6806   }
6807 
6808   // If we have 2 user-defined types, fall into that path.
6809   if (LHS->getInterface() && RHS->getInterface()) {
6810     return finish(canAssignObjCInterfaces(LHS, RHS));
6811   }
6812 
6813   return false;
6814 }
6815 
6816 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written
6817 /// for providing type-safety for objective-c pointers used to pass/return
6818 /// arguments in block literals. When passed as arguments, passing 'A*' where
6819 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is
6820 /// not OK. For the return type, the opposite is not OK.
canAssignObjCInterfacesInBlockPointer(const ObjCObjectPointerType * LHSOPT,const ObjCObjectPointerType * RHSOPT,bool BlockReturnType)6821 bool ASTContext::canAssignObjCInterfacesInBlockPointer(
6822                                          const ObjCObjectPointerType *LHSOPT,
6823                                          const ObjCObjectPointerType *RHSOPT,
6824                                          bool BlockReturnType) {
6825 
6826   // Function object that propagates a successful result or handles
6827   // __kindof types.
6828   auto finish = [&](bool succeeded) -> bool {
6829     if (succeeded)
6830       return true;
6831 
6832     const ObjCObjectPointerType *Expected = BlockReturnType ? RHSOPT : LHSOPT;
6833     if (!Expected->isKindOfType())
6834       return false;
6835 
6836     // Strip off __kindof and protocol qualifiers, then check whether
6837     // we can assign the other way.
6838     return canAssignObjCInterfacesInBlockPointer(
6839              RHSOPT->stripObjCKindOfTypeAndQuals(*this),
6840              LHSOPT->stripObjCKindOfTypeAndQuals(*this),
6841              BlockReturnType);
6842   };
6843 
6844   if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType())
6845     return true;
6846 
6847   if (LHSOPT->isObjCBuiltinType()) {
6848     return finish(RHSOPT->isObjCBuiltinType() ||
6849                   RHSOPT->isObjCQualifiedIdType());
6850   }
6851 
6852   if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType())
6853     return finish(ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0),
6854                                                     QualType(RHSOPT,0),
6855                                                     false));
6856 
6857   const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType();
6858   const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType();
6859   if (LHS && RHS)  { // We have 2 user-defined types.
6860     if (LHS != RHS) {
6861       if (LHS->getDecl()->isSuperClassOf(RHS->getDecl()))
6862         return finish(BlockReturnType);
6863       if (RHS->getDecl()->isSuperClassOf(LHS->getDecl()))
6864         return finish(!BlockReturnType);
6865     }
6866     else
6867       return true;
6868   }
6869   return false;
6870 }
6871 
6872 /// Comparison routine for Objective-C protocols to be used with
6873 /// llvm::array_pod_sort.
compareObjCProtocolsByName(ObjCProtocolDecl * const * lhs,ObjCProtocolDecl * const * rhs)6874 static int compareObjCProtocolsByName(ObjCProtocolDecl * const *lhs,
6875                                       ObjCProtocolDecl * const *rhs) {
6876   return (*lhs)->getName().compare((*rhs)->getName());
6877 
6878 }
6879 
6880 /// getIntersectionOfProtocols - This routine finds the intersection of set
6881 /// of protocols inherited from two distinct objective-c pointer objects with
6882 /// the given common base.
6883 /// It is used to build composite qualifier list of the composite type of
6884 /// the conditional expression involving two objective-c pointer objects.
6885 static
getIntersectionOfProtocols(ASTContext & Context,const ObjCInterfaceDecl * CommonBase,const ObjCObjectPointerType * LHSOPT,const ObjCObjectPointerType * RHSOPT,SmallVectorImpl<ObjCProtocolDecl * > & IntersectionSet)6886 void getIntersectionOfProtocols(ASTContext &Context,
6887                                 const ObjCInterfaceDecl *CommonBase,
6888                                 const ObjCObjectPointerType *LHSOPT,
6889                                 const ObjCObjectPointerType *RHSOPT,
6890       SmallVectorImpl<ObjCProtocolDecl *> &IntersectionSet) {
6891 
6892   const ObjCObjectType* LHS = LHSOPT->getObjectType();
6893   const ObjCObjectType* RHS = RHSOPT->getObjectType();
6894   assert(LHS->getInterface() && "LHS must have an interface base");
6895   assert(RHS->getInterface() && "RHS must have an interface base");
6896 
6897   // Add all of the protocols for the LHS.
6898   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSProtocolSet;
6899 
6900   // Start with the protocol qualifiers.
6901   for (auto proto : LHS->quals()) {
6902     Context.CollectInheritedProtocols(proto, LHSProtocolSet);
6903   }
6904 
6905   // Also add the protocols associated with the LHS interface.
6906   Context.CollectInheritedProtocols(LHS->getInterface(), LHSProtocolSet);
6907 
6908   // Add all of the protocls for the RHS.
6909   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSProtocolSet;
6910 
6911   // Start with the protocol qualifiers.
6912   for (auto proto : RHS->quals()) {
6913     Context.CollectInheritedProtocols(proto, RHSProtocolSet);
6914   }
6915 
6916   // Also add the protocols associated with the RHS interface.
6917   Context.CollectInheritedProtocols(RHS->getInterface(), RHSProtocolSet);
6918 
6919   // Compute the intersection of the collected protocol sets.
6920   for (auto proto : LHSProtocolSet) {
6921     if (RHSProtocolSet.count(proto))
6922       IntersectionSet.push_back(proto);
6923   }
6924 
6925   // Compute the set of protocols that is implied by either the common type or
6926   // the protocols within the intersection.
6927   llvm::SmallPtrSet<ObjCProtocolDecl *, 8> ImpliedProtocols;
6928   Context.CollectInheritedProtocols(CommonBase, ImpliedProtocols);
6929 
6930   // Remove any implied protocols from the list of inherited protocols.
6931   if (!ImpliedProtocols.empty()) {
6932     IntersectionSet.erase(
6933       std::remove_if(IntersectionSet.begin(),
6934                      IntersectionSet.end(),
6935                      [&](ObjCProtocolDecl *proto) -> bool {
6936                        return ImpliedProtocols.count(proto) > 0;
6937                      }),
6938       IntersectionSet.end());
6939   }
6940 
6941   // Sort the remaining protocols by name.
6942   llvm::array_pod_sort(IntersectionSet.begin(), IntersectionSet.end(),
6943                        compareObjCProtocolsByName);
6944 }
6945 
6946 /// Determine whether the first type is a subtype of the second.
canAssignObjCObjectTypes(ASTContext & ctx,QualType lhs,QualType rhs)6947 static bool canAssignObjCObjectTypes(ASTContext &ctx, QualType lhs,
6948                                      QualType rhs) {
6949   // Common case: two object pointers.
6950   const ObjCObjectPointerType *lhsOPT = lhs->getAs<ObjCObjectPointerType>();
6951   const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>();
6952   if (lhsOPT && rhsOPT)
6953     return ctx.canAssignObjCInterfaces(lhsOPT, rhsOPT);
6954 
6955   // Two block pointers.
6956   const BlockPointerType *lhsBlock = lhs->getAs<BlockPointerType>();
6957   const BlockPointerType *rhsBlock = rhs->getAs<BlockPointerType>();
6958   if (lhsBlock && rhsBlock)
6959     return ctx.typesAreBlockPointerCompatible(lhs, rhs);
6960 
6961   // If either is an unqualified 'id' and the other is a block, it's
6962   // acceptable.
6963   if ((lhsOPT && lhsOPT->isObjCIdType() && rhsBlock) ||
6964       (rhsOPT && rhsOPT->isObjCIdType() && lhsBlock))
6965     return true;
6966 
6967   return false;
6968 }
6969 
6970 // Check that the given Objective-C type argument lists are equivalent.
sameObjCTypeArgs(ASTContext & ctx,const ObjCInterfaceDecl * iface,ArrayRef<QualType> lhsArgs,ArrayRef<QualType> rhsArgs,bool stripKindOf)6971 static bool sameObjCTypeArgs(ASTContext &ctx,
6972                              const ObjCInterfaceDecl *iface,
6973                              ArrayRef<QualType> lhsArgs,
6974                              ArrayRef<QualType> rhsArgs,
6975                              bool stripKindOf) {
6976   if (lhsArgs.size() != rhsArgs.size())
6977     return false;
6978 
6979   ObjCTypeParamList *typeParams = iface->getTypeParamList();
6980   for (unsigned i = 0, n = lhsArgs.size(); i != n; ++i) {
6981     if (ctx.hasSameType(lhsArgs[i], rhsArgs[i]))
6982       continue;
6983 
6984     switch (typeParams->begin()[i]->getVariance()) {
6985     case ObjCTypeParamVariance::Invariant:
6986       if (!stripKindOf ||
6987           !ctx.hasSameType(lhsArgs[i].stripObjCKindOfType(ctx),
6988                            rhsArgs[i].stripObjCKindOfType(ctx))) {
6989         return false;
6990       }
6991       break;
6992 
6993     case ObjCTypeParamVariance::Covariant:
6994       if (!canAssignObjCObjectTypes(ctx, lhsArgs[i], rhsArgs[i]))
6995         return false;
6996       break;
6997 
6998     case ObjCTypeParamVariance::Contravariant:
6999       if (!canAssignObjCObjectTypes(ctx, rhsArgs[i], lhsArgs[i]))
7000         return false;
7001       break;
7002     }
7003   }
7004 
7005   return true;
7006 }
7007 
areCommonBaseCompatible(const ObjCObjectPointerType * Lptr,const ObjCObjectPointerType * Rptr)7008 QualType ASTContext::areCommonBaseCompatible(
7009            const ObjCObjectPointerType *Lptr,
7010            const ObjCObjectPointerType *Rptr) {
7011   const ObjCObjectType *LHS = Lptr->getObjectType();
7012   const ObjCObjectType *RHS = Rptr->getObjectType();
7013   const ObjCInterfaceDecl* LDecl = LHS->getInterface();
7014   const ObjCInterfaceDecl* RDecl = RHS->getInterface();
7015 
7016   if (!LDecl || !RDecl)
7017     return QualType();
7018 
7019   // Follow the left-hand side up the class hierarchy until we either hit a
7020   // root or find the RHS. Record the ancestors in case we don't find it.
7021   llvm::SmallDenseMap<const ObjCInterfaceDecl *, const ObjCObjectType *, 4>
7022     LHSAncestors;
7023   while (true) {
7024     // Record this ancestor. We'll need this if the common type isn't in the
7025     // path from the LHS to the root.
7026     LHSAncestors[LHS->getInterface()->getCanonicalDecl()] = LHS;
7027 
7028     if (declaresSameEntity(LHS->getInterface(), RDecl)) {
7029       // Get the type arguments.
7030       ArrayRef<QualType> LHSTypeArgs = LHS->getTypeArgsAsWritten();
7031       bool anyChanges = false;
7032       if (LHS->isSpecialized() && RHS->isSpecialized()) {
7033         // Both have type arguments, compare them.
7034         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7035                               LHS->getTypeArgs(), RHS->getTypeArgs(),
7036                               /*stripKindOf=*/true))
7037           return QualType();
7038       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7039         // If only one has type arguments, the result will not have type
7040         // arguments.
7041         LHSTypeArgs = { };
7042         anyChanges = true;
7043       }
7044 
7045       // Compute the intersection of protocols.
7046       SmallVector<ObjCProtocolDecl *, 8> Protocols;
7047       getIntersectionOfProtocols(*this, LHS->getInterface(), Lptr, Rptr,
7048                                  Protocols);
7049       if (!Protocols.empty())
7050         anyChanges = true;
7051 
7052       // If anything in the LHS will have changed, build a new result type.
7053       if (anyChanges) {
7054         QualType Result = getObjCInterfaceType(LHS->getInterface());
7055         Result = getObjCObjectType(Result, LHSTypeArgs, Protocols,
7056                                    LHS->isKindOfType());
7057         return getObjCObjectPointerType(Result);
7058       }
7059 
7060       return getObjCObjectPointerType(QualType(LHS, 0));
7061     }
7062 
7063     // Find the superclass.
7064     QualType LHSSuperType = LHS->getSuperClassType();
7065     if (LHSSuperType.isNull())
7066       break;
7067 
7068     LHS = LHSSuperType->castAs<ObjCObjectType>();
7069   }
7070 
7071   // We didn't find anything by following the LHS to its root; now check
7072   // the RHS against the cached set of ancestors.
7073   while (true) {
7074     auto KnownLHS = LHSAncestors.find(RHS->getInterface()->getCanonicalDecl());
7075     if (KnownLHS != LHSAncestors.end()) {
7076       LHS = KnownLHS->second;
7077 
7078       // Get the type arguments.
7079       ArrayRef<QualType> RHSTypeArgs = RHS->getTypeArgsAsWritten();
7080       bool anyChanges = false;
7081       if (LHS->isSpecialized() && RHS->isSpecialized()) {
7082         // Both have type arguments, compare them.
7083         if (!sameObjCTypeArgs(*this, LHS->getInterface(),
7084                               LHS->getTypeArgs(), RHS->getTypeArgs(),
7085                               /*stripKindOf=*/true))
7086           return QualType();
7087       } else if (LHS->isSpecialized() != RHS->isSpecialized()) {
7088         // If only one has type arguments, the result will not have type
7089         // arguments.
7090         RHSTypeArgs = { };
7091         anyChanges = true;
7092       }
7093 
7094       // Compute the intersection of protocols.
7095       SmallVector<ObjCProtocolDecl *, 8> Protocols;
7096       getIntersectionOfProtocols(*this, RHS->getInterface(), Lptr, Rptr,
7097                                  Protocols);
7098       if (!Protocols.empty())
7099         anyChanges = true;
7100 
7101       if (anyChanges) {
7102         QualType Result = getObjCInterfaceType(RHS->getInterface());
7103         Result = getObjCObjectType(Result, RHSTypeArgs, Protocols,
7104                                    RHS->isKindOfType());
7105         return getObjCObjectPointerType(Result);
7106       }
7107 
7108       return getObjCObjectPointerType(QualType(RHS, 0));
7109     }
7110 
7111     // Find the superclass of the RHS.
7112     QualType RHSSuperType = RHS->getSuperClassType();
7113     if (RHSSuperType.isNull())
7114       break;
7115 
7116     RHS = RHSSuperType->castAs<ObjCObjectType>();
7117   }
7118 
7119   return QualType();
7120 }
7121 
canAssignObjCInterfaces(const ObjCObjectType * LHS,const ObjCObjectType * RHS)7122 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS,
7123                                          const ObjCObjectType *RHS) {
7124   assert(LHS->getInterface() && "LHS is not an interface type");
7125   assert(RHS->getInterface() && "RHS is not an interface type");
7126 
7127   // Verify that the base decls are compatible: the RHS must be a subclass of
7128   // the LHS.
7129   ObjCInterfaceDecl *LHSInterface = LHS->getInterface();
7130   bool IsSuperClass = LHSInterface->isSuperClassOf(RHS->getInterface());
7131   if (!IsSuperClass)
7132     return false;
7133 
7134   // If the LHS has protocol qualifiers, determine whether all of them are
7135   // satisfied by the RHS (i.e., the RHS has a superset of the protocols in the
7136   // LHS).
7137   if (LHS->getNumProtocols() > 0) {
7138     // OK if conversion of LHS to SuperClass results in narrowing of types
7139     // ; i.e., SuperClass may implement at least one of the protocols
7140     // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok.
7141     // But not SuperObj<P1,P2,P3> = lhs<P1,P2>.
7142     llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols;
7143     CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols);
7144     // Also, if RHS has explicit quelifiers, include them for comparing with LHS's
7145     // qualifiers.
7146     for (auto *RHSPI : RHS->quals())
7147       CollectInheritedProtocols(RHSPI, SuperClassInheritedProtocols);
7148     // If there is no protocols associated with RHS, it is not a match.
7149     if (SuperClassInheritedProtocols.empty())
7150       return false;
7151 
7152     for (const auto *LHSProto : LHS->quals()) {
7153       bool SuperImplementsProtocol = false;
7154       for (auto *SuperClassProto : SuperClassInheritedProtocols)
7155         if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) {
7156           SuperImplementsProtocol = true;
7157           break;
7158         }
7159       if (!SuperImplementsProtocol)
7160         return false;
7161     }
7162   }
7163 
7164   // If the LHS is specialized, we may need to check type arguments.
7165   if (LHS->isSpecialized()) {
7166     // Follow the superclass chain until we've matched the LHS class in the
7167     // hierarchy. This substitutes type arguments through.
7168     const ObjCObjectType *RHSSuper = RHS;
7169     while (!declaresSameEntity(RHSSuper->getInterface(), LHSInterface))
7170       RHSSuper = RHSSuper->getSuperClassType()->castAs<ObjCObjectType>();
7171 
7172     // If the RHS is specializd, compare type arguments.
7173     if (RHSSuper->isSpecialized() &&
7174         !sameObjCTypeArgs(*this, LHS->getInterface(),
7175                           LHS->getTypeArgs(), RHSSuper->getTypeArgs(),
7176                           /*stripKindOf=*/true)) {
7177       return false;
7178     }
7179   }
7180 
7181   return true;
7182 }
7183 
areComparableObjCPointerTypes(QualType LHS,QualType RHS)7184 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) {
7185   // get the "pointed to" types
7186   const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>();
7187   const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>();
7188 
7189   if (!LHSOPT || !RHSOPT)
7190     return false;
7191 
7192   return canAssignObjCInterfaces(LHSOPT, RHSOPT) ||
7193          canAssignObjCInterfaces(RHSOPT, LHSOPT);
7194 }
7195 
canBindObjCObjectType(QualType To,QualType From)7196 bool ASTContext::canBindObjCObjectType(QualType To, QualType From) {
7197   return canAssignObjCInterfaces(
7198                 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(),
7199                 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>());
7200 }
7201 
7202 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible,
7203 /// both shall have the identically qualified version of a compatible type.
7204 /// C99 6.2.7p1: Two types have compatible types if their types are the
7205 /// same. See 6.7.[2,3,5] for additional rules.
typesAreCompatible(QualType LHS,QualType RHS,bool CompareUnqualified)7206 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS,
7207                                     bool CompareUnqualified) {
7208   if (getLangOpts().CPlusPlus)
7209     return hasSameType(LHS, RHS);
7210 
7211   return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull();
7212 }
7213 
propertyTypesAreCompatible(QualType LHS,QualType RHS)7214 bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) {
7215   return typesAreCompatible(LHS, RHS);
7216 }
7217 
typesAreBlockPointerCompatible(QualType LHS,QualType RHS)7218 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) {
7219   return !mergeTypes(LHS, RHS, true).isNull();
7220 }
7221 
7222 /// mergeTransparentUnionType - if T is a transparent union type and a member
7223 /// of T is compatible with SubType, return the merged type, else return
7224 /// QualType()
mergeTransparentUnionType(QualType T,QualType SubType,bool OfBlockPointer,bool Unqualified)7225 QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType,
7226                                                bool OfBlockPointer,
7227                                                bool Unqualified) {
7228   if (const RecordType *UT = T->getAsUnionType()) {
7229     RecordDecl *UD = UT->getDecl();
7230     if (UD->hasAttr<TransparentUnionAttr>()) {
7231       for (const auto *I : UD->fields()) {
7232         QualType ET = I->getType().getUnqualifiedType();
7233         QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified);
7234         if (!MT.isNull())
7235           return MT;
7236       }
7237     }
7238   }
7239 
7240   return QualType();
7241 }
7242 
7243 /// mergeFunctionParameterTypes - merge two types which appear as function
7244 /// parameter types
mergeFunctionParameterTypes(QualType lhs,QualType rhs,bool OfBlockPointer,bool Unqualified)7245 QualType ASTContext::mergeFunctionParameterTypes(QualType lhs, QualType rhs,
7246                                                  bool OfBlockPointer,
7247                                                  bool Unqualified) {
7248   // GNU extension: two types are compatible if they appear as a function
7249   // argument, one of the types is a transparent union type and the other
7250   // type is compatible with a union member
7251   QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer,
7252                                               Unqualified);
7253   if (!lmerge.isNull())
7254     return lmerge;
7255 
7256   QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer,
7257                                               Unqualified);
7258   if (!rmerge.isNull())
7259     return rmerge;
7260 
7261   return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified);
7262 }
7263 
mergeFunctionTypes(QualType lhs,QualType rhs,bool OfBlockPointer,bool Unqualified)7264 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs,
7265                                         bool OfBlockPointer,
7266                                         bool Unqualified) {
7267   const FunctionType *lbase = lhs->getAs<FunctionType>();
7268   const FunctionType *rbase = rhs->getAs<FunctionType>();
7269   const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase);
7270   const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase);
7271   bool allLTypes = true;
7272   bool allRTypes = true;
7273 
7274   // Check return type
7275   QualType retType;
7276   if (OfBlockPointer) {
7277     QualType RHS = rbase->getReturnType();
7278     QualType LHS = lbase->getReturnType();
7279     bool UnqualifiedResult = Unqualified;
7280     if (!UnqualifiedResult)
7281       UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers());
7282     retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true);
7283   }
7284   else
7285     retType = mergeTypes(lbase->getReturnType(), rbase->getReturnType(), false,
7286                          Unqualified);
7287   if (retType.isNull()) return QualType();
7288 
7289   if (Unqualified)
7290     retType = retType.getUnqualifiedType();
7291 
7292   CanQualType LRetType = getCanonicalType(lbase->getReturnType());
7293   CanQualType RRetType = getCanonicalType(rbase->getReturnType());
7294   if (Unqualified) {
7295     LRetType = LRetType.getUnqualifiedType();
7296     RRetType = RRetType.getUnqualifiedType();
7297   }
7298 
7299   if (getCanonicalType(retType) != LRetType)
7300     allLTypes = false;
7301   if (getCanonicalType(retType) != RRetType)
7302     allRTypes = false;
7303 
7304   // FIXME: double check this
7305   // FIXME: should we error if lbase->getRegParmAttr() != 0 &&
7306   //                           rbase->getRegParmAttr() != 0 &&
7307   //                           lbase->getRegParmAttr() != rbase->getRegParmAttr()?
7308   FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo();
7309   FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo();
7310 
7311   // Compatible functions must have compatible calling conventions
7312   if (lbaseInfo.getCC() != rbaseInfo.getCC())
7313     return QualType();
7314 
7315   // Regparm is part of the calling convention.
7316   if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm())
7317     return QualType();
7318   if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm())
7319     return QualType();
7320 
7321   if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult())
7322     return QualType();
7323 
7324   // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'.
7325   bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn();
7326 
7327   if (lbaseInfo.getNoReturn() != NoReturn)
7328     allLTypes = false;
7329   if (rbaseInfo.getNoReturn() != NoReturn)
7330     allRTypes = false;
7331 
7332   FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn);
7333 
7334   if (lproto && rproto) { // two C99 style function prototypes
7335     assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() &&
7336            "C++ shouldn't be here");
7337     // Compatible functions must have the same number of parameters
7338     if (lproto->getNumParams() != rproto->getNumParams())
7339       return QualType();
7340 
7341     // Variadic and non-variadic functions aren't compatible
7342     if (lproto->isVariadic() != rproto->isVariadic())
7343       return QualType();
7344 
7345     if (lproto->getTypeQuals() != rproto->getTypeQuals())
7346       return QualType();
7347 
7348     if (LangOpts.ObjCAutoRefCount &&
7349         !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto))
7350       return QualType();
7351 
7352     // Check parameter type compatibility
7353     SmallVector<QualType, 10> types;
7354     for (unsigned i = 0, n = lproto->getNumParams(); i < n; i++) {
7355       QualType lParamType = lproto->getParamType(i).getUnqualifiedType();
7356       QualType rParamType = rproto->getParamType(i).getUnqualifiedType();
7357       QualType paramType = mergeFunctionParameterTypes(
7358           lParamType, rParamType, OfBlockPointer, Unqualified);
7359       if (paramType.isNull())
7360         return QualType();
7361 
7362       if (Unqualified)
7363         paramType = paramType.getUnqualifiedType();
7364 
7365       types.push_back(paramType);
7366       if (Unqualified) {
7367         lParamType = lParamType.getUnqualifiedType();
7368         rParamType = rParamType.getUnqualifiedType();
7369       }
7370 
7371       if (getCanonicalType(paramType) != getCanonicalType(lParamType))
7372         allLTypes = false;
7373       if (getCanonicalType(paramType) != getCanonicalType(rParamType))
7374         allRTypes = false;
7375     }
7376 
7377     if (allLTypes) return lhs;
7378     if (allRTypes) return rhs;
7379 
7380     FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo();
7381     EPI.ExtInfo = einfo;
7382     return getFunctionType(retType, types, EPI);
7383   }
7384 
7385   if (lproto) allRTypes = false;
7386   if (rproto) allLTypes = false;
7387 
7388   const FunctionProtoType *proto = lproto ? lproto : rproto;
7389   if (proto) {
7390     assert(!proto->hasExceptionSpec() && "C++ shouldn't be here");
7391     if (proto->isVariadic()) return QualType();
7392     // Check that the types are compatible with the types that
7393     // would result from default argument promotions (C99 6.7.5.3p15).
7394     // The only types actually affected are promotable integer
7395     // types and floats, which would be passed as a different
7396     // type depending on whether the prototype is visible.
7397     for (unsigned i = 0, n = proto->getNumParams(); i < n; ++i) {
7398       QualType paramTy = proto->getParamType(i);
7399 
7400       // Look at the converted type of enum types, since that is the type used
7401       // to pass enum values.
7402       if (const EnumType *Enum = paramTy->getAs<EnumType>()) {
7403         paramTy = Enum->getDecl()->getIntegerType();
7404         if (paramTy.isNull())
7405           return QualType();
7406       }
7407 
7408       if (paramTy->isPromotableIntegerType() ||
7409           getCanonicalType(paramTy).getUnqualifiedType() == FloatTy)
7410         return QualType();
7411     }
7412 
7413     if (allLTypes) return lhs;
7414     if (allRTypes) return rhs;
7415 
7416     FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo();
7417     EPI.ExtInfo = einfo;
7418     return getFunctionType(retType, proto->getParamTypes(), EPI);
7419   }
7420 
7421   if (allLTypes) return lhs;
7422   if (allRTypes) return rhs;
7423   return getFunctionNoProtoType(retType, einfo);
7424 }
7425 
7426 /// Given that we have an enum type and a non-enum type, try to merge them.
mergeEnumWithInteger(ASTContext & Context,const EnumType * ET,QualType other,bool isBlockReturnType)7427 static QualType mergeEnumWithInteger(ASTContext &Context, const EnumType *ET,
7428                                      QualType other, bool isBlockReturnType) {
7429   // C99 6.7.2.2p4: Each enumerated type shall be compatible with char,
7430   // a signed integer type, or an unsigned integer type.
7431   // Compatibility is based on the underlying type, not the promotion
7432   // type.
7433   QualType underlyingType = ET->getDecl()->getIntegerType();
7434   if (underlyingType.isNull()) return QualType();
7435   if (Context.hasSameType(underlyingType, other))
7436     return other;
7437 
7438   // In block return types, we're more permissive and accept any
7439   // integral type of the same size.
7440   if (isBlockReturnType && other->isIntegerType() &&
7441       Context.getTypeSize(underlyingType) == Context.getTypeSize(other))
7442     return other;
7443 
7444   return QualType();
7445 }
7446 
mergeTypes(QualType LHS,QualType RHS,bool OfBlockPointer,bool Unqualified,bool BlockReturnType)7447 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
7448                                 bool OfBlockPointer,
7449                                 bool Unqualified, bool BlockReturnType) {
7450   // C++ [expr]: If an expression initially has the type "reference to T", the
7451   // type is adjusted to "T" prior to any further analysis, the expression
7452   // designates the object or function denoted by the reference, and the
7453   // expression is an lvalue unless the reference is an rvalue reference and
7454   // the expression is a function call (possibly inside parentheses).
7455   assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?");
7456   assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?");
7457 
7458   if (Unqualified) {
7459     LHS = LHS.getUnqualifiedType();
7460     RHS = RHS.getUnqualifiedType();
7461   }
7462 
7463   QualType LHSCan = getCanonicalType(LHS),
7464            RHSCan = getCanonicalType(RHS);
7465 
7466   // If two types are identical, they are compatible.
7467   if (LHSCan == RHSCan)
7468     return LHS;
7469 
7470   // If the qualifiers are different, the types aren't compatible... mostly.
7471   Qualifiers LQuals = LHSCan.getLocalQualifiers();
7472   Qualifiers RQuals = RHSCan.getLocalQualifiers();
7473   if (LQuals != RQuals) {
7474     // If any of these qualifiers are different, we have a type
7475     // mismatch.
7476     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7477         LQuals.getAddressSpace() != RQuals.getAddressSpace() ||
7478         LQuals.getObjCLifetime() != RQuals.getObjCLifetime())
7479       return QualType();
7480 
7481     // Exactly one GC qualifier difference is allowed: __strong is
7482     // okay if the other type has no GC qualifier but is an Objective
7483     // C object pointer (i.e. implicitly strong by default).  We fix
7484     // this by pretending that the unqualified type was actually
7485     // qualified __strong.
7486     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7487     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7488     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7489 
7490     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7491       return QualType();
7492 
7493     if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) {
7494       return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong));
7495     }
7496     if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) {
7497       return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS);
7498     }
7499     return QualType();
7500   }
7501 
7502   // Okay, qualifiers are equal.
7503 
7504   Type::TypeClass LHSClass = LHSCan->getTypeClass();
7505   Type::TypeClass RHSClass = RHSCan->getTypeClass();
7506 
7507   // We want to consider the two function types to be the same for these
7508   // comparisons, just force one to the other.
7509   if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto;
7510   if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto;
7511 
7512   // Same as above for arrays
7513   if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray)
7514     LHSClass = Type::ConstantArray;
7515   if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray)
7516     RHSClass = Type::ConstantArray;
7517 
7518   // ObjCInterfaces are just specialized ObjCObjects.
7519   if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject;
7520   if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject;
7521 
7522   // Canonicalize ExtVector -> Vector.
7523   if (LHSClass == Type::ExtVector) LHSClass = Type::Vector;
7524   if (RHSClass == Type::ExtVector) RHSClass = Type::Vector;
7525 
7526   // If the canonical type classes don't match.
7527   if (LHSClass != RHSClass) {
7528     // Note that we only have special rules for turning block enum
7529     // returns into block int returns, not vice-versa.
7530     if (const EnumType* ETy = LHS->getAs<EnumType>()) {
7531       return mergeEnumWithInteger(*this, ETy, RHS, false);
7532     }
7533     if (const EnumType* ETy = RHS->getAs<EnumType>()) {
7534       return mergeEnumWithInteger(*this, ETy, LHS, BlockReturnType);
7535     }
7536     // allow block pointer type to match an 'id' type.
7537     if (OfBlockPointer && !BlockReturnType) {
7538        if (LHS->isObjCIdType() && RHS->isBlockPointerType())
7539          return LHS;
7540       if (RHS->isObjCIdType() && LHS->isBlockPointerType())
7541         return RHS;
7542     }
7543 
7544     return QualType();
7545   }
7546 
7547   // The canonical type classes match.
7548   switch (LHSClass) {
7549 #define TYPE(Class, Base)
7550 #define ABSTRACT_TYPE(Class, Base)
7551 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
7552 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
7553 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
7554 #include "clang/AST/TypeNodes.def"
7555     llvm_unreachable("Non-canonical and dependent types shouldn't get here");
7556 
7557   case Type::Auto:
7558   case Type::LValueReference:
7559   case Type::RValueReference:
7560   case Type::MemberPointer:
7561     llvm_unreachable("C++ should never be in mergeTypes");
7562 
7563   case Type::ObjCInterface:
7564   case Type::IncompleteArray:
7565   case Type::VariableArray:
7566   case Type::FunctionProto:
7567   case Type::ExtVector:
7568     llvm_unreachable("Types are eliminated above");
7569 
7570   case Type::Pointer:
7571   {
7572     // Merge two pointer types, while trying to preserve typedef info
7573     QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType();
7574     QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType();
7575     if (Unqualified) {
7576       LHSPointee = LHSPointee.getUnqualifiedType();
7577       RHSPointee = RHSPointee.getUnqualifiedType();
7578     }
7579     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false,
7580                                      Unqualified);
7581     if (ResultType.isNull()) return QualType();
7582     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7583       return LHS;
7584     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7585       return RHS;
7586     return getPointerType(ResultType);
7587   }
7588   case Type::BlockPointer:
7589   {
7590     // Merge two block pointer types, while trying to preserve typedef info
7591     QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType();
7592     QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType();
7593     if (Unqualified) {
7594       LHSPointee = LHSPointee.getUnqualifiedType();
7595       RHSPointee = RHSPointee.getUnqualifiedType();
7596     }
7597     QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer,
7598                                      Unqualified);
7599     if (ResultType.isNull()) return QualType();
7600     if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType))
7601       return LHS;
7602     if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType))
7603       return RHS;
7604     return getBlockPointerType(ResultType);
7605   }
7606   case Type::Atomic:
7607   {
7608     // Merge two pointer types, while trying to preserve typedef info
7609     QualType LHSValue = LHS->getAs<AtomicType>()->getValueType();
7610     QualType RHSValue = RHS->getAs<AtomicType>()->getValueType();
7611     if (Unqualified) {
7612       LHSValue = LHSValue.getUnqualifiedType();
7613       RHSValue = RHSValue.getUnqualifiedType();
7614     }
7615     QualType ResultType = mergeTypes(LHSValue, RHSValue, false,
7616                                      Unqualified);
7617     if (ResultType.isNull()) return QualType();
7618     if (getCanonicalType(LHSValue) == getCanonicalType(ResultType))
7619       return LHS;
7620     if (getCanonicalType(RHSValue) == getCanonicalType(ResultType))
7621       return RHS;
7622     return getAtomicType(ResultType);
7623   }
7624   case Type::ConstantArray:
7625   {
7626     const ConstantArrayType* LCAT = getAsConstantArrayType(LHS);
7627     const ConstantArrayType* RCAT = getAsConstantArrayType(RHS);
7628     if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize())
7629       return QualType();
7630 
7631     QualType LHSElem = getAsArrayType(LHS)->getElementType();
7632     QualType RHSElem = getAsArrayType(RHS)->getElementType();
7633     if (Unqualified) {
7634       LHSElem = LHSElem.getUnqualifiedType();
7635       RHSElem = RHSElem.getUnqualifiedType();
7636     }
7637 
7638     QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified);
7639     if (ResultType.isNull()) return QualType();
7640     if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7641       return LHS;
7642     if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7643       return RHS;
7644     if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(),
7645                                           ArrayType::ArraySizeModifier(), 0);
7646     if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(),
7647                                           ArrayType::ArraySizeModifier(), 0);
7648     const VariableArrayType* LVAT = getAsVariableArrayType(LHS);
7649     const VariableArrayType* RVAT = getAsVariableArrayType(RHS);
7650     if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType))
7651       return LHS;
7652     if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType))
7653       return RHS;
7654     if (LVAT) {
7655       // FIXME: This isn't correct! But tricky to implement because
7656       // the array's size has to be the size of LHS, but the type
7657       // has to be different.
7658       return LHS;
7659     }
7660     if (RVAT) {
7661       // FIXME: This isn't correct! But tricky to implement because
7662       // the array's size has to be the size of RHS, but the type
7663       // has to be different.
7664       return RHS;
7665     }
7666     if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS;
7667     if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS;
7668     return getIncompleteArrayType(ResultType,
7669                                   ArrayType::ArraySizeModifier(), 0);
7670   }
7671   case Type::FunctionNoProto:
7672     return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified);
7673   case Type::Record:
7674   case Type::Enum:
7675     return QualType();
7676   case Type::Builtin:
7677     // Only exactly equal builtin types are compatible, which is tested above.
7678     return QualType();
7679   case Type::Complex:
7680     // Distinct complex types are incompatible.
7681     return QualType();
7682   case Type::Vector:
7683     // FIXME: The merged type should be an ExtVector!
7684     if (areCompatVectorTypes(LHSCan->getAs<VectorType>(),
7685                              RHSCan->getAs<VectorType>()))
7686       return LHS;
7687     return QualType();
7688   case Type::ObjCObject: {
7689     // Check if the types are assignment compatible.
7690     // FIXME: This should be type compatibility, e.g. whether
7691     // "LHS x; RHS x;" at global scope is legal.
7692     const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>();
7693     const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>();
7694     if (canAssignObjCInterfaces(LHSIface, RHSIface))
7695       return LHS;
7696 
7697     return QualType();
7698   }
7699   case Type::ObjCObjectPointer: {
7700     if (OfBlockPointer) {
7701       if (canAssignObjCInterfacesInBlockPointer(
7702                                           LHS->getAs<ObjCObjectPointerType>(),
7703                                           RHS->getAs<ObjCObjectPointerType>(),
7704                                           BlockReturnType))
7705         return LHS;
7706       return QualType();
7707     }
7708     if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(),
7709                                 RHS->getAs<ObjCObjectPointerType>()))
7710       return LHS;
7711 
7712     return QualType();
7713   }
7714   }
7715 
7716   llvm_unreachable("Invalid Type::Class!");
7717 }
7718 
FunctionTypesMatchOnNSConsumedAttrs(const FunctionProtoType * FromFunctionType,const FunctionProtoType * ToFunctionType)7719 bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs(
7720                    const FunctionProtoType *FromFunctionType,
7721                    const FunctionProtoType *ToFunctionType) {
7722   if (FromFunctionType->hasAnyConsumedParams() !=
7723       ToFunctionType->hasAnyConsumedParams())
7724     return false;
7725   FunctionProtoType::ExtProtoInfo FromEPI =
7726     FromFunctionType->getExtProtoInfo();
7727   FunctionProtoType::ExtProtoInfo ToEPI =
7728     ToFunctionType->getExtProtoInfo();
7729   if (FromEPI.ConsumedParameters && ToEPI.ConsumedParameters)
7730     for (unsigned i = 0, n = FromFunctionType->getNumParams(); i != n; ++i) {
7731       if (FromEPI.ConsumedParameters[i] != ToEPI.ConsumedParameters[i])
7732         return false;
7733     }
7734   return true;
7735 }
7736 
7737 /// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and
7738 /// 'RHS' attributes and returns the merged version; including for function
7739 /// return types.
mergeObjCGCQualifiers(QualType LHS,QualType RHS)7740 QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) {
7741   QualType LHSCan = getCanonicalType(LHS),
7742   RHSCan = getCanonicalType(RHS);
7743   // If two types are identical, they are compatible.
7744   if (LHSCan == RHSCan)
7745     return LHS;
7746   if (RHSCan->isFunctionType()) {
7747     if (!LHSCan->isFunctionType())
7748       return QualType();
7749     QualType OldReturnType =
7750         cast<FunctionType>(RHSCan.getTypePtr())->getReturnType();
7751     QualType NewReturnType =
7752         cast<FunctionType>(LHSCan.getTypePtr())->getReturnType();
7753     QualType ResReturnType =
7754       mergeObjCGCQualifiers(NewReturnType, OldReturnType);
7755     if (ResReturnType.isNull())
7756       return QualType();
7757     if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) {
7758       // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo();
7759       // In either case, use OldReturnType to build the new function type.
7760       const FunctionType *F = LHS->getAs<FunctionType>();
7761       if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) {
7762         FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7763         EPI.ExtInfo = getFunctionExtInfo(LHS);
7764         QualType ResultType =
7765             getFunctionType(OldReturnType, FPT->getParamTypes(), EPI);
7766         return ResultType;
7767       }
7768     }
7769     return QualType();
7770   }
7771 
7772   // If the qualifiers are different, the types can still be merged.
7773   Qualifiers LQuals = LHSCan.getLocalQualifiers();
7774   Qualifiers RQuals = RHSCan.getLocalQualifiers();
7775   if (LQuals != RQuals) {
7776     // If any of these qualifiers are different, we have a type mismatch.
7777     if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() ||
7778         LQuals.getAddressSpace() != RQuals.getAddressSpace())
7779       return QualType();
7780 
7781     // Exactly one GC qualifier difference is allowed: __strong is
7782     // okay if the other type has no GC qualifier but is an Objective
7783     // C object pointer (i.e. implicitly strong by default).  We fix
7784     // this by pretending that the unqualified type was actually
7785     // qualified __strong.
7786     Qualifiers::GC GC_L = LQuals.getObjCGCAttr();
7787     Qualifiers::GC GC_R = RQuals.getObjCGCAttr();
7788     assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements");
7789 
7790     if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak)
7791       return QualType();
7792 
7793     if (GC_L == Qualifiers::Strong)
7794       return LHS;
7795     if (GC_R == Qualifiers::Strong)
7796       return RHS;
7797     return QualType();
7798   }
7799 
7800   if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) {
7801     QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7802     QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType();
7803     QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT);
7804     if (ResQT == LHSBaseQT)
7805       return LHS;
7806     if (ResQT == RHSBaseQT)
7807       return RHS;
7808   }
7809   return QualType();
7810 }
7811 
7812 //===----------------------------------------------------------------------===//
7813 //                         Integer Predicates
7814 //===----------------------------------------------------------------------===//
7815 
getIntWidth(QualType T) const7816 unsigned ASTContext::getIntWidth(QualType T) const {
7817   if (const EnumType *ET = T->getAs<EnumType>())
7818     T = ET->getDecl()->getIntegerType();
7819   if (T->isBooleanType())
7820     return 1;
7821   // For builtin types, just use the standard type sizing method
7822   return (unsigned)getTypeSize(T);
7823 }
7824 
getCorrespondingUnsignedType(QualType T) const7825 QualType ASTContext::getCorrespondingUnsignedType(QualType T) const {
7826   assert(T->hasSignedIntegerRepresentation() && "Unexpected type");
7827 
7828   // Turn <4 x signed int> -> <4 x unsigned int>
7829   if (const VectorType *VTy = T->getAs<VectorType>())
7830     return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()),
7831                          VTy->getNumElements(), VTy->getVectorKind());
7832 
7833   // For enums, we return the unsigned version of the base type.
7834   if (const EnumType *ETy = T->getAs<EnumType>())
7835     T = ETy->getDecl()->getIntegerType();
7836 
7837   const BuiltinType *BTy = T->getAs<BuiltinType>();
7838   assert(BTy && "Unexpected signed integer type");
7839   switch (BTy->getKind()) {
7840   case BuiltinType::Char_S:
7841   case BuiltinType::SChar:
7842     return UnsignedCharTy;
7843   case BuiltinType::Short:
7844     return UnsignedShortTy;
7845   case BuiltinType::Int:
7846     return UnsignedIntTy;
7847   case BuiltinType::Long:
7848     return UnsignedLongTy;
7849   case BuiltinType::LongLong:
7850     return UnsignedLongLongTy;
7851   case BuiltinType::Int128:
7852     return UnsignedInt128Ty;
7853   default:
7854     llvm_unreachable("Unexpected signed integer type");
7855   }
7856 }
7857 
~ASTMutationListener()7858 ASTMutationListener::~ASTMutationListener() { }
7859 
DeducedReturnType(const FunctionDecl * FD,QualType ReturnType)7860 void ASTMutationListener::DeducedReturnType(const FunctionDecl *FD,
7861                                             QualType ReturnType) {}
7862 
7863 //===----------------------------------------------------------------------===//
7864 //                          Builtin Type Computation
7865 //===----------------------------------------------------------------------===//
7866 
7867 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the
7868 /// pointer over the consumed characters.  This returns the resultant type.  If
7869 /// AllowTypeModifiers is false then modifier like * are not parsed, just basic
7870 /// types.  This allows "v2i*" to be parsed as a pointer to a v2i instead of
7871 /// a vector of "i*".
7872 ///
7873 /// RequiresICE is filled in on return to indicate whether the value is required
7874 /// to be an Integer Constant Expression.
DecodeTypeFromStr(const char * & Str,const ASTContext & Context,ASTContext::GetBuiltinTypeError & Error,bool & RequiresICE,bool AllowTypeModifiers)7875 static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context,
7876                                   ASTContext::GetBuiltinTypeError &Error,
7877                                   bool &RequiresICE,
7878                                   bool AllowTypeModifiers) {
7879   // Modifiers.
7880   int HowLong = 0;
7881   bool Signed = false, Unsigned = false;
7882   RequiresICE = false;
7883 
7884   // Read the prefixed modifiers first.
7885   bool Done = false;
7886   while (!Done) {
7887     switch (*Str++) {
7888     default: Done = true; --Str; break;
7889     case 'I':
7890       RequiresICE = true;
7891       break;
7892     case 'S':
7893       assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!");
7894       assert(!Signed && "Can't use 'S' modifier multiple times!");
7895       Signed = true;
7896       break;
7897     case 'U':
7898       assert(!Signed && "Can't use both 'S' and 'U' modifiers!");
7899       assert(!Unsigned && "Can't use 'U' modifier multiple times!");
7900       Unsigned = true;
7901       break;
7902     case 'L':
7903       assert(HowLong <= 2 && "Can't have LLLL modifier");
7904       ++HowLong;
7905       break;
7906     case 'W':
7907       // This modifier represents int64 type.
7908       assert(HowLong == 0 && "Can't use both 'L' and 'W' modifiers!");
7909       switch (Context.getTargetInfo().getInt64Type()) {
7910       default:
7911         llvm_unreachable("Unexpected integer type");
7912       case TargetInfo::SignedLong:
7913         HowLong = 1;
7914         break;
7915       case TargetInfo::SignedLongLong:
7916         HowLong = 2;
7917         break;
7918       }
7919     }
7920   }
7921 
7922   QualType Type;
7923 
7924   // Read the base type.
7925   switch (*Str++) {
7926   default: llvm_unreachable("Unknown builtin type letter!");
7927   case 'v':
7928     assert(HowLong == 0 && !Signed && !Unsigned &&
7929            "Bad modifiers used with 'v'!");
7930     Type = Context.VoidTy;
7931     break;
7932   case 'h':
7933     assert(HowLong == 0 && !Signed && !Unsigned &&
7934            "Bad modifiers used with 'h'!");
7935     Type = Context.HalfTy;
7936     break;
7937   case 'f':
7938     assert(HowLong == 0 && !Signed && !Unsigned &&
7939            "Bad modifiers used with 'f'!");
7940     Type = Context.FloatTy;
7941     break;
7942   case 'd':
7943     assert(HowLong < 2 && !Signed && !Unsigned &&
7944            "Bad modifiers used with 'd'!");
7945     if (HowLong)
7946       Type = Context.LongDoubleTy;
7947     else
7948       Type = Context.DoubleTy;
7949     break;
7950   case 's':
7951     assert(HowLong == 0 && "Bad modifiers used with 's'!");
7952     if (Unsigned)
7953       Type = Context.UnsignedShortTy;
7954     else
7955       Type = Context.ShortTy;
7956     break;
7957   case 'i':
7958     if (HowLong == 3)
7959       Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty;
7960     else if (HowLong == 2)
7961       Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy;
7962     else if (HowLong == 1)
7963       Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy;
7964     else
7965       Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy;
7966     break;
7967   case 'c':
7968     assert(HowLong == 0 && "Bad modifiers used with 'c'!");
7969     if (Signed)
7970       Type = Context.SignedCharTy;
7971     else if (Unsigned)
7972       Type = Context.UnsignedCharTy;
7973     else
7974       Type = Context.CharTy;
7975     break;
7976   case 'b': // boolean
7977     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!");
7978     Type = Context.BoolTy;
7979     break;
7980   case 'z':  // size_t.
7981     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!");
7982     Type = Context.getSizeType();
7983     break;
7984   case 'F':
7985     Type = Context.getCFConstantStringType();
7986     break;
7987   case 'G':
7988     Type = Context.getObjCIdType();
7989     break;
7990   case 'H':
7991     Type = Context.getObjCSelType();
7992     break;
7993   case 'M':
7994     Type = Context.getObjCSuperType();
7995     break;
7996   case 'a':
7997     Type = Context.getBuiltinVaListType();
7998     assert(!Type.isNull() && "builtin va list type not initialized!");
7999     break;
8000   case 'A':
8001     // This is a "reference" to a va_list; however, what exactly
8002     // this means depends on how va_list is defined. There are two
8003     // different kinds of va_list: ones passed by value, and ones
8004     // passed by reference.  An example of a by-value va_list is
8005     // x86, where va_list is a char*. An example of by-ref va_list
8006     // is x86-64, where va_list is a __va_list_tag[1]. For x86,
8007     // we want this argument to be a char*&; for x86-64, we want
8008     // it to be a __va_list_tag*.
8009     Type = Context.getBuiltinVaListType();
8010     assert(!Type.isNull() && "builtin va list type not initialized!");
8011     if (Type->isArrayType())
8012       Type = Context.getArrayDecayedType(Type);
8013     else
8014       Type = Context.getLValueReferenceType(Type);
8015     break;
8016   case 'V': {
8017     char *End;
8018     unsigned NumElements = strtoul(Str, &End, 10);
8019     assert(End != Str && "Missing vector size");
8020     Str = End;
8021 
8022     QualType ElementType = DecodeTypeFromStr(Str, Context, Error,
8023                                              RequiresICE, false);
8024     assert(!RequiresICE && "Can't require vector ICE");
8025 
8026     // TODO: No way to make AltiVec vectors in builtins yet.
8027     Type = Context.getVectorType(ElementType, NumElements,
8028                                  VectorType::GenericVector);
8029     break;
8030   }
8031   case 'E': {
8032     char *End;
8033 
8034     unsigned NumElements = strtoul(Str, &End, 10);
8035     assert(End != Str && "Missing vector size");
8036 
8037     Str = End;
8038 
8039     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8040                                              false);
8041     Type = Context.getExtVectorType(ElementType, NumElements);
8042     break;
8043   }
8044   case 'X': {
8045     QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE,
8046                                              false);
8047     assert(!RequiresICE && "Can't require complex ICE");
8048     Type = Context.getComplexType(ElementType);
8049     break;
8050   }
8051   case 'Y' : {
8052     Type = Context.getPointerDiffType();
8053     break;
8054   }
8055   case 'P':
8056     Type = Context.getFILEType();
8057     if (Type.isNull()) {
8058       Error = ASTContext::GE_Missing_stdio;
8059       return QualType();
8060     }
8061     break;
8062   case 'J':
8063     if (Signed)
8064       Type = Context.getsigjmp_bufType();
8065     else
8066       Type = Context.getjmp_bufType();
8067 
8068     if (Type.isNull()) {
8069       Error = ASTContext::GE_Missing_setjmp;
8070       return QualType();
8071     }
8072     break;
8073   case 'K':
8074     assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!");
8075     Type = Context.getucontext_tType();
8076 
8077     if (Type.isNull()) {
8078       Error = ASTContext::GE_Missing_ucontext;
8079       return QualType();
8080     }
8081     break;
8082   case 'p':
8083     Type = Context.getProcessIDType();
8084     break;
8085   }
8086 
8087   // If there are modifiers and if we're allowed to parse them, go for it.
8088   Done = !AllowTypeModifiers;
8089   while (!Done) {
8090     switch (char c = *Str++) {
8091     default: Done = true; --Str; break;
8092     case '*':
8093     case '&': {
8094       // Both pointers and references can have their pointee types
8095       // qualified with an address space.
8096       char *End;
8097       unsigned AddrSpace = strtoul(Str, &End, 10);
8098       if (End != Str && AddrSpace != 0) {
8099         Type = Context.getAddrSpaceQualType(Type, AddrSpace);
8100         Str = End;
8101       }
8102       if (c == '*')
8103         Type = Context.getPointerType(Type);
8104       else
8105         Type = Context.getLValueReferenceType(Type);
8106       break;
8107     }
8108     // FIXME: There's no way to have a built-in with an rvalue ref arg.
8109     case 'C':
8110       Type = Type.withConst();
8111       break;
8112     case 'D':
8113       Type = Context.getVolatileType(Type);
8114       break;
8115     case 'R':
8116       Type = Type.withRestrict();
8117       break;
8118     }
8119   }
8120 
8121   assert((!RequiresICE || Type->isIntegralOrEnumerationType()) &&
8122          "Integer constant 'I' type must be an integer");
8123 
8124   return Type;
8125 }
8126 
8127 /// GetBuiltinType - Return the type for the specified builtin.
GetBuiltinType(unsigned Id,GetBuiltinTypeError & Error,unsigned * IntegerConstantArgs) const8128 QualType ASTContext::GetBuiltinType(unsigned Id,
8129                                     GetBuiltinTypeError &Error,
8130                                     unsigned *IntegerConstantArgs) const {
8131   const char *TypeStr = BuiltinInfo.GetTypeString(Id);
8132 
8133   SmallVector<QualType, 8> ArgTypes;
8134 
8135   bool RequiresICE = false;
8136   Error = GE_None;
8137   QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error,
8138                                        RequiresICE, true);
8139   if (Error != GE_None)
8140     return QualType();
8141 
8142   assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE");
8143 
8144   while (TypeStr[0] && TypeStr[0] != '.') {
8145     QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true);
8146     if (Error != GE_None)
8147       return QualType();
8148 
8149     // If this argument is required to be an IntegerConstantExpression and the
8150     // caller cares, fill in the bitmask we return.
8151     if (RequiresICE && IntegerConstantArgs)
8152       *IntegerConstantArgs |= 1 << ArgTypes.size();
8153 
8154     // Do array -> pointer decay.  The builtin should use the decayed type.
8155     if (Ty->isArrayType())
8156       Ty = getArrayDecayedType(Ty);
8157 
8158     ArgTypes.push_back(Ty);
8159   }
8160 
8161   if (Id == Builtin::BI__GetExceptionInfo)
8162     return QualType();
8163 
8164   assert((TypeStr[0] != '.' || TypeStr[1] == 0) &&
8165          "'.' should only occur at end of builtin type list!");
8166 
8167   FunctionType::ExtInfo EI(CC_C);
8168   if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true);
8169 
8170   bool Variadic = (TypeStr[0] == '.');
8171 
8172   // We really shouldn't be making a no-proto type here, especially in C++.
8173   if (ArgTypes.empty() && Variadic)
8174     return getFunctionNoProtoType(ResType, EI);
8175 
8176   FunctionProtoType::ExtProtoInfo EPI;
8177   EPI.ExtInfo = EI;
8178   EPI.Variadic = Variadic;
8179 
8180   return getFunctionType(ResType, ArgTypes, EPI);
8181 }
8182 
basicGVALinkageForFunction(const ASTContext & Context,const FunctionDecl * FD)8183 static GVALinkage basicGVALinkageForFunction(const ASTContext &Context,
8184                                              const FunctionDecl *FD) {
8185   if (!FD->isExternallyVisible())
8186     return GVA_Internal;
8187 
8188   GVALinkage External = GVA_StrongExternal;
8189   switch (FD->getTemplateSpecializationKind()) {
8190   case TSK_Undeclared:
8191   case TSK_ExplicitSpecialization:
8192     External = GVA_StrongExternal;
8193     break;
8194 
8195   case TSK_ExplicitInstantiationDefinition:
8196     return GVA_StrongODR;
8197 
8198   // C++11 [temp.explicit]p10:
8199   //   [ Note: The intent is that an inline function that is the subject of
8200   //   an explicit instantiation declaration will still be implicitly
8201   //   instantiated when used so that the body can be considered for
8202   //   inlining, but that no out-of-line copy of the inline function would be
8203   //   generated in the translation unit. -- end note ]
8204   case TSK_ExplicitInstantiationDeclaration:
8205     return GVA_AvailableExternally;
8206 
8207   case TSK_ImplicitInstantiation:
8208     External = GVA_DiscardableODR;
8209     break;
8210   }
8211 
8212   if (!FD->isInlined())
8213     return External;
8214 
8215   if ((!Context.getLangOpts().CPlusPlus && !Context.getLangOpts().MSVCCompat &&
8216        !FD->hasAttr<DLLExportAttr>()) ||
8217       FD->hasAttr<GNUInlineAttr>()) {
8218     // FIXME: This doesn't match gcc's behavior for dllexport inline functions.
8219 
8220     // GNU or C99 inline semantics. Determine whether this symbol should be
8221     // externally visible.
8222     if (FD->isInlineDefinitionExternallyVisible())
8223       return External;
8224 
8225     // C99 inline semantics, where the symbol is not externally visible.
8226     return GVA_AvailableExternally;
8227   }
8228 
8229   // Functions specified with extern and inline in -fms-compatibility mode
8230   // forcibly get emitted.  While the body of the function cannot be later
8231   // replaced, the function definition cannot be discarded.
8232   if (FD->isMSExternInline())
8233     return GVA_StrongODR;
8234 
8235   return GVA_DiscardableODR;
8236 }
8237 
adjustGVALinkageForDLLAttribute(GVALinkage L,const Decl * D)8238 static GVALinkage adjustGVALinkageForDLLAttribute(GVALinkage L, const Decl *D) {
8239   // See http://msdn.microsoft.com/en-us/library/xa0d9ste.aspx
8240   // dllexport/dllimport on inline functions.
8241   if (D->hasAttr<DLLImportAttr>()) {
8242     if (L == GVA_DiscardableODR || L == GVA_StrongODR)
8243       return GVA_AvailableExternally;
8244   } else if (D->hasAttr<DLLExportAttr>()) {
8245     if (L == GVA_DiscardableODR)
8246       return GVA_StrongODR;
8247   }
8248   return L;
8249 }
8250 
GetGVALinkageForFunction(const FunctionDecl * FD) const8251 GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) const {
8252   return adjustGVALinkageForDLLAttribute(basicGVALinkageForFunction(*this, FD),
8253                                          FD);
8254 }
8255 
basicGVALinkageForVariable(const ASTContext & Context,const VarDecl * VD)8256 static GVALinkage basicGVALinkageForVariable(const ASTContext &Context,
8257                                              const VarDecl *VD) {
8258   if (!VD->isExternallyVisible())
8259     return GVA_Internal;
8260 
8261   if (VD->isStaticLocal()) {
8262     GVALinkage StaticLocalLinkage = GVA_DiscardableODR;
8263     const DeclContext *LexicalContext = VD->getParentFunctionOrMethod();
8264     while (LexicalContext && !isa<FunctionDecl>(LexicalContext))
8265       LexicalContext = LexicalContext->getLexicalParent();
8266 
8267     // Let the static local variable inherit its linkage from the nearest
8268     // enclosing function.
8269     if (LexicalContext)
8270       StaticLocalLinkage =
8271           Context.GetGVALinkageForFunction(cast<FunctionDecl>(LexicalContext));
8272 
8273     // GVA_StrongODR function linkage is stronger than what we need,
8274     // downgrade to GVA_DiscardableODR.
8275     // This allows us to discard the variable if we never end up needing it.
8276     return StaticLocalLinkage == GVA_StrongODR ? GVA_DiscardableODR
8277                                                : StaticLocalLinkage;
8278   }
8279 
8280   // MSVC treats in-class initialized static data members as definitions.
8281   // By giving them non-strong linkage, out-of-line definitions won't
8282   // cause link errors.
8283   if (Context.isMSStaticDataMemberInlineDefinition(VD))
8284     return GVA_DiscardableODR;
8285 
8286   switch (VD->getTemplateSpecializationKind()) {
8287   case TSK_Undeclared:
8288   case TSK_ExplicitSpecialization:
8289     return GVA_StrongExternal;
8290 
8291   case TSK_ExplicitInstantiationDefinition:
8292     return GVA_StrongODR;
8293 
8294   case TSK_ExplicitInstantiationDeclaration:
8295     return GVA_AvailableExternally;
8296 
8297   case TSK_ImplicitInstantiation:
8298     return GVA_DiscardableODR;
8299   }
8300 
8301   llvm_unreachable("Invalid Linkage!");
8302 }
8303 
GetGVALinkageForVariable(const VarDecl * VD)8304 GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) {
8305   return adjustGVALinkageForDLLAttribute(basicGVALinkageForVariable(*this, VD),
8306                                          VD);
8307 }
8308 
DeclMustBeEmitted(const Decl * D)8309 bool ASTContext::DeclMustBeEmitted(const Decl *D) {
8310   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8311     if (!VD->isFileVarDecl())
8312       return false;
8313     // Global named register variables (GNU extension) are never emitted.
8314     if (VD->getStorageClass() == SC_Register)
8315       return false;
8316   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8317     // We never need to emit an uninstantiated function template.
8318     if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
8319       return false;
8320   } else if (isa<OMPThreadPrivateDecl>(D))
8321     return true;
8322   else
8323     return false;
8324 
8325   // If this is a member of a class template, we do not need to emit it.
8326   if (D->getDeclContext()->isDependentContext())
8327     return false;
8328 
8329   // Weak references don't produce any output by themselves.
8330   if (D->hasAttr<WeakRefAttr>())
8331     return false;
8332 
8333   // Aliases and used decls are required.
8334   if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>())
8335     return true;
8336 
8337   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8338     // Forward declarations aren't required.
8339     if (!FD->doesThisDeclarationHaveABody())
8340       return FD->doesDeclarationForceExternallyVisibleDefinition();
8341 
8342     // Constructors and destructors are required.
8343     if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>())
8344       return true;
8345 
8346     // The key function for a class is required.  This rule only comes
8347     // into play when inline functions can be key functions, though.
8348     if (getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
8349       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8350         const CXXRecordDecl *RD = MD->getParent();
8351         if (MD->isOutOfLine() && RD->isDynamicClass()) {
8352           const CXXMethodDecl *KeyFunc = getCurrentKeyFunction(RD);
8353           if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl())
8354             return true;
8355         }
8356       }
8357     }
8358 
8359     GVALinkage Linkage = GetGVALinkageForFunction(FD);
8360 
8361     // static, static inline, always_inline, and extern inline functions can
8362     // always be deferred.  Normal inline functions can be deferred in C99/C++.
8363     // Implicit template instantiations can also be deferred in C++.
8364     if (Linkage == GVA_Internal || Linkage == GVA_AvailableExternally ||
8365         Linkage == GVA_DiscardableODR)
8366       return false;
8367     return true;
8368   }
8369 
8370   const VarDecl *VD = cast<VarDecl>(D);
8371   assert(VD->isFileVarDecl() && "Expected file scoped var");
8372 
8373   if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly &&
8374       !isMSStaticDataMemberInlineDefinition(VD))
8375     return false;
8376 
8377   // Variables that can be needed in other TUs are required.
8378   GVALinkage L = GetGVALinkageForVariable(VD);
8379   if (L != GVA_Internal && L != GVA_AvailableExternally &&
8380       L != GVA_DiscardableODR)
8381     return true;
8382 
8383   // Variables that have destruction with side-effects are required.
8384   if (VD->getType().isDestructedType())
8385     return true;
8386 
8387   // Variables that have initialization with side-effects are required.
8388   if (VD->getInit() && VD->getInit()->HasSideEffects(*this))
8389     return true;
8390 
8391   return false;
8392 }
8393 
getDefaultCallingConvention(bool IsVariadic,bool IsCXXMethod) const8394 CallingConv ASTContext::getDefaultCallingConvention(bool IsVariadic,
8395                                                     bool IsCXXMethod) const {
8396   // Pass through to the C++ ABI object
8397   if (IsCXXMethod)
8398     return ABI->getDefaultMethodCallConv(IsVariadic);
8399 
8400   if (LangOpts.MRTD && !IsVariadic) return CC_X86StdCall;
8401 
8402   return Target->getDefaultCallingConv(TargetInfo::CCMT_Unknown);
8403 }
8404 
isNearlyEmpty(const CXXRecordDecl * RD) const8405 bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const {
8406   // Pass through to the C++ ABI object
8407   return ABI->isNearlyEmpty(RD);
8408 }
8409 
getVTableContext()8410 VTableContextBase *ASTContext::getVTableContext() {
8411   if (!VTContext.get()) {
8412     if (Target->getCXXABI().isMicrosoft())
8413       VTContext.reset(new MicrosoftVTableContext(*this));
8414     else
8415       VTContext.reset(new ItaniumVTableContext(*this));
8416   }
8417   return VTContext.get();
8418 }
8419 
createMangleContext()8420 MangleContext *ASTContext::createMangleContext() {
8421   switch (Target->getCXXABI().getKind()) {
8422   case TargetCXXABI::GenericAArch64:
8423   case TargetCXXABI::GenericItanium:
8424   case TargetCXXABI::GenericARM:
8425   case TargetCXXABI::GenericMIPS:
8426   case TargetCXXABI::iOS:
8427   case TargetCXXABI::iOS64:
8428     return ItaniumMangleContext::create(*this, getDiagnostics());
8429   case TargetCXXABI::Microsoft:
8430     return MicrosoftMangleContext::create(*this, getDiagnostics());
8431   }
8432   llvm_unreachable("Unsupported ABI");
8433 }
8434 
~CXXABI()8435 CXXABI::~CXXABI() {}
8436 
getSideTableAllocatedMemory() const8437 size_t ASTContext::getSideTableAllocatedMemory() const {
8438   return ASTRecordLayouts.getMemorySize() +
8439          llvm::capacity_in_bytes(ObjCLayouts) +
8440          llvm::capacity_in_bytes(KeyFunctions) +
8441          llvm::capacity_in_bytes(ObjCImpls) +
8442          llvm::capacity_in_bytes(BlockVarCopyInits) +
8443          llvm::capacity_in_bytes(DeclAttrs) +
8444          llvm::capacity_in_bytes(TemplateOrInstantiation) +
8445          llvm::capacity_in_bytes(InstantiatedFromUsingDecl) +
8446          llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) +
8447          llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) +
8448          llvm::capacity_in_bytes(OverriddenMethods) +
8449          llvm::capacity_in_bytes(Types) +
8450          llvm::capacity_in_bytes(VariableArrayTypes) +
8451          llvm::capacity_in_bytes(ClassScopeSpecializationPattern);
8452 }
8453 
8454 /// getIntTypeForBitwidth -
8455 /// sets integer QualTy according to specified details:
8456 /// bitwidth, signed/unsigned.
8457 /// Returns empty type if there is no appropriate target types.
getIntTypeForBitwidth(unsigned DestWidth,unsigned Signed) const8458 QualType ASTContext::getIntTypeForBitwidth(unsigned DestWidth,
8459                                            unsigned Signed) const {
8460   TargetInfo::IntType Ty = getTargetInfo().getIntTypeByWidth(DestWidth, Signed);
8461   CanQualType QualTy = getFromTargetType(Ty);
8462   if (!QualTy && DestWidth == 128)
8463     return Signed ? Int128Ty : UnsignedInt128Ty;
8464   return QualTy;
8465 }
8466 
8467 /// getRealTypeForBitwidth -
8468 /// sets floating point QualTy according to specified bitwidth.
8469 /// Returns empty type if there is no appropriate target types.
getRealTypeForBitwidth(unsigned DestWidth) const8470 QualType ASTContext::getRealTypeForBitwidth(unsigned DestWidth) const {
8471   TargetInfo::RealType Ty = getTargetInfo().getRealTypeByWidth(DestWidth);
8472   switch (Ty) {
8473   case TargetInfo::Float:
8474     return FloatTy;
8475   case TargetInfo::Double:
8476     return DoubleTy;
8477   case TargetInfo::LongDouble:
8478     return LongDoubleTy;
8479   case TargetInfo::NoFloat:
8480     return QualType();
8481   }
8482 
8483   llvm_unreachable("Unhandled TargetInfo::RealType value");
8484 }
8485 
setManglingNumber(const NamedDecl * ND,unsigned Number)8486 void ASTContext::setManglingNumber(const NamedDecl *ND, unsigned Number) {
8487   if (Number > 1)
8488     MangleNumbers[ND] = Number;
8489 }
8490 
getManglingNumber(const NamedDecl * ND) const8491 unsigned ASTContext::getManglingNumber(const NamedDecl *ND) const {
8492   llvm::DenseMap<const NamedDecl *, unsigned>::const_iterator I =
8493     MangleNumbers.find(ND);
8494   return I != MangleNumbers.end() ? I->second : 1;
8495 }
8496 
setStaticLocalNumber(const VarDecl * VD,unsigned Number)8497 void ASTContext::setStaticLocalNumber(const VarDecl *VD, unsigned Number) {
8498   if (Number > 1)
8499     StaticLocalNumbers[VD] = Number;
8500 }
8501 
getStaticLocalNumber(const VarDecl * VD) const8502 unsigned ASTContext::getStaticLocalNumber(const VarDecl *VD) const {
8503   llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I =
8504       StaticLocalNumbers.find(VD);
8505   return I != StaticLocalNumbers.end() ? I->second : 1;
8506 }
8507 
8508 MangleNumberingContext &
getManglingNumberContext(const DeclContext * DC)8509 ASTContext::getManglingNumberContext(const DeclContext *DC) {
8510   assert(LangOpts.CPlusPlus);  // We don't need mangling numbers for plain C.
8511   MangleNumberingContext *&MCtx = MangleNumberingContexts[DC];
8512   if (!MCtx)
8513     MCtx = createMangleNumberingContext();
8514   return *MCtx;
8515 }
8516 
createMangleNumberingContext() const8517 MangleNumberingContext *ASTContext::createMangleNumberingContext() const {
8518   return ABI->createMangleNumberingContext();
8519 }
8520 
8521 const CXXConstructorDecl *
getCopyConstructorForExceptionObject(CXXRecordDecl * RD)8522 ASTContext::getCopyConstructorForExceptionObject(CXXRecordDecl *RD) {
8523   return ABI->getCopyConstructorForExceptionObject(
8524       cast<CXXRecordDecl>(RD->getFirstDecl()));
8525 }
8526 
addCopyConstructorForExceptionObject(CXXRecordDecl * RD,CXXConstructorDecl * CD)8527 void ASTContext::addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
8528                                                       CXXConstructorDecl *CD) {
8529   return ABI->addCopyConstructorForExceptionObject(
8530       cast<CXXRecordDecl>(RD->getFirstDecl()),
8531       cast<CXXConstructorDecl>(CD->getFirstDecl()));
8532 }
8533 
addDefaultArgExprForConstructor(const CXXConstructorDecl * CD,unsigned ParmIdx,Expr * DAE)8534 void ASTContext::addDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8535                                                  unsigned ParmIdx, Expr *DAE) {
8536   ABI->addDefaultArgExprForConstructor(
8537       cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx, DAE);
8538 }
8539 
getDefaultArgExprForConstructor(const CXXConstructorDecl * CD,unsigned ParmIdx)8540 Expr *ASTContext::getDefaultArgExprForConstructor(const CXXConstructorDecl *CD,
8541                                                   unsigned ParmIdx) {
8542   return ABI->getDefaultArgExprForConstructor(
8543       cast<CXXConstructorDecl>(CD->getFirstDecl()), ParmIdx);
8544 }
8545 
setParameterIndex(const ParmVarDecl * D,unsigned int index)8546 void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) {
8547   ParamIndices[D] = index;
8548 }
8549 
getParameterIndex(const ParmVarDecl * D) const8550 unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const {
8551   ParameterIndexTable::const_iterator I = ParamIndices.find(D);
8552   assert(I != ParamIndices.end() &&
8553          "ParmIndices lacks entry set by ParmVarDecl");
8554   return I->second;
8555 }
8556 
8557 APValue *
getMaterializedTemporaryValue(const MaterializeTemporaryExpr * E,bool MayCreate)8558 ASTContext::getMaterializedTemporaryValue(const MaterializeTemporaryExpr *E,
8559                                           bool MayCreate) {
8560   assert(E && E->getStorageDuration() == SD_Static &&
8561          "don't need to cache the computed value for this temporary");
8562   if (MayCreate)
8563     return &MaterializedTemporaryValues[E];
8564 
8565   llvm::DenseMap<const MaterializeTemporaryExpr *, APValue>::iterator I =
8566       MaterializedTemporaryValues.find(E);
8567   return I == MaterializedTemporaryValues.end() ? nullptr : &I->second;
8568 }
8569 
AtomicUsesUnsupportedLibcall(const AtomicExpr * E) const8570 bool ASTContext::AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const {
8571   const llvm::Triple &T = getTargetInfo().getTriple();
8572   if (!T.isOSDarwin())
8573     return false;
8574 
8575   if (!(T.isiOS() && T.isOSVersionLT(7)) &&
8576       !(T.isMacOSX() && T.isOSVersionLT(10, 9)))
8577     return false;
8578 
8579   QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
8580   CharUnits sizeChars = getTypeSizeInChars(AtomicTy);
8581   uint64_t Size = sizeChars.getQuantity();
8582   CharUnits alignChars = getTypeAlignInChars(AtomicTy);
8583   unsigned Align = alignChars.getQuantity();
8584   unsigned MaxInlineWidthInBits = getTargetInfo().getMaxAtomicInlineWidth();
8585   return (Size != Align || toBits(sizeChars) > MaxInlineWidthInBits);
8586 }
8587 
8588 namespace {
8589 
8590   /// \brief A \c RecursiveASTVisitor that builds a map from nodes to their
8591   /// parents as defined by the \c RecursiveASTVisitor.
8592   ///
8593   /// Note that the relationship described here is purely in terms of AST
8594   /// traversal - there are other relationships (for example declaration context)
8595   /// in the AST that are better modeled by special matchers.
8596   ///
8597   /// FIXME: Currently only builds up the map using \c Stmt and \c Decl nodes.
8598   class ParentMapASTVisitor : public RecursiveASTVisitor<ParentMapASTVisitor> {
8599 
8600   public:
8601     /// \brief Builds and returns the translation unit's parent map.
8602     ///
8603     ///  The caller takes ownership of the returned \c ParentMap.
buildMap(TranslationUnitDecl & TU)8604     static ASTContext::ParentMap *buildMap(TranslationUnitDecl &TU) {
8605       ParentMapASTVisitor Visitor(new ASTContext::ParentMap);
8606       Visitor.TraverseDecl(&TU);
8607       return Visitor.Parents;
8608     }
8609 
8610   private:
8611     typedef RecursiveASTVisitor<ParentMapASTVisitor> VisitorBase;
8612 
ParentMapASTVisitor(ASTContext::ParentMap * Parents)8613     ParentMapASTVisitor(ASTContext::ParentMap *Parents) : Parents(Parents) {
8614     }
8615 
shouldVisitTemplateInstantiations() const8616     bool shouldVisitTemplateInstantiations() const {
8617       return true;
8618     }
shouldVisitImplicitCode() const8619     bool shouldVisitImplicitCode() const {
8620       return true;
8621     }
8622     // Disables data recursion. We intercept Traverse* methods in the RAV, which
8623     // are not triggered during data recursion.
shouldUseDataRecursionFor(clang::Stmt * S) const8624     bool shouldUseDataRecursionFor(clang::Stmt *S) const {
8625       return false;
8626     }
8627 
8628     template <typename T>
TraverseNode(T * Node,bool (VisitorBase::* traverse)(T *))8629     bool TraverseNode(T *Node, bool(VisitorBase:: *traverse) (T *)) {
8630       if (!Node)
8631         return true;
8632       if (ParentStack.size() > 0) {
8633         // FIXME: Currently we add the same parent multiple times, but only
8634         // when no memoization data is available for the type.
8635         // For example when we visit all subexpressions of template
8636         // instantiations; this is suboptimal, but benign: the only way to
8637         // visit those is with hasAncestor / hasParent, and those do not create
8638         // new matches.
8639         // The plan is to enable DynTypedNode to be storable in a map or hash
8640         // map. The main problem there is to implement hash functions /
8641         // comparison operators for all types that DynTypedNode supports that
8642         // do not have pointer identity.
8643         auto &NodeOrVector = (*Parents)[Node];
8644         if (NodeOrVector.isNull()) {
8645           NodeOrVector = new ast_type_traits::DynTypedNode(ParentStack.back());
8646         } else {
8647           if (NodeOrVector.template is<ast_type_traits::DynTypedNode *>()) {
8648             auto *Node =
8649                 NodeOrVector.template get<ast_type_traits::DynTypedNode *>();
8650             auto *Vector = new ASTContext::ParentVector(1, *Node);
8651             NodeOrVector = Vector;
8652             delete Node;
8653           }
8654           assert(NodeOrVector.template is<ASTContext::ParentVector *>());
8655 
8656           auto *Vector =
8657               NodeOrVector.template get<ASTContext::ParentVector *>();
8658           // Skip duplicates for types that have memoization data.
8659           // We must check that the type has memoization data before calling
8660           // std::find() because DynTypedNode::operator== can't compare all
8661           // types.
8662           bool Found = ParentStack.back().getMemoizationData() &&
8663                        std::find(Vector->begin(), Vector->end(),
8664                                  ParentStack.back()) != Vector->end();
8665           if (!Found)
8666             Vector->push_back(ParentStack.back());
8667         }
8668       }
8669       ParentStack.push_back(ast_type_traits::DynTypedNode::create(*Node));
8670       bool Result = (this ->* traverse) (Node);
8671       ParentStack.pop_back();
8672       return Result;
8673     }
8674 
TraverseDecl(Decl * DeclNode)8675     bool TraverseDecl(Decl *DeclNode) {
8676       return TraverseNode(DeclNode, &VisitorBase::TraverseDecl);
8677     }
8678 
TraverseStmt(Stmt * StmtNode)8679     bool TraverseStmt(Stmt *StmtNode) {
8680       return TraverseNode(StmtNode, &VisitorBase::TraverseStmt);
8681     }
8682 
8683     ASTContext::ParentMap *Parents;
8684     llvm::SmallVector<ast_type_traits::DynTypedNode, 16> ParentStack;
8685 
8686     friend class RecursiveASTVisitor<ParentMapASTVisitor>;
8687   };
8688 
8689 } // end namespace
8690 
8691 ArrayRef<ast_type_traits::DynTypedNode>
getParents(const ast_type_traits::DynTypedNode & Node)8692 ASTContext::getParents(const ast_type_traits::DynTypedNode &Node) {
8693   assert(Node.getMemoizationData() &&
8694          "Invariant broken: only nodes that support memoization may be "
8695          "used in the parent map.");
8696   if (!AllParents) {
8697     // We always need to run over the whole translation unit, as
8698     // hasAncestor can escape any subtree.
8699     AllParents.reset(
8700         ParentMapASTVisitor::buildMap(*getTranslationUnitDecl()));
8701   }
8702   ParentMap::const_iterator I = AllParents->find(Node.getMemoizationData());
8703   if (I == AllParents->end()) {
8704     return None;
8705   }
8706   if (auto *N = I->second.dyn_cast<ast_type_traits::DynTypedNode *>()) {
8707     return llvm::makeArrayRef(N, 1);
8708   }
8709   return *I->second.get<ParentVector *>();
8710 }
8711 
8712 bool
ObjCMethodsAreEqual(const ObjCMethodDecl * MethodDecl,const ObjCMethodDecl * MethodImpl)8713 ASTContext::ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
8714                                 const ObjCMethodDecl *MethodImpl) {
8715   // No point trying to match an unavailable/deprecated mothod.
8716   if (MethodDecl->hasAttr<UnavailableAttr>()
8717       || MethodDecl->hasAttr<DeprecatedAttr>())
8718     return false;
8719   if (MethodDecl->getObjCDeclQualifier() !=
8720       MethodImpl->getObjCDeclQualifier())
8721     return false;
8722   if (!hasSameType(MethodDecl->getReturnType(), MethodImpl->getReturnType()))
8723     return false;
8724 
8725   if (MethodDecl->param_size() != MethodImpl->param_size())
8726     return false;
8727 
8728   for (ObjCMethodDecl::param_const_iterator IM = MethodImpl->param_begin(),
8729        IF = MethodDecl->param_begin(), EM = MethodImpl->param_end(),
8730        EF = MethodDecl->param_end();
8731        IM != EM && IF != EF; ++IM, ++IF) {
8732     const ParmVarDecl *DeclVar = (*IF);
8733     const ParmVarDecl *ImplVar = (*IM);
8734     if (ImplVar->getObjCDeclQualifier() != DeclVar->getObjCDeclQualifier())
8735       return false;
8736     if (!hasSameType(DeclVar->getType(), ImplVar->getType()))
8737       return false;
8738   }
8739   return (MethodDecl->isVariadic() == MethodImpl->isVariadic());
8740 
8741 }
8742 
8743 // Explicitly instantiate this in case a Redeclarable<T> is used from a TU that
8744 // doesn't include ASTContext.h
8745 template
8746 clang::LazyGenerationalUpdatePtr<
8747     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::ValueType
8748 clang::LazyGenerationalUpdatePtr<
8749     const Decl *, Decl *, &ExternalASTSource::CompleteRedeclChain>::makeValue(
8750         const clang::ASTContext &Ctx, Decl *Value);
8751