clang  3.8.0
SemaType.cpp
Go to the documentation of this file.
1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
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 type-related semantic analysis.
11 //
12 //===----------------------------------------------------------------------===//
13 
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/TypeLoc.h"
25 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Sema/DeclSpec.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/ScopeInfo.h"
33 #include "clang/Sema/Template.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/Support/ErrorHandling.h"
37 
38 using namespace clang;
39 
44 };
45 
46 /// isOmittedBlockReturnType - Return true if this declarator is missing a
47 /// return type because this is a omitted return type on a block literal.
48 static bool isOmittedBlockReturnType(const Declarator &D) {
51  return false;
52 
53  if (D.getNumTypeObjects() == 0)
54  return true; // ^{ ... }
55 
56  if (D.getNumTypeObjects() == 1 &&
58  return true; // ^(int X, float Y) { ... }
59 
60  return false;
61 }
62 
63 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
64 /// doesn't apply to the given type.
65 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
66  QualType type) {
67  TypeDiagSelector WhichType;
68  bool useExpansionLoc = true;
69  switch (attr.getKind()) {
70  case AttributeList::AT_ObjCGC: WhichType = TDS_Pointer; break;
71  case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break;
72  default:
73  // Assume everything else was a function attribute.
74  WhichType = TDS_Function;
75  useExpansionLoc = false;
76  break;
77  }
78 
79  SourceLocation loc = attr.getLoc();
80  StringRef name = attr.getName()->getName();
81 
82  // The GC attributes are usually written with macros; special-case them.
83  IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
84  : nullptr;
85  if (useExpansionLoc && loc.isMacroID() && II) {
86  if (II->isStr("strong")) {
87  if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
88  } else if (II->isStr("weak")) {
89  if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
90  }
91  }
92 
93  S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
94  << type;
95 }
96 
97 // objc_gc applies to Objective-C pointers or, otherwise, to the
98 // smallest available pointer type (i.e. 'void*' in 'void**').
99 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
100  case AttributeList::AT_ObjCGC: \
101  case AttributeList::AT_ObjCOwnership
102 
103 // Function type attributes.
104 #define FUNCTION_TYPE_ATTRS_CASELIST \
105  case AttributeList::AT_NoReturn: \
106  case AttributeList::AT_CDecl: \
107  case AttributeList::AT_FastCall: \
108  case AttributeList::AT_StdCall: \
109  case AttributeList::AT_ThisCall: \
110  case AttributeList::AT_Pascal: \
111  case AttributeList::AT_VectorCall: \
112  case AttributeList::AT_MSABI: \
113  case AttributeList::AT_SysVABI: \
114  case AttributeList::AT_Regparm: \
115  case AttributeList::AT_Pcs: \
116  case AttributeList::AT_IntelOclBicc
117 
118 // Microsoft-specific type qualifiers.
119 #define MS_TYPE_ATTRS_CASELIST \
120  case AttributeList::AT_Ptr32: \
121  case AttributeList::AT_Ptr64: \
122  case AttributeList::AT_SPtr: \
123  case AttributeList::AT_UPtr
124 
125 // Nullability qualifiers.
126 #define NULLABILITY_TYPE_ATTRS_CASELIST \
127  case AttributeList::AT_TypeNonNull: \
128  case AttributeList::AT_TypeNullable: \
129  case AttributeList::AT_TypeNullUnspecified
130 
131 namespace {
132  /// An object which stores processing state for the entire
133  /// GetTypeForDeclarator process.
134  class TypeProcessingState {
135  Sema &sema;
136 
137  /// The declarator being processed.
138  Declarator &declarator;
139 
140  /// The index of the declarator chunk we're currently processing.
141  /// May be the total number of valid chunks, indicating the
142  /// DeclSpec.
143  unsigned chunkIndex;
144 
145  /// Whether there are non-trivial modifications to the decl spec.
146  bool trivial;
147 
148  /// Whether we saved the attributes in the decl spec.
149  bool hasSavedAttrs;
150 
151  /// The original set of attributes on the DeclSpec.
153 
154  /// A list of attributes to diagnose the uselessness of when the
155  /// processing is complete.
156  SmallVector<AttributeList*, 2> ignoredTypeAttrs;
157 
158  public:
159  TypeProcessingState(Sema &sema, Declarator &declarator)
160  : sema(sema), declarator(declarator),
161  chunkIndex(declarator.getNumTypeObjects()),
162  trivial(true), hasSavedAttrs(false) {}
163 
164  Sema &getSema() const {
165  return sema;
166  }
167 
168  Declarator &getDeclarator() const {
169  return declarator;
170  }
171 
172  bool isProcessingDeclSpec() const {
173  return chunkIndex == declarator.getNumTypeObjects();
174  }
175 
176  unsigned getCurrentChunkIndex() const {
177  return chunkIndex;
178  }
179 
180  void setCurrentChunkIndex(unsigned idx) {
181  assert(idx <= declarator.getNumTypeObjects());
182  chunkIndex = idx;
183  }
184 
185  AttributeList *&getCurrentAttrListRef() const {
186  if (isProcessingDeclSpec())
187  return getMutableDeclSpec().getAttributes().getListRef();
188  return declarator.getTypeObject(chunkIndex).getAttrListRef();
189  }
190 
191  /// Save the current set of attributes on the DeclSpec.
192  void saveDeclSpecAttrs() {
193  // Don't try to save them multiple times.
194  if (hasSavedAttrs) return;
195 
196  DeclSpec &spec = getMutableDeclSpec();
197  for (AttributeList *attr = spec.getAttributes().getList(); attr;
198  attr = attr->getNext())
199  savedAttrs.push_back(attr);
200  trivial &= savedAttrs.empty();
201  hasSavedAttrs = true;
202  }
203 
204  /// Record that we had nowhere to put the given type attribute.
205  /// We will diagnose such attributes later.
206  void addIgnoredTypeAttr(AttributeList &attr) {
207  ignoredTypeAttrs.push_back(&attr);
208  }
209 
210  /// Diagnose all the ignored type attributes, given that the
211  /// declarator worked out to the given type.
212  void diagnoseIgnoredTypeAttrs(QualType type) const {
213  for (auto *Attr : ignoredTypeAttrs)
214  diagnoseBadTypeAttribute(getSema(), *Attr, type);
215  }
216 
217  ~TypeProcessingState() {
218  if (trivial) return;
219 
220  restoreDeclSpecAttrs();
221  }
222 
223  private:
224  DeclSpec &getMutableDeclSpec() const {
225  return const_cast<DeclSpec&>(declarator.getDeclSpec());
226  }
227 
228  void restoreDeclSpecAttrs() {
229  assert(hasSavedAttrs);
230 
231  if (savedAttrs.empty()) {
232  getMutableDeclSpec().getAttributes().set(nullptr);
233  return;
234  }
235 
236  getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
237  for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
238  savedAttrs[i]->setNext(savedAttrs[i+1]);
239  savedAttrs.back()->setNext(nullptr);
240  }
241  };
242 }
243 
244 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
245  attr.setNext(head);
246  head = &attr;
247 }
248 
249 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
250  if (head == &attr) {
251  head = attr.getNext();
252  return;
253  }
254 
255  AttributeList *cur = head;
256  while (true) {
257  assert(cur && cur->getNext() && "ran out of attrs?");
258  if (cur->getNext() == &attr) {
259  cur->setNext(attr.getNext());
260  return;
261  }
262  cur = cur->getNext();
263  }
264 }
265 
267  AttributeList *&fromList,
268  AttributeList *&toList) {
269  spliceAttrOutOfList(attr, fromList);
270  spliceAttrIntoList(attr, toList);
271 }
272 
273 /// The location of a type attribute.
275  /// The attribute is in the decl-specifier-seq.
277  /// The attribute is part of a DeclaratorChunk.
279  /// The attribute is immediately after the declaration's name.
281 };
282 
283 static void processTypeAttrs(TypeProcessingState &state,
285  AttributeList *attrs);
286 
287 static bool handleFunctionTypeAttr(TypeProcessingState &state,
288  AttributeList &attr,
289  QualType &type);
290 
291 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
292  AttributeList &attr,
293  QualType &type);
294 
295 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
296  AttributeList &attr, QualType &type);
297 
298 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
299  AttributeList &attr, QualType &type);
300 
301 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
302  AttributeList &attr, QualType &type) {
303  if (attr.getKind() == AttributeList::AT_ObjCGC)
304  return handleObjCGCTypeAttr(state, attr, type);
305  assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
306  return handleObjCOwnershipTypeAttr(state, attr, type);
307 }
308 
309 /// Given the index of a declarator chunk, check whether that chunk
310 /// directly specifies the return type of a function and, if so, find
311 /// an appropriate place for it.
312 ///
313 /// \param i - a notional index which the search will start
314 /// immediately inside
315 ///
316 /// \param onlyBlockPointers Whether we should only look into block
317 /// pointer types (vs. all pointer types).
319  unsigned i,
320  bool onlyBlockPointers) {
321  assert(i <= declarator.getNumTypeObjects());
322 
323  DeclaratorChunk *result = nullptr;
324 
325  // First, look inwards past parens for a function declarator.
326  for (; i != 0; --i) {
327  DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
328  switch (fnChunk.Kind) {
330  continue;
331 
332  // If we find anything except a function, bail out.
339  return result;
340 
341  // If we do find a function declarator, scan inwards from that,
342  // looking for a (block-)pointer declarator.
344  for (--i; i != 0; --i) {
345  DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
346  switch (ptrChunk.Kind) {
352  continue;
353 
356  if (onlyBlockPointers)
357  continue;
358 
359  // fallthrough
360 
362  result = &ptrChunk;
363  goto continue_outer;
364  }
365  llvm_unreachable("bad declarator chunk kind");
366  }
367 
368  // If we run out of declarators doing that, we're done.
369  return result;
370  }
371  llvm_unreachable("bad declarator chunk kind");
372 
373  // Okay, reconsider from our new point.
374  continue_outer: ;
375  }
376 
377  // Ran out of chunks, bail out.
378  return result;
379 }
380 
381 /// Given that an objc_gc attribute was written somewhere on a
382 /// declaration *other* than on the declarator itself (for which, use
383 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
384 /// didn't apply in whatever position it was written in, try to move
385 /// it to a more appropriate position.
386 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
387  AttributeList &attr,
388  QualType type) {
389  Declarator &declarator = state.getDeclarator();
390 
391  // Move it to the outermost normal or block pointer declarator.
392  for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
393  DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
394  switch (chunk.Kind) {
397  // But don't move an ARC ownership attribute to the return type
398  // of a block.
399  DeclaratorChunk *destChunk = nullptr;
400  if (state.isProcessingDeclSpec() &&
401  attr.getKind() == AttributeList::AT_ObjCOwnership)
402  destChunk = maybeMovePastReturnType(declarator, i - 1,
403  /*onlyBlockPointers=*/true);
404  if (!destChunk) destChunk = &chunk;
405 
406  moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
407  destChunk->getAttrListRef());
408  return;
409  }
410 
413  continue;
414 
415  // We may be starting at the return type of a block.
417  if (state.isProcessingDeclSpec() &&
418  attr.getKind() == AttributeList::AT_ObjCOwnership) {
420  declarator, i,
421  /*onlyBlockPointers=*/true)) {
422  moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
423  dest->getAttrListRef());
424  return;
425  }
426  }
427  goto error;
428 
429  // Don't walk through these.
433  goto error;
434  }
435  }
436  error:
437 
438  diagnoseBadTypeAttribute(state.getSema(), attr, type);
439 }
440 
441 /// Distribute an objc_gc type attribute that was written on the
442 /// declarator.
443 static void
445  AttributeList &attr,
446  QualType &declSpecType) {
447  Declarator &declarator = state.getDeclarator();
448 
449  // objc_gc goes on the innermost pointer to something that's not a
450  // pointer.
451  unsigned innermost = -1U;
452  bool considerDeclSpec = true;
453  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
454  DeclaratorChunk &chunk = declarator.getTypeObject(i);
455  switch (chunk.Kind) {
458  innermost = i;
459  continue;
460 
466  continue;
467 
469  considerDeclSpec = false;
470  goto done;
471  }
472  }
473  done:
474 
475  // That might actually be the decl spec if we weren't blocked by
476  // anything in the declarator.
477  if (considerDeclSpec) {
478  if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
479  // Splice the attribute into the decl spec. Prevents the
480  // attribute from being applied multiple times and gives
481  // the source-location-filler something to work with.
482  state.saveDeclSpecAttrs();
483  moveAttrFromListToList(attr, declarator.getAttrListRef(),
484  declarator.getMutableDeclSpec().getAttributes().getListRef());
485  return;
486  }
487  }
488 
489  // Otherwise, if we found an appropriate chunk, splice the attribute
490  // into it.
491  if (innermost != -1U) {
492  moveAttrFromListToList(attr, declarator.getAttrListRef(),
493  declarator.getTypeObject(innermost).getAttrListRef());
494  return;
495  }
496 
497  // Otherwise, diagnose when we're done building the type.
498  spliceAttrOutOfList(attr, declarator.getAttrListRef());
499  state.addIgnoredTypeAttr(attr);
500 }
501 
502 /// A function type attribute was written somewhere in a declaration
503 /// *other* than on the declarator itself or in the decl spec. Given
504 /// that it didn't apply in whatever position it was written in, try
505 /// to move it to a more appropriate position.
506 static void distributeFunctionTypeAttr(TypeProcessingState &state,
507  AttributeList &attr,
508  QualType type) {
509  Declarator &declarator = state.getDeclarator();
510 
511  // Try to push the attribute from the return type of a function to
512  // the function itself.
513  for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
514  DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
515  switch (chunk.Kind) {
517  moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
518  chunk.getAttrListRef());
519  return;
520 
528  continue;
529  }
530  }
531 
532  diagnoseBadTypeAttribute(state.getSema(), attr, type);
533 }
534 
535 /// Try to distribute a function type attribute to the innermost
536 /// function chunk or type. Returns true if the attribute was
537 /// distributed, false if no location was found.
538 static bool
539 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
540  AttributeList &attr,
541  AttributeList *&attrList,
542  QualType &declSpecType) {
543  Declarator &declarator = state.getDeclarator();
544 
545  // Put it on the innermost function chunk, if there is one.
546  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
547  DeclaratorChunk &chunk = declarator.getTypeObject(i);
548  if (chunk.Kind != DeclaratorChunk::Function) continue;
549 
550  moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
551  return true;
552  }
553 
554  return handleFunctionTypeAttr(state, attr, declSpecType);
555 }
556 
557 /// A function type attribute was written in the decl spec. Try to
558 /// apply it somewhere.
559 static void
560 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
561  AttributeList &attr,
562  QualType &declSpecType) {
563  state.saveDeclSpecAttrs();
564 
565  // C++11 attributes before the decl specifiers actually appertain to
566  // the declarators. Move them straight there. We don't support the
567  // 'put them wherever you like' semantics we allow for GNU attributes.
568  if (attr.isCXX11Attribute()) {
569  moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
570  state.getDeclarator().getAttrListRef());
571  return;
572  }
573 
574  // Try to distribute to the innermost.
576  state.getCurrentAttrListRef(),
577  declSpecType))
578  return;
579 
580  // If that failed, diagnose the bad attribute when the declarator is
581  // fully built.
582  state.addIgnoredTypeAttr(attr);
583 }
584 
585 /// A function type attribute was written on the declarator. Try to
586 /// apply it somewhere.
587 static void
588 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
589  AttributeList &attr,
590  QualType &declSpecType) {
591  Declarator &declarator = state.getDeclarator();
592 
593  // Try to distribute to the innermost.
595  declarator.getAttrListRef(),
596  declSpecType))
597  return;
598 
599  // If that failed, diagnose the bad attribute when the declarator is
600  // fully built.
601  spliceAttrOutOfList(attr, declarator.getAttrListRef());
602  state.addIgnoredTypeAttr(attr);
603 }
604 
605 /// \brief Given that there are attributes written on the declarator
606 /// itself, try to distribute any type attributes to the appropriate
607 /// declarator chunk.
608 ///
609 /// These are attributes like the following:
610 /// int f ATTR;
611 /// int (f ATTR)();
612 /// but not necessarily this:
613 /// int f() ATTR;
614 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
615  QualType &declSpecType) {
616  // Collect all the type attributes from the declarator itself.
617  assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
618  AttributeList *attr = state.getDeclarator().getAttributes();
619  AttributeList *next;
620  do {
621  next = attr->getNext();
622 
623  // Do not distribute C++11 attributes. They have strict rules for what
624  // they appertain to.
625  if (attr->isCXX11Attribute())
626  continue;
627 
628  switch (attr->getKind()) {
630  distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
631  break;
632 
633  case AttributeList::AT_NSReturnsRetained:
634  if (!state.getSema().getLangOpts().ObjCAutoRefCount)
635  break;
636  // fallthrough
637 
639  distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
640  break;
641 
643  // Microsoft type attributes cannot go after the declarator-id.
644  continue;
645 
647  // Nullability specifiers cannot go after the declarator-id.
648 
649  // Objective-C __kindof does not get distributed.
650  case AttributeList::AT_ObjCKindOf:
651  continue;
652 
653  default:
654  break;
655  }
656  } while ((attr = next));
657 }
658 
659 /// Add a synthetic '()' to a block-literal declarator if it is
660 /// required, given the return type.
661 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
662  QualType declSpecType) {
663  Declarator &declarator = state.getDeclarator();
664 
665  // First, check whether the declarator would produce a function,
666  // i.e. whether the innermost semantic chunk is a function.
667  if (declarator.isFunctionDeclarator()) {
668  // If so, make that declarator a prototyped declarator.
669  declarator.getFunctionTypeInfo().hasPrototype = true;
670  return;
671  }
672 
673  // If there are any type objects, the type as written won't name a
674  // function, regardless of the decl spec type. This is because a
675  // block signature declarator is always an abstract-declarator, and
676  // abstract-declarators can't just be parentheses chunks. Therefore
677  // we need to build a function chunk unless there are no type
678  // objects and the decl spec type is a function.
679  if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
680  return;
681 
682  // Note that there *are* cases with invalid declarators where
683  // declarators consist solely of parentheses. In general, these
684  // occur only in failed efforts to make function declarators, so
685  // faking up the function chunk is still the right thing to do.
686 
687  // Otherwise, we need to fake up a function declarator.
688  SourceLocation loc = declarator.getLocStart();
689 
690  // ...and *prepend* it to the declarator.
691  SourceLocation NoLoc;
693  /*HasProto=*/true,
694  /*IsAmbiguous=*/false,
695  /*LParenLoc=*/NoLoc,
696  /*ArgInfo=*/nullptr,
697  /*NumArgs=*/0,
698  /*EllipsisLoc=*/NoLoc,
699  /*RParenLoc=*/NoLoc,
700  /*TypeQuals=*/0,
701  /*RefQualifierIsLvalueRef=*/true,
702  /*RefQualifierLoc=*/NoLoc,
703  /*ConstQualifierLoc=*/NoLoc,
704  /*VolatileQualifierLoc=*/NoLoc,
705  /*RestrictQualifierLoc=*/NoLoc,
706  /*MutableLoc=*/NoLoc, EST_None,
707  /*ESpecRange=*/SourceRange(),
708  /*Exceptions=*/nullptr,
709  /*ExceptionRanges=*/nullptr,
710  /*NumExceptions=*/0,
711  /*NoexceptExpr=*/nullptr,
712  /*ExceptionSpecTokens=*/nullptr,
713  loc, loc, declarator));
714 
715  // For consistency, make sure the state still has us as processing
716  // the decl spec.
717  assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
718  state.setCurrentChunkIndex(declarator.getNumTypeObjects());
719 }
720 
722  unsigned &TypeQuals,
723  QualType TypeSoFar,
724  unsigned RemoveTQs,
725  unsigned DiagID) {
726  // If this occurs outside a template instantiation, warn the user about
727  // it; they probably didn't mean to specify a redundant qualifier.
728  typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
729  for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
731  QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
732  if (!(RemoveTQs & Qual.first))
733  continue;
734 
735  if (S.ActiveTemplateInstantiations.empty()) {
736  if (TypeQuals & Qual.first)
737  S.Diag(Qual.second, DiagID)
738  << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
739  << FixItHint::CreateRemoval(Qual.second);
740  }
741 
742  TypeQuals &= ~Qual.first;
743  }
744 }
745 
746 /// Apply Objective-C type arguments to the given type.
749  SourceRange typeArgsRange,
750  bool failOnError = false) {
751  // We can only apply type arguments to an Objective-C class type.
752  const auto *objcObjectType = type->getAs<ObjCObjectType>();
753  if (!objcObjectType || !objcObjectType->getInterface()) {
754  S.Diag(loc, diag::err_objc_type_args_non_class)
755  << type
756  << typeArgsRange;
757 
758  if (failOnError)
759  return QualType();
760  return type;
761  }
762 
763  // The class type must be parameterized.
764  ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
765  ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
766  if (!typeParams) {
767  S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
768  << objcClass->getDeclName()
769  << FixItHint::CreateRemoval(typeArgsRange);
770 
771  if (failOnError)
772  return QualType();
773 
774  return type;
775  }
776 
777  // The type must not already be specialized.
778  if (objcObjectType->isSpecialized()) {
779  S.Diag(loc, diag::err_objc_type_args_specialized_class)
780  << type
781  << FixItHint::CreateRemoval(typeArgsRange);
782 
783  if (failOnError)
784  return QualType();
785 
786  return type;
787  }
788 
789  // Check the type arguments.
790  SmallVector<QualType, 4> finalTypeArgs;
791  unsigned numTypeParams = typeParams->size();
792  bool anyPackExpansions = false;
793  for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
794  TypeSourceInfo *typeArgInfo = typeArgs[i];
795  QualType typeArg = typeArgInfo->getType();
796 
797  // Type arguments cannot have explicit qualifiers or nullability.
798  // We ignore indirect sources of these, e.g. behind typedefs or
799  // template arguments.
800  if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
801  bool diagnosed = false;
802  SourceRange rangeToRemove;
803  if (auto attr = qual.getAs<AttributedTypeLoc>()) {
804  rangeToRemove = attr.getLocalSourceRange();
805  if (attr.getTypePtr()->getImmediateNullability()) {
806  typeArg = attr.getTypePtr()->getModifiedType();
807  S.Diag(attr.getLocStart(),
808  diag::err_objc_type_arg_explicit_nullability)
809  << typeArg << FixItHint::CreateRemoval(rangeToRemove);
810  diagnosed = true;
811  }
812  }
813 
814  if (!diagnosed) {
815  S.Diag(qual.getLocStart(), diag::err_objc_type_arg_qualified)
816  << typeArg << typeArg.getQualifiers().getAsString()
817  << FixItHint::CreateRemoval(rangeToRemove);
818  }
819  }
820 
821  // Remove qualifiers even if they're non-local.
822  typeArg = typeArg.getUnqualifiedType();
823 
824  finalTypeArgs.push_back(typeArg);
825 
826  if (typeArg->getAs<PackExpansionType>())
827  anyPackExpansions = true;
828 
829  // Find the corresponding type parameter, if there is one.
830  ObjCTypeParamDecl *typeParam = nullptr;
831  if (!anyPackExpansions) {
832  if (i < numTypeParams) {
833  typeParam = typeParams->begin()[i];
834  } else {
835  // Too many arguments.
836  S.Diag(loc, diag::err_objc_type_args_wrong_arity)
837  << false
838  << objcClass->getDeclName()
839  << (unsigned)typeArgs.size()
840  << numTypeParams;
841  S.Diag(objcClass->getLocation(), diag::note_previous_decl)
842  << objcClass;
843 
844  if (failOnError)
845  return QualType();
846 
847  return type;
848  }
849  }
850 
851  // Objective-C object pointer types must be substitutable for the bounds.
852  if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
853  // If we don't have a type parameter to match against, assume
854  // everything is fine. There was a prior pack expansion that
855  // means we won't be able to match anything.
856  if (!typeParam) {
857  assert(anyPackExpansions && "Too many arguments?");
858  continue;
859  }
860 
861  // Retrieve the bound.
862  QualType bound = typeParam->getUnderlyingType();
863  const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
864 
865  // Determine whether the type argument is substitutable for the bound.
866  if (typeArgObjC->isObjCIdType()) {
867  // When the type argument is 'id', the only acceptable type
868  // parameter bound is 'id'.
869  if (boundObjC->isObjCIdType())
870  continue;
871  } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
872  // Otherwise, we follow the assignability rules.
873  continue;
874  }
875 
876  // Diagnose the mismatch.
877  S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
878  diag::err_objc_type_arg_does_not_match_bound)
879  << typeArg << bound << typeParam->getDeclName();
880  S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
881  << typeParam->getDeclName();
882 
883  if (failOnError)
884  return QualType();
885 
886  return type;
887  }
888 
889  // Block pointer types are permitted for unqualified 'id' bounds.
890  if (typeArg->isBlockPointerType()) {
891  // If we don't have a type parameter to match against, assume
892  // everything is fine. There was a prior pack expansion that
893  // means we won't be able to match anything.
894  if (!typeParam) {
895  assert(anyPackExpansions && "Too many arguments?");
896  continue;
897  }
898 
899  // Retrieve the bound.
900  QualType bound = typeParam->getUnderlyingType();
902  continue;
903 
904  // Diagnose the mismatch.
905  S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
906  diag::err_objc_type_arg_does_not_match_bound)
907  << typeArg << bound << typeParam->getDeclName();
908  S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
909  << typeParam->getDeclName();
910 
911  if (failOnError)
912  return QualType();
913 
914  return type;
915  }
916 
917  // Dependent types will be checked at instantiation time.
918  if (typeArg->isDependentType()) {
919  continue;
920  }
921 
922  // Diagnose non-id-compatible type arguments.
923  S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
924  diag::err_objc_type_arg_not_id_compatible)
925  << typeArg
926  << typeArgInfo->getTypeLoc().getSourceRange();
927 
928  if (failOnError)
929  return QualType();
930 
931  return type;
932  }
933 
934  // Make sure we didn't have the wrong number of arguments.
935  if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
936  S.Diag(loc, diag::err_objc_type_args_wrong_arity)
937  << (typeArgs.size() < typeParams->size())
938  << objcClass->getDeclName()
939  << (unsigned)finalTypeArgs.size()
940  << (unsigned)numTypeParams;
941  S.Diag(objcClass->getLocation(), diag::note_previous_decl)
942  << objcClass;
943 
944  if (failOnError)
945  return QualType();
946 
947  return type;
948  }
949 
950  // Success. Form the specialized type.
951  return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
952 }
953 
954 /// Apply Objective-C protocol qualifiers to the given type.
956  Sema &S, SourceLocation loc, SourceRange range, QualType type,
958  const SourceLocation *protocolLocs,
959  bool failOnError = false) {
960  ASTContext &ctx = S.Context;
961  if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
962  // FIXME: Check for protocols to which the class type is already
963  // known to conform.
964 
965  return ctx.getObjCObjectType(objT->getBaseType(),
966  objT->getTypeArgsAsWritten(),
967  protocols,
968  objT->isKindOfTypeAsWritten());
969  }
970 
971  if (type->isObjCObjectType()) {
972  // Silently overwrite any existing protocol qualifiers.
973  // TODO: determine whether that's the right thing to do.
974 
975  // FIXME: Check for protocols to which the class type is already
976  // known to conform.
977  return ctx.getObjCObjectType(type, { }, protocols, false);
978  }
979 
980  // id<protocol-list>
981  if (type->isObjCIdType()) {
982  const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
983  type = ctx.getObjCObjectType(ctx.ObjCBuiltinIdTy, { }, protocols,
984  objPtr->isKindOfType());
985  return ctx.getObjCObjectPointerType(type);
986  }
987 
988  // Class<protocol-list>
989  if (type->isObjCClassType()) {
990  const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
991  type = ctx.getObjCObjectType(ctx.ObjCBuiltinClassTy, { }, protocols,
992  objPtr->isKindOfType());
993  return ctx.getObjCObjectPointerType(type);
994  }
995 
996  S.Diag(loc, diag::err_invalid_protocol_qualifiers)
997  << range;
998 
999  if (failOnError)
1000  return QualType();
1001 
1002  return type;
1003 }
1004 
1005 QualType Sema::BuildObjCObjectType(QualType BaseType,
1006  SourceLocation Loc,
1007  SourceLocation TypeArgsLAngleLoc,
1008  ArrayRef<TypeSourceInfo *> TypeArgs,
1009  SourceLocation TypeArgsRAngleLoc,
1010  SourceLocation ProtocolLAngleLoc,
1011  ArrayRef<ObjCProtocolDecl *> Protocols,
1012  ArrayRef<SourceLocation> ProtocolLocs,
1013  SourceLocation ProtocolRAngleLoc,
1014  bool FailOnError) {
1015  QualType Result = BaseType;
1016  if (!TypeArgs.empty()) {
1017  Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1018  SourceRange(TypeArgsLAngleLoc,
1019  TypeArgsRAngleLoc),
1020  FailOnError);
1021  if (FailOnError && Result.isNull())
1022  return QualType();
1023  }
1024 
1025  if (!Protocols.empty()) {
1026  Result = applyObjCProtocolQualifiers(*this, Loc,
1027  SourceRange(ProtocolLAngleLoc,
1028  ProtocolRAngleLoc),
1029  Result, Protocols,
1030  ProtocolLocs.data(),
1031  FailOnError);
1032  if (FailOnError && Result.isNull())
1033  return QualType();
1034  }
1035 
1036  return Result;
1037 }
1038 
1040  SourceLocation lAngleLoc,
1041  ArrayRef<Decl *> protocols,
1042  ArrayRef<SourceLocation> protocolLocs,
1043  SourceLocation rAngleLoc) {
1044  // Form id<protocol-list>.
1046  Context.ObjCBuiltinIdTy, { },
1047  llvm::makeArrayRef(
1048  (ObjCProtocolDecl * const *)protocols.data(),
1049  protocols.size()),
1050  false);
1052 
1053  TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1054  TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1055 
1056  auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1057  ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1058 
1059  auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1060  .castAs<ObjCObjectTypeLoc>();
1061  ObjCObjectTL.setHasBaseTypeAsWritten(false);
1062  ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1063 
1064  // No type arguments.
1065  ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1066  ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1067 
1068  // Fill in protocol qualifiers.
1069  ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1070  ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1071  for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1072  ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1073 
1074  // We're done. Return the completed type to the parser.
1075  return CreateParsedType(Result, ResultTInfo);
1076 }
1077 
1079  Scope *S,
1080  SourceLocation Loc,
1081  ParsedType BaseType,
1082  SourceLocation TypeArgsLAngleLoc,
1083  ArrayRef<ParsedType> TypeArgs,
1084  SourceLocation TypeArgsRAngleLoc,
1085  SourceLocation ProtocolLAngleLoc,
1086  ArrayRef<Decl *> Protocols,
1087  ArrayRef<SourceLocation> ProtocolLocs,
1088  SourceLocation ProtocolRAngleLoc) {
1089  TypeSourceInfo *BaseTypeInfo = nullptr;
1090  QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1091  if (T.isNull())
1092  return true;
1093 
1094  // Handle missing type-source info.
1095  if (!BaseTypeInfo)
1096  BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1097 
1098  // Extract type arguments.
1099  SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1100  for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1101  TypeSourceInfo *TypeArgInfo = nullptr;
1102  QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1103  if (TypeArg.isNull()) {
1104  ActualTypeArgInfos.clear();
1105  break;
1106  }
1107 
1108  assert(TypeArgInfo && "No type source info?");
1109  ActualTypeArgInfos.push_back(TypeArgInfo);
1110  }
1111 
1112  // Build the object type.
1114  T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1115  TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1116  ProtocolLAngleLoc,
1117  llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1118  Protocols.size()),
1119  ProtocolLocs, ProtocolRAngleLoc,
1120  /*FailOnError=*/false);
1121 
1122  if (Result == T)
1123  return BaseType;
1124 
1125  // Create source information for this type.
1126  TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1127  TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1128 
1129  // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1130  // object pointer type. Fill in source information for it.
1131  if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1132  // The '*' is implicit.
1133  ObjCObjectPointerTL.setStarLoc(SourceLocation());
1134  ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1135  }
1136 
1137  auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1138 
1139  // Type argument information.
1140  if (ObjCObjectTL.getNumTypeArgs() > 0) {
1141  assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1142  ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1143  ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1144  for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1145  ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1146  } else {
1147  ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1148  ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1149  }
1150 
1151  // Protocol qualifier information.
1152  if (ObjCObjectTL.getNumProtocols() > 0) {
1153  assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1154  ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1155  ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1156  for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1157  ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1158  } else {
1159  ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1160  ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1161  }
1162 
1163  // Base type.
1164  ObjCObjectTL.setHasBaseTypeAsWritten(true);
1165  if (ObjCObjectTL.getType() == T)
1166  ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1167  else
1168  ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1169 
1170  // We're done. Return the completed type to the parser.
1171  return CreateParsedType(Result, ResultTInfo);
1172 }
1173 
1174 /// \brief Convert the specified declspec to the appropriate type
1175 /// object.
1176 /// \param state Specifies the declarator containing the declaration specifier
1177 /// to be converted, along with other associated processing state.
1178 /// \returns The type described by the declaration specifiers. This function
1179 /// never returns null.
1180 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1181  // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1182  // checking.
1183 
1184  Sema &S = state.getSema();
1185  Declarator &declarator = state.getDeclarator();
1186  const DeclSpec &DS = declarator.getDeclSpec();
1187  SourceLocation DeclLoc = declarator.getIdentifierLoc();
1188  if (DeclLoc.isInvalid())
1189  DeclLoc = DS.getLocStart();
1190 
1191  ASTContext &Context = S.Context;
1192 
1193  QualType Result;
1194  switch (DS.getTypeSpecType()) {
1195  case DeclSpec::TST_void:
1196  Result = Context.VoidTy;
1197  break;
1198  case DeclSpec::TST_char:
1200  Result = Context.CharTy;
1201  else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
1202  Result = Context.SignedCharTy;
1203  else {
1204  assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1205  "Unknown TSS value");
1206  Result = Context.UnsignedCharTy;
1207  }
1208  break;
1209  case DeclSpec::TST_wchar:
1211  Result = Context.WCharTy;
1212  else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
1213  S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1214  << DS.getSpecifierName(DS.getTypeSpecType(),
1215  Context.getPrintingPolicy());
1216  Result = Context.getSignedWCharType();
1217  } else {
1218  assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1219  "Unknown TSS value");
1220  S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1221  << DS.getSpecifierName(DS.getTypeSpecType(),
1222  Context.getPrintingPolicy());
1223  Result = Context.getUnsignedWCharType();
1224  }
1225  break;
1226  case DeclSpec::TST_char16:
1227  assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1228  "Unknown TSS value");
1229  Result = Context.Char16Ty;
1230  break;
1231  case DeclSpec::TST_char32:
1232  assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1233  "Unknown TSS value");
1234  Result = Context.Char32Ty;
1235  break;
1237  // If this is a missing declspec in a block literal return context, then it
1238  // is inferred from the return statements inside the block.
1239  // The declspec is always missing in a lambda expr context; it is either
1240  // specified with a trailing return type or inferred.
1241  if (S.getLangOpts().CPlusPlus14 &&
1242  declarator.getContext() == Declarator::LambdaExprContext) {
1243  // In C++1y, a lambda's implicit return type is 'auto'.
1244  Result = Context.getAutoDeductType();
1245  break;
1246  } else if (declarator.getContext() == Declarator::LambdaExprContext ||
1247  isOmittedBlockReturnType(declarator)) {
1248  Result = Context.DependentTy;
1249  break;
1250  }
1251 
1252  // Unspecified typespec defaults to int in C90. However, the C90 grammar
1253  // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1254  // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
1255  // Note that the one exception to this is function definitions, which are
1256  // allowed to be completely missing a declspec. This is handled in the
1257  // parser already though by it pretending to have seen an 'int' in this
1258  // case.
1259  if (S.getLangOpts().ImplicitInt) {
1260  // In C89 mode, we only warn if there is a completely missing declspec
1261  // when one is not allowed.
1262  if (DS.isEmpty()) {
1263  S.Diag(DeclLoc, diag::ext_missing_declspec)
1264  << DS.getSourceRange()
1265  << FixItHint::CreateInsertion(DS.getLocStart(), "int");
1266  }
1267  } else if (!DS.hasTypeSpecifier()) {
1268  // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1269  // "At least one type specifier shall be given in the declaration
1270  // specifiers in each declaration, and in the specifier-qualifier list in
1271  // each struct declaration and type name."
1272  if (S.getLangOpts().CPlusPlus) {
1273  S.Diag(DeclLoc, diag::err_missing_type_specifier)
1274  << DS.getSourceRange();
1275 
1276  // When this occurs in C++ code, often something is very broken with the
1277  // value being declared, poison it as invalid so we don't get chains of
1278  // errors.
1279  declarator.setInvalidType(true);
1280  } else if (S.getLangOpts().OpenCLVersion >= 200 && DS.isTypeSpecPipe()){
1281  S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1282  << DS.getSourceRange();
1283  declarator.setInvalidType(true);
1284  } else {
1285  S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1286  << DS.getSourceRange();
1287  }
1288  }
1289 
1290  // FALL THROUGH.
1291  case DeclSpec::TST_int: {
1293  switch (DS.getTypeSpecWidth()) {
1294  case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
1295  case DeclSpec::TSW_short: Result = Context.ShortTy; break;
1296  case DeclSpec::TSW_long: Result = Context.LongTy; break;
1298  Result = Context.LongLongTy;
1299 
1300  // 'long long' is a C99 or C++11 feature.
1301  if (!S.getLangOpts().C99) {
1302  if (S.getLangOpts().CPlusPlus)
1303  S.Diag(DS.getTypeSpecWidthLoc(),
1304  S.getLangOpts().CPlusPlus11 ?
1305  diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1306  else
1307  S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1308  }
1309  break;
1310  }
1311  } else {
1312  switch (DS.getTypeSpecWidth()) {
1313  case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
1314  case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
1315  case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
1317  Result = Context.UnsignedLongLongTy;
1318 
1319  // 'long long' is a C99 or C++11 feature.
1320  if (!S.getLangOpts().C99) {
1321  if (S.getLangOpts().CPlusPlus)
1322  S.Diag(DS.getTypeSpecWidthLoc(),
1323  S.getLangOpts().CPlusPlus11 ?
1324  diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1325  else
1326  S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1327  }
1328  break;
1329  }
1330  }
1331  break;
1332  }
1333  case DeclSpec::TST_int128:
1334  if (!S.Context.getTargetInfo().hasInt128Type())
1335  S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported);
1337  Result = Context.UnsignedInt128Ty;
1338  else
1339  Result = Context.Int128Ty;
1340  break;
1341  case DeclSpec::TST_half: Result = Context.HalfTy; break;
1342  case DeclSpec::TST_float: Result = Context.FloatTy; break;
1343  case DeclSpec::TST_double:
1345  Result = Context.LongDoubleTy;
1346  else
1347  Result = Context.DoubleTy;
1348 
1349  if (S.getLangOpts().OpenCL &&
1350  !((S.getLangOpts().OpenCLVersion >= 120) ||
1351  S.getOpenCLOptions().cl_khr_fp64)) {
1352  S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1353  << Result << "cl_khr_fp64";
1354  declarator.setInvalidType(true);
1355  }
1356  break;
1357  case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
1358  case DeclSpec::TST_decimal32: // _Decimal32
1359  case DeclSpec::TST_decimal64: // _Decimal64
1360  case DeclSpec::TST_decimal128: // _Decimal128
1361  S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1362  Result = Context.IntTy;
1363  declarator.setInvalidType(true);
1364  break;
1365  case DeclSpec::TST_class:
1366  case DeclSpec::TST_enum:
1367  case DeclSpec::TST_union:
1368  case DeclSpec::TST_struct:
1369  case DeclSpec::TST_interface: {
1370  TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
1371  if (!D) {
1372  // This can happen in C++ with ambiguous lookups.
1373  Result = Context.IntTy;
1374  declarator.setInvalidType(true);
1375  break;
1376  }
1377 
1378  // If the type is deprecated or unavailable, diagnose it.
1380 
1381  assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1382  DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
1383 
1384  // TypeQuals handled by caller.
1385  Result = Context.getTypeDeclType(D);
1386 
1387  // In both C and C++, make an ElaboratedType.
1388  ElaboratedTypeKeyword Keyword
1390  Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
1391  break;
1392  }
1393  case DeclSpec::TST_typename: {
1394  assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1395  DS.getTypeSpecSign() == 0 &&
1396  "Can't handle qualifiers on typedef names yet!");
1397  Result = S.GetTypeFromParser(DS.getRepAsType());
1398  if (Result.isNull()) {
1399  declarator.setInvalidType(true);
1400  } else if (S.getLangOpts().OpenCL) {
1401  if (Result->getAs<AtomicType>()) {
1402  StringRef TypeName = Result.getBaseTypeIdentifier()->getName();
1403  bool NoExtTypes =
1404  llvm::StringSwitch<bool>(TypeName)
1405  .Cases("atomic_int", "atomic_uint", "atomic_float",
1406  "atomic_flag", true)
1407  .Default(false);
1408  if (!S.getOpenCLOptions().cl_khr_int64_base_atomics && !NoExtTypes) {
1409  S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1410  << Result << "cl_khr_int64_base_atomics";
1411  declarator.setInvalidType(true);
1412  }
1413  if (!S.getOpenCLOptions().cl_khr_int64_extended_atomics &&
1414  !NoExtTypes) {
1415  S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1416  << Result << "cl_khr_int64_extended_atomics";
1417  declarator.setInvalidType(true);
1418  }
1419  if (!S.getOpenCLOptions().cl_khr_fp64 &&
1420  !TypeName.compare("atomic_double")) {
1421  S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1422  << Result << "cl_khr_fp64";
1423  declarator.setInvalidType(true);
1424  }
1425  } else if (!S.getOpenCLOptions().cl_khr_gl_msaa_sharing &&
1426  (Result->isImage2dMSAAT() || Result->isImage2dArrayMSAAT() ||
1427  Result->isImage2dArrayMSAATDepth() ||
1428  Result->isImage2dMSAATDepth())) {
1429  S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1430  << Result << "cl_khr_gl_msaa_sharing";
1431  declarator.setInvalidType(true);
1432  }
1433  }
1434 
1435  // TypeQuals handled by caller.
1436  break;
1437  }
1439  // FIXME: Preserve type source info.
1440  Result = S.GetTypeFromParser(DS.getRepAsType());
1441  assert(!Result.isNull() && "Didn't get a type for typeof?");
1442  if (!Result->isDependentType())
1443  if (const TagType *TT = Result->getAs<TagType>())
1444  S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1445  // TypeQuals handled by caller.
1446  Result = Context.getTypeOfType(Result);
1447  break;
1448  case DeclSpec::TST_typeofExpr: {
1449  Expr *E = DS.getRepAsExpr();
1450  assert(E && "Didn't get an expression for typeof?");
1451  // TypeQuals handled by caller.
1452  Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1453  if (Result.isNull()) {
1454  Result = Context.IntTy;
1455  declarator.setInvalidType(true);
1456  }
1457  break;
1458  }
1459  case DeclSpec::TST_decltype: {
1460  Expr *E = DS.getRepAsExpr();
1461  assert(E && "Didn't get an expression for decltype?");
1462  // TypeQuals handled by caller.
1463  Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1464  if (Result.isNull()) {
1465  Result = Context.IntTy;
1466  declarator.setInvalidType(true);
1467  }
1468  break;
1469  }
1471  Result = S.GetTypeFromParser(DS.getRepAsType());
1472  assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1473  Result = S.BuildUnaryTransformType(Result,
1475  DS.getTypeSpecTypeLoc());
1476  if (Result.isNull()) {
1477  Result = Context.IntTy;
1478  declarator.setInvalidType(true);
1479  }
1480  break;
1481 
1482  case DeclSpec::TST_auto:
1483  // TypeQuals handled by caller.
1484  // If auto is mentioned in a lambda parameter context, convert it to a
1485  // template parameter type immediately, with the appropriate depth and
1486  // index, and update sema's state (LambdaScopeInfo) for the current lambda
1487  // being analyzed (which tracks the invented type template parameter).
1488  if (declarator.getContext() == Declarator::LambdaExprParameterContext) {
1490  assert(LSI && "No LambdaScopeInfo on the stack!");
1491  const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
1492  const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
1493  const bool IsParameterPack = declarator.hasEllipsis();
1494 
1495  // Turns out we must create the TemplateTypeParmDecl here to
1496  // retrieve the corresponding template parameter type.
1497  TemplateTypeParmDecl *CorrespondingTemplateParam =
1499  // Temporarily add to the TranslationUnit DeclContext. When the
1500  // associated TemplateParameterList is attached to a template
1501  // declaration (such as FunctionTemplateDecl), the DeclContext
1502  // for each template parameter gets updated appropriately via
1503  // a call to AdoptTemplateParameterList.
1504  Context.getTranslationUnitDecl(),
1505  /*KeyLoc*/ SourceLocation(),
1506  /*NameLoc*/ declarator.getLocStart(),
1507  TemplateParameterDepth,
1508  AutoParameterPosition, // our template param index
1509  /* Identifier*/ nullptr, false, IsParameterPack);
1510  LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
1511  // Replace the 'auto' in the function parameter with this invented
1512  // template type parameter.
1513  Result = QualType(CorrespondingTemplateParam->getTypeForDecl(), 0);
1514  } else {
1515  Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
1516  }
1517  break;
1518 
1520  Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1521  break;
1522 
1525  /*IsDependent*/ false);
1526  break;
1527 
1529  Result = Context.UnknownAnyTy;
1530  break;
1531 
1532  case DeclSpec::TST_atomic:
1533  Result = S.GetTypeFromParser(DS.getRepAsType());
1534  assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1535  Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1536  if (Result.isNull()) {
1537  Result = Context.IntTy;
1538  declarator.setInvalidType(true);
1539  }
1540  break;
1541 
1542  case DeclSpec::TST_error:
1543  Result = Context.IntTy;
1544  declarator.setInvalidType(true);
1545  break;
1546  }
1547 
1548  // Handle complex types.
1550  if (S.getLangOpts().Freestanding)
1551  S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1552  Result = Context.getComplexType(Result);
1553  } else if (DS.isTypeAltiVecVector()) {
1554  unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1555  assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1557  if (DS.isTypeAltiVecPixel())
1558  VecKind = VectorType::AltiVecPixel;
1559  else if (DS.isTypeAltiVecBool())
1560  VecKind = VectorType::AltiVecBool;
1561  Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1562  }
1563 
1564  // FIXME: Imaginary.
1566  S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1567 
1568  // Before we process any type attributes, synthesize a block literal
1569  // function declarator if necessary.
1570  if (declarator.getContext() == Declarator::BlockLiteralContext)
1571  maybeSynthesizeBlockSignature(state, Result);
1572 
1573  // Apply any type attributes from the decl spec. This may cause the
1574  // list of type attributes to be temporarily saved while the type
1575  // attributes are pushed around.
1576  // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1577  if (!DS.isTypeSpecPipe())
1578  processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes().getList());
1579 
1580  // Apply const/volatile/restrict qualifiers to T.
1581  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1582  // Warn about CV qualifiers on function types.
1583  // C99 6.7.3p8:
1584  // If the specification of a function type includes any type qualifiers,
1585  // the behavior is undefined.
1586  // C++11 [dcl.fct]p7:
1587  // The effect of a cv-qualifier-seq in a function declarator is not the
1588  // same as adding cv-qualification on top of the function type. In the
1589  // latter case, the cv-qualifiers are ignored.
1590  if (TypeQuals && Result->isFunctionType()) {
1592  S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1593  S.getLangOpts().CPlusPlus
1594  ? diag::warn_typecheck_function_qualifiers_ignored
1595  : diag::warn_typecheck_function_qualifiers_unspecified);
1596  // No diagnostic for 'restrict' or '_Atomic' applied to a
1597  // function type; we'll diagnose those later, in BuildQualifiedType.
1598  }
1599 
1600  // C++11 [dcl.ref]p1:
1601  // Cv-qualified references are ill-formed except when the
1602  // cv-qualifiers are introduced through the use of a typedef-name
1603  // or decltype-specifier, in which case the cv-qualifiers are ignored.
1604  //
1605  // There don't appear to be any other contexts in which a cv-qualified
1606  // reference type could be formed, so the 'ill-formed' clause here appears
1607  // to never happen.
1608  if (TypeQuals && Result->isReferenceType()) {
1610  S, DS, TypeQuals, Result,
1612  diag::warn_typecheck_reference_qualifiers);
1613  }
1614 
1615  // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1616  // than once in the same specifier-list or qualifier-list, either directly
1617  // or via one or more typedefs."
1618  if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1619  && TypeQuals & Result.getCVRQualifiers()) {
1620  if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1621  S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1622  << "const";
1623  }
1624 
1625  if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1626  S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1627  << "volatile";
1628  }
1629 
1630  // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1631  // produce a warning in this case.
1632  }
1633 
1634  QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1635 
1636  // If adding qualifiers fails, just use the unqualified type.
1637  if (Qualified.isNull())
1638  declarator.setInvalidType(true);
1639  else
1640  Result = Qualified;
1641  }
1642 
1643  assert(!Result.isNull() && "This function should not return a null type");
1644  return Result;
1645 }
1646 
1647 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1648  if (Entity)
1649  return Entity.getAsString();
1650 
1651  return "type name";
1652 }
1653 
1655  Qualifiers Qs, const DeclSpec *DS) {
1656  if (T.isNull())
1657  return QualType();
1658 
1659  // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1660  // object or incomplete types shall not be restrict-qualified."
1661  if (Qs.hasRestrict()) {
1662  unsigned DiagID = 0;
1663  QualType ProblemTy;
1664 
1665  if (T->isAnyPointerType() || T->isReferenceType() ||
1666  T->isMemberPointerType()) {
1667  QualType EltTy;
1668  if (T->isObjCObjectPointerType())
1669  EltTy = T;
1670  else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1671  EltTy = PTy->getPointeeType();
1672  else
1673  EltTy = T->getPointeeType();
1674 
1675  // If we have a pointer or reference, the pointee must have an object
1676  // incomplete type.
1677  if (!EltTy->isIncompleteOrObjectType()) {
1678  DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1679  ProblemTy = EltTy;
1680  }
1681  } else if (!T->isDependentType()) {
1682  DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1683  ProblemTy = T;
1684  }
1685 
1686  if (DiagID) {
1687  Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1688  Qs.removeRestrict();
1689  }
1690  }
1691 
1692  return Context.getQualifiedType(T, Qs);
1693 }
1694 
1696  unsigned CVRA, const DeclSpec *DS) {
1697  if (T.isNull())
1698  return QualType();
1699 
1700  // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic.
1701  unsigned CVR = CVRA & ~DeclSpec::TQ_atomic;
1702 
1703  // C11 6.7.3/5:
1704  // If the same qualifier appears more than once in the same
1705  // specifier-qualifier-list, either directly or via one or more typedefs,
1706  // the behavior is the same as if it appeared only once.
1707  //
1708  // It's not specified what happens when the _Atomic qualifier is applied to
1709  // a type specified with the _Atomic specifier, but we assume that this
1710  // should be treated as if the _Atomic qualifier appeared multiple times.
1711  if (CVRA & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1712  // C11 6.7.3/5:
1713  // If other qualifiers appear along with the _Atomic qualifier in a
1714  // specifier-qualifier-list, the resulting type is the so-qualified
1715  // atomic type.
1716  //
1717  // Don't need to worry about array types here, since _Atomic can't be
1718  // applied to such types.
1720  T = BuildAtomicType(QualType(Split.Ty, 0),
1721  DS ? DS->getAtomicSpecLoc() : Loc);
1722  if (T.isNull())
1723  return T;
1724  Split.Quals.addCVRQualifiers(CVR);
1725  return BuildQualifiedType(T, Loc, Split.Quals);
1726  }
1727 
1728  return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR), DS);
1729 }
1730 
1731 /// \brief Build a paren type including \p T.
1733  return Context.getParenType(T);
1734 }
1735 
1736 /// Given that we're building a pointer or reference to the given
1738  SourceLocation loc,
1739  bool isReference) {
1740  // Bail out if retention is unrequired or already specified.
1741  if (!type->isObjCLifetimeType() ||
1743  return type;
1744 
1746 
1747  // If the object type is const-qualified, we can safely use
1748  // __unsafe_unretained. This is safe (because there are no read
1749  // barriers), and it'll be safe to coerce anything but __weak* to
1750  // the resulting type.
1751  if (type.isConstQualified()) {
1752  implicitLifetime = Qualifiers::OCL_ExplicitNone;
1753 
1754  // Otherwise, check whether the static type does not require
1755  // retaining. This currently only triggers for Class (possibly
1756  // protocol-qualifed, and arrays thereof).
1757  } else if (type->isObjCARCImplicitlyUnretainedType()) {
1758  implicitLifetime = Qualifiers::OCL_ExplicitNone;
1759 
1760  // If we are in an unevaluated context, like sizeof, skip adding a
1761  // qualification.
1762  } else if (S.isUnevaluatedContext()) {
1763  return type;
1764 
1765  // If that failed, give an error and recover using __strong. __strong
1766  // is the option most likely to prevent spurious second-order diagnostics,
1767  // like when binding a reference to a field.
1768  } else {
1769  // These types can show up in private ivars in system headers, so
1770  // we need this to not be an error in those cases. Instead we
1771  // want to delay.
1775  diag::err_arc_indirect_no_ownership, type, isReference));
1776  } else {
1777  S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1778  }
1779  implicitLifetime = Qualifiers::OCL_Strong;
1780  }
1781  assert(implicitLifetime && "didn't infer any lifetime!");
1782 
1783  Qualifiers qs;
1784  qs.addObjCLifetime(implicitLifetime);
1785  return S.Context.getQualifiedType(type, qs);
1786 }
1787 
1788 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1789  std::string Quals =
1790  Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1791 
1792  switch (FnTy->getRefQualifier()) {
1793  case RQ_None:
1794  break;
1795 
1796  case RQ_LValue:
1797  if (!Quals.empty())
1798  Quals += ' ';
1799  Quals += '&';
1800  break;
1801 
1802  case RQ_RValue:
1803  if (!Quals.empty())
1804  Quals += ' ';
1805  Quals += "&&";
1806  break;
1807  }
1808 
1809  return Quals;
1810 }
1811 
1812 namespace {
1813 /// Kinds of declarator that cannot contain a qualified function type.
1814 ///
1815 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1816 /// a function type with a cv-qualifier or a ref-qualifier can only appear
1817 /// at the topmost level of a type.
1818 ///
1819 /// Parens and member pointers are permitted. We don't diagnose array and
1820 /// function declarators, because they don't allow function types at all.
1821 ///
1822 /// The values of this enum are used in diagnostics.
1823 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1824 }
1825 
1826 /// Check whether the type T is a qualified function type, and if it is,
1827 /// diagnose that it cannot be contained within the given kind of declarator.
1829  QualifiedFunctionKind QFK) {
1830  // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1831  const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1832  if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None))
1833  return false;
1834 
1835  S.Diag(Loc, diag::err_compound_qualified_function_type)
1836  << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1838  return true;
1839 }
1840 
1841 /// \brief Build a pointer type.
1842 ///
1843 /// \param T The type to which we'll be building a pointer.
1844 ///
1845 /// \param Loc The location of the entity whose type involves this
1846 /// pointer type or, if there is no such entity, the location of the
1847 /// type that will have pointer type.
1848 ///
1849 /// \param Entity The name of the entity that involves the pointer
1850 /// type, if known.
1851 ///
1852 /// \returns A suitable pointer type, if there are no
1853 /// errors. Otherwise, returns a NULL type.
1855  SourceLocation Loc, DeclarationName Entity) {
1856  if (T->isReferenceType()) {
1857  // C++ 8.3.2p4: There shall be no ... pointers to references ...
1858  Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1859  << getPrintableNameForEntity(Entity) << T;
1860  return QualType();
1861  }
1862 
1863  if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1864  return QualType();
1865 
1866  assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1867 
1868  // In ARC, it is forbidden to build pointers to unqualified pointers.
1869  if (getLangOpts().ObjCAutoRefCount)
1870  T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1871 
1872  // Build the pointer type.
1873  return Context.getPointerType(T);
1874 }
1875 
1876 /// \brief Build a reference type.
1877 ///
1878 /// \param T The type to which we'll be building a reference.
1879 ///
1880 /// \param Loc The location of the entity whose type involves this
1881 /// reference type or, if there is no such entity, the location of the
1882 /// type that will have reference type.
1883 ///
1884 /// \param Entity The name of the entity that involves the reference
1885 /// type, if known.
1886 ///
1887 /// \returns A suitable reference type, if there are no
1888 /// errors. Otherwise, returns a NULL type.
1890  SourceLocation Loc,
1891  DeclarationName Entity) {
1892  assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1893  "Unresolved overloaded function type");
1894 
1895  // C++0x [dcl.ref]p6:
1896  // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1897  // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1898  // type T, an attempt to create the type "lvalue reference to cv TR" creates
1899  // the type "lvalue reference to T", while an attempt to create the type
1900  // "rvalue reference to cv TR" creates the type TR.
1901  bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1902 
1903  // C++ [dcl.ref]p4: There shall be no references to references.
1904  //
1905  // According to C++ DR 106, references to references are only
1906  // diagnosed when they are written directly (e.g., "int & &"),
1907  // but not when they happen via a typedef:
1908  //
1909  // typedef int& intref;
1910  // typedef intref& intref2;
1911  //
1912  // Parser::ParseDeclaratorInternal diagnoses the case where
1913  // references are written directly; here, we handle the
1914  // collapsing of references-to-references as described in C++0x.
1915  // DR 106 and 540 introduce reference-collapsing into C++98/03.
1916 
1917  // C++ [dcl.ref]p1:
1918  // A declarator that specifies the type "reference to cv void"
1919  // is ill-formed.
1920  if (T->isVoidType()) {
1921  Diag(Loc, diag::err_reference_to_void);
1922  return QualType();
1923  }
1924 
1925  if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1926  return QualType();
1927 
1928  // In ARC, it is forbidden to build references to unqualified pointers.
1929  if (getLangOpts().ObjCAutoRefCount)
1930  T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1931 
1932  // Handle restrict on references.
1933  if (LValueRef)
1934  return Context.getLValueReferenceType(T, SpelledAsLValue);
1935  return Context.getRValueReferenceType(T);
1936 }
1937 
1938 /// \brief Build a Pipe type.
1939 ///
1940 /// \param T The type to which we'll be building a Pipe.
1941 ///
1942 /// \param Loc We do not use it for now.
1943 ///
1944 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
1945 /// NULL type.
1947  assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1948 
1949  // Build the pipe type.
1950  return Context.getPipeType(T);
1951 }
1952 
1953 /// Check whether the specified array size makes the array type a VLA. If so,
1954 /// return true, if not, return the size of the array in SizeVal.
1955 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1956  // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1957  // (like gnu99, but not c99) accept any evaluatable value as an extension.
1958  class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1959  public:
1960  VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
1961 
1962  void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
1963  }
1964 
1965  void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
1966  S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
1967  }
1968  } Diagnoser;
1969 
1970  return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
1971  S.LangOpts.GNUMode).isInvalid();
1972 }
1973 
1974 
1975 /// \brief Build an array type.
1976 ///
1977 /// \param T The type of each element in the array.
1978 ///
1979 /// \param ASM C99 array size modifier (e.g., '*', 'static').
1980 ///
1981 /// \param ArraySize Expression describing the size of the array.
1982 ///
1983 /// \param Brackets The range from the opening '[' to the closing ']'.
1984 ///
1985 /// \param Entity The name of the entity that involves the array
1986 /// type, if known.
1987 ///
1988 /// \returns A suitable array type, if there are no errors. Otherwise,
1989 /// returns a NULL type.
1991  Expr *ArraySize, unsigned Quals,
1992  SourceRange Brackets, DeclarationName Entity) {
1993 
1994  SourceLocation Loc = Brackets.getBegin();
1995  if (getLangOpts().CPlusPlus) {
1996  // C++ [dcl.array]p1:
1997  // T is called the array element type; this type shall not be a reference
1998  // type, the (possibly cv-qualified) type void, a function type or an
1999  // abstract class type.
2000  //
2001  // C++ [dcl.array]p3:
2002  // When several "array of" specifications are adjacent, [...] only the
2003  // first of the constant expressions that specify the bounds of the arrays
2004  // may be omitted.
2005  //
2006  // Note: function types are handled in the common path with C.
2007  if (T->isReferenceType()) {
2008  Diag(Loc, diag::err_illegal_decl_array_of_references)
2009  << getPrintableNameForEntity(Entity) << T;
2010  return QualType();
2011  }
2012 
2013  if (T->isVoidType() || T->isIncompleteArrayType()) {
2014  Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
2015  return QualType();
2016  }
2017 
2018  if (RequireNonAbstractType(Brackets.getBegin(), T,
2019  diag::err_array_of_abstract_type))
2020  return QualType();
2021 
2022  // Mentioning a member pointer type for an array type causes us to lock in
2023  // an inheritance model, even if it's inside an unused typedef.
2025  if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2026  if (!MPTy->getClass()->isDependentType())
2027  (void)isCompleteType(Loc, T);
2028 
2029  } else {
2030  // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2031  // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2032  if (RequireCompleteType(Loc, T,
2033  diag::err_illegal_decl_array_incomplete_type))
2034  return QualType();
2035  }
2036 
2037  if (T->isFunctionType()) {
2038  Diag(Loc, diag::err_illegal_decl_array_of_functions)
2039  << getPrintableNameForEntity(Entity) << T;
2040  return QualType();
2041  }
2042 
2043  if (const RecordType *EltTy = T->getAs<RecordType>()) {
2044  // If the element type is a struct or union that contains a variadic
2045  // array, accept it as a GNU extension: C99 6.7.2.1p2.
2046  if (EltTy->getDecl()->hasFlexibleArrayMember())
2047  Diag(Loc, diag::ext_flexible_array_in_array) << T;
2048  } else if (T->isObjCObjectType()) {
2049  Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2050  return QualType();
2051  }
2052 
2053  // Do placeholder conversions on the array size expression.
2054  if (ArraySize && ArraySize->hasPlaceholderType()) {
2055  ExprResult Result = CheckPlaceholderExpr(ArraySize);
2056  if (Result.isInvalid()) return QualType();
2057  ArraySize = Result.get();
2058  }
2059 
2060  // Do lvalue-to-rvalue conversions on the array size expression.
2061  if (ArraySize && !ArraySize->isRValue()) {
2063  if (Result.isInvalid())
2064  return QualType();
2065 
2066  ArraySize = Result.get();
2067  }
2068 
2069  // C99 6.7.5.2p1: The size expression shall have integer type.
2070  // C++11 allows contextual conversions to such types.
2071  if (!getLangOpts().CPlusPlus11 &&
2072  ArraySize && !ArraySize->isTypeDependent() &&
2073  !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2074  Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2075  << ArraySize->getType() << ArraySize->getSourceRange();
2076  return QualType();
2077  }
2078 
2079  llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2080  if (!ArraySize) {
2081  if (ASM == ArrayType::Star)
2082  T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2083  else
2084  T = Context.getIncompleteArrayType(T, ASM, Quals);
2085  } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2086  T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2087  } else if ((!T->isDependentType() && !T->isIncompleteType() &&
2088  !T->isConstantSizeType()) ||
2089  isArraySizeVLA(*this, ArraySize, ConstVal)) {
2090  // Even in C++11, don't allow contextual conversions in the array bound
2091  // of a VLA.
2092  if (getLangOpts().CPlusPlus11 &&
2093  !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2094  Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2095  << ArraySize->getType() << ArraySize->getSourceRange();
2096  return QualType();
2097  }
2098 
2099  // C99: an array with an element type that has a non-constant-size is a VLA.
2100  // C99: an array with a non-ICE size is a VLA. We accept any expression
2101  // that we can fold to a non-zero positive value as an extension.
2102  T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2103  } else {
2104  // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2105  // have a value greater than zero.
2106  if (ConstVal.isSigned() && ConstVal.isNegative()) {
2107  if (Entity)
2108  Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
2109  << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
2110  else
2111  Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
2112  << ArraySize->getSourceRange();
2113  return QualType();
2114  }
2115  if (ConstVal == 0) {
2116  // GCC accepts zero sized static arrays. We allow them when
2117  // we're not in a SFINAE context.
2118  Diag(ArraySize->getLocStart(),
2119  isSFINAEContext()? diag::err_typecheck_zero_array_size
2120  : diag::ext_typecheck_zero_array_size)
2121  << ArraySize->getSourceRange();
2122 
2123  if (ASM == ArrayType::Static) {
2124  Diag(ArraySize->getLocStart(),
2125  diag::warn_typecheck_zero_static_array_size)
2126  << ArraySize->getSourceRange();
2127  ASM = ArrayType::Normal;
2128  }
2129  } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
2130  !T->isIncompleteType() && !T->isUndeducedType()) {
2131  // Is the array too large?
2132  unsigned ActiveSizeBits
2134  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2135  Diag(ArraySize->getLocStart(), diag::err_array_too_large)
2136  << ConstVal.toString(10)
2137  << ArraySize->getSourceRange();
2138  return QualType();
2139  }
2140  }
2141 
2142  T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
2143  }
2144 
2145  // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2146  if (getLangOpts().OpenCL && T->isVariableArrayType()) {
2147  Diag(Loc, diag::err_opencl_vla);
2148  return QualType();
2149  }
2150  // If this is not C99, extwarn about VLA's and C99 array size modifiers.
2151  if (!getLangOpts().C99) {
2152  if (T->isVariableArrayType()) {
2153  // Prohibit the use of non-POD types in VLAs.
2154  QualType BaseT = Context.getBaseElementType(T);
2155  if (!T->isDependentType() && isCompleteType(Loc, BaseT) &&
2156  !BaseT.isPODType(Context) && !BaseT->isObjCLifetimeType()) {
2157  Diag(Loc, diag::err_vla_non_pod) << BaseT;
2158  return QualType();
2159  }
2160  // Prohibit the use of VLAs during template argument deduction.
2161  else if (isSFINAEContext()) {
2162  Diag(Loc, diag::err_vla_in_sfinae);
2163  return QualType();
2164  }
2165  // Just extwarn about VLAs.
2166  else
2167  Diag(Loc, diag::ext_vla);
2168  } else if (ASM != ArrayType::Normal || Quals != 0)
2169  Diag(Loc,
2170  getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
2171  : diag::ext_c99_array_usage) << ASM;
2172  }
2173 
2174  if (T->isVariableArrayType()) {
2175  // Warn about VLAs for -Wvla.
2176  Diag(Loc, diag::warn_vla_used);
2177  }
2178 
2179  return T;
2180 }
2181 
2182 /// \brief Build an ext-vector type.
2183 ///
2184 /// Run the required checks for the extended vector type.
2186  SourceLocation AttrLoc) {
2187  // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2188  // in conjunction with complex types (pointers, arrays, functions, etc.).
2189  if (!T->isDependentType() &&
2190  !T->isIntegerType() && !T->isRealFloatingType()) {
2191  Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2192  return QualType();
2193  }
2194 
2195  if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2196  llvm::APSInt vecSize(32);
2197  if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
2198  Diag(AttrLoc, diag::err_attribute_argument_type)
2199  << "ext_vector_type" << AANT_ArgumentIntegerConstant
2200  << ArraySize->getSourceRange();
2201  return QualType();
2202  }
2203 
2204  // unlike gcc's vector_size attribute, the size is specified as the
2205  // number of elements, not the number of bytes.
2206  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
2207 
2208  if (vectorSize == 0) {
2209  Diag(AttrLoc, diag::err_attribute_zero_size)
2210  << ArraySize->getSourceRange();
2211  return QualType();
2212  }
2213 
2214  if (VectorType::isVectorSizeTooLarge(vectorSize)) {
2215  Diag(AttrLoc, diag::err_attribute_size_too_large)
2216  << ArraySize->getSourceRange();
2217  return QualType();
2218  }
2219 
2220  return Context.getExtVectorType(T, vectorSize);
2221  }
2222 
2223  return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2224 }
2225 
2227  if (T->isArrayType() || T->isFunctionType()) {
2228  Diag(Loc, diag::err_func_returning_array_function)
2229  << T->isFunctionType() << T;
2230  return true;
2231  }
2232 
2233  // Functions cannot return half FP.
2234  if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2235  Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2236  FixItHint::CreateInsertion(Loc, "*");
2237  return true;
2238  }
2239 
2240  // Methods cannot return interface types. All ObjC objects are
2241  // passed by reference.
2242  if (T->isObjCObjectType()) {
2243  Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T;
2244  return 0;
2245  }
2246 
2247  return false;
2248 }
2249 
2251  MutableArrayRef<QualType> ParamTypes,
2252  SourceLocation Loc, DeclarationName Entity,
2253  const FunctionProtoType::ExtProtoInfo &EPI) {
2254  bool Invalid = false;
2255 
2256  Invalid |= CheckFunctionReturnType(T, Loc);
2257 
2258  for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2259  // FIXME: Loc is too inprecise here, should use proper locations for args.
2260  QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2261  if (ParamType->isVoidType()) {
2262  Diag(Loc, diag::err_param_with_void_type);
2263  Invalid = true;
2264  } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2265  // Disallow half FP arguments.
2266  Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2267  FixItHint::CreateInsertion(Loc, "*");
2268  Invalid = true;
2269  }
2270 
2271  ParamTypes[Idx] = ParamType;
2272  }
2273 
2274  if (Invalid)
2275  return QualType();
2276 
2277  return Context.getFunctionType(T, ParamTypes, EPI);
2278 }
2279 
2280 /// \brief Build a member pointer type \c T Class::*.
2281 ///
2282 /// \param T the type to which the member pointer refers.
2283 /// \param Class the class type into which the member pointer points.
2284 /// \param Loc the location where this type begins
2285 /// \param Entity the name of the entity that will have this member pointer type
2286 ///
2287 /// \returns a member pointer type, if successful, or a NULL type if there was
2288 /// an error.
2290  SourceLocation Loc,
2291  DeclarationName Entity) {
2292  // Verify that we're not building a pointer to pointer to function with
2293  // exception specification.
2294  if (CheckDistantExceptionSpec(T)) {
2295  Diag(Loc, diag::err_distant_exception_spec);
2296  return QualType();
2297  }
2298 
2299  // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2300  // with reference type, or "cv void."
2301  if (T->isReferenceType()) {
2302  Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2303  << getPrintableNameForEntity(Entity) << T;
2304  return QualType();
2305  }
2306 
2307  if (T->isVoidType()) {
2308  Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2309  << getPrintableNameForEntity(Entity);
2310  return QualType();
2311  }
2312 
2313  if (!Class->isDependentType() && !Class->isRecordType()) {
2314  Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2315  return QualType();
2316  }
2317 
2318  // Adjust the default free function calling convention to the default method
2319  // calling convention.
2320  bool IsCtorOrDtor =
2323  if (T->isFunctionType())
2324  adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2325 
2326  return Context.getMemberPointerType(T, Class.getTypePtr());
2327 }
2328 
2329 /// \brief Build a block pointer type.
2330 ///
2331 /// \param T The type to which we'll be building a block pointer.
2332 ///
2333 /// \param Loc The source location, used for diagnostics.
2334 ///
2335 /// \param Entity The name of the entity that involves the block pointer
2336 /// type, if known.
2337 ///
2338 /// \returns A suitable block pointer type, if there are no
2339 /// errors. Otherwise, returns a NULL type.
2341  SourceLocation Loc,
2342  DeclarationName Entity) {
2343  if (!T->isFunctionType()) {
2344  Diag(Loc, diag::err_nonfunction_block_type);
2345  return QualType();
2346  }
2347 
2348  if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2349  return QualType();
2350 
2351  return Context.getBlockPointerType(T);
2352 }
2353 
2355  QualType QT = Ty.get();
2356  if (QT.isNull()) {
2357  if (TInfo) *TInfo = nullptr;
2358  return QualType();
2359  }
2360 
2361  TypeSourceInfo *DI = nullptr;
2362  if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2363  QT = LIT->getType();
2364  DI = LIT->getTypeSourceInfo();
2365  }
2366 
2367  if (TInfo) *TInfo = DI;
2368  return QT;
2369 }
2370 
2371 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2372  Qualifiers::ObjCLifetime ownership,
2373  unsigned chunkIndex);
2374 
2375 /// Given that this is the declaration of a parameter under ARC,
2376 /// attempt to infer attributes and such for pointer-to-whatever
2377 /// types.
2378 static void inferARCWriteback(TypeProcessingState &state,
2379  QualType &declSpecType) {
2380  Sema &S = state.getSema();
2381  Declarator &declarator = state.getDeclarator();
2382 
2383  // TODO: should we care about decl qualifiers?
2384 
2385  // Check whether the declarator has the expected form. We walk
2386  // from the inside out in order to make the block logic work.
2387  unsigned outermostPointerIndex = 0;
2388  bool isBlockPointer = false;
2389  unsigned numPointers = 0;
2390  for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2391  unsigned chunkIndex = i;
2392  DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2393  switch (chunk.Kind) {
2395  // Ignore parens.
2396  break;
2397 
2400  // Count the number of pointers. Treat references
2401  // interchangeably as pointers; if they're mis-ordered, normal
2402  // type building will discover that.
2403  outermostPointerIndex = chunkIndex;
2404  numPointers++;
2405  break;
2406 
2408  // If we have a pointer to block pointer, that's an acceptable
2409  // indirect reference; anything else is not an application of
2410  // the rules.
2411  if (numPointers != 1) return;
2412  numPointers++;
2413  outermostPointerIndex = chunkIndex;
2414  isBlockPointer = true;
2415 
2416  // We don't care about pointer structure in return values here.
2417  goto done;
2418 
2419  case DeclaratorChunk::Array: // suppress if written (id[])?
2422  case DeclaratorChunk::Pipe:
2423  return;
2424  }
2425  }
2426  done:
2427 
2428  // If we have *one* pointer, then we want to throw the qualifier on
2429  // the declaration-specifiers, which means that it needs to be a
2430  // retainable object type.
2431  if (numPointers == 1) {
2432  // If it's not a retainable object type, the rule doesn't apply.
2433  if (!declSpecType->isObjCRetainableType()) return;
2434 
2435  // If it already has lifetime, don't do anything.
2436  if (declSpecType.getObjCLifetime()) return;
2437 
2438  // Otherwise, modify the type in-place.
2439  Qualifiers qs;
2440 
2441  if (declSpecType->isObjCARCImplicitlyUnretainedType())
2443  else
2445  declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2446 
2447  // If we have *two* pointers, then we want to throw the qualifier on
2448  // the outermost pointer.
2449  } else if (numPointers == 2) {
2450  // If we don't have a block pointer, we need to check whether the
2451  // declaration-specifiers gave us something that will turn into a
2452  // retainable object pointer after we slap the first pointer on it.
2453  if (!isBlockPointer && !declSpecType->isObjCObjectType())
2454  return;
2455 
2456  // Look for an explicit lifetime attribute there.
2457  DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2458  if (chunk.Kind != DeclaratorChunk::Pointer &&
2460  return;
2461  for (const AttributeList *attr = chunk.getAttrs(); attr;
2462  attr = attr->getNext())
2463  if (attr->getKind() == AttributeList::AT_ObjCOwnership)
2464  return;
2465 
2467  outermostPointerIndex);
2468 
2469  // Any other number of pointers/references does not trigger the rule.
2470  } else return;
2471 
2472  // TODO: mark whether we did this inference?
2473 }
2474 
2475 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2476  SourceLocation FallbackLoc,
2477  SourceLocation ConstQualLoc,
2478  SourceLocation VolatileQualLoc,
2479  SourceLocation RestrictQualLoc,
2480  SourceLocation AtomicQualLoc) {
2481  if (!Quals)
2482  return;
2483 
2484  struct Qual {
2485  const char *Name;
2486  unsigned Mask;
2487  SourceLocation Loc;
2488  } const QualKinds[4] = {
2489  { "const", DeclSpec::TQ_const, ConstQualLoc },
2490  { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2491  { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2492  { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2493  };
2494 
2495  SmallString<32> QualStr;
2496  unsigned NumQuals = 0;
2497  SourceLocation Loc;
2498  FixItHint FixIts[4];
2499 
2500  // Build a string naming the redundant qualifiers.
2501  for (unsigned I = 0; I != 4; ++I) {
2502  if (Quals & QualKinds[I].Mask) {
2503  if (!QualStr.empty()) QualStr += ' ';
2504  QualStr += QualKinds[I].Name;
2505 
2506  // If we have a location for the qualifier, offer a fixit.
2507  SourceLocation QualLoc = QualKinds[I].Loc;
2508  if (QualLoc.isValid()) {
2509  FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2510  if (Loc.isInvalid() ||
2512  Loc = QualLoc;
2513  }
2514 
2515  ++NumQuals;
2516  }
2517  }
2518 
2519  Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2520  << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2521 }
2522 
2523 // Diagnose pointless type qualifiers on the return type of a function.
2525  Declarator &D,
2526  unsigned FunctionChunkIndex) {
2527  if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2528  // FIXME: TypeSourceInfo doesn't preserve location information for
2529  // qualifiers.
2530  S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2531  RetTy.getLocalCVRQualifiers(),
2532  D.getIdentifierLoc());
2533  return;
2534  }
2535 
2536  for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2537  End = D.getNumTypeObjects();
2538  OuterChunkIndex != End; ++OuterChunkIndex) {
2539  DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2540  switch (OuterChunk.Kind) {
2542  continue;
2543 
2544  case DeclaratorChunk::Pointer: {
2545  DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2547  diag::warn_qual_return_type,
2548  PTI.TypeQuals,
2549  SourceLocation(),
2554  return;
2555  }
2556 
2562  case DeclaratorChunk::Pipe:
2563  // FIXME: We can't currently provide an accurate source location and a
2564  // fix-it hint for these.
2565  unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2566  S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2567  RetTy.getCVRQualifiers() | AtomicQual,
2568  D.getIdentifierLoc());
2569  return;
2570  }
2571 
2572  llvm_unreachable("unknown declarator chunk kind");
2573  }
2574 
2575  // If the qualifiers come from a conversion function type, don't diagnose
2576  // them -- they're not necessarily redundant, since such a conversion
2577  // operator can be explicitly called as "x.operator const int()".
2579  return;
2580 
2581  // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2582  // which are present there.
2583  S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2585  D.getIdentifierLoc(),
2590 }
2591 
2592 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2593  TypeSourceInfo *&ReturnTypeInfo) {
2594  Sema &SemaRef = state.getSema();
2595  Declarator &D = state.getDeclarator();
2596  QualType T;
2597  ReturnTypeInfo = nullptr;
2598 
2599  // The TagDecl owned by the DeclSpec.
2600  TagDecl *OwnedTagDecl = nullptr;
2601 
2602  switch (D.getName().getKind()) {
2608  T = ConvertDeclSpecToType(state);
2609 
2610  if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2611  OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2612  // Owned declaration is embedded in declarator.
2613  OwnedTagDecl->setEmbeddedInDeclarator(true);
2614  }
2615  break;
2616 
2620  // Constructors and destructors don't have return types. Use
2621  // "void" instead.
2622  T = SemaRef.Context.VoidTy;
2623  processTypeAttrs(state, T, TAL_DeclSpec,
2625  break;
2626 
2628  // The result type of a conversion function is the type that it
2629  // converts to.
2631  &ReturnTypeInfo);
2632  break;
2633  }
2634 
2635  if (D.getAttributes())
2637 
2638  // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2640  int Error = -1;
2641 
2642  switch (D.getContext()) {
2644  llvm_unreachable("Can't specify a type specifier in lambda grammar");
2648  Error = 0;
2649  break;
2651  // In C++14, generic lambdas allow 'auto' in their parameters.
2652  if (!(SemaRef.getLangOpts().CPlusPlus14
2654  Error = 16;
2655  break;
2659  break;
2660  bool Cxx = SemaRef.getLangOpts().CPlusPlus;
2661  switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2662  case TTK_Enum: llvm_unreachable("unhandled tag kind");
2663  case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
2664  case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
2665  case TTK_Class: Error = 5; /* Class member */ break;
2666  case TTK_Interface: Error = 6; /* Interface member */ break;
2667  }
2668  break;
2669  }
2672  Error = 7; // Exception declaration
2673  break;
2675  Error = 8; // Template parameter
2676  break;
2678  Error = 9; // Block literal
2679  break;
2681  Error = 10; // Template type argument
2682  break;
2685  Error = 12; // Type alias
2686  break;
2688  if (!SemaRef.getLangOpts().CPlusPlus14 ||
2690  Error = 13; // Function return type
2691  break;
2693  if (!SemaRef.getLangOpts().CPlusPlus14 ||
2695  Error = 14; // conversion-type-id
2696  break;
2698  Error = 15; // Generic
2699  break;
2704  break;
2707  Error = 17; // 'new' type
2708  break;
2710  Error = 18; // K&R function parameter
2711  break;
2712  }
2713 
2715  Error = 11;
2716 
2717  // In Objective-C it is an error to use 'auto' on a function declarator
2718  // (and everywhere for '__auto_type').
2719  if (D.isFunctionDeclarator() &&
2720  (!SemaRef.getLangOpts().CPlusPlus11 ||
2722  Error = 13;
2723 
2724  bool HaveTrailing = false;
2725 
2726  // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2727  // contains a trailing return type. That is only legal at the outermost
2728  // level. Check all declarator chunks (outermost first) anyway, to give
2729  // better diagnostics.
2730  // We don't support '__auto_type' with trailing return types.
2731  if (SemaRef.getLangOpts().CPlusPlus11 &&
2733  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2734  unsigned chunkIndex = e - i - 1;
2735  state.setCurrentChunkIndex(chunkIndex);
2736  DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2737  if (DeclType.Kind == DeclaratorChunk::Function) {
2738  const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2739  if (FTI.hasTrailingReturnType()) {
2740  HaveTrailing = true;
2741  Error = -1;
2742  break;
2743  }
2744  }
2745  }
2746  }
2747 
2748  SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2750  AutoRange = D.getName().getSourceRange();
2751 
2752  if (Error != -1) {
2753  unsigned Keyword;
2754  switch (D.getDeclSpec().getTypeSpecType()) {
2755  case DeclSpec::TST_auto: Keyword = 0; break;
2756  case DeclSpec::TST_decltype_auto: Keyword = 1; break;
2757  case DeclSpec::TST_auto_type: Keyword = 2; break;
2758  default: llvm_unreachable("unknown auto TypeSpecType");
2759  }
2760  SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
2761  << Keyword << Error << AutoRange;
2762  T = SemaRef.Context.IntTy;
2763  D.setInvalidType(true);
2764  } else if (!HaveTrailing) {
2765  // If there was a trailing return type, we already got
2766  // warn_cxx98_compat_trailing_return_type in the parser.
2767  SemaRef.Diag(AutoRange.getBegin(),
2768  diag::warn_cxx98_compat_auto_type_specifier)
2769  << AutoRange;
2770  }
2771  }
2772 
2773  if (SemaRef.getLangOpts().CPlusPlus &&
2774  OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
2775  // Check the contexts where C++ forbids the declaration of a new class
2776  // or enumeration in a type-specifier-seq.
2777  unsigned DiagID = 0;
2778  switch (D.getContext()) {
2780  // Class and enumeration definitions are syntactically not allowed in
2781  // trailing return types.
2782  llvm_unreachable("parser should not have allowed this");
2783  break;
2790  // C++11 [dcl.type]p3:
2791  // A type-specifier-seq shall not define a class or enumeration unless
2792  // it appears in the type-id of an alias-declaration (7.1.3) that is not
2793  // the declaration of a template-declaration.
2795  break;
2797  DiagID = diag::err_type_defined_in_alias_template;
2798  break;
2806  DiagID = diag::err_type_defined_in_type_specifier;
2807  break;
2813  // C++ [dcl.fct]p6:
2814  // Types shall not be defined in return or parameter types.
2815  DiagID = diag::err_type_defined_in_param_type;
2816  break;
2818  // C++ 6.4p2:
2819  // The type-specifier-seq shall not contain typedef and shall not declare
2820  // a new class or enumeration.
2821  DiagID = diag::err_type_defined_in_condition;
2822  break;
2823  }
2824 
2825  if (DiagID != 0) {
2826  SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
2827  << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2828  D.setInvalidType(true);
2829  }
2830  }
2831 
2832  assert(!T.isNull() && "This function should not return a null type");
2833  return T;
2834 }
2835 
2836 /// Produce an appropriate diagnostic for an ambiguity between a function
2837 /// declarator and a C++ direct-initializer.
2839  DeclaratorChunk &DeclType, QualType RT) {
2840  const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2841  assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
2842 
2843  // If the return type is void there is no ambiguity.
2844  if (RT->isVoidType())
2845  return;
2846 
2847  // An initializer for a non-class type can have at most one argument.
2848  if (!RT->isRecordType() && FTI.NumParams > 1)
2849  return;
2850 
2851  // An initializer for a reference must have exactly one argument.
2852  if (RT->isReferenceType() && FTI.NumParams != 1)
2853  return;
2854 
2855  // Only warn if this declarator is declaring a function at block scope, and
2856  // doesn't have a storage class (such as 'extern') specified.
2857  if (!D.isFunctionDeclarator() ||
2862  return;
2863 
2864  // Inside a condition, a direct initializer is not permitted. We allow one to
2865  // be parsed in order to give better diagnostics in condition parsing.
2867  return;
2868 
2869  SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
2870 
2871  S.Diag(DeclType.Loc,
2872  FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
2873  : diag::warn_empty_parens_are_function_decl)
2874  << ParenRange;
2875 
2876  // If the declaration looks like:
2877  // T var1,
2878  // f();
2879  // and name lookup finds a function named 'f', then the ',' was
2880  // probably intended to be a ';'.
2881  if (!D.isFirstDeclarator() && D.getIdentifier()) {
2884  if (Comma.getFileID() != Name.getFileID() ||
2885  Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
2888  if (S.LookupName(Result, S.getCurScope()))
2889  S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
2891  << D.getIdentifier();
2892  }
2893  }
2894 
2895  if (FTI.NumParams > 0) {
2896  // For a declaration with parameters, eg. "T var(T());", suggest adding
2897  // parens around the first parameter to turn the declaration into a
2898  // variable declaration.
2899  SourceRange Range = FTI.Params[0].Param->getSourceRange();
2900  SourceLocation B = Range.getBegin();
2902  // FIXME: Maybe we should suggest adding braces instead of parens
2903  // in C++11 for classes that don't have an initializer_list constructor.
2904  S.Diag(B, diag::note_additional_parens_for_variable_declaration)
2905  << FixItHint::CreateInsertion(B, "(")
2906  << FixItHint::CreateInsertion(E, ")");
2907  } else {
2908  // For a declaration without parameters, eg. "T var();", suggest replacing
2909  // the parens with an initializer to turn the declaration into a variable
2910  // declaration.
2911  const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
2912 
2913  // Empty parens mean value-initialization, and no parens mean
2914  // default initialization. These are equivalent if the default
2915  // constructor is user-provided or if zero-initialization is a
2916  // no-op.
2917  if (RD && RD->hasDefinition() &&
2918  (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
2919  S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
2920  << FixItHint::CreateRemoval(ParenRange);
2921  else {
2922  std::string Init =
2923  S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
2924  if (Init.empty() && S.LangOpts.CPlusPlus11)
2925  Init = "{}";
2926  if (!Init.empty())
2927  S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
2928  << FixItHint::CreateReplacement(ParenRange, Init);
2929  }
2930  }
2931 }
2932 
2933 /// Helper for figuring out the default CC for a function declarator type. If
2934 /// this is the outermost chunk, then we can determine the CC from the
2935 /// declarator context. If not, then this could be either a member function
2936 /// type or normal function type.
2937 static CallingConv
2940  unsigned ChunkIndex) {
2941  assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
2942 
2943  bool IsCXXInstanceMethod = false;
2944 
2945  if (S.getLangOpts().CPlusPlus) {
2946  // Look inwards through parentheses to see if this chunk will form a
2947  // member pointer type or if we're the declarator. Any type attributes
2948  // between here and there will override the CC we choose here.
2949  unsigned I = ChunkIndex;
2950  bool FoundNonParen = false;
2951  while (I && !FoundNonParen) {
2952  --I;
2954  FoundNonParen = true;
2955  }
2956 
2957  if (FoundNonParen) {
2958  // If we're not the declarator, we're a regular function type unless we're
2959  // in a member pointer.
2960  IsCXXInstanceMethod =
2962  } else if (D.getContext() == Declarator::LambdaExprContext) {
2963  // This can only be a call operator for a lambda, which is an instance
2964  // method.
2965  IsCXXInstanceMethod = true;
2966  } else {
2967  // We're the innermost decl chunk, so must be a function declarator.
2968  assert(D.isFunctionDeclarator());
2969 
2970  // If we're inside a record, we're declaring a method, but it could be
2971  // explicitly or implicitly static.
2972  IsCXXInstanceMethod =
2975  !D.isStaticMember();
2976  }
2977  }
2978 
2980  IsCXXInstanceMethod);
2981 
2982  // Attribute AT_OpenCLKernel affects the calling convention only on
2983  // the SPIR target, hence it cannot be treated as a calling
2984  // convention attribute. This is the simplest place to infer
2985  // "spir_kernel" for OpenCL kernels on SPIR.
2986  if (CC == CC_SpirFunction) {
2987  for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
2988  Attr; Attr = Attr->getNext()) {
2989  if (Attr->getKind() == AttributeList::AT_OpenCLKernel) {
2990  CC = CC_SpirKernel;
2991  break;
2992  }
2993  }
2994  }
2995 
2996  return CC;
2997 }
2998 
2999 namespace {
3000  /// A simple notion of pointer kinds, which matches up with the various
3001  /// pointer declarators.
3002  enum class SimplePointerKind {
3003  Pointer,
3004  BlockPointer,
3005  MemberPointer,
3006  };
3007 }
3008 
3010  switch (nullability) {
3012  if (!Ident__Nonnull)
3013  Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3014  return Ident__Nonnull;
3015 
3017  if (!Ident__Nullable)
3018  Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3019  return Ident__Nullable;
3020 
3022  if (!Ident__Null_unspecified)
3023  Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3024  return Ident__Null_unspecified;
3025  }
3026  llvm_unreachable("Unknown nullability kind.");
3027 }
3028 
3029 /// Retrieve the identifier "NSError".
3031  if (!Ident_NSError)
3032  Ident_NSError = PP.getIdentifierInfo("NSError");
3033 
3034  return Ident_NSError;
3035 }
3036 
3037 /// Check whether there is a nullability attribute of any kind in the given
3038 /// attribute list.
3039 static bool hasNullabilityAttr(const AttributeList *attrs) {
3040  for (const AttributeList *attr = attrs; attr;
3041  attr = attr->getNext()) {
3042  if (attr->getKind() == AttributeList::AT_TypeNonNull ||
3043  attr->getKind() == AttributeList::AT_TypeNullable ||
3044  attr->getKind() == AttributeList::AT_TypeNullUnspecified)
3045  return true;
3046  }
3047 
3048  return false;
3049 }
3050 
3051 namespace {
3052  /// Describes the kind of a pointer a declarator describes.
3054  // Not a pointer.
3055  NonPointer,
3056  // Single-level pointer.
3057  SingleLevelPointer,
3058  // Multi-level pointer (of any pointer kind).
3059  MultiLevelPointer,
3060  // CFFooRef*
3061  MaybePointerToCFRef,
3062  // CFErrorRef*
3063  CFErrorRefPointer,
3064  // NSError**
3065  NSErrorPointerPointer,
3066  };
3067 }
3068 
3069 /// Classify the given declarator, whose type-specified is \c type, based on
3070 /// what kind of pointer it refers to.
3071 ///
3072 /// This is used to determine the default nullability.
3074  QualType type,
3075  Declarator &declarator) {
3076  unsigned numNormalPointers = 0;
3077 
3078  // For any dependent type, we consider it a non-pointer.
3079  if (type->isDependentType())
3080  return PointerDeclaratorKind::NonPointer;
3081 
3082  // Look through the declarator chunks to identify pointers.
3083  for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3084  DeclaratorChunk &chunk = declarator.getTypeObject(i);
3085  switch (chunk.Kind) {
3088  case DeclaratorChunk::Pipe:
3089  break;
3090 
3093  return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3094  : PointerDeclaratorKind::SingleLevelPointer;
3095 
3098  continue;
3099 
3101  ++numNormalPointers;
3102  if (numNormalPointers > 2)
3103  return PointerDeclaratorKind::MultiLevelPointer;
3104  continue;
3105  }
3106  }
3107 
3108  // Then, dig into the type specifier itself.
3109  unsigned numTypeSpecifierPointers = 0;
3110  do {
3111  // Decompose normal pointers.
3112  if (auto ptrType = type->getAs<PointerType>()) {
3113  ++numNormalPointers;
3114 
3115  if (numNormalPointers > 2)
3116  return PointerDeclaratorKind::MultiLevelPointer;
3117 
3118  type = ptrType->getPointeeType();
3119  ++numTypeSpecifierPointers;
3120  continue;
3121  }
3122 
3123  // Decompose block pointers.
3124  if (type->getAs<BlockPointerType>()) {
3125  return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3126  : PointerDeclaratorKind::SingleLevelPointer;
3127  }
3128 
3129  // Decompose member pointers.
3130  if (type->getAs<MemberPointerType>()) {
3131  return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3132  : PointerDeclaratorKind::SingleLevelPointer;
3133  }
3134 
3135  // Look at Objective-C object pointers.
3136  if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3137  ++numNormalPointers;
3138  ++numTypeSpecifierPointers;
3139 
3140  // If this is NSError**, report that.
3141  if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3142  if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
3143  numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3144  return PointerDeclaratorKind::NSErrorPointerPointer;
3145  }
3146  }
3147 
3148  break;
3149  }
3150 
3151  // Look at Objective-C class types.
3152  if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3153  if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
3154  if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3155  return PointerDeclaratorKind::NSErrorPointerPointer;;
3156  }
3157 
3158  break;
3159  }
3160 
3161  // If at this point we haven't seen a pointer, we won't see one.
3162  if (numNormalPointers == 0)
3163  return PointerDeclaratorKind::NonPointer;
3164 
3165  if (auto recordType = type->getAs<RecordType>()) {
3166  RecordDecl *recordDecl = recordType->getDecl();
3167 
3168  bool isCFError = false;
3169  if (S.CFError) {
3170  // If we already know about CFError, test it directly.
3171  isCFError = (S.CFError == recordDecl);
3172  } else {
3173  // Check whether this is CFError, which we identify based on its bridge
3174  // to NSError.
3175  if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
3176  if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) {
3177  if (bridgeAttr->getBridgedType() == S.getNSErrorIdent()) {
3178  S.CFError = recordDecl;
3179  isCFError = true;
3180  }
3181  }
3182  }
3183  }
3184 
3185  // If this is CFErrorRef*, report it as such.
3186  if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3187  return PointerDeclaratorKind::CFErrorRefPointer;
3188  }
3189  break;
3190  }
3191 
3192  break;
3193  } while (true);
3194 
3195 
3196  switch (numNormalPointers) {
3197  case 0:
3198  return PointerDeclaratorKind::NonPointer;
3199 
3200  case 1:
3201  return PointerDeclaratorKind::SingleLevelPointer;
3202 
3203  case 2:
3204  return PointerDeclaratorKind::MaybePointerToCFRef;
3205 
3206  default:
3207  return PointerDeclaratorKind::MultiLevelPointer;
3208  }
3209 }
3210 
3212  SourceLocation loc) {
3213  // If we're anywhere in a function, method, or closure context, don't perform
3214  // completeness checks.
3215  for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
3216  if (ctx->isFunctionOrMethod())
3217  return FileID();
3218 
3219  if (ctx->isFileContext())
3220  break;
3221  }
3222 
3223  // We only care about the expansion location.
3224  loc = S.SourceMgr.getExpansionLoc(loc);
3225  FileID file = S.SourceMgr.getFileID(loc);
3226  if (file.isInvalid())
3227  return FileID();
3228 
3229  // Retrieve file information.
3230  bool invalid = false;
3231  const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
3232  if (invalid || !sloc.isFile())
3233  return FileID();
3234 
3235  // We don't want to perform completeness checks on the main file or in
3236  // system headers.
3237  const SrcMgr::FileInfo &fileInfo = sloc.getFile();
3238  if (fileInfo.getIncludeLoc().isInvalid())
3239  return FileID();
3240  if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
3242  return FileID();
3243  }
3244 
3245  return file;
3246 }
3247 
3248 /// Check for consistent use of nullability.
3249 static void checkNullabilityConsistency(TypeProcessingState &state,
3250  SimplePointerKind pointerKind,
3251  SourceLocation pointerLoc) {
3252  Sema &S = state.getSema();
3253 
3254  // Determine which file we're performing consistency checking for.
3255  FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
3256  if (file.isInvalid())
3257  return;
3258 
3259  // If we haven't seen any type nullability in this file, we won't warn now
3260  // about anything.
3261  FileNullability &fileNullability = S.NullabilityMap[file];
3262  if (!fileNullability.SawTypeNullability) {
3263  // If this is the first pointer declarator in the file, record it.
3264  if (fileNullability.PointerLoc.isInvalid() &&
3265  !S.Context.getDiagnostics().isIgnored(diag::warn_nullability_missing,
3266  pointerLoc)) {
3267  fileNullability.PointerLoc = pointerLoc;
3268  fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
3269  }
3270 
3271  return;
3272  }
3273 
3274  // Complain about missing nullability.
3275  S.Diag(pointerLoc, diag::warn_nullability_missing)
3276  << static_cast<unsigned>(pointerKind);
3277 }
3278 
3279 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
3280  QualType declSpecType,
3281  TypeSourceInfo *TInfo) {
3282  // The TypeSourceInfo that this function returns will not be a null type.
3283  // If there is an error, this function will fill in a dummy type as fallback.
3284  QualType T = declSpecType;
3285  Declarator &D = state.getDeclarator();
3286  Sema &S = state.getSema();
3287  ASTContext &Context = S.Context;
3288  const LangOptions &LangOpts = S.getLangOpts();
3289 
3290  // The name we're declaring, if any.
3292  if (D.getIdentifier())
3293  Name = D.getIdentifier();
3294 
3295  // Does this declaration declare a typedef-name?
3296  bool IsTypedefName =
3300 
3301  // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
3302  bool IsQualifiedFunction = T->isFunctionProtoType() &&
3303  (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
3304  T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
3305 
3306  // If T is 'decltype(auto)', the only declarators we can have are parens
3307  // and at most one function declarator if this is a function declaration.
3308  if (const AutoType *AT = T->getAs<AutoType>()) {
3309  if (AT->isDecltypeAuto()) {
3310  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3311  unsigned Index = E - I - 1;
3312  DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
3313  unsigned DiagId = diag::err_decltype_auto_compound_type;
3314  unsigned DiagKind = 0;
3315  switch (DeclChunk.Kind) {
3317  continue;
3319  unsigned FnIndex;
3320  if (D.isFunctionDeclarationContext() &&
3321  D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
3322  continue;
3323  DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
3324  break;
3325  }
3329  DiagKind = 0;
3330  break;
3332  DiagKind = 1;
3333  break;
3335  DiagKind = 2;
3336  break;
3337  case DeclaratorChunk::Pipe:
3338  break;
3339  }
3340 
3341  S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
3342  D.setInvalidType(true);
3343  break;
3344  }
3345  }
3346  }
3347 
3348  // Determine whether we should infer _Nonnull on pointer types.
3349  Optional<NullabilityKind> inferNullability;
3350  bool inferNullabilityCS = false;
3351  bool inferNullabilityInnerOnly = false;
3352  bool inferNullabilityInnerOnlyComplete = false;
3353 
3354  // Are we in an assume-nonnull region?
3355  bool inAssumeNonNullRegion = false;
3356  if (S.PP.getPragmaAssumeNonNullLoc().isValid()) {
3357  inAssumeNonNullRegion = true;
3358  // Determine which file we saw the assume-nonnull region in.
3360  S, S.PP.getPragmaAssumeNonNullLoc());
3361  if (file.isValid()) {
3362  FileNullability &fileNullability = S.NullabilityMap[file];
3363 
3364  // If we haven't seen any type nullability before, now we have.
3365  if (!fileNullability.SawTypeNullability) {
3366  if (fileNullability.PointerLoc.isValid()) {
3367  S.Diag(fileNullability.PointerLoc, diag::warn_nullability_missing)
3368  << static_cast<unsigned>(fileNullability.PointerKind);
3369  }
3370 
3371  fileNullability.SawTypeNullability = true;
3372  }
3373  }
3374  }
3375 
3376  // Whether to complain about missing nullability specifiers or not.
3377  enum {
3378  /// Never complain.
3379  CAMN_No,
3380  /// Complain on the inner pointers (but not the outermost
3381  /// pointer).
3382  CAMN_InnerPointers,
3383  /// Complain about any pointers that don't have nullability
3384  /// specified or inferred.
3385  CAMN_Yes
3386  } complainAboutMissingNullability = CAMN_No;
3387  unsigned NumPointersRemaining = 0;
3388 
3389  if (IsTypedefName) {
3390  // For typedefs, we do not infer any nullability (the default),
3391  // and we only complain about missing nullability specifiers on
3392  // inner pointers.
3393  complainAboutMissingNullability = CAMN_InnerPointers;
3394 
3395  if (T->canHaveNullability() && !T->getNullability(S.Context)) {
3396  ++NumPointersRemaining;
3397  }
3398 
3399  for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
3400  DeclaratorChunk &chunk = D.getTypeObject(i);
3401  switch (chunk.Kind) {
3404  case DeclaratorChunk::Pipe:
3405  break;
3406 
3409  ++NumPointersRemaining;
3410  break;
3411 
3414  continue;
3415 
3417  ++NumPointersRemaining;
3418  continue;
3419  }
3420  }
3421  } else {
3422  bool isFunctionOrMethod = false;
3423  switch (auto context = state.getDeclarator().getContext()) {
3428  isFunctionOrMethod = true;
3429  // fallthrough
3430 
3432  if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
3433  complainAboutMissingNullability = CAMN_No;
3434  break;
3435  }
3436 
3437  // Weak properties are inferred to be nullable.
3438  if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
3439  inferNullability = NullabilityKind::Nullable;
3440  break;
3441  }
3442 
3443  // fallthrough
3444 
3447  complainAboutMissingNullability = CAMN_Yes;
3448 
3449  // Nullability inference depends on the type and declarator.
3450  switch (classifyPointerDeclarator(S, T, D)) {
3451  case PointerDeclaratorKind::NonPointer:
3452  case PointerDeclaratorKind::MultiLevelPointer:
3453  // Cannot infer nullability.
3454  break;
3455 
3456  case PointerDeclaratorKind::SingleLevelPointer:
3457  // Infer _Nonnull if we are in an assumes-nonnull region.
3458  if (inAssumeNonNullRegion) {
3459  inferNullability = NullabilityKind::NonNull;
3460  inferNullabilityCS = (context == Declarator::ObjCParameterContext ||
3461  context == Declarator::ObjCResultContext);
3462  }
3463  break;
3464 
3465  case PointerDeclaratorKind::CFErrorRefPointer:
3466  case PointerDeclaratorKind::NSErrorPointerPointer:
3467  // Within a function or method signature, infer _Nullable at both
3468  // levels.
3469  if (isFunctionOrMethod && inAssumeNonNullRegion)
3470  inferNullability = NullabilityKind::Nullable;
3471  break;
3472 
3473  case PointerDeclaratorKind::MaybePointerToCFRef:
3474  if (isFunctionOrMethod) {
3475  // On pointer-to-pointer parameters marked cf_returns_retained or
3476  // cf_returns_not_retained, if the outer pointer is explicit then
3477  // infer the inner pointer as _Nullable.
3478  auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool {
3479  while (NextAttr) {
3480  if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained ||
3481  NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained)
3482  return true;
3483  NextAttr = NextAttr->getNext();
3484  }
3485  return false;
3486  };
3487  if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
3488  if (hasCFReturnsAttr(D.getAttributes()) ||
3489  hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
3490  hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) {
3491  inferNullability = NullabilityKind::Nullable;
3492  inferNullabilityInnerOnly = true;
3493  }
3494  }
3495  }
3496  break;
3497  }
3498  break;
3499 
3501  complainAboutMissingNullability = CAMN_Yes;
3502  break;
3503 
3518  // Don't infer in these contexts.
3519  break;
3520  }
3521  }
3522 
3523  // Local function that checks the nullability for a given pointer declarator.
3524  // Returns true if _Nonnull was inferred.
3525  auto inferPointerNullability = [&](SimplePointerKind pointerKind,
3526  SourceLocation pointerLoc,
3527  AttributeList *&attrs) -> AttributeList * {
3528  // We've seen a pointer.
3529  if (NumPointersRemaining > 0)
3530  --NumPointersRemaining;
3531 
3532  // If a nullability attribute is present, there's nothing to do.
3533  if (hasNullabilityAttr(attrs))
3534  return nullptr;
3535 
3536  // If we're supposed to infer nullability, do so now.
3537  if (inferNullability && !inferNullabilityInnerOnlyComplete) {
3538  AttributeList::Syntax syntax
3539  = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword
3541  AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool()
3542  .create(
3544  *inferNullability),
3545  SourceRange(pointerLoc),
3546  nullptr, SourceLocation(),
3547  nullptr, 0, syntax);
3548 
3549  spliceAttrIntoList(*nullabilityAttr, attrs);
3550 
3551  if (inferNullabilityCS) {
3552  state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
3553  ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
3554  }
3555 
3556  if (inferNullabilityInnerOnly)
3557  inferNullabilityInnerOnlyComplete = true;
3558  return nullabilityAttr;
3559  }
3560 
3561  // If we're supposed to complain about missing nullability, do so
3562  // now if it's truly missing.
3563  switch (complainAboutMissingNullability) {
3564  case CAMN_No:
3565  break;
3566 
3567  case CAMN_InnerPointers:
3568  if (NumPointersRemaining == 0)
3569  break;
3570  // Fallthrough.
3571 
3572  case CAMN_Yes:
3573  checkNullabilityConsistency(state, pointerKind, pointerLoc);
3574  }
3575  return nullptr;
3576  };
3577 
3578  // If the type itself could have nullability but does not, infer pointer
3579  // nullability and perform consistency checking.
3580  if (T->canHaveNullability() && S.ActiveTemplateInstantiations.empty() &&
3581  !T->getNullability(S.Context)) {
3582  SimplePointerKind pointerKind = SimplePointerKind::Pointer;
3583  if (T->isBlockPointerType())
3584  pointerKind = SimplePointerKind::BlockPointer;
3585  else if (T->isMemberPointerType())
3586  pointerKind = SimplePointerKind::MemberPointer;
3587 
3588  if (auto *attr = inferPointerNullability(
3589  pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
3591  T = Context.getAttributedType(
3592  AttributedType::getNullabilityAttrKind(*inferNullability), T, T);
3593  attr->setUsedAsTypeAttr();
3594  }
3595  }
3596 
3597  // Walk the DeclTypeInfo, building the recursive type as we go.
3598  // DeclTypeInfos are ordered from the identifier out, which is
3599  // opposite of what we want :).
3600  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3601  unsigned chunkIndex = e - i - 1;
3602  state.setCurrentChunkIndex(chunkIndex);
3603  DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
3604  IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
3605  switch (DeclType.Kind) {
3607  T = S.BuildParenType(T);
3608  break;
3610  // If blocks are disabled, emit an error.
3611  if (!LangOpts.Blocks)
3612  S.Diag(DeclType.Loc, diag::err_blocks_disable);
3613 
3614  // Handle pointer nullability.
3615  inferPointerNullability(SimplePointerKind::BlockPointer,
3616  DeclType.Loc, DeclType.getAttrListRef());
3617 
3619  if (DeclType.Cls.TypeQuals)
3620  T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
3621  break;
3623  // Verify that we're not building a pointer to pointer to function with
3624  // exception specification.
3625  if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3626  S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3627  D.setInvalidType(true);
3628  // Build the type anyway.
3629  }
3630 
3631  // Handle pointer nullability
3632  inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
3633  DeclType.getAttrListRef());
3634 
3635  if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
3636  T = Context.getObjCObjectPointerType(T);
3637  if (DeclType.Ptr.TypeQuals)
3638  T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
3639  break;
3640  }
3641  T = S.BuildPointerType(T, DeclType.Loc, Name);
3642  if (DeclType.Ptr.TypeQuals)
3643  T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
3644 
3645  break;
3647  // Verify that we're not building a reference to pointer to function with
3648  // exception specification.
3649  if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3650  S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3651  D.setInvalidType(true);
3652  // Build the type anyway.
3653  }
3654  T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
3655 
3656  if (DeclType.Ref.HasRestrict)
3657  T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
3658  break;
3659  }
3660  case DeclaratorChunk::Array: {
3661  // Verify that we're not building an array of pointers to function with
3662  // exception specification.
3663  if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3664  S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3665  D.setInvalidType(true);
3666  // Build the type anyway.
3667  }
3668  DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
3669  Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
3671  if (ATI.isStar)
3672  ASM = ArrayType::Star;
3673  else if (ATI.hasStatic)
3674  ASM = ArrayType::Static;
3675  else
3676  ASM = ArrayType::Normal;
3677  if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
3678  // FIXME: This check isn't quite right: it allows star in prototypes
3679  // for function definitions, and disallows some edge cases detailed
3680  // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
3681  S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
3682  ASM = ArrayType::Normal;
3683  D.setInvalidType(true);
3684  }
3685 
3686  // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
3687  // shall appear only in a declaration of a function parameter with an
3688  // array type, ...
3689  if (ASM == ArrayType::Static || ATI.TypeQuals) {
3690  if (!(D.isPrototypeContext() ||
3692  S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
3693  (ASM == ArrayType::Static ? "'static'" : "type qualifier");
3694  // Remove the 'static' and the type qualifiers.
3695  if (ASM == ArrayType::Static)
3696  ASM = ArrayType::Normal;
3697  ATI.TypeQuals = 0;
3698  D.setInvalidType(true);
3699  }
3700 
3701  // C99 6.7.5.2p1: ... and then only in the outermost array type
3702  // derivation.
3703  unsigned x = chunkIndex;
3704  while (x != 0) {
3705  // Walk outwards along the declarator chunks.
3706  x--;
3707  const DeclaratorChunk &DC = D.getTypeObject(x);
3708  switch (DC.Kind) {
3710  continue;
3715  S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
3716  (ASM == ArrayType::Static ? "'static'" : "type qualifier");
3717  if (ASM == ArrayType::Static)
3718  ASM = ArrayType::Normal;
3719  ATI.TypeQuals = 0;
3720  D.setInvalidType(true);
3721  break;
3724  case DeclaratorChunk::Pipe:
3725  // These are invalid anyway, so just ignore.
3726  break;
3727  }
3728  }
3729  }
3730  const AutoType *AT = T->getContainedAutoType();
3731  // Allow arrays of auto if we are a generic lambda parameter.
3732  // i.e. [](auto (&array)[5]) { return array[0]; }; OK
3734  // We've already diagnosed this for decltype(auto).
3735  if (!AT->isDecltypeAuto())
3736  S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
3737  << getPrintableNameForEntity(Name) << T;
3738  T = QualType();
3739  break;
3740  }
3741 
3742  T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
3743  SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
3744  break;
3745  }
3747  // If the function declarator has a prototype (i.e. it is not () and
3748  // does not have a K&R-style identifier list), then the arguments are part
3749  // of the type, otherwise the argument list is ().
3750  const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3751  IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
3752 
3753  // Check for auto functions and trailing return type and adjust the
3754  // return type accordingly.
3755  if (!D.isInvalidType()) {
3756  // trailing-return-type is only required if we're declaring a function,
3757  // and not, for instance, a pointer to a function.
3759  !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
3760  !S.getLangOpts().CPlusPlus14) {
3763  ? diag::err_auto_missing_trailing_return
3764  : diag::err_deduced_return_type);
3765  T = Context.IntTy;
3766  D.setInvalidType(true);
3767  } else if (FTI.hasTrailingReturnType()) {
3768  // T must be exactly 'auto' at this point. See CWG issue 681.
3769  if (isa<ParenType>(T)) {
3771  diag::err_trailing_return_in_parens)
3772  << T << D.getDeclSpec().getSourceRange();
3773  D.setInvalidType(true);
3774  } else if (D.getContext() != Declarator::LambdaExprContext &&
3775  (T.hasQualifiers() || !isa<AutoType>(T) ||
3776  cast<AutoType>(T)->getKeyword() != AutoTypeKeyword::Auto)) {
3778  diag::err_trailing_return_without_auto)
3779  << T << D.getDeclSpec().getSourceRange();
3780  D.setInvalidType(true);
3781  }
3782  T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
3783  if (T.isNull()) {
3784  // An error occurred parsing the trailing return type.
3785  T = Context.IntTy;
3786  D.setInvalidType(true);
3787  }
3788  }
3789  }
3790 
3791  // C99 6.7.5.3p1: The return type may not be a function or array type.
3792  // For conversion functions, we'll diagnose this particular error later.
3793  if ((T->isArrayType() || T->isFunctionType()) &&
3795  unsigned diagID = diag::err_func_returning_array_function;
3796  // Last processing chunk in block context means this function chunk
3797  // represents the block.
3798  if (chunkIndex == 0 &&
3800  diagID = diag::err_block_returning_array_function;
3801  S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
3802  T = Context.IntTy;
3803  D.setInvalidType(true);
3804  }
3805 
3806  // Do not allow returning half FP value.
3807  // FIXME: This really should be in BuildFunctionType.
3808  if (T->isHalfType()) {
3809  if (S.getLangOpts().OpenCL) {
3810  if (!S.getOpenCLOptions().cl_khr_fp16) {
3811  S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T;
3812  D.setInvalidType(true);
3813  }
3814  } else if (!S.getLangOpts().HalfArgsAndReturns) {
3815  S.Diag(D.getIdentifierLoc(),
3816  diag::err_parameters_retval_cannot_have_fp16_type) << 1;
3817  D.setInvalidType(true);
3818  }
3819  }
3820 
3821  // Methods cannot return interface types. All ObjC objects are
3822  // passed by reference.
3823  if (T->isObjCObjectType()) {
3824  SourceLocation DiagLoc, FixitLoc;
3825  if (TInfo) {
3826  DiagLoc = TInfo->getTypeLoc().getLocStart();
3827  FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
3828  } else {
3829  DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
3830  FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
3831  }
3832  S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
3833  << 0 << T
3834  << FixItHint::CreateInsertion(FixitLoc, "*");
3835 
3836  T = Context.getObjCObjectPointerType(T);
3837  if (TInfo) {
3838  TypeLocBuilder TLB;
3839  TLB.pushFullCopy(TInfo->getTypeLoc());
3841  TLoc.setStarLoc(FixitLoc);
3842  TInfo = TLB.getTypeSourceInfo(Context, T);
3843  }
3844 
3845  D.setInvalidType(true);
3846  }
3847 
3848  // cv-qualifiers on return types are pointless except when the type is a
3849  // class type in C++.
3850  if ((T.getCVRQualifiers() || T->isAtomicType()) &&
3851  !(S.getLangOpts().CPlusPlus &&
3852  (T->isDependentType() || T->isRecordType()))) {
3853  if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
3855  // [6.9.1/3] qualified void return is invalid on a C
3856  // function definition. Apparently ok on declarations and
3857  // in C++ though (!)
3858  S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
3859  } else
3860  diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
3861  }
3862 
3863  // Objective-C ARC ownership qualifiers are ignored on the function
3864  // return type (by type canonicalization). Complain if this attribute
3865  // was written here.
3866  if (T.getQualifiers().hasObjCLifetime()) {
3867  SourceLocation AttrLoc;
3868  if (chunkIndex + 1 < D.getNumTypeObjects()) {
3869  DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
3870  for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
3871  Attr; Attr = Attr->getNext()) {
3872  if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
3873  AttrLoc = Attr->getLoc();
3874  break;
3875  }
3876  }
3877  }
3878  if (AttrLoc.isInvalid()) {
3879  for (const AttributeList *Attr
3880  = D.getDeclSpec().getAttributes().getList();
3881  Attr; Attr = Attr->getNext()) {
3882  if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
3883  AttrLoc = Attr->getLoc();
3884  break;
3885  }
3886  }
3887  }
3888 
3889  if (AttrLoc.isValid()) {
3890  // The ownership attributes are almost always written via
3891  // the predefined
3892  // __strong/__weak/__autoreleasing/__unsafe_unretained.
3893  if (AttrLoc.isMacroID())
3894  AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
3895 
3896  S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
3897  << T.getQualifiers().getObjCLifetime();
3898  }
3899  }
3900 
3901  if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
3902  // C++ [dcl.fct]p6:
3903  // Types shall not be defined in return or parameter types.
3904  TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3905  S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
3906  << Context.getTypeDeclType(Tag);
3907  }
3908 
3909  // Exception specs are not allowed in typedefs. Complain, but add it
3910  // anyway.
3911  if (IsTypedefName && FTI.getExceptionSpecType())
3912  S.Diag(FTI.getExceptionSpecLocBeg(),
3913  diag::err_exception_spec_in_typedef)
3916 
3917  // If we see "T var();" or "T var(T());" at block scope, it is probably
3918  // an attempt to initialize a variable, not a function declaration.
3919  if (FTI.isAmbiguous)
3920  warnAboutAmbiguousFunction(S, D, DeclType, T);
3921 
3922  FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
3923 
3924  if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) {
3925  // Simple void foo(), where the incoming T is the result type.
3926  T = Context.getFunctionNoProtoType(T, EI);
3927  } else {
3928  // We allow a zero-parameter variadic function in C if the
3929  // function is marked with the "overloadable" attribute. Scan
3930  // for this attribute now.
3931  if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
3932  bool Overloadable = false;
3933  for (const AttributeList *Attrs = D.getAttributes();
3934  Attrs; Attrs = Attrs->getNext()) {
3935  if (Attrs->getKind() == AttributeList::AT_Overloadable) {
3936  Overloadable = true;
3937  break;
3938  }
3939  }
3940 
3941  if (!Overloadable)
3942  S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
3943  }
3944 
3945  if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
3946  // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
3947  // definition.
3948  S.Diag(FTI.Params[0].IdentLoc,
3949  diag::err_ident_list_in_fn_declaration);
3950  D.setInvalidType(true);
3951  // Recover by creating a K&R-style function type.
3952  T = Context.getFunctionNoProtoType(T, EI);
3953  break;
3954  }
3955 
3957  EPI.ExtInfo = EI;
3958  EPI.Variadic = FTI.isVariadic;
3960  EPI.TypeQuals = FTI.TypeQuals;
3961  EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
3963  : RQ_RValue;
3964 
3965  // Otherwise, we have a function with a parameter list that is
3966  // potentially variadic.
3967  SmallVector<QualType, 16> ParamTys;
3968  ParamTys.reserve(FTI.NumParams);
3969 
3970  SmallVector<bool, 16> ConsumedParameters;
3971  ConsumedParameters.reserve(FTI.NumParams);
3972  bool HasAnyConsumedParameters = false;
3973 
3974  for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
3975  ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
3976  QualType ParamTy = Param->getType();
3977  assert(!ParamTy.isNull() && "Couldn't parse type?");
3978 
3979  // Look for 'void'. void is allowed only as a single parameter to a
3980  // function with no other parameters (C99 6.7.5.3p10). We record
3981  // int(void) as a FunctionProtoType with an empty parameter list.
3982  if (ParamTy->isVoidType()) {
3983  // If this is something like 'float(int, void)', reject it. 'void'
3984  // is an incomplete type (C99 6.2.5p19) and function decls cannot
3985  // have parameters of incomplete type.
3986  if (FTI.NumParams != 1 || FTI.isVariadic) {
3987  S.Diag(DeclType.Loc, diag::err_void_only_param);
3988  ParamTy = Context.IntTy;
3989  Param->setType(ParamTy);
3990  } else if (FTI.Params[i].Ident) {
3991  // Reject, but continue to parse 'int(void abc)'.
3992  S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
3993  ParamTy = Context.IntTy;
3994  Param->setType(ParamTy);
3995  } else {
3996  // Reject, but continue to parse 'float(const void)'.
3997  if (ParamTy.hasQualifiers())
3998  S.Diag(DeclType.Loc, diag::err_void_param_qualified);
3999 
4000  // Do not add 'void' to the list.
4001  break;
4002  }
4003  } else if (ParamTy->isHalfType()) {
4004  // Disallow half FP parameters.
4005  // FIXME: This really should be in BuildFunctionType.
4006  if (S.getLangOpts().OpenCL) {
4007  if (!S.getOpenCLOptions().cl_khr_fp16) {
4008  S.Diag(Param->getLocation(),
4009  diag::err_opencl_half_param) << ParamTy;
4010  D.setInvalidType();
4011  Param->setInvalidDecl();
4012  }
4013  } else if (!S.getLangOpts().HalfArgsAndReturns) {
4014  S.Diag(Param->getLocation(),
4015  diag::err_parameters_retval_cannot_have_fp16_type) << 0;
4016  D.setInvalidType();
4017  }
4018  } else if (!FTI.hasPrototype) {
4019  if (ParamTy->isPromotableIntegerType()) {
4020  ParamTy = Context.getPromotedIntegerType(ParamTy);
4021  Param->setKNRPromoted(true);
4022  } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
4023  if (BTy->getKind() == BuiltinType::Float) {
4024  ParamTy = Context.DoubleTy;
4025  Param->setKNRPromoted(true);
4026  }
4027  }
4028  }
4029 
4030  if (LangOpts.ObjCAutoRefCount) {
4031  bool Consumed = Param->hasAttr<NSConsumedAttr>();
4032  ConsumedParameters.push_back(Consumed);
4033  HasAnyConsumedParameters |= Consumed;
4034  }
4035 
4036  ParamTys.push_back(ParamTy);
4037  }
4038 
4039  if (HasAnyConsumedParameters)
4040  EPI.ConsumedParameters = ConsumedParameters.data();
4041 
4042  SmallVector<QualType, 4> Exceptions;
4043  SmallVector<ParsedType, 2> DynamicExceptions;
4044  SmallVector<SourceRange, 2> DynamicExceptionRanges;
4045  Expr *NoexceptExpr = nullptr;
4046 
4047  if (FTI.getExceptionSpecType() == EST_Dynamic) {
4048  // FIXME: It's rather inefficient to have to split into two vectors
4049  // here.
4050  unsigned N = FTI.NumExceptions;
4051  DynamicExceptions.reserve(N);
4052  DynamicExceptionRanges.reserve(N);
4053  for (unsigned I = 0; I != N; ++I) {
4054  DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
4055  DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
4056  }
4057  } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
4058  NoexceptExpr = FTI.NoexceptExpr;
4059  }
4060 
4062  FTI.getExceptionSpecType(),
4063  DynamicExceptions,
4064  DynamicExceptionRanges,
4065  NoexceptExpr,
4066  Exceptions,
4067  EPI.ExceptionSpec);
4068 
4069  T = Context.getFunctionType(T, ParamTys, EPI);
4070  }
4071 
4072  break;
4073  }
4075  // The scope spec must refer to a class, or be dependent.
4076  CXXScopeSpec &SS = DeclType.Mem.Scope();
4077  QualType ClsType;
4078 
4079  // Handle pointer nullability.
4080  inferPointerNullability(SimplePointerKind::MemberPointer,
4081  DeclType.Loc, DeclType.getAttrListRef());
4082 
4083  if (SS.isInvalid()) {
4084  // Avoid emitting extra errors if we already errored on the scope.
4085  D.setInvalidType(true);
4086  } else if (S.isDependentScopeSpecifier(SS) ||
4087  dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
4088  NestedNameSpecifier *NNS = SS.getScopeRep();
4089  NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
4090  switch (NNS->getKind()) {
4092  ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
4093  NNS->getAsIdentifier());
4094  break;
4095 
4100  llvm_unreachable("Nested-name-specifier must name a type");
4101 
4104  ClsType = QualType(NNS->getAsType(), 0);
4105  // Note: if the NNS has a prefix and ClsType is a nondependent
4106  // TemplateSpecializationType, then the NNS prefix is NOT included
4107  // in ClsType; hence we wrap ClsType into an ElaboratedType.
4108  // NOTE: in particular, no wrap occurs if ClsType already is an
4109  // Elaborated, DependentName, or DependentTemplateSpecialization.
4110  if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
4111  ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
4112  break;
4113  }
4114  } else {
4115  S.Diag(DeclType.Mem.Scope().getBeginLoc(),
4116  diag::err_illegal_decl_mempointer_in_nonclass)
4117  << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
4118  << DeclType.Mem.Scope().getRange();
4119  D.setInvalidType(true);
4120  }
4121 
4122  if (!ClsType.isNull())
4123  T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
4124  D.getIdentifier());
4125  if (T.isNull()) {
4126  T = Context.IntTy;
4127  D.setInvalidType(true);
4128  } else if (DeclType.Mem.TypeQuals) {
4129  T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
4130  }
4131  break;
4132  }
4133 
4134  case DeclaratorChunk::Pipe: {
4135  T = S.BuildPipeType(T, DeclType.Loc );
4136  break;
4137  }
4138  }
4139 
4140  if (T.isNull()) {
4141  D.setInvalidType(true);
4142  T = Context.IntTy;
4143  }
4144 
4145  // See if there are any attributes on this declarator chunk.
4146  processTypeAttrs(state, T, TAL_DeclChunk,
4147  const_cast<AttributeList *>(DeclType.getAttrs()));
4148  }
4149 
4150  assert(!T.isNull() && "T must not be null after this point");
4151 
4152  if (LangOpts.CPlusPlus && T->isFunctionType()) {
4153  const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
4154  assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
4155 
4156  // C++ 8.3.5p4:
4157  // A cv-qualifier-seq shall only be part of the function type
4158  // for a nonstatic member function, the function type to which a pointer
4159  // to member refers, or the top-level function type of a function typedef
4160  // declaration.
4161  //
4162  // Core issue 547 also allows cv-qualifiers on function types that are
4163  // top-level template type arguments.
4164  bool FreeFunction;
4165  if (!D.getCXXScopeSpec().isSet()) {
4166  FreeFunction = ((D.getContext() != Declarator::MemberContext &&
4169  } else {
4171  FreeFunction = (DC && !DC->isRecord());
4172  }
4173 
4174  // C++11 [dcl.fct]p6 (w/DR1417):
4175  // An attempt to specify a function type with a cv-qualifier-seq or a
4176  // ref-qualifier (including by typedef-name) is ill-formed unless it is:
4177  // - the function type for a non-static member function,
4178  // - the function type to which a pointer to member refers,
4179  // - the top-level function type of a function typedef declaration or
4180  // alias-declaration,
4181  // - the type-id in the default argument of a type-parameter, or
4182  // - the type-id of a template-argument for a type-parameter
4183  //
4184  // FIXME: Checking this here is insufficient. We accept-invalid on:
4185  //
4186  // template<typename T> struct S { void f(T); };
4187  // S<int() const> s;
4188  //
4189  // ... for instance.
4190  if (IsQualifiedFunction &&
4191  !(!FreeFunction &&
4193  !IsTypedefName &&
4195  SourceLocation Loc = D.getLocStart();
4196  SourceRange RemovalRange;
4197  unsigned I;
4198  if (D.isFunctionDeclarator(I)) {
4199  SmallVector<SourceLocation, 4> RemovalLocs;
4200  const DeclaratorChunk &Chunk = D.getTypeObject(I);
4201  assert(Chunk.Kind == DeclaratorChunk::Function);
4202  if (Chunk.Fun.hasRefQualifier())
4203  RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
4204  if (Chunk.Fun.TypeQuals & Qualifiers::Const)
4205  RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
4206  if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
4207  RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
4208  if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
4209  RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
4210  if (!RemovalLocs.empty()) {
4211  std::sort(RemovalLocs.begin(), RemovalLocs.end(),
4213  RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
4214  Loc = RemovalLocs.front();
4215  }
4216  }
4217 
4218  S.Diag(Loc, diag::err_invalid_qualified_function_type)
4219  << FreeFunction << D.isFunctionDeclarator() << T
4221  << FixItHint::CreateRemoval(RemovalRange);
4222 
4223  // Strip the cv-qualifiers and ref-qualifiers from the type.
4225  EPI.TypeQuals = 0;
4226  EPI.RefQualifier = RQ_None;
4227 
4228  T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
4229  EPI);
4230  // Rebuild any parens around the identifier in the function type.
4231  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4233  break;
4234  T = S.BuildParenType(T);
4235  }
4236  }
4237  }
4238 
4239  // Apply any undistributed attributes from the declarator.
4241 
4242  // Diagnose any ignored type attributes.
4243  state.diagnoseIgnoredTypeAttrs(T);
4244 
4245  // C++0x [dcl.constexpr]p9:
4246  // A constexpr specifier used in an object declaration declares the object
4247  // as const.
4248  if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
4249  T.addConst();
4250  }
4251 
4252  // If there was an ellipsis in the declarator, the declaration declares a
4253  // parameter pack whose type may be a pack expansion type.
4254  if (D.hasEllipsis()) {
4255  // C++0x [dcl.fct]p13:
4256  // A declarator-id or abstract-declarator containing an ellipsis shall
4257  // only be used in a parameter-declaration. Such a parameter-declaration
4258  // is a parameter pack (14.5.3). [...]
4259  switch (D.getContext()) {
4262  // C++0x [dcl.fct]p13:
4263  // [...] When it is part of a parameter-declaration-clause, the
4264  // parameter pack is a function parameter pack (14.5.3). The type T
4265  // of the declarator-id of the function parameter pack shall contain
4266  // a template parameter pack; each template parameter pack in T is
4267  // expanded by the function parameter pack.
4268  //
4269  // We represent function parameter packs as function parameters whose
4270  // type is a pack expansion.
4271  if (!T->containsUnexpandedParameterPack()) {
4272  S.Diag(D.getEllipsisLoc(),
4273  diag::err_function_parameter_pack_without_parameter_packs)
4274  << T << D.getSourceRange();
4276  } else {
4277  T = Context.getPackExpansionType(T, None);
4278  }
4279  break;
4281  // C++0x [temp.param]p15:
4282  // If a template-parameter is a [...] is a parameter-declaration that
4283  // declares a parameter pack (8.3.5), then the template-parameter is a
4284  // template parameter pack (14.5.3).
4285  //
4286  // Note: core issue 778 clarifies that, if there are any unexpanded
4287  // parameter packs in the type of the non-type template parameter, then
4288  // it expands those parameter packs.
4290  T = Context.getPackExpansionType(T, None);
4291  else
4292  S.Diag(D.getEllipsisLoc(),
4293  LangOpts.CPlusPlus11
4294  ? diag::warn_cxx98_compat_variadic_templates
4295  : diag::ext_variadic_templates);
4296  break;
4297 
4300  case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
4301  case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
4317  // FIXME: We may want to allow parameter packs in block-literal contexts
4318  // in the future.
4319  S.Diag(D.getEllipsisLoc(),
4320  diag::err_ellipsis_in_declarator_not_parameter);
4322  break;
4323  }
4324  }
4325 
4326  assert(!T.isNull() && "T must not be null at the end of this function");
4327  if (D.isInvalidType())
4328  return Context.getTrivialTypeSourceInfo(T);
4329 
4330  return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
4331 }
4332 
4333 /// GetTypeForDeclarator - Convert the type for the specified
4334 /// declarator to Type instances.
4335 ///
4336 /// The result of this call will never be null, but the associated
4337 /// type may be a null type if there's an unrecoverable error.
4339  // Determine the type of the declarator. Not all forms of declarator
4340  // have a type.
4341 
4342  TypeProcessingState state(*this, D);
4343 
4344  TypeSourceInfo *ReturnTypeInfo = nullptr;
4345  QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4346 
4347  if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
4348  inferARCWriteback(state, T);
4349 
4350  return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
4351 }
4352 
4354  QualType &declSpecTy,
4355  Qualifiers::ObjCLifetime ownership) {
4356  if (declSpecTy->isObjCRetainableType() &&
4357  declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
4358  Qualifiers qs;
4359  qs.addObjCLifetime(ownership);
4360  declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
4361  }
4362 }
4363 
4364 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
4365  Qualifiers::ObjCLifetime ownership,
4366  unsigned chunkIndex) {
4367  Sema &S = state.getSema();
4368  Declarator &D = state.getDeclarator();
4369 
4370  // Look for an explicit lifetime attribute.
4371  DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
4372  for (const AttributeList *attr = chunk.getAttrs(); attr;
4373  attr = attr->getNext())
4374  if (attr->getKind() == AttributeList::AT_ObjCOwnership)
4375  return;
4376 
4377  const char *attrStr = nullptr;
4378  switch (ownership) {
4379  case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
4380  case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
4381  case Qualifiers::OCL_Strong: attrStr = "strong"; break;
4382  case Qualifiers::OCL_Weak: attrStr = "weak"; break;
4383  case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
4384  }
4385 
4386  IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
4387  Arg->Ident = &S.Context.Idents.get(attrStr);
4388  Arg->Loc = SourceLocation();
4389 
4390  ArgsUnion Args(Arg);
4391 
4392  // If there wasn't one, add one (with an invalid source location
4393  // so that we don't make an AttributedType for it).
4394  AttributeList *attr = D.getAttributePool()
4395  .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
4396  /*scope*/ nullptr, SourceLocation(),
4397  /*args*/ &Args, 1, AttributeList::AS_GNU);
4398  spliceAttrIntoList(*attr, chunk.getAttrListRef());
4399 
4400  // TODO: mark whether we did this inference?
4401 }
4402 
4403 /// \brief Used for transferring ownership in casts resulting in l-values.
4404 static void transferARCOwnership(TypeProcessingState &state,
4405  QualType &declSpecTy,
4406  Qualifiers::ObjCLifetime ownership) {
4407  Sema &S = state.getSema();
4408  Declarator &D = state.getDeclarator();
4409 
4410  int inner = -1;
4411  bool hasIndirection = false;
4412  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4413  DeclaratorChunk &chunk = D.getTypeObject(i);
4414  switch (chunk.Kind) {
4416  // Ignore parens.
4417  break;
4418 
4422  if (inner != -1)
4423  hasIndirection = true;
4424  inner = i;
4425  break;
4426 
4428  if (inner != -1)
4429  transferARCOwnershipToDeclaratorChunk(state, ownership, i);
4430  return;
4431 
4434  case DeclaratorChunk::Pipe:
4435  return;
4436  }
4437  }
4438 
4439  if (inner == -1)
4440  return;
4441 
4442  DeclaratorChunk &chunk = D.getTypeObject(inner);
4443  if (chunk.Kind == DeclaratorChunk::Pointer) {
4444  if (declSpecTy->isObjCRetainableType())
4445  return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4446  if (declSpecTy->isObjCObjectType() && hasIndirection)
4447  return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
4448  } else {
4449  assert(chunk.Kind == DeclaratorChunk::Array ||
4450  chunk.Kind == DeclaratorChunk::Reference);
4451  return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4452  }
4453 }
4454 
4456  TypeProcessingState state(*this, D);
4457 
4458  TypeSourceInfo *ReturnTypeInfo = nullptr;
4459  QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4460 
4461  if (getLangOpts().ObjC1) {
4463  if (ownership != Qualifiers::OCL_None)
4464  transferARCOwnership(state, declSpecTy, ownership);
4465  }
4466 
4467  return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
4468 }
4469 
4470 /// Map an AttributedType::Kind to an AttributeList::Kind.
4472  switch (kind) {
4474  return AttributeList::AT_AddressSpace;
4476  return AttributeList::AT_Regparm;
4478  return AttributeList::AT_VectorSize;
4480  return AttributeList::AT_NeonVectorType;
4482  return AttributeList::AT_NeonPolyVectorType;
4484  return AttributeList::AT_ObjCGC;
4487  return AttributeList::AT_ObjCOwnership;
4489  return AttributeList::AT_NoReturn;
4491  return AttributeList::AT_CDecl;
4493  return AttributeList::AT_FastCall;
4495  return AttributeList::AT_StdCall;
4497  return AttributeList::AT_ThisCall;
4499  return AttributeList::AT_Pascal;
4501  return AttributeList::AT_VectorCall;
4504  return AttributeList::AT_Pcs;
4506  return AttributeList::AT_IntelOclBicc;
4508  return AttributeList::AT_MSABI;
4510  return AttributeList::AT_SysVABI;
4512  return AttributeList::AT_Ptr32;
4514  return AttributeList::AT_Ptr64;
4516  return AttributeList::AT_SPtr;
4518  return AttributeList::AT_UPtr;
4520  return AttributeList::AT_TypeNonNull;
4522  return AttributeList::AT_TypeNullable;
4524  return AttributeList::AT_TypeNullUnspecified;
4526  return AttributeList::AT_ObjCKindOf;
4527  }
4528  llvm_unreachable("unexpected attribute kind!");
4529 }
4530 
4532  const AttributeList *attrs,
4533  const AttributeList *DeclAttrs = nullptr) {
4534  // DeclAttrs and attrs cannot be both empty.
4535  assert((attrs || DeclAttrs) &&
4536  "no type attributes in the expected location!");
4537 
4538  AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind());
4539  // Try to search for an attribute of matching kind in attrs list.
4540  while (attrs && attrs->getKind() != parsedKind)
4541  attrs = attrs->getNext();
4542  if (!attrs) {
4543  // No matching type attribute in attrs list found.
4544  // Try searching through C++11 attributes in the declarator attribute list.
4545  while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() ||
4546  DeclAttrs->getKind() != parsedKind))
4547  DeclAttrs = DeclAttrs->getNext();
4548  attrs = DeclAttrs;
4549  }
4550 
4551  assert(attrs && "no matching type attribute in expected location!");
4552 
4553  TL.setAttrNameLoc(attrs->getLoc());
4554  if (TL.hasAttrExprOperand()) {
4555  assert(attrs->isArgExpr(0) && "mismatched attribute operand kind");
4556  TL.setAttrExprOperand(attrs->getArgAsExpr(0));
4557  } else if (TL.hasAttrEnumOperand()) {
4558  assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&
4559  "unexpected attribute operand kind");
4560  if (attrs->isArgIdent(0))
4561  TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
4562  else
4564  }
4565 
4566  // FIXME: preserve this information to here.
4567  if (TL.hasAttrOperand())
4569 }
4570 
4571 namespace {
4572  class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
4574  const DeclSpec &DS;
4575 
4576  public:
4577  TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
4578  : Context(Context), DS(DS) {}
4579 
4580  void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4582  Visit(TL.getModifiedLoc());
4583  }
4584  void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4585  Visit(TL.getUnqualifiedLoc());
4586  }
4587  void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
4588  TL.setNameLoc(DS.getTypeSpecTypeLoc());
4589  }
4590  void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
4591  TL.setNameLoc(DS.getTypeSpecTypeLoc());
4592  // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
4593  // addition field. What we have is good enough for dispay of location
4594  // of 'fixit' on interface name.
4595  TL.setNameEndLoc(DS.getLocEnd());
4596  }
4597  void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
4598  TypeSourceInfo *RepTInfo = nullptr;
4599  Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
4600  TL.copy(RepTInfo->getTypeLoc());
4601  }
4602  void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4603  TypeSourceInfo *RepTInfo = nullptr;
4604  Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
4605  TL.copy(RepTInfo->getTypeLoc());
4606  }
4607  void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
4608  TypeSourceInfo *TInfo = nullptr;
4609  Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4610 
4611  // If we got no declarator info from previous Sema routines,
4612  // just fill with the typespec loc.
4613  if (!TInfo) {
4615  return;
4616  }
4617 
4618  TypeLoc OldTL = TInfo->getTypeLoc();
4619  if (TInfo->getType()->getAs<ElaboratedType>()) {
4620  ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
4623  TL.copy(NamedTL);
4624  } else {
4626  assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
4627  }
4628 
4629  }
4630  void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
4631  assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
4634  }
4635  void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
4636  assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
4639  assert(DS.getRepAsType());
4640  TypeSourceInfo *TInfo = nullptr;
4641  Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4642  TL.setUnderlyingTInfo(TInfo);
4643  }
4644  void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
4645  // FIXME: This holds only because we only have one unary transform.
4647  TL.setKWLoc(DS.getTypeSpecTypeLoc());
4649  assert(DS.getRepAsType());
4650  TypeSourceInfo *TInfo = nullptr;
4651  Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4652  TL.setUnderlyingTInfo(TInfo);
4653  }
4654  void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
4655  // By default, use the source location of the type specifier.
4657  if (TL.needsExtraLocalData()) {
4658  // Set info for the written builtin specifiers.
4660  // Try to have a meaningful source location.
4661  if (TL.getWrittenSignSpec() != TSS_unspecified)
4662  // Sign spec loc overrides the others (e.g., 'unsigned long').
4664  else if (TL.getWrittenWidthSpec() != TSW_unspecified)
4665  // Width spec loc overrides type spec loc (e.g., 'short int').
4667  }
4668  }
4669  void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
4670  ElaboratedTypeKeyword Keyword
4672  if (DS.getTypeSpecType() == TST_typename) {
4673  TypeSourceInfo *TInfo = nullptr;
4674  Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4675  if (TInfo) {
4676  TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
4677  return;
4678  }
4679  }
4680  TL.setElaboratedKeywordLoc(Keyword != ETK_None
4681  ? DS.getTypeSpecTypeLoc()
4682  : SourceLocation());
4683  const CXXScopeSpec& SS = DS.getTypeSpecScope();
4685  Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
4686  }
4687  void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
4688  assert(DS.getTypeSpecType() == TST_typename);
4689  TypeSourceInfo *TInfo = nullptr;
4690  Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4691  assert(TInfo);
4692  TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
4693  }
4694  void VisitDependentTemplateSpecializationTypeLoc(
4696  assert(DS.getTypeSpecType() == TST_typename);
4697  TypeSourceInfo *TInfo = nullptr;
4698  Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4699  assert(TInfo);
4700  TL.copy(
4701  TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
4702  }
4703  void VisitTagTypeLoc(TagTypeLoc TL) {
4705  }
4706  void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
4707  // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
4708  // or an _Atomic qualifier.
4709  if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
4710  TL.setKWLoc(DS.getTypeSpecTypeLoc());
4712 
4713  TypeSourceInfo *TInfo = nullptr;
4714  Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4715  assert(TInfo);
4716  TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
4717  } else {
4718  TL.setKWLoc(DS.getAtomicSpecLoc());
4719  // No parens, to indicate this was spelled as an _Atomic qualifier.
4721  Visit(TL.getValueLoc());
4722  }
4723  }
4724 
4725  void VisitPipeTypeLoc(PipeTypeLoc TL) {
4726  TL.setKWLoc(DS.getTypeSpecTypeLoc());
4727 
4728  TypeSourceInfo *TInfo = 0;
4729  Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4730  TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
4731  }
4732 
4733  void VisitTypeLoc(TypeLoc TL) {
4734  // FIXME: add other typespec types and change this to an assert.
4736  }
4737  };
4738 
4739  class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
4741  const DeclaratorChunk &Chunk;
4742 
4743  public:
4744  DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
4745  : Context(Context), Chunk(Chunk) {}
4746 
4747  void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4748  llvm_unreachable("qualified type locs not expected here!");
4749  }
4750  void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
4751  llvm_unreachable("decayed type locs not expected here!");
4752  }
4753 
4754  void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4755  fillAttributedTypeLoc(TL, Chunk.getAttrs());
4756  }
4757  void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
4758  // nothing
4759  }
4760  void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
4761  assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
4762  TL.setCaretLoc(Chunk.Loc);
4763  }
4764  void VisitPointerTypeLoc(PointerTypeLoc TL) {
4765  assert(Chunk.Kind == DeclaratorChunk::Pointer);
4766  TL.setStarLoc(Chunk.Loc);
4767  }
4768  void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4769  assert(Chunk.Kind == DeclaratorChunk::Pointer);
4770  TL.setStarLoc(Chunk.Loc);
4771  }
4772  void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
4773  assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
4774  const CXXScopeSpec& SS = Chunk.Mem.Scope();
4776 
4777  const Type* ClsTy = TL.getClass();
4778  QualType ClsQT = QualType(ClsTy, 0);
4779  TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
4780  // Now copy source location info into the type loc component.
4781  TypeLoc ClsTL = ClsTInfo->getTypeLoc();
4782  switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
4784  assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
4785  {
4788  DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
4789  DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
4790  }
4791  break;
4792 
4795  if (isa<ElaboratedType>(ClsTy)) {
4796  ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
4798  ETLoc.setQualifierLoc(NNSLoc.getPrefix());
4799  TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
4800  NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
4801  } else {
4802  ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
4803  }
4804  break;
4805 
4810  llvm_unreachable("Nested-name-specifier must name a type");
4811  }
4812 
4813  // Finally fill in MemberPointerLocInfo fields.
4814  TL.setStarLoc(Chunk.Loc);
4815  TL.setClassTInfo(ClsTInfo);
4816  }
4817  void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
4818  assert(Chunk.Kind == DeclaratorChunk::Reference);
4819  // 'Amp' is misleading: this might have been originally
4820  /// spelled with AmpAmp.
4821  TL.setAmpLoc(Chunk.Loc);
4822  }
4823  void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
4824  assert(Chunk.Kind == DeclaratorChunk::Reference);
4825  assert(!Chunk.Ref.LValueRef);
4826  TL.setAmpAmpLoc(Chunk.Loc);
4827  }
4828  void VisitArrayTypeLoc(ArrayTypeLoc TL) {
4829  assert(Chunk.Kind == DeclaratorChunk::Array);
4830  TL.setLBracketLoc(Chunk.Loc);
4831  TL.setRBracketLoc(Chunk.EndLoc);
4832  TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
4833  }
4834  void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
4835  assert(Chunk.Kind == DeclaratorChunk::Function);
4836  TL.setLocalRangeBegin(Chunk.Loc);
4837  TL.setLocalRangeEnd(Chunk.EndLoc);
4838 
4839  const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
4840  TL.setLParenLoc(FTI.getLParenLoc());
4841  TL.setRParenLoc(FTI.getRParenLoc());
4842  for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
4843  ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4844  TL.setParam(tpi++, Param);
4845  }
4846  // FIXME: exception specs
4847  }
4848  void VisitParenTypeLoc(ParenTypeLoc TL) {
4849  assert(Chunk.Kind == DeclaratorChunk::Paren);
4850  TL.setLParenLoc(Chunk.Loc);
4851  TL.setRParenLoc(Chunk.EndLoc);
4852  }
4853  void VisitPipeTypeLoc(PipeTypeLoc TL) {
4854  assert(Chunk.Kind == DeclaratorChunk::Pipe);
4855  TL.setKWLoc(Chunk.Loc);
4856  }
4857 
4858  void VisitTypeLoc(TypeLoc TL) {
4859  llvm_unreachable("unsupported TypeLoc kind in declarator!");
4860  }
4861  };
4862 }
4863 
4864 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
4865  SourceLocation Loc;
4866  switch (Chunk.Kind) {
4870  case DeclaratorChunk::Pipe:
4871  llvm_unreachable("cannot be _Atomic qualified");
4872 
4875  break;
4876 
4880  // FIXME: Provide a source location for the _Atomic keyword.
4881  break;
4882  }
4883 
4884  ATL.setKWLoc(Loc);
4885  ATL.setParensRange(SourceRange());
4886 }
4887 
4888 /// \brief Create and instantiate a TypeSourceInfo with type source information.
4889 ///
4890 /// \param T QualType referring to the type as written in source code.
4891 ///
4892 /// \param ReturnTypeInfo For declarators whose return type does not show
4893 /// up in the normal place in the declaration specifiers (such as a C++
4894 /// conversion function), this pointer will refer to a type source information
4895 /// for that return type.
4898  TypeSourceInfo *ReturnTypeInfo) {
4900  UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
4901  const AttributeList *DeclAttrs = D.getAttributes();
4902 
4903  // Handle parameter packs whose type is a pack expansion.
4904  if (isa<PackExpansionType>(T)) {
4905  CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
4906  CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
4907  }
4908 
4909  for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4910  // An AtomicTypeLoc might be produced by an atomic qualifier in this
4911  // declarator chunk.
4912  if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
4913  fillAtomicQualLoc(ATL, D.getTypeObject(i));
4914  CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
4915  }
4916 
4917  while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
4918  fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs);
4919  CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
4920  }
4921 
4922  // FIXME: Ordering here?
4923  while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
4924  CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
4925 
4926  DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
4927  CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
4928  }
4929 
4930  // If we have different source information for the return type, use
4931  // that. This really only applies to C++ conversion functions.
4932  if (ReturnTypeInfo) {
4933  TypeLoc TL = ReturnTypeInfo->getTypeLoc();
4934  assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
4935  memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
4936  } else {
4937  TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
4938  }
4939 
4940  return TInfo;
4941 }
4942 
4943 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
4945  // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
4946  // and Sema during declaration parsing. Try deallocating/caching them when
4947  // it's appropriate, instead of allocating them and keeping them around.
4948  LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
4949  TypeAlignment);
4950  new (LocT) LocInfoType(T, TInfo);
4951  assert(LocT->getTypeClass() != T->getTypeClass() &&
4952  "LocInfoType's TypeClass conflicts with an existing Type class");
4953  return ParsedType::make(QualType(LocT, 0));
4954 }
4955 
4956 void LocInfoType::getAsStringInternal(std::string &Str,
4957  const PrintingPolicy &Policy) const {
4958  llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
4959  " was used directly instead of getting the QualType through"
4960  " GetTypeFromParser");
4961 }
4962 
4964  // C99 6.7.6: Type names have no identifier. This is already validated by
4965  // the parser.
4966  assert(D.getIdentifier() == nullptr &&
4967  "Type name should have no identifier!");
4968 
4969  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4970  QualType T = TInfo->getType();
4971  if (D.isInvalidType())
4972  return true;
4973 
4974  // Make sure there are no unused decl attributes on the declarator.
4975  // We don't want to do this for ObjC parameters because we're going
4976  // to apply them to the actual parameter declaration.
4977  // Likewise, we don't want to do this for alias declarations, because
4978  // we are actually going to build a declaration from this eventually.
4983 
4984  if (getLangOpts().CPlusPlus) {
4985  // Check that there are no default arguments (C++ only).
4987  }
4988 
4989  return CreateParsedType(T, TInfo);
4990 }
4991 
4995  return CreateParsedType(T, TInfo);
4996 }
4997 
4998 
4999 //===----------------------------------------------------------------------===//
5000 // Type Attribute Processing
5001 //===----------------------------------------------------------------------===//
5002 
5003 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
5004 /// specified type. The attribute contains 1 argument, the id of the address
5005 /// space for the type.
5007  const AttributeList &Attr, Sema &S){
5008 
5009  // If this type is already address space qualified, reject it.
5010  // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
5011  // qualifiers for two or more different address spaces."
5012  if (Type.getAddressSpace()) {
5013  S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
5014  Attr.setInvalid();
5015  return;
5016  }
5017 
5018  // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
5019  // qualified by an address-space qualifier."
5020  if (Type->isFunctionType()) {
5021  S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
5022  Attr.setInvalid();
5023  return;
5024  }
5025 
5026  unsigned ASIdx;
5027  if (Attr.getKind() == AttributeList::AT_AddressSpace) {
5028  // Check the attribute arguments.
5029  if (Attr.getNumArgs() != 1) {
5030  S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5031  << Attr.getName() << 1;
5032  Attr.setInvalid();
5033  return;
5034  }
5035  Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5036  llvm::APSInt addrSpace(32);
5037  if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
5038  !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
5039  S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5041  << ASArgExpr->getSourceRange();
5042  Attr.setInvalid();
5043  return;
5044  }
5045 
5046  // Bounds checking.
5047  if (addrSpace.isSigned()) {
5048  if (addrSpace.isNegative()) {
5049  S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
5050  << ASArgExpr->getSourceRange();
5051  Attr.setInvalid();
5052  return;
5053  }
5054  addrSpace.setIsSigned(false);
5055  }
5056  llvm::APSInt max(addrSpace.getBitWidth());
5058  if (addrSpace > max) {
5059  S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
5060  << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange();
5061  Attr.setInvalid();
5062  return;
5063  }
5064  ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
5065  } else {
5066  // The keyword-based type attributes imply which address space to use.
5067  switch (Attr.getKind()) {
5068  case AttributeList::AT_OpenCLGlobalAddressSpace:
5069  ASIdx = LangAS::opencl_global; break;
5070  case AttributeList::AT_OpenCLLocalAddressSpace:
5071  ASIdx = LangAS::opencl_local; break;
5072  case AttributeList::AT_OpenCLConstantAddressSpace:
5073  ASIdx = LangAS::opencl_constant; break;
5074  case AttributeList::AT_OpenCLGenericAddressSpace:
5075  ASIdx = LangAS::opencl_generic; break;
5076  default:
5077  assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace);
5078  ASIdx = 0; break;
5079  }
5080  }
5081 
5082  Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
5083 }
5084 
5085 /// Does this type have a "direct" ownership qualifier? That is,
5086 /// is it written like "__strong id", as opposed to something like
5087 /// "typeof(foo)", where that happens to be strong?
5089  // Fast path: no qualifier at all.
5090  assert(type.getQualifiers().hasObjCLifetime());
5091 
5092  while (true) {
5093  // __strong id
5094  if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
5095  if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
5096  return true;
5097 
5098  type = attr->getModifiedType();
5099 
5100  // X *__strong (...)
5101  } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
5102  type = paren->getInnerType();
5103 
5104  // That's it for things we want to complain about. In particular,
5105  // we do not want to look through typedefs, typeof(expr),
5106  // typeof(type), or any other way that the type is somehow
5107  // abstracted.
5108  } else {
5109 
5110  return false;
5111  }
5112  }
5113 }
5114 
5115 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
5116 /// attribute on the specified type.
5117 ///
5118 /// Returns 'true' if the attribute was handled.
5119 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
5120  AttributeList &attr,
5121  QualType &type) {
5122  bool NonObjCPointer = false;
5123 
5124  if (!type->isDependentType() && !type->isUndeducedType()) {
5125  if (const PointerType *ptr = type->getAs<PointerType>()) {
5126  QualType pointee = ptr->getPointeeType();
5127  if (pointee->isObjCRetainableType() || pointee->isPointerType())
5128  return false;
5129  // It is important not to lose the source info that there was an attribute
5130  // applied to non-objc pointer. We will create an attributed type but
5131  // its type will be the same as the original type.
5132  NonObjCPointer = true;
5133  } else if (!type->isObjCRetainableType()) {
5134  return false;
5135  }
5136 
5137  // Don't accept an ownership attribute in the declspec if it would
5138  // just be the return type of a block pointer.
5139  if (state.isProcessingDeclSpec()) {
5140  Declarator &D = state.getDeclarator();
5142  /*onlyBlockPointers=*/true))
5143  return false;
5144  }
5145  }
5146 
5147  Sema &S = state.getSema();
5148  SourceLocation AttrLoc = attr.getLoc();
5149  if (AttrLoc.isMacroID())
5150  AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
5151 
5152  if (!attr.isArgIdent(0)) {
5153  S.Diag(AttrLoc, diag::err_attribute_argument_type)
5154  << attr.getName() << AANT_ArgumentString;
5155  attr.setInvalid();
5156  return true;
5157  }
5158 
5159  IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5160  Qualifiers::ObjCLifetime lifetime;
5161  if (II->isStr("none"))
5162  lifetime = Qualifiers::OCL_ExplicitNone;
5163  else if (II->isStr("strong"))
5164  lifetime = Qualifiers::OCL_Strong;
5165  else if (II->isStr("weak"))
5166  lifetime = Qualifiers::OCL_Weak;
5167  else if (II->isStr("autoreleasing"))
5168  lifetime = Qualifiers::OCL_Autoreleasing;
5169  else {
5170  S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
5171  << attr.getName() << II;
5172  attr.setInvalid();
5173  return true;
5174  }
5175 
5176  // Just ignore lifetime attributes other than __weak and __unsafe_unretained
5177  // outside of ARC mode.
5178  if (!S.getLangOpts().ObjCAutoRefCount &&
5179  lifetime != Qualifiers::OCL_Weak &&
5180  lifetime != Qualifiers::OCL_ExplicitNone) {
5181  return true;
5182  }
5183 
5184  SplitQualType underlyingType = type.split();
5185 
5186  // Check for redundant/conflicting ownership qualifiers.
5187  if (Qualifiers::ObjCLifetime previousLifetime
5188  = type.getQualifiers().getObjCLifetime()) {
5189  // If it's written directly, that's an error.
5190  if (hasDirectOwnershipQualifier(type)) {
5191  S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
5192  << type;
5193  return true;
5194  }
5195 
5196  // Otherwise, if the qualifiers actually conflict, pull sugar off
5197  // until we reach a type that is directly qualified.
5198  if (previousLifetime != lifetime) {
5199  // This should always terminate: the canonical type is
5200  // qualified, so some bit of sugar must be hiding it.
5201  while (!underlyingType.Quals.hasObjCLifetime()) {
5202  underlyingType = underlyingType.getSingleStepDesugaredType();
5203  }
5204  underlyingType.Quals.removeObjCLifetime();
5205  }
5206  }
5207 
5208  underlyingType.Quals.addObjCLifetime(lifetime);
5209 
5210  if (NonObjCPointer) {
5211  StringRef name = attr.getName()->getName();
5212  switch (lifetime) {
5213  case Qualifiers::OCL_None:
5215  break;
5216  case Qualifiers::OCL_Strong: name = "__strong"; break;
5217  case Qualifiers::OCL_Weak: name = "__weak"; break;
5218  case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
5219  }
5220  S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
5221  << TDS_ObjCObjOrBlock << type;
5222  }
5223 
5224  // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
5225  // because having both 'T' and '__unsafe_unretained T' exist in the type
5226  // system causes unfortunate widespread consistency problems. (For example,
5227  // they're not considered compatible types, and we mangle them identicially
5228  // as template arguments.) These problems are all individually fixable,
5229  // but it's easier to just not add the qualifier and instead sniff it out
5230  // in specific places using isObjCInertUnsafeUnretainedType().
5231  //
5232  // Doing this does means we miss some trivial consistency checks that
5233  // would've triggered in ARC, but that's better than trying to solve all
5234  // the coexistence problems with __unsafe_unretained.
5235  if (!S.getLangOpts().ObjCAutoRefCount &&
5236  lifetime == Qualifiers::OCL_ExplicitNone) {
5237  type = S.Context.getAttributedType(
5239  type, type);
5240  return true;
5241  }
5242 
5243  QualType origType = type;
5244  if (!NonObjCPointer)
5245  type = S.Context.getQualifiedType(underlyingType);
5246 
5247  // If we have a valid source location for the attribute, use an
5248  // AttributedType instead.
5249  if (AttrLoc.isValid())
5251  origType, type);
5252 
5253  auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
5254  unsigned diagnostic, QualType type) {
5259  diagnostic, type, /*ignored*/ 0));
5260  } else {
5261  S.Diag(loc, diagnostic);
5262  }
5263  };
5264 
5265  // Sometimes, __weak isn't allowed.
5266  if (lifetime == Qualifiers::OCL_Weak &&
5267  !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
5268 
5269  // Use a specialized diagnostic if the runtime just doesn't support them.
5270  unsigned diagnostic =
5271  (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
5272  : diag::err_arc_weak_no_runtime);
5273 
5274  // In any case, delay the diagnostic until we know what we're parsing.
5275  diagnoseOrDelay(S, AttrLoc, diagnostic, type);
5276 
5277  attr.setInvalid();
5278  return true;
5279  }
5280 
5281  // Forbid __weak for class objects marked as
5282  // objc_arc_weak_reference_unavailable
5283  if (lifetime == Qualifiers::OCL_Weak) {
5284  if (const ObjCObjectPointerType *ObjT =
5285  type->getAs<ObjCObjectPointerType>()) {
5286  if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
5287  if (Class->isArcWeakrefUnavailable()) {
5288  S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
5289  S.Diag(ObjT->getInterfaceDecl()->getLocation(),
5290  diag::note_class_declared);
5291  }
5292  }
5293  }
5294  }
5295 
5296  return true;
5297 }
5298 
5299 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
5300 /// attribute on the specified type. Returns true to indicate that
5301 /// the attribute was handled, false to indicate that the type does
5302 /// not permit the attribute.
5303 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
5304  AttributeList &attr,
5305  QualType &type) {
5306  Sema &S = state.getSema();
5307 
5308  // Delay if this isn't some kind of pointer.
5309  if (!type->isPointerType() &&
5310  !type->isObjCObjectPointerType() &&
5311  !type->isBlockPointerType())
5312  return false;
5313 
5314  if (type.getObjCGCAttr() != Qualifiers::GCNone) {
5315  S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
5316  attr.setInvalid();
5317  return true;
5318  }
5319 
5320  // Check the attribute arguments.
5321  if (!attr.isArgIdent(0)) {
5322  S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
5323  << attr.getName() << AANT_ArgumentString;
5324  attr.setInvalid();
5325  return true;
5326  }
5327  Qualifiers::GC GCAttr;
5328  if (attr.getNumArgs() > 1) {
5329  S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5330  << attr.getName() << 1;
5331  attr.setInvalid();
5332  return true;
5333  }
5334 
5335  IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5336  if (II->isStr("weak"))
5337  GCAttr = Qualifiers::Weak;
5338  else if (II->isStr("strong"))
5339  GCAttr = Qualifiers::Strong;
5340  else {
5341  S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
5342  << attr.getName() << II;
5343  attr.setInvalid();
5344  return true;
5345  }
5346 
5347  QualType origType = type;
5348  type = S.Context.getObjCGCQualType(origType, GCAttr);
5349 
5350  // Make an attributed type to preserve the source information.
5351  if (attr.getLoc().isValid())
5353  origType, type);
5354 
5355  return true;
5356 }
5357 
5358 namespace {
5359  /// A helper class to unwrap a type down to a function for the
5360  /// purposes of applying attributes there.
5361  ///
5362  /// Use:
5363  /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
5364  /// if (unwrapped.isFunctionType()) {
5365  /// const FunctionType *fn = unwrapped.get();
5366  /// // change fn somehow
5367  /// T = unwrapped.wrap(fn);
5368  /// }
5369  struct FunctionTypeUnwrapper {
5370  enum WrapKind {
5371  Desugar,
5372  Parens,
5373  Pointer,
5374  BlockPointer,
5375  Reference,
5376  MemberPointer
5377  };
5378 
5379  QualType Original;
5380  const FunctionType *Fn;
5381  SmallVector<unsigned char /*WrapKind*/, 8> Stack;
5382 
5383  FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
5384  while (true) {
5385  const Type *Ty = T.getTypePtr();
5386  if (isa<FunctionType>(Ty)) {
5387  Fn = cast<FunctionType>(Ty);
5388  return;
5389  } else if (isa<ParenType>(Ty)) {
5390  T = cast<ParenType>(Ty)->getInnerType();
5391  Stack.push_back(Parens);
5392  } else if (isa<PointerType>(Ty)) {
5393  T = cast<PointerType>(Ty)->getPointeeType();
5394  Stack.push_back(Pointer);
5395  } else if (isa<BlockPointerType>(Ty)) {
5396  T = cast<BlockPointerType>(Ty)->getPointeeType();
5397  Stack.push_back(BlockPointer);
5398  } else if (isa<MemberPointerType>(Ty)) {
5399  T = cast<MemberPointerType>(Ty)->getPointeeType();
5400  Stack.push_back(MemberPointer);
5401  } else if (isa<ReferenceType>(Ty)) {
5402  T = cast<ReferenceType>(Ty)->getPointeeType();
5403  Stack.push_back(Reference);
5404  } else {
5405  const Type *DTy = Ty->getUnqualifiedDesugaredType();
5406  if (Ty == DTy) {
5407  Fn = nullptr;
5408  return;
5409  }
5410 
5411  T = QualType(DTy, 0);
5412  Stack.push_back(Desugar);
5413  }
5414  }
5415  }
5416 
5417  bool isFunctionType() const { return (Fn != nullptr); }
5418  const FunctionType *get() const { return Fn; }
5419 
5420  QualType wrap(Sema &S, const FunctionType *New) {
5421  // If T wasn't modified from the unwrapped type, do nothing.
5422  if (New == get()) return Original;
5423 
5424  Fn = New;
5425  return wrap(S.Context, Original, 0);
5426  }
5427 
5428  private:
5429  QualType wrap(ASTContext &C, QualType Old, unsigned I) {
5430  if (I == Stack.size())
5431  return C.getQualifiedType(Fn, Old.getQualifiers());
5432 
5433  // Build up the inner type, applying the qualifiers from the old
5434  // type to the new type.
5435  SplitQualType SplitOld = Old.split();
5436 
5437  // As a special case, tail-recurse if there are no qualifiers.
5438  if (SplitOld.Quals.empty())
5439  return wrap(C, SplitOld.Ty, I);
5440  return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
5441  }
5442 
5443  QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
5444  if (I == Stack.size()) return QualType(Fn, 0);
5445 
5446  switch (static_cast<WrapKind>(Stack[I++])) {
5447  case Desugar:
5448  // This is the point at which we potentially lose source
5449  // information.
5450  return wrap(C, Old->getUnqualifiedDesugaredType(), I);
5451 
5452  case Parens: {
5453  QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
5454  return C.getParenType(New);
5455  }
5456 
5457  case Pointer: {
5458  QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
5459  return C.getPointerType(New);
5460  }
5461 
5462  case BlockPointer: {
5463  QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
5464  return C.getBlockPointerType(New);
5465  }
5466 
5467  case MemberPointer: {
5468  const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
5469  QualType New = wrap(C, OldMPT->getPointeeType(), I);
5470  return C.getMemberPointerType(New, OldMPT->getClass());
5471  }
5472 
5473  case Reference: {
5474  const ReferenceType *OldRef = cast<ReferenceType>(Old);
5475  QualType New = wrap(C, OldRef->getPointeeType(), I);
5476  if (isa<LValueReferenceType>(OldRef))
5477  return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
5478  else
5479  return C.getRValueReferenceType(New);
5480  }
5481  }
5482 
5483  llvm_unreachable("unknown wrapping kind");
5484  }
5485  };
5486 }
5487 
5488 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
5490  QualType &Type) {
5491  Sema &S = State.getSema();
5492 
5493  AttributeList::Kind Kind = Attr.getKind();
5494  QualType Desugared = Type;
5495  const AttributedType *AT = dyn_cast<AttributedType>(Type);
5496  while (AT) {
5497  AttributedType::Kind CurAttrKind = AT->getAttrKind();
5498 
5499  // You cannot specify duplicate type attributes, so if the attribute has
5500  // already been applied, flag it.
5501  if (getAttrListKind(CurAttrKind) == Kind) {
5502  S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
5503  << Attr.getName();
5504  return true;
5505  }
5506 
5507  // You cannot have both __sptr and __uptr on the same type, nor can you
5508  // have __ptr32 and __ptr64.
5509  if ((CurAttrKind == AttributedType::attr_ptr32 &&
5510  Kind == AttributeList::AT_Ptr64) ||
5511  (CurAttrKind == AttributedType::attr_ptr64 &&
5512  Kind == AttributeList::AT_Ptr32)) {
5513  S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5514  << "'__ptr32'" << "'__ptr64'";
5515  return true;
5516  } else if ((CurAttrKind == AttributedType::attr_sptr &&
5517  Kind == AttributeList::AT_UPtr) ||
5518  (CurAttrKind == AttributedType::attr_uptr &&
5519  Kind == AttributeList::AT_SPtr)) {
5520  S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5521  << "'__sptr'" << "'__uptr'";
5522  return true;
5523  }
5524 
5525  Desugared = AT->getEquivalentType();
5526  AT = dyn_cast<AttributedType>(Desugared);
5527  }
5528 
5529  // Pointer type qualifiers can only operate on pointer types, but not
5530  // pointer-to-member types.
5531  if (!isa<PointerType>(Desugared)) {
5532  if (Type->isMemberPointerType())
5533  S.Diag(Attr.getLoc(), diag::err_attribute_no_member_pointers)
5534  << Attr.getName();
5535  else
5536  S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
5537  << Attr.getName() << 0;
5538  return true;
5539  }
5540 
5542  switch (Kind) {
5543  default: llvm_unreachable("Unknown attribute kind");
5544  case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
5545  case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
5546  case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
5547  case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
5548  }
5549 
5550  Type = S.Context.getAttributedType(TAK, Type, Type);
5551  return false;
5552 }
5553 
5555  NullabilityKind nullability,
5556  SourceLocation nullabilityLoc,
5557  bool isContextSensitive) {
5558  // We saw a nullability type specifier. If this is the first one for
5559  // this file, note that.
5560  FileID file = getNullabilityCompletenessCheckFileID(*this, nullabilityLoc);
5561  if (!file.isInvalid()) {
5562  FileNullability &fileNullability = NullabilityMap[file];
5563  if (!fileNullability.SawTypeNullability) {
5564  // If we have already seen a pointer declarator without a nullability
5565  // annotation, complain about it.
5566  if (fileNullability.PointerLoc.isValid()) {
5567  Diag(fileNullability.PointerLoc, diag::warn_nullability_missing)
5568  << static_cast<unsigned>(fileNullability.PointerKind);
5569  }
5570 
5571  fileNullability.SawTypeNullability = true;
5572  }
5573  }
5574 
5575  // Check for existing nullability attributes on the type.
5576  QualType desugared = type;
5577  while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
5578  // Check whether there is already a null
5579  if (auto existingNullability = attributed->getImmediateNullability()) {
5580  // Duplicated nullability.
5581  if (nullability == *existingNullability) {
5582  Diag(nullabilityLoc, diag::warn_nullability_duplicate)
5583  << DiagNullabilityKind(nullability, isContextSensitive)
5584  << FixItHint::CreateRemoval(nullabilityLoc);
5585 
5586  break;
5587  }
5588 
5589  // Conflicting nullability.
5590  Diag(nullabilityLoc, diag::err_nullability_conflicting)
5591  << DiagNullabilityKind(nullability, isContextSensitive)
5592  << DiagNullabilityKind(*existingNullability, false);
5593  return true;
5594  }
5595 
5596  desugared = attributed->getModifiedType();
5597  }
5598 
5599  // If there is already a different nullability specifier, complain.
5600  // This (unlike the code above) looks through typedefs that might
5601  // have nullability specifiers on them, which means we cannot
5602  // provide a useful Fix-It.
5603  if (auto existingNullability = desugared->getNullability(Context)) {
5604  if (nullability != *existingNullability) {
5605  Diag(nullabilityLoc, diag::err_nullability_conflicting)
5606  << DiagNullabilityKind(nullability, isContextSensitive)
5607  << DiagNullabilityKind(*existingNullability, false);
5608 
5609  // Try to find the typedef with the existing nullability specifier.
5610  if (auto typedefType = desugared->getAs<TypedefType>()) {
5611  TypedefNameDecl *typedefDecl = typedefType->getDecl();
5612  QualType underlyingType = typedefDecl->getUnderlyingType();
5613  if (auto typedefNullability
5614  = AttributedType::stripOuterNullability(underlyingType)) {
5615  if (*typedefNullability == *existingNullability) {
5616  Diag(typedefDecl->getLocation(), diag::note_nullability_here)
5617  << DiagNullabilityKind(*existingNullability, false);
5618  }
5619  }
5620  }
5621 
5622  return true;
5623  }
5624  }
5625 
5626  // If this definitely isn't a pointer type, reject the specifier.
5627  if (!desugared->canHaveNullability()) {
5628  Diag(nullabilityLoc, diag::err_nullability_nonpointer)
5629  << DiagNullabilityKind(nullability, isContextSensitive) << type;
5630  return true;
5631  }
5632 
5633  // For the context-sensitive keywords/Objective-C property
5634  // attributes, require that the type be a single-level pointer.
5635  if (isContextSensitive) {
5636  // Make sure that the pointee isn't itself a pointer type.
5637  QualType pointeeType = desugared->getPointeeType();
5638  if (pointeeType->isAnyPointerType() ||
5639  pointeeType->isObjCObjectPointerType() ||
5640  pointeeType->isMemberPointerType()) {
5641  Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
5642  << DiagNullabilityKind(nullability, true)
5643  << type;
5644  Diag(nullabilityLoc, diag::note_nullability_type_specifier)
5645  << DiagNullabilityKind(nullability, false)
5646  << type
5647  << FixItHint::CreateReplacement(nullabilityLoc,
5648  getNullabilitySpelling(nullability));
5649  return true;
5650  }
5651  }
5652 
5653  // Form the attributed type.
5654  type = Context.getAttributedType(
5655  AttributedType::getNullabilityAttrKind(nullability), type, type);
5656  return false;
5657 }
5658 
5660  // Find out if it's an Objective-C object or object pointer type;
5661  const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
5662  const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
5663  : type->getAs<ObjCObjectType>();
5664 
5665  // If not, we can't apply __kindof.
5666  if (!objType) {
5667  // FIXME: Handle dependent types that aren't yet object types.
5668  Diag(loc, diag::err_objc_kindof_nonobject)
5669  << type;
5670  return true;
5671  }
5672 
5673  // Rebuild the "equivalent" type, which pushes __kindof down into
5674  // the object type.
5675  QualType equivType = Context.getObjCObjectType(objType->getBaseType(),
5676  objType->getTypeArgsAsWritten(),
5677  objType->getProtocols(),
5678  /*isKindOf=*/true);
5679 
5680  // If we started with an object pointer type, rebuild it.
5681  if (ptrType) {
5682  equivType = Context.getObjCObjectPointerType(equivType);
5683  if (auto nullability = type->getNullability(Context)) {
5684  auto attrKind = AttributedType::getNullabilityAttrKind(*nullability);
5685  equivType = Context.getAttributedType(attrKind, equivType, equivType);
5686  }
5687  }
5688 
5689  // Build the attributed type to record where __kindof occurred.
5691  type,
5692  equivType);
5693 
5694  return false;
5695 }
5696 
5697 /// Map a nullability attribute kind to a nullability kind.
5699  switch (kind) {
5700  case AttributeList::AT_TypeNonNull:
5701  return NullabilityKind::NonNull;
5702 
5703  case AttributeList::AT_TypeNullable:
5705 
5706  case AttributeList::AT_TypeNullUnspecified:
5708 
5709  default:
5710  llvm_unreachable("not a nullability attribute kind");
5711  }
5712 }
5713 
5714 /// Distribute a nullability type attribute that cannot be applied to
5715 /// the type specifier to a pointer, block pointer, or member pointer
5716 /// declarator, complaining if necessary.
5717 ///
5718 /// \returns true if the nullability annotation was distributed, false
5719 /// otherwise.
5720 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
5721  QualType type,
5722  AttributeList &attr) {
5723  Declarator &declarator = state.getDeclarator();
5724 
5725  /// Attempt to move the attribute to the specified chunk.
5726  auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
5727  // If there is already a nullability attribute there, don't add
5728  // one.
5729  if (hasNullabilityAttr(chunk.getAttrListRef()))
5730  return false;
5731 
5732  // Complain about the nullability qualifier being in the wrong
5733  // place.
5734  enum {
5735  PK_Pointer,
5736  PK_BlockPointer,
5737  PK_MemberPointer,
5738  PK_FunctionPointer,
5739  PK_MemberFunctionPointer,
5740  } pointerKind
5741  = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
5742  : PK_Pointer)
5743  : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
5744  : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
5745 
5746  auto diag = state.getSema().Diag(attr.getLoc(),
5747  diag::warn_nullability_declspec)
5750  << type
5751  << static_cast<unsigned>(pointerKind);
5752 
5753  // FIXME: MemberPointer chunks don't carry the location of the *.
5754  if (chunk.Kind != DeclaratorChunk::MemberPointer) {
5755  diag << FixItHint::CreateRemoval(attr.getLoc())
5757  state.getSema().getPreprocessor()
5758  .getLocForEndOfToken(chunk.Loc),
5759  " " + attr.getName()->getName().str() + " ");
5760  }
5761 
5762  moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
5763  chunk.getAttrListRef());
5764  return true;
5765  };
5766 
5767  // Move it to the outermost pointer, member pointer, or block
5768  // pointer declarator.
5769  for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
5770  DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
5771  switch (chunk.Kind) {
5775  return moveToChunk(chunk, false);
5776 
5779  continue;
5780 
5782  // Try to move past the return type to a function/block/member
5783  // function pointer.
5785  declarator, i,
5786  /*onlyBlockPointers=*/false)) {
5787  return moveToChunk(*dest, true);
5788  }
5789 
5790  return false;
5791 
5792  // Don't walk through these.
5794  case DeclaratorChunk::Pipe:
5795  return false;
5796  }
5797  }
5798 
5799  return false;
5800 }
5801 
5803  assert(!Attr.isInvalid());
5804  switch (Attr.getKind()) {
5805  default:
5806  llvm_unreachable("not a calling convention attribute");
5807  case AttributeList::AT_CDecl:
5809  case AttributeList::AT_FastCall:
5811  case AttributeList::AT_StdCall:
5813  case AttributeList::AT_ThisCall:
5815  case AttributeList::AT_Pascal:
5817  case AttributeList::AT_VectorCall:
5819  case AttributeList::AT_Pcs: {
5820  // The attribute may have had a fixit applied where we treated an
5821  // identifier as a string literal. The contents of the string are valid,
5822  // but the form may not be.
5823  StringRef Str;
5824  if (Attr.isArgExpr(0))
5825  Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
5826  else
5827  Str = Attr.getArgAsIdent(0)->Ident->getName();
5828  return llvm::StringSwitch<AttributedType::Kind>(Str)
5829  .Case("aapcs", AttributedType::attr_pcs)
5830  .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
5831  }
5832  case AttributeList::AT_IntelOclBicc:
5834  case AttributeList::AT_MSABI:
5836  case AttributeList::AT_SysVABI:
5838  }
5839  llvm_unreachable("unexpected attribute kind!");
5840 }
5841 
5842 /// Process an individual function attribute. Returns true to
5843 /// indicate that the attribute was handled, false if it wasn't.
5844 static bool handleFunctionTypeAttr(TypeProcessingState &state,
5845  AttributeList &attr,
5846  QualType &type) {
5847  Sema &S = state.getSema();
5848 
5849  FunctionTypeUnwrapper unwrapped(S, type);
5850 
5851  if (attr.getKind() == AttributeList::AT_NoReturn) {
5852  if (S.CheckNoReturnAttr(attr))
5853  return true;
5854 
5855  // Delay if this is not a function type.
5856  if (!unwrapped.isFunctionType())
5857  return false;
5858 
5859  // Otherwise we can process right away.
5860  FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
5861  type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5862  return true;
5863  }
5864 
5865  // ns_returns_retained is not always a type attribute, but if we got
5866  // here, we're treating it as one right now.
5867  if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
5868  assert(S.getLangOpts().ObjCAutoRefCount &&
5869  "ns_returns_retained treated as type attribute in non-ARC");
5870  if (attr.getNumArgs()) return true;
5871 
5872  // Delay if this is not a function type.
5873  if (!unwrapped.isFunctionType())
5874  return false;
5875 
5877  = unwrapped.get()->getExtInfo().withProducesResult(true);
5878  type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5879  return true;
5880  }
5881 
5882  if (attr.getKind() == AttributeList::AT_Regparm) {
5883  unsigned value;
5884  if (S.CheckRegparmAttr(attr, value))
5885  return true;
5886 
5887  // Delay if this is not a function type.
5888  if (!unwrapped.isFunctionType())
5889  return false;
5890 
5891  // Diagnose regparm with fastcall.
5892  const FunctionType *fn = unwrapped.get();
5893  CallingConv CC = fn->getCallConv();
5894  if (CC == CC_X86FastCall) {
5895  S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5897  << "regparm";
5898  attr.setInvalid();
5899  return true;
5900  }
5901 
5903  unwrapped.get()->getExtInfo().withRegParm(value);
5904  type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5905  return true;
5906  }
5907 
5908  // Delay if the type didn't work out to a function.
5909  if (!unwrapped.isFunctionType()) return false;
5910 
5911  // Otherwise, a calling convention.
5912  CallingConv CC;
5913  if (S.CheckCallingConvAttr(attr, CC))
5914  return true;
5915 
5916  const FunctionType *fn = unwrapped.get();
5917  CallingConv CCOld = fn->getCallConv();
5918  AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
5919 
5920  if (CCOld != CC) {
5921  // Error out on when there's already an attribute on the type
5922  // and the CCs don't match.
5923  const AttributedType *AT = S.getCallingConvAttributedType(type);
5924  if (AT && AT->getAttrKind() != CCAttrKind) {
5925  S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5928  attr.setInvalid();
5929  return true;
5930  }
5931  }
5932 
5933  // Diagnose use of callee-cleanup calling convention on variadic functions.
5934  if (!supportsVariadicCall(CC)) {
5935  const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
5936  if (FnP && FnP->isVariadic()) {
5937  unsigned DiagID = diag::err_cconv_varargs;
5938  // stdcall and fastcall are ignored with a warning for GCC and MS
5939  // compatibility.
5940  if (CC == CC_X86StdCall || CC == CC_X86FastCall)
5941  DiagID = diag::warn_cconv_varargs;
5942 
5943  S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
5944  attr.setInvalid();
5945  return true;
5946  }
5947  }
5948 
5949  // Also diagnose fastcall with regparm.
5950  if (CC == CC_X86FastCall && fn->getHasRegParm()) {
5951  S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5953  attr.setInvalid();
5954  return true;
5955  }
5956 
5957  // Modify the CC from the wrapped function type, wrap it all back, and then
5958  // wrap the whole thing in an AttributedType as written. The modified type
5959  // might have a different CC if we ignored the attribute.
5960  FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
5961  QualType Equivalent =
5962  unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5963  type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
5964  return true;
5965 }
5966 
5968  QualType R = T.IgnoreParens();
5969  while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
5970  if (AT->isCallingConv())
5971  return true;
5972  R = AT->getModifiedType().IgnoreParens();
5973  }
5974  return false;
5975 }
5976 
5977 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
5978  SourceLocation Loc) {
5979  FunctionTypeUnwrapper Unwrapped(*this, T);
5980  const FunctionType *FT = Unwrapped.get();
5981  bool IsVariadic = (isa<FunctionProtoType>(FT) &&
5982  cast<FunctionProtoType>(FT)->isVariadic());
5983  CallingConv CurCC = FT->getCallConv();
5984  CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
5985 
5986  if (CurCC == ToCC)
5987  return;
5988 
5989  // MS compiler ignores explicit calling convention attributes on structors. We
5990  // should do the same.
5991  if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
5992  // Issue a warning on ignored calling convention -- except of __stdcall.
5993  // Again, this is what MS compiler does.
5994  if (CurCC != CC_X86StdCall)
5995  Diag(Loc, diag::warn_cconv_structors)
5997  // Default adjustment.
5998  } else {
5999  // Only adjust types with the default convention. For example, on Windows
6000  // we should adjust a __cdecl type to __thiscall for instance methods, and a
6001  // __thiscall type to __cdecl for static methods.
6002  CallingConv DefaultCC =
6003  Context.getDefaultCallingConvention(IsVariadic, IsStatic);
6004 
6005  if (CurCC != DefaultCC || DefaultCC == ToCC)
6006  return;
6007 
6008  if (hasExplicitCallingConv(T))
6009  return;
6010  }
6011 
6012  FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
6013  QualType Wrapped = Unwrapped.wrap(*this, FT);
6014  T = Context.getAdjustedType(T, Wrapped);
6015 }
6016 
6017 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
6018 /// and float scalars, although arrays, pointers, and function return values are
6019 /// allowed in conjunction with this construct. Aggregates with this attribute
6020 /// are invalid, even if they are of the same size as a corresponding scalar.
6021 /// The raw attribute should contain precisely 1 argument, the vector size for
6022 /// the variable, measured in bytes. If curType and rawAttr are well formed,
6023 /// this routine will return a new vector type.
6024 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
6025  Sema &S) {
6026  // Check the attribute arguments.
6027  if (Attr.getNumArgs() != 1) {
6028  S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6029  << Attr.getName() << 1;
6030  Attr.setInvalid();
6031  return;
6032  }
6033  Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6034  llvm::APSInt vecSize(32);
6035  if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
6036  !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
6037  S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6039  << sizeExpr->getSourceRange();
6040  Attr.setInvalid();
6041  return;
6042  }
6043  // The base type must be integer (not Boolean or enumeration) or float, and
6044  // can't already be a vector.
6045  if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
6046  (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
6047  S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6048  Attr.setInvalid();
6049  return;
6050  }
6051  unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6052  // vecSize is specified in bytes - convert to bits.
6053  unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
6054 
6055  // the vector size needs to be an integral multiple of the type size.
6056  if (vectorSize % typeSize) {
6057  S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
6058  << sizeExpr->getSourceRange();
6059  Attr.setInvalid();
6060  return;
6061  }
6062  if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
6063  S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
6064  << sizeExpr->getSourceRange();
6065  Attr.setInvalid();
6066  return;
6067  }
6068  if (vectorSize == 0) {
6069  S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
6070  << sizeExpr->getSourceRange();
6071  Attr.setInvalid();
6072  return;
6073  }
6074 
6075  // Success! Instantiate the vector type, the number of elements is > 0, and
6076  // not required to be a power of 2, unlike GCC.
6077  CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
6079 }
6080 
6081 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
6082 /// a type.
6083 static void HandleExtVectorTypeAttr(QualType &CurType,
6084  const AttributeList &Attr,
6085  Sema &S) {
6086  // check the attribute arguments.
6087  if (Attr.getNumArgs() != 1) {
6088  S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6089  << Attr.getName() << 1;
6090  return;
6091  }
6092 
6093  Expr *sizeExpr;
6094 
6095  // Special case where the argument is a template id.
6096  if (Attr.isArgIdent(0)) {
6097  CXXScopeSpec SS;
6098  SourceLocation TemplateKWLoc;
6099  UnqualifiedId id;
6100  id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
6101 
6102  ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
6103  id, false, false);
6104  if (Size.isInvalid())
6105  return;
6106 
6107  sizeExpr = Size.get();
6108  } else {
6109  sizeExpr = Attr.getArgAsExpr(0);
6110  }
6111 
6112  // Create the vector type.
6113  QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
6114  if (!T.isNull())
6115  CurType = T;
6116 }
6117 
6119  VectorType::VectorKind VecKind, Sema &S) {
6120  const BuiltinType *BTy = Ty->getAs<BuiltinType>();
6121  if (!BTy)
6122  return false;
6123 
6124  llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
6125 
6126  // Signed poly is mathematically wrong, but has been baked into some ABIs by
6127  // now.
6128  bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
6129  Triple.getArch() == llvm::Triple::aarch64_be;
6130  if (VecKind == VectorType::NeonPolyVector) {
6131  if (IsPolyUnsigned) {
6132  // AArch64 polynomial vectors are unsigned and support poly64.
6133  return BTy->getKind() == BuiltinType::UChar ||
6134  BTy->getKind() == BuiltinType::UShort ||
6135  BTy->getKind() == BuiltinType::ULong ||
6136  BTy->getKind() == BuiltinType::ULongLong;
6137  } else {
6138  // AArch32 polynomial vector are signed.
6139  return BTy->getKind() == BuiltinType::SChar ||
6140  BTy->getKind() == BuiltinType::Short;
6141  }
6142  }
6143 
6144  // Non-polynomial vector types: the usual suspects are allowed, as well as
6145  // float64_t on AArch64.
6146  bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
6147  Triple.getArch() == llvm::Triple::aarch64_be;
6148 
6149  if (Is64Bit && BTy->getKind() == BuiltinType::Double)
6150  return true;
6151 
6152  return BTy->getKind() == BuiltinType::SChar ||
6153  BTy->getKind() == BuiltinType::UChar ||
6154  BTy->getKind() == BuiltinType::Short ||
6155  BTy->getKind() == BuiltinType::UShort ||
6156  BTy->getKind() == BuiltinType::Int ||
6157  BTy->getKind() == BuiltinType::UInt ||
6158  BTy->getKind() == BuiltinType::Long ||
6159  BTy->getKind() == BuiltinType::ULong ||
6160  BTy->getKind() == BuiltinType::LongLong ||
6161  BTy->getKind() == BuiltinType::ULongLong ||
6162  BTy->getKind() == BuiltinType::Float ||
6163  BTy->getKind() == BuiltinType::Half;
6164 }
6165 
6166 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
6167 /// "neon_polyvector_type" attributes are used to create vector types that
6168 /// are mangled according to ARM's ABI. Otherwise, these types are identical
6169 /// to those created with the "vector_size" attribute. Unlike "vector_size"
6170 /// the argument to these Neon attributes is the number of vector elements,
6171 /// not the vector size in bytes. The vector width and element type must
6172 /// match one of the standard Neon vector types.
6173 static void HandleNeonVectorTypeAttr(QualType& CurType,
6174  const AttributeList &Attr, Sema &S,
6175  VectorType::VectorKind VecKind) {
6176  // Target must have NEON
6177  if (!S.Context.getTargetInfo().hasFeature("neon")) {
6178  S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
6179  Attr.setInvalid();
6180  return;
6181  }
6182  // Check the attribute arguments.
6183  if (Attr.getNumArgs() != 1) {
6184  S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6185  << Attr.getName() << 1;
6186  Attr.setInvalid();
6187  return;
6188  }
6189  // The number of elements must be an ICE.
6190  Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6191  llvm::APSInt numEltsInt(32);
6192  if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
6193  !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
6194  S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6196  << numEltsExpr->getSourceRange();
6197  Attr.setInvalid();
6198  return;
6199  }
6200  // Only certain element types are supported for Neon vectors.
6201  if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
6202  S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6203  Attr.setInvalid();
6204  return;
6205  }
6206 
6207  // The total size of the vector must be 64 or 128 bits.
6208  unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6209  unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
6210  unsigned vecSize = typeSize * numElts;
6211  if (vecSize != 64 && vecSize != 128) {
6212  S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
6213  Attr.setInvalid();
6214  return;
6215  }
6216 
6217  CurType = S.Context.getVectorType(CurType, numElts, VecKind);
6218 }
6219 
6220 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
6221  TypeAttrLocation TAL, AttributeList *attrs) {
6222  // Scan through and apply attributes to this type where it makes sense. Some
6223  // attributes (such as __address_space__, __vector_size__, etc) apply to the
6224  // type, but others can be present in the type specifiers even though they
6225  // apply to the decl. Here we apply type attributes and ignore the rest.
6226 
6227  bool hasOpenCLAddressSpace = false;
6228  while (attrs) {
6229  AttributeList &attr = *attrs;
6230  attrs = attr.getNext(); // reset to the next here due to early loop continue
6231  // stmts
6232 
6233  // Skip attributes that were marked to be invalid.
6234  if (attr.isInvalid())
6235  continue;
6236 
6237  if (attr.isCXX11Attribute()) {
6238  // [[gnu::...]] attributes are treated as declaration attributes, so may
6239  // not appertain to a DeclaratorChunk, even if we handle them as type
6240  // attributes.
6241  if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
6242  if (TAL == TAL_DeclChunk) {
6243  state.getSema().Diag(attr.getLoc(),
6244  diag::warn_cxx11_gnu_attribute_on_type)
6245  << attr.getName();
6246  continue;
6247  }
6248  } else if (TAL != TAL_DeclChunk) {
6249  // Otherwise, only consider type processing for a C++11 attribute if
6250  // it's actually been applied to a type.
6251  continue;
6252  }
6253  }
6254 
6255  // If this is an attribute we can handle, do so now,
6256  // otherwise, add it to the FnAttrs list for rechaining.
6257  switch (attr.getKind()) {
6258  default:
6259  // A C++11 attribute on a declarator chunk must appertain to a type.
6260  if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
6261  state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
6262  << attr.getName();
6263  attr.setUsedAsTypeAttr();
6264  }
6265  break;
6266 
6268  if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
6269  state.getSema().Diag(attr.getLoc(),
6270  diag::warn_unknown_attribute_ignored)
6271  << attr.getName();
6272  break;
6273 
6275  break;
6276 
6277  case AttributeList::AT_MayAlias:
6278  // FIXME: This attribute needs to actually be handled, but if we ignore
6279  // it it breaks large amounts of Linux software.
6280  attr.setUsedAsTypeAttr();
6281  break;
6282  case AttributeList::AT_OpenCLPrivateAddressSpace:
6283  case AttributeList::AT_OpenCLGlobalAddressSpace:
6284  case AttributeList::AT_OpenCLLocalAddressSpace:
6285  case AttributeList::AT_OpenCLConstantAddressSpace:
6286  case AttributeList::AT_OpenCLGenericAddressSpace:
6287  case AttributeList::AT_AddressSpace:
6288  HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
6289  attr.setUsedAsTypeAttr();
6290  hasOpenCLAddressSpace = true;
6291  break;
6293  if (!handleObjCPointerTypeAttr(state, attr, type))
6294  distributeObjCPointerTypeAttr(state, attr, type);
6295  attr.setUsedAsTypeAttr();
6296  break;
6297  case AttributeList::AT_VectorSize:
6298  HandleVectorSizeAttr(type, attr, state.getSema());
6299  attr.setUsedAsTypeAttr();
6300  break;
6301  case AttributeList::AT_ExtVectorType:
6302  HandleExtVectorTypeAttr(type, attr, state.getSema());
6303  attr.setUsedAsTypeAttr();
6304  break;
6305  case AttributeList::AT_NeonVectorType:
6306  HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6308  attr.setUsedAsTypeAttr();
6309  break;
6310  case AttributeList::AT_NeonPolyVectorType:
6311  HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6313  attr.setUsedAsTypeAttr();
6314  break;
6315  case AttributeList::AT_OpenCLImageAccess:
6316  // FIXME: there should be some type checking happening here, I would
6317  // imagine, but the original handler's checking was entirely superfluous.
6318  attr.setUsedAsTypeAttr();
6319  break;
6320 
6322  if (!handleMSPointerTypeQualifierAttr(state, attr, type))
6323  attr.setUsedAsTypeAttr();
6324  break;
6325 
6326 
6328  // Either add nullability here or try to distribute it. We
6329  // don't want to distribute the nullability specifier past any
6330  // dependent type, because that complicates the user model.
6331  if (type->canHaveNullability() || type->isDependentType() ||
6332  !distributeNullabilityTypeAttr(state, type, attr)) {
6333  if (state.getSema().checkNullabilityTypeSpecifier(
6334  type,
6336  attr.getLoc(),
6338  attr.setInvalid();
6339  }
6340 
6341  attr.setUsedAsTypeAttr();
6342  }
6343  break;
6344 
6345  case AttributeList::AT_ObjCKindOf:
6346  // '__kindof' must be part of the decl-specifiers.
6347  switch (TAL) {
6348  case TAL_DeclSpec:
6349  break;
6350 
6351  case TAL_DeclChunk:
6352  case TAL_DeclName:
6353  state.getSema().Diag(attr.getLoc(),
6354  diag::err_objc_kindof_wrong_position)
6355  << FixItHint::CreateRemoval(attr.getLoc())
6357  state.getDeclarator().getDeclSpec().getLocStart(), "__kindof ");
6358  break;
6359  }
6360 
6361  // Apply it regardless.
6362  if (state.getSema().checkObjCKindOfType(type, attr.getLoc()))
6363  attr.setInvalid();
6364  attr.setUsedAsTypeAttr();
6365  break;
6366 
6367  case AttributeList::AT_NSReturnsRetained:
6368  if (!state.getSema().getLangOpts().ObjCAutoRefCount)
6369  break;
6370  // fallthrough into the function attrs
6371 
6373  attr.setUsedAsTypeAttr();
6374 
6375  // Never process function type attributes as part of the
6376  // declaration-specifiers.
6377  if (TAL == TAL_DeclSpec)
6378  distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
6379 
6380  // Otherwise, handle the possible delays.
6381  else if (!handleFunctionTypeAttr(state, attr, type))
6382  distributeFunctionTypeAttr(state, attr, type);
6383  break;
6384  }
6385  }
6386 
6387  // If address space is not set, OpenCL 2.0 defines non private default
6388  // address spaces for some cases:
6389  // OpenCL 2.0, section 6.5:
6390  // The address space for a variable at program scope or a static variable
6391  // inside a function can either be __global or __constant, but defaults to
6392  // __global if not specified.
6393  // (...)
6394  // Pointers that are declared without pointing to a named address space point
6395  // to the generic address space.
6396  if (state.getSema().getLangOpts().OpenCLVersion >= 200 &&
6397  !hasOpenCLAddressSpace && type.getAddressSpace() == 0 &&
6398  (TAL == TAL_DeclSpec || TAL == TAL_DeclChunk)) {
6399  Declarator &D = state.getDeclarator();
6400  if (state.getCurrentChunkIndex() > 0 &&
6401  D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind ==
6403  type = state.getSema().Context.getAddrSpaceQualType(
6404  type, LangAS::opencl_generic);
6405  } else if (state.getCurrentChunkIndex() == 0 &&
6409  !type->isSamplerT())
6410  type = state.getSema().Context.getAddrSpaceQualType(
6411  type, LangAS::opencl_global);
6412  else if (state.getCurrentChunkIndex() == 0 &&
6415  type = state.getSema().Context.getAddrSpaceQualType(
6416  type, LangAS::opencl_global);
6417  }
6418 }
6419 
6421  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
6422  if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
6423  if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
6424  SourceLocation PointOfInstantiation = E->getExprLoc();
6425 
6426  if (MemberSpecializationInfo *MSInfo =
6427  Var->getMemberSpecializationInfo()) {
6428  // If we don't already have a point of instantiation, this is it.
6429  if (MSInfo->getPointOfInstantiation().isInvalid()) {
6430  MSInfo->setPointOfInstantiation(PointOfInstantiation);
6431 
6432  // This is a modification of an existing AST node. Notify
6433  // listeners.
6435  L->StaticDataMemberInstantiated(Var);
6436  }
6437  } else {
6439  cast<VarTemplateSpecializationDecl>(Var);
6440  if (VarSpec->getPointOfInstantiation().isInvalid())
6441  VarSpec->setPointOfInstantiation(PointOfInstantiation);
6442  }
6443 
6444  InstantiateVariableDefinition(PointOfInstantiation, Var);
6445 
6446  // Update the type to the newly instantiated definition's type both
6447  // here and within the expression.
6448  if (VarDecl *Def = Var->getDefinition()) {
6449  DRE->setDecl(Def);
6450  QualType T = Def->getType();
6451  DRE->setType(T);
6452  // FIXME: Update the type on all intervening expressions.
6453  E->setType(T);
6454  }
6455 
6456  // We still go on to try to complete the type independently, as it
6457  // may also require instantiations or diagnostics if it remains
6458  // incomplete.
6459  }
6460  }
6461  }
6462 }
6463 
6464 /// \brief Ensure that the type of the given expression is complete.
6465 ///
6466 /// This routine checks whether the expression \p E has a complete type. If the
6467 /// expression refers to an instantiable construct, that instantiation is
6468 /// performed as needed to complete its type. Furthermore
6469 /// Sema::RequireCompleteType is called for the expression's type (or in the
6470 /// case of a reference type, the referred-to type).
6471 ///
6472 /// \param E The expression whose type is required to be complete.
6473 /// \param Diagnoser The object that will emit a diagnostic if the type is
6474 /// incomplete.
6475 ///
6476 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
6477 /// otherwise.
6479  QualType T = E->getType();
6480 
6481  // Incomplete array types may be completed by the initializer attached to
6482  // their definitions. For static data members of class templates and for
6483  // variable templates, we need to instantiate the definition to get this
6484  // initializer and complete the type.
6485  if (T->isIncompleteArrayType()) {
6487  T = E->getType();
6488  }
6489 
6490  // FIXME: Are there other cases which require instantiating something other
6491  // than the type to complete the type of an expression?
6492 
6493  return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
6494 }
6495 
6496 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
6497  BoundTypeDiagnoser<> Diagnoser(DiagID);
6498  return RequireCompleteExprType(E, Diagnoser);
6499 }
6500 
6501 /// @brief Ensure that the type T is a complete type.
6502 ///
6503 /// This routine checks whether the type @p T is complete in any
6504 /// context where a complete type is required. If @p T is a complete
6505 /// type, returns false. If @p T is a class template specialization,
6506 /// this routine then attempts to perform class template
6507 /// instantiation. If instantiation fails, or if @p T is incomplete
6508 /// and cannot be completed, issues the diagnostic @p diag (giving it
6509 /// the type @p T) and returns true.
6510 ///
6511 /// @param Loc The location in the source that the incomplete type
6512 /// diagnostic should refer to.
6513 ///
6514 /// @param T The type that this routine is examining for completeness.
6515 ///
6516 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
6517 /// @c false otherwise.
6519  TypeDiagnoser &Diagnoser) {
6520  if (RequireCompleteTypeImpl(Loc, T, &Diagnoser))
6521  return true;
6522  if (const TagType *Tag = T->getAs<TagType>()) {
6523  if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
6524  Tag->getDecl()->setCompleteDefinitionRequired();
6525  Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
6526  }
6527  }
6528  return false;
6529 }
6530 
6531 /// \brief Determine whether there is any declaration of \p D that was ever a
6532 /// definition (perhaps before module merging) and is currently visible.
6533 /// \param D The definition of the entity.
6534 /// \param Suggested Filled in with the declaration that should be made visible
6535 /// in order to provide a definition of this entity.
6536 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
6537 /// not defined. This only matters for enums with a fixed underlying
6538 /// type, since in all other cases, a type is complete if and only if it
6539 /// is defined.
6541  bool OnlyNeedComplete) {
6542  // Easy case: if we don't have modules, all declarations are visible.
6543  if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
6544  return true;
6545 
6546  // If this definition was instantiated from a template, map back to the
6547  // pattern from which it was instantiated.
6548  if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
6549  // We're in the middle of defining it; this definition should be treated
6550  // as visible.
6551  return true;
6552  } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6553  if (auto *Pattern = RD->getTemplateInstantiationPattern())
6554  RD = Pattern;
6555  D = RD->getDefinition();
6556  } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
6557  while (auto *NewED = ED->getInstantiatedFromMemberEnum())
6558  ED = NewED;
6559  if (OnlyNeedComplete && ED->isFixed()) {
6560  // If the enum has a fixed underlying type, and we're only looking for a
6561  // complete type (not a definition), any visible declaration of it will
6562  // do.
6563  *Suggested = nullptr;
6564  for (auto *Redecl : ED->redecls()) {
6565  if (isVisible(Redecl))
6566  return true;
6567  if (Redecl->isThisDeclarationADefinition() ||
6568  (Redecl->isCanonicalDecl() && !*Suggested))
6569  *Suggested = Redecl;
6570  }
6571  return false;
6572  }
6573  D = ED->getDefinition();
6574  }
6575  assert(D && "missing definition for pattern of instantiated definition");
6576 
6577  *Suggested = D;
6578  if (isVisible(D))
6579  return true;
6580 
6581  // The external source may have additional definitions of this type that are
6582  // visible, so complete the redeclaration chain now and ask again.
6583  if (auto *Source = Context.getExternalSource()) {
6584  Source->CompleteRedeclChain(D);
6585  return isVisible(D);
6586  }
6587 
6588  return false;
6589 }
6590 
6591 /// Locks in the inheritance model for the given class and all of its bases.
6593  RD = RD->getMostRecentDecl();
6594  if (!RD->hasAttr<MSInheritanceAttr>()) {
6595  MSInheritanceAttr::Spelling IM;
6596 
6599  IM = RD->calculateInheritanceModel();
6600  break;
6602  IM = MSInheritanceAttr::Keyword_single_inheritance;
6603  break;
6605  IM = MSInheritanceAttr::Keyword_multiple_inheritance;
6606  break;
6608  IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
6609  break;
6610  }
6611 
6612  RD->addAttr(MSInheritanceAttr::CreateImplicit(
6613  S.getASTContext(), IM,
6614  /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
6618  : RD->getSourceRange()));
6619  }
6620 }
6621 
6622 /// \brief The implementation of RequireCompleteType
6623 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
6624  TypeDiagnoser *Diagnoser) {
6625  // FIXME: Add this assertion to make sure we always get instantiation points.
6626  // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
6627  // FIXME: Add this assertion to help us flush out problems with
6628  // checking for dependent types and type-dependent expressions.
6629  //
6630  // assert(!T->isDependentType() &&
6631  // "Can't ask whether a dependent type is complete");
6632 
6633  // We lock in the inheritance model once somebody has asked us to ensure
6634  // that a pointer-to-member type is complete.
6636  if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
6637  if (!MPTy->getClass()->isDependentType()) {
6638  (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
6639  assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
6640  }
6641  }
6642  }
6643 
6644  // If we have a complete type, we're done.
6645  NamedDecl *Def = nullptr;
6646  if (!T->isIncompleteType(&Def)) {
6647  // If we know about the definition but it is not visible, complain.
6648  NamedDecl *SuggestedDef = nullptr;
6649  if (Def &&
6650  !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
6651  // If the user is going to see an error here, recover by making the
6652  // definition visible.
6653  bool TreatAsComplete = Diagnoser && !isSFINAEContext();
6654  if (Diagnoser)
6655  diagnoseMissingImport(Loc, SuggestedDef, /*NeedDefinition*/true,
6656  /*Recover*/TreatAsComplete);
6657  return !TreatAsComplete;
6658  }
6659 
6660  return false;
6661  }
6662 
6663  const TagType *Tag = T->getAs<TagType>();
6664  const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
6665 
6666  // If there's an unimported definition of this type in a module (for
6667  // instance, because we forward declared it, then imported the definition),
6668  // import that definition now.
6669  //
6670  // FIXME: What about other cases where an import extends a redeclaration
6671  // chain for a declaration that can be accessed through a mechanism other
6672  // than name lookup (eg, referenced in a template, or a variable whose type
6673  // could be completed by the module)?
6674  //
6675  // FIXME: Should we map through to the base array element type before
6676  // checking for a tag type?
6677  if (Tag || IFace) {
6678  NamedDecl *D =
6679  Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
6680 
6681  // Avoid diagnosing invalid decls as incomplete.
6682  if (D->isInvalidDecl())
6683  return true;
6684 
6685  // Give the external AST source a chance to complete the type.
6686  if (auto *Source = Context.getExternalSource()) {
6687  if (Tag)
6688  Source->CompleteType(Tag->getDecl());
6689  else
6690  Source->CompleteType(IFace->getDecl());
6691 
6692  // If the external source completed the type, go through the motions
6693  // again to ensure we're allowed to use the completed type.
6694  if (!T->isIncompleteType())
6695  return RequireCompleteTypeImpl(Loc, T, Diagnoser);
6696  }
6697  }
6698 
6699  // If we have a class template specialization or a class member of a
6700  // class template specialization, or an array with known size of such,
6701  // try to instantiate it.
6702  QualType MaybeTemplate = T;
6703  while (const ConstantArrayType *Array
6704  = Context.getAsConstantArrayType(MaybeTemplate))
6705  MaybeTemplate = Array->getElementType();
6706  if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
6707  bool Instantiated = false;
6708  bool Diagnosed = false;
6709  if (ClassTemplateSpecializationDecl *ClassTemplateSpec
6710  = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
6711  if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
6713  Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
6714  /*Complain=*/Diagnoser);
6715  Instantiated = true;
6716  }
6717  } else if (CXXRecordDecl *Rec
6718  = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
6720  if (!Rec->isBeingDefined() && Pattern) {
6721  MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
6722  assert(MSI && "Missing member specialization information?");
6723  // This record was instantiated from a class within a template.
6724  if (MSI->getTemplateSpecializationKind() !=
6726  Diagnosed = InstantiateClass(Loc, Rec, Pattern,
6729  /*Complain=*/Diagnoser);
6730  Instantiated = true;
6731  }
6732  }
6733  }
6734 
6735  if (Instantiated) {
6736  // Instantiate* might have already complained that the template is not
6737  // defined, if we asked it to.
6738  if (Diagnoser && Diagnosed)
6739  return true;
6740  // If we instantiated a definition, check that it's usable, even if
6741  // instantiation produced an error, so that repeated calls to this
6742  // function give consistent answers.
6743  if (!T->isIncompleteType())
6744  return RequireCompleteTypeImpl(Loc, T, Diagnoser);
6745  }
6746  }
6747 
6748  if (!Diagnoser)
6749  return true;
6750 
6751  // We have an incomplete type. Produce a diagnostic.
6752  if (Ident___float128 &&
6754  Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128);
6755  return true;
6756  }
6757 
6758  Diagnoser->diagnose(*this, Loc, T);
6759 
6760  // If the type was a forward declaration of a class/struct/union
6761  // type, produce a note.
6762  if (Tag && !Tag->getDecl()->isInvalidDecl())
6763  Diag(Tag->getDecl()->getLocation(),
6764  Tag->isBeingDefined() ? diag::note_type_being_defined
6765  : diag::note_forward_declaration)
6766  << QualType(Tag, 0);
6767 
6768  // If the Objective-C class was a forward declaration, produce a note.
6769  if (IFace && !IFace->getDecl()->isInvalidDecl())
6770  Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
6771 
6772  // If we have external information that we can use to suggest a fix,
6773  // produce a note.
6774  if (ExternalSource)
6775  ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
6776 
6777  return true;
6778 }
6779 
6781  unsigned DiagID) {
6782  BoundTypeDiagnoser<> Diagnoser(DiagID);
6783  return RequireCompleteType(Loc, T, Diagnoser);
6784 }
6785 
6786 /// \brief Get diagnostic %select index for tag kind for
6787 /// literal type diagnostic message.
6788 /// WARNING: Indexes apply to particular diagnostics only!
6789 ///
6790 /// \returns diagnostic %select index.
6792  switch (Tag) {
6793  case TTK_Struct: return 0;
6794  case TTK_Interface: return 1;
6795  case TTK_Class: return 2;
6796  default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
6797  }
6798 }
6799 
6800 /// @brief Ensure that the type T is a literal type.
6801 ///
6802 /// This routine checks whether the type @p T is a literal type. If @p T is an
6803 /// incomplete type, an attempt is made to complete it. If @p T is a literal
6804 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
6805 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
6806 /// it the type @p T), along with notes explaining why the type is not a
6807 /// literal type, and returns true.
6808 ///
6809 /// @param Loc The location in the source that the non-literal type
6810 /// diagnostic should refer to.
6811 ///
6812 /// @param T The type that this routine is examining for literalness.
6813 ///
6814 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
6815 ///
6816 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
6817 /// @c false otherwise.
6819  TypeDiagnoser &Diagnoser) {
6820  assert(!T->isDependentType() && "type should not be dependent");
6821 
6822  QualType ElemType = Context.getBaseElementType(T);
6823  if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
6824  T->isLiteralType(Context))
6825  return false;
6826 
6827  Diagnoser.diagnose(*this, Loc, T);
6828 
6829  if (T->isVariableArrayType())
6830  return true;
6831 
6832  const RecordType *RT = ElemType->getAs<RecordType>();
6833  if (!RT)
6834  return true;
6835 
6836  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
6837 
6838  // A partially-defined class type can't be a literal type, because a literal
6839  // class type must have a trivial destructor (which can't be checked until
6840  // the class definition is complete).
6841  if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
6842  return true;
6843 
6844  // If the class has virtual base classes, then it's not an aggregate, and
6845  // cannot have any constexpr constructors or a trivial default constructor,
6846  // so is non-literal. This is better to diagnose than the resulting absence
6847  // of constexpr constructors.
6848  if (RD->getNumVBases()) {
6849  Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
6851  for (const auto &I : RD->vbases())
6852  Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
6853  << I.getSourceRange();
6854  } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
6856  Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
6857  } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
6858  for (const auto &I : RD->bases()) {
6859  if (!I.getType()->isLiteralType(Context)) {
6860  Diag(I.getLocStart(),
6861  diag::note_non_literal_base_class)
6862  << RD << I.getType() << I.getSourceRange();
6863  return true;
6864  }
6865  }
6866  for (const auto *I : RD->fields()) {
6867  if (!I->getType()->isLiteralType(Context) ||
6868  I->getType().isVolatileQualified()) {
6869  Diag(I->getLocation(), diag::note_non_literal_field)
6870  << RD << I << I->getType()
6871  << I->getType().isVolatileQualified();
6872  return true;
6873  }
6874  }
6875  } else if (!RD->hasTrivialDestructor()) {
6876  // All fields and bases are of literal types, so have trivial destructors.
6877  // If this class's destructor is non-trivial it must be user-declared.
6878  CXXDestructorDecl *Dtor = RD->getDestructor();
6879  assert(Dtor && "class has literal fields and bases but no dtor?");
6880  if (!Dtor)
6881  return true;
6882 
6883  Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
6884  diag::note_non_literal_user_provided_dtor :
6885  diag::note_non_literal_nontrivial_dtor) << RD;
6886  if (!Dtor->isUserProvided())
6887  SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
6888  }
6889 
6890  return true;
6891 }
6892 
6893 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
6894  BoundTypeDiagnoser<> Diagnoser(DiagID);
6895  return RequireLiteralType(Loc, T, Diagnoser);
6896 }
6897 
6898 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
6899 /// and qualified by the nested-name-specifier contained in SS.
6901  const CXXScopeSpec &SS, QualType T) {
6902  if (T.isNull())
6903  return T;
6904  NestedNameSpecifier *NNS;
6905  if (SS.isValid())
6906  NNS = SS.getScopeRep();
6907  else {
6908  if (Keyword == ETK_None)
6909  return T;
6910  NNS = nullptr;
6911  }
6912  return Context.getElaboratedType(Keyword, NNS, T);
6913 }
6914 
6917  if (ER.isInvalid()) return QualType();
6918  E = ER.get();
6919 
6920  if (!getLangOpts().CPlusPlus && E->refersToBitField())
6921  Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
6922 
6923  if (!E->isTypeDependent()) {
6924  QualType T = E->getType();
6925  if (const TagType *TT = T->getAs<TagType>())
6926  DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
6927  }
6928  return Context.getTypeOfExprType(E);
6929 }
6930 
6931 /// getDecltypeForExpr - Given an expr, will return the decltype for
6932 /// that expression, according to the rules in C++11
6933 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
6935  if (E->isTypeDependent())
6936  return S.Context.DependentTy;
6937 
6938  // C++11 [dcl.type.simple]p4:
6939  // The type denoted by decltype(e) is defined as follows:
6940  //
6941  // - if e is an unparenthesized id-expression or an unparenthesized class
6942  // member access (5.2.5), decltype(e) is the type of the entity named
6943  // by e. If there is no such entity, or if e names a set of overloaded
6944  // functions, the program is ill-formed;
6945  //
6946  // We apply the same rules for Objective-C ivar and property references.
6947  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6948  if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
6949  return VD->getType();
6950  } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6951  if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
6952  return FD->getType();
6953  } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
6954  return IR->getDecl()->getType();
6955  } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
6956  if (PR->isExplicitProperty())
6957  return PR->getExplicitProperty()->getType();
6958  } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
6959  return PE->getType();
6960  }
6961 
6962  // C++11 [expr.lambda.prim]p18:
6963  // Every occurrence of decltype((x)) where x is a possibly
6964  // parenthesized id-expression that names an entity of automatic
6965  // storage duration is treated as if x were transformed into an
6966  // access to a corresponding data member of the closure type that
6967  // would have been declared if x were an odr-use of the denoted
6968  // entity.
6969  using namespace sema;
6970  if (S.getCurLambda()) {
6971  if (isa<ParenExpr>(E)) {
6972  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
6973  if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
6974  QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
6975  if (!T.isNull())
6976  return S.Context.getLValueReferenceType(T);
6977  }
6978  }
6979  }
6980  }
6981 
6982 
6983  // C++11 [dcl.type.simple]p4:
6984  // [...]
6985  QualType T = E->getType();
6986  switch (E->getValueKind()) {
6987  // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6988  // type of e;
6989  case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
6990  // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6991  // type of e;
6992  case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
6993  // - otherwise, decltype(e) is the type of e.
6994  case VK_RValue: break;
6995  }
6996 
6997  return T;
6998 }
6999 
7001  bool AsUnevaluated) {
7003  if (ER.isInvalid()) return QualType();
7004  E = ER.get();
7005 
7006  if (AsUnevaluated && ActiveTemplateInstantiations.empty() &&
7007  E->HasSideEffects(Context, false)) {
7008  // The expression operand for decltype is in an unevaluated expression
7009  // context, so side effects could result in unintended consequences.
7010  Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7011  }
7012 
7013  return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
7014 }
7015 
7018  SourceLocation Loc) {
7019  switch (UKind) {
7021  if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
7022  Diag(Loc, diag::err_only_enums_have_underlying_types);
7023  return QualType();
7024  } else {
7025  QualType Underlying = BaseType;
7026  if (!BaseType->isDependentType()) {
7027  // The enum could be incomplete if we're parsing its definition or
7028  // recovering from an error.
7029  NamedDecl *FwdDecl = nullptr;
7030  if (BaseType->isIncompleteType(&FwdDecl)) {
7031  Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
7032  Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
7033  return QualType();
7034  }
7035 
7036  EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
7037  assert(ED && "EnumType has no EnumDecl");
7038 
7039  DiagnoseUseOfDecl(ED, Loc);
7040 
7041  Underlying = ED->getIntegerType();
7042  assert(!Underlying.isNull());
7043  }
7044  return Context.getUnaryTransformType(BaseType, Underlying,
7046  }
7047  }
7048  llvm_unreachable("unknown unary transform type");
7049 }
7050 
7052  if (!T->isDependentType()) {
7053  // FIXME: It isn't entirely clear whether incomplete atomic types
7054  // are allowed or not; for simplicity, ban them for the moment.
7055  if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
7056  return QualType();
7057 
7058  int DisallowedKind = -1;
7059  if (T->isArrayType())
7060  DisallowedKind = 1;
7061  else if (T->isFunctionType())
7062  DisallowedKind = 2;
7063  else if (T->isReferenceType())
7064  DisallowedKind = 3;
7065  else if (T->isAtomicType())
7066  DisallowedKind = 4;
7067  else if (T.hasQualifiers())
7068  DisallowedKind = 5;
7069  else if (!T.isTriviallyCopyableType(Context))
7070  // Some other non-trivially-copyable type (probably a C++ class)
7071  DisallowedKind = 6;
7072 
7073  if (DisallowedKind != -1) {
7074  Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
7075  return QualType();
7076  }
7077 
7078  // FIXME: Do we need any handling for ARC here?
7079  }
7080 
7081  // Build the pointer type.
7082  return Context.getAtomicType(T);
7083 }
FileNullabilityMap NullabilityMap
A mapping that describes the nullability we've seen in each header file.
Definition: Sema.h:391
Abstract class used to diagnose incomplete types.
Definition: Sema.h:1320
static QualType applyObjCProtocolQualifiers(Sema &S, SourceLocation loc, SourceRange range, QualType type, ArrayRef< ObjCProtocolDecl * > protocols, const SourceLocation *protocolLocs, bool failOnError=false)
Apply Objective-C protocol qualifiers to the given type.
Definition: SemaType.cpp:955
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
Definition: ExprObjC.h:539
static CallingConv getCCForDeclaratorChunk(Sema &S, Declarator &D, const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex)
Helper for figuring out the default CC for a function declarator type.
Definition: SemaType.cpp:2938
Kind getKind() const
Definition: Type.h:2028
bool CheckNoReturnAttr(const AttributeList &attr)
unsigned getAddressSpace() const
Return the address space of this type.
Definition: Type.h:5204
static void HandleExtVectorTypeAttr(QualType &CurType, const AttributeList &Attr, Sema &S)
Process the OpenCL-like ext_vector_type attribute when it occurs on a type.
Definition: SemaType.cpp:6083
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType) const
Defines the clang::ASTContext interface.
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
Definition: SemaDecl.cpp:2575
Represents a type that was referred to using an elaborated type keyword, e.g., struct S...
Definition: Type.h:4262
SourceLocation getEnd() const
static bool handleObjCPointerTypeAttr(TypeProcessingState &state, AttributeList &attr, QualType &type)
Definition: SemaType.cpp:301
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:64
const Type * Ty
The locally-unqualified type.
Definition: Type.h:520
IdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:971
CanQualType LongLongTy
Definition: ASTContext.h:889
static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for literal type diagnostic message.
Definition: SemaType.cpp:6791
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:4944
bool isVariadic() const
Definition: Type.h:3255
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2076
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition: DeclSpec.h:1206
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:9197
static bool isOmittedBlockReturnType(const Declarator &D)
isOmittedBlockReturnType - Return true if this declarator is missing a return type because this is a ...
Definition: SemaType.cpp:48
no exception specification
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
Definition: SemaType.cpp:2250
This is a discriminated union of FileInfo and ExpansionInfo.
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2147
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:536
A (possibly-)qualified type.
Definition: Type.h:575
ASTConsumer & Consumer
Definition: Sema.h:296
base_class_range bases()
Definition: DeclCXX.h:713
bool isInvalid() const
Definition: Ownership.h:159
const AttributeList * getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition: DeclSpec.h:1454
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1206
bool isMacroID() const
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:535
TypeResult actOnObjCTypeArgsAndProtocolQualifiers(Scope *S, SourceLocation Loc, ParsedType BaseType, SourceLocation TypeArgsLAngleLoc, ArrayRef< ParsedType > TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef< Decl * > Protocols, ArrayRef< SourceLocation > ProtocolLocs, SourceLocation ProtocolRAngleLoc)
Build a specialized and/or protocol-qualified Objective-C type.
Definition: SemaType.cpp:1078
Wrapper for source info for tag types.
Definition: TypeLoc.h:657
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:2954
TSW getTypeSpecWidth() const
Definition: DeclSpec.h:470
static void distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state, AttributeList &attr, QualType &declSpecType)
Distribute an objc_gc type attribute that was written on the declarator.
Definition: SemaType.cpp:444
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1077
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1263
static const TSS TSS_unsigned
Definition: DeclSpec.h:268
bool isMemberPointerType() const
Definition: Type.h:5329
QualType getAdjustedType(QualType Orig, QualType New) const
Return the uniqued reference to a type adjusted from the original type to a new type.
TheContext getContext() const
Definition: DeclSpec.h:1733
QualType BuildUnaryTransformType(QualType BaseType, UnaryTransformType::UTTKind UKind, SourceLocation Loc)
Definition: SemaType.cpp:7016
__auto_type (GNU extension)
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type...
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
Definition: Sema.h:2636
void setNameEndLoc(SourceLocation Loc)
Definition: TypeLoc.h:1006
static const TST TST_wchar
Definition: DeclSpec.h:275
Decl * getRepAsDecl() const
Definition: DeclSpec.h:485
CanQualType Char32Ty
Definition: ASTContext.h:888
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1673
const LangOptions & getLangOpts() const
Definition: Sema.h:1041
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false)
Perform unqualified name lookup starting from a given scope.
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:2048
The attribute is immediately after the declaration's name.
Definition: SemaType.cpp:280
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1284
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration...
Definition: DeclCXX.h:1786
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1140
NullabilityKind
Describes the nullability of a particular type.
Definition: Specifiers.h:271
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:2847
TypeLoc getNamedTypeLoc() const
Definition: TypeLoc.h:1759
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 canHaveNullability() const
Determine whether the given type can have a nullability specifier applied to it, i.e., if it is any kind of pointer type or a dependent type that could instantiate to any kind of pointer type.
Definition: Type.cpp:3495
void setEmbeddedInDeclarator(bool isInDeclarator)
Definition: Decl.h:2806
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
Definition: Preprocessor.h:927
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:738
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in...
Qualifiers::GC getObjCGCAttr() const
Returns gc attribute of this type.
Definition: Type.h:5209
A conversion function name, e.g., operator int.
Definition: DeclSpec.h:887
QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, UnaryTransformType::UTTKind UKind) const
Unary type transforms.
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:462
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
bool isRecordType() const
Definition: Type.h:5362
static const TST TST_typeofExpr
Definition: DeclSpec.h:294
QualType getUnderlyingType() const
Definition: Decl.h:2566
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1118
static const TST TST_char16
Definition: DeclSpec.h:276
static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind)
Map a nullability attribute kind to a nullability kind.
Definition: SemaType.cpp:5698
const SrcMgr::SLocEntry & getSLocEntry(FileID FID, bool *Invalid=nullptr) const
bool isTypeAltiVecBool() const
Definition: DeclSpec.h:476
WrittenBuiltinSpecs & getWrittenBuiltinSpecs()
Definition: TypeLoc.h:531
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2002
void setType(QualType t)
Definition: Expr.h:126
AttributePool & getAttributePool() const
Definition: DeclSpec.h:1721
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2149
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type...
Definition: Type.cpp:1589
Defines the C++ template declaration subclasses.
static void processTypeAttrs(TypeProcessingState &state, QualType &type, TypeAttrLocation TAL, AttributeList *attrs)
Definition: SemaType.cpp:6220
Represents a C++11 auto or C++14 decltype(auto) type.
Definition: Type.h:3918
IdentifierInfo * Ident
Definition: AttributeList.h:52
bool isEnumeralType() const
Definition: Type.h:5365
QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceRange Brackets, DeclarationName Entity)
Build an array type.
Definition: SemaType.cpp:1990
SCS getStorageClassSpec() const
Definition: DeclSpec.h:441
bool hasDefinition() const
Definition: DeclCXX.h:680
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition: DeclSpec.h:2223
PtrTy get() const
Definition: Ownership.h:163
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type...
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, unsigned TypeQuals, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation ConstQualifierLoc, SourceLocation VolatileQualifierLoc, SourceLocation RestrictQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult())
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition: DeclSpec.cpp:152
QualType getPointeeType() const
Definition: Type.h:2388
The base class of the type hierarchy.
Definition: Type.h:1249
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain=true)
static PointerDeclaratorKind classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator)
Classify the given declarator, whose type-specified is type, based on what kind of pointer it refers ...
Definition: SemaType.cpp:3073
CanQualType LongTy
Definition: ASTContext.h:889
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition: Type.h:5122
One instance of this struct is used for each type in a declarator that is parsed. ...
Definition: DeclSpec.h:1091
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:4861
SourceLocation EndLoc
EndLoc - If valid, the place where this chunck ends.
Definition: DeclSpec.h:1099
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:46
Wrapper for source info for typedefs.
Definition: TypeLoc.h:620
static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk)
Definition: SemaType.cpp:4864
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition: DeclSpec.cpp:444
bool isDecltypeAuto() const
Definition: Type.h:3933
The attribute is part of a DeclaratorChunk.
Definition: SemaType.cpp:278
bool isBooleanType() const
Definition: Type.h:5609
A container of type source information.
Definition: Decl.h:61
static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS, unsigned &TypeQuals, QualType TypeSoFar, unsigned RemoveTQs, unsigned DiagID)
Definition: SemaType.cpp:721
static void transferARCOwnership(TypeProcessingState &state, QualType &declSpecTy, Qualifiers::ObjCLifetime ownership)
Used for transferring ownership in casts resulting in l-values.
Definition: SemaType.cpp:4404
bool getHasRegParm() const
Definition: Type.h:2979
AttributeList *& getAttrListRef()
Definition: DeclSpec.h:2165
bool isBlockPointerType() const
Definition: Type.h:5311
Wrapper for source info for pointers decayed from arrays and functions.
Definition: TypeLoc.h:1095
bool hasAttrEnumOperand() const
Definition: TypeLoc.h:738
Abstract base class used for diagnosing integer constant expression violations.
Definition: Sema.h:8711
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:2940
TypeLoc getNextTypeLoc() const
Definition: TypeLoc.h:375
bool isSpelledAsLValue() const
Definition: Type.h:2304
QualType getPipeType(QualType T) const
Return pipe type for the specified type.
#define NULLABILITY_TYPE_ATTRS_CASELIST
Definition: SemaType.cpp:126
CanQualType HalfTy
Definition: ASTContext.h:893
unsigned RestrictQualLoc
The location of the restrict-qualifier, if any.
Definition: DeclSpec.h:1122
static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr)
Definition: SemaType.cpp:5802
bool checkObjCKindOfType(QualType &type, SourceLocation loc)
Check the application of the Objective-C '__kindof' qualifier to the given type.
Definition: SemaType.cpp:5659
ParsedType getTrailingReturnType() const
Get the trailing-return-type for this function declarator.
Definition: DeclSpec.h:1389
void setParensRange(SourceRange range)
Definition: TypeLoc.h:1611
SourceLocation getIncludeLoc() const
CharacteristicKind getFileCharacteristic() const
Return whether this is a system header or not.
An identifier, stored as an IdentifierInfo*.
SourceLocation getCommaLoc() const
Definition: DeclSpec.h:2208
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:699
static DeclaratorChunk * maybeMovePastReturnType(Declarator &declarator, unsigned i, bool onlyBlockPointers)
Given the index of a declarator chunk, check whether that chunk directly specifies the return type of...
Definition: SemaType.cpp:318
static const TST TST_underlyingType
Definition: DeclSpec.h:297
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1608
void removeObjCLifetime()
Definition: Type.h:296
DiagnosticsEngine & Diags
Definition: Sema.h:297
Wrapper for source info for member pointers.
Definition: TypeLoc.h:1163
Wrapper of type source information for a type with non-trivial direct qualifiers. ...
Definition: TypeLoc.h:247
ObjCLifetime getObjCLifetime() const
Definition: Type.h:290
bool hasAttrExprOperand() const
Definition: TypeLoc.h:733
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:1326
The "union" keyword.
Definition: Type.h:4180
Extra information about a function prototype.
Definition: Type.h:3067
CallingConv getCallConv() const
Definition: Type.h:2985
std::string getAsString() const
The "__interface" keyword.
Definition: Type.h:4178
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:1793
Represents a variable template specialization, which refers to a variable template with a given set o...
static const TST TST_interface
Definition: DeclSpec.h:290
static const TST TST_char
Definition: DeclSpec.h:274
A namespace, stored as a NamespaceDecl*.
Describes how types, statements, expressions, and declarations should be printed. ...
Definition: PrettyPrinter.h:35
bool hasAttrOperand() const
Definition: TypeLoc.h:743
unsigned size() const
Determine the number of type parameters in this list.
Definition: DeclObjC.h:653
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:1521
bool isArgIdent(unsigned Arg) const
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, bool Diagnose=false)
Determine whether a defaulted or deleted special member function is trivial, as specified in C++11 [c...
ParmVarDecl - Represents a parameter to a function.
Definition: Decl.h:1299
bool isObjCRetainableType() const
Definition: Type.cpp:3704
static bool handleFunctionTypeAttr(TypeProcessingState &state, AttributeList &attr, QualType &type)
Process an individual function attribute.
Definition: SemaType.cpp:5844
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:1042
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
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:1739
SourceLocation Loc
Definition: AttributeList.h:51
bool isVoidType() const
Definition: Type.h:5546
The collection of all-type qualifiers we support.
Definition: Type.h:116
void setParensRange(SourceRange Range)
Definition: TypeLoc.h:2020
static const TST TST_unknown_anytype
Definition: DeclSpec.h:300
SourceLocation getPragmaAssumeNonNullLoc() const
The location of the currently-active #pragma clang assume_nonnull begin.
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:40
QualType BuildMemberPointerType(QualType T, QualType Class, SourceLocation Loc, DeclarationName Entity)
Build a member pointer type T Class::*.
Definition: SemaType.cpp:2289
RecordDecl - Represents a struct/union/class.
Definition: Decl.h:3166
__ptr16, alignas(...), etc.
Definition: AttributeList.h:83
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
Expr * NoexceptExpr
Pointer to the expression in the noexcept-specifier of this function, if it has one.
Definition: DeclSpec.h:1282
FunctionType::ExtInfo ExtInfo
Definition: Type.h:3082
Represents a class template specialization, which refers to a class template with a given set of temp...
One of these records is kept for each identifier that is lexed.
void setLocalRangeEnd(SourceLocation L)
Definition: TypeLoc.h:1270
static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc, QualifiedFunctionKind QFK)
Check whether the type T is a qualified function type, and if it is, diagnose that it cannot be conta...
Definition: SemaType.cpp:1828
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1144
static void distributeFunctionTypeAttr(TypeProcessingState &state, AttributeList &attr, QualType type)
A function type attribute was written somewhere in a declaration other than on the declarator itself ...
Definition: SemaType.cpp:506
static const TST TST_decimal32
Definition: DeclSpec.h:284
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:4381
bool hasAttr() const
Definition: DeclBase.h:498
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition: DeclSpec.h:929
void removeRestrict()
Definition: Type.h:247
Represents a class type in Objective C.
Definition: Type.h:4557
AttributeList * getList() const
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:1766
llvm::PointerUnion< Expr *, IdentifierLoc * > ArgsUnion
A union of the various pointer types that can be passed to an AttributeList as an argument...
Definition: AttributeList.h:60
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:91
A C++ nested-name-specifier augmented with source location information.
is ARM Neon vector
Definition: Type.h:2731
SourceLocation getRestrictQualifierLoc() const
Retrieve the location of the 'restrict' qualifier, if any.
Definition: DeclSpec.h:1362
bool isTypeSpecPipe() const
Definition: DeclSpec.h:479
LineState State
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:3165
bool isObjCARCImplicitlyUnretainedType() const
Determines if this type, which must satisfy isObjCLifetimeType(), is implicitly __unsafe_unretained r...
Definition: Type.cpp:3674
QualType BuildParenType(QualType T)
Build a paren type including T.
Definition: SemaType.cpp:1732
void setBuiltinLoc(SourceLocation Loc)
Definition: TypeLoc.h:525
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:1727
SourceLocation getTypeSpecSignLoc() const
Definition: DeclSpec.h:502
QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
TSS getTypeSpecSign() const
Definition: DeclSpec.h:472
void setRBracketLoc(SourceLocation Loc)
Definition: TypeLoc.h:1373
static SourceLocation getFromRawEncoding(unsigned Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
bool isReferenceType() const
Definition: Type.h:5314
static bool distributeNullabilityTypeAttr(TypeProcessingState &state, QualType type, AttributeList &attr)
Distribute a nullability type attribute that cannot be applied to the type specifier to a pointer...
Definition: SemaType.cpp:5720
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
static const TST TST_class
Definition: DeclSpec.h:291
void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl< QualType > &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI)
Check the given exception-specification and update the exception specification information with the r...
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:2209
bool isCompleteDefinition() const
isCompleteDefinition - Return true if this decl has its body fully specified.
Definition: Decl.h:2788
bool isAnyPointerType() const
Definition: Type.h:5308
static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, AttributeList &attr, QualType &type)
handleObjCOwnershipTypeAttr - Process an objc_ownership attribute on the specified type...
Definition: SemaType.cpp:5119
unsigned TypeQuals
The type qualifiers: const/volatile/restrict.
Definition: DeclSpec.h:1210
bool isEmpty() const
isEmpty - Return true if this declaration specifier is completely empty: no tokens were parsed in the...
Definition: DeclSpec.h:595
bool isBeingDefined() const
Determines whether this type is in the process of being defined.
Definition: Type.cpp:2965
static const TST TST_double
Definition: DeclSpec.h:282
static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr, QualType type)
diagnoseBadTypeAttribute - Diagnoses a type attribute which doesn't apply to the given type...
Definition: SemaType.cpp:65
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1788
static std::string getPrintableNameForEntity(DeclarationName Entity)
Definition: SemaType.cpp:1647
TagKind getTagKind() const
Definition: Decl.h:2847
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition: DeclBase.h:374
ParsedType ActOnObjCInstanceType(SourceLocation Loc)
The parser has parsed the context-sensitive type 'instancetype' in an Objective-C message declaration...
Definition: SemaType.cpp:4992
static const TST TST_error
Definition: DeclSpec.h:302
TypeLoc getValueLoc() const
Definition: TypeLoc.h:2043
virtual bool MaybeDiagnoseMissingCompleteType(SourceLocation Loc, QualType T)
Produces a diagnostic note if the external source contains a complete definition for T...
static const TST TST_enum
Definition: DeclSpec.h:287
QualType getTypeOfType(QualType t) const
getTypeOfType - Unlike many "get<Type>" functions, we don't unique TypeOfType nodes...
static void maybeSynthesizeBlockSignature(TypeProcessingState &state, QualType declSpecType)
Add a synthetic '()' to a block-literal declarator if it is required, given the return type...
Definition: SemaType.cpp:661
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:503
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:1744
static const TSW TSW_unspecified
Definition: DeclSpec.h:253
void copy(DependentTemplateSpecializationTypeLoc Loc)
Definition: TypeLoc.h:1925
static unsigned getNumAddressingBits(ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition: Type.cpp:77
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition: TypeLoc.h:1688
Wrapper of type source information for a type with no direct qualifiers.
Definition: TypeLoc.h:222
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
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:1191
virtual void HandleTagDeclRequiredDefinition(const TagDecl *D)
This callback is invoked the first time each TagDecl is required to be complete.
Definition: ASTConsumer.h:79
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator, which is not a function declaration or definition and therefore is not permitted to have default arguments.
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword...
Definition: Diagnostic.h:1112
llvm::BumpPtrAllocator BumpAlloc
Definition: Sema.h:919
IdentifierTable & Idents
Definition: ASTContext.h:451
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:102
Values of this type can be null.
static void inferARCWriteback(TypeProcessingState &state, QualType &declSpecType)
Given that this is the declaration of a parameter under ARC, attempt to infer attributes and such for...
Definition: SemaType.cpp:2378
T * getAttr() const
Definition: DeclBase.h:495
bool hasStatic
True if this dimension included the 'static' keyword.
Definition: DeclSpec.h:1145
PointerTypeInfo Ptr
Definition: DeclSpec.h:1430
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:1633
void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly...
Definition: SemaType.cpp:5977
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:874
bool isCompleteType(SourceLocation Loc, QualType T)
Definition: Sema.h:1416
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition: Sema.cpp:1080
QualType getParenType(QualType NamedType) const
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:496
static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, TypeSourceInfo *&ReturnTypeInfo)
Definition: SemaType.cpp:2592
Represents the results of name lookup.
Definition: Sema/Lookup.h:30
const internal::VariadicDynCastAllOfMatcher< Decl, TypedefDecl > typedefDecl
Matches typedef declarations.
Definition: ASTMatchers.h:169
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:580
static void HandleVectorSizeAttr(QualType &CurType, const AttributeList &Attr, Sema &S)
HandleVectorSizeAttribute - this attribute is only applicable to integral and float scalars...
Definition: SemaType.cpp:6024
An lvalue ref-qualifier was provided (&).
Definition: Type.h:1208
unsigned ConstQualLoc
The location of the const-qualifier, if any.
Definition: DeclSpec.h:1116
bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics...
Definition: SemaExpr.cpp:324
void setCaretLoc(SourceLocation Loc)
Definition: TypeLoc.h:1153
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:1983
static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head)
Definition: SemaType.cpp:249
SourceLocation getRAngleLoc() const
Definition: TypeLoc.h:1462
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition: DeclSpec.h:2099
QualType getReturnType() const
Definition: Type.h:2977
Wrapper for source info for functions.
Definition: TypeLoc.h:1255
static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
Definition: Type.cpp:2372
ArrayTypeInfo Arr
Definition: DeclSpec.h:1432
static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, AttributeList &attr, QualType &type)
Definition: SemaType.cpp:5488
static bool hasDirectOwnershipQualifier(QualType type)
Does this type have a "direct" ownership qualifier? That is, is it written like "__strong id"...
Definition: SemaType.cpp:5088
Whether values of this type can be null is (explicitly) unspecified.
An x-value expression is a reference to an object with independent storage but which can be "moved"...
Definition: Specifiers.h:111
Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const
Recurses in pointer/array types until it finds an Objective-C retainable type and returns its ownersh...
static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, QualType &declSpecType)
Given that there are attributes written on the declarator itself, try to distribute any type attribut...
Definition: SemaType.cpp:614
field_range fields() const
Definition: Decl.h:3295
SplitQualType getSplitUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:5176
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:3723
bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC, const FunctionDecl *FD=nullptr)
bool hasNonLiteralTypeFieldsOrBases() const
Determine whether this class has a non-literal or/ volatile type non-static data member or base class...
Definition: DeclCXX.h:1284
void addCVRQualifiers(unsigned mask)
Definition: Type.h:263
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:2486
An implicit 'self' parameter.
Definition: DeclSpec.h:899
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
Definition: Expr.h:146
bool needsExtraLocalData() const
Definition: TypeLoc.h:538
RecordDecl * getDecl() const
Definition: Type.h:3553
void AddInnermostTypeInfo(const DeclaratorChunk &TI)
Add a new innermost chunk to this declarator.
Definition: DeclSpec.h:1978
CanQualType LongDoubleTy
Definition: ASTContext.h:892
Values of this type can never be null.
QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc)
Given a variable, determine the type that a reference to that variable will have in the given scope...
Definition: SemaExpr.cpp:13392
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:38
Wrapper for source info for ObjC interfaces.
Definition: TypeLoc.h:981
QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc)
Build an ext-vector type.
Definition: SemaType.cpp:2185
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:63
TypeClass getTypeClass() const
Definition: Type.h:1501
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:1728
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
Definition: Type.cpp:1886
#define MS_TYPE_ATTRS_CASELIST
Definition: SemaType.cpp:119
std::string getAsString() const
getNameAsString - Retrieve the human-readable string for this name.
static FileID getNullabilityCompletenessCheckFileID(Sema &S, SourceLocation loc)
Definition: SemaType.cpp:3211
Preprocessor & PP
Definition: Sema.h:294
bool isInvalid() const
void setLocalRangeBegin(SourceLocation L)
Definition: TypeLoc.h:1263
static void transferARCOwnershipToDeclSpec(Sema &S, QualType &declSpecTy, Qualifiers::ObjCLifetime ownership)
Definition: SemaType.cpp:4353
Represents an ObjC class declaration.
Definition: DeclObjC.h:853
void copy(ElaboratedTypeLoc Loc)
Definition: TypeLoc.h:1767
SourceLocation getLocStart() const LLVM_READONLY
Definition: DeclSpec.h:497
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:496
bool empty() const
Definition: Type.h:359
void setInvalid(bool b=true) const
detail::InMemoryDirectory::const_iterator I
is ARM Neon polynomial vector
Definition: Type.h:2732
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this attribute.
unsigned getNumParams() const
Definition: TypeLoc.h:1301
SmallVector< TemplateTypeParmDecl *, 4 > AutoTemplateParams
Store the list of the auto parameters for a generic lambda.
Definition: ScopeInfo.h:677
CanQualType UnsignedCharTy
Definition: ASTContext.h:890
QualType getType() const
Definition: Decl.h:530
bool isInvalid() const
const LangOptions & LangOpts
Definition: Sema.h:293
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type...
Definition: TypeLoc.h:53
static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy)
Definition: SemaType.cpp:1788
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:1677
uint8_t PointerKind
Which kind of pointer declarator we saw.
Definition: Sema.h:222
This object can be modified without requiring retains or releases.
Definition: Type.h:137
SourceRange getRange() const
Definition: DeclSpec.h:68
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5...
Definition: Sema.h:6811
DiagnosticsEngine & getDiagnostics() const
static const TST TST_float
Definition: DeclSpec.h:281
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void setUnderlyingTInfo(TypeSourceInfo *TI) const
Definition: TypeLoc.h:1649
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
Definition: SemaType.cpp:4956
AttributedType::Kind getAttrKind() const
Definition: TypeLoc.h:729
QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity)
Build a block pointer type.
Definition: SemaType.cpp:2340
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition: TypeLoc.h:145
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:1719
SourceRange getTypeofParensRange() const
Definition: DeclSpec.h:511
bool hasConstexprNonCopyMoveConstructor() const
Determine whether this class has at least one constexpr constructor other than the copy or move const...
Definition: DeclCXX.h:1185
ExtInfo getExtInfo() const
Definition: Type.h:2986
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:259
static const TSW TSW_long
Definition: DeclSpec.h:255
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
CXXRecordDecl * getMostRecentDecl()
Definition: DeclCXX.h:666
static bool handleObjCGCTypeAttr(TypeProcessingState &state, AttributeList &attr, QualType &type)
handleObjCGCTypeAttr - Process the attribute((objc_gc)) type attribute on the specified type...
Definition: SemaType.cpp:5303
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2045
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
TST getTypeSpecType() const
Definition: DeclSpec.h:473
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3041
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition: DeclCXX.cpp:1214
Kind getKind() const
void setParensRange(SourceRange Range)
Definition: TypeLoc.h:1699
Holds a QualType and a TypeSourceInfo* that came out of a declarator parsing.
Definition: LocInfoType.h:29
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:980
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1233
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition: Type.h:2430
ASTContext * Context
std::vector< bool > & Stack
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/atomic.
Definition: DeclSpec.h:1113
void addObjCLifetime(ObjCLifetime type)
Definition: Type.h:297
static QualType ConvertDeclSpecToType(TypeProcessingState &state)
Convert the specified declspec to the appropriate type object.
Definition: SemaType.cpp:1180
void setSizeExpr(Expr *Size)
Definition: TypeLoc.h:1384
bool checkNullabilityTypeSpecifier(QualType &type, NullabilityKind nullability, SourceLocation nullabilityLoc, bool isContextSensitive)
Check whether a nullability type specifier can be added to the given type.
Definition: SemaType.cpp:5554
const SmallVectorImpl< AnnotatedLine * >::const_iterator End
unsigned NumExceptions
NumExceptions - This is the number of types in the dynamic-exception- decl, if the function has one...
Definition: DeclSpec.h:1237
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
NameKind getNameKind() const
getNameKind - Determine what kind of name this is.
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:534
bool isRealFloatingType() const
Floating point categories.
Definition: Type.cpp:1793
const WrittenBuiltinSpecs & getWrittenBuiltinSpecs() const
Definition: DeclSpec.h:753
QualType BuildObjCObjectType(QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc, ArrayRef< TypeSourceInfo * > TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef< ObjCProtocolDecl * > Protocols, ArrayRef< SourceLocation > ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError=false)
Build an Objective-C object pointer type.
Definition: SemaType.cpp:1005
SourceLocation getLParenLoc() const
Definition: DeclSpec.h:1322
bool isKindOfType() const
Whether this is a "__kindof" type.
Definition: Type.h:4910
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition: Type.h:5097
SourceLocation getVolatileQualifierLoc() const
Retrieve the location of the 'volatile' qualifier, if any.
Definition: DeclSpec.h:1357
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:155
Type source information for an attributed type.
Definition: TypeLoc.h:724
const Type * getTypeForDecl() const
Definition: Decl.h:2507
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, const TemplateArgumentList *Innermost=nullptr, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Definition: Decl.h:521
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:5615
Expr - This represents one expression.
Definition: Expr.h:104
MSInheritanceAttr::Spelling calculateInheritanceModel() const
Calculate what the inheritance model would be for this class.
StringRef getName() const
Return the actual identifier string.
static unsigned getMaxSizeBits(ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition: Type.cpp:112
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:538
void * getOpaqueData() const
Get the pointer where source information is stored.
Definition: TypeLoc.h:116
SourceLocation getTypeSpecComplexLoc() const
Definition: DeclSpec.h:501
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:3696
Declaration of a template type parameter.
TypeSpecifierWidth getWrittenWidthSpec() const
Definition: TypeLoc.h:572
bool isFunctionDefinition() const
Definition: DeclSpec.h:2219
unsigned VolatileQualLoc
The location of the volatile-qualifier, if any.
Definition: DeclSpec.h:1119
This file defines the classes used to store parsed information about declaration-specifiers and decla...
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:4189
TypeResult ActOnTypeName(Scope *S, Declarator &D)
Definition: SemaType.cpp:4963
bool isAtomicType() const
Definition: Type.h:5387
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2345
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:111
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:875
QualType BuildAtomicType(QualType T, SourceLocation Loc)
Definition: SemaType.cpp:7051
bool isVariableArrayType() const
Definition: Type.h:5353
Defines the clang::Preprocessor interface.
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, bool AllowFold=true)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
Definition: SemaExpr.cpp:12273
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:3169
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
static void HandleNeonVectorTypeAttr(QualType &CurType, const AttributeList &Attr, Sema &S, VectorType::VectorKind VecKind)
HandleNeonVectorTypeAttr - The "neon_vector_type" and "neon_polyvector_type" attributes are used ...
Definition: SemaType.cpp:6173
void completeExprArrayBound(Expr *E)
Definition: SemaType.cpp:6420
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:537
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition: Specifiers.h:246
const internal::VariadicDynCastAllOfMatcher< Decl, RecordDecl > recordDecl
Matches class, struct, and union declarations.
Definition: ASTMatchers.h:319
CanQualType ShortTy
Definition: ASTContext.h:889
An abstract interface that should be implemented by listeners that want to be notified when an AST en...
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
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:14543
static const TST TST_decimal64
Definition: DeclSpec.h:285
bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:6518
Defines the clang::TypeLoc interface and its subclasses.
A namespace alias, stored as a NamespaceAliasDecl*.
bool isObjCIdType() const
Definition: Type.h:5401
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:1388
static QualType getDecltypeForExpr(Sema &S, Expr *E)
getDecltypeForExpr - Given an expr, will return the decltype for that expression, according to the ru...
Definition: SemaType.cpp:6934
bool isConstexprSpecified() const
Definition: DeclSpec.h:698
CanQualType UnsignedInt128Ty
Definition: ASTContext.h:891
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition: Type.h:518
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:994
Kind getAttrKind() const
Definition: Type.h:3661
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:318
TypeDiagSelector
Definition: SemaType.cpp:40
static Optional< NullabilityKind > stripOuterNullability(QualType &T)
Strip off the top-level nullability annotation on the given type, if it's there.
Definition: Type.cpp:3624
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
bool LValueRef
True if this is an lvalue reference, false if it's an rvalue reference.
Definition: DeclSpec.h:1135
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition: DeclSpec.h:582
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:1751
SourceLocation Loc
Loc - The place where this type was defined.
Definition: DeclSpec.h:1097
bool isFunctionOrMethod() const
Definition: DeclBase.h:1249
Qualifiers Quals
The local qualifiers.
Definition: Type.h:523
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1200
SourceLocation getConstQualifierLoc() const
Retrieve the location of the 'const' qualifier, if any.
Definition: DeclSpec.h:1352
static const TST TST_int
Definition: DeclSpec.h:278
void setHasBaseTypeAsWritten(bool HasBaseType)
Definition: TypeLoc.h:937
void setEllipsisLoc(SourceLocation EL)
Definition: DeclSpec.h:2213
static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, AttributeList &attr, QualType &declSpecType)
A function type attribute was written in the decl spec.
Definition: SemaType.cpp:560
void setPointOfInstantiation(SourceLocation Loc)
static QualType inferARCLifetimeForPointee(Sema &S, QualType type, SourceLocation loc, bool isReference)
Given that we're building a pointer or reference to the given.
Definition: SemaType.cpp:1737
TypeSourceInfo * GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, TypeSourceInfo *ReturnTypeInfo)
Create and instantiate a TypeSourceInfo with type source information.
Definition: SemaType.cpp:4897
Compare two source locations.
SmallVector< ActiveTemplateInstantiation, 16 > ActiveTemplateInstantiations
List of active template instantiations.
Definition: Sema.h:6601
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
Definition: SemaType.cpp:6818
static const TST TST_half
Definition: DeclSpec.h:280
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:2334
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
Definition: Decl.h:190
ExceptionSpecificationType getExceptionSpecType() const
Get the type of exception specification this function has.
Definition: DeclSpec.h:1380
Wraps an identifier and optional source location for the identifier.
Definition: AttributeList.h:50
bool hasTrailingReturnType() const
Determine whether this function declarator had a trailing-return-type.
Definition: DeclSpec.h:1386
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
static QualType Desugar(ASTContext &Context, QualType QT, bool &ShouldAKA)
The result type of a method or function.
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:144
SourceLocation getLocEnd() const LLVM_READONLY
Definition: TypeLoc.h:131
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:1797
bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
Definition: SemaType.cpp:6478
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition: Type.h:704
static const TSW TSW_short
Definition: DeclSpec.h:254
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:162
AttributeList * create(IdentifierInfo *attrName, SourceRange attrRange, IdentifierInfo *scopeName, SourceLocation scopeLoc, ArgsUnion *args, unsigned numArgs, AttributeList::Syntax syntax, SourceLocation ellipsisLoc=SourceLocation())
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:228
SourceLocation getPointOfInstantiation() const
Get the point of instantiation (if any), or null if none.
SourceLocation PointerLoc
The first pointer declarator (of any pointer kind) in the file that does not have a corresponding nul...
Definition: Sema.h:219
CanQualType SignedCharTy
Definition: ASTContext.h:889
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:545
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
Definition: SemaType.cpp:4455
bool isObjectType() const
Determine whether this type is an object type.
Definition: Type.h:1556
bool hasObjCLifetime() const
Definition: Type.h:289
TypeAndRange * Exceptions
Pointer to a new[]'d array of TypeAndRange objects that contain the types in the function's dynamic e...
Definition: DeclSpec.h:1278
bool getSuppressSystemWarnings() const
Definition: Diagnostic.h:460
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:76
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1170
static const TST TST_char32
Definition: DeclSpec.h:277
void addAttr(Attr *A)
Definition: DeclBase.h:449
QualType getPackExpansionType(QualType Pattern, Optional< unsigned > NumExpansions)
void setTypeofLoc(SourceLocation Loc)
Definition: TypeLoc.h:1590
Context-sensitive version of a keyword attribute.
Definition: AttributeList.h:85
bool SawTypeNullability
Whether we saw any type nullability annotations in the given file.
Definition: Sema.h:225
bool isPrototypeContext() const
Definition: DeclSpec.h:1735
static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, Declarator &D, unsigned FunctionChunkIndex)
Definition: SemaType.cpp:2524
Wrapper for source info for arrays.
Definition: TypeLoc.h:1358
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
CanQualType OverloadTy
Definition: ASTContext.h:896
There is no lifetime qualification on this type.
Definition: Type.h:133
Information about a FileID, basically just the logical file that it represents and include stack info...
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:215
void setAttrOperandParensRange(SourceRange range)
Definition: TypeLoc.h:801
is AltiVec 'vector Pixel'
Definition: Type.h:2729
The "struct" keyword.
Definition: Type.h:4176
Assigning into this object requires the old value to be released and the new value to be retained...
Definition: Type.h:144
Kind
TypeLoc getValueLoc() const
Definition: TypeLoc.h:1988
not a target-specific vector type
Definition: Type.h:2727
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:145
The attribute is in the decl-specifier-seq.
Definition: SemaType.cpp:276
enum clang::DeclaratorChunk::@183 Kind
void setKNRPromoted(bool promoted)
Definition: Decl.h:1376
static bool distributeFunctionTypeAttrToInnermost(TypeProcessingState &state, AttributeList &attr, AttributeList *&attrList, QualType &declSpecType)
Try to distribute a function type attribute to the innermost function chunk or type.
Definition: SemaType.cpp:539
static bool isPermittedNeonBaseType(QualType &Ty, VectorType::VectorKind VecKind, Sema &S)
Definition: SemaType.cpp:6118
Encodes a location in the source.
Sugar for parentheses used when specifying types.
Definition: Type.h:2116
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static const TST TST_auto_type
Definition: DeclSpec.h:299
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any...
Definition: ASTContext.h:932
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
Definition: Type.h:3570
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:5089
bool CheckDistantExceptionSpec(QualType T)
CheckDistantExceptionSpec - Check if the given type is a pointer or pointer to member to a function w...
ReferenceTypeInfo Ref
Definition: DeclSpec.h:1431
PointerDeclaratorKind
Describes the kind of a pointer a declarator describes.
Definition: SemaType.cpp:3053
CanQualType Int128Ty
Definition: ASTContext.h:889
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition: Type.h:3271
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:4766
The maximum supported address space number.
Definition: Type.h:156
An overloaded operator name, e.g., operator+.
Definition: DeclSpec.h:885
Expr * getRepAsExpr() const
Definition: DeclSpec.h:489
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:1731
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition: Type.h:5359
bool isValid() const
Return true if this is a valid SourceLocation object.
TagDecl - Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:2644
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context...
Definition: DeclSpec.cpp:143
static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, Qualifiers::ObjCLifetime ownership, unsigned chunkIndex)
Definition: SemaType.cpp:4364
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:1876
FunctionTypeInfo Fun
Definition: DeclSpec.h:1433
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.
ASTContext & getASTContext() const
Definition: Sema.h:1048
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...
static const TST TST_union
Definition: DeclSpec.h:288
ParsedType getRepAsType() const
Definition: DeclSpec.h:481
static void moveAttrFromListToList(AttributeList &attr, AttributeList *&fromList, AttributeList *&toList)
Definition: SemaType.cpp:266
TSC getTypeSpecComplex() const
Definition: DeclSpec.h:471
SourceLocation getLocalBeginLoc() const
Retrieve the location of the beginning of this component of the nested-name-specifier.
static const TSS TSS_signed
Definition: DeclSpec.h:267
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition: Sema.h:561
RecordDecl * CFError
The struct behind the CFErrorRef pointer.
Definition: Sema.h:9184
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
Definition: SemaType.cpp:6540
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
ExprResult DefaultLvalueConversion(Expr *E)
Definition: SemaExpr.cpp:618
No ref-qualifier was provided.
Definition: Type.h:1206
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T)
Retrieve a version of the type 'T' that is elaborated by Keyword and qualified by the nested-name-spe...
Definition: SemaType.cpp:6900
CanQualType FloatTy
Definition: ASTContext.h:892
bool hasUserProvidedDefaultConstructor() const
Whether this class has a user-provided default constructor per C++11.
Definition: DeclCXX.h:845
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...
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:194
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:3522
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2094
MemberPointerTypeInfo Mem
Definition: DeclSpec.h:1435
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return true if this expression is a valid integer constant expression...
static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type, ArrayRef< TypeSourceInfo * > typeArgs, SourceRange typeArgsRange, bool failOnError=false)
Apply Objective-C type arguments to the given type.
Definition: SemaType.cpp:747
SimplePointerKind
A simple notion of pointer kinds, which matches up with the various pointer declarators.
Definition: SemaType.cpp:3002
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
CanQualType VoidTy
Definition: ASTContext.h:881
const DeclaratorChunk * getInnermostNonParenChunk() const
Return the innermost (closest to the declarator) chunk of this declarator that is not a parens chunk...
Definition: DeclSpec.h:2013
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
Definition: SemaType.cpp:1654
const FileInfo & getFile() const
is AltiVec 'vector bool ...'
Definition: Type.h:2730
bool isRValue() const
Definition: Expr.h:247
static const TST TST_typeofType
Definition: DeclSpec.h:293
is AltiVec vector
Definition: Type.h:2728
SourceLocation getBegin() const
void setAmpLoc(SourceLocation Loc)
Definition: TypeLoc.h:1228
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:164
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:5706
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:72
bool isArgExpr(unsigned Arg) const
void setLBracketLoc(SourceLocation Loc)
Definition: TypeLoc.h:1366
AttributeList *& getAttrListRef()
Definition: DeclSpec.h:1458
IdentifierInfo * getScopeName() const
QualType getAttributedType(AttributedType::Kind attrKind, QualType modifiedType, QualType equivalentType)
This template specialization was formed from a template-id but has not yet been declared, defined, or instantiated.
Definition: Specifiers.h:141
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent) const
C++11 deduced auto type.
PtrTy get() const
Definition: Ownership.h:74
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
Definition: SemaType.cpp:1889
bool HasRestrict
The type qualifier: restrict. [GNU] C++ extension.
Definition: DeclSpec.h:1133
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/_Atomic.
Definition: DeclSpec.h:1403
static bool isVectorSizeTooLarge(unsigned NumElements)
Definition: Type.h:2750
IdentifierLoc * getArgAsIdent(unsigned Arg) const
bool isStaticMember()
Returns true if this declares a static member.
Definition: DeclSpec.cpp:338
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1210
Assigning into this object requires a lifetime extension.
Definition: Type.h:150
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:645
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:432
SourceLocation getExceptionSpecLocBeg() const
Definition: DeclSpec.h:1334
QualType getType() const
Return the type wrapped by this type source info.
Definition: Decl.h:69
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:193
QualType getObjCInstanceType()
Retrieve the Objective-C "instancetype" type, if already known; otherwise, returns a NULL type;...
Definition: ASTContext.h:1469
bool isFunctionProtoType() const
Definition: Type.h:1630
A constructor named via a template-id.
Definition: DeclSpec.h:893
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:4471
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
bool containsPlaceholderType() const
Definition: DeclSpec.h:514
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1277
void setTypeArgsLAngleLoc(SourceLocation Loc)
Definition: TypeLoc.h:871
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:1743
CanQualType UnsignedShortTy
Definition: ASTContext.h:890
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
TypeLoc findExplicitQualifierLoc() const
Find a type with the location of an explicit type qualifier.
Definition: TypeLoc.cpp:379
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:2526
attr::Kind getKind() const
Definition: Attr.h:86
QualType getType() const
Definition: Expr.h:125
sema::LambdaScopeInfo * getCurLambda()
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:1207
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T-> getSizeExpr()))
CanQualType CharTy
Definition: ASTContext.h:883
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 ...
static const TST TST_decltype_auto
Definition: DeclSpec.h:296
void setClassTInfo(TypeSourceInfo *TI)
Definition: TypeLoc.h:1180
TagTypeKind
The kind of a tag type.
Definition: Type.h:4174
CanQualType ObjCBuiltinIdTy
Definition: ASTContext.h:899
void checkUnusedDeclAttributes(Declarator &D)
checkUnusedDeclAttributes - Given a declarator which is not being used to build a declaration...
unsigned TypeQuals
The type qualifiers for the array: const/volatile/restrict/_Atomic.
Definition: DeclSpec.h:1142
SourceLocation ImplicitMSInheritanceAttrLoc
Source location for newly created implicit MSInheritanceAttrs.
Definition: Sema.h:359
static const TSS TSS_unspecified
Definition: DeclSpec.h:266
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1121
void setAmpAmpLoc(SourceLocation Loc)
Definition: TypeLoc.h:1241
bool CheckFunctionReturnType(QualType T, SourceLocation Loc)
Definition: SemaType.cpp:2226
static const TST TST_decltype
Definition: DeclSpec.h:295
static const TST TST_auto
Definition: DeclSpec.h:298
bool isFriendSpecified() const
Definition: DeclSpec.h:692
static const TST TST_void
Definition: DeclSpec.h:273
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1308
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Definition: ASTMatchers.h:1723
SourceLocation getLocStart() const LLVM_READONLY
Definition: TypeLoc.h:130
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with ',...)', this is true.
Definition: DeclSpec.h:1199
SourceLocation getTypeSpecTypeNameLoc() const
Definition: DeclSpec.h:506
static const TST TST_int128
Definition: DeclSpec.h:279
bool isInvalidDecl() const
Definition: DeclBase.h:509
QualType IgnoreParens() const
Returns the specified type after dropping any outer-level parentheses.
Definition: Type.h:888
QualType getEquivalentType() const
Definition: Type.h:3666
std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const
Get a string to suggest for zero-initialization of a type.
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:891
static void checkNullabilityConsistency(TypeProcessingState &state, SimplePointerKind pointerKind, SourceLocation pointerLoc)
Check for consistent use of nullability.
Definition: SemaType.cpp:3249
bool hasTagDefinition() const
Definition: DeclSpec.cpp:351
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:104
QualType BuildPointerType(QualType T, SourceLocation Loc, DeclarationName Entity)
Build a pointer type.
Definition: SemaType.cpp:1854
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
std::pair< SourceLocation, SourceLocation > getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:514
Expr * getArgAsExpr(unsigned Arg) const
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1170
DeclarationName - The name of a declaration.
Represents the declaration of an Objective-C type parameter.
Definition: DeclObjC.h:537
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
SourceLocation getLocEnd() const LLVM_READONLY
Definition: DeclSpec.h:498
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
EnumDecl - Represents an enum.
Definition: Decl.h:2930
#define FUNCTION_TYPE_ATTRS_CASELIST
Definition: SemaType.cpp:104
static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal)
Check whether the specified array size makes the array type a VLA.
Definition: SemaType.cpp:1955
detail::InMemoryDirectory::const_iterator E
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2369
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
bool isHalfType() const
Definition: Type.h:5552
bool isSamplerT() const
Definition: Type.h:5468
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:1946
A type that was preceded by the 'template' keyword, stored as a Type*.
static const TST TST_unspecified
Definition: DeclSpec.h:272
bool isFirstDeclarator() const
Definition: DeclSpec.h:2207
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:1807
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
Represents a pointer to an Objective C object.
Definition: Type.h:4821
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:127
Pointer to a block type.
Definition: Type.h:2254
IdentifierInfo * getNSErrorIdent()
Retrieve the identifier "NSError".
Definition: SemaType.cpp:3030
TypeResult actOnObjCProtocolQualifierType(SourceLocation lAngleLoc, ArrayRef< Decl * > protocols, ArrayRef< SourceLocation > protocolLocs, SourceLocation rAngleLoc)
Build a an Objective-C protocol-qualified 'id' type where no base type was specified.
Definition: SemaType.cpp:1039
Syntax
The style used to specify an attribute.
Definition: AttributeList.h:75
bool isObjCObjectType() const
Definition: Type.h:5380
void setAttrEnumOperandLoc(SourceLocation loc)
Definition: TypeLoc.h:788
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:3544
TypeSpecifierSign getWrittenSignSpec() const
Definition: TypeLoc.h:558
bool isTriviallyCopyableType(ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
Definition: Type.cpp:2092
IdentifierInfo * getName() const
static const TST TST_decimal128
Definition: DeclSpec.h:286
SourceManager & getSourceManager() const
Definition: Sema.h:1046
CanQualType UnknownAnyTy
Definition: ASTContext.h:896
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:5675
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
unsigned getTypeQuals() const
Definition: Type.h:3267
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition: DeclObjC.cpp:260
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition: DeclSpec.h:1194
This template specialization was declared or defined by an explicit specialization (C++ [temp...
Definition: Specifiers.h:148
#define OBJC_POINTER_TYPE_ATTRS_CASELIST
Definition: SemaType.cpp:99
CanQualType UnsignedLongTy
Definition: ASTContext.h:890
static bool isFunctionOrMethod(const Decl *D)
isFunctionOrMethod - Return true if the given decl has function type (function or function-typed vari...
bool isInvalid() const
CanQualType DependentTy
Definition: ASTContext.h:896
void setNext(AttributeList *N)
UnqualTypeLoc getUnqualifiedLoc() const
Definition: TypeLoc.h:253
CanQualType WCharTy
Definition: ASTContext.h:884
QualType getIntegerType() const
getIntegerType - Return the integer type this enum decl corresponds to.
Definition: Decl.h:3054
void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, bool NeedDefinition, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
bool isFunctionType() const
Definition: Type.h:5302
QualType BuildPipeType(QualType T, SourceLocation Loc)
Build a Pipe type.
Definition: SemaType.cpp:1946
static const TST TST_typename
Definition: DeclSpec.h:292
QualType BuildDecltypeType(Expr *E, SourceLocation Loc, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
Definition: SemaType.cpp:7000
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2287
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1522
void copy(TemplateSpecializationTypeLoc Loc)
Copy the location information from the given info.
Definition: TypeLoc.h:1491
Wraps an ObjCPointerType with source location information.
Definition: TypeLoc.h:1198
unsigned AtomicQualLoc
The location of the _Atomic-qualifier, if any.
Definition: DeclSpec.h:1125
SourceLocation getLoc() const
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:78
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream...
The "class" keyword.
Definition: Type.h:4182
A template-id, e.g., f<int>.
Definition: DeclSpec.h:897
CXXScopeSpec & getTypeSpecScope()
Definition: DeclSpec.h:493
BlockPointerTypeInfo Cls
Definition: DeclSpec.h:1434
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:2354
QualType getPointeeType() const
Definition: Type.h:2308
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:479
static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, DeclaratorChunk &DeclType, QualType RT)
Produce an appropriate diagnostic for an ambiguity between a function declarator and a C++ direct-ini...
Definition: SemaType.cpp:2838
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:1951
TypeDecl * getFloat128StubType() const
Retrieve the declaration for a 128-bit float stub type.
Definition: ASTContext.cpp:969
static bool hasNullabilityAttr(const AttributeList *attrs)
Check whether there is a nullability attribute of any kind in the given attribute list...
Definition: SemaType.cpp:3039
ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, std::unique_ptr< CorrectionCandidateCallback > CCC=nullptr, bool IsInlineAsmIdentifier=false, Token *KeywordReplacement=nullptr)
Definition: SemaExpr.cpp:2046
Describes whether we've seen any nullability information for the given file.
Definition: Sema.h:216
bool CheckRegparmAttr(const AttributeList &attr, unsigned &value)
Checks a regparm attribute, returning true if it is ill-formed and otherwise setting numParams to the...
bool isCXX11Attribute() const
const Type * getClass() const
Definition: Type.h:2402
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2199
Reading or writing from this object requires a barrier call.
Definition: Type.h:147
bool isContextSensitiveKeywordAttribute() const
unsigned AutoTemplateParameterDepth
If this is a generic lambda, use this as the depth of each 'auto' parameter, during initial AST const...
Definition: ScopeInfo.h:670
bool isPODType(ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:1961
QualType getTypeOfExprType(Expr *e) const
GCC extension.
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:3598
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition: TypeLoc.h:139
void setKWLoc(SourceLocation Loc)
Definition: TypeLoc.h:1999
unsigned TypeQuals
For now, sema will catch these as invalid.
Definition: DeclSpec.h:1395
bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const
Definition: Type.cpp:3635
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:2297
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...
Captures information about "declaration specifiers".
Definition: DeclSpec.h:228
bool isAggregate() const
Determine whether this class is an aggregate (C++ [dcl.init.aggr]), which is a class with no user-dec...
Definition: DeclCXX.h:1102
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:1957
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:5169
Represents a C++ struct/union/class.
Definition: DeclCXX.h:285
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc=SourceLocation(), SourceLocation VolatileQualLoc=SourceLocation(), SourceLocation RestrictQualLoc=SourceLocation(), SourceLocation AtomicQualLoc=SourceLocation())
Definition: SemaType.cpp:2475
A user-defined literal name, e.g., operator "" _i.
Definition: DeclSpec.h:889
bool isObjCObjectPointerType() const
Definition: Type.h:5377
Optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
Expr * NumElts
This is the size of the array, or null if [] or [*] was specified.
Definition: DeclSpec.h:1153
void setParam(unsigned i, ParmVarDecl *VD)
Definition: TypeLoc.h:1307
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:492
CanQualType Char16Ty
Definition: ASTContext.h:887
LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod
Controls member pointer representation format under the MS ABI.
Definition: Sema.h:325
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1031
static const TST TST_bool
Definition: DeclSpec.h:283
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:307
The "enum" keyword.
Definition: Type.h:4184
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:615
static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD)
Locks in the inheritance model for the given class and all of its bases.
Definition: SemaType.cpp:6592
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:43
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:115
This class is used for builtin types like 'int'.
Definition: Type.h:2011
IdentifierInfo * getNullabilityKeyword(NullabilityKind nullability)
Retrieve the keyword associated.
Definition: SemaType.cpp:3009
SourceLocation getRParenLoc() const
Definition: DeclSpec.h:1330
static void HandleAddressSpaceTypeAttribute(QualType &Type, const AttributeList &Attr, Sema &S)
HandleAddressSpaceTypeAttribute - Process an address_space attribute on the specified type...
Definition: SemaType.cpp:5006
bool isTypeSpecOwned() const
Definition: DeclSpec.h:477
bool isArrayType() const
Definition: Type.h:5344
Defines the clang::TargetInfo interface.
SourceLocation getTypeSpecWidthLoc() const
Definition: DeclSpec.h:500
bool isStar
True if this dimension was [*]. In this case, NumElts is null.
Definition: DeclSpec.h:1148
A SourceLocation and its associated SourceManager.
static Qualifiers fromCVRMask(unsigned CVR)
Definition: Type.h:211
static const TSW TSW_longlong
Definition: DeclSpec.h:256
TagDecl * getDecl() const
Definition: Type.cpp:2961
bool isIncompleteArrayType() const
Definition: Type.h:5350
CanQualType IntTy
Definition: ASTContext.h:889
bool isRecord() const
Definition: DeclBase.h:1273
static OpaquePtr make(QualTypeP)
Definition: Ownership.h:54
bool isTypeAltiVecVector() const
Definition: DeclSpec.h:474
bool hasEllipsis() const
Definition: DeclSpec.h:2211
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:196
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:922
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:400
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
bool isSet() const
Deprecated.
Definition: DeclSpec.h:209
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
bool hasRestrict() const
Definition: Type.h:243
void copy(TypeLoc other)
Copies the other type loc into this one.
Definition: TypeLoc.cpp:146
static const TST TST_atomic
Definition: DeclSpec.h:301
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...
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:5164
SourceManager & SourceMgr
Definition: Sema.h:298
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition: DeclSpec.h:1373
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition: DeclSpec.h:1347
static const TST TST_struct
Definition: DeclSpec.h:289
SplitQualType getSingleStepDesugaredType() const
Definition: Type.h:5082
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:52
class clang::Sema::DelayedDiagnostics DelayedDiagnostics
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition: TypeLoc.h:173
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false)
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:1987
AttributeList * getNext() const
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:2643
Wrapper for source info for builtin types.
Definition: TypeLoc.h:517
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:106
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1034
A trivial tuple used to represent a source range.
SourceLocation getLocation() const
Definition: DeclBase.h:384
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
Definition: DeclCXX.h:728
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition: TypeLoc.h:297
ASTContext & Context
Definition: Sema.h:295
NamedDecl - This represents a decl with a name.
Definition: Decl.h:145
bool isInvalidType() const
Definition: DeclSpec.h:2200
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
QualType getSignedWCharType() const
Return the type of "signed wchar_t".
void copy(DependentNameTypeLoc Loc)
Definition: TypeLoc.h:1818
QualifiedFunctionKind
Kinds of declarator that cannot contain a qualified function type.
Definition: SemaType.cpp:1823
bool hasExplicitCallingConv(QualType &T)
Definition: SemaType.cpp:5967
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID...
CanQualType BoolTy
Definition: ASTContext.h:882
bool isValid() const
No keyword precedes the qualified type name.
Definition: Type.h:4204
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:5148
TypeAttrLocation
The location of a type attribute.
Definition: SemaType.cpp:274
static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, AttributeList &attr, QualType &declSpecType)
A function type attribute was written on the declarator.
Definition: SemaType.cpp:588
CanQualType DoubleTy
Definition: ASTContext.h:892
const Type * getClass() const
Definition: TypeLoc.h:1174
static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head)
Definition: SemaType.cpp:244
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:642
static TypeSourceInfo * GetFullTypeForDeclarator(TypeProcessingState &state, QualType declSpecType, TypeSourceInfo *TInfo)
Definition: SemaType.cpp:3279
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition: DeclSpec.h:2228
llvm::StringRef getNullabilitySpelling(NullabilityKind kind, bool isContextSensitive=false)
Retrieve the spelling of the given nullability kind.
The global specifier '::'. There is no stored value.
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
void setType(QualType newType)
Definition: Decl.h:531
Wrapper for source info for pointers.
Definition: TypeLoc.h:1134
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
Definition: Type.cpp:3476
Wrapper for source info for block pointers.
Definition: TypeLoc.h:1147
bool isTypeAltiVecPixel() const
Definition: DeclSpec.h:475
base_class_range vbases()
Definition: DeclCXX.h:730
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2480
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:3087
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
static AttributeList::Kind getAttrListKind(AttributedType::Kind kind)
Map an AttributedType::Kind to an AttributeList::Kind.
Definition: SemaType.cpp:4471
A class which abstracts out some details necessary for making a call.
Definition: Type.h:2872
AttributeList *& getListRef()
Returns a reference to the attribute list.
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1272
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:1730
Attr - This represents one attribute.
Definition: Attr.h:44
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:741
TypeSourceInfo * GetTypeForDeclarator(Declarator &D, Scope *S)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:4338
static void distributeObjCPointerTypeAttr(TypeProcessingState &state, AttributeList &attr, QualType type)
Given that an objc_gc attribute was written somewhere on a declaration other than on the declarator i...
Definition: SemaType.cpp:386
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:5568
QualType BuildTypeofExprType(Expr *E, SourceLocation Loc)
Definition: SemaType.cpp:6915
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
Definition: Expr.cpp:2433
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:1712
AttributeList - Represents a syntactic attribute.
Definition: AttributeList.h:72
CanQualType UnsignedIntTy
Definition: ASTContext.h:890
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:5116
static void fillAttributedTypeLoc(AttributedTypeLoc TL, const AttributeList *attrs, const AttributeList *DeclAttrs=nullptr)
Definition: SemaType.cpp:4531
bool isPointerType() const
Definition: Type.h:5305
SourceLocation getEllipsisLoc() const
Definition: DeclSpec.h:2212
const AttributeList * getAttributes() const
Definition: DeclSpec.h:2162
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type...
Definition: Type.h:1551
unsigned isAmbiguous
Can this declaration be a constructor-style initializer?
Definition: DeclSpec.h:1202