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/Basic/PartialDiagnostic.h"
26 #include "clang/Basic/TargetInfo.h"
27 #include "clang/Parse/ParseDiagnostic.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/DelayedDiagnostic.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/ScopeInfo.h"
32 #include "clang/Sema/Template.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/Support/ErrorHandling.h"
37 using namespace clang;
39 enum TypeDiagSelector {
45 /// isOmittedBlockReturnType - Return true if this declarator is missing a
46 /// return type because this is a omitted return type on a block literal.
47 static bool isOmittedBlockReturnType(const Declarator &D) {
48 if (D.getContext() != Declarator::BlockLiteralContext ||
49 D.getDeclSpec().hasTypeSpecifier())
52 if (D.getNumTypeObjects() == 0)
53 return true; // ^{ ... }
55 if (D.getNumTypeObjects() == 1 &&
56 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
57 return true; // ^(int X, float Y) { ... }
62 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
63 /// doesn't apply to the given type.
64 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
66 TypeDiagSelector WhichType;
67 bool useExpansionLoc = true;
68 switch (attr.getKind()) {
69 case AttributeList::AT_ObjCGC: WhichType = TDS_Pointer; break;
70 case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break;
72 // Assume everything else was a function attribute.
73 WhichType = TDS_Function;
74 useExpansionLoc = false;
78 SourceLocation loc = attr.getLoc();
79 StringRef name = attr.getName()->getName();
81 // The GC attributes are usually written with macros; special-case them.
82 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
84 if (useExpansionLoc && loc.isMacroID() && II) {
85 if (II->isStr("strong")) {
86 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
87 } else if (II->isStr("weak")) {
88 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
92 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
96 // objc_gc applies to Objective-C pointers or, otherwise, to the
97 // smallest available pointer type (i.e. 'void*' in 'void**').
98 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
99 case AttributeList::AT_ObjCGC: \
100 case AttributeList::AT_ObjCOwnership
102 // Function type attributes.
103 #define FUNCTION_TYPE_ATTRS_CASELIST \
104 case AttributeList::AT_NoReturn: \
105 case AttributeList::AT_CDecl: \
106 case AttributeList::AT_FastCall: \
107 case AttributeList::AT_StdCall: \
108 case AttributeList::AT_ThisCall: \
109 case AttributeList::AT_Pascal: \
110 case AttributeList::AT_MSABI: \
111 case AttributeList::AT_SysVABI: \
112 case AttributeList::AT_Regparm: \
113 case AttributeList::AT_Pcs: \
114 case AttributeList::AT_PnaclCall: \
115 case AttributeList::AT_IntelOclBicc
117 // Microsoft-specific type qualifiers.
118 #define MS_TYPE_ATTRS_CASELIST \
119 case AttributeList::AT_Ptr32: \
120 case AttributeList::AT_Ptr64: \
121 case AttributeList::AT_SPtr: \
122 case AttributeList::AT_UPtr
125 /// An object which stores processing state for the entire
126 /// GetTypeForDeclarator process.
127 class TypeProcessingState {
130 /// The declarator being processed.
131 Declarator &declarator;
133 /// The index of the declarator chunk we're currently processing.
134 /// May be the total number of valid chunks, indicating the
138 /// Whether there are non-trivial modifications to the decl spec.
141 /// Whether we saved the attributes in the decl spec.
144 /// The original set of attributes on the DeclSpec.
145 SmallVector<AttributeList*, 2> savedAttrs;
147 /// A list of attributes to diagnose the uselessness of when the
148 /// processing is complete.
149 SmallVector<AttributeList*, 2> ignoredTypeAttrs;
152 TypeProcessingState(Sema &sema, Declarator &declarator)
153 : sema(sema), declarator(declarator),
154 chunkIndex(declarator.getNumTypeObjects()),
155 trivial(true), hasSavedAttrs(false) {}
157 Sema &getSema() const {
161 Declarator &getDeclarator() const {
165 bool isProcessingDeclSpec() const {
166 return chunkIndex == declarator.getNumTypeObjects();
169 unsigned getCurrentChunkIndex() const {
173 void setCurrentChunkIndex(unsigned idx) {
174 assert(idx <= declarator.getNumTypeObjects());
178 AttributeList *&getCurrentAttrListRef() const {
179 if (isProcessingDeclSpec())
180 return getMutableDeclSpec().getAttributes().getListRef();
181 return declarator.getTypeObject(chunkIndex).getAttrListRef();
184 /// Save the current set of attributes on the DeclSpec.
185 void saveDeclSpecAttrs() {
186 // Don't try to save them multiple times.
187 if (hasSavedAttrs) return;
189 DeclSpec &spec = getMutableDeclSpec();
190 for (AttributeList *attr = spec.getAttributes().getList(); attr;
191 attr = attr->getNext())
192 savedAttrs.push_back(attr);
193 trivial &= savedAttrs.empty();
194 hasSavedAttrs = true;
197 /// Record that we had nowhere to put the given type attribute.
198 /// We will diagnose such attributes later.
199 void addIgnoredTypeAttr(AttributeList &attr) {
200 ignoredTypeAttrs.push_back(&attr);
203 /// Diagnose all the ignored type attributes, given that the
204 /// declarator worked out to the given type.
205 void diagnoseIgnoredTypeAttrs(QualType type) const {
206 for (SmallVectorImpl<AttributeList*>::const_iterator
207 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
209 diagnoseBadTypeAttribute(getSema(), **i, type);
212 ~TypeProcessingState() {
215 restoreDeclSpecAttrs();
219 DeclSpec &getMutableDeclSpec() const {
220 return const_cast<DeclSpec&>(declarator.getDeclSpec());
223 void restoreDeclSpecAttrs() {
224 assert(hasSavedAttrs);
226 if (savedAttrs.empty()) {
227 getMutableDeclSpec().getAttributes().set(nullptr);
231 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
232 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
233 savedAttrs[i]->setNext(savedAttrs[i+1]);
234 savedAttrs.back()->setNext(nullptr);
239 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
244 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
246 head = attr.getNext();
250 AttributeList *cur = head;
252 assert(cur && cur->getNext() && "ran out of attrs?");
253 if (cur->getNext() == &attr) {
254 cur->setNext(attr.getNext());
257 cur = cur->getNext();
261 static void moveAttrFromListToList(AttributeList &attr,
262 AttributeList *&fromList,
263 AttributeList *&toList) {
264 spliceAttrOutOfList(attr, fromList);
265 spliceAttrIntoList(attr, toList);
268 /// The location of a type attribute.
269 enum TypeAttrLocation {
270 /// The attribute is in the decl-specifier-seq.
272 /// The attribute is part of a DeclaratorChunk.
274 /// The attribute is immediately after the declaration's name.
278 static void processTypeAttrs(TypeProcessingState &state,
279 QualType &type, TypeAttrLocation TAL,
280 AttributeList *attrs);
282 static bool handleFunctionTypeAttr(TypeProcessingState &state,
286 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
290 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
291 AttributeList &attr, QualType &type);
293 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
294 AttributeList &attr, QualType &type);
296 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
297 AttributeList &attr, QualType &type) {
298 if (attr.getKind() == AttributeList::AT_ObjCGC)
299 return handleObjCGCTypeAttr(state, attr, type);
300 assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
301 return handleObjCOwnershipTypeAttr(state, attr, type);
304 /// Given the index of a declarator chunk, check whether that chunk
305 /// directly specifies the return type of a function and, if so, find
306 /// an appropriate place for it.
308 /// \param i - a notional index which the search will start
309 /// immediately inside
310 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
312 assert(i <= declarator.getNumTypeObjects());
314 DeclaratorChunk *result = nullptr;
316 // First, look inwards past parens for a function declarator.
317 for (; i != 0; --i) {
318 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
319 switch (fnChunk.Kind) {
320 case DeclaratorChunk::Paren:
323 // If we find anything except a function, bail out.
324 case DeclaratorChunk::Pointer:
325 case DeclaratorChunk::BlockPointer:
326 case DeclaratorChunk::Array:
327 case DeclaratorChunk::Reference:
328 case DeclaratorChunk::MemberPointer:
331 // If we do find a function declarator, scan inwards from that,
332 // looking for a block-pointer declarator.
333 case DeclaratorChunk::Function:
334 for (--i; i != 0; --i) {
335 DeclaratorChunk &blockChunk = declarator.getTypeObject(i-1);
336 switch (blockChunk.Kind) {
337 case DeclaratorChunk::Paren:
338 case DeclaratorChunk::Pointer:
339 case DeclaratorChunk::Array:
340 case DeclaratorChunk::Function:
341 case DeclaratorChunk::Reference:
342 case DeclaratorChunk::MemberPointer:
344 case DeclaratorChunk::BlockPointer:
345 result = &blockChunk;
348 llvm_unreachable("bad declarator chunk kind");
351 // If we run out of declarators doing that, we're done.
354 llvm_unreachable("bad declarator chunk kind");
356 // Okay, reconsider from our new point.
360 // Ran out of chunks, bail out.
364 /// Given that an objc_gc attribute was written somewhere on a
365 /// declaration *other* than on the declarator itself (for which, use
366 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
367 /// didn't apply in whatever position it was written in, try to move
368 /// it to a more appropriate position.
369 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
372 Declarator &declarator = state.getDeclarator();
374 // Move it to the outermost normal or block pointer declarator.
375 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
376 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
377 switch (chunk.Kind) {
378 case DeclaratorChunk::Pointer:
379 case DeclaratorChunk::BlockPointer: {
380 // But don't move an ARC ownership attribute to the return type
382 DeclaratorChunk *destChunk = nullptr;
383 if (state.isProcessingDeclSpec() &&
384 attr.getKind() == AttributeList::AT_ObjCOwnership)
385 destChunk = maybeMovePastReturnType(declarator, i - 1);
386 if (!destChunk) destChunk = &chunk;
388 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
389 destChunk->getAttrListRef());
393 case DeclaratorChunk::Paren:
394 case DeclaratorChunk::Array:
397 // We may be starting at the return type of a block.
398 case DeclaratorChunk::Function:
399 if (state.isProcessingDeclSpec() &&
400 attr.getKind() == AttributeList::AT_ObjCOwnership) {
401 if (DeclaratorChunk *dest = maybeMovePastReturnType(declarator, i)) {
402 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
403 dest->getAttrListRef());
409 // Don't walk through these.
410 case DeclaratorChunk::Reference:
411 case DeclaratorChunk::MemberPointer:
417 diagnoseBadTypeAttribute(state.getSema(), attr, type);
420 /// Distribute an objc_gc type attribute that was written on the
423 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
425 QualType &declSpecType) {
426 Declarator &declarator = state.getDeclarator();
428 // objc_gc goes on the innermost pointer to something that's not a
430 unsigned innermost = -1U;
431 bool considerDeclSpec = true;
432 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
433 DeclaratorChunk &chunk = declarator.getTypeObject(i);
434 switch (chunk.Kind) {
435 case DeclaratorChunk::Pointer:
436 case DeclaratorChunk::BlockPointer:
440 case DeclaratorChunk::Reference:
441 case DeclaratorChunk::MemberPointer:
442 case DeclaratorChunk::Paren:
443 case DeclaratorChunk::Array:
446 case DeclaratorChunk::Function:
447 considerDeclSpec = false;
453 // That might actually be the decl spec if we weren't blocked by
454 // anything in the declarator.
455 if (considerDeclSpec) {
456 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
457 // Splice the attribute into the decl spec. Prevents the
458 // attribute from being applied multiple times and gives
459 // the source-location-filler something to work with.
460 state.saveDeclSpecAttrs();
461 moveAttrFromListToList(attr, declarator.getAttrListRef(),
462 declarator.getMutableDeclSpec().getAttributes().getListRef());
467 // Otherwise, if we found an appropriate chunk, splice the attribute
469 if (innermost != -1U) {
470 moveAttrFromListToList(attr, declarator.getAttrListRef(),
471 declarator.getTypeObject(innermost).getAttrListRef());
475 // Otherwise, diagnose when we're done building the type.
476 spliceAttrOutOfList(attr, declarator.getAttrListRef());
477 state.addIgnoredTypeAttr(attr);
480 /// A function type attribute was written somewhere in a declaration
481 /// *other* than on the declarator itself or in the decl spec. Given
482 /// that it didn't apply in whatever position it was written in, try
483 /// to move it to a more appropriate position.
484 static void distributeFunctionTypeAttr(TypeProcessingState &state,
487 Declarator &declarator = state.getDeclarator();
489 // Try to push the attribute from the return type of a function to
490 // the function itself.
491 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
492 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
493 switch (chunk.Kind) {
494 case DeclaratorChunk::Function:
495 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
496 chunk.getAttrListRef());
499 case DeclaratorChunk::Paren:
500 case DeclaratorChunk::Pointer:
501 case DeclaratorChunk::BlockPointer:
502 case DeclaratorChunk::Array:
503 case DeclaratorChunk::Reference:
504 case DeclaratorChunk::MemberPointer:
509 diagnoseBadTypeAttribute(state.getSema(), attr, type);
512 /// Try to distribute a function type attribute to the innermost
513 /// function chunk or type. Returns true if the attribute was
514 /// distributed, false if no location was found.
516 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
518 AttributeList *&attrList,
519 QualType &declSpecType) {
520 Declarator &declarator = state.getDeclarator();
522 // Put it on the innermost function chunk, if there is one.
523 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
524 DeclaratorChunk &chunk = declarator.getTypeObject(i);
525 if (chunk.Kind != DeclaratorChunk::Function) continue;
527 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
531 return handleFunctionTypeAttr(state, attr, declSpecType);
534 /// A function type attribute was written in the decl spec. Try to
535 /// apply it somewhere.
537 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
539 QualType &declSpecType) {
540 state.saveDeclSpecAttrs();
542 // C++11 attributes before the decl specifiers actually appertain to
543 // the declarators. Move them straight there. We don't support the
544 // 'put them wherever you like' semantics we allow for GNU attributes.
545 if (attr.isCXX11Attribute()) {
546 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
547 state.getDeclarator().getAttrListRef());
551 // Try to distribute to the innermost.
552 if (distributeFunctionTypeAttrToInnermost(state, attr,
553 state.getCurrentAttrListRef(),
557 // If that failed, diagnose the bad attribute when the declarator is
559 state.addIgnoredTypeAttr(attr);
562 /// A function type attribute was written on the declarator. Try to
563 /// apply it somewhere.
565 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
567 QualType &declSpecType) {
568 Declarator &declarator = state.getDeclarator();
570 // Try to distribute to the innermost.
571 if (distributeFunctionTypeAttrToInnermost(state, attr,
572 declarator.getAttrListRef(),
576 // If that failed, diagnose the bad attribute when the declarator is
578 spliceAttrOutOfList(attr, declarator.getAttrListRef());
579 state.addIgnoredTypeAttr(attr);
582 /// \brief Given that there are attributes written on the declarator
583 /// itself, try to distribute any type attributes to the appropriate
584 /// declarator chunk.
586 /// These are attributes like the following:
589 /// but not necessarily this:
591 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
592 QualType &declSpecType) {
593 // Collect all the type attributes from the declarator itself.
594 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
595 AttributeList *attr = state.getDeclarator().getAttributes();
598 next = attr->getNext();
600 // Do not distribute C++11 attributes. They have strict rules for what
601 // they appertain to.
602 if (attr->isCXX11Attribute())
605 switch (attr->getKind()) {
606 OBJC_POINTER_TYPE_ATTRS_CASELIST:
607 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
610 case AttributeList::AT_NSReturnsRetained:
611 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
615 FUNCTION_TYPE_ATTRS_CASELIST:
616 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
619 MS_TYPE_ATTRS_CASELIST:
620 // Microsoft type attributes cannot go after the declarator-id.
626 } while ((attr = next));
629 /// Add a synthetic '()' to a block-literal declarator if it is
630 /// required, given the return type.
631 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
632 QualType declSpecType) {
633 Declarator &declarator = state.getDeclarator();
635 // First, check whether the declarator would produce a function,
636 // i.e. whether the innermost semantic chunk is a function.
637 if (declarator.isFunctionDeclarator()) {
638 // If so, make that declarator a prototyped declarator.
639 declarator.getFunctionTypeInfo().hasPrototype = true;
643 // If there are any type objects, the type as written won't name a
644 // function, regardless of the decl spec type. This is because a
645 // block signature declarator is always an abstract-declarator, and
646 // abstract-declarators can't just be parentheses chunks. Therefore
647 // we need to build a function chunk unless there are no type
648 // objects and the decl spec type is a function.
649 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
652 // Note that there *are* cases with invalid declarators where
653 // declarators consist solely of parentheses. In general, these
654 // occur only in failed efforts to make function declarators, so
655 // faking up the function chunk is still the right thing to do.
657 // Otherwise, we need to fake up a function declarator.
658 SourceLocation loc = declarator.getLocStart();
660 // ...and *prepend* it to the declarator.
661 SourceLocation NoLoc;
662 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
664 /*IsAmbiguous=*/false,
668 /*EllipsisLoc=*/NoLoc,
671 /*RefQualifierIsLvalueRef=*/true,
672 /*RefQualifierLoc=*/NoLoc,
673 /*ConstQualifierLoc=*/NoLoc,
674 /*VolatileQualifierLoc=*/NoLoc,
675 /*MutableLoc=*/NoLoc,
678 /*Exceptions=*/nullptr,
679 /*ExceptionRanges=*/nullptr,
681 /*NoexceptExpr=*/nullptr,
682 loc, loc, declarator));
684 // For consistency, make sure the state still has us as processing
686 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
687 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
690 /// \brief Convert the specified declspec to the appropriate type
692 /// \param state Specifies the declarator containing the declaration specifier
693 /// to be converted, along with other associated processing state.
694 /// \returns The type described by the declaration specifiers. This function
695 /// never returns null.
696 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
697 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
700 Sema &S = state.getSema();
701 Declarator &declarator = state.getDeclarator();
702 const DeclSpec &DS = declarator.getDeclSpec();
703 SourceLocation DeclLoc = declarator.getIdentifierLoc();
704 if (DeclLoc.isInvalid())
705 DeclLoc = DS.getLocStart();
707 ASTContext &Context = S.Context;
710 switch (DS.getTypeSpecType()) {
711 case DeclSpec::TST_void:
712 Result = Context.VoidTy;
714 case DeclSpec::TST_char:
715 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
716 Result = Context.CharTy;
717 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
718 Result = Context.SignedCharTy;
720 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
721 "Unknown TSS value");
722 Result = Context.UnsignedCharTy;
725 case DeclSpec::TST_wchar:
726 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
727 Result = Context.WCharTy;
728 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
729 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
730 << DS.getSpecifierName(DS.getTypeSpecType(),
731 Context.getPrintingPolicy());
732 Result = Context.getSignedWCharType();
734 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
735 "Unknown TSS value");
736 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
737 << DS.getSpecifierName(DS.getTypeSpecType(),
738 Context.getPrintingPolicy());
739 Result = Context.getUnsignedWCharType();
742 case DeclSpec::TST_char16:
743 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
744 "Unknown TSS value");
745 Result = Context.Char16Ty;
747 case DeclSpec::TST_char32:
748 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
749 "Unknown TSS value");
750 Result = Context.Char32Ty;
752 case DeclSpec::TST_unspecified:
753 // "<proto1,proto2>" is an objc qualified ID with a missing id.
754 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
755 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
756 (ObjCProtocolDecl*const*)PQ,
757 DS.getNumProtocolQualifiers());
758 Result = Context.getObjCObjectPointerType(Result);
762 // If this is a missing declspec in a block literal return context, then it
763 // is inferred from the return statements inside the block.
764 // The declspec is always missing in a lambda expr context; it is either
765 // specified with a trailing return type or inferred.
766 if (S.getLangOpts().CPlusPlus1y &&
767 declarator.getContext() == Declarator::LambdaExprContext) {
768 // In C++1y, a lambda's implicit return type is 'auto'.
769 Result = Context.getAutoDeductType();
771 } else if (declarator.getContext() == Declarator::LambdaExprContext ||
772 isOmittedBlockReturnType(declarator)) {
773 Result = Context.DependentTy;
777 // Unspecified typespec defaults to int in C90. However, the C90 grammar
778 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
779 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
780 // Note that the one exception to this is function definitions, which are
781 // allowed to be completely missing a declspec. This is handled in the
782 // parser already though by it pretending to have seen an 'int' in this
784 if (S.getLangOpts().ImplicitInt) {
785 // In C89 mode, we only warn if there is a completely missing declspec
786 // when one is not allowed.
788 S.Diag(DeclLoc, diag::ext_missing_declspec)
789 << DS.getSourceRange()
790 << FixItHint::CreateInsertion(DS.getLocStart(), "int");
792 } else if (!DS.hasTypeSpecifier()) {
793 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
794 // "At least one type specifier shall be given in the declaration
795 // specifiers in each declaration, and in the specifier-qualifier list in
796 // each struct declaration and type name."
797 if (S.getLangOpts().CPlusPlus) {
798 S.Diag(DeclLoc, diag::err_missing_type_specifier)
799 << DS.getSourceRange();
801 // When this occurs in C++ code, often something is very broken with the
802 // value being declared, poison it as invalid so we don't get chains of
804 declarator.setInvalidType(true);
806 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
807 << DS.getSourceRange();
812 case DeclSpec::TST_int: {
813 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
814 switch (DS.getTypeSpecWidth()) {
815 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
816 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
817 case DeclSpec::TSW_long: Result = Context.LongTy; break;
818 case DeclSpec::TSW_longlong:
819 Result = Context.LongLongTy;
821 // 'long long' is a C99 or C++11 feature.
822 if (!S.getLangOpts().C99) {
823 if (S.getLangOpts().CPlusPlus)
824 S.Diag(DS.getTypeSpecWidthLoc(),
825 S.getLangOpts().CPlusPlus11 ?
826 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
828 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
833 switch (DS.getTypeSpecWidth()) {
834 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
835 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
836 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
837 case DeclSpec::TSW_longlong:
838 Result = Context.UnsignedLongLongTy;
840 // 'long long' is a C99 or C++11 feature.
841 if (!S.getLangOpts().C99) {
842 if (S.getLangOpts().CPlusPlus)
843 S.Diag(DS.getTypeSpecWidthLoc(),
844 S.getLangOpts().CPlusPlus11 ?
845 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
847 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
854 case DeclSpec::TST_int128:
855 if (!S.Context.getTargetInfo().hasInt128Type())
856 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported);
857 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
858 Result = Context.UnsignedInt128Ty;
860 Result = Context.Int128Ty;
862 case DeclSpec::TST_half: Result = Context.HalfTy; break;
863 case DeclSpec::TST_float: Result = Context.FloatTy; break;
864 case DeclSpec::TST_double:
865 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
866 Result = Context.LongDoubleTy;
868 Result = Context.DoubleTy;
870 if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
871 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
872 declarator.setInvalidType(true);
875 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
876 case DeclSpec::TST_decimal32: // _Decimal32
877 case DeclSpec::TST_decimal64: // _Decimal64
878 case DeclSpec::TST_decimal128: // _Decimal128
879 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
880 Result = Context.IntTy;
881 declarator.setInvalidType(true);
883 case DeclSpec::TST_class:
884 case DeclSpec::TST_enum:
885 case DeclSpec::TST_union:
886 case DeclSpec::TST_struct:
887 case DeclSpec::TST_interface: {
888 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
890 // This can happen in C++ with ambiguous lookups.
891 Result = Context.IntTy;
892 declarator.setInvalidType(true);
896 // If the type is deprecated or unavailable, diagnose it.
897 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
899 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
900 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
902 // TypeQuals handled by caller.
903 Result = Context.getTypeDeclType(D);
905 // In both C and C++, make an ElaboratedType.
906 ElaboratedTypeKeyword Keyword
907 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
908 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
911 case DeclSpec::TST_typename: {
912 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
913 DS.getTypeSpecSign() == 0 &&
914 "Can't handle qualifiers on typedef names yet!");
915 Result = S.GetTypeFromParser(DS.getRepAsType());
917 declarator.setInvalidType(true);
918 else if (DeclSpec::ProtocolQualifierListTy PQ
919 = DS.getProtocolQualifiers()) {
920 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
921 // Silently drop any existing protocol qualifiers.
922 // TODO: determine whether that's the right thing to do.
923 if (ObjT->getNumProtocols())
924 Result = ObjT->getBaseType();
926 if (DS.getNumProtocolQualifiers())
927 Result = Context.getObjCObjectType(Result,
928 (ObjCProtocolDecl*const*) PQ,
929 DS.getNumProtocolQualifiers());
930 } else if (Result->isObjCIdType()) {
932 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
933 (ObjCProtocolDecl*const*) PQ,
934 DS.getNumProtocolQualifiers());
935 Result = Context.getObjCObjectPointerType(Result);
936 } else if (Result->isObjCClassType()) {
937 // Class<protocol-list>
938 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
939 (ObjCProtocolDecl*const*) PQ,
940 DS.getNumProtocolQualifiers());
941 Result = Context.getObjCObjectPointerType(Result);
943 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
944 << DS.getSourceRange();
945 declarator.setInvalidType(true);
949 // TypeQuals handled by caller.
952 case DeclSpec::TST_typeofType:
953 // FIXME: Preserve type source info.
954 Result = S.GetTypeFromParser(DS.getRepAsType());
955 assert(!Result.isNull() && "Didn't get a type for typeof?");
956 if (!Result->isDependentType())
957 if (const TagType *TT = Result->getAs<TagType>())
958 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
959 // TypeQuals handled by caller.
960 Result = Context.getTypeOfType(Result);
962 case DeclSpec::TST_typeofExpr: {
963 Expr *E = DS.getRepAsExpr();
964 assert(E && "Didn't get an expression for typeof?");
965 // TypeQuals handled by caller.
966 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
967 if (Result.isNull()) {
968 Result = Context.IntTy;
969 declarator.setInvalidType(true);
973 case DeclSpec::TST_decltype: {
974 Expr *E = DS.getRepAsExpr();
975 assert(E && "Didn't get an expression for decltype?");
976 // TypeQuals handled by caller.
977 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
978 if (Result.isNull()) {
979 Result = Context.IntTy;
980 declarator.setInvalidType(true);
984 case DeclSpec::TST_underlyingType:
985 Result = S.GetTypeFromParser(DS.getRepAsType());
986 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
987 Result = S.BuildUnaryTransformType(Result,
988 UnaryTransformType::EnumUnderlyingType,
989 DS.getTypeSpecTypeLoc());
990 if (Result.isNull()) {
991 Result = Context.IntTy;
992 declarator.setInvalidType(true);
996 case DeclSpec::TST_auto:
997 // TypeQuals handled by caller.
998 // If auto is mentioned in a lambda parameter context, convert it to a
999 // template parameter type immediately, with the appropriate depth and
1000 // index, and update sema's state (LambdaScopeInfo) for the current lambda
1001 // being analyzed (which tracks the invented type template parameter).
1002 if (declarator.getContext() == Declarator::LambdaExprParameterContext) {
1003 sema::LambdaScopeInfo *LSI = S.getCurLambda();
1004 assert(LSI && "No LambdaScopeInfo on the stack!");
1005 const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
1006 const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
1007 const bool IsParameterPack = declarator.hasEllipsis();
1009 // Create a name for the invented template parameter type.
1010 std::string InventedTemplateParamName = "$auto-";
1011 llvm::raw_string_ostream ss(InventedTemplateParamName);
1012 ss << TemplateParameterDepth;
1013 ss << "-" << AutoParameterPosition;
1016 IdentifierInfo& TemplateParamII = Context.Idents.get(
1017 InventedTemplateParamName.c_str());
1018 // Turns out we must create the TemplateTypeParmDecl here to
1019 // retrieve the corresponding template parameter type.
1020 TemplateTypeParmDecl *CorrespondingTemplateParam =
1021 TemplateTypeParmDecl::Create(Context,
1022 // Temporarily add to the TranslationUnit DeclContext. When the
1023 // associated TemplateParameterList is attached to a template
1024 // declaration (such as FunctionTemplateDecl), the DeclContext
1025 // for each template parameter gets updated appropriately via
1026 // a call to AdoptTemplateParameterList.
1027 Context.getTranslationUnitDecl(),
1028 /*KeyLoc*/ SourceLocation(),
1029 /*NameLoc*/ declarator.getLocStart(),
1030 TemplateParameterDepth,
1031 AutoParameterPosition, // our template param index
1032 /* Identifier*/ &TemplateParamII, false, IsParameterPack);
1033 LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
1034 // Replace the 'auto' in the function parameter with this invented
1035 // template type parameter.
1036 Result = QualType(CorrespondingTemplateParam->getTypeForDecl(), 0);
1038 Result = Context.getAutoType(QualType(), /*decltype(auto)*/false, false);
1042 case DeclSpec::TST_decltype_auto:
1043 Result = Context.getAutoType(QualType(),
1044 /*decltype(auto)*/true,
1045 /*IsDependent*/ false);
1048 case DeclSpec::TST_unknown_anytype:
1049 Result = Context.UnknownAnyTy;
1052 case DeclSpec::TST_atomic:
1053 Result = S.GetTypeFromParser(DS.getRepAsType());
1054 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1055 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1056 if (Result.isNull()) {
1057 Result = Context.IntTy;
1058 declarator.setInvalidType(true);
1062 case DeclSpec::TST_error:
1063 Result = Context.IntTy;
1064 declarator.setInvalidType(true);
1068 // Handle complex types.
1069 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1070 if (S.getLangOpts().Freestanding)
1071 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1072 Result = Context.getComplexType(Result);
1073 } else if (DS.isTypeAltiVecVector()) {
1074 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1075 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1076 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1077 if (DS.isTypeAltiVecPixel())
1078 VecKind = VectorType::AltiVecPixel;
1079 else if (DS.isTypeAltiVecBool())
1080 VecKind = VectorType::AltiVecBool;
1081 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1084 // FIXME: Imaginary.
1085 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1086 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1088 // Before we process any type attributes, synthesize a block literal
1089 // function declarator if necessary.
1090 if (declarator.getContext() == Declarator::BlockLiteralContext)
1091 maybeSynthesizeBlockSignature(state, Result);
1093 // Apply any type attributes from the decl spec. This may cause the
1094 // list of type attributes to be temporarily saved while the type
1095 // attributes are pushed around.
1096 if (AttributeList *attrs = DS.getAttributes().getList())
1097 processTypeAttrs(state, Result, TAL_DeclSpec, attrs);
1099 // Apply const/volatile/restrict qualifiers to T.
1100 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1102 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
1103 // of a function type includes any type qualifiers, the behavior is
1105 if (Result->isFunctionType() && TypeQuals) {
1106 if (TypeQuals & DeclSpec::TQ_const)
1107 S.Diag(DS.getConstSpecLoc(), diag::warn_typecheck_function_qualifiers)
1108 << Result << DS.getSourceRange();
1109 else if (TypeQuals & DeclSpec::TQ_volatile)
1110 S.Diag(DS.getVolatileSpecLoc(), diag::warn_typecheck_function_qualifiers)
1111 << Result << DS.getSourceRange();
1113 assert((TypeQuals & (DeclSpec::TQ_restrict | DeclSpec::TQ_atomic)) &&
1114 "Has CVRA quals but not C, V, R, or A?");
1115 // No diagnostic; we'll diagnose 'restrict' or '_Atomic' applied to a
1116 // function type later, in BuildQualifiedType.
1120 // C++11 [dcl.ref]p1:
1121 // Cv-qualified references are ill-formed except when the
1122 // cv-qualifiers are introduced through the use of a typedef-name
1123 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1125 // There don't appear to be any other contexts in which a cv-qualified
1126 // reference type could be formed, so the 'ill-formed' clause here appears
1128 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
1129 TypeQuals && Result->isReferenceType()) {
1130 // If this occurs outside a template instantiation, warn the user about
1131 // it; they probably didn't mean to specify a redundant qualifier.
1132 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
1134 QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
1135 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
1136 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())
1138 for (unsigned I = 0, N = llvm::array_lengthof(Quals); I != N; ++I) {
1139 if (S.ActiveTemplateInstantiations.empty()) {
1140 if (TypeQuals & Quals[I].first)
1141 S.Diag(Quals[I].second, diag::warn_typecheck_reference_qualifiers)
1142 << DeclSpec::getSpecifierName(Quals[I].first) << Result
1143 << FixItHint::CreateRemoval(Quals[I].second);
1145 TypeQuals &= ~Quals[I].first;
1149 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1150 // than once in the same specifier-list or qualifier-list, either directly
1151 // or via one or more typedefs."
1152 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1153 && TypeQuals & Result.getCVRQualifiers()) {
1154 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1155 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1159 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1160 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1164 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1165 // produce a warning in this case.
1168 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1170 // If adding qualifiers fails, just use the unqualified type.
1171 if (Qualified.isNull())
1172 declarator.setInvalidType(true);
1180 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1182 return Entity.getAsString();
1187 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1188 Qualifiers Qs, const DeclSpec *DS) {
1189 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1190 // object or incomplete types shall not be restrict-qualified."
1191 if (Qs.hasRestrict()) {
1192 unsigned DiagID = 0;
1195 if (T->isAnyPointerType() || T->isReferenceType() ||
1196 T->isMemberPointerType()) {
1198 if (T->isObjCObjectPointerType())
1200 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1201 EltTy = PTy->getPointeeType();
1203 EltTy = T->getPointeeType();
1205 // If we have a pointer or reference, the pointee must have an object
1207 if (!EltTy->isIncompleteOrObjectType()) {
1208 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1211 } else if (!T->isDependentType()) {
1212 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1217 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1218 Qs.removeRestrict();
1222 return Context.getQualifiedType(T, Qs);
1225 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1226 unsigned CVRA, const DeclSpec *DS) {
1227 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic.
1228 unsigned CVR = CVRA & ~DeclSpec::TQ_atomic;
1231 // If the same qualifier appears more than once in the same
1232 // specifier-qualifier-list, either directly or via one or more typedefs,
1233 // the behavior is the same as if it appeared only once.
1235 // It's not specified what happens when the _Atomic qualifier is applied to
1236 // a type specified with the _Atomic specifier, but we assume that this
1237 // should be treated as if the _Atomic qualifier appeared multiple times.
1238 if (CVRA & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1240 // If other qualifiers appear along with the _Atomic qualifier in a
1241 // specifier-qualifier-list, the resulting type is the so-qualified
1244 // Don't need to worry about array types here, since _Atomic can't be
1245 // applied to such types.
1246 SplitQualType Split = T.getSplitUnqualifiedType();
1247 T = BuildAtomicType(QualType(Split.Ty, 0),
1248 DS ? DS->getAtomicSpecLoc() : Loc);
1251 Split.Quals.addCVRQualifiers(CVR);
1252 return BuildQualifiedType(T, Loc, Split.Quals);
1255 return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR), DS);
1258 /// \brief Build a paren type including \p T.
1259 QualType Sema::BuildParenType(QualType T) {
1260 return Context.getParenType(T);
1263 /// Given that we're building a pointer or reference to the given
1264 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1267 // Bail out if retention is unrequired or already specified.
1268 if (!type->isObjCLifetimeType() ||
1269 type.getObjCLifetime() != Qualifiers::OCL_None)
1272 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1274 // If the object type is const-qualified, we can safely use
1275 // __unsafe_unretained. This is safe (because there are no read
1276 // barriers), and it'll be safe to coerce anything but __weak* to
1277 // the resulting type.
1278 if (type.isConstQualified()) {
1279 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1281 // Otherwise, check whether the static type does not require
1282 // retaining. This currently only triggers for Class (possibly
1283 // protocol-qualifed, and arrays thereof).
1284 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1285 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1287 // If we are in an unevaluated context, like sizeof, skip adding a
1289 } else if (S.isUnevaluatedContext()) {
1292 // If that failed, give an error and recover using __strong. __strong
1293 // is the option most likely to prevent spurious second-order diagnostics,
1294 // like when binding a reference to a field.
1296 // These types can show up in private ivars in system headers, so
1297 // we need this to not be an error in those cases. Instead we
1299 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1300 S.DelayedDiagnostics.add(
1301 sema::DelayedDiagnostic::makeForbiddenType(loc,
1302 diag::err_arc_indirect_no_ownership, type, isReference));
1304 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1306 implicitLifetime = Qualifiers::OCL_Strong;
1308 assert(implicitLifetime && "didn't infer any lifetime!");
1311 qs.addObjCLifetime(implicitLifetime);
1312 return S.Context.getQualifiedType(type, qs);
1315 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1317 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1319 switch (FnTy->getRefQualifier()) {
1340 /// Kinds of declarator that cannot contain a qualified function type.
1342 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1343 /// a function type with a cv-qualifier or a ref-qualifier can only appear
1344 /// at the topmost level of a type.
1346 /// Parens and member pointers are permitted. We don't diagnose array and
1347 /// function declarators, because they don't allow function types at all.
1349 /// The values of this enum are used in diagnostics.
1350 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1353 /// Check whether the type T is a qualified function type, and if it is,
1354 /// diagnose that it cannot be contained within the given kind of declarator.
1355 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
1356 QualifiedFunctionKind QFK) {
1357 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1358 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1359 if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None))
1362 S.Diag(Loc, diag::err_compound_qualified_function_type)
1363 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1364 << getFunctionQualifiersAsString(FPT);
1368 /// \brief Build a pointer type.
1370 /// \param T The type to which we'll be building a pointer.
1372 /// \param Loc The location of the entity whose type involves this
1373 /// pointer type or, if there is no such entity, the location of the
1374 /// type that will have pointer type.
1376 /// \param Entity The name of the entity that involves the pointer
1379 /// \returns A suitable pointer type, if there are no
1380 /// errors. Otherwise, returns a NULL type.
1381 QualType Sema::BuildPointerType(QualType T,
1382 SourceLocation Loc, DeclarationName Entity) {
1383 if (T->isReferenceType()) {
1384 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1385 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1386 << getPrintableNameForEntity(Entity) << T;
1390 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1393 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1395 // In ARC, it is forbidden to build pointers to unqualified pointers.
1396 if (getLangOpts().ObjCAutoRefCount)
1397 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1399 // Build the pointer type.
1400 return Context.getPointerType(T);
1403 /// \brief Build a reference type.
1405 /// \param T The type to which we'll be building a reference.
1407 /// \param Loc The location of the entity whose type involves this
1408 /// reference type or, if there is no such entity, the location of the
1409 /// type that will have reference type.
1411 /// \param Entity The name of the entity that involves the reference
1414 /// \returns A suitable reference type, if there are no
1415 /// errors. Otherwise, returns a NULL type.
1416 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1418 DeclarationName Entity) {
1419 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1420 "Unresolved overloaded function type");
1422 // C++0x [dcl.ref]p6:
1423 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1424 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1425 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1426 // the type "lvalue reference to T", while an attempt to create the type
1427 // "rvalue reference to cv TR" creates the type TR.
1428 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1430 // C++ [dcl.ref]p4: There shall be no references to references.
1432 // According to C++ DR 106, references to references are only
1433 // diagnosed when they are written directly (e.g., "int & &"),
1434 // but not when they happen via a typedef:
1436 // typedef int& intref;
1437 // typedef intref& intref2;
1439 // Parser::ParseDeclaratorInternal diagnoses the case where
1440 // references are written directly; here, we handle the
1441 // collapsing of references-to-references as described in C++0x.
1442 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1445 // A declarator that specifies the type "reference to cv void"
1447 if (T->isVoidType()) {
1448 Diag(Loc, diag::err_reference_to_void);
1452 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1455 // In ARC, it is forbidden to build references to unqualified pointers.
1456 if (getLangOpts().ObjCAutoRefCount)
1457 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1459 // Handle restrict on references.
1461 return Context.getLValueReferenceType(T, SpelledAsLValue);
1462 return Context.getRValueReferenceType(T);
1465 /// Check whether the specified array size makes the array type a VLA. If so,
1466 /// return true, if not, return the size of the array in SizeVal.
1467 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1468 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1469 // (like gnu99, but not c99) accept any evaluatable value as an extension.
1470 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1472 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
1474 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
1477 void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
1478 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
1482 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
1483 S.LangOpts.GNUMode).isInvalid();
1487 /// \brief Build an array type.
1489 /// \param T The type of each element in the array.
1491 /// \param ASM C99 array size modifier (e.g., '*', 'static').
1493 /// \param ArraySize Expression describing the size of the array.
1495 /// \param Brackets The range from the opening '[' to the closing ']'.
1497 /// \param Entity The name of the entity that involves the array
1500 /// \returns A suitable array type, if there are no errors. Otherwise,
1501 /// returns a NULL type.
1502 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1503 Expr *ArraySize, unsigned Quals,
1504 SourceRange Brackets, DeclarationName Entity) {
1506 SourceLocation Loc = Brackets.getBegin();
1507 if (getLangOpts().CPlusPlus) {
1508 // C++ [dcl.array]p1:
1509 // T is called the array element type; this type shall not be a reference
1510 // type, the (possibly cv-qualified) type void, a function type or an
1511 // abstract class type.
1513 // C++ [dcl.array]p3:
1514 // When several "array of" specifications are adjacent, [...] only the
1515 // first of the constant expressions that specify the bounds of the arrays
1518 // Note: function types are handled in the common path with C.
1519 if (T->isReferenceType()) {
1520 Diag(Loc, diag::err_illegal_decl_array_of_references)
1521 << getPrintableNameForEntity(Entity) << T;
1525 if (T->isVoidType() || T->isIncompleteArrayType()) {
1526 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1530 if (RequireNonAbstractType(Brackets.getBegin(), T,
1531 diag::err_array_of_abstract_type))
1534 // Mentioning a member pointer type for an array type causes us to lock in
1535 // an inheritance model, even if it's inside an unused typedef.
1536 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
1537 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
1538 if (!MPTy->getClass()->isDependentType())
1539 RequireCompleteType(Loc, T, 0);
1542 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1543 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
1544 if (RequireCompleteType(Loc, T,
1545 diag::err_illegal_decl_array_incomplete_type))
1549 if (T->isFunctionType()) {
1550 Diag(Loc, diag::err_illegal_decl_array_of_functions)
1551 << getPrintableNameForEntity(Entity) << T;
1555 if (const RecordType *EltTy = T->getAs<RecordType>()) {
1556 // If the element type is a struct or union that contains a variadic
1557 // array, accept it as a GNU extension: C99 6.7.2.1p2.
1558 if (EltTy->getDecl()->hasFlexibleArrayMember())
1559 Diag(Loc, diag::ext_flexible_array_in_array) << T;
1560 } else if (T->isObjCObjectType()) {
1561 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1565 // Do placeholder conversions on the array size expression.
1566 if (ArraySize && ArraySize->hasPlaceholderType()) {
1567 ExprResult Result = CheckPlaceholderExpr(ArraySize);
1568 if (Result.isInvalid()) return QualType();
1569 ArraySize = Result.get();
1572 // Do lvalue-to-rvalue conversions on the array size expression.
1573 if (ArraySize && !ArraySize->isRValue()) {
1574 ExprResult Result = DefaultLvalueConversion(ArraySize);
1575 if (Result.isInvalid())
1578 ArraySize = Result.get();
1581 // C99 6.7.5.2p1: The size expression shall have integer type.
1582 // C++11 allows contextual conversions to such types.
1583 if (!getLangOpts().CPlusPlus11 &&
1584 ArraySize && !ArraySize->isTypeDependent() &&
1585 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1586 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1587 << ArraySize->getType() << ArraySize->getSourceRange();
1591 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
1593 if (ASM == ArrayType::Star)
1594 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
1596 T = Context.getIncompleteArrayType(T, ASM, Quals);
1597 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
1598 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
1599 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
1600 !T->isConstantSizeType()) ||
1601 isArraySizeVLA(*this, ArraySize, ConstVal)) {
1602 // Even in C++11, don't allow contextual conversions in the array bound
1604 if (getLangOpts().CPlusPlus11 &&
1605 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1606 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1607 << ArraySize->getType() << ArraySize->getSourceRange();
1611 // C99: an array with an element type that has a non-constant-size is a VLA.
1612 // C99: an array with a non-ICE size is a VLA. We accept any expression
1613 // that we can fold to a non-zero positive value as an extension.
1614 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1616 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1617 // have a value greater than zero.
1618 if (ConstVal.isSigned() && ConstVal.isNegative()) {
1620 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1621 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1623 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1624 << ArraySize->getSourceRange();
1627 if (ConstVal == 0) {
1628 // GCC accepts zero sized static arrays. We allow them when
1629 // we're not in a SFINAE context.
1630 Diag(ArraySize->getLocStart(),
1631 isSFINAEContext()? diag::err_typecheck_zero_array_size
1632 : diag::ext_typecheck_zero_array_size)
1633 << ArraySize->getSourceRange();
1635 if (ASM == ArrayType::Static) {
1636 Diag(ArraySize->getLocStart(),
1637 diag::warn_typecheck_zero_static_array_size)
1638 << ArraySize->getSourceRange();
1639 ASM = ArrayType::Normal;
1641 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1642 !T->isIncompleteType() && !T->isUndeducedType()) {
1643 // Is the array too large?
1644 unsigned ActiveSizeBits
1645 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1646 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1647 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1648 << ConstVal.toString(10)
1649 << ArraySize->getSourceRange();
1654 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
1657 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
1658 if (getLangOpts().OpenCL && T->isVariableArrayType()) {
1659 Diag(Loc, diag::err_opencl_vla);
1662 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1663 if (!getLangOpts().C99) {
1664 if (T->isVariableArrayType()) {
1665 // Prohibit the use of non-POD types in VLAs.
1666 QualType BaseT = Context.getBaseElementType(T);
1667 if (!T->isDependentType() &&
1668 !RequireCompleteType(Loc, BaseT, 0) &&
1669 !BaseT.isPODType(Context) &&
1670 !BaseT->isObjCLifetimeType()) {
1671 Diag(Loc, diag::err_vla_non_pod)
1675 // Prohibit the use of VLAs during template argument deduction.
1676 else if (isSFINAEContext()) {
1677 Diag(Loc, diag::err_vla_in_sfinae);
1680 // Just extwarn about VLAs.
1682 Diag(Loc, diag::ext_vla);
1683 } else if (ASM != ArrayType::Normal || Quals != 0)
1685 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
1686 : diag::ext_c99_array_usage) << ASM;
1689 if (T->isVariableArrayType()) {
1690 // Warn about VLAs for -Wvla.
1691 Diag(Loc, diag::warn_vla_used);
1697 /// \brief Build an ext-vector type.
1699 /// Run the required checks for the extended vector type.
1700 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
1701 SourceLocation AttrLoc) {
1702 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1703 // in conjunction with complex types (pointers, arrays, functions, etc.).
1704 if (!T->isDependentType() &&
1705 !T->isIntegerType() && !T->isRealFloatingType()) {
1706 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1710 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
1711 llvm::APSInt vecSize(32);
1712 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
1713 Diag(AttrLoc, diag::err_attribute_argument_type)
1714 << "ext_vector_type" << AANT_ArgumentIntegerConstant
1715 << ArraySize->getSourceRange();
1719 // unlike gcc's vector_size attribute, the size is specified as the
1720 // number of elements, not the number of bytes.
1721 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1723 if (vectorSize == 0) {
1724 Diag(AttrLoc, diag::err_attribute_zero_size)
1725 << ArraySize->getSourceRange();
1729 if (VectorType::isVectorSizeTooLarge(vectorSize)) {
1730 Diag(AttrLoc, diag::err_attribute_size_too_large)
1731 << ArraySize->getSourceRange();
1735 return Context.getExtVectorType(T, vectorSize);
1738 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
1741 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
1742 if (T->isArrayType() || T->isFunctionType()) {
1743 Diag(Loc, diag::err_func_returning_array_function)
1744 << T->isFunctionType() << T;
1748 // Functions cannot return half FP.
1749 if (T->isHalfType()) {
1750 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
1751 FixItHint::CreateInsertion(Loc, "*");
1755 // Methods cannot return interface types. All ObjC objects are
1756 // passed by reference.
1757 if (T->isObjCObjectType()) {
1758 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T;
1765 QualType Sema::BuildFunctionType(QualType T,
1766 MutableArrayRef<QualType> ParamTypes,
1767 SourceLocation Loc, DeclarationName Entity,
1768 const FunctionProtoType::ExtProtoInfo &EPI) {
1769 bool Invalid = false;
1771 Invalid |= CheckFunctionReturnType(T, Loc);
1773 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
1774 // FIXME: Loc is too inprecise here, should use proper locations for args.
1775 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
1776 if (ParamType->isVoidType()) {
1777 Diag(Loc, diag::err_param_with_void_type);
1779 } else if (ParamType->isHalfType()) {
1780 // Disallow half FP arguments.
1781 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
1782 FixItHint::CreateInsertion(Loc, "*");
1786 ParamTypes[Idx] = ParamType;
1792 return Context.getFunctionType(T, ParamTypes, EPI);
1795 /// \brief Build a member pointer type \c T Class::*.
1797 /// \param T the type to which the member pointer refers.
1798 /// \param Class the class type into which the member pointer points.
1799 /// \param Loc the location where this type begins
1800 /// \param Entity the name of the entity that will have this member pointer type
1802 /// \returns a member pointer type, if successful, or a NULL type if there was
1804 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
1806 DeclarationName Entity) {
1807 // Verify that we're not building a pointer to pointer to function with
1808 // exception specification.
1809 if (CheckDistantExceptionSpec(T)) {
1810 Diag(Loc, diag::err_distant_exception_spec);
1812 // FIXME: If we're doing this as part of template instantiation,
1813 // we should return immediately.
1815 // Build the type anyway, but use the canonical type so that the
1816 // exception specifiers are stripped off.
1817 T = Context.getCanonicalType(T);
1820 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
1821 // with reference type, or "cv void."
1822 if (T->isReferenceType()) {
1823 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
1824 << getPrintableNameForEntity(Entity) << T;
1828 if (T->isVoidType()) {
1829 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1830 << getPrintableNameForEntity(Entity);
1834 if (!Class->isDependentType() && !Class->isRecordType()) {
1835 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1839 // Adjust the default free function calling convention to the default method
1840 // calling convention.
1841 if (T->isFunctionType())
1842 adjustMemberFunctionCC(T, /*IsStatic=*/false);
1844 return Context.getMemberPointerType(T, Class.getTypePtr());
1847 /// \brief Build a block pointer type.
1849 /// \param T The type to which we'll be building a block pointer.
1851 /// \param Loc The source location, used for diagnostics.
1853 /// \param Entity The name of the entity that involves the block pointer
1856 /// \returns A suitable block pointer type, if there are no
1857 /// errors. Otherwise, returns a NULL type.
1858 QualType Sema::BuildBlockPointerType(QualType T,
1860 DeclarationName Entity) {
1861 if (!T->isFunctionType()) {
1862 Diag(Loc, diag::err_nonfunction_block_type);
1866 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
1869 return Context.getBlockPointerType(T);
1872 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1873 QualType QT = Ty.get();
1875 if (TInfo) *TInfo = nullptr;
1879 TypeSourceInfo *DI = nullptr;
1880 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
1881 QT = LIT->getType();
1882 DI = LIT->getTypeSourceInfo();
1885 if (TInfo) *TInfo = DI;
1889 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1890 Qualifiers::ObjCLifetime ownership,
1891 unsigned chunkIndex);
1893 /// Given that this is the declaration of a parameter under ARC,
1894 /// attempt to infer attributes and such for pointer-to-whatever
1896 static void inferARCWriteback(TypeProcessingState &state,
1897 QualType &declSpecType) {
1898 Sema &S = state.getSema();
1899 Declarator &declarator = state.getDeclarator();
1901 // TODO: should we care about decl qualifiers?
1903 // Check whether the declarator has the expected form. We walk
1904 // from the inside out in order to make the block logic work.
1905 unsigned outermostPointerIndex = 0;
1906 bool isBlockPointer = false;
1907 unsigned numPointers = 0;
1908 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1909 unsigned chunkIndex = i;
1910 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1911 switch (chunk.Kind) {
1912 case DeclaratorChunk::Paren:
1916 case DeclaratorChunk::Reference:
1917 case DeclaratorChunk::Pointer:
1918 // Count the number of pointers. Treat references
1919 // interchangeably as pointers; if they're mis-ordered, normal
1920 // type building will discover that.
1921 outermostPointerIndex = chunkIndex;
1925 case DeclaratorChunk::BlockPointer:
1926 // If we have a pointer to block pointer, that's an acceptable
1927 // indirect reference; anything else is not an application of
1929 if (numPointers != 1) return;
1931 outermostPointerIndex = chunkIndex;
1932 isBlockPointer = true;
1934 // We don't care about pointer structure in return values here.
1937 case DeclaratorChunk::Array: // suppress if written (id[])?
1938 case DeclaratorChunk::Function:
1939 case DeclaratorChunk::MemberPointer:
1945 // If we have *one* pointer, then we want to throw the qualifier on
1946 // the declaration-specifiers, which means that it needs to be a
1947 // retainable object type.
1948 if (numPointers == 1) {
1949 // If it's not a retainable object type, the rule doesn't apply.
1950 if (!declSpecType->isObjCRetainableType()) return;
1952 // If it already has lifetime, don't do anything.
1953 if (declSpecType.getObjCLifetime()) return;
1955 // Otherwise, modify the type in-place.
1958 if (declSpecType->isObjCARCImplicitlyUnretainedType())
1959 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
1961 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
1962 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
1964 // If we have *two* pointers, then we want to throw the qualifier on
1965 // the outermost pointer.
1966 } else if (numPointers == 2) {
1967 // If we don't have a block pointer, we need to check whether the
1968 // declaration-specifiers gave us something that will turn into a
1969 // retainable object pointer after we slap the first pointer on it.
1970 if (!isBlockPointer && !declSpecType->isObjCObjectType())
1973 // Look for an explicit lifetime attribute there.
1974 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
1975 if (chunk.Kind != DeclaratorChunk::Pointer &&
1976 chunk.Kind != DeclaratorChunk::BlockPointer)
1978 for (const AttributeList *attr = chunk.getAttrs(); attr;
1979 attr = attr->getNext())
1980 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
1983 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
1984 outermostPointerIndex);
1986 // Any other number of pointers/references does not trigger the rule.
1989 // TODO: mark whether we did this inference?
1992 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
1993 SourceLocation FallbackLoc,
1994 SourceLocation ConstQualLoc,
1995 SourceLocation VolatileQualLoc,
1996 SourceLocation RestrictQualLoc,
1997 SourceLocation AtomicQualLoc) {
2005 } const QualKinds[4] = {
2006 { DeclSpec::TQ_const, "const", ConstQualLoc },
2007 { DeclSpec::TQ_volatile, "volatile", VolatileQualLoc },
2008 { DeclSpec::TQ_restrict, "restrict", RestrictQualLoc },
2009 { DeclSpec::TQ_atomic, "_Atomic", AtomicQualLoc }
2012 SmallString<32> QualStr;
2013 unsigned NumQuals = 0;
2015 FixItHint FixIts[4];
2017 // Build a string naming the redundant qualifiers.
2018 for (unsigned I = 0; I != 4; ++I) {
2019 if (Quals & QualKinds[I].Mask) {
2020 if (!QualStr.empty()) QualStr += ' ';
2021 QualStr += QualKinds[I].Name;
2023 // If we have a location for the qualifier, offer a fixit.
2024 SourceLocation QualLoc = QualKinds[I].Loc;
2025 if (!QualLoc.isInvalid()) {
2026 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2027 if (Loc.isInvalid() ||
2028 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2036 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2037 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2040 // Diagnose pointless type qualifiers on the return type of a function.
2041 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
2043 unsigned FunctionChunkIndex) {
2044 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2045 // FIXME: TypeSourceInfo doesn't preserve location information for
2047 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2048 RetTy.getLocalCVRQualifiers(),
2049 D.getIdentifierLoc());
2053 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2054 End = D.getNumTypeObjects();
2055 OuterChunkIndex != End; ++OuterChunkIndex) {
2056 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2057 switch (OuterChunk.Kind) {
2058 case DeclaratorChunk::Paren:
2061 case DeclaratorChunk::Pointer: {
2062 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2063 S.diagnoseIgnoredQualifiers(
2064 diag::warn_qual_return_type,
2067 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2068 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2069 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2070 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc));
2074 case DeclaratorChunk::Function:
2075 case DeclaratorChunk::BlockPointer:
2076 case DeclaratorChunk::Reference:
2077 case DeclaratorChunk::Array:
2078 case DeclaratorChunk::MemberPointer:
2079 // FIXME: We can't currently provide an accurate source location and a
2080 // fix-it hint for these.
2081 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2082 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2083 RetTy.getCVRQualifiers() | AtomicQual,
2084 D.getIdentifierLoc());
2088 llvm_unreachable("unknown declarator chunk kind");
2091 // If the qualifiers come from a conversion function type, don't diagnose
2092 // them -- they're not necessarily redundant, since such a conversion
2093 // operator can be explicitly called as "x.operator const int()".
2094 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2097 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2098 // which are present there.
2099 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2100 D.getDeclSpec().getTypeQualifiers(),
2101 D.getIdentifierLoc(),
2102 D.getDeclSpec().getConstSpecLoc(),
2103 D.getDeclSpec().getVolatileSpecLoc(),
2104 D.getDeclSpec().getRestrictSpecLoc(),
2105 D.getDeclSpec().getAtomicSpecLoc());
2108 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2109 TypeSourceInfo *&ReturnTypeInfo) {
2110 Sema &SemaRef = state.getSema();
2111 Declarator &D = state.getDeclarator();
2113 ReturnTypeInfo = nullptr;
2115 // The TagDecl owned by the DeclSpec.
2116 TagDecl *OwnedTagDecl = nullptr;
2118 bool ContainsPlaceholderType = false;
2120 switch (D.getName().getKind()) {
2121 case UnqualifiedId::IK_ImplicitSelfParam:
2122 case UnqualifiedId::IK_OperatorFunctionId:
2123 case UnqualifiedId::IK_Identifier:
2124 case UnqualifiedId::IK_LiteralOperatorId:
2125 case UnqualifiedId::IK_TemplateId:
2126 T = ConvertDeclSpecToType(state);
2127 ContainsPlaceholderType = D.getDeclSpec().containsPlaceholderType();
2129 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2130 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2131 // Owned declaration is embedded in declarator.
2132 OwnedTagDecl->setEmbeddedInDeclarator(true);
2136 case UnqualifiedId::IK_ConstructorName:
2137 case UnqualifiedId::IK_ConstructorTemplateId:
2138 case UnqualifiedId::IK_DestructorName:
2139 // Constructors and destructors don't have return types. Use
2141 T = SemaRef.Context.VoidTy;
2142 if (AttributeList *attrs = D.getDeclSpec().getAttributes().getList())
2143 processTypeAttrs(state, T, TAL_DeclSpec, attrs);
2146 case UnqualifiedId::IK_ConversionFunctionId:
2147 // The result type of a conversion function is the type that it
2149 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2151 ContainsPlaceholderType = T->getContainedAutoType();
2155 if (D.getAttributes())
2156 distributeTypeAttrsFromDeclarator(state, T);
2158 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2159 // In C++11, a function declarator using 'auto' must have a trailing return
2160 // type (this is checked later) and we can skip this. In other languages
2161 // using auto, we need to check regardless.
2162 // C++14 In generic lambdas allow 'auto' in their parameters.
2163 if (ContainsPlaceholderType &&
2164 (!SemaRef.getLangOpts().CPlusPlus11 || !D.isFunctionDeclarator())) {
2167 switch (D.getContext()) {
2168 case Declarator::KNRTypeListContext:
2169 llvm_unreachable("K&R type lists aren't allowed in C++");
2170 case Declarator::LambdaExprContext:
2171 llvm_unreachable("Can't specify a type specifier in lambda grammar");
2172 case Declarator::ObjCParameterContext:
2173 case Declarator::ObjCResultContext:
2174 case Declarator::PrototypeContext:
2177 case Declarator::LambdaExprParameterContext:
2178 if (!(SemaRef.getLangOpts().CPlusPlus1y
2179 && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto))
2182 case Declarator::MemberContext:
2183 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
2185 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2186 case TTK_Enum: llvm_unreachable("unhandled tag kind");
2187 case TTK_Struct: Error = 1; /* Struct member */ break;
2188 case TTK_Union: Error = 2; /* Union member */ break;
2189 case TTK_Class: Error = 3; /* Class member */ break;
2190 case TTK_Interface: Error = 4; /* Interface member */ break;
2193 case Declarator::CXXCatchContext:
2194 case Declarator::ObjCCatchContext:
2195 Error = 5; // Exception declaration
2197 case Declarator::TemplateParamContext:
2198 Error = 6; // Template parameter
2200 case Declarator::BlockLiteralContext:
2201 Error = 7; // Block literal
2203 case Declarator::TemplateTypeArgContext:
2204 Error = 8; // Template type argument
2206 case Declarator::AliasDeclContext:
2207 case Declarator::AliasTemplateContext:
2208 Error = 10; // Type alias
2210 case Declarator::TrailingReturnContext:
2211 if (!SemaRef.getLangOpts().CPlusPlus1y)
2212 Error = 11; // Function return type
2214 case Declarator::ConversionIdContext:
2215 if (!SemaRef.getLangOpts().CPlusPlus1y)
2216 Error = 12; // conversion-type-id
2218 case Declarator::TypeNameContext:
2219 Error = 13; // Generic
2221 case Declarator::FileContext:
2222 case Declarator::BlockContext:
2223 case Declarator::ForContext:
2224 case Declarator::ConditionContext:
2225 case Declarator::CXXNewContext:
2229 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2232 // In Objective-C it is an error to use 'auto' on a function declarator.
2233 if (D.isFunctionDeclarator())
2236 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2237 // contains a trailing return type. That is only legal at the outermost
2238 // level. Check all declarator chunks (outermost first) anyway, to give
2239 // better diagnostics.
2240 if (SemaRef.getLangOpts().CPlusPlus11 && Error != -1) {
2241 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2242 unsigned chunkIndex = e - i - 1;
2243 state.setCurrentChunkIndex(chunkIndex);
2244 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2245 if (DeclType.Kind == DeclaratorChunk::Function) {
2246 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2247 if (FTI.hasTrailingReturnType()) {
2255 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2256 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2257 AutoRange = D.getName().getSourceRange();
2260 const bool IsDeclTypeAuto =
2261 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_decltype_auto;
2262 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
2263 << IsDeclTypeAuto << Error << AutoRange;
2264 T = SemaRef.Context.IntTy;
2265 D.setInvalidType(true);
2267 SemaRef.Diag(AutoRange.getBegin(),
2268 diag::warn_cxx98_compat_auto_type_specifier)
2272 if (SemaRef.getLangOpts().CPlusPlus &&
2273 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
2274 // Check the contexts where C++ forbids the declaration of a new class
2275 // or enumeration in a type-specifier-seq.
2276 switch (D.getContext()) {
2277 case Declarator::TrailingReturnContext:
2278 // Class and enumeration definitions are syntactically not allowed in
2279 // trailing return types.
2280 llvm_unreachable("parser should not have allowed this");
2282 case Declarator::FileContext:
2283 case Declarator::MemberContext:
2284 case Declarator::BlockContext:
2285 case Declarator::ForContext:
2286 case Declarator::BlockLiteralContext:
2287 case Declarator::LambdaExprContext:
2288 // C++11 [dcl.type]p3:
2289 // A type-specifier-seq shall not define a class or enumeration unless
2290 // it appears in the type-id of an alias-declaration (7.1.3) that is not
2291 // the declaration of a template-declaration.
2292 case Declarator::AliasDeclContext:
2294 case Declarator::AliasTemplateContext:
2295 SemaRef.Diag(OwnedTagDecl->getLocation(),
2296 diag::err_type_defined_in_alias_template)
2297 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2298 D.setInvalidType(true);
2300 case Declarator::TypeNameContext:
2301 case Declarator::ConversionIdContext:
2302 case Declarator::TemplateParamContext:
2303 case Declarator::CXXNewContext:
2304 case Declarator::CXXCatchContext:
2305 case Declarator::ObjCCatchContext:
2306 case Declarator::TemplateTypeArgContext:
2307 SemaRef.Diag(OwnedTagDecl->getLocation(),
2308 diag::err_type_defined_in_type_specifier)
2309 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2310 D.setInvalidType(true);
2312 case Declarator::PrototypeContext:
2313 case Declarator::LambdaExprParameterContext:
2314 case Declarator::ObjCParameterContext:
2315 case Declarator::ObjCResultContext:
2316 case Declarator::KNRTypeListContext:
2318 // Types shall not be defined in return or parameter types.
2319 SemaRef.Diag(OwnedTagDecl->getLocation(),
2320 diag::err_type_defined_in_param_type)
2321 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2322 D.setInvalidType(true);
2324 case Declarator::ConditionContext:
2326 // The type-specifier-seq shall not contain typedef and shall not declare
2327 // a new class or enumeration.
2328 SemaRef.Diag(OwnedTagDecl->getLocation(),
2329 diag::err_type_defined_in_condition);
2330 D.setInvalidType(true);
2338 /// Produce an appropriate diagnostic for an ambiguity between a function
2339 /// declarator and a C++ direct-initializer.
2340 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
2341 DeclaratorChunk &DeclType, QualType RT) {
2342 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2343 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
2345 // If the return type is void there is no ambiguity.
2346 if (RT->isVoidType())
2349 // An initializer for a non-class type can have at most one argument.
2350 if (!RT->isRecordType() && FTI.NumParams > 1)
2353 // An initializer for a reference must have exactly one argument.
2354 if (RT->isReferenceType() && FTI.NumParams != 1)
2357 // Only warn if this declarator is declaring a function at block scope, and
2358 // doesn't have a storage class (such as 'extern') specified.
2359 if (!D.isFunctionDeclarator() ||
2360 D.getFunctionDefinitionKind() != FDK_Declaration ||
2361 !S.CurContext->isFunctionOrMethod() ||
2362 D.getDeclSpec().getStorageClassSpec()
2363 != DeclSpec::SCS_unspecified)
2366 // Inside a condition, a direct initializer is not permitted. We allow one to
2367 // be parsed in order to give better diagnostics in condition parsing.
2368 if (D.getContext() == Declarator::ConditionContext)
2371 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
2373 S.Diag(DeclType.Loc,
2374 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
2375 : diag::warn_empty_parens_are_function_decl)
2378 // If the declaration looks like:
2381 // and name lookup finds a function named 'f', then the ',' was
2382 // probably intended to be a ';'.
2383 if (!D.isFirstDeclarator() && D.getIdentifier()) {
2384 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
2385 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
2386 if (Comma.getFileID() != Name.getFileID() ||
2387 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
2388 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
2389 Sema::LookupOrdinaryName);
2390 if (S.LookupName(Result, S.getCurScope()))
2391 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
2392 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
2393 << D.getIdentifier();
2397 if (FTI.NumParams > 0) {
2398 // For a declaration with parameters, eg. "T var(T());", suggest adding
2399 // parens around the first parameter to turn the declaration into a
2400 // variable declaration.
2401 SourceRange Range = FTI.Params[0].Param->getSourceRange();
2402 SourceLocation B = Range.getBegin();
2403 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
2404 // FIXME: Maybe we should suggest adding braces instead of parens
2405 // in C++11 for classes that don't have an initializer_list constructor.
2406 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
2407 << FixItHint::CreateInsertion(B, "(")
2408 << FixItHint::CreateInsertion(E, ")");
2410 // For a declaration without parameters, eg. "T var();", suggest replacing
2411 // the parens with an initializer to turn the declaration into a variable
2413 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
2415 // Empty parens mean value-initialization, and no parens mean
2416 // default initialization. These are equivalent if the default
2417 // constructor is user-provided or if zero-initialization is a
2419 if (RD && RD->hasDefinition() &&
2420 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
2421 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
2422 << FixItHint::CreateRemoval(ParenRange);
2425 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
2426 if (Init.empty() && S.LangOpts.CPlusPlus11)
2429 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
2430 << FixItHint::CreateReplacement(ParenRange, Init);
2435 /// Helper for figuring out the default CC for a function declarator type. If
2436 /// this is the outermost chunk, then we can determine the CC from the
2437 /// declarator context. If not, then this could be either a member function
2438 /// type or normal function type.
2440 getCCForDeclaratorChunk(Sema &S, Declarator &D,
2441 const DeclaratorChunk::FunctionTypeInfo &FTI,
2442 unsigned ChunkIndex) {
2443 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
2445 bool IsCXXInstanceMethod = false;
2447 if (S.getLangOpts().CPlusPlus) {
2448 // Look inwards through parentheses to see if this chunk will form a
2449 // member pointer type or if we're the declarator. Any type attributes
2450 // between here and there will override the CC we choose here.
2451 unsigned I = ChunkIndex;
2452 bool FoundNonParen = false;
2453 while (I && !FoundNonParen) {
2455 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
2456 FoundNonParen = true;
2459 if (FoundNonParen) {
2460 // If we're not the declarator, we're a regular function type unless we're
2461 // in a member pointer.
2462 IsCXXInstanceMethod =
2463 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
2465 // We're the innermost decl chunk, so must be a function declarator.
2466 assert(D.isFunctionDeclarator());
2468 // If we're inside a record, we're declaring a method, but it could be
2469 // explicitly or implicitly static.
2470 IsCXXInstanceMethod =
2471 D.isFirstDeclarationOfMember() &&
2472 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
2473 !D.isStaticMember();
2477 return S.Context.getDefaultCallingConvention(FTI.isVariadic,
2478 IsCXXInstanceMethod);
2481 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
2482 QualType declSpecType,
2483 TypeSourceInfo *TInfo) {
2485 QualType T = declSpecType;
2486 Declarator &D = state.getDeclarator();
2487 Sema &S = state.getSema();
2488 ASTContext &Context = S.Context;
2489 const LangOptions &LangOpts = S.getLangOpts();
2491 // The name we're declaring, if any.
2492 DeclarationName Name;
2493 if (D.getIdentifier())
2494 Name = D.getIdentifier();
2496 // Does this declaration declare a typedef-name?
2497 bool IsTypedefName =
2498 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
2499 D.getContext() == Declarator::AliasDeclContext ||
2500 D.getContext() == Declarator::AliasTemplateContext;
2502 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2503 bool IsQualifiedFunction = T->isFunctionProtoType() &&
2504 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
2505 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
2507 // If T is 'decltype(auto)', the only declarators we can have are parens
2508 // and at most one function declarator if this is a function declaration.
2509 if (const AutoType *AT = T->getAs<AutoType>()) {
2510 if (AT->isDecltypeAuto()) {
2511 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
2512 unsigned Index = E - I - 1;
2513 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
2514 unsigned DiagId = diag::err_decltype_auto_compound_type;
2515 unsigned DiagKind = 0;
2516 switch (DeclChunk.Kind) {
2517 case DeclaratorChunk::Paren:
2519 case DeclaratorChunk::Function: {
2521 if (D.isFunctionDeclarationContext() &&
2522 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
2524 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
2527 case DeclaratorChunk::Pointer:
2528 case DeclaratorChunk::BlockPointer:
2529 case DeclaratorChunk::MemberPointer:
2532 case DeclaratorChunk::Reference:
2535 case DeclaratorChunk::Array:
2540 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
2541 D.setInvalidType(true);
2547 // Walk the DeclTypeInfo, building the recursive type as we go.
2548 // DeclTypeInfos are ordered from the identifier out, which is
2549 // opposite of what we want :).
2550 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2551 unsigned chunkIndex = e - i - 1;
2552 state.setCurrentChunkIndex(chunkIndex);
2553 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2554 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
2555 switch (DeclType.Kind) {
2556 case DeclaratorChunk::Paren:
2557 T = S.BuildParenType(T);
2559 case DeclaratorChunk::BlockPointer:
2560 // If blocks are disabled, emit an error.
2561 if (!LangOpts.Blocks)
2562 S.Diag(DeclType.Loc, diag::err_blocks_disable);
2564 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
2565 if (DeclType.Cls.TypeQuals)
2566 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
2568 case DeclaratorChunk::Pointer:
2569 // Verify that we're not building a pointer to pointer to function with
2570 // exception specification.
2571 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2572 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2573 D.setInvalidType(true);
2574 // Build the type anyway.
2576 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
2577 T = Context.getObjCObjectPointerType(T);
2578 if (DeclType.Ptr.TypeQuals)
2579 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
2582 T = S.BuildPointerType(T, DeclType.Loc, Name);
2583 if (DeclType.Ptr.TypeQuals)
2584 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
2587 case DeclaratorChunk::Reference: {
2588 // Verify that we're not building a reference to pointer to function with
2589 // exception specification.
2590 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2591 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2592 D.setInvalidType(true);
2593 // Build the type anyway.
2595 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
2597 if (DeclType.Ref.HasRestrict)
2598 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
2601 case DeclaratorChunk::Array: {
2602 // Verify that we're not building an array of pointers to function with
2603 // exception specification.
2604 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2605 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2606 D.setInvalidType(true);
2607 // Build the type anyway.
2609 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
2610 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
2611 ArrayType::ArraySizeModifier ASM;
2613 ASM = ArrayType::Star;
2614 else if (ATI.hasStatic)
2615 ASM = ArrayType::Static;
2617 ASM = ArrayType::Normal;
2618 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
2619 // FIXME: This check isn't quite right: it allows star in prototypes
2620 // for function definitions, and disallows some edge cases detailed
2621 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
2622 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
2623 ASM = ArrayType::Normal;
2624 D.setInvalidType(true);
2627 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
2628 // shall appear only in a declaration of a function parameter with an
2630 if (ASM == ArrayType::Static || ATI.TypeQuals) {
2631 if (!(D.isPrototypeContext() ||
2632 D.getContext() == Declarator::KNRTypeListContext)) {
2633 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
2634 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
2635 // Remove the 'static' and the type qualifiers.
2636 if (ASM == ArrayType::Static)
2637 ASM = ArrayType::Normal;
2639 D.setInvalidType(true);
2642 // C99 6.7.5.2p1: ... and then only in the outermost array type
2644 unsigned x = chunkIndex;
2646 // Walk outwards along the declarator chunks.
2648 const DeclaratorChunk &DC = D.getTypeObject(x);
2650 case DeclaratorChunk::Paren:
2652 case DeclaratorChunk::Array:
2653 case DeclaratorChunk::Pointer:
2654 case DeclaratorChunk::Reference:
2655 case DeclaratorChunk::MemberPointer:
2656 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
2657 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
2658 if (ASM == ArrayType::Static)
2659 ASM = ArrayType::Normal;
2661 D.setInvalidType(true);
2663 case DeclaratorChunk::Function:
2664 case DeclaratorChunk::BlockPointer:
2665 // These are invalid anyway, so just ignore.
2670 const AutoType *AT = T->getContainedAutoType();
2671 // Allow arrays of auto if we are a generic lambda parameter.
2672 // i.e. [](auto (&array)[5]) { return array[0]; }; OK
2673 if (AT && D.getContext() != Declarator::LambdaExprParameterContext) {
2674 // We've already diagnosed this for decltype(auto).
2675 if (!AT->isDecltypeAuto())
2676 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
2677 << getPrintableNameForEntity(Name) << T;
2682 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
2683 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
2686 case DeclaratorChunk::Function: {
2687 // If the function declarator has a prototype (i.e. it is not () and
2688 // does not have a K&R-style identifier list), then the arguments are part
2689 // of the type, otherwise the argument list is ().
2690 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2691 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
2693 // Check for auto functions and trailing return type and adjust the
2694 // return type accordingly.
2695 if (!D.isInvalidType()) {
2696 // trailing-return-type is only required if we're declaring a function,
2697 // and not, for instance, a pointer to a function.
2698 if (D.getDeclSpec().containsPlaceholderType() &&
2699 !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
2700 !S.getLangOpts().CPlusPlus1y) {
2701 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2702 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
2703 ? diag::err_auto_missing_trailing_return
2704 : diag::err_deduced_return_type);
2706 D.setInvalidType(true);
2707 } else if (FTI.hasTrailingReturnType()) {
2708 // T must be exactly 'auto' at this point. See CWG issue 681.
2709 if (isa<ParenType>(T)) {
2710 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2711 diag::err_trailing_return_in_parens)
2712 << T << D.getDeclSpec().getSourceRange();
2713 D.setInvalidType(true);
2714 } else if (D.getContext() != Declarator::LambdaExprContext &&
2715 (T.hasQualifiers() || !isa<AutoType>(T) ||
2716 cast<AutoType>(T)->isDecltypeAuto())) {
2717 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2718 diag::err_trailing_return_without_auto)
2719 << T << D.getDeclSpec().getSourceRange();
2720 D.setInvalidType(true);
2722 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
2724 // An error occurred parsing the trailing return type.
2726 D.setInvalidType(true);
2731 // C99 6.7.5.3p1: The return type may not be a function or array type.
2732 // For conversion functions, we'll diagnose this particular error later.
2733 if ((T->isArrayType() || T->isFunctionType()) &&
2734 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
2735 unsigned diagID = diag::err_func_returning_array_function;
2736 // Last processing chunk in block context means this function chunk
2737 // represents the block.
2738 if (chunkIndex == 0 &&
2739 D.getContext() == Declarator::BlockLiteralContext)
2740 diagID = diag::err_block_returning_array_function;
2741 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
2743 D.setInvalidType(true);
2746 // Do not allow returning half FP value.
2747 // FIXME: This really should be in BuildFunctionType.
2748 if (T->isHalfType()) {
2749 if (S.getLangOpts().OpenCL) {
2750 if (!S.getOpenCLOptions().cl_khr_fp16) {
2751 S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T;
2752 D.setInvalidType(true);
2755 S.Diag(D.getIdentifierLoc(),
2756 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
2757 D.setInvalidType(true);
2761 // Methods cannot return interface types. All ObjC objects are
2762 // passed by reference.
2763 if (T->isObjCObjectType()) {
2764 SourceLocation DiagLoc, FixitLoc;
2766 DiagLoc = TInfo->getTypeLoc().getLocStart();
2767 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
2769 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
2770 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
2772 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
2774 << FixItHint::CreateInsertion(FixitLoc, "*");
2776 T = Context.getObjCObjectPointerType(T);
2779 TLB.pushFullCopy(TInfo->getTypeLoc());
2780 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
2781 TLoc.setStarLoc(FixitLoc);
2782 TInfo = TLB.getTypeSourceInfo(Context, T);
2785 D.setInvalidType(true);
2788 // cv-qualifiers on return types are pointless except when the type is a
2789 // class type in C++.
2790 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
2791 !(S.getLangOpts().CPlusPlus &&
2792 (T->isDependentType() || T->isRecordType())))
2793 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
2795 // Objective-C ARC ownership qualifiers are ignored on the function
2796 // return type (by type canonicalization). Complain if this attribute
2797 // was written here.
2798 if (T.getQualifiers().hasObjCLifetime()) {
2799 SourceLocation AttrLoc;
2800 if (chunkIndex + 1 < D.getNumTypeObjects()) {
2801 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2802 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
2803 Attr; Attr = Attr->getNext()) {
2804 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
2805 AttrLoc = Attr->getLoc();
2810 if (AttrLoc.isInvalid()) {
2811 for (const AttributeList *Attr
2812 = D.getDeclSpec().getAttributes().getList();
2813 Attr; Attr = Attr->getNext()) {
2814 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
2815 AttrLoc = Attr->getLoc();
2821 if (AttrLoc.isValid()) {
2822 // The ownership attributes are almost always written via
2824 // __strong/__weak/__autoreleasing/__unsafe_unretained.
2825 if (AttrLoc.isMacroID())
2826 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
2828 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
2829 << T.getQualifiers().getObjCLifetime();
2833 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
2835 // Types shall not be defined in return or parameter types.
2836 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2837 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
2838 << Context.getTypeDeclType(Tag);
2841 // Exception specs are not allowed in typedefs. Complain, but add it
2843 if (IsTypedefName && FTI.getExceptionSpecType())
2844 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
2845 << (D.getContext() == Declarator::AliasDeclContext ||
2846 D.getContext() == Declarator::AliasTemplateContext);
2848 // If we see "T var();" or "T var(T());" at block scope, it is probably
2849 // an attempt to initialize a variable, not a function declaration.
2850 if (FTI.isAmbiguous)
2851 warnAboutAmbiguousFunction(S, D, DeclType, T);
2853 FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
2855 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) {
2856 // Simple void foo(), where the incoming T is the result type.
2857 T = Context.getFunctionNoProtoType(T, EI);
2859 // We allow a zero-parameter variadic function in C if the
2860 // function is marked with the "overloadable" attribute. Scan
2861 // for this attribute now.
2862 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
2863 bool Overloadable = false;
2864 for (const AttributeList *Attrs = D.getAttributes();
2865 Attrs; Attrs = Attrs->getNext()) {
2866 if (Attrs->getKind() == AttributeList::AT_Overloadable) {
2867 Overloadable = true;
2873 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
2876 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
2877 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
2879 S.Diag(FTI.Params[0].IdentLoc,
2880 diag::err_ident_list_in_fn_declaration);
2881 D.setInvalidType(true);
2882 // Recover by creating a K&R-style function type.
2883 T = Context.getFunctionNoProtoType(T, EI);
2887 FunctionProtoType::ExtProtoInfo EPI;
2889 EPI.Variadic = FTI.isVariadic;
2890 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
2891 EPI.TypeQuals = FTI.TypeQuals;
2892 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
2893 : FTI.RefQualifierIsLValueRef? RQ_LValue
2896 // Otherwise, we have a function with a parameter list that is
2897 // potentially variadic.
2898 SmallVector<QualType, 16> ParamTys;
2899 ParamTys.reserve(FTI.NumParams);
2901 SmallVector<bool, 16> ConsumedParameters;
2902 ConsumedParameters.reserve(FTI.NumParams);
2903 bool HasAnyConsumedParameters = false;
2905 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
2906 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
2907 QualType ParamTy = Param->getType();
2908 assert(!ParamTy.isNull() && "Couldn't parse type?");
2910 // Look for 'void'. void is allowed only as a single parameter to a
2911 // function with no other parameters (C99 6.7.5.3p10). We record
2912 // int(void) as a FunctionProtoType with an empty parameter list.
2913 if (ParamTy->isVoidType()) {
2914 // If this is something like 'float(int, void)', reject it. 'void'
2915 // is an incomplete type (C99 6.2.5p19) and function decls cannot
2916 // have parameters of incomplete type.
2917 if (FTI.NumParams != 1 || FTI.isVariadic) {
2918 S.Diag(DeclType.Loc, diag::err_void_only_param);
2919 ParamTy = Context.IntTy;
2920 Param->setType(ParamTy);
2921 } else if (FTI.Params[i].Ident) {
2922 // Reject, but continue to parse 'int(void abc)'.
2923 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
2924 ParamTy = Context.IntTy;
2925 Param->setType(ParamTy);
2927 // Reject, but continue to parse 'float(const void)'.
2928 if (ParamTy.hasQualifiers())
2929 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
2931 // Do not add 'void' to the list.
2934 } else if (ParamTy->isHalfType()) {
2935 // Disallow half FP parameters.
2936 // FIXME: This really should be in BuildFunctionType.
2937 if (S.getLangOpts().OpenCL) {
2938 if (!S.getOpenCLOptions().cl_khr_fp16) {
2939 S.Diag(Param->getLocation(),
2940 diag::err_opencl_half_param) << ParamTy;
2942 Param->setInvalidDecl();
2945 S.Diag(Param->getLocation(),
2946 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
2949 } else if (!FTI.hasPrototype) {
2950 if (ParamTy->isPromotableIntegerType()) {
2951 ParamTy = Context.getPromotedIntegerType(ParamTy);
2952 Param->setKNRPromoted(true);
2953 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
2954 if (BTy->getKind() == BuiltinType::Float) {
2955 ParamTy = Context.DoubleTy;
2956 Param->setKNRPromoted(true);
2961 if (LangOpts.ObjCAutoRefCount) {
2962 bool Consumed = Param->hasAttr<NSConsumedAttr>();
2963 ConsumedParameters.push_back(Consumed);
2964 HasAnyConsumedParameters |= Consumed;
2967 ParamTys.push_back(ParamTy);
2970 if (HasAnyConsumedParameters)
2971 EPI.ConsumedParameters = ConsumedParameters.data();
2973 SmallVector<QualType, 4> Exceptions;
2974 SmallVector<ParsedType, 2> DynamicExceptions;
2975 SmallVector<SourceRange, 2> DynamicExceptionRanges;
2976 Expr *NoexceptExpr = nullptr;
2978 if (FTI.getExceptionSpecType() == EST_Dynamic) {
2979 // FIXME: It's rather inefficient to have to split into two vectors
2981 unsigned N = FTI.NumExceptions;
2982 DynamicExceptions.reserve(N);
2983 DynamicExceptionRanges.reserve(N);
2984 for (unsigned I = 0; I != N; ++I) {
2985 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
2986 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
2988 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
2989 NoexceptExpr = FTI.NoexceptExpr;
2992 S.checkExceptionSpecification(FTI.getExceptionSpecType(),
2994 DynamicExceptionRanges,
2999 T = Context.getFunctionType(T, ParamTys, EPI);
3004 case DeclaratorChunk::MemberPointer:
3005 // The scope spec must refer to a class, or be dependent.
3006 CXXScopeSpec &SS = DeclType.Mem.Scope();
3008 if (SS.isInvalid()) {
3009 // Avoid emitting extra errors if we already errored on the scope.
3010 D.setInvalidType(true);
3011 } else if (S.isDependentScopeSpecifier(SS) ||
3012 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
3013 NestedNameSpecifier *NNS = SS.getScopeRep();
3014 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
3015 switch (NNS->getKind()) {
3016 case NestedNameSpecifier::Identifier:
3017 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
3018 NNS->getAsIdentifier());
3021 case NestedNameSpecifier::Namespace:
3022 case NestedNameSpecifier::NamespaceAlias:
3023 case NestedNameSpecifier::Global:
3024 llvm_unreachable("Nested-name-specifier must name a type");
3026 case NestedNameSpecifier::TypeSpec:
3027 case NestedNameSpecifier::TypeSpecWithTemplate:
3028 ClsType = QualType(NNS->getAsType(), 0);
3029 // Note: if the NNS has a prefix and ClsType is a nondependent
3030 // TemplateSpecializationType, then the NNS prefix is NOT included
3031 // in ClsType; hence we wrap ClsType into an ElaboratedType.
3032 // NOTE: in particular, no wrap occurs if ClsType already is an
3033 // Elaborated, DependentName, or DependentTemplateSpecialization.
3034 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
3035 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
3039 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
3040 diag::err_illegal_decl_mempointer_in_nonclass)
3041 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
3042 << DeclType.Mem.Scope().getRange();
3043 D.setInvalidType(true);
3046 if (!ClsType.isNull())
3047 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
3050 D.setInvalidType(true);
3051 } else if (DeclType.Mem.TypeQuals) {
3052 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
3058 D.setInvalidType(true);
3062 // See if there are any attributes on this declarator chunk.
3063 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
3064 processTypeAttrs(state, T, TAL_DeclChunk, attrs);
3067 if (LangOpts.CPlusPlus && T->isFunctionType()) {
3068 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
3069 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
3072 // A cv-qualifier-seq shall only be part of the function type
3073 // for a nonstatic member function, the function type to which a pointer
3074 // to member refers, or the top-level function type of a function typedef
3077 // Core issue 547 also allows cv-qualifiers on function types that are
3078 // top-level template type arguments.
3080 if (!D.getCXXScopeSpec().isSet()) {
3081 FreeFunction = ((D.getContext() != Declarator::MemberContext &&
3082 D.getContext() != Declarator::LambdaExprContext) ||
3083 D.getDeclSpec().isFriendSpecified());
3085 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
3086 FreeFunction = (DC && !DC->isRecord());
3089 // C++11 [dcl.fct]p6 (w/DR1417):
3090 // An attempt to specify a function type with a cv-qualifier-seq or a
3091 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
3092 // - the function type for a non-static member function,
3093 // - the function type to which a pointer to member refers,
3094 // - the top-level function type of a function typedef declaration or
3095 // alias-declaration,
3096 // - the type-id in the default argument of a type-parameter, or
3097 // - the type-id of a template-argument for a type-parameter
3099 // FIXME: Checking this here is insufficient. We accept-invalid on:
3101 // template<typename T> struct S { void f(T); };
3102 // S<int() const> s;
3104 // ... for instance.
3105 if (IsQualifiedFunction &&
3107 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
3109 D.getContext() != Declarator::TemplateTypeArgContext) {
3110 SourceLocation Loc = D.getLocStart();
3111 SourceRange RemovalRange;
3113 if (D.isFunctionDeclarator(I)) {
3114 SmallVector<SourceLocation, 4> RemovalLocs;
3115 const DeclaratorChunk &Chunk = D.getTypeObject(I);
3116 assert(Chunk.Kind == DeclaratorChunk::Function);
3117 if (Chunk.Fun.hasRefQualifier())
3118 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
3119 if (Chunk.Fun.TypeQuals & Qualifiers::Const)
3120 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
3121 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
3122 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
3123 // FIXME: We do not track the location of the __restrict qualifier.
3124 //if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
3125 // RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
3126 if (!RemovalLocs.empty()) {
3127 std::sort(RemovalLocs.begin(), RemovalLocs.end(),
3128 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
3129 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
3130 Loc = RemovalLocs.front();
3134 S.Diag(Loc, diag::err_invalid_qualified_function_type)
3135 << FreeFunction << D.isFunctionDeclarator() << T
3136 << getFunctionQualifiersAsString(FnTy)
3137 << FixItHint::CreateRemoval(RemovalRange);
3139 // Strip the cv-qualifiers and ref-qualifiers from the type.
3140 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
3142 EPI.RefQualifier = RQ_None;
3144 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
3146 // Rebuild any parens around the identifier in the function type.
3147 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3148 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
3150 T = S.BuildParenType(T);
3155 // Apply any undistributed attributes from the declarator.
3157 if (AttributeList *attrs = D.getAttributes())
3158 processTypeAttrs(state, T, TAL_DeclName, attrs);
3160 // Diagnose any ignored type attributes.
3161 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
3163 // C++0x [dcl.constexpr]p9:
3164 // A constexpr specifier used in an object declaration declares the object
3166 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
3170 // If there was an ellipsis in the declarator, the declaration declares a
3171 // parameter pack whose type may be a pack expansion type.
3172 if (D.hasEllipsis() && !T.isNull()) {
3173 // C++0x [dcl.fct]p13:
3174 // A declarator-id or abstract-declarator containing an ellipsis shall
3175 // only be used in a parameter-declaration. Such a parameter-declaration
3176 // is a parameter pack (14.5.3). [...]
3177 switch (D.getContext()) {
3178 case Declarator::PrototypeContext:
3179 case Declarator::LambdaExprParameterContext:
3180 // C++0x [dcl.fct]p13:
3181 // [...] When it is part of a parameter-declaration-clause, the
3182 // parameter pack is a function parameter pack (14.5.3). The type T
3183 // of the declarator-id of the function parameter pack shall contain
3184 // a template parameter pack; each template parameter pack in T is
3185 // expanded by the function parameter pack.
3187 // We represent function parameter packs as function parameters whose
3188 // type is a pack expansion.
3189 if (!T->containsUnexpandedParameterPack()) {
3190 S.Diag(D.getEllipsisLoc(),
3191 diag::err_function_parameter_pack_without_parameter_packs)
3192 << T << D.getSourceRange();
3193 D.setEllipsisLoc(SourceLocation());
3195 T = Context.getPackExpansionType(T, None);
3198 case Declarator::TemplateParamContext:
3199 // C++0x [temp.param]p15:
3200 // If a template-parameter is a [...] is a parameter-declaration that
3201 // declares a parameter pack (8.3.5), then the template-parameter is a
3202 // template parameter pack (14.5.3).
3204 // Note: core issue 778 clarifies that, if there are any unexpanded
3205 // parameter packs in the type of the non-type template parameter, then
3206 // it expands those parameter packs.
3207 if (T->containsUnexpandedParameterPack())
3208 T = Context.getPackExpansionType(T, None);
3210 S.Diag(D.getEllipsisLoc(),
3211 LangOpts.CPlusPlus11
3212 ? diag::warn_cxx98_compat_variadic_templates
3213 : diag::ext_variadic_templates);
3216 case Declarator::FileContext:
3217 case Declarator::KNRTypeListContext:
3218 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
3219 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
3220 case Declarator::TypeNameContext:
3221 case Declarator::CXXNewContext:
3222 case Declarator::AliasDeclContext:
3223 case Declarator::AliasTemplateContext:
3224 case Declarator::MemberContext:
3225 case Declarator::BlockContext:
3226 case Declarator::ForContext:
3227 case Declarator::ConditionContext:
3228 case Declarator::CXXCatchContext:
3229 case Declarator::ObjCCatchContext:
3230 case Declarator::BlockLiteralContext:
3231 case Declarator::LambdaExprContext:
3232 case Declarator::ConversionIdContext:
3233 case Declarator::TrailingReturnContext:
3234 case Declarator::TemplateTypeArgContext:
3235 // FIXME: We may want to allow parameter packs in block-literal contexts
3237 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
3238 D.setEllipsisLoc(SourceLocation());
3244 return Context.getNullTypeSourceInfo();
3245 else if (D.isInvalidType())
3246 return Context.getTrivialTypeSourceInfo(T);
3248 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
3251 /// GetTypeForDeclarator - Convert the type for the specified
3252 /// declarator to Type instances.
3254 /// The result of this call will never be null, but the associated
3255 /// type may be a null type if there's an unrecoverable error.
3256 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
3257 // Determine the type of the declarator. Not all forms of declarator
3260 TypeProcessingState state(*this, D);
3262 TypeSourceInfo *ReturnTypeInfo = nullptr;
3263 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3265 return Context.getNullTypeSourceInfo();
3267 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
3268 inferARCWriteback(state, T);
3270 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
3273 static void transferARCOwnershipToDeclSpec(Sema &S,
3274 QualType &declSpecTy,
3275 Qualifiers::ObjCLifetime ownership) {
3276 if (declSpecTy->isObjCRetainableType() &&
3277 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
3279 qs.addObjCLifetime(ownership);
3280 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
3284 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
3285 Qualifiers::ObjCLifetime ownership,
3286 unsigned chunkIndex) {
3287 Sema &S = state.getSema();
3288 Declarator &D = state.getDeclarator();
3290 // Look for an explicit lifetime attribute.
3291 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
3292 for (const AttributeList *attr = chunk.getAttrs(); attr;
3293 attr = attr->getNext())
3294 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
3297 const char *attrStr = nullptr;
3298 switch (ownership) {
3299 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
3300 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
3301 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
3302 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
3303 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
3306 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
3307 Arg->Ident = &S.Context.Idents.get(attrStr);
3308 Arg->Loc = SourceLocation();
3310 ArgsUnion Args(Arg);
3312 // If there wasn't one, add one (with an invalid source location
3313 // so that we don't make an AttributedType for it).
3314 AttributeList *attr = D.getAttributePool()
3315 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
3316 /*scope*/ nullptr, SourceLocation(),
3317 /*args*/ &Args, 1, AttributeList::AS_GNU);
3318 spliceAttrIntoList(*attr, chunk.getAttrListRef());
3320 // TODO: mark whether we did this inference?
3323 /// \brief Used for transferring ownership in casts resulting in l-values.
3324 static void transferARCOwnership(TypeProcessingState &state,
3325 QualType &declSpecTy,
3326 Qualifiers::ObjCLifetime ownership) {
3327 Sema &S = state.getSema();
3328 Declarator &D = state.getDeclarator();
3331 bool hasIndirection = false;
3332 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3333 DeclaratorChunk &chunk = D.getTypeObject(i);
3334 switch (chunk.Kind) {
3335 case DeclaratorChunk::Paren:
3339 case DeclaratorChunk::Array:
3340 case DeclaratorChunk::Reference:
3341 case DeclaratorChunk::Pointer:
3343 hasIndirection = true;
3347 case DeclaratorChunk::BlockPointer:
3349 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
3352 case DeclaratorChunk::Function:
3353 case DeclaratorChunk::MemberPointer:
3361 DeclaratorChunk &chunk = D.getTypeObject(inner);
3362 if (chunk.Kind == DeclaratorChunk::Pointer) {
3363 if (declSpecTy->isObjCRetainableType())
3364 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
3365 if (declSpecTy->isObjCObjectType() && hasIndirection)
3366 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
3368 assert(chunk.Kind == DeclaratorChunk::Array ||
3369 chunk.Kind == DeclaratorChunk::Reference);
3370 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
3374 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
3375 TypeProcessingState state(*this, D);
3377 TypeSourceInfo *ReturnTypeInfo = nullptr;
3378 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3379 if (declSpecTy.isNull())
3380 return Context.getNullTypeSourceInfo();
3382 if (getLangOpts().ObjCAutoRefCount) {
3383 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
3384 if (ownership != Qualifiers::OCL_None)
3385 transferARCOwnership(state, declSpecTy, ownership);
3388 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
3391 /// Map an AttributedType::Kind to an AttributeList::Kind.
3392 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
3394 case AttributedType::attr_address_space:
3395 return AttributeList::AT_AddressSpace;
3396 case AttributedType::attr_regparm:
3397 return AttributeList::AT_Regparm;
3398 case AttributedType::attr_vector_size:
3399 return AttributeList::AT_VectorSize;
3400 case AttributedType::attr_neon_vector_type:
3401 return AttributeList::AT_NeonVectorType;
3402 case AttributedType::attr_neon_polyvector_type:
3403 return AttributeList::AT_NeonPolyVectorType;
3404 case AttributedType::attr_objc_gc:
3405 return AttributeList::AT_ObjCGC;
3406 case AttributedType::attr_objc_ownership:
3407 return AttributeList::AT_ObjCOwnership;
3408 case AttributedType::attr_noreturn:
3409 return AttributeList::AT_NoReturn;
3410 case AttributedType::attr_cdecl:
3411 return AttributeList::AT_CDecl;
3412 case AttributedType::attr_fastcall:
3413 return AttributeList::AT_FastCall;
3414 case AttributedType::attr_stdcall:
3415 return AttributeList::AT_StdCall;
3416 case AttributedType::attr_thiscall:
3417 return AttributeList::AT_ThisCall;
3418 case AttributedType::attr_pascal:
3419 return AttributeList::AT_Pascal;
3420 case AttributedType::attr_pcs:
3421 case AttributedType::attr_pcs_vfp:
3422 return AttributeList::AT_Pcs;
3423 case AttributedType::attr_pnaclcall:
3424 return AttributeList::AT_PnaclCall;
3425 case AttributedType::attr_inteloclbicc:
3426 return AttributeList::AT_IntelOclBicc;
3427 case AttributedType::attr_ms_abi:
3428 return AttributeList::AT_MSABI;
3429 case AttributedType::attr_sysv_abi:
3430 return AttributeList::AT_SysVABI;
3431 case AttributedType::attr_ptr32:
3432 return AttributeList::AT_Ptr32;
3433 case AttributedType::attr_ptr64:
3434 return AttributeList::AT_Ptr64;
3435 case AttributedType::attr_sptr:
3436 return AttributeList::AT_SPtr;
3437 case AttributedType::attr_uptr:
3438 return AttributeList::AT_UPtr;
3440 llvm_unreachable("unexpected attribute kind!");
3443 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
3444 const AttributeList *attrs) {
3445 AttributedType::Kind kind = TL.getAttrKind();
3447 assert(attrs && "no type attributes in the expected location!");
3448 AttributeList::Kind parsedKind = getAttrListKind(kind);
3449 while (attrs->getKind() != parsedKind) {
3450 attrs = attrs->getNext();
3451 assert(attrs && "no matching attribute in expected location!");
3454 TL.setAttrNameLoc(attrs->getLoc());
3455 if (TL.hasAttrExprOperand()) {
3456 assert(attrs->isArgExpr(0) && "mismatched attribute operand kind");
3457 TL.setAttrExprOperand(attrs->getArgAsExpr(0));
3458 } else if (TL.hasAttrEnumOperand()) {
3459 assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&
3460 "unexpected attribute operand kind");
3461 if (attrs->isArgIdent(0))
3462 TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
3464 TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc());
3467 // FIXME: preserve this information to here.
3468 if (TL.hasAttrOperand())
3469 TL.setAttrOperandParensRange(SourceRange());
3473 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
3474 ASTContext &Context;
3478 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
3479 : Context(Context), DS(DS) {}
3481 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3482 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
3483 Visit(TL.getModifiedLoc());
3485 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3486 Visit(TL.getUnqualifiedLoc());
3488 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
3489 TL.setNameLoc(DS.getTypeSpecTypeLoc());
3491 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
3492 TL.setNameLoc(DS.getTypeSpecTypeLoc());
3493 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
3494 // addition field. What we have is good enough for dispay of location
3495 // of 'fixit' on interface name.
3496 TL.setNameEndLoc(DS.getLocEnd());
3498 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
3499 // Handle the base type, which might not have been written explicitly.
3500 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
3501 TL.setHasBaseTypeAsWritten(false);
3502 TL.getBaseLoc().initialize(Context, SourceLocation());
3504 TL.setHasBaseTypeAsWritten(true);
3505 Visit(TL.getBaseLoc());
3508 // Protocol qualifiers.
3509 if (DS.getProtocolQualifiers()) {
3510 assert(TL.getNumProtocols() > 0);
3511 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
3512 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
3513 TL.setRAngleLoc(DS.getSourceRange().getEnd());
3514 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
3515 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
3517 assert(TL.getNumProtocols() == 0);
3518 TL.setLAngleLoc(SourceLocation());
3519 TL.setRAngleLoc(SourceLocation());
3522 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3523 TL.setStarLoc(SourceLocation());
3524 Visit(TL.getPointeeLoc());
3526 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
3527 TypeSourceInfo *TInfo = nullptr;
3528 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3530 // If we got no declarator info from previous Sema routines,
3531 // just fill with the typespec loc.
3533 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
3537 TypeLoc OldTL = TInfo->getTypeLoc();
3538 if (TInfo->getType()->getAs<ElaboratedType>()) {
3539 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
3540 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
3541 .castAs<TemplateSpecializationTypeLoc>();
3544 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
3545 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
3549 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
3550 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
3551 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3552 TL.setParensRange(DS.getTypeofParensRange());
3554 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
3555 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
3556 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3557 TL.setParensRange(DS.getTypeofParensRange());
3558 assert(DS.getRepAsType());
3559 TypeSourceInfo *TInfo = nullptr;
3560 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3561 TL.setUnderlyingTInfo(TInfo);
3563 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
3564 // FIXME: This holds only because we only have one unary transform.
3565 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
3566 TL.setKWLoc(DS.getTypeSpecTypeLoc());
3567 TL.setParensRange(DS.getTypeofParensRange());
3568 assert(DS.getRepAsType());
3569 TypeSourceInfo *TInfo = nullptr;
3570 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3571 TL.setUnderlyingTInfo(TInfo);
3573 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
3574 // By default, use the source location of the type specifier.
3575 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
3576 if (TL.needsExtraLocalData()) {
3577 // Set info for the written builtin specifiers.
3578 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
3579 // Try to have a meaningful source location.
3580 if (TL.getWrittenSignSpec() != TSS_unspecified)
3581 // Sign spec loc overrides the others (e.g., 'unsigned long').
3582 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
3583 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
3584 // Width spec loc overrides type spec loc (e.g., 'short int').
3585 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
3588 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
3589 ElaboratedTypeKeyword Keyword
3590 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
3591 if (DS.getTypeSpecType() == TST_typename) {
3592 TypeSourceInfo *TInfo = nullptr;
3593 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3595 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
3599 TL.setElaboratedKeywordLoc(Keyword != ETK_None
3600 ? DS.getTypeSpecTypeLoc()
3601 : SourceLocation());
3602 const CXXScopeSpec& SS = DS.getTypeSpecScope();
3603 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3604 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
3606 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
3607 assert(DS.getTypeSpecType() == TST_typename);
3608 TypeSourceInfo *TInfo = nullptr;
3609 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3611 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
3613 void VisitDependentTemplateSpecializationTypeLoc(
3614 DependentTemplateSpecializationTypeLoc TL) {
3615 assert(DS.getTypeSpecType() == TST_typename);
3616 TypeSourceInfo *TInfo = nullptr;
3617 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3620 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
3622 void VisitTagTypeLoc(TagTypeLoc TL) {
3623 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
3625 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
3626 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
3627 // or an _Atomic qualifier.
3628 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
3629 TL.setKWLoc(DS.getTypeSpecTypeLoc());
3630 TL.setParensRange(DS.getTypeofParensRange());
3632 TypeSourceInfo *TInfo = nullptr;
3633 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3635 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
3637 TL.setKWLoc(DS.getAtomicSpecLoc());
3638 // No parens, to indicate this was spelled as an _Atomic qualifier.
3639 TL.setParensRange(SourceRange());
3640 Visit(TL.getValueLoc());
3644 void VisitTypeLoc(TypeLoc TL) {
3645 // FIXME: add other typespec types and change this to an assert.
3646 TL.initialize(Context, DS.getTypeSpecTypeLoc());
3650 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
3651 ASTContext &Context;
3652 const DeclaratorChunk &Chunk;
3655 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
3656 : Context(Context), Chunk(Chunk) {}
3658 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3659 llvm_unreachable("qualified type locs not expected here!");
3661 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
3662 llvm_unreachable("decayed type locs not expected here!");
3665 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3666 fillAttributedTypeLoc(TL, Chunk.getAttrs());
3668 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
3671 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3672 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
3673 TL.setCaretLoc(Chunk.Loc);
3675 void VisitPointerTypeLoc(PointerTypeLoc TL) {
3676 assert(Chunk.Kind == DeclaratorChunk::Pointer);
3677 TL.setStarLoc(Chunk.Loc);
3679 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3680 assert(Chunk.Kind == DeclaratorChunk::Pointer);
3681 TL.setStarLoc(Chunk.Loc);
3683 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3684 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
3685 const CXXScopeSpec& SS = Chunk.Mem.Scope();
3686 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
3688 const Type* ClsTy = TL.getClass();
3689 QualType ClsQT = QualType(ClsTy, 0);
3690 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
3691 // Now copy source location info into the type loc component.
3692 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
3693 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
3694 case NestedNameSpecifier::Identifier:
3695 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
3697 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
3698 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
3699 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
3700 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
3704 case NestedNameSpecifier::TypeSpec:
3705 case NestedNameSpecifier::TypeSpecWithTemplate:
3706 if (isa<ElaboratedType>(ClsTy)) {
3707 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
3708 ETLoc.setElaboratedKeywordLoc(SourceLocation());
3709 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
3710 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
3711 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
3713 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
3717 case NestedNameSpecifier::Namespace:
3718 case NestedNameSpecifier::NamespaceAlias:
3719 case NestedNameSpecifier::Global:
3720 llvm_unreachable("Nested-name-specifier must name a type");
3723 // Finally fill in MemberPointerLocInfo fields.
3724 TL.setStarLoc(Chunk.Loc);
3725 TL.setClassTInfo(ClsTInfo);
3727 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3728 assert(Chunk.Kind == DeclaratorChunk::Reference);
3729 // 'Amp' is misleading: this might have been originally
3730 /// spelled with AmpAmp.
3731 TL.setAmpLoc(Chunk.Loc);
3733 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3734 assert(Chunk.Kind == DeclaratorChunk::Reference);
3735 assert(!Chunk.Ref.LValueRef);
3736 TL.setAmpAmpLoc(Chunk.Loc);
3738 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
3739 assert(Chunk.Kind == DeclaratorChunk::Array);
3740 TL.setLBracketLoc(Chunk.Loc);
3741 TL.setRBracketLoc(Chunk.EndLoc);
3742 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
3744 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3745 assert(Chunk.Kind == DeclaratorChunk::Function);
3746 TL.setLocalRangeBegin(Chunk.Loc);
3747 TL.setLocalRangeEnd(Chunk.EndLoc);
3749 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
3750 TL.setLParenLoc(FTI.getLParenLoc());
3751 TL.setRParenLoc(FTI.getRParenLoc());
3752 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
3753 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
3754 TL.setParam(tpi++, Param);
3756 // FIXME: exception specs
3758 void VisitParenTypeLoc(ParenTypeLoc TL) {
3759 assert(Chunk.Kind == DeclaratorChunk::Paren);
3760 TL.setLParenLoc(Chunk.Loc);
3761 TL.setRParenLoc(Chunk.EndLoc);
3764 void VisitTypeLoc(TypeLoc TL) {
3765 llvm_unreachable("unsupported TypeLoc kind in declarator!");
3770 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
3772 switch (Chunk.Kind) {
3773 case DeclaratorChunk::Function:
3774 case DeclaratorChunk::Array:
3775 case DeclaratorChunk::Paren:
3776 llvm_unreachable("cannot be _Atomic qualified");
3778 case DeclaratorChunk::Pointer:
3779 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
3782 case DeclaratorChunk::BlockPointer:
3783 case DeclaratorChunk::Reference:
3784 case DeclaratorChunk::MemberPointer:
3785 // FIXME: Provide a source location for the _Atomic keyword.
3790 ATL.setParensRange(SourceRange());
3793 /// \brief Create and instantiate a TypeSourceInfo with type source information.
3795 /// \param T QualType referring to the type as written in source code.
3797 /// \param ReturnTypeInfo For declarators whose return type does not show
3798 /// up in the normal place in the declaration specifiers (such as a C++
3799 /// conversion function), this pointer will refer to a type source information
3800 /// for that return type.
3802 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
3803 TypeSourceInfo *ReturnTypeInfo) {
3804 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
3805 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
3807 // Handle parameter packs whose type is a pack expansion.
3808 if (isa<PackExpansionType>(T)) {
3809 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
3810 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3813 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3814 // An AtomicTypeLoc might be produced by an atomic qualifier in this
3815 // declarator chunk.
3816 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
3817 fillAtomicQualLoc(ATL, D.getTypeObject(i));
3818 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
3821 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
3822 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
3823 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3826 // FIXME: Ordering here?
3827 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
3828 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3830 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
3831 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3834 // If we have different source information for the return type, use
3835 // that. This really only applies to C++ conversion functions.
3836 if (ReturnTypeInfo) {
3837 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
3838 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
3839 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
3841 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
3847 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
3848 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
3849 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
3850 // and Sema during declaration parsing. Try deallocating/caching them when
3851 // it's appropriate, instead of allocating them and keeping them around.
3852 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
3854 new (LocT) LocInfoType(T, TInfo);
3855 assert(LocT->getTypeClass() != T->getTypeClass() &&
3856 "LocInfoType's TypeClass conflicts with an existing Type class");
3857 return ParsedType::make(QualType(LocT, 0));
3860 void LocInfoType::getAsStringInternal(std::string &Str,
3861 const PrintingPolicy &Policy) const {
3862 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
3863 " was used directly instead of getting the QualType through"
3864 " GetTypeFromParser");
3867 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
3868 // C99 6.7.6: Type names have no identifier. This is already validated by
3870 assert(D.getIdentifier() == nullptr &&
3871 "Type name should have no identifier!");
3873 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3874 QualType T = TInfo->getType();
3875 if (D.isInvalidType())
3878 // Make sure there are no unused decl attributes on the declarator.
3879 // We don't want to do this for ObjC parameters because we're going
3880 // to apply them to the actual parameter declaration.
3881 // Likewise, we don't want to do this for alias declarations, because
3882 // we are actually going to build a declaration from this eventually.
3883 if (D.getContext() != Declarator::ObjCParameterContext &&
3884 D.getContext() != Declarator::AliasDeclContext &&
3885 D.getContext() != Declarator::AliasTemplateContext)
3886 checkUnusedDeclAttributes(D);
3888 if (getLangOpts().CPlusPlus) {
3889 // Check that there are no default arguments (C++ only).
3890 CheckExtraCXXDefaultArguments(D);
3893 return CreateParsedType(T, TInfo);
3896 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
3897 QualType T = Context.getObjCInstanceType();
3898 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
3899 return CreateParsedType(T, TInfo);
3903 //===----------------------------------------------------------------------===//
3904 // Type Attribute Processing
3905 //===----------------------------------------------------------------------===//
3907 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
3908 /// specified type. The attribute contains 1 argument, the id of the address
3909 /// space for the type.
3910 static void HandleAddressSpaceTypeAttribute(QualType &Type,
3911 const AttributeList &Attr, Sema &S){
3913 // If this type is already address space qualified, reject it.
3914 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
3915 // qualifiers for two or more different address spaces."
3916 if (Type.getAddressSpace()) {
3917 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
3922 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
3923 // qualified by an address-space qualifier."
3924 if (Type->isFunctionType()) {
3925 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
3931 if (Attr.getKind() == AttributeList::AT_AddressSpace) {
3932 // Check the attribute arguments.
3933 if (Attr.getNumArgs() != 1) {
3934 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3935 << Attr.getName() << 1;
3939 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
3940 llvm::APSInt addrSpace(32);
3941 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
3942 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
3943 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
3944 << Attr.getName() << AANT_ArgumentIntegerConstant
3945 << ASArgExpr->getSourceRange();
3951 if (addrSpace.isSigned()) {
3952 if (addrSpace.isNegative()) {
3953 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
3954 << ASArgExpr->getSourceRange();
3958 addrSpace.setIsSigned(false);
3960 llvm::APSInt max(addrSpace.getBitWidth());
3961 max = Qualifiers::MaxAddressSpace;
3962 if (addrSpace > max) {
3963 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
3964 << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange();
3968 ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
3970 // The keyword-based type attributes imply which address space to use.
3971 switch (Attr.getKind()) {
3972 case AttributeList::AT_OpenCLGlobalAddressSpace:
3973 ASIdx = LangAS::opencl_global; break;
3974 case AttributeList::AT_OpenCLLocalAddressSpace:
3975 ASIdx = LangAS::opencl_local; break;
3976 case AttributeList::AT_OpenCLConstantAddressSpace:
3977 ASIdx = LangAS::opencl_constant; break;
3979 assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace);
3984 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
3987 /// Does this type have a "direct" ownership qualifier? That is,
3988 /// is it written like "__strong id", as opposed to something like
3989 /// "typeof(foo)", where that happens to be strong?
3990 static bool hasDirectOwnershipQualifier(QualType type) {
3991 // Fast path: no qualifier at all.
3992 assert(type.getQualifiers().hasObjCLifetime());
3996 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
3997 if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
4000 type = attr->getModifiedType();
4002 // X *__strong (...)
4003 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
4004 type = paren->getInnerType();
4006 // That's it for things we want to complain about. In particular,
4007 // we do not want to look through typedefs, typeof(expr),
4008 // typeof(type), or any other way that the type is somehow
4017 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
4018 /// attribute on the specified type.
4020 /// Returns 'true' if the attribute was handled.
4021 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
4022 AttributeList &attr,
4024 bool NonObjCPointer = false;
4026 if (!type->isDependentType() && !type->isUndeducedType()) {
4027 if (const PointerType *ptr = type->getAs<PointerType>()) {
4028 QualType pointee = ptr->getPointeeType();
4029 if (pointee->isObjCRetainableType() || pointee->isPointerType())
4031 // It is important not to lose the source info that there was an attribute
4032 // applied to non-objc pointer. We will create an attributed type but
4033 // its type will be the same as the original type.
4034 NonObjCPointer = true;
4035 } else if (!type->isObjCRetainableType()) {
4039 // Don't accept an ownership attribute in the declspec if it would
4040 // just be the return type of a block pointer.
4041 if (state.isProcessingDeclSpec()) {
4042 Declarator &D = state.getDeclarator();
4043 if (maybeMovePastReturnType(D, D.getNumTypeObjects()))
4048 Sema &S = state.getSema();
4049 SourceLocation AttrLoc = attr.getLoc();
4050 if (AttrLoc.isMacroID())
4051 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
4053 if (!attr.isArgIdent(0)) {
4054 S.Diag(AttrLoc, diag::err_attribute_argument_type)
4055 << attr.getName() << AANT_ArgumentString;
4060 // Consume lifetime attributes without further comment outside of
4062 if (!S.getLangOpts().ObjCAutoRefCount)
4065 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
4066 Qualifiers::ObjCLifetime lifetime;
4067 if (II->isStr("none"))
4068 lifetime = Qualifiers::OCL_ExplicitNone;
4069 else if (II->isStr("strong"))
4070 lifetime = Qualifiers::OCL_Strong;
4071 else if (II->isStr("weak"))
4072 lifetime = Qualifiers::OCL_Weak;
4073 else if (II->isStr("autoreleasing"))
4074 lifetime = Qualifiers::OCL_Autoreleasing;
4076 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
4077 << attr.getName() << II;
4082 SplitQualType underlyingType = type.split();
4084 // Check for redundant/conflicting ownership qualifiers.
4085 if (Qualifiers::ObjCLifetime previousLifetime
4086 = type.getQualifiers().getObjCLifetime()) {
4087 // If it's written directly, that's an error.
4088 if (hasDirectOwnershipQualifier(type)) {
4089 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
4094 // Otherwise, if the qualifiers actually conflict, pull sugar off
4095 // until we reach a type that is directly qualified.
4096 if (previousLifetime != lifetime) {
4097 // This should always terminate: the canonical type is
4098 // qualified, so some bit of sugar must be hiding it.
4099 while (!underlyingType.Quals.hasObjCLifetime()) {
4100 underlyingType = underlyingType.getSingleStepDesugaredType();
4102 underlyingType.Quals.removeObjCLifetime();
4106 underlyingType.Quals.addObjCLifetime(lifetime);
4108 if (NonObjCPointer) {
4109 StringRef name = attr.getName()->getName();
4111 case Qualifiers::OCL_None:
4112 case Qualifiers::OCL_ExplicitNone:
4114 case Qualifiers::OCL_Strong: name = "__strong"; break;
4115 case Qualifiers::OCL_Weak: name = "__weak"; break;
4116 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
4118 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
4119 << TDS_ObjCObjOrBlock << type;
4122 QualType origType = type;
4123 if (!NonObjCPointer)
4124 type = S.Context.getQualifiedType(underlyingType);
4126 // If we have a valid source location for the attribute, use an
4127 // AttributedType instead.
4128 if (AttrLoc.isValid())
4129 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
4132 // Forbid __weak if the runtime doesn't support it.
4133 if (lifetime == Qualifiers::OCL_Weak &&
4134 !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) {
4136 // Actually, delay this until we know what we're parsing.
4137 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
4138 S.DelayedDiagnostics.add(
4139 sema::DelayedDiagnostic::makeForbiddenType(
4140 S.getSourceManager().getExpansionLoc(AttrLoc),
4141 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
4143 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
4150 // Forbid __weak for class objects marked as
4151 // objc_arc_weak_reference_unavailable
4152 if (lifetime == Qualifiers::OCL_Weak) {
4153 if (const ObjCObjectPointerType *ObjT =
4154 type->getAs<ObjCObjectPointerType>()) {
4155 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
4156 if (Class->isArcWeakrefUnavailable()) {
4157 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
4158 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
4159 diag::note_class_declared);
4168 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
4169 /// attribute on the specified type. Returns true to indicate that
4170 /// the attribute was handled, false to indicate that the type does
4171 /// not permit the attribute.
4172 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
4173 AttributeList &attr,
4175 Sema &S = state.getSema();
4177 // Delay if this isn't some kind of pointer.
4178 if (!type->isPointerType() &&
4179 !type->isObjCObjectPointerType() &&
4180 !type->isBlockPointerType())
4183 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
4184 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
4189 // Check the attribute arguments.
4190 if (!attr.isArgIdent(0)) {
4191 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
4192 << attr.getName() << AANT_ArgumentString;
4196 Qualifiers::GC GCAttr;
4197 if (attr.getNumArgs() > 1) {
4198 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4199 << attr.getName() << 1;
4204 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
4205 if (II->isStr("weak"))
4206 GCAttr = Qualifiers::Weak;
4207 else if (II->isStr("strong"))
4208 GCAttr = Qualifiers::Strong;
4210 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
4211 << attr.getName() << II;
4216 QualType origType = type;
4217 type = S.Context.getObjCGCQualType(origType, GCAttr);
4219 // Make an attributed type to preserve the source information.
4220 if (attr.getLoc().isValid())
4221 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
4228 /// A helper class to unwrap a type down to a function for the
4229 /// purposes of applying attributes there.
4232 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
4233 /// if (unwrapped.isFunctionType()) {
4234 /// const FunctionType *fn = unwrapped.get();
4235 /// // change fn somehow
4236 /// T = unwrapped.wrap(fn);
4238 struct FunctionTypeUnwrapper {
4249 const FunctionType *Fn;
4250 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
4252 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
4254 const Type *Ty = T.getTypePtr();
4255 if (isa<FunctionType>(Ty)) {
4256 Fn = cast<FunctionType>(Ty);
4258 } else if (isa<ParenType>(Ty)) {
4259 T = cast<ParenType>(Ty)->getInnerType();
4260 Stack.push_back(Parens);
4261 } else if (isa<PointerType>(Ty)) {
4262 T = cast<PointerType>(Ty)->getPointeeType();
4263 Stack.push_back(Pointer);
4264 } else if (isa<BlockPointerType>(Ty)) {
4265 T = cast<BlockPointerType>(Ty)->getPointeeType();
4266 Stack.push_back(BlockPointer);
4267 } else if (isa<MemberPointerType>(Ty)) {
4268 T = cast<MemberPointerType>(Ty)->getPointeeType();
4269 Stack.push_back(MemberPointer);
4270 } else if (isa<ReferenceType>(Ty)) {
4271 T = cast<ReferenceType>(Ty)->getPointeeType();
4272 Stack.push_back(Reference);
4274 const Type *DTy = Ty->getUnqualifiedDesugaredType();
4280 T = QualType(DTy, 0);
4281 Stack.push_back(Desugar);
4286 bool isFunctionType() const { return (Fn != nullptr); }
4287 const FunctionType *get() const { return Fn; }
4289 QualType wrap(Sema &S, const FunctionType *New) {
4290 // If T wasn't modified from the unwrapped type, do nothing.
4291 if (New == get()) return Original;
4294 return wrap(S.Context, Original, 0);
4298 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
4299 if (I == Stack.size())
4300 return C.getQualifiedType(Fn, Old.getQualifiers());
4302 // Build up the inner type, applying the qualifiers from the old
4303 // type to the new type.
4304 SplitQualType SplitOld = Old.split();
4306 // As a special case, tail-recurse if there are no qualifiers.
4307 if (SplitOld.Quals.empty())
4308 return wrap(C, SplitOld.Ty, I);
4309 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
4312 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
4313 if (I == Stack.size()) return QualType(Fn, 0);
4315 switch (static_cast<WrapKind>(Stack[I++])) {
4317 // This is the point at which we potentially lose source
4319 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
4322 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
4323 return C.getParenType(New);
4327 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
4328 return C.getPointerType(New);
4331 case BlockPointer: {
4332 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
4333 return C.getBlockPointerType(New);
4336 case MemberPointer: {
4337 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
4338 QualType New = wrap(C, OldMPT->getPointeeType(), I);
4339 return C.getMemberPointerType(New, OldMPT->getClass());
4343 const ReferenceType *OldRef = cast<ReferenceType>(Old);
4344 QualType New = wrap(C, OldRef->getPointeeType(), I);
4345 if (isa<LValueReferenceType>(OldRef))
4346 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
4348 return C.getRValueReferenceType(New);
4352 llvm_unreachable("unknown wrapping kind");
4357 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
4358 AttributeList &Attr,
4360 Sema &S = State.getSema();
4362 AttributeList::Kind Kind = Attr.getKind();
4363 QualType Desugared = Type;
4364 const AttributedType *AT = dyn_cast<AttributedType>(Type);
4366 AttributedType::Kind CurAttrKind = AT->getAttrKind();
4368 // You cannot specify duplicate type attributes, so if the attribute has
4369 // already been applied, flag it.
4370 if (getAttrListKind(CurAttrKind) == Kind) {
4371 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
4376 // You cannot have both __sptr and __uptr on the same type, nor can you
4377 // have __ptr32 and __ptr64.
4378 if ((CurAttrKind == AttributedType::attr_ptr32 &&
4379 Kind == AttributeList::AT_Ptr64) ||
4380 (CurAttrKind == AttributedType::attr_ptr64 &&
4381 Kind == AttributeList::AT_Ptr32)) {
4382 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
4383 << "'__ptr32'" << "'__ptr64'";
4385 } else if ((CurAttrKind == AttributedType::attr_sptr &&
4386 Kind == AttributeList::AT_UPtr) ||
4387 (CurAttrKind == AttributedType::attr_uptr &&
4388 Kind == AttributeList::AT_SPtr)) {
4389 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
4390 << "'__sptr'" << "'__uptr'";
4394 Desugared = AT->getEquivalentType();
4395 AT = dyn_cast<AttributedType>(Desugared);
4398 // Pointer type qualifiers can only operate on pointer types, but not
4399 // pointer-to-member types.
4400 if (!isa<PointerType>(Desugared)) {
4401 S.Diag(Attr.getLoc(), Type->isMemberPointerType() ?
4402 diag::err_attribute_no_member_pointers :
4403 diag::err_attribute_pointers_only) << Attr.getName();
4407 AttributedType::Kind TAK;
4409 default: llvm_unreachable("Unknown attribute kind");
4410 case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
4411 case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
4412 case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
4413 case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
4416 Type = S.Context.getAttributedType(TAK, Type, Type);
4420 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
4421 assert(!Attr.isInvalid());
4422 switch (Attr.getKind()) {
4424 llvm_unreachable("not a calling convention attribute");
4425 case AttributeList::AT_CDecl:
4426 return AttributedType::attr_cdecl;
4427 case AttributeList::AT_FastCall:
4428 return AttributedType::attr_fastcall;
4429 case AttributeList::AT_StdCall:
4430 return AttributedType::attr_stdcall;
4431 case AttributeList::AT_ThisCall:
4432 return AttributedType::attr_thiscall;
4433 case AttributeList::AT_Pascal:
4434 return AttributedType::attr_pascal;
4435 case AttributeList::AT_Pcs: {
4436 // The attribute may have had a fixit applied where we treated an
4437 // identifier as a string literal. The contents of the string are valid,
4438 // but the form may not be.
4440 if (Attr.isArgExpr(0))
4441 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
4443 Str = Attr.getArgAsIdent(0)->Ident->getName();
4444 return llvm::StringSwitch<AttributedType::Kind>(Str)
4445 .Case("aapcs", AttributedType::attr_pcs)
4446 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
4448 case AttributeList::AT_PnaclCall:
4449 return AttributedType::attr_pnaclcall;
4450 case AttributeList::AT_IntelOclBicc:
4451 return AttributedType::attr_inteloclbicc;
4452 case AttributeList::AT_MSABI:
4453 return AttributedType::attr_ms_abi;
4454 case AttributeList::AT_SysVABI:
4455 return AttributedType::attr_sysv_abi;
4457 llvm_unreachable("unexpected attribute kind!");
4460 /// Process an individual function attribute. Returns true to
4461 /// indicate that the attribute was handled, false if it wasn't.
4462 static bool handleFunctionTypeAttr(TypeProcessingState &state,
4463 AttributeList &attr,
4465 Sema &S = state.getSema();
4467 FunctionTypeUnwrapper unwrapped(S, type);
4469 if (attr.getKind() == AttributeList::AT_NoReturn) {
4470 if (S.CheckNoReturnAttr(attr))
4473 // Delay if this is not a function type.
4474 if (!unwrapped.isFunctionType())
4477 // Otherwise we can process right away.
4478 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
4479 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4483 // ns_returns_retained is not always a type attribute, but if we got
4484 // here, we're treating it as one right now.
4485 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
4486 assert(S.getLangOpts().ObjCAutoRefCount &&
4487 "ns_returns_retained treated as type attribute in non-ARC");
4488 if (attr.getNumArgs()) return true;
4490 // Delay if this is not a function type.
4491 if (!unwrapped.isFunctionType())
4494 FunctionType::ExtInfo EI
4495 = unwrapped.get()->getExtInfo().withProducesResult(true);
4496 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4500 if (attr.getKind() == AttributeList::AT_Regparm) {
4502 if (S.CheckRegparmAttr(attr, value))
4505 // Delay if this is not a function type.
4506 if (!unwrapped.isFunctionType())
4509 // Diagnose regparm with fastcall.
4510 const FunctionType *fn = unwrapped.get();
4511 CallingConv CC = fn->getCallConv();
4512 if (CC == CC_X86FastCall) {
4513 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4514 << FunctionType::getNameForCallConv(CC)
4520 FunctionType::ExtInfo EI =
4521 unwrapped.get()->getExtInfo().withRegParm(value);
4522 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4526 // Delay if the type didn't work out to a function.
4527 if (!unwrapped.isFunctionType()) return false;
4529 // Otherwise, a calling convention.
4531 if (S.CheckCallingConvAttr(attr, CC))
4534 const FunctionType *fn = unwrapped.get();
4535 CallingConv CCOld = fn->getCallConv();
4536 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
4539 // Error out on when there's already an attribute on the type
4540 // and the CCs don't match.
4541 const AttributedType *AT = S.getCallingConvAttributedType(type);
4542 if (AT && AT->getAttrKind() != CCAttrKind) {
4543 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4544 << FunctionType::getNameForCallConv(CC)
4545 << FunctionType::getNameForCallConv(CCOld);
4551 // Diagnose use of callee-cleanup calling convention on variadic functions.
4552 if (isCalleeCleanup(CC)) {
4553 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
4554 if (FnP && FnP->isVariadic()) {
4555 unsigned DiagID = diag::err_cconv_varargs;
4556 // stdcall and fastcall are ignored with a warning for GCC and MS
4558 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
4559 DiagID = diag::warn_cconv_varargs;
4561 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
4567 // Diagnose the use of X86 fastcall on unprototyped functions.
4568 if (CC == CC_X86FastCall) {
4569 if (isa<FunctionNoProtoType>(fn)) {
4570 S.Diag(attr.getLoc(), diag::err_cconv_knr)
4571 << FunctionType::getNameForCallConv(CC);
4576 // Also diagnose fastcall with regparm.
4577 if (fn->getHasRegParm()) {
4578 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4580 << FunctionType::getNameForCallConv(CC);
4586 // Modify the CC from the wrapped function type, wrap it all back, and then
4587 // wrap the whole thing in an AttributedType as written. The modified type
4588 // might have a different CC if we ignored the attribute.
4589 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
4590 QualType Equivalent =
4591 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4592 type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
4596 bool Sema::hasExplicitCallingConv(QualType &T) {
4597 QualType R = T.IgnoreParens();
4598 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
4599 if (AT->isCallingConv())
4601 R = AT->getModifiedType().IgnoreParens();
4606 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic) {
4607 FunctionTypeUnwrapper Unwrapped(*this, T);
4608 const FunctionType *FT = Unwrapped.get();
4609 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
4610 cast<FunctionProtoType>(FT)->isVariadic());
4612 // Only adjust types with the default convention. For example, on Windows we
4613 // should adjust a __cdecl type to __thiscall for instance methods, and a
4614 // __thiscall type to __cdecl for static methods.
4615 CallingConv CurCC = FT->getCallConv();
4616 CallingConv FromCC =
4617 Context.getDefaultCallingConvention(IsVariadic, IsStatic);
4618 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
4619 if (CurCC != FromCC || FromCC == ToCC)
4622 if (hasExplicitCallingConv(T))
4625 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
4626 QualType Wrapped = Unwrapped.wrap(*this, FT);
4627 T = Context.getAdjustedType(T, Wrapped);
4630 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
4631 /// and float scalars, although arrays, pointers, and function return values are
4632 /// allowed in conjunction with this construct. Aggregates with this attribute
4633 /// are invalid, even if they are of the same size as a corresponding scalar.
4634 /// The raw attribute should contain precisely 1 argument, the vector size for
4635 /// the variable, measured in bytes. If curType and rawAttr are well formed,
4636 /// this routine will return a new vector type.
4637 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
4639 // Check the attribute arguments.
4640 if (Attr.getNumArgs() != 1) {
4641 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4642 << Attr.getName() << 1;
4646 Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4647 llvm::APSInt vecSize(32);
4648 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
4649 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
4650 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4651 << Attr.getName() << AANT_ArgumentIntegerConstant
4652 << sizeExpr->getSourceRange();
4656 // The base type must be integer (not Boolean or enumeration) or float, and
4657 // can't already be a vector.
4658 if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
4659 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
4660 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
4664 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4665 // vecSize is specified in bytes - convert to bits.
4666 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
4668 // the vector size needs to be an integral multiple of the type size.
4669 if (vectorSize % typeSize) {
4670 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
4671 << sizeExpr->getSourceRange();
4675 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
4676 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
4677 << sizeExpr->getSourceRange();
4681 if (vectorSize == 0) {
4682 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
4683 << sizeExpr->getSourceRange();
4688 // Success! Instantiate the vector type, the number of elements is > 0, and
4689 // not required to be a power of 2, unlike GCC.
4690 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
4691 VectorType::GenericVector);
4694 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
4696 static void HandleExtVectorTypeAttr(QualType &CurType,
4697 const AttributeList &Attr,
4699 // check the attribute arguments.
4700 if (Attr.getNumArgs() != 1) {
4701 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4702 << Attr.getName() << 1;
4708 // Special case where the argument is a template id.
4709 if (Attr.isArgIdent(0)) {
4711 SourceLocation TemplateKWLoc;
4713 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
4715 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
4717 if (Size.isInvalid())
4720 sizeExpr = Size.get();
4722 sizeExpr = Attr.getArgAsExpr(0);
4725 // Create the vector type.
4726 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
4731 static bool isPermittedNeonBaseType(QualType &Ty,
4732 VectorType::VectorKind VecKind, Sema &S) {
4733 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
4737 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
4739 // Signed poly is mathematically wrong, but has been baked into some ABIs by
4741 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
4742 Triple.getArch() == llvm::Triple::aarch64_be ||
4743 Triple.getArch() == llvm::Triple::arm64 ||
4744 Triple.getArch() == llvm::Triple::arm64_be;
4745 if (VecKind == VectorType::NeonPolyVector) {
4746 if (IsPolyUnsigned) {
4747 // AArch64 polynomial vectors are unsigned and support poly64.
4748 return BTy->getKind() == BuiltinType::UChar ||
4749 BTy->getKind() == BuiltinType::UShort ||
4750 BTy->getKind() == BuiltinType::ULong ||
4751 BTy->getKind() == BuiltinType::ULongLong;
4753 // AArch32 polynomial vector are signed.
4754 return BTy->getKind() == BuiltinType::SChar ||
4755 BTy->getKind() == BuiltinType::Short;
4759 // Non-polynomial vector types: the usual suspects are allowed, as well as
4760 // float64_t on AArch64.
4761 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
4762 Triple.getArch() == llvm::Triple::aarch64_be ||
4763 Triple.getArch() == llvm::Triple::arm64 ||
4764 Triple.getArch() == llvm::Triple::arm64_be;
4766 if (Is64Bit && BTy->getKind() == BuiltinType::Double)
4769 return BTy->getKind() == BuiltinType::SChar ||
4770 BTy->getKind() == BuiltinType::UChar ||
4771 BTy->getKind() == BuiltinType::Short ||
4772 BTy->getKind() == BuiltinType::UShort ||
4773 BTy->getKind() == BuiltinType::Int ||
4774 BTy->getKind() == BuiltinType::UInt ||
4775 BTy->getKind() == BuiltinType::Long ||
4776 BTy->getKind() == BuiltinType::ULong ||
4777 BTy->getKind() == BuiltinType::LongLong ||
4778 BTy->getKind() == BuiltinType::ULongLong ||
4779 BTy->getKind() == BuiltinType::Float ||
4780 BTy->getKind() == BuiltinType::Half;
4783 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
4784 /// "neon_polyvector_type" attributes are used to create vector types that
4785 /// are mangled according to ARM's ABI. Otherwise, these types are identical
4786 /// to those created with the "vector_size" attribute. Unlike "vector_size"
4787 /// the argument to these Neon attributes is the number of vector elements,
4788 /// not the vector size in bytes. The vector width and element type must
4789 /// match one of the standard Neon vector types.
4790 static void HandleNeonVectorTypeAttr(QualType& CurType,
4791 const AttributeList &Attr, Sema &S,
4792 VectorType::VectorKind VecKind) {
4793 // Target must have NEON
4794 if (!S.Context.getTargetInfo().hasFeature("neon")) {
4795 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
4799 // Check the attribute arguments.
4800 if (Attr.getNumArgs() != 1) {
4801 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4802 << Attr.getName() << 1;
4806 // The number of elements must be an ICE.
4807 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4808 llvm::APSInt numEltsInt(32);
4809 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
4810 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
4811 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4812 << Attr.getName() << AANT_ArgumentIntegerConstant
4813 << numEltsExpr->getSourceRange();
4817 // Only certain element types are supported for Neon vectors.
4818 if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
4819 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
4824 // The total size of the vector must be 64 or 128 bits.
4825 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4826 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
4827 unsigned vecSize = typeSize * numElts;
4828 if (vecSize != 64 && vecSize != 128) {
4829 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
4834 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
4837 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
4838 TypeAttrLocation TAL, AttributeList *attrs) {
4839 // Scan through and apply attributes to this type where it makes sense. Some
4840 // attributes (such as __address_space__, __vector_size__, etc) apply to the
4841 // type, but others can be present in the type specifiers even though they
4842 // apply to the decl. Here we apply type attributes and ignore the rest.
4844 AttributeList *next;
4846 AttributeList &attr = *attrs;
4847 next = attr.getNext();
4849 // Skip attributes that were marked to be invalid.
4850 if (attr.isInvalid())
4853 if (attr.isCXX11Attribute()) {
4854 // [[gnu::...]] attributes are treated as declaration attributes, so may
4855 // not appertain to a DeclaratorChunk, even if we handle them as type
4857 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
4858 if (TAL == TAL_DeclChunk) {
4859 state.getSema().Diag(attr.getLoc(),
4860 diag::warn_cxx11_gnu_attribute_on_type)
4864 } else if (TAL != TAL_DeclChunk) {
4865 // Otherwise, only consider type processing for a C++11 attribute if
4866 // it's actually been applied to a type.
4871 // If this is an attribute we can handle, do so now,
4872 // otherwise, add it to the FnAttrs list for rechaining.
4873 switch (attr.getKind()) {
4875 // A C++11 attribute on a declarator chunk must appertain to a type.
4876 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
4877 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
4879 attr.setUsedAsTypeAttr();
4883 case AttributeList::UnknownAttribute:
4884 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
4885 state.getSema().Diag(attr.getLoc(),
4886 diag::warn_unknown_attribute_ignored)
4890 case AttributeList::IgnoredAttribute:
4893 case AttributeList::AT_MayAlias:
4894 // FIXME: This attribute needs to actually be handled, but if we ignore
4895 // it it breaks large amounts of Linux software.
4896 attr.setUsedAsTypeAttr();
4898 case AttributeList::AT_OpenCLPrivateAddressSpace:
4899 case AttributeList::AT_OpenCLGlobalAddressSpace:
4900 case AttributeList::AT_OpenCLLocalAddressSpace:
4901 case AttributeList::AT_OpenCLConstantAddressSpace:
4902 case AttributeList::AT_AddressSpace:
4903 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
4904 attr.setUsedAsTypeAttr();
4906 OBJC_POINTER_TYPE_ATTRS_CASELIST:
4907 if (!handleObjCPointerTypeAttr(state, attr, type))
4908 distributeObjCPointerTypeAttr(state, attr, type);
4909 attr.setUsedAsTypeAttr();
4911 case AttributeList::AT_VectorSize:
4912 HandleVectorSizeAttr(type, attr, state.getSema());
4913 attr.setUsedAsTypeAttr();
4915 case AttributeList::AT_ExtVectorType:
4916 HandleExtVectorTypeAttr(type, attr, state.getSema());
4917 attr.setUsedAsTypeAttr();
4919 case AttributeList::AT_NeonVectorType:
4920 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4921 VectorType::NeonVector);
4922 attr.setUsedAsTypeAttr();
4924 case AttributeList::AT_NeonPolyVectorType:
4925 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4926 VectorType::NeonPolyVector);
4927 attr.setUsedAsTypeAttr();
4929 case AttributeList::AT_OpenCLImageAccess:
4930 // FIXME: there should be some type checking happening here, I would
4931 // imagine, but the original handler's checking was entirely superfluous.
4932 attr.setUsedAsTypeAttr();
4935 MS_TYPE_ATTRS_CASELIST:
4936 if (!handleMSPointerTypeQualifierAttr(state, attr, type))
4937 attr.setUsedAsTypeAttr();
4940 case AttributeList::AT_NSReturnsRetained:
4941 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
4943 // fallthrough into the function attrs
4945 FUNCTION_TYPE_ATTRS_CASELIST:
4946 attr.setUsedAsTypeAttr();
4948 // Never process function type attributes as part of the
4949 // declaration-specifiers.
4950 if (TAL == TAL_DeclSpec)
4951 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
4953 // Otherwise, handle the possible delays.
4954 else if (!handleFunctionTypeAttr(state, attr, type))
4955 distributeFunctionTypeAttr(state, attr, type);
4958 } while ((attrs = next));
4961 /// \brief Ensure that the type of the given expression is complete.
4963 /// This routine checks whether the expression \p E has a complete type. If the
4964 /// expression refers to an instantiable construct, that instantiation is
4965 /// performed as needed to complete its type. Furthermore
4966 /// Sema::RequireCompleteType is called for the expression's type (or in the
4967 /// case of a reference type, the referred-to type).
4969 /// \param E The expression whose type is required to be complete.
4970 /// \param Diagnoser The object that will emit a diagnostic if the type is
4973 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
4975 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){
4976 QualType T = E->getType();
4978 // Fast path the case where the type is already complete.
4979 if (!T->isIncompleteType())
4980 // FIXME: The definition might not be visible.
4983 // Incomplete array types may be completed by the initializer attached to
4984 // their definitions. For static data members of class templates and for
4985 // variable templates, we need to instantiate the definition to get this
4986 // initializer and complete the type.
4987 if (T->isIncompleteArrayType()) {
4988 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4989 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
4990 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
4991 SourceLocation PointOfInstantiation = E->getExprLoc();
4993 if (MemberSpecializationInfo *MSInfo =
4994 Var->getMemberSpecializationInfo()) {
4995 // If we don't already have a point of instantiation, this is it.
4996 if (MSInfo->getPointOfInstantiation().isInvalid()) {
4997 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4999 // This is a modification of an existing AST node. Notify
5001 if (ASTMutationListener *L = getASTMutationListener())
5002 L->StaticDataMemberInstantiated(Var);
5005 VarTemplateSpecializationDecl *VarSpec =
5006 cast<VarTemplateSpecializationDecl>(Var);
5007 if (VarSpec->getPointOfInstantiation().isInvalid())
5008 VarSpec->setPointOfInstantiation(PointOfInstantiation);
5011 InstantiateVariableDefinition(PointOfInstantiation, Var);
5013 // Update the type to the newly instantiated definition's type both
5014 // here and within the expression.
5015 if (VarDecl *Def = Var->getDefinition()) {
5022 // We still go on to try to complete the type independently, as it
5023 // may also require instantiations or diagnostics if it remains
5030 // FIXME: Are there other cases which require instantiating something other
5031 // than the type to complete the type of an expression?
5033 // Look through reference types and complete the referred type.
5034 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5035 T = Ref->getPointeeType();
5037 return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
5041 struct TypeDiagnoserDiag : Sema::TypeDiagnoser {
5044 TypeDiagnoserDiag(unsigned DiagID)
5045 : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {}
5047 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5048 if (Suppressed) return;
5049 S.Diag(Loc, DiagID) << T;
5054 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
5055 TypeDiagnoserDiag Diagnoser(DiagID);
5056 return RequireCompleteExprType(E, Diagnoser);
5059 /// @brief Ensure that the type T is a complete type.
5061 /// This routine checks whether the type @p T is complete in any
5062 /// context where a complete type is required. If @p T is a complete
5063 /// type, returns false. If @p T is a class template specialization,
5064 /// this routine then attempts to perform class template
5065 /// instantiation. If instantiation fails, or if @p T is incomplete
5066 /// and cannot be completed, issues the diagnostic @p diag (giving it
5067 /// the type @p T) and returns true.
5069 /// @param Loc The location in the source that the incomplete type
5070 /// diagnostic should refer to.
5072 /// @param T The type that this routine is examining for completeness.
5074 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
5075 /// @c false otherwise.
5076 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
5077 TypeDiagnoser &Diagnoser) {
5078 if (RequireCompleteTypeImpl(Loc, T, Diagnoser))
5080 if (const TagType *Tag = T->getAs<TagType>()) {
5081 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
5082 Tag->getDecl()->setCompleteDefinitionRequired();
5083 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
5089 /// \brief Determine whether there is any declaration of \p D that was ever a
5090 /// definition (perhaps before module merging) and is currently visible.
5091 /// \param D The definition of the entity.
5092 /// \param Suggested Filled in with the declaration that should be made visible
5093 /// in order to provide a definition of this entity.
5094 static bool hasVisibleDefinition(Sema &S, NamedDecl *D, NamedDecl **Suggested) {
5095 // Easy case: if we don't have modules, all declarations are visible.
5096 if (!S.getLangOpts().Modules)
5099 // If this definition was instantiated from a template, map back to the
5100 // pattern from which it was instantiated.
5102 // FIXME: There must be a better place for this to live.
5103 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
5104 if (auto *TD = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
5105 auto From = TD->getInstantiatedFrom();
5106 if (auto *CTD = From.dyn_cast<ClassTemplateDecl*>()) {
5107 while (auto *NewCTD = CTD->getInstantiatedFromMemberTemplate()) {
5108 if (NewCTD->isMemberSpecialization())
5112 RD = CTD->getTemplatedDecl();
5113 } else if (auto *CTPSD = From.dyn_cast<
5114 ClassTemplatePartialSpecializationDecl *>()) {
5115 while (auto *NewCTPSD = CTPSD->getInstantiatedFromMember()) {
5116 if (NewCTPSD->isMemberSpecialization())
5122 } else if (isTemplateInstantiation(RD->getTemplateSpecializationKind())) {
5123 while (auto *NewRD = RD->getInstantiatedFromMemberClass())
5126 D = RD->getDefinition();
5127 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
5128 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
5130 if (ED->isFixed()) {
5131 // If the enum has a fixed underlying type, any declaration of it will do.
5132 *Suggested = nullptr;
5133 for (auto *Redecl : ED->redecls()) {
5134 if (LookupResult::isVisible(S, Redecl))
5136 if (Redecl->isThisDeclarationADefinition() ||
5137 (Redecl->isCanonicalDecl() && !*Suggested))
5138 *Suggested = Redecl;
5142 D = ED->getDefinition();
5144 assert(D && "missing definition for pattern of instantiated definition");
5146 // FIXME: If we merged any other decl into D, and that declaration is visible,
5147 // then we should consider a definition to be visible.
5149 return LookupResult::isVisible(S, D);
5152 /// Locks in the inheritance model for the given class and all of its bases.
5153 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
5154 RD = RD->getMostRecentDecl();
5155 if (!RD->hasAttr<MSInheritanceAttr>()) {
5156 MSInheritanceAttr::Spelling IM;
5158 switch (S.MSPointerToMemberRepresentationMethod) {
5159 case LangOptions::PPTMK_BestCase:
5160 IM = RD->calculateInheritanceModel();
5162 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
5163 IM = MSInheritanceAttr::Keyword_single_inheritance;
5165 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
5166 IM = MSInheritanceAttr::Keyword_multiple_inheritance;
5168 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
5169 IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
5173 RD->addAttr(MSInheritanceAttr::CreateImplicit(
5174 S.getASTContext(), IM,
5175 /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
5176 LangOptions::PPTMK_BestCase,
5177 S.ImplicitMSInheritanceAttrLoc.isValid()
5178 ? S.ImplicitMSInheritanceAttrLoc
5179 : RD->getSourceRange()));
5182 if (RD->hasDefinition()) {
5183 // Assign inheritance models to all of the base classes, because now we can
5184 // form pointers to members of base classes without calling
5185 // RequireCompleteType on the pointer to member of the base class type.
5186 for (const CXXBaseSpecifier &BS : RD->bases())
5187 assignInheritanceModel(S, BS.getType()->getAsCXXRecordDecl());
5191 /// \brief The implementation of RequireCompleteType
5192 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
5193 TypeDiagnoser &Diagnoser) {
5194 // FIXME: Add this assertion to make sure we always get instantiation points.
5195 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
5196 // FIXME: Add this assertion to help us flush out problems with
5197 // checking for dependent types and type-dependent expressions.
5199 // assert(!T->isDependentType() &&
5200 // "Can't ask whether a dependent type is complete");
5202 // If we have a complete type, we're done.
5203 NamedDecl *Def = nullptr;
5204 if (!T->isIncompleteType(&Def)) {
5205 // If we know about the definition but it is not visible, complain.
5206 NamedDecl *SuggestedDef = nullptr;
5207 if (!Diagnoser.Suppressed && Def &&
5208 !hasVisibleDefinition(*this, Def, &SuggestedDef)) {
5209 // Suppress this error outside of a SFINAE context if we've already
5210 // emitted the error once for this type. There's no usefulness in
5211 // repeating the diagnostic.
5212 // FIXME: Add a Fix-It that imports the corresponding module or includes
5214 Module *Owner = SuggestedDef->getOwningModule();
5215 Diag(Loc, diag::err_module_private_definition)
5216 << T << Owner->getFullModuleName();
5217 Diag(SuggestedDef->getLocation(), diag::note_previous_definition);
5219 // Try to recover by implicitly importing this module.
5220 createImplicitModuleImportForErrorRecovery(Loc, Owner);
5223 // We lock in the inheritance model once somebody has asked us to ensure
5224 // that a pointer-to-member type is complete.
5225 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5226 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
5227 if (!MPTy->getClass()->isDependentType()) {
5228 RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), 0);
5229 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
5237 const TagType *Tag = T->getAs<TagType>();
5238 const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
5240 // If there's an unimported definition of this type in a module (for
5241 // instance, because we forward declared it, then imported the definition),
5242 // import that definition now.
5244 // FIXME: What about other cases where an import extends a redeclaration
5245 // chain for a declaration that can be accessed through a mechanism other
5246 // than name lookup (eg, referenced in a template, or a variable whose type
5247 // could be completed by the module)?
5250 Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
5252 // Avoid diagnosing invalid decls as incomplete.
5253 if (D->isInvalidDecl())
5256 // Give the external AST source a chance to complete the type.
5257 if (auto *Source = Context.getExternalSource()) {
5259 Source->CompleteType(Tag->getDecl());
5261 Source->CompleteType(IFace->getDecl());
5263 // If the external source completed the type, go through the motions
5264 // again to ensure we're allowed to use the completed type.
5265 if (!T->isIncompleteType())
5266 return RequireCompleteTypeImpl(Loc, T, Diagnoser);
5270 // If we have a class template specialization or a class member of a
5271 // class template specialization, or an array with known size of such,
5272 // try to instantiate it.
5273 QualType MaybeTemplate = T;
5274 while (const ConstantArrayType *Array
5275 = Context.getAsConstantArrayType(MaybeTemplate))
5276 MaybeTemplate = Array->getElementType();
5277 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
5278 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
5279 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
5280 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
5281 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
5282 TSK_ImplicitInstantiation,
5283 /*Complain=*/!Diagnoser.Suppressed);
5284 } else if (CXXRecordDecl *Rec
5285 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
5286 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
5287 if (!Rec->isBeingDefined() && Pattern) {
5288 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
5289 assert(MSI && "Missing member specialization information?");
5290 // This record was instantiated from a class within a template.
5291 if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5292 return InstantiateClass(Loc, Rec, Pattern,
5293 getTemplateInstantiationArgs(Rec),
5294 TSK_ImplicitInstantiation,
5295 /*Complain=*/!Diagnoser.Suppressed);
5300 if (Diagnoser.Suppressed)
5303 // We have an incomplete type. Produce a diagnostic.
5304 if (Ident___float128 &&
5305 T == Context.getTypeDeclType(Context.getFloat128StubType())) {
5306 Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128);
5310 Diagnoser.diagnose(*this, Loc, T);
5312 // If the type was a forward declaration of a class/struct/union
5313 // type, produce a note.
5314 if (Tag && !Tag->getDecl()->isInvalidDecl())
5315 Diag(Tag->getDecl()->getLocation(),
5316 Tag->isBeingDefined() ? diag::note_type_being_defined
5317 : diag::note_forward_declaration)
5318 << QualType(Tag, 0);
5320 // If the Objective-C class was a forward declaration, produce a note.
5321 if (IFace && !IFace->getDecl()->isInvalidDecl())
5322 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
5324 // If we have external information that we can use to suggest a fix,
5327 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
5332 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
5334 TypeDiagnoserDiag Diagnoser(DiagID);
5335 return RequireCompleteType(Loc, T, Diagnoser);
5338 /// \brief Get diagnostic %select index for tag kind for
5339 /// literal type diagnostic message.
5340 /// WARNING: Indexes apply to particular diagnostics only!
5342 /// \returns diagnostic %select index.
5343 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
5345 case TTK_Struct: return 0;
5346 case TTK_Interface: return 1;
5347 case TTK_Class: return 2;
5348 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
5352 /// @brief Ensure that the type T is a literal type.
5354 /// This routine checks whether the type @p T is a literal type. If @p T is an
5355 /// incomplete type, an attempt is made to complete it. If @p T is a literal
5356 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
5357 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
5358 /// it the type @p T), along with notes explaining why the type is not a
5359 /// literal type, and returns true.
5361 /// @param Loc The location in the source that the non-literal type
5362 /// diagnostic should refer to.
5364 /// @param T The type that this routine is examining for literalness.
5366 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
5368 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
5369 /// @c false otherwise.
5370 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
5371 TypeDiagnoser &Diagnoser) {
5372 assert(!T->isDependentType() && "type should not be dependent");
5374 QualType ElemType = Context.getBaseElementType(T);
5375 RequireCompleteType(Loc, ElemType, 0);
5377 if (T->isLiteralType(Context))
5380 if (Diagnoser.Suppressed)
5383 Diagnoser.diagnose(*this, Loc, T);
5385 if (T->isVariableArrayType())
5388 const RecordType *RT = ElemType->getAs<RecordType>();
5392 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5394 // A partially-defined class type can't be a literal type, because a literal
5395 // class type must have a trivial destructor (which can't be checked until
5396 // the class definition is complete).
5397 if (!RD->isCompleteDefinition()) {
5398 RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T);
5402 // If the class has virtual base classes, then it's not an aggregate, and
5403 // cannot have any constexpr constructors or a trivial default constructor,
5404 // so is non-literal. This is better to diagnose than the resulting absence
5405 // of constexpr constructors.
5406 if (RD->getNumVBases()) {
5407 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
5408 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
5409 for (const auto &I : RD->vbases())
5410 Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
5411 << I.getSourceRange();
5412 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
5413 !RD->hasTrivialDefaultConstructor()) {
5414 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
5415 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
5416 for (const auto &I : RD->bases()) {
5417 if (!I.getType()->isLiteralType(Context)) {
5418 Diag(I.getLocStart(),
5419 diag::note_non_literal_base_class)
5420 << RD << I.getType() << I.getSourceRange();
5424 for (const auto *I : RD->fields()) {
5425 if (!I->getType()->isLiteralType(Context) ||
5426 I->getType().isVolatileQualified()) {
5427 Diag(I->getLocation(), diag::note_non_literal_field)
5428 << RD << I << I->getType()
5429 << I->getType().isVolatileQualified();
5433 } else if (!RD->hasTrivialDestructor()) {
5434 // All fields and bases are of literal types, so have trivial destructors.
5435 // If this class's destructor is non-trivial it must be user-declared.
5436 CXXDestructorDecl *Dtor = RD->getDestructor();
5437 assert(Dtor && "class has literal fields and bases but no dtor?");
5441 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
5442 diag::note_non_literal_user_provided_dtor :
5443 diag::note_non_literal_nontrivial_dtor) << RD;
5444 if (!Dtor->isUserProvided())
5445 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
5451 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
5452 TypeDiagnoserDiag Diagnoser(DiagID);
5453 return RequireLiteralType(Loc, T, Diagnoser);
5456 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
5457 /// and qualified by the nested-name-specifier contained in SS.
5458 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
5459 const CXXScopeSpec &SS, QualType T) {
5462 NestedNameSpecifier *NNS;
5464 NNS = SS.getScopeRep();
5466 if (Keyword == ETK_None)
5470 return Context.getElaboratedType(Keyword, NNS, T);
5473 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
5474 ExprResult ER = CheckPlaceholderExpr(E);
5475 if (ER.isInvalid()) return QualType();
5478 if (!E->isTypeDependent()) {
5479 QualType T = E->getType();
5480 if (const TagType *TT = T->getAs<TagType>())
5481 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
5483 return Context.getTypeOfExprType(E);
5486 /// getDecltypeForExpr - Given an expr, will return the decltype for
5487 /// that expression, according to the rules in C++11
5488 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
5489 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
5490 if (E->isTypeDependent())
5491 return S.Context.DependentTy;
5493 // C++11 [dcl.type.simple]p4:
5494 // The type denoted by decltype(e) is defined as follows:
5496 // - if e is an unparenthesized id-expression or an unparenthesized class
5497 // member access (5.2.5), decltype(e) is the type of the entity named
5498 // by e. If there is no such entity, or if e names a set of overloaded
5499 // functions, the program is ill-formed;
5501 // We apply the same rules for Objective-C ivar and property references.
5502 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
5503 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
5504 return VD->getType();
5505 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5506 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
5507 return FD->getType();
5508 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
5509 return IR->getDecl()->getType();
5510 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
5511 if (PR->isExplicitProperty())
5512 return PR->getExplicitProperty()->getType();
5515 // C++11 [expr.lambda.prim]p18:
5516 // Every occurrence of decltype((x)) where x is a possibly
5517 // parenthesized id-expression that names an entity of automatic
5518 // storage duration is treated as if x were transformed into an
5519 // access to a corresponding data member of the closure type that
5520 // would have been declared if x were an odr-use of the denoted
5522 using namespace sema;
5523 if (S.getCurLambda()) {
5524 if (isa<ParenExpr>(E)) {
5525 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
5526 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
5527 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
5529 return S.Context.getLValueReferenceType(T);
5536 // C++11 [dcl.type.simple]p4:
5538 QualType T = E->getType();
5539 switch (E->getValueKind()) {
5540 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
5542 case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
5543 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
5545 case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
5546 // - otherwise, decltype(e) is the type of e.
5547 case VK_RValue: break;
5553 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
5554 ExprResult ER = CheckPlaceholderExpr(E);
5555 if (ER.isInvalid()) return QualType();
5558 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
5561 QualType Sema::BuildUnaryTransformType(QualType BaseType,
5562 UnaryTransformType::UTTKind UKind,
5563 SourceLocation Loc) {
5565 case UnaryTransformType::EnumUnderlyingType:
5566 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
5567 Diag(Loc, diag::err_only_enums_have_underlying_types);
5570 QualType Underlying = BaseType;
5571 if (!BaseType->isDependentType()) {
5572 // The enum could be incomplete if we're parsing its definition or
5573 // recovering from an error.
5574 NamedDecl *FwdDecl = nullptr;
5575 if (BaseType->isIncompleteType(&FwdDecl)) {
5576 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
5577 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
5581 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
5582 assert(ED && "EnumType has no EnumDecl");
5584 DiagnoseUseOfDecl(ED, Loc);
5586 Underlying = ED->getIntegerType();
5587 assert(!Underlying.isNull());
5589 return Context.getUnaryTransformType(BaseType, Underlying,
5590 UnaryTransformType::EnumUnderlyingType);
5593 llvm_unreachable("unknown unary transform type");
5596 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
5597 if (!T->isDependentType()) {
5598 // FIXME: It isn't entirely clear whether incomplete atomic types
5599 // are allowed or not; for simplicity, ban them for the moment.
5600 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
5603 int DisallowedKind = -1;
5604 if (T->isArrayType())
5606 else if (T->isFunctionType())
5608 else if (T->isReferenceType())
5610 else if (T->isAtomicType())
5612 else if (T.hasQualifiers())
5614 else if (!T.isTriviallyCopyableType(Context))
5615 // Some other non-trivially-copyable type (probably a C++ class)
5618 if (DisallowedKind != -1) {
5619 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
5623 // FIXME: Do we need any handling for ARC here?
5626 // Build the pointer type.
5627 return Context.getAtomicType(T);