1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements type-related semantic analysis.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.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"
24 #include "clang/AST/TypeLocVisitor.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "clang/Basic/PartialDiagnostic.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/DelayedDiagnostic.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"
38 using namespace clang;
40 enum TypeDiagSelector {
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) {
49 if (D.getContext() != Declarator::BlockLiteralContext ||
50 D.getDeclSpec().hasTypeSpecifier())
53 if (D.getNumTypeObjects() == 0)
54 return true; // ^{ ... }
56 if (D.getNumTypeObjects() == 1 &&
57 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
58 return true; // ^(int X, float Y) { ... }
63 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
64 /// doesn't apply to the given type.
65 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
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;
73 // Assume everything else was a function attribute.
74 WhichType = TDS_Function;
75 useExpansionLoc = false;
79 SourceLocation loc = attr.getLoc();
80 StringRef name = attr.getName()->getName();
82 // The GC attributes are usually written with macros; special-case them.
83 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
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";
93 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
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
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
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
125 // Nullability qualifiers.
126 #define NULLABILITY_TYPE_ATTRS_CASELIST \
127 case AttributeList::AT_TypeNonNull: \
128 case AttributeList::AT_TypeNullable: \
129 case AttributeList::AT_TypeNullUnspecified
132 /// An object which stores processing state for the entire
133 /// GetTypeForDeclarator process.
134 class TypeProcessingState {
137 /// The declarator being processed.
138 Declarator &declarator;
140 /// The index of the declarator chunk we're currently processing.
141 /// May be the total number of valid chunks, indicating the
145 /// Whether there are non-trivial modifications to the decl spec.
148 /// Whether we saved the attributes in the decl spec.
151 /// The original set of attributes on the DeclSpec.
152 SmallVector<AttributeList*, 2> savedAttrs;
154 /// A list of attributes to diagnose the uselessness of when the
155 /// processing is complete.
156 SmallVector<AttributeList*, 2> ignoredTypeAttrs;
159 TypeProcessingState(Sema &sema, Declarator &declarator)
160 : sema(sema), declarator(declarator),
161 chunkIndex(declarator.getNumTypeObjects()),
162 trivial(true), hasSavedAttrs(false) {}
164 Sema &getSema() const {
168 Declarator &getDeclarator() const {
172 bool isProcessingDeclSpec() const {
173 return chunkIndex == declarator.getNumTypeObjects();
176 unsigned getCurrentChunkIndex() const {
180 void setCurrentChunkIndex(unsigned idx) {
181 assert(idx <= declarator.getNumTypeObjects());
185 AttributeList *&getCurrentAttrListRef() const {
186 if (isProcessingDeclSpec())
187 return getMutableDeclSpec().getAttributes().getListRef();
188 return declarator.getTypeObject(chunkIndex).getAttrListRef();
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;
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;
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);
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);
217 ~TypeProcessingState() {
220 restoreDeclSpecAttrs();
224 DeclSpec &getMutableDeclSpec() const {
225 return const_cast<DeclSpec&>(declarator.getDeclSpec());
228 void restoreDeclSpecAttrs() {
229 assert(hasSavedAttrs);
231 if (savedAttrs.empty()) {
232 getMutableDeclSpec().getAttributes().set(nullptr);
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);
244 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
249 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
251 head = attr.getNext();
255 AttributeList *cur = head;
257 assert(cur && cur->getNext() && "ran out of attrs?");
258 if (cur->getNext() == &attr) {
259 cur->setNext(attr.getNext());
262 cur = cur->getNext();
266 static void moveAttrFromListToList(AttributeList &attr,
267 AttributeList *&fromList,
268 AttributeList *&toList) {
269 spliceAttrOutOfList(attr, fromList);
270 spliceAttrIntoList(attr, toList);
273 /// The location of a type attribute.
274 enum TypeAttrLocation {
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.
283 static void processTypeAttrs(TypeProcessingState &state,
284 QualType &type, TypeAttrLocation TAL,
285 AttributeList *attrs);
287 static bool handleFunctionTypeAttr(TypeProcessingState &state,
291 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
295 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
296 AttributeList &attr, QualType &type);
298 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
299 AttributeList &attr, QualType &type);
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);
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.
313 /// \param i - a notional index which the search will start
314 /// immediately inside
316 /// \param onlyBlockPointers Whether we should only look into block
317 /// pointer types (vs. all pointer types).
318 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
320 bool onlyBlockPointers) {
321 assert(i <= declarator.getNumTypeObjects());
323 DeclaratorChunk *result = nullptr;
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) {
329 case DeclaratorChunk::Paren:
332 // If we find anything except a function, bail out.
333 case DeclaratorChunk::Pointer:
334 case DeclaratorChunk::BlockPointer:
335 case DeclaratorChunk::Array:
336 case DeclaratorChunk::Reference:
337 case DeclaratorChunk::MemberPointer:
338 case DeclaratorChunk::Pipe:
341 // If we do find a function declarator, scan inwards from that,
342 // looking for a (block-)pointer declarator.
343 case DeclaratorChunk::Function:
344 for (--i; i != 0; --i) {
345 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
346 switch (ptrChunk.Kind) {
347 case DeclaratorChunk::Paren:
348 case DeclaratorChunk::Array:
349 case DeclaratorChunk::Function:
350 case DeclaratorChunk::Reference:
351 case DeclaratorChunk::Pipe:
354 case DeclaratorChunk::MemberPointer:
355 case DeclaratorChunk::Pointer:
356 if (onlyBlockPointers)
361 case DeclaratorChunk::BlockPointer:
365 llvm_unreachable("bad declarator chunk kind");
368 // If we run out of declarators doing that, we're done.
371 llvm_unreachable("bad declarator chunk kind");
373 // Okay, reconsider from our new point.
377 // Ran out of chunks, bail out.
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,
389 Declarator &declarator = state.getDeclarator();
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) {
395 case DeclaratorChunk::Pointer:
396 case DeclaratorChunk::BlockPointer: {
397 // But don't move an ARC ownership attribute to the return type
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;
406 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
407 destChunk->getAttrListRef());
411 case DeclaratorChunk::Paren:
412 case DeclaratorChunk::Array:
415 // We may be starting at the return type of a block.
416 case DeclaratorChunk::Function:
417 if (state.isProcessingDeclSpec() &&
418 attr.getKind() == AttributeList::AT_ObjCOwnership) {
419 if (DeclaratorChunk *dest = maybeMovePastReturnType(
421 /*onlyBlockPointers=*/true)) {
422 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
423 dest->getAttrListRef());
429 // Don't walk through these.
430 case DeclaratorChunk::Reference:
431 case DeclaratorChunk::MemberPointer:
432 case DeclaratorChunk::Pipe:
438 diagnoseBadTypeAttribute(state.getSema(), attr, type);
441 /// Distribute an objc_gc type attribute that was written on the
444 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
446 QualType &declSpecType) {
447 Declarator &declarator = state.getDeclarator();
449 // objc_gc goes on the innermost pointer to something that's not a
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) {
456 case DeclaratorChunk::Pointer:
457 case DeclaratorChunk::BlockPointer:
461 case DeclaratorChunk::Reference:
462 case DeclaratorChunk::MemberPointer:
463 case DeclaratorChunk::Paren:
464 case DeclaratorChunk::Array:
465 case DeclaratorChunk::Pipe:
468 case DeclaratorChunk::Function:
469 considerDeclSpec = false;
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());
489 // Otherwise, if we found an appropriate chunk, splice the attribute
491 if (innermost != -1U) {
492 moveAttrFromListToList(attr, declarator.getAttrListRef(),
493 declarator.getTypeObject(innermost).getAttrListRef());
497 // Otherwise, diagnose when we're done building the type.
498 spliceAttrOutOfList(attr, declarator.getAttrListRef());
499 state.addIgnoredTypeAttr(attr);
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,
509 Declarator &declarator = state.getDeclarator();
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) {
516 case DeclaratorChunk::Function:
517 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
518 chunk.getAttrListRef());
521 case DeclaratorChunk::Paren:
522 case DeclaratorChunk::Pointer:
523 case DeclaratorChunk::BlockPointer:
524 case DeclaratorChunk::Array:
525 case DeclaratorChunk::Reference:
526 case DeclaratorChunk::MemberPointer:
527 case DeclaratorChunk::Pipe:
532 diagnoseBadTypeAttribute(state.getSema(), attr, type);
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.
539 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
541 AttributeList *&attrList,
542 QualType &declSpecType) {
543 Declarator &declarator = state.getDeclarator();
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;
550 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
554 return handleFunctionTypeAttr(state, attr, declSpecType);
557 /// A function type attribute was written in the decl spec. Try to
558 /// apply it somewhere.
560 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
562 QualType &declSpecType) {
563 state.saveDeclSpecAttrs();
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());
574 // Try to distribute to the innermost.
575 if (distributeFunctionTypeAttrToInnermost(state, attr,
576 state.getCurrentAttrListRef(),
580 // If that failed, diagnose the bad attribute when the declarator is
582 state.addIgnoredTypeAttr(attr);
585 /// A function type attribute was written on the declarator. Try to
586 /// apply it somewhere.
588 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
590 QualType &declSpecType) {
591 Declarator &declarator = state.getDeclarator();
593 // Try to distribute to the innermost.
594 if (distributeFunctionTypeAttrToInnermost(state, attr,
595 declarator.getAttrListRef(),
599 // If that failed, diagnose the bad attribute when the declarator is
601 spliceAttrOutOfList(attr, declarator.getAttrListRef());
602 state.addIgnoredTypeAttr(attr);
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.
609 /// These are attributes like the following:
612 /// but not necessarily this:
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();
621 next = attr->getNext();
623 // Do not distribute C++11 attributes. They have strict rules for what
624 // they appertain to.
625 if (attr->isCXX11Attribute())
628 switch (attr->getKind()) {
629 OBJC_POINTER_TYPE_ATTRS_CASELIST:
630 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
633 case AttributeList::AT_NSReturnsRetained:
634 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
638 FUNCTION_TYPE_ATTRS_CASELIST:
639 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
642 MS_TYPE_ATTRS_CASELIST:
643 // Microsoft type attributes cannot go after the declarator-id.
646 NULLABILITY_TYPE_ATTRS_CASELIST:
647 // Nullability specifiers cannot go after the declarator-id.
649 // Objective-C __kindof does not get distributed.
650 case AttributeList::AT_ObjCKindOf:
656 } while ((attr = next));
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();
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;
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())
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.
687 // Otherwise, we need to fake up a function declarator.
688 SourceLocation loc = declarator.getLocStart();
690 // ...and *prepend* it to the declarator.
691 SourceLocation NoLoc;
692 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
694 /*IsAmbiguous=*/false,
698 /*EllipsisLoc=*/NoLoc,
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,
711 /*NoexceptExpr=*/nullptr,
712 /*ExceptionSpecTokens=*/nullptr,
713 loc, loc, declarator));
715 // For consistency, make sure the state still has us as processing
717 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
718 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
721 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
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()),
730 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
731 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
732 if (!(RemoveTQs & Qual.first))
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);
742 TypeQuals &= ~Qual.first;
746 /// Apply Objective-C type arguments to the given type.
747 static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
748 ArrayRef<TypeSourceInfo *> typeArgs,
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)
763 // The class type must be parameterized.
764 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
765 ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
767 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
768 << objcClass->getDeclName()
769 << FixItHint::CreateRemoval(typeArgsRange);
777 // The type must not already be specialized.
778 if (objcObjectType->isSpecialized()) {
779 S.Diag(loc, diag::err_objc_type_args_specialized_class)
781 << FixItHint::CreateRemoval(typeArgsRange);
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();
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);
815 S.Diag(qual.getLocStart(), diag::err_objc_type_arg_qualified)
816 << typeArg << typeArg.getQualifiers().getAsString()
817 << FixItHint::CreateRemoval(rangeToRemove);
821 // Remove qualifiers even if they're non-local.
822 typeArg = typeArg.getUnqualifiedType();
824 finalTypeArgs.push_back(typeArg);
826 if (typeArg->getAs<PackExpansionType>())
827 anyPackExpansions = true;
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];
835 // Too many arguments.
836 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
838 << objcClass->getDeclName()
839 << (unsigned)typeArgs.size()
841 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
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.
857 assert(anyPackExpansions && "Too many arguments?");
861 // Retrieve the bound.
862 QualType bound = typeParam->getUnderlyingType();
863 const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
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())
871 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
872 // Otherwise, we follow the assignability rules.
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();
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.
895 assert(anyPackExpansions && "Too many arguments?");
899 // Retrieve the bound.
900 QualType bound = typeParam->getUnderlyingType();
901 if (bound->isBlockCompatibleObjCPointerType(S.Context))
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();
917 // Dependent types will be checked at instantiation time.
918 if (typeArg->isDependentType()) {
922 // Diagnose non-id-compatible type arguments.
923 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
924 diag::err_objc_type_arg_not_id_compatible)
926 << typeArgInfo->getTypeLoc().getSourceRange();
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)
950 // Success. Form the specialized type.
951 return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
954 /// Apply Objective-C protocol qualifiers to the given type.
955 static QualType applyObjCProtocolQualifiers(
956 Sema &S, SourceLocation loc, SourceRange range, QualType type,
957 ArrayRef<ObjCProtocolDecl *> protocols,
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
965 return ctx.getObjCObjectType(objT->getBaseType(),
966 objT->getTypeArgsAsWritten(),
968 objT->isKindOfTypeAsWritten());
971 if (type->isObjCObjectType()) {
972 // Silently overwrite any existing protocol qualifiers.
973 // TODO: determine whether that's the right thing to do.
975 // FIXME: Check for protocols to which the class type is already
977 return ctx.getObjCObjectType(type, { }, protocols, false);
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);
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);
996 S.Diag(loc, diag::err_invalid_protocol_qualifiers)
1005 QualType Sema::BuildObjCObjectType(QualType BaseType,
1007 SourceLocation TypeArgsLAngleLoc,
1008 ArrayRef<TypeSourceInfo *> TypeArgs,
1009 SourceLocation TypeArgsRAngleLoc,
1010 SourceLocation ProtocolLAngleLoc,
1011 ArrayRef<ObjCProtocolDecl *> Protocols,
1012 ArrayRef<SourceLocation> ProtocolLocs,
1013 SourceLocation ProtocolRAngleLoc,
1015 QualType Result = BaseType;
1016 if (!TypeArgs.empty()) {
1017 Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1018 SourceRange(TypeArgsLAngleLoc,
1021 if (FailOnError && Result.isNull())
1025 if (!Protocols.empty()) {
1026 Result = applyObjCProtocolQualifiers(*this, Loc,
1027 SourceRange(ProtocolLAngleLoc,
1030 ProtocolLocs.data(),
1032 if (FailOnError && Result.isNull())
1039 TypeResult Sema::actOnObjCProtocolQualifierType(
1040 SourceLocation lAngleLoc,
1041 ArrayRef<Decl *> protocols,
1042 ArrayRef<SourceLocation> protocolLocs,
1043 SourceLocation rAngleLoc) {
1044 // Form id<protocol-list>.
1045 QualType Result = Context.getObjCObjectType(
1046 Context.ObjCBuiltinIdTy, { },
1048 (ObjCProtocolDecl * const *)protocols.data(),
1051 Result = Context.getObjCObjectPointerType(Result);
1053 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1054 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1056 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1057 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1059 auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1060 .castAs<ObjCObjectTypeLoc>();
1061 ObjCObjectTL.setHasBaseTypeAsWritten(false);
1062 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1064 // No type arguments.
1065 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1066 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
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]);
1074 // We're done. Return the completed type to the parser.
1075 return CreateParsedType(Result, ResultTInfo);
1078 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
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);
1094 // Handle missing type-source info.
1096 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
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();
1108 assert(TypeArgInfo && "No type source info?");
1109 ActualTypeArgInfos.push_back(TypeArgInfo);
1112 // Build the object type.
1113 QualType Result = BuildObjCObjectType(
1114 T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1115 TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1117 llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1119 ProtocolLocs, ProtocolRAngleLoc,
1120 /*FailOnError=*/false);
1125 // Create source information for this type.
1126 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1127 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
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();
1137 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
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]);
1147 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1148 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
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]);
1159 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1160 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1164 ObjCObjectTL.setHasBaseTypeAsWritten(true);
1165 if (ObjCObjectTL.getType() == T)
1166 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1168 ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1170 // We're done. Return the completed type to the parser.
1171 return CreateParsedType(Result, ResultTInfo);
1174 /// \brief Convert the specified declspec to the appropriate type
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
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();
1191 ASTContext &Context = S.Context;
1194 switch (DS.getTypeSpecType()) {
1195 case DeclSpec::TST_void:
1196 Result = Context.VoidTy;
1198 case DeclSpec::TST_char:
1199 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1200 Result = Context.CharTy;
1201 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
1202 Result = Context.SignedCharTy;
1204 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1205 "Unknown TSS value");
1206 Result = Context.UnsignedCharTy;
1209 case DeclSpec::TST_wchar:
1210 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
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();
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();
1226 case DeclSpec::TST_char16:
1227 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1228 "Unknown TSS value");
1229 Result = Context.Char16Ty;
1231 case DeclSpec::TST_char32:
1232 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1233 "Unknown TSS value");
1234 Result = Context.Char32Ty;
1236 case DeclSpec::TST_unspecified:
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();
1246 } else if (declarator.getContext() == Declarator::LambdaExprContext ||
1247 isOmittedBlockReturnType(declarator)) {
1248 Result = Context.DependentTy;
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
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.
1263 S.Diag(DeclLoc, diag::ext_missing_declspec)
1264 << DS.getSourceRange()
1265 << FixItHint::CreateInsertion(DS.getLocStart(), "int");
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();
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
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);
1285 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1286 << DS.getSourceRange();
1291 case DeclSpec::TST_int: {
1292 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
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;
1297 case DeclSpec::TSW_longlong:
1298 Result = Context.LongLongTy;
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);
1307 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
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;
1316 case DeclSpec::TSW_longlong:
1317 Result = Context.UnsignedLongLongTy;
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);
1326 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1333 case DeclSpec::TST_int128:
1334 if (!S.Context.getTargetInfo().hasInt128Type())
1335 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported);
1336 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1337 Result = Context.UnsignedInt128Ty;
1339 Result = Context.Int128Ty;
1341 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1342 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1343 case DeclSpec::TST_double:
1344 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
1345 Result = Context.LongDoubleTy;
1347 Result = Context.DoubleTy;
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);
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);
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());
1372 // This can happen in C++ with ambiguous lookups.
1373 Result = Context.IntTy;
1374 declarator.setInvalidType(true);
1378 // If the type is deprecated or unavailable, diagnose it.
1379 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1381 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1382 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
1384 // TypeQuals handled by caller.
1385 Result = Context.getTypeDeclType(D);
1387 // In both C and C++, make an ElaboratedType.
1388 ElaboratedTypeKeyword Keyword
1389 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1390 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
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();
1404 llvm::StringSwitch<bool>(TypeName)
1405 .Cases("atomic_int", "atomic_uint", "atomic_float",
1406 "atomic_flag", true)
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);
1413 if (!S.getOpenCLOptions().cl_khr_int64_extended_atomics &&
1415 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1416 << Result << "cl_khr_int64_extended_atomics";
1417 declarator.setInvalidType(true);
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);
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);
1435 // TypeQuals handled by caller.
1438 case DeclSpec::TST_typeofType:
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);
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);
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);
1470 case DeclSpec::TST_underlyingType:
1471 Result = S.GetTypeFromParser(DS.getRepAsType());
1472 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1473 Result = S.BuildUnaryTransformType(Result,
1474 UnaryTransformType::EnumUnderlyingType,
1475 DS.getTypeSpecTypeLoc());
1476 if (Result.isNull()) {
1477 Result = Context.IntTy;
1478 declarator.setInvalidType(true);
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) {
1489 sema::LambdaScopeInfo *LSI = S.getCurLambda();
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();
1495 // Turns out we must create the TemplateTypeParmDecl here to
1496 // retrieve the corresponding template parameter type.
1497 TemplateTypeParmDecl *CorrespondingTemplateParam =
1498 TemplateTypeParmDecl::Create(Context,
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);
1515 Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
1519 case DeclSpec::TST_auto_type:
1520 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1523 case DeclSpec::TST_decltype_auto:
1524 Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto,
1525 /*IsDependent*/ false);
1528 case DeclSpec::TST_unknown_anytype:
1529 Result = Context.UnknownAnyTy;
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);
1542 case DeclSpec::TST_error:
1543 Result = Context.IntTy;
1544 declarator.setInvalidType(true);
1548 // Handle complex types.
1549 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
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");
1556 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
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);
1564 // FIXME: Imaginary.
1565 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1566 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
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);
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());
1580 // Apply const/volatile/restrict qualifiers to T.
1581 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1582 // Warn about CV qualifiers on function types.
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()) {
1591 diagnoseAndRemoveTypeQualifiers(
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.
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.
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
1608 if (TypeQuals && Result->isReferenceType()) {
1609 diagnoseAndRemoveTypeQualifiers(
1610 S, DS, TypeQuals, Result,
1611 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1612 diag::warn_typecheck_reference_qualifiers);
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)
1625 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1626 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1630 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1631 // produce a warning in this case.
1634 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1636 // If adding qualifiers fails, just use the unqualified type.
1637 if (Qualified.isNull())
1638 declarator.setInvalidType(true);
1643 assert(!Result.isNull() && "This function should not return a null type");
1647 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1649 return Entity.getAsString();
1654 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1655 Qualifiers Qs, const DeclSpec *DS) {
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;
1665 if (T->isAnyPointerType() || T->isReferenceType() ||
1666 T->isMemberPointerType()) {
1668 if (T->isObjCObjectPointerType())
1670 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1671 EltTy = PTy->getPointeeType();
1673 EltTy = T->getPointeeType();
1675 // If we have a pointer or reference, the pointee must have an object
1677 if (!EltTy->isIncompleteOrObjectType()) {
1678 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1681 } else if (!T->isDependentType()) {
1682 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1687 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1688 Qs.removeRestrict();
1692 return Context.getQualifiedType(T, Qs);
1695 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1696 unsigned CVRA, const DeclSpec *DS) {
1700 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic.
1701 unsigned CVR = CVRA & ~DeclSpec::TQ_atomic;
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.
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()) {
1713 // If other qualifiers appear along with the _Atomic qualifier in a
1714 // specifier-qualifier-list, the resulting type is the so-qualified
1717 // Don't need to worry about array types here, since _Atomic can't be
1718 // applied to such types.
1719 SplitQualType Split = T.getSplitUnqualifiedType();
1720 T = BuildAtomicType(QualType(Split.Ty, 0),
1721 DS ? DS->getAtomicSpecLoc() : Loc);
1724 Split.Quals.addCVRQualifiers(CVR);
1725 return BuildQualifiedType(T, Loc, Split.Quals);
1728 return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR), DS);
1731 /// \brief Build a paren type including \p T.
1732 QualType Sema::BuildParenType(QualType T) {
1733 return Context.getParenType(T);
1736 /// Given that we're building a pointer or reference to the given
1737 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1740 // Bail out if retention is unrequired or already specified.
1741 if (!type->isObjCLifetimeType() ||
1742 type.getObjCLifetime() != Qualifiers::OCL_None)
1745 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
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;
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;
1760 // If we are in an unevaluated context, like sizeof, skip adding a
1762 } else if (S.isUnevaluatedContext()) {
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.
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
1772 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1773 S.DelayedDiagnostics.add(
1774 sema::DelayedDiagnostic::makeForbiddenType(loc,
1775 diag::err_arc_indirect_no_ownership, type, isReference));
1777 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1779 implicitLifetime = Qualifiers::OCL_Strong;
1781 assert(implicitLifetime && "didn't infer any lifetime!");
1784 qs.addObjCLifetime(implicitLifetime);
1785 return S.Context.getQualifiedType(type, qs);
1788 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1790 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1792 switch (FnTy->getRefQualifier()) {
1813 /// Kinds of declarator that cannot contain a qualified function type.
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.
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.
1822 /// The values of this enum are used in diagnostics.
1823 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
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.
1828 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
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))
1835 S.Diag(Loc, diag::err_compound_qualified_function_type)
1836 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1837 << getFunctionQualifiersAsString(FPT);
1841 /// \brief Build a pointer type.
1843 /// \param T The type to which we'll be building a pointer.
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.
1849 /// \param Entity The name of the entity that involves the pointer
1852 /// \returns A suitable pointer type, if there are no
1853 /// errors. Otherwise, returns a NULL type.
1854 QualType Sema::BuildPointerType(QualType T,
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;
1863 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1866 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1868 // In ARC, it is forbidden to build pointers to unqualified pointers.
1869 if (getLangOpts().ObjCAutoRefCount)
1870 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1872 // Build the pointer type.
1873 return Context.getPointerType(T);
1876 /// \brief Build a reference type.
1878 /// \param T The type to which we'll be building a reference.
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.
1884 /// \param Entity The name of the entity that involves the reference
1887 /// \returns A suitable reference type, if there are no
1888 /// errors. Otherwise, returns a NULL type.
1889 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1891 DeclarationName Entity) {
1892 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1893 "Unresolved overloaded function type");
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>();
1903 // C++ [dcl.ref]p4: There shall be no references to references.
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:
1909 // typedef int& intref;
1910 // typedef intref& intref2;
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.
1918 // A declarator that specifies the type "reference to cv void"
1920 if (T->isVoidType()) {
1921 Diag(Loc, diag::err_reference_to_void);
1925 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1928 // In ARC, it is forbidden to build references to unqualified pointers.
1929 if (getLangOpts().ObjCAutoRefCount)
1930 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1932 // Handle restrict on references.
1934 return Context.getLValueReferenceType(T, SpelledAsLValue);
1935 return Context.getRValueReferenceType(T);
1938 /// \brief Build a Pipe type.
1940 /// \param T The type to which we'll be building a Pipe.
1942 /// \param Loc We do not use it for now.
1944 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
1946 QualType Sema::BuildPipeType(QualType T, SourceLocation Loc) {
1947 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1949 // Build the pipe type.
1950 return Context.getPipeType(T);
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 {
1960 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
1962 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
1965 void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
1966 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
1970 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
1971 S.LangOpts.GNUMode).isInvalid();
1975 /// \brief Build an array type.
1977 /// \param T The type of each element in the array.
1979 /// \param ASM C99 array size modifier (e.g., '*', 'static').
1981 /// \param ArraySize Expression describing the size of the array.
1983 /// \param Brackets The range from the opening '[' to the closing ']'.
1985 /// \param Entity The name of the entity that involves the array
1988 /// \returns A suitable array type, if there are no errors. Otherwise,
1989 /// returns a NULL type.
1990 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1991 Expr *ArraySize, unsigned Quals,
1992 SourceRange Brackets, DeclarationName Entity) {
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.
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
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;
2013 if (T->isVoidType() || T->isIncompleteArrayType()) {
2014 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
2018 if (RequireNonAbstractType(Brackets.getBegin(), T,
2019 diag::err_array_of_abstract_type))
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.
2024 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2025 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2026 if (!MPTy->getClass()->isDependentType())
2027 (void)isCompleteType(Loc, T);
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))
2037 if (T->isFunctionType()) {
2038 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2039 << getPrintableNameForEntity(Entity) << T;
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;
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();
2060 // Do lvalue-to-rvalue conversions on the array size expression.
2061 if (ArraySize && !ArraySize->isRValue()) {
2062 ExprResult Result = DefaultLvalueConversion(ArraySize);
2063 if (Result.isInvalid())
2066 ArraySize = Result.get();
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();
2079 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2081 if (ASM == ArrayType::Star)
2082 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
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
2092 if (getLangOpts().CPlusPlus11 &&
2093 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2094 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2095 << ArraySize->getType() << ArraySize->getSourceRange();
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);
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()) {
2108 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
2109 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
2111 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
2112 << ArraySize->getSourceRange();
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();
2123 if (ASM == ArrayType::Static) {
2124 Diag(ArraySize->getLocStart(),
2125 diag::warn_typecheck_zero_static_array_size)
2126 << ArraySize->getSourceRange();
2127 ASM = ArrayType::Normal;
2129 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
2130 !T->isIncompleteType() && !T->isUndeducedType()) {
2131 // Is the array too large?
2132 unsigned ActiveSizeBits
2133 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
2134 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2135 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
2136 << ConstVal.toString(10)
2137 << ArraySize->getSourceRange();
2142 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
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);
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;
2160 // Prohibit the use of VLAs during template argument deduction.
2161 else if (isSFINAEContext()) {
2162 Diag(Loc, diag::err_vla_in_sfinae);
2165 // Just extwarn about VLAs.
2167 Diag(Loc, diag::ext_vla);
2168 } else if (ASM != ArrayType::Normal || Quals != 0)
2170 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
2171 : diag::ext_c99_array_usage) << ASM;
2174 if (T->isVariableArrayType()) {
2175 // Warn about VLAs for -Wvla.
2176 Diag(Loc, diag::warn_vla_used);
2182 /// \brief Build an ext-vector type.
2184 /// Run the required checks for the extended vector type.
2185 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
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;
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();
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());
2208 if (vectorSize == 0) {
2209 Diag(AttrLoc, diag::err_attribute_zero_size)
2210 << ArraySize->getSourceRange();
2214 if (VectorType::isVectorSizeTooLarge(vectorSize)) {
2215 Diag(AttrLoc, diag::err_attribute_size_too_large)
2216 << ArraySize->getSourceRange();
2220 return Context.getExtVectorType(T, vectorSize);
2223 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2226 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2227 if (T->isArrayType() || T->isFunctionType()) {
2228 Diag(Loc, diag::err_func_returning_array_function)
2229 << T->isFunctionType() << T;
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, "*");
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;
2250 QualType Sema::BuildFunctionType(QualType T,
2251 MutableArrayRef<QualType> ParamTypes,
2252 SourceLocation Loc, DeclarationName Entity,
2253 const FunctionProtoType::ExtProtoInfo &EPI) {
2254 bool Invalid = false;
2256 Invalid |= CheckFunctionReturnType(T, Loc);
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);
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, "*");
2271 ParamTypes[Idx] = ParamType;
2277 return Context.getFunctionType(T, ParamTypes, EPI);
2280 /// \brief Build a member pointer type \c T Class::*.
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
2287 /// \returns a member pointer type, if successful, or a NULL type if there was
2289 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
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);
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;
2307 if (T->isVoidType()) {
2308 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2309 << getPrintableNameForEntity(Entity);
2313 if (!Class->isDependentType() && !Class->isRecordType()) {
2314 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2318 // Adjust the default free function calling convention to the default method
2319 // calling convention.
2321 (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2322 (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2323 if (T->isFunctionType())
2324 adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2326 return Context.getMemberPointerType(T, Class.getTypePtr());
2329 /// \brief Build a block pointer type.
2331 /// \param T The type to which we'll be building a block pointer.
2333 /// \param Loc The source location, used for diagnostics.
2335 /// \param Entity The name of the entity that involves the block pointer
2338 /// \returns A suitable block pointer type, if there are no
2339 /// errors. Otherwise, returns a NULL type.
2340 QualType Sema::BuildBlockPointerType(QualType T,
2342 DeclarationName Entity) {
2343 if (!T->isFunctionType()) {
2344 Diag(Loc, diag::err_nonfunction_block_type);
2348 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2351 return Context.getBlockPointerType(T);
2354 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2355 QualType QT = Ty.get();
2357 if (TInfo) *TInfo = nullptr;
2361 TypeSourceInfo *DI = nullptr;
2362 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2363 QT = LIT->getType();
2364 DI = LIT->getTypeSourceInfo();
2367 if (TInfo) *TInfo = DI;
2371 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2372 Qualifiers::ObjCLifetime ownership,
2373 unsigned chunkIndex);
2375 /// Given that this is the declaration of a parameter under ARC,
2376 /// attempt to infer attributes and such for pointer-to-whatever
2378 static void inferARCWriteback(TypeProcessingState &state,
2379 QualType &declSpecType) {
2380 Sema &S = state.getSema();
2381 Declarator &declarator = state.getDeclarator();
2383 // TODO: should we care about decl qualifiers?
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) {
2394 case DeclaratorChunk::Paren:
2398 case DeclaratorChunk::Reference:
2399 case DeclaratorChunk::Pointer:
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;
2407 case DeclaratorChunk::BlockPointer:
2408 // If we have a pointer to block pointer, that's an acceptable
2409 // indirect reference; anything else is not an application of
2411 if (numPointers != 1) return;
2413 outermostPointerIndex = chunkIndex;
2414 isBlockPointer = true;
2416 // We don't care about pointer structure in return values here.
2419 case DeclaratorChunk::Array: // suppress if written (id[])?
2420 case DeclaratorChunk::Function:
2421 case DeclaratorChunk::MemberPointer:
2422 case DeclaratorChunk::Pipe:
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;
2435 // If it already has lifetime, don't do anything.
2436 if (declSpecType.getObjCLifetime()) return;
2438 // Otherwise, modify the type in-place.
2441 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2442 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
2444 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
2445 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
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())
2456 // Look for an explicit lifetime attribute there.
2457 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2458 if (chunk.Kind != DeclaratorChunk::Pointer &&
2459 chunk.Kind != DeclaratorChunk::BlockPointer)
2461 for (const AttributeList *attr = chunk.getAttrs(); attr;
2462 attr = attr->getNext())
2463 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
2466 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
2467 outermostPointerIndex);
2469 // Any other number of pointers/references does not trigger the rule.
2472 // TODO: mark whether we did this inference?
2475 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2476 SourceLocation FallbackLoc,
2477 SourceLocation ConstQualLoc,
2478 SourceLocation VolatileQualLoc,
2479 SourceLocation RestrictQualLoc,
2480 SourceLocation AtomicQualLoc) {
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 }
2495 SmallString<32> QualStr;
2496 unsigned NumQuals = 0;
2498 FixItHint FixIts[4];
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;
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() ||
2511 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2519 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2520 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2523 // Diagnose pointless type qualifiers on the return type of a function.
2524 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
2526 unsigned FunctionChunkIndex) {
2527 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2528 // FIXME: TypeSourceInfo doesn't preserve location information for
2530 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2531 RetTy.getLocalCVRQualifiers(),
2532 D.getIdentifierLoc());
2536 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2537 End = D.getNumTypeObjects();
2538 OuterChunkIndex != End; ++OuterChunkIndex) {
2539 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2540 switch (OuterChunk.Kind) {
2541 case DeclaratorChunk::Paren:
2544 case DeclaratorChunk::Pointer: {
2545 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2546 S.diagnoseIgnoredQualifiers(
2547 diag::warn_qual_return_type,
2550 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2551 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2552 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2553 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc));
2557 case DeclaratorChunk::Function:
2558 case DeclaratorChunk::BlockPointer:
2559 case DeclaratorChunk::Reference:
2560 case DeclaratorChunk::Array:
2561 case DeclaratorChunk::MemberPointer:
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());
2572 llvm_unreachable("unknown declarator chunk kind");
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()".
2578 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
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,
2584 D.getDeclSpec().getTypeQualifiers(),
2585 D.getIdentifierLoc(),
2586 D.getDeclSpec().getConstSpecLoc(),
2587 D.getDeclSpec().getVolatileSpecLoc(),
2588 D.getDeclSpec().getRestrictSpecLoc(),
2589 D.getDeclSpec().getAtomicSpecLoc());
2592 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2593 TypeSourceInfo *&ReturnTypeInfo) {
2594 Sema &SemaRef = state.getSema();
2595 Declarator &D = state.getDeclarator();
2597 ReturnTypeInfo = nullptr;
2599 // The TagDecl owned by the DeclSpec.
2600 TagDecl *OwnedTagDecl = nullptr;
2602 switch (D.getName().getKind()) {
2603 case UnqualifiedId::IK_ImplicitSelfParam:
2604 case UnqualifiedId::IK_OperatorFunctionId:
2605 case UnqualifiedId::IK_Identifier:
2606 case UnqualifiedId::IK_LiteralOperatorId:
2607 case UnqualifiedId::IK_TemplateId:
2608 T = ConvertDeclSpecToType(state);
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);
2617 case UnqualifiedId::IK_ConstructorName:
2618 case UnqualifiedId::IK_ConstructorTemplateId:
2619 case UnqualifiedId::IK_DestructorName:
2620 // Constructors and destructors don't have return types. Use
2622 T = SemaRef.Context.VoidTy;
2623 processTypeAttrs(state, T, TAL_DeclSpec,
2624 D.getDeclSpec().getAttributes().getList());
2627 case UnqualifiedId::IK_ConversionFunctionId:
2628 // The result type of a conversion function is the type that it
2630 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2635 if (D.getAttributes())
2636 distributeTypeAttrsFromDeclarator(state, T);
2638 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2639 if (D.getDeclSpec().containsPlaceholderType()) {
2642 switch (D.getContext()) {
2643 case Declarator::LambdaExprContext:
2644 llvm_unreachable("Can't specify a type specifier in lambda grammar");
2645 case Declarator::ObjCParameterContext:
2646 case Declarator::ObjCResultContext:
2647 case Declarator::PrototypeContext:
2650 case Declarator::LambdaExprParameterContext:
2651 // In C++14, generic lambdas allow 'auto' in their parameters.
2652 if (!(SemaRef.getLangOpts().CPlusPlus14
2653 && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto))
2656 case Declarator::MemberContext: {
2657 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
2658 D.isFunctionDeclarator())
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;
2670 case Declarator::CXXCatchContext:
2671 case Declarator::ObjCCatchContext:
2672 Error = 7; // Exception declaration
2674 case Declarator::TemplateParamContext:
2675 Error = 8; // Template parameter
2677 case Declarator::BlockLiteralContext:
2678 Error = 9; // Block literal
2680 case Declarator::TemplateTypeArgContext:
2681 Error = 10; // Template type argument
2683 case Declarator::AliasDeclContext:
2684 case Declarator::AliasTemplateContext:
2685 Error = 12; // Type alias
2687 case Declarator::TrailingReturnContext:
2688 if (!SemaRef.getLangOpts().CPlusPlus14 ||
2689 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)
2690 Error = 13; // Function return type
2692 case Declarator::ConversionIdContext:
2693 if (!SemaRef.getLangOpts().CPlusPlus14 ||
2694 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)
2695 Error = 14; // conversion-type-id
2697 case Declarator::TypeNameContext:
2698 Error = 15; // Generic
2700 case Declarator::FileContext:
2701 case Declarator::BlockContext:
2702 case Declarator::ForContext:
2703 case Declarator::ConditionContext:
2705 case Declarator::CXXNewContext:
2706 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)
2707 Error = 17; // 'new' type
2709 case Declarator::KNRTypeListContext:
2710 Error = 18; // K&R function parameter
2714 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
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 ||
2721 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type))
2724 bool HaveTrailing = false;
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 &&
2732 D.getDeclSpec().getTypeSpecType() != DeclSpec::TST_auto_type) {
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;
2748 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2749 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2750 AutoRange = D.getName().getSourceRange();
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");
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)
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()) {
2779 case Declarator::TrailingReturnContext:
2780 // Class and enumeration definitions are syntactically not allowed in
2781 // trailing return types.
2782 llvm_unreachable("parser should not have allowed this");
2784 case Declarator::FileContext:
2785 case Declarator::MemberContext:
2786 case Declarator::BlockContext:
2787 case Declarator::ForContext:
2788 case Declarator::BlockLiteralContext:
2789 case Declarator::LambdaExprContext:
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.
2794 case Declarator::AliasDeclContext:
2796 case Declarator::AliasTemplateContext:
2797 DiagID = diag::err_type_defined_in_alias_template;
2799 case Declarator::TypeNameContext:
2800 case Declarator::ConversionIdContext:
2801 case Declarator::TemplateParamContext:
2802 case Declarator::CXXNewContext:
2803 case Declarator::CXXCatchContext:
2804 case Declarator::ObjCCatchContext:
2805 case Declarator::TemplateTypeArgContext:
2806 DiagID = diag::err_type_defined_in_type_specifier;
2808 case Declarator::PrototypeContext:
2809 case Declarator::LambdaExprParameterContext:
2810 case Declarator::ObjCParameterContext:
2811 case Declarator::ObjCResultContext:
2812 case Declarator::KNRTypeListContext:
2814 // Types shall not be defined in return or parameter types.
2815 DiagID = diag::err_type_defined_in_param_type;
2817 case Declarator::ConditionContext:
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;
2826 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
2827 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2828 D.setInvalidType(true);
2832 assert(!T.isNull() && "This function should not return a null type");
2836 /// Produce an appropriate diagnostic for an ambiguity between a function
2837 /// declarator and a C++ direct-initializer.
2838 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
2839 DeclaratorChunk &DeclType, QualType RT) {
2840 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2841 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
2843 // If the return type is void there is no ambiguity.
2844 if (RT->isVoidType())
2847 // An initializer for a non-class type can have at most one argument.
2848 if (!RT->isRecordType() && FTI.NumParams > 1)
2851 // An initializer for a reference must have exactly one argument.
2852 if (RT->isReferenceType() && FTI.NumParams != 1)
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() ||
2858 D.getFunctionDefinitionKind() != FDK_Declaration ||
2859 !S.CurContext->isFunctionOrMethod() ||
2860 D.getDeclSpec().getStorageClassSpec()
2861 != DeclSpec::SCS_unspecified)
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.
2866 if (D.getContext() == Declarator::ConditionContext)
2869 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
2871 S.Diag(DeclType.Loc,
2872 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
2873 : diag::warn_empty_parens_are_function_decl)
2876 // If the declaration looks like:
2879 // and name lookup finds a function named 'f', then the ',' was
2880 // probably intended to be a ';'.
2881 if (!D.isFirstDeclarator() && D.getIdentifier()) {
2882 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
2883 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
2884 if (Comma.getFileID() != Name.getFileID() ||
2885 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
2886 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
2887 Sema::LookupOrdinaryName);
2888 if (S.LookupName(Result, S.getCurScope()))
2889 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
2890 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
2891 << D.getIdentifier();
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();
2901 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
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, ")");
2908 // For a declaration without parameters, eg. "T var();", suggest replacing
2909 // the parens with an initializer to turn the declaration into a variable
2911 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
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
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);
2923 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
2924 if (Init.empty() && S.LangOpts.CPlusPlus11)
2927 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
2928 << FixItHint::CreateReplacement(ParenRange, Init);
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.
2938 getCCForDeclaratorChunk(Sema &S, Declarator &D,
2939 const DeclaratorChunk::FunctionTypeInfo &FTI,
2940 unsigned ChunkIndex) {
2941 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
2943 bool IsCXXInstanceMethod = false;
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) {
2953 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
2954 FoundNonParen = true;
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 =
2961 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
2962 } else if (D.getContext() == Declarator::LambdaExprContext) {
2963 // This can only be a call operator for a lambda, which is an instance
2965 IsCXXInstanceMethod = true;
2967 // We're the innermost decl chunk, so must be a function declarator.
2968 assert(D.isFunctionDeclarator());
2970 // If we're inside a record, we're declaring a method, but it could be
2971 // explicitly or implicitly static.
2972 IsCXXInstanceMethod =
2973 D.isFirstDeclarationOfMember() &&
2974 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
2975 !D.isStaticMember();
2979 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
2980 IsCXXInstanceMethod);
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) {
3000 /// A simple notion of pointer kinds, which matches up with the various
3001 /// pointer declarators.
3002 enum class SimplePointerKind {
3009 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
3010 switch (nullability) {
3011 case NullabilityKind::NonNull:
3012 if (!Ident__Nonnull)
3013 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3014 return Ident__Nonnull;
3016 case NullabilityKind::Nullable:
3017 if (!Ident__Nullable)
3018 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3019 return Ident__Nullable;
3021 case NullabilityKind::Unspecified:
3022 if (!Ident__Null_unspecified)
3023 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3024 return Ident__Null_unspecified;
3026 llvm_unreachable("Unknown nullability kind.");
3029 /// Retrieve the identifier "NSError".
3030 IdentifierInfo *Sema::getNSErrorIdent() {
3032 Ident_NSError = PP.getIdentifierInfo("NSError");
3034 return Ident_NSError;
3037 /// Check whether there is a nullability attribute of any kind in the given
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)
3052 /// Describes the kind of a pointer a declarator describes.
3053 enum class PointerDeclaratorKind {
3056 // Single-level pointer.
3058 // Multi-level pointer (of any pointer kind).
3061 MaybePointerToCFRef,
3065 NSErrorPointerPointer,
3069 /// Classify the given declarator, whose type-specified is \c type, based on
3070 /// what kind of pointer it refers to.
3072 /// This is used to determine the default nullability.
3073 static PointerDeclaratorKind classifyPointerDeclarator(Sema &S,
3075 Declarator &declarator) {
3076 unsigned numNormalPointers = 0;
3078 // For any dependent type, we consider it a non-pointer.
3079 if (type->isDependentType())
3080 return PointerDeclaratorKind::NonPointer;
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) {
3086 case DeclaratorChunk::Array:
3087 case DeclaratorChunk::Function:
3088 case DeclaratorChunk::Pipe:
3091 case DeclaratorChunk::BlockPointer:
3092 case DeclaratorChunk::MemberPointer:
3093 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3094 : PointerDeclaratorKind::SingleLevelPointer;
3096 case DeclaratorChunk::Paren:
3097 case DeclaratorChunk::Reference:
3100 case DeclaratorChunk::Pointer:
3101 ++numNormalPointers;
3102 if (numNormalPointers > 2)
3103 return PointerDeclaratorKind::MultiLevelPointer;
3108 // Then, dig into the type specifier itself.
3109 unsigned numTypeSpecifierPointers = 0;
3111 // Decompose normal pointers.
3112 if (auto ptrType = type->getAs<PointerType>()) {
3113 ++numNormalPointers;
3115 if (numNormalPointers > 2)
3116 return PointerDeclaratorKind::MultiLevelPointer;
3118 type = ptrType->getPointeeType();
3119 ++numTypeSpecifierPointers;
3123 // Decompose block pointers.
3124 if (type->getAs<BlockPointerType>()) {
3125 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3126 : PointerDeclaratorKind::SingleLevelPointer;
3129 // Decompose member pointers.
3130 if (type->getAs<MemberPointerType>()) {
3131 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3132 : PointerDeclaratorKind::SingleLevelPointer;
3135 // Look at Objective-C object pointers.
3136 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3137 ++numNormalPointers;
3138 ++numTypeSpecifierPointers;
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;
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;;
3161 // If at this point we haven't seen a pointer, we won't see one.
3162 if (numNormalPointers == 0)
3163 return PointerDeclaratorKind::NonPointer;
3165 if (auto recordType = type->getAs<RecordType>()) {
3166 RecordDecl *recordDecl = recordType->getDecl();
3168 bool isCFError = false;
3170 // If we already know about CFError, test it directly.
3171 isCFError = (S.CFError == recordDecl);
3173 // Check whether this is CFError, which we identify based on its bridge
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;
3185 // If this is CFErrorRef*, report it as such.
3186 if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3187 return PointerDeclaratorKind::CFErrorRefPointer;
3196 switch (numNormalPointers) {
3198 return PointerDeclaratorKind::NonPointer;
3201 return PointerDeclaratorKind::SingleLevelPointer;
3204 return PointerDeclaratorKind::MaybePointerToCFRef;
3207 return PointerDeclaratorKind::MultiLevelPointer;
3211 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
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())
3219 if (ctx->isFileContext())
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())
3229 // Retrieve file information.
3230 bool invalid = false;
3231 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
3232 if (invalid || !sloc.isFile())
3235 // We don't want to perform completeness checks on the main file or in
3237 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
3238 if (fileInfo.getIncludeLoc().isInvalid())
3240 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
3241 S.Diags.getSuppressSystemWarnings()) {
3248 /// Check for consistent use of nullability.
3249 static void checkNullabilityConsistency(TypeProcessingState &state,
3250 SimplePointerKind pointerKind,
3251 SourceLocation pointerLoc) {
3252 Sema &S = state.getSema();
3254 // Determine which file we're performing consistency checking for.
3255 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
3256 if (file.isInvalid())
3259 // If we haven't seen any type nullability in this file, we won't warn now
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,
3267 fileNullability.PointerLoc = pointerLoc;
3268 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
3274 // Complain about missing nullability.
3275 S.Diag(pointerLoc, diag::warn_nullability_missing)
3276 << static_cast<unsigned>(pointerKind);
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();
3290 // The name we're declaring, if any.
3291 DeclarationName Name;
3292 if (D.getIdentifier())
3293 Name = D.getIdentifier();
3295 // Does this declaration declare a typedef-name?
3296 bool IsTypedefName =
3297 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
3298 D.getContext() == Declarator::AliasDeclContext ||
3299 D.getContext() == Declarator::AliasTemplateContext;
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);
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) {
3316 case DeclaratorChunk::Paren:
3318 case DeclaratorChunk::Function: {
3320 if (D.isFunctionDeclarationContext() &&
3321 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
3323 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
3326 case DeclaratorChunk::Pointer:
3327 case DeclaratorChunk::BlockPointer:
3328 case DeclaratorChunk::MemberPointer:
3331 case DeclaratorChunk::Reference:
3334 case DeclaratorChunk::Array:
3337 case DeclaratorChunk::Pipe:
3341 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
3342 D.setInvalidType(true);
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;
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.
3359 FileID file = getNullabilityCompletenessCheckFileID(
3360 S, S.PP.getPragmaAssumeNonNullLoc());
3361 if (file.isValid()) {
3362 FileNullability &fileNullability = S.NullabilityMap[file];
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);
3371 fileNullability.SawTypeNullability = true;
3376 // Whether to complain about missing nullability specifiers or not.
3380 /// Complain on the inner pointers (but not the outermost
3383 /// Complain about any pointers that don't have nullability
3384 /// specified or inferred.
3386 } complainAboutMissingNullability = CAMN_No;
3387 unsigned NumPointersRemaining = 0;
3389 if (IsTypedefName) {
3390 // For typedefs, we do not infer any nullability (the default),
3391 // and we only complain about missing nullability specifiers on
3393 complainAboutMissingNullability = CAMN_InnerPointers;
3395 if (T->canHaveNullability() && !T->getNullability(S.Context)) {
3396 ++NumPointersRemaining;
3399 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
3400 DeclaratorChunk &chunk = D.getTypeObject(i);
3401 switch (chunk.Kind) {
3402 case DeclaratorChunk::Array:
3403 case DeclaratorChunk::Function:
3404 case DeclaratorChunk::Pipe:
3407 case DeclaratorChunk::BlockPointer:
3408 case DeclaratorChunk::MemberPointer:
3409 ++NumPointersRemaining;
3412 case DeclaratorChunk::Paren:
3413 case DeclaratorChunk::Reference:
3416 case DeclaratorChunk::Pointer:
3417 ++NumPointersRemaining;
3422 bool isFunctionOrMethod = false;
3423 switch (auto context = state.getDeclarator().getContext()) {
3424 case Declarator::ObjCParameterContext:
3425 case Declarator::ObjCResultContext:
3426 case Declarator::PrototypeContext:
3427 case Declarator::TrailingReturnContext:
3428 isFunctionOrMethod = true;
3431 case Declarator::MemberContext:
3432 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
3433 complainAboutMissingNullability = CAMN_No;
3437 // Weak properties are inferred to be nullable.
3438 if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
3439 inferNullability = NullabilityKind::Nullable;
3445 case Declarator::FileContext:
3446 case Declarator::KNRTypeListContext:
3447 complainAboutMissingNullability = CAMN_Yes;
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.
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);
3465 case PointerDeclaratorKind::CFErrorRefPointer:
3466 case PointerDeclaratorKind::NSErrorPointerPointer:
3467 // Within a function or method signature, infer _Nullable at both
3469 if (isFunctionOrMethod && inAssumeNonNullRegion)
3470 inferNullability = NullabilityKind::Nullable;
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 {
3480 if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained ||
3481 NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained)
3483 NextAttr = NextAttr->getNext();
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;
3500 case Declarator::ConversionIdContext:
3501 complainAboutMissingNullability = CAMN_Yes;
3504 case Declarator::AliasDeclContext:
3505 case Declarator::AliasTemplateContext:
3506 case Declarator::BlockContext:
3507 case Declarator::BlockLiteralContext:
3508 case Declarator::ConditionContext:
3509 case Declarator::CXXCatchContext:
3510 case Declarator::CXXNewContext:
3511 case Declarator::ForContext:
3512 case Declarator::LambdaExprContext:
3513 case Declarator::LambdaExprParameterContext:
3514 case Declarator::ObjCCatchContext:
3515 case Declarator::TemplateParamContext:
3516 case Declarator::TemplateTypeArgContext:
3517 case Declarator::TypeNameContext:
3518 // Don't infer in these contexts.
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;
3532 // If a nullability attribute is present, there's nothing to do.
3533 if (hasNullabilityAttr(attrs))
3536 // If we're supposed to infer nullability, do so now.
3537 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
3538 AttributeList::Syntax syntax
3539 = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword
3540 : AttributeList::AS_Keyword;
3541 AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool()
3543 S.getNullabilityKeyword(
3545 SourceRange(pointerLoc),
3546 nullptr, SourceLocation(),
3547 nullptr, 0, syntax);
3549 spliceAttrIntoList(*nullabilityAttr, attrs);
3551 if (inferNullabilityCS) {
3552 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
3553 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
3556 if (inferNullabilityInnerOnly)
3557 inferNullabilityInnerOnlyComplete = true;
3558 return nullabilityAttr;
3561 // If we're supposed to complain about missing nullability, do so
3562 // now if it's truly missing.
3563 switch (complainAboutMissingNullability) {
3567 case CAMN_InnerPointers:
3568 if (NumPointersRemaining == 0)
3573 checkNullabilityConsistency(state, pointerKind, pointerLoc);
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;
3588 if (auto *attr = inferPointerNullability(
3589 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
3590 D.getMutableDeclSpec().getAttributes().getListRef())) {
3591 T = Context.getAttributedType(
3592 AttributedType::getNullabilityAttrKind(*inferNullability), T, T);
3593 attr->setUsedAsTypeAttr();
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) {
3606 case DeclaratorChunk::Paren:
3607 T = S.BuildParenType(T);
3609 case DeclaratorChunk::BlockPointer:
3610 // If blocks are disabled, emit an error.
3611 if (!LangOpts.Blocks)
3612 S.Diag(DeclType.Loc, diag::err_blocks_disable);
3614 // Handle pointer nullability.
3615 inferPointerNullability(SimplePointerKind::BlockPointer,
3616 DeclType.Loc, DeclType.getAttrListRef());
3618 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
3619 if (DeclType.Cls.TypeQuals)
3620 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
3622 case DeclaratorChunk::Pointer:
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.
3631 // Handle pointer nullability
3632 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
3633 DeclType.getAttrListRef());
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);
3641 T = S.BuildPointerType(T, DeclType.Loc, Name);
3642 if (DeclType.Ptr.TypeQuals)
3643 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
3646 case DeclaratorChunk::Reference: {
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.
3654 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
3656 if (DeclType.Ref.HasRestrict)
3657 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
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.
3668 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
3669 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
3670 ArrayType::ArraySizeModifier ASM;
3672 ASM = ArrayType::Star;
3673 else if (ATI.hasStatic)
3674 ASM = ArrayType::Static;
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);
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
3689 if (ASM == ArrayType::Static || ATI.TypeQuals) {
3690 if (!(D.isPrototypeContext() ||
3691 D.getContext() == Declarator::KNRTypeListContext)) {
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;
3698 D.setInvalidType(true);
3701 // C99 6.7.5.2p1: ... and then only in the outermost array type
3703 unsigned x = chunkIndex;
3705 // Walk outwards along the declarator chunks.
3707 const DeclaratorChunk &DC = D.getTypeObject(x);
3709 case DeclaratorChunk::Paren:
3711 case DeclaratorChunk::Array:
3712 case DeclaratorChunk::Pointer:
3713 case DeclaratorChunk::Reference:
3714 case DeclaratorChunk::MemberPointer:
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;
3720 D.setInvalidType(true);
3722 case DeclaratorChunk::Function:
3723 case DeclaratorChunk::BlockPointer:
3724 case DeclaratorChunk::Pipe:
3725 // These are invalid anyway, so just ignore.
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
3733 if (AT && D.getContext() != Declarator::LambdaExprParameterContext) {
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;
3742 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
3743 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
3746 case DeclaratorChunk::Function: {
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();
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.
3758 if (D.getDeclSpec().containsPlaceholderType() &&
3759 !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
3760 !S.getLangOpts().CPlusPlus14) {
3761 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3762 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
3763 ? diag::err_auto_missing_trailing_return
3764 : diag::err_deduced_return_type);
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)) {
3770 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
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)) {
3777 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3778 diag::err_trailing_return_without_auto)
3779 << T << D.getDeclSpec().getSourceRange();
3780 D.setInvalidType(true);
3782 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
3784 // An error occurred parsing the trailing return type.
3786 D.setInvalidType(true);
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()) &&
3794 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
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 &&
3799 D.getContext() == Declarator::BlockLiteralContext)
3800 diagID = diag::err_block_returning_array_function;
3801 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
3803 D.setInvalidType(true);
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);
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);
3821 // Methods cannot return interface types. All ObjC objects are
3822 // passed by reference.
3823 if (T->isObjCObjectType()) {
3824 SourceLocation DiagLoc, FixitLoc;
3826 DiagLoc = TInfo->getTypeLoc().getLocStart();
3827 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
3829 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
3830 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
3832 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
3834 << FixItHint::CreateInsertion(FixitLoc, "*");
3836 T = Context.getObjCObjectPointerType(T);
3839 TLB.pushFullCopy(TInfo->getTypeLoc());
3840 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
3841 TLoc.setStarLoc(FixitLoc);
3842 TInfo = TLB.getTypeSourceInfo(Context, T);
3845 D.setInvalidType(true);
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 &&
3854 D.getFunctionDefinitionKind() == FDK_Definition) {
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;
3860 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
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();
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();
3889 if (AttrLoc.isValid()) {
3890 // The ownership attributes are almost always written via
3892 // __strong/__weak/__autoreleasing/__unsafe_unretained.
3893 if (AttrLoc.isMacroID())
3894 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
3896 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
3897 << T.getQualifiers().getObjCLifetime();
3901 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
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);
3909 // Exception specs are not allowed in typedefs. Complain, but add it
3911 if (IsTypedefName && FTI.getExceptionSpecType())
3912 S.Diag(FTI.getExceptionSpecLocBeg(),
3913 diag::err_exception_spec_in_typedef)
3914 << (D.getContext() == Declarator::AliasDeclContext ||
3915 D.getContext() == Declarator::AliasTemplateContext);
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);
3922 FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
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);
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;
3942 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
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
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);
3956 FunctionProtoType::ExtProtoInfo EPI;
3958 EPI.Variadic = FTI.isVariadic;
3959 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
3960 EPI.TypeQuals = FTI.TypeQuals;
3961 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
3962 : FTI.RefQualifierIsLValueRef? RQ_LValue
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);
3970 SmallVector<bool, 16> ConsumedParameters;
3971 ConsumedParameters.reserve(FTI.NumParams);
3972 bool HasAnyConsumedParameters = false;
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?");
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);
3996 // Reject, but continue to parse 'float(const void)'.
3997 if (ParamTy.hasQualifiers())
3998 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
4000 // Do not add 'void' to the list.
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;
4011 Param->setInvalidDecl();
4013 } else if (!S.getLangOpts().HalfArgsAndReturns) {
4014 S.Diag(Param->getLocation(),
4015 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
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);
4030 if (LangOpts.ObjCAutoRefCount) {
4031 bool Consumed = Param->hasAttr<NSConsumedAttr>();
4032 ConsumedParameters.push_back(Consumed);
4033 HasAnyConsumedParameters |= Consumed;
4036 ParamTys.push_back(ParamTy);
4039 if (HasAnyConsumedParameters)
4040 EPI.ConsumedParameters = ConsumedParameters.data();
4042 SmallVector<QualType, 4> Exceptions;
4043 SmallVector<ParsedType, 2> DynamicExceptions;
4044 SmallVector<SourceRange, 2> DynamicExceptionRanges;
4045 Expr *NoexceptExpr = nullptr;
4047 if (FTI.getExceptionSpecType() == EST_Dynamic) {
4048 // FIXME: It's rather inefficient to have to split into two vectors
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);
4057 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
4058 NoexceptExpr = FTI.NoexceptExpr;
4061 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
4062 FTI.getExceptionSpecType(),
4064 DynamicExceptionRanges,
4069 T = Context.getFunctionType(T, ParamTys, EPI);
4074 case DeclaratorChunk::MemberPointer: {
4075 // The scope spec must refer to a class, or be dependent.
4076 CXXScopeSpec &SS = DeclType.Mem.Scope();
4079 // Handle pointer nullability.
4080 inferPointerNullability(SimplePointerKind::MemberPointer,
4081 DeclType.Loc, DeclType.getAttrListRef());
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()) {
4091 case NestedNameSpecifier::Identifier:
4092 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
4093 NNS->getAsIdentifier());
4096 case NestedNameSpecifier::Namespace:
4097 case NestedNameSpecifier::NamespaceAlias:
4098 case NestedNameSpecifier::Global:
4099 case NestedNameSpecifier::Super:
4100 llvm_unreachable("Nested-name-specifier must name a type");
4102 case NestedNameSpecifier::TypeSpec:
4103 case NestedNameSpecifier::TypeSpecWithTemplate:
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);
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);
4122 if (!ClsType.isNull())
4123 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
4127 D.setInvalidType(true);
4128 } else if (DeclType.Mem.TypeQuals) {
4129 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
4134 case DeclaratorChunk::Pipe: {
4135 T = S.BuildPipeType(T, DeclType.Loc );
4141 D.setInvalidType(true);
4145 // See if there are any attributes on this declarator chunk.
4146 processTypeAttrs(state, T, TAL_DeclChunk,
4147 const_cast<AttributeList *>(DeclType.getAttrs()));
4150 assert(!T.isNull() && "T must not be null after this point");
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?");
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
4162 // Core issue 547 also allows cv-qualifiers on function types that are
4163 // top-level template type arguments.
4165 if (!D.getCXXScopeSpec().isSet()) {
4166 FreeFunction = ((D.getContext() != Declarator::MemberContext &&
4167 D.getContext() != Declarator::LambdaExprContext) ||
4168 D.getDeclSpec().isFriendSpecified());
4170 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
4171 FreeFunction = (DC && !DC->isRecord());
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
4184 // FIXME: Checking this here is insufficient. We accept-invalid on:
4186 // template<typename T> struct S { void f(T); };
4187 // S<int() const> s;
4189 // ... for instance.
4190 if (IsQualifiedFunction &&
4192 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
4194 D.getContext() != Declarator::TemplateTypeArgContext) {
4195 SourceLocation Loc = D.getLocStart();
4196 SourceRange RemovalRange;
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(),
4212 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
4213 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
4214 Loc = RemovalLocs.front();
4218 S.Diag(Loc, diag::err_invalid_qualified_function_type)
4219 << FreeFunction << D.isFunctionDeclarator() << T
4220 << getFunctionQualifiersAsString(FnTy)
4221 << FixItHint::CreateRemoval(RemovalRange);
4223 // Strip the cv-qualifiers and ref-qualifiers from the type.
4224 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
4226 EPI.RefQualifier = RQ_None;
4228 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
4230 // Rebuild any parens around the identifier in the function type.
4231 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4232 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
4234 T = S.BuildParenType(T);
4239 // Apply any undistributed attributes from the declarator.
4240 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
4242 // Diagnose any ignored type attributes.
4243 state.diagnoseIgnoredTypeAttrs(T);
4245 // C++0x [dcl.constexpr]p9:
4246 // A constexpr specifier used in an object declaration declares the object
4248 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
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()) {
4260 case Declarator::PrototypeContext:
4261 case Declarator::LambdaExprParameterContext:
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.
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();
4275 D.setEllipsisLoc(SourceLocation());
4277 T = Context.getPackExpansionType(T, None);
4280 case Declarator::TemplateParamContext:
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).
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.
4289 if (T->containsUnexpandedParameterPack())
4290 T = Context.getPackExpansionType(T, None);
4292 S.Diag(D.getEllipsisLoc(),
4293 LangOpts.CPlusPlus11
4294 ? diag::warn_cxx98_compat_variadic_templates
4295 : diag::ext_variadic_templates);
4298 case Declarator::FileContext:
4299 case Declarator::KNRTypeListContext:
4300 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
4301 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
4302 case Declarator::TypeNameContext:
4303 case Declarator::CXXNewContext:
4304 case Declarator::AliasDeclContext:
4305 case Declarator::AliasTemplateContext:
4306 case Declarator::MemberContext:
4307 case Declarator::BlockContext:
4308 case Declarator::ForContext:
4309 case Declarator::ConditionContext:
4310 case Declarator::CXXCatchContext:
4311 case Declarator::ObjCCatchContext:
4312 case Declarator::BlockLiteralContext:
4313 case Declarator::LambdaExprContext:
4314 case Declarator::ConversionIdContext:
4315 case Declarator::TrailingReturnContext:
4316 case Declarator::TemplateTypeArgContext:
4317 // FIXME: We may want to allow parameter packs in block-literal contexts
4319 S.Diag(D.getEllipsisLoc(),
4320 diag::err_ellipsis_in_declarator_not_parameter);
4321 D.setEllipsisLoc(SourceLocation());
4326 assert(!T.isNull() && "T must not be null at the end of this function");
4327 if (D.isInvalidType())
4328 return Context.getTrivialTypeSourceInfo(T);
4330 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
4333 /// GetTypeForDeclarator - Convert the type for the specified
4334 /// declarator to Type instances.
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.
4338 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
4339 // Determine the type of the declarator. Not all forms of declarator
4342 TypeProcessingState state(*this, D);
4344 TypeSourceInfo *ReturnTypeInfo = nullptr;
4345 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4347 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
4348 inferARCWriteback(state, T);
4350 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
4353 static void transferARCOwnershipToDeclSpec(Sema &S,
4354 QualType &declSpecTy,
4355 Qualifiers::ObjCLifetime ownership) {
4356 if (declSpecTy->isObjCRetainableType() &&
4357 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
4359 qs.addObjCLifetime(ownership);
4360 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
4364 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
4365 Qualifiers::ObjCLifetime ownership,
4366 unsigned chunkIndex) {
4367 Sema &S = state.getSema();
4368 Declarator &D = state.getDeclarator();
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)
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;
4386 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
4387 Arg->Ident = &S.Context.Idents.get(attrStr);
4388 Arg->Loc = SourceLocation();
4390 ArgsUnion Args(Arg);
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());
4400 // TODO: mark whether we did this inference?
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();
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) {
4415 case DeclaratorChunk::Paren:
4419 case DeclaratorChunk::Array:
4420 case DeclaratorChunk::Reference:
4421 case DeclaratorChunk::Pointer:
4423 hasIndirection = true;
4427 case DeclaratorChunk::BlockPointer:
4429 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
4432 case DeclaratorChunk::Function:
4433 case DeclaratorChunk::MemberPointer:
4434 case DeclaratorChunk::Pipe:
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);
4449 assert(chunk.Kind == DeclaratorChunk::Array ||
4450 chunk.Kind == DeclaratorChunk::Reference);
4451 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4455 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
4456 TypeProcessingState state(*this, D);
4458 TypeSourceInfo *ReturnTypeInfo = nullptr;
4459 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4461 if (getLangOpts().ObjC1) {
4462 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
4463 if (ownership != Qualifiers::OCL_None)
4464 transferARCOwnership(state, declSpecTy, ownership);
4467 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
4470 /// Map an AttributedType::Kind to an AttributeList::Kind.
4471 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
4473 case AttributedType::attr_address_space:
4474 return AttributeList::AT_AddressSpace;
4475 case AttributedType::attr_regparm:
4476 return AttributeList::AT_Regparm;
4477 case AttributedType::attr_vector_size:
4478 return AttributeList::AT_VectorSize;
4479 case AttributedType::attr_neon_vector_type:
4480 return AttributeList::AT_NeonVectorType;
4481 case AttributedType::attr_neon_polyvector_type:
4482 return AttributeList::AT_NeonPolyVectorType;
4483 case AttributedType::attr_objc_gc:
4484 return AttributeList::AT_ObjCGC;
4485 case AttributedType::attr_objc_ownership:
4486 case AttributedType::attr_objc_inert_unsafe_unretained:
4487 return AttributeList::AT_ObjCOwnership;
4488 case AttributedType::attr_noreturn:
4489 return AttributeList::AT_NoReturn;
4490 case AttributedType::attr_cdecl:
4491 return AttributeList::AT_CDecl;
4492 case AttributedType::attr_fastcall:
4493 return AttributeList::AT_FastCall;
4494 case AttributedType::attr_stdcall:
4495 return AttributeList::AT_StdCall;
4496 case AttributedType::attr_thiscall:
4497 return AttributeList::AT_ThisCall;
4498 case AttributedType::attr_pascal:
4499 return AttributeList::AT_Pascal;
4500 case AttributedType::attr_vectorcall:
4501 return AttributeList::AT_VectorCall;
4502 case AttributedType::attr_pcs:
4503 case AttributedType::attr_pcs_vfp:
4504 return AttributeList::AT_Pcs;
4505 case AttributedType::attr_inteloclbicc:
4506 return AttributeList::AT_IntelOclBicc;
4507 case AttributedType::attr_ms_abi:
4508 return AttributeList::AT_MSABI;
4509 case AttributedType::attr_sysv_abi:
4510 return AttributeList::AT_SysVABI;
4511 case AttributedType::attr_ptr32:
4512 return AttributeList::AT_Ptr32;
4513 case AttributedType::attr_ptr64:
4514 return AttributeList::AT_Ptr64;
4515 case AttributedType::attr_sptr:
4516 return AttributeList::AT_SPtr;
4517 case AttributedType::attr_uptr:
4518 return AttributeList::AT_UPtr;
4519 case AttributedType::attr_nonnull:
4520 return AttributeList::AT_TypeNonNull;
4521 case AttributedType::attr_nullable:
4522 return AttributeList::AT_TypeNullable;
4523 case AttributedType::attr_null_unspecified:
4524 return AttributeList::AT_TypeNullUnspecified;
4525 case AttributedType::attr_objc_kindof:
4526 return AttributeList::AT_ObjCKindOf;
4528 llvm_unreachable("unexpected attribute kind!");
4531 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
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!");
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();
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();
4551 assert(attrs && "no matching type attribute in expected location!");
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);
4563 TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc());
4566 // FIXME: preserve this information to here.
4567 if (TL.hasAttrOperand())
4568 TL.setAttrOperandParensRange(SourceRange());
4572 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
4573 ASTContext &Context;
4577 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
4578 : Context(Context), DS(DS) {}
4580 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4581 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
4582 Visit(TL.getModifiedLoc());
4584 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4585 Visit(TL.getUnqualifiedLoc());
4587 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
4588 TL.setNameLoc(DS.getTypeSpecTypeLoc());
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());
4597 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
4598 TypeSourceInfo *RepTInfo = nullptr;
4599 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
4600 TL.copy(RepTInfo->getTypeLoc());
4602 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4603 TypeSourceInfo *RepTInfo = nullptr;
4604 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
4605 TL.copy(RepTInfo->getTypeLoc());
4607 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
4608 TypeSourceInfo *TInfo = nullptr;
4609 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4611 // If we got no declarator info from previous Sema routines,
4612 // just fill with the typespec loc.
4614 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
4618 TypeLoc OldTL = TInfo->getTypeLoc();
4619 if (TInfo->getType()->getAs<ElaboratedType>()) {
4620 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
4621 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
4622 .castAs<TemplateSpecializationTypeLoc>();
4625 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
4626 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
4630 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
4631 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
4632 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
4633 TL.setParensRange(DS.getTypeofParensRange());
4635 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
4636 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
4637 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
4638 TL.setParensRange(DS.getTypeofParensRange());
4639 assert(DS.getRepAsType());
4640 TypeSourceInfo *TInfo = nullptr;
4641 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4642 TL.setUnderlyingTInfo(TInfo);
4644 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
4645 // FIXME: This holds only because we only have one unary transform.
4646 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
4647 TL.setKWLoc(DS.getTypeSpecTypeLoc());
4648 TL.setParensRange(DS.getTypeofParensRange());
4649 assert(DS.getRepAsType());
4650 TypeSourceInfo *TInfo = nullptr;
4651 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4652 TL.setUnderlyingTInfo(TInfo);
4654 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
4655 // By default, use the source location of the type specifier.
4656 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
4657 if (TL.needsExtraLocalData()) {
4658 // Set info for the written builtin specifiers.
4659 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
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').
4663 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
4664 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
4665 // Width spec loc overrides type spec loc (e.g., 'short int').
4666 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
4669 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
4670 ElaboratedTypeKeyword Keyword
4671 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
4672 if (DS.getTypeSpecType() == TST_typename) {
4673 TypeSourceInfo *TInfo = nullptr;
4674 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4676 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
4680 TL.setElaboratedKeywordLoc(Keyword != ETK_None
4681 ? DS.getTypeSpecTypeLoc()
4682 : SourceLocation());
4683 const CXXScopeSpec& SS = DS.getTypeSpecScope();
4684 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4685 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
4687 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
4688 assert(DS.getTypeSpecType() == TST_typename);
4689 TypeSourceInfo *TInfo = nullptr;
4690 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4692 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
4694 void VisitDependentTemplateSpecializationTypeLoc(
4695 DependentTemplateSpecializationTypeLoc TL) {
4696 assert(DS.getTypeSpecType() == TST_typename);
4697 TypeSourceInfo *TInfo = nullptr;
4698 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4701 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
4703 void VisitTagTypeLoc(TagTypeLoc TL) {
4704 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
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());
4711 TL.setParensRange(DS.getTypeofParensRange());
4713 TypeSourceInfo *TInfo = nullptr;
4714 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4716 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
4718 TL.setKWLoc(DS.getAtomicSpecLoc());
4719 // No parens, to indicate this was spelled as an _Atomic qualifier.
4720 TL.setParensRange(SourceRange());
4721 Visit(TL.getValueLoc());
4725 void VisitPipeTypeLoc(PipeTypeLoc TL) {
4726 TL.setKWLoc(DS.getTypeSpecTypeLoc());
4728 TypeSourceInfo *TInfo = 0;
4729 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4730 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
4733 void VisitTypeLoc(TypeLoc TL) {
4734 // FIXME: add other typespec types and change this to an assert.
4735 TL.initialize(Context, DS.getTypeSpecTypeLoc());
4739 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
4740 ASTContext &Context;
4741 const DeclaratorChunk &Chunk;
4744 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
4745 : Context(Context), Chunk(Chunk) {}
4747 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4748 llvm_unreachable("qualified type locs not expected here!");
4750 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
4751 llvm_unreachable("decayed type locs not expected here!");
4754 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4755 fillAttributedTypeLoc(TL, Chunk.getAttrs());
4757 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
4760 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
4761 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
4762 TL.setCaretLoc(Chunk.Loc);
4764 void VisitPointerTypeLoc(PointerTypeLoc TL) {
4765 assert(Chunk.Kind == DeclaratorChunk::Pointer);
4766 TL.setStarLoc(Chunk.Loc);
4768 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4769 assert(Chunk.Kind == DeclaratorChunk::Pointer);
4770 TL.setStarLoc(Chunk.Loc);
4772 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
4773 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
4774 const CXXScopeSpec& SS = Chunk.Mem.Scope();
4775 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
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()) {
4783 case NestedNameSpecifier::Identifier:
4784 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
4786 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
4787 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
4788 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
4789 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
4793 case NestedNameSpecifier::TypeSpec:
4794 case NestedNameSpecifier::TypeSpecWithTemplate:
4795 if (isa<ElaboratedType>(ClsTy)) {
4796 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
4797 ETLoc.setElaboratedKeywordLoc(SourceLocation());
4798 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
4799 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
4800 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
4802 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
4806 case NestedNameSpecifier::Namespace:
4807 case NestedNameSpecifier::NamespaceAlias:
4808 case NestedNameSpecifier::Global:
4809 case NestedNameSpecifier::Super:
4810 llvm_unreachable("Nested-name-specifier must name a type");
4813 // Finally fill in MemberPointerLocInfo fields.
4814 TL.setStarLoc(Chunk.Loc);
4815 TL.setClassTInfo(ClsTInfo);
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);
4823 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
4824 assert(Chunk.Kind == DeclaratorChunk::Reference);
4825 assert(!Chunk.Ref.LValueRef);
4826 TL.setAmpAmpLoc(Chunk.Loc);
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));
4834 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
4835 assert(Chunk.Kind == DeclaratorChunk::Function);
4836 TL.setLocalRangeBegin(Chunk.Loc);
4837 TL.setLocalRangeEnd(Chunk.EndLoc);
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);
4846 // FIXME: exception specs
4848 void VisitParenTypeLoc(ParenTypeLoc TL) {
4849 assert(Chunk.Kind == DeclaratorChunk::Paren);
4850 TL.setLParenLoc(Chunk.Loc);
4851 TL.setRParenLoc(Chunk.EndLoc);
4853 void VisitPipeTypeLoc(PipeTypeLoc TL) {
4854 assert(Chunk.Kind == DeclaratorChunk::Pipe);
4855 TL.setKWLoc(Chunk.Loc);
4858 void VisitTypeLoc(TypeLoc TL) {
4859 llvm_unreachable("unsupported TypeLoc kind in declarator!");
4864 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
4866 switch (Chunk.Kind) {
4867 case DeclaratorChunk::Function:
4868 case DeclaratorChunk::Array:
4869 case DeclaratorChunk::Paren:
4870 case DeclaratorChunk::Pipe:
4871 llvm_unreachable("cannot be _Atomic qualified");
4873 case DeclaratorChunk::Pointer:
4874 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
4877 case DeclaratorChunk::BlockPointer:
4878 case DeclaratorChunk::Reference:
4879 case DeclaratorChunk::MemberPointer:
4880 // FIXME: Provide a source location for the _Atomic keyword.
4885 ATL.setParensRange(SourceRange());
4888 /// \brief Create and instantiate a TypeSourceInfo with type source information.
4890 /// \param T QualType referring to the type as written in source code.
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.
4897 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
4898 TypeSourceInfo *ReturnTypeInfo) {
4899 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
4900 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
4901 const AttributeList *DeclAttrs = D.getAttributes();
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();
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();
4917 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
4918 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs);
4919 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
4922 // FIXME: Ordering here?
4923 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
4924 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
4926 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
4927 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
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());
4937 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
4943 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
4944 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
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),
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));
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");
4963 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
4964 // C99 6.7.6: Type names have no identifier. This is already validated by
4966 assert(D.getIdentifier() == nullptr &&
4967 "Type name should have no identifier!");
4969 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4970 QualType T = TInfo->getType();
4971 if (D.isInvalidType())
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.
4979 if (D.getContext() != Declarator::ObjCParameterContext &&
4980 D.getContext() != Declarator::AliasDeclContext &&
4981 D.getContext() != Declarator::AliasTemplateContext)
4982 checkUnusedDeclAttributes(D);
4984 if (getLangOpts().CPlusPlus) {
4985 // Check that there are no default arguments (C++ only).
4986 CheckExtraCXXDefaultArguments(D);
4989 return CreateParsedType(T, TInfo);
4992 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
4993 QualType T = Context.getObjCInstanceType();
4994 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
4995 return CreateParsedType(T, TInfo);
4999 //===----------------------------------------------------------------------===//
5000 // Type Attribute Processing
5001 //===----------------------------------------------------------------------===//
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.
5006 static void HandleAddressSpaceTypeAttribute(QualType &Type,
5007 const AttributeList &Attr, Sema &S){
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);
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);
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;
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)
5040 << Attr.getName() << AANT_ArgumentIntegerConstant
5041 << ASArgExpr->getSourceRange();
5047 if (addrSpace.isSigned()) {
5048 if (addrSpace.isNegative()) {
5049 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
5050 << ASArgExpr->getSourceRange();
5054 addrSpace.setIsSigned(false);
5056 llvm::APSInt max(addrSpace.getBitWidth());
5057 max = Qualifiers::MaxAddressSpace;
5058 if (addrSpace > max) {
5059 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
5060 << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange();
5064 ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
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;
5077 assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace);
5082 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
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?
5088 static bool hasDirectOwnershipQualifier(QualType type) {
5089 // Fast path: no qualifier at all.
5090 assert(type.getQualifiers().hasObjCLifetime());
5094 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
5095 if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
5098 type = attr->getModifiedType();
5100 // X *__strong (...)
5101 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
5102 type = paren->getInnerType();
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
5115 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
5116 /// attribute on the specified type.
5118 /// Returns 'true' if the attribute was handled.
5119 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
5120 AttributeList &attr,
5122 bool NonObjCPointer = false;
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())
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()) {
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();
5141 if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
5142 /*onlyBlockPointers=*/true))
5147 Sema &S = state.getSema();
5148 SourceLocation AttrLoc = attr.getLoc();
5149 if (AttrLoc.isMacroID())
5150 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
5152 if (!attr.isArgIdent(0)) {
5153 S.Diag(AttrLoc, diag::err_attribute_argument_type)
5154 << attr.getName() << AANT_ArgumentString;
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;
5170 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
5171 << attr.getName() << II;
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) {
5184 SplitQualType underlyingType = type.split();
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)
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();
5204 underlyingType.Quals.removeObjCLifetime();
5208 underlyingType.Quals.addObjCLifetime(lifetime);
5210 if (NonObjCPointer) {
5211 StringRef name = attr.getName()->getName();
5213 case Qualifiers::OCL_None:
5214 case Qualifiers::OCL_ExplicitNone:
5216 case Qualifiers::OCL_Strong: name = "__strong"; break;
5217 case Qualifiers::OCL_Weak: name = "__weak"; break;
5218 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
5220 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
5221 << TDS_ObjCObjOrBlock << type;
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().
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(
5238 AttributedType::attr_objc_inert_unsafe_unretained,
5243 QualType origType = type;
5244 if (!NonObjCPointer)
5245 type = S.Context.getQualifiedType(underlyingType);
5247 // If we have a valid source location for the attribute, use an
5248 // AttributedType instead.
5249 if (AttrLoc.isValid())
5250 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
5253 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
5254 unsigned diagnostic, QualType type) {
5255 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
5256 S.DelayedDiagnostics.add(
5257 sema::DelayedDiagnostic::makeForbiddenType(
5258 S.getSourceManager().getExpansionLoc(loc),
5259 diagnostic, type, /*ignored*/ 0));
5261 S.Diag(loc, diagnostic);
5265 // Sometimes, __weak isn't allowed.
5266 if (lifetime == Qualifiers::OCL_Weak &&
5267 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
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);
5274 // In any case, delay the diagnostic until we know what we're parsing.
5275 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
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);
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,
5306 Sema &S = state.getSema();
5308 // Delay if this isn't some kind of pointer.
5309 if (!type->isPointerType() &&
5310 !type->isObjCObjectPointerType() &&
5311 !type->isBlockPointerType())
5314 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
5315 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
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;
5327 Qualifiers::GC GCAttr;
5328 if (attr.getNumArgs() > 1) {
5329 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5330 << attr.getName() << 1;
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;
5341 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
5342 << attr.getName() << II;
5347 QualType origType = type;
5348 type = S.Context.getObjCGCQualType(origType, GCAttr);
5350 // Make an attributed type to preserve the source information.
5351 if (attr.getLoc().isValid())
5352 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
5359 /// A helper class to unwrap a type down to a function for the
5360 /// purposes of applying attributes there.
5363 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
5364 /// if (unwrapped.isFunctionType()) {
5365 /// const FunctionType *fn = unwrapped.get();
5366 /// // change fn somehow
5367 /// T = unwrapped.wrap(fn);
5369 struct FunctionTypeUnwrapper {
5380 const FunctionType *Fn;
5381 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
5383 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
5385 const Type *Ty = T.getTypePtr();
5386 if (isa<FunctionType>(Ty)) {
5387 Fn = cast<FunctionType>(Ty);
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);
5405 const Type *DTy = Ty->getUnqualifiedDesugaredType();
5411 T = QualType(DTy, 0);
5412 Stack.push_back(Desugar);
5417 bool isFunctionType() const { return (Fn != nullptr); }
5418 const FunctionType *get() const { return Fn; }
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;
5425 return wrap(S.Context, Original, 0);
5429 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
5430 if (I == Stack.size())
5431 return C.getQualifiedType(Fn, Old.getQualifiers());
5433 // Build up the inner type, applying the qualifiers from the old
5434 // type to the new type.
5435 SplitQualType SplitOld = Old.split();
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);
5443 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
5444 if (I == Stack.size()) return QualType(Fn, 0);
5446 switch (static_cast<WrapKind>(Stack[I++])) {
5448 // This is the point at which we potentially lose source
5450 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
5453 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
5454 return C.getParenType(New);
5458 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
5459 return C.getPointerType(New);
5462 case BlockPointer: {
5463 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
5464 return C.getBlockPointerType(New);
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());
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());
5479 return C.getRValueReferenceType(New);
5483 llvm_unreachable("unknown wrapping kind");
5488 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
5489 AttributeList &Attr,
5491 Sema &S = State.getSema();
5493 AttributeList::Kind Kind = Attr.getKind();
5494 QualType Desugared = Type;
5495 const AttributedType *AT = dyn_cast<AttributedType>(Type);
5497 AttributedType::Kind CurAttrKind = AT->getAttrKind();
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)
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'";
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'";
5525 Desugared = AT->getEquivalentType();
5526 AT = dyn_cast<AttributedType>(Desugared);
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)
5536 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
5537 << Attr.getName() << 0;
5541 AttributedType::Kind TAK;
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;
5550 Type = S.Context.getAttributedType(TAK, Type, Type);
5554 bool Sema::checkNullabilityTypeSpecifier(QualType &type,
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);
5571 fileNullability.SawTypeNullability = true;
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);
5589 // Conflicting nullability.
5590 Diag(nullabilityLoc, diag::err_nullability_conflicting)
5591 << DiagNullabilityKind(nullability, isContextSensitive)
5592 << DiagNullabilityKind(*existingNullability, false);
5596 desugared = attributed->getModifiedType();
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);
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);
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;
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)
5644 Diag(nullabilityLoc, diag::note_nullability_type_specifier)
5645 << DiagNullabilityKind(nullability, false)
5647 << FixItHint::CreateReplacement(nullabilityLoc,
5648 getNullabilitySpelling(nullability));
5653 // Form the attributed type.
5654 type = Context.getAttributedType(
5655 AttributedType::getNullabilityAttrKind(nullability), type, type);
5659 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) {
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>();
5665 // If not, we can't apply __kindof.
5667 // FIXME: Handle dependent types that aren't yet object types.
5668 Diag(loc, diag::err_objc_kindof_nonobject)
5673 // Rebuild the "equivalent" type, which pushes __kindof down into
5675 QualType equivType = Context.getObjCObjectType(objType->getBaseType(),
5676 objType->getTypeArgsAsWritten(),
5677 objType->getProtocols(),
5680 // If we started with an object pointer type, rebuild it.
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);
5689 // Build the attributed type to record where __kindof occurred.
5690 type = Context.getAttributedType(AttributedType::attr_objc_kindof,
5697 /// Map a nullability attribute kind to a nullability kind.
5698 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) {
5700 case AttributeList::AT_TypeNonNull:
5701 return NullabilityKind::NonNull;
5703 case AttributeList::AT_TypeNullable:
5704 return NullabilityKind::Nullable;
5706 case AttributeList::AT_TypeNullUnspecified:
5707 return NullabilityKind::Unspecified;
5710 llvm_unreachable("not a nullability attribute kind");
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.
5718 /// \returns true if the nullability annotation was distributed, false
5720 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
5722 AttributeList &attr) {
5723 Declarator &declarator = state.getDeclarator();
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
5729 if (hasNullabilityAttr(chunk.getAttrListRef()))
5732 // Complain about the nullability qualifier being in the wrong
5739 PK_MemberFunctionPointer,
5741 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
5743 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
5744 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
5746 auto diag = state.getSema().Diag(attr.getLoc(),
5747 diag::warn_nullability_declspec)
5748 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
5749 attr.isContextSensitiveKeywordAttribute())
5751 << static_cast<unsigned>(pointerKind);
5753 // FIXME: MemberPointer chunks don't carry the location of the *.
5754 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
5755 diag << FixItHint::CreateRemoval(attr.getLoc())
5756 << FixItHint::CreateInsertion(
5757 state.getSema().getPreprocessor()
5758 .getLocForEndOfToken(chunk.Loc),
5759 " " + attr.getName()->getName().str() + " ");
5762 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
5763 chunk.getAttrListRef());
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) {
5772 case DeclaratorChunk::Pointer:
5773 case DeclaratorChunk::BlockPointer:
5774 case DeclaratorChunk::MemberPointer:
5775 return moveToChunk(chunk, false);
5777 case DeclaratorChunk::Paren:
5778 case DeclaratorChunk::Array:
5781 case DeclaratorChunk::Function:
5782 // Try to move past the return type to a function/block/member
5783 // function pointer.
5784 if (DeclaratorChunk *dest = maybeMovePastReturnType(
5786 /*onlyBlockPointers=*/false)) {
5787 return moveToChunk(*dest, true);
5792 // Don't walk through these.
5793 case DeclaratorChunk::Reference:
5794 case DeclaratorChunk::Pipe:
5802 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
5803 assert(!Attr.isInvalid());
5804 switch (Attr.getKind()) {
5806 llvm_unreachable("not a calling convention attribute");
5807 case AttributeList::AT_CDecl:
5808 return AttributedType::attr_cdecl;
5809 case AttributeList::AT_FastCall:
5810 return AttributedType::attr_fastcall;
5811 case AttributeList::AT_StdCall:
5812 return AttributedType::attr_stdcall;
5813 case AttributeList::AT_ThisCall:
5814 return AttributedType::attr_thiscall;
5815 case AttributeList::AT_Pascal:
5816 return AttributedType::attr_pascal;
5817 case AttributeList::AT_VectorCall:
5818 return AttributedType::attr_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.
5824 if (Attr.isArgExpr(0))
5825 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
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);
5832 case AttributeList::AT_IntelOclBicc:
5833 return AttributedType::attr_inteloclbicc;
5834 case AttributeList::AT_MSABI:
5835 return AttributedType::attr_ms_abi;
5836 case AttributeList::AT_SysVABI:
5837 return AttributedType::attr_sysv_abi;
5839 llvm_unreachable("unexpected attribute kind!");
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,
5847 Sema &S = state.getSema();
5849 FunctionTypeUnwrapper unwrapped(S, type);
5851 if (attr.getKind() == AttributeList::AT_NoReturn) {
5852 if (S.CheckNoReturnAttr(attr))
5855 // Delay if this is not a function type.
5856 if (!unwrapped.isFunctionType())
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));
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;
5872 // Delay if this is not a function type.
5873 if (!unwrapped.isFunctionType())
5876 FunctionType::ExtInfo EI
5877 = unwrapped.get()->getExtInfo().withProducesResult(true);
5878 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5882 if (attr.getKind() == AttributeList::AT_Regparm) {
5884 if (S.CheckRegparmAttr(attr, value))
5887 // Delay if this is not a function type.
5888 if (!unwrapped.isFunctionType())
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)
5896 << FunctionType::getNameForCallConv(CC)
5902 FunctionType::ExtInfo EI =
5903 unwrapped.get()->getExtInfo().withRegParm(value);
5904 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5908 // Delay if the type didn't work out to a function.
5909 if (!unwrapped.isFunctionType()) return false;
5911 // Otherwise, a calling convention.
5913 if (S.CheckCallingConvAttr(attr, CC))
5916 const FunctionType *fn = unwrapped.get();
5917 CallingConv CCOld = fn->getCallConv();
5918 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
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)
5926 << FunctionType::getNameForCallConv(CC)
5927 << FunctionType::getNameForCallConv(CCOld);
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
5940 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
5941 DiagID = diag::warn_cconv_varargs;
5943 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
5949 // Also diagnose fastcall with regparm.
5950 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
5951 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5952 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
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);
5967 bool Sema::hasExplicitCallingConv(QualType &T) {
5968 QualType R = T.IgnoreParens();
5969 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
5970 if (AT->isCallingConv())
5972 R = AT->getModifiedType().IgnoreParens();
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);
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)
5996 << FunctionType::getNameForCallConv(CurCC);
5997 // Default adjustment.
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);
6005 if (CurCC != DefaultCC || DefaultCC == ToCC)
6008 if (hasExplicitCallingConv(T))
6012 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
6013 QualType Wrapped = Unwrapped.wrap(*this, FT);
6014 T = Context.getAdjustedType(T, Wrapped);
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,
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;
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)
6038 << Attr.getName() << AANT_ArgumentIntegerConstant
6039 << sizeExpr->getSourceRange();
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;
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);
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();
6062 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
6063 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
6064 << sizeExpr->getSourceRange();
6068 if (vectorSize == 0) {
6069 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
6070 << sizeExpr->getSourceRange();
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,
6078 VectorType::GenericVector);
6081 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
6083 static void HandleExtVectorTypeAttr(QualType &CurType,
6084 const AttributeList &Attr,
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;
6095 // Special case where the argument is a template id.
6096 if (Attr.isArgIdent(0)) {
6098 SourceLocation TemplateKWLoc;
6100 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
6102 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
6104 if (Size.isInvalid())
6107 sizeExpr = Size.get();
6109 sizeExpr = Attr.getArgAsExpr(0);
6112 // Create the vector type.
6113 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
6118 static bool isPermittedNeonBaseType(QualType &Ty,
6119 VectorType::VectorKind VecKind, Sema &S) {
6120 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
6124 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
6126 // Signed poly is mathematically wrong, but has been baked into some ABIs by
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;
6138 // AArch32 polynomial vector are signed.
6139 return BTy->getKind() == BuiltinType::SChar ||
6140 BTy->getKind() == BuiltinType::Short;
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;
6149 if (Is64Bit && BTy->getKind() == BuiltinType::Double)
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;
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();
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;
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)
6195 << Attr.getName() << AANT_ArgumentIntegerConstant
6196 << numEltsExpr->getSourceRange();
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;
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;
6217 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
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.
6227 bool hasOpenCLAddressSpace = false;
6229 AttributeList &attr = *attrs;
6230 attrs = attr.getNext(); // reset to the next here due to early loop continue
6233 // Skip attributes that were marked to be invalid.
6234 if (attr.isInvalid())
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
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)
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.
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()) {
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)
6263 attr.setUsedAsTypeAttr();
6267 case AttributeList::UnknownAttribute:
6268 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
6269 state.getSema().Diag(attr.getLoc(),
6270 diag::warn_unknown_attribute_ignored)
6274 case AttributeList::IgnoredAttribute:
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();
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;
6292 OBJC_POINTER_TYPE_ATTRS_CASELIST:
6293 if (!handleObjCPointerTypeAttr(state, attr, type))
6294 distributeObjCPointerTypeAttr(state, attr, type);
6295 attr.setUsedAsTypeAttr();
6297 case AttributeList::AT_VectorSize:
6298 HandleVectorSizeAttr(type, attr, state.getSema());
6299 attr.setUsedAsTypeAttr();
6301 case AttributeList::AT_ExtVectorType:
6302 HandleExtVectorTypeAttr(type, attr, state.getSema());
6303 attr.setUsedAsTypeAttr();
6305 case AttributeList::AT_NeonVectorType:
6306 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6307 VectorType::NeonVector);
6308 attr.setUsedAsTypeAttr();
6310 case AttributeList::AT_NeonPolyVectorType:
6311 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6312 VectorType::NeonPolyVector);
6313 attr.setUsedAsTypeAttr();
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();
6321 MS_TYPE_ATTRS_CASELIST:
6322 if (!handleMSPointerTypeQualifierAttr(state, attr, type))
6323 attr.setUsedAsTypeAttr();
6327 NULLABILITY_TYPE_ATTRS_CASELIST:
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(
6335 mapNullabilityAttrKind(attr.getKind()),
6337 attr.isContextSensitiveKeywordAttribute())) {
6341 attr.setUsedAsTypeAttr();
6345 case AttributeList::AT_ObjCKindOf:
6346 // '__kindof' must be part of the decl-specifiers.
6353 state.getSema().Diag(attr.getLoc(),
6354 diag::err_objc_kindof_wrong_position)
6355 << FixItHint::CreateRemoval(attr.getLoc())
6356 << FixItHint::CreateInsertion(
6357 state.getDeclarator().getDeclSpec().getLocStart(), "__kindof ");
6361 // Apply it regardless.
6362 if (state.getSema().checkObjCKindOfType(type, attr.getLoc()))
6364 attr.setUsedAsTypeAttr();
6367 case AttributeList::AT_NSReturnsRetained:
6368 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
6370 // fallthrough into the function attrs
6372 FUNCTION_TYPE_ATTRS_CASELIST:
6373 attr.setUsedAsTypeAttr();
6375 // Never process function type attributes as part of the
6376 // declaration-specifiers.
6377 if (TAL == TAL_DeclSpec)
6378 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
6380 // Otherwise, handle the possible delays.
6381 else if (!handleFunctionTypeAttr(state, attr, type))
6382 distributeFunctionTypeAttr(state, attr, type);
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.
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 ==
6402 DeclaratorChunk::Pointer) {
6403 type = state.getSema().Context.getAddrSpaceQualType(
6404 type, LangAS::opencl_generic);
6405 } else if (state.getCurrentChunkIndex() == 0 &&
6406 D.getContext() == Declarator::FileContext &&
6407 !D.isFunctionDeclarator() && !D.isFunctionDefinition() &&
6408 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6409 !type->isSamplerT())
6410 type = state.getSema().Context.getAddrSpaceQualType(
6411 type, LangAS::opencl_global);
6412 else if (state.getCurrentChunkIndex() == 0 &&
6413 D.getContext() == Declarator::BlockContext &&
6414 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
6415 type = state.getSema().Context.getAddrSpaceQualType(
6416 type, LangAS::opencl_global);
6420 void Sema::completeExprArrayBound(Expr *E) {
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();
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);
6432 // This is a modification of an existing AST node. Notify
6434 if (ASTMutationListener *L = getASTMutationListener())
6435 L->StaticDataMemberInstantiated(Var);
6438 VarTemplateSpecializationDecl *VarSpec =
6439 cast<VarTemplateSpecializationDecl>(Var);
6440 if (VarSpec->getPointOfInstantiation().isInvalid())
6441 VarSpec->setPointOfInstantiation(PointOfInstantiation);
6444 InstantiateVariableDefinition(PointOfInstantiation, Var);
6446 // Update the type to the newly instantiated definition's type both
6447 // here and within the expression.
6448 if (VarDecl *Def = Var->getDefinition()) {
6450 QualType T = Def->getType();
6452 // FIXME: Update the type on all intervening expressions.
6456 // We still go on to try to complete the type independently, as it
6457 // may also require instantiations or diagnostics if it remains
6464 /// \brief Ensure that the type of the given expression is complete.
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).
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
6476 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
6478 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) {
6479 QualType T = E->getType();
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()) {
6486 completeExprArrayBound(E);
6490 // FIXME: Are there other cases which require instantiating something other
6491 // than the type to complete the type of an expression?
6493 return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
6496 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
6497 BoundTypeDiagnoser<> Diagnoser(DiagID);
6498 return RequireCompleteExprType(E, Diagnoser);
6501 /// @brief Ensure that the type T is a complete type.
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.
6511 /// @param Loc The location in the source that the incomplete type
6512 /// diagnostic should refer to.
6514 /// @param T The type that this routine is examining for completeness.
6516 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
6517 /// @c false otherwise.
6518 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
6519 TypeDiagnoser &Diagnoser) {
6520 if (RequireCompleteTypeImpl(Loc, T, &Diagnoser))
6522 if (const TagType *Tag = T->getAs<TagType>()) {
6523 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
6524 Tag->getDecl()->setCompleteDefinitionRequired();
6525 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
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
6540 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
6541 bool OnlyNeedComplete) {
6542 // Easy case: if we don't have modules, all declarations are visible.
6543 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
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
6552 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6553 if (auto *Pattern = RD->getTemplateInstantiationPattern())
6555 D = RD->getDefinition();
6556 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
6557 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
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
6563 *Suggested = nullptr;
6564 for (auto *Redecl : ED->redecls()) {
6565 if (isVisible(Redecl))
6567 if (Redecl->isThisDeclarationADefinition() ||
6568 (Redecl->isCanonicalDecl() && !*Suggested))
6569 *Suggested = Redecl;
6573 D = ED->getDefinition();
6575 assert(D && "missing definition for pattern of instantiated definition");
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);
6591 /// Locks in the inheritance model for the given class and all of its bases.
6592 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
6593 RD = RD->getMostRecentDecl();
6594 if (!RD->hasAttr<MSInheritanceAttr>()) {
6595 MSInheritanceAttr::Spelling IM;
6597 switch (S.MSPointerToMemberRepresentationMethod) {
6598 case LangOptions::PPTMK_BestCase:
6599 IM = RD->calculateInheritanceModel();
6601 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
6602 IM = MSInheritanceAttr::Keyword_single_inheritance;
6604 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
6605 IM = MSInheritanceAttr::Keyword_multiple_inheritance;
6607 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
6608 IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
6612 RD->addAttr(MSInheritanceAttr::CreateImplicit(
6613 S.getASTContext(), IM,
6614 /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
6615 LangOptions::PPTMK_BestCase,
6616 S.ImplicitMSInheritanceAttrLoc.isValid()
6617 ? S.ImplicitMSInheritanceAttrLoc
6618 : RD->getSourceRange()));
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.
6630 // assert(!T->isDependentType() &&
6631 // "Can't ask whether a dependent type is complete");
6633 // We lock in the inheritance model once somebody has asked us to ensure
6634 // that a pointer-to-member type is complete.
6635 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
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());
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;
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();
6655 diagnoseMissingImport(Loc, SuggestedDef, /*NeedDefinition*/true,
6656 /*Recover*/TreatAsComplete);
6657 return !TreatAsComplete;
6663 const TagType *Tag = T->getAs<TagType>();
6664 const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
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.
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)?
6675 // FIXME: Should we map through to the base array element type before
6676 // checking for a tag type?
6679 Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
6681 // Avoid diagnosing invalid decls as incomplete.
6682 if (D->isInvalidDecl())
6685 // Give the external AST source a chance to complete the type.
6686 if (auto *Source = Context.getExternalSource()) {
6688 Source->CompleteType(Tag->getDecl());
6690 Source->CompleteType(IFace->getDecl());
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);
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) {
6712 Diagnosed = InstantiateClassTemplateSpecialization(
6713 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
6714 /*Complain=*/Diagnoser);
6715 Instantiated = true;
6717 } else if (CXXRecordDecl *Rec
6718 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
6719 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
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() !=
6725 TSK_ExplicitSpecialization) {
6726 Diagnosed = InstantiateClass(Loc, Rec, Pattern,
6727 getTemplateInstantiationArgs(Rec),
6728 TSK_ImplicitInstantiation,
6729 /*Complain=*/Diagnoser);
6730 Instantiated = true;
6736 // Instantiate* might have already complained that the template is not
6737 // defined, if we asked it to.
6738 if (Diagnoser && Diagnosed)
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);
6751 // We have an incomplete type. Produce a diagnostic.
6752 if (Ident___float128 &&
6753 T == Context.getTypeDeclType(Context.getFloat128StubType())) {
6754 Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128);
6758 Diagnoser->diagnose(*this, Loc, T);
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);
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);
6772 // If we have external information that we can use to suggest a fix,
6775 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
6780 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
6782 BoundTypeDiagnoser<> Diagnoser(DiagID);
6783 return RequireCompleteType(Loc, T, Diagnoser);
6786 /// \brief Get diagnostic %select index for tag kind for
6787 /// literal type diagnostic message.
6788 /// WARNING: Indexes apply to particular diagnostics only!
6790 /// \returns diagnostic %select index.
6791 static unsigned getLiteralDiagFromTagKind(TagTypeKind 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!");
6800 /// @brief Ensure that the type T is a literal type.
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.
6809 /// @param Loc The location in the source that the non-literal type
6810 /// diagnostic should refer to.
6812 /// @param T The type that this routine is examining for literalness.
6814 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
6816 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
6817 /// @c false otherwise.
6818 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
6819 TypeDiagnoser &Diagnoser) {
6820 assert(!T->isDependentType() && "type should not be dependent");
6822 QualType ElemType = Context.getBaseElementType(T);
6823 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
6824 T->isLiteralType(Context))
6827 Diagnoser.diagnose(*this, Loc, T);
6829 if (T->isVariableArrayType())
6832 const RecordType *RT = ElemType->getAs<RecordType>();
6836 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
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))
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)
6850 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
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() &&
6855 !RD->hasTrivialDefaultConstructor()) {
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();
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();
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?");
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);
6893 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
6894 BoundTypeDiagnoser<> Diagnoser(DiagID);
6895 return RequireLiteralType(Loc, T, Diagnoser);
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.
6900 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
6901 const CXXScopeSpec &SS, QualType T) {
6904 NestedNameSpecifier *NNS;
6906 NNS = SS.getScopeRep();
6908 if (Keyword == ETK_None)
6912 return Context.getElaboratedType(Keyword, NNS, T);
6915 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
6916 ExprResult ER = CheckPlaceholderExpr(E);
6917 if (ER.isInvalid()) return QualType();
6920 if (!getLangOpts().CPlusPlus && E->refersToBitField())
6921 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
6923 if (!E->isTypeDependent()) {
6924 QualType T = E->getType();
6925 if (const TagType *TT = T->getAs<TagType>())
6926 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
6928 return Context.getTypeOfExprType(E);
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.
6934 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
6935 if (E->isTypeDependent())
6936 return S.Context.DependentTy;
6938 // C++11 [dcl.type.simple]p4:
6939 // The type denoted by decltype(e) is defined as follows:
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;
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();
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
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());
6976 return S.Context.getLValueReferenceType(T);
6983 // C++11 [dcl.type.simple]p4:
6985 QualType T = E->getType();
6986 switch (E->getValueKind()) {
6987 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
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
6992 case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
6993 // - otherwise, decltype(e) is the type of e.
6994 case VK_RValue: break;
7000 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
7001 bool AsUnevaluated) {
7002 ExprResult ER = CheckPlaceholderExpr(E);
7003 if (ER.isInvalid()) return QualType();
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);
7013 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
7016 QualType Sema::BuildUnaryTransformType(QualType BaseType,
7017 UnaryTransformType::UTTKind UKind,
7018 SourceLocation Loc) {
7020 case UnaryTransformType::EnumUnderlyingType:
7021 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
7022 Diag(Loc, diag::err_only_enums_have_underlying_types);
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;
7036 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
7037 assert(ED && "EnumType has no EnumDecl");
7039 DiagnoseUseOfDecl(ED, Loc);
7041 Underlying = ED->getIntegerType();
7042 assert(!Underlying.isNull());
7044 return Context.getUnaryTransformType(BaseType, Underlying,
7045 UnaryTransformType::EnumUnderlyingType);
7048 llvm_unreachable("unknown unary transform type");
7051 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
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))
7058 int DisallowedKind = -1;
7059 if (T->isArrayType())
7061 else if (T->isFunctionType())
7063 else if (T->isReferenceType())
7065 else if (T->isAtomicType())
7067 else if (T.hasQualifiers())
7069 else if (!T.isTriviallyCopyableType(Context))
7070 // Some other non-trivially-copyable type (probably a C++ class)
7073 if (DisallowedKind != -1) {
7074 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
7078 // FIXME: Do we need any handling for ARC here?
7081 // Build the pointer type.
7082 return Context.getAtomicType(T);