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