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/ScopeInfo.h"
15 #include "clang/Sema/SemaInternal.h"
16 #include "clang/Sema/Template.h"
17 #include "clang/Basic/OpenCL.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/ASTMutationListener.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/TypeLoc.h"
24 #include "clang/AST/TypeLocVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/Basic/PartialDiagnostic.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Parse/ParseDiagnostic.h"
30 #include "clang/Sema/DeclSpec.h"
31 #include "clang/Sema/DelayedDiagnostic.h"
32 #include "clang/Sema/Lookup.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/Support/ErrorHandling.h"
35 using namespace clang;
37 /// isOmittedBlockReturnType - Return true if this declarator is missing a
38 /// return type because this is a omitted return type on a block literal.
39 static bool isOmittedBlockReturnType(const Declarator &D) {
40 if (D.getContext() != Declarator::BlockLiteralContext ||
41 D.getDeclSpec().hasTypeSpecifier())
44 if (D.getNumTypeObjects() == 0)
45 return true; // ^{ ... }
47 if (D.getNumTypeObjects() == 1 &&
48 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
49 return true; // ^(int X, float Y) { ... }
54 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
55 /// doesn't apply to the given type.
56 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
58 bool useExpansionLoc = false;
61 switch (attr.getKind()) {
62 case AttributeList::AT_ObjCGC:
63 diagID = diag::warn_pointer_attribute_wrong_type;
64 useExpansionLoc = true;
67 case AttributeList::AT_ObjCOwnership:
68 diagID = diag::warn_objc_object_attribute_wrong_type;
69 useExpansionLoc = true;
73 // Assume everything else was a function attribute.
74 diagID = diag::warn_function_attribute_wrong_type;
78 SourceLocation loc = attr.getLoc();
79 StringRef name = attr.getName()->getName();
81 // The GC attributes are usually written with macros; special-case them.
82 if (useExpansionLoc && loc.isMacroID() && attr.getParameterName()) {
83 if (attr.getParameterName()->isStr("strong")) {
84 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
85 } else if (attr.getParameterName()->isStr("weak")) {
86 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
90 S.Diag(loc, diagID) << name << type;
93 // objc_gc applies to Objective-C pointers or, otherwise, to the
94 // smallest available pointer type (i.e. 'void*' in 'void**').
95 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
96 case AttributeList::AT_ObjCGC: \
97 case AttributeList::AT_ObjCOwnership
99 // Function type attributes.
100 #define FUNCTION_TYPE_ATTRS_CASELIST \
101 case AttributeList::AT_NoReturn: \
102 case AttributeList::AT_CDecl: \
103 case AttributeList::AT_FastCall: \
104 case AttributeList::AT_StdCall: \
105 case AttributeList::AT_ThisCall: \
106 case AttributeList::AT_Pascal: \
107 case AttributeList::AT_Regparm: \
108 case AttributeList::AT_Pcs \
111 /// An object which stores processing state for the entire
112 /// GetTypeForDeclarator process.
113 class TypeProcessingState {
116 /// The declarator being processed.
117 Declarator &declarator;
119 /// The index of the declarator chunk we're currently processing.
120 /// May be the total number of valid chunks, indicating the
124 /// Whether there are non-trivial modifications to the decl spec.
127 /// Whether we saved the attributes in the decl spec.
130 /// The original set of attributes on the DeclSpec.
131 SmallVector<AttributeList*, 2> savedAttrs;
133 /// A list of attributes to diagnose the uselessness of when the
134 /// processing is complete.
135 SmallVector<AttributeList*, 2> ignoredTypeAttrs;
138 TypeProcessingState(Sema &sema, Declarator &declarator)
139 : sema(sema), declarator(declarator),
140 chunkIndex(declarator.getNumTypeObjects()),
141 trivial(true), hasSavedAttrs(false) {}
143 Sema &getSema() const {
147 Declarator &getDeclarator() const {
151 unsigned getCurrentChunkIndex() const {
155 void setCurrentChunkIndex(unsigned idx) {
156 assert(idx <= declarator.getNumTypeObjects());
160 AttributeList *&getCurrentAttrListRef() const {
161 assert(chunkIndex <= declarator.getNumTypeObjects());
162 if (chunkIndex == declarator.getNumTypeObjects())
163 return getMutableDeclSpec().getAttributes().getListRef();
164 return declarator.getTypeObject(chunkIndex).getAttrListRef();
167 /// Save the current set of attributes on the DeclSpec.
168 void saveDeclSpecAttrs() {
169 // Don't try to save them multiple times.
170 if (hasSavedAttrs) return;
172 DeclSpec &spec = getMutableDeclSpec();
173 for (AttributeList *attr = spec.getAttributes().getList(); attr;
174 attr = attr->getNext())
175 savedAttrs.push_back(attr);
176 trivial &= savedAttrs.empty();
177 hasSavedAttrs = true;
180 /// Record that we had nowhere to put the given type attribute.
181 /// We will diagnose such attributes later.
182 void addIgnoredTypeAttr(AttributeList &attr) {
183 ignoredTypeAttrs.push_back(&attr);
186 /// Diagnose all the ignored type attributes, given that the
187 /// declarator worked out to the given type.
188 void diagnoseIgnoredTypeAttrs(QualType type) const {
189 for (SmallVectorImpl<AttributeList*>::const_iterator
190 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
192 diagnoseBadTypeAttribute(getSema(), **i, type);
195 ~TypeProcessingState() {
198 restoreDeclSpecAttrs();
202 DeclSpec &getMutableDeclSpec() const {
203 return const_cast<DeclSpec&>(declarator.getDeclSpec());
206 void restoreDeclSpecAttrs() {
207 assert(hasSavedAttrs);
209 if (savedAttrs.empty()) {
210 getMutableDeclSpec().getAttributes().set(0);
214 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
215 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
216 savedAttrs[i]->setNext(savedAttrs[i+1]);
217 savedAttrs.back()->setNext(0);
221 /// Basically std::pair except that we really want to avoid an
222 /// implicit operator= for safety concerns. It's also a minor
223 /// link-time optimization for this to be a private type.
226 AttributeList &first;
228 /// The head of the list the attribute is currently in.
229 AttributeList *&second;
231 AttrAndList(AttributeList &attr, AttributeList *&head)
232 : first(attr), second(head) {}
237 template <> struct isPodLike<AttrAndList> {
238 static const bool value = true;
242 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
247 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
249 head = attr.getNext();
253 AttributeList *cur = head;
255 assert(cur && cur->getNext() && "ran out of attrs?");
256 if (cur->getNext() == &attr) {
257 cur->setNext(attr.getNext());
260 cur = cur->getNext();
264 static void moveAttrFromListToList(AttributeList &attr,
265 AttributeList *&fromList,
266 AttributeList *&toList) {
267 spliceAttrOutOfList(attr, fromList);
268 spliceAttrIntoList(attr, toList);
271 static void processTypeAttrs(TypeProcessingState &state,
272 QualType &type, bool isDeclSpec,
273 AttributeList *attrs);
275 static bool handleFunctionTypeAttr(TypeProcessingState &state,
279 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
280 AttributeList &attr, QualType &type);
282 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
283 AttributeList &attr, QualType &type);
285 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
286 AttributeList &attr, QualType &type) {
287 if (attr.getKind() == AttributeList::AT_ObjCGC)
288 return handleObjCGCTypeAttr(state, attr, type);
289 assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
290 return handleObjCOwnershipTypeAttr(state, attr, type);
293 /// Given that an objc_gc attribute was written somewhere on a
294 /// declaration *other* than on the declarator itself (for which, use
295 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
296 /// didn't apply in whatever position it was written in, try to move
297 /// it to a more appropriate position.
298 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
301 Declarator &declarator = state.getDeclarator();
302 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
303 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
304 switch (chunk.Kind) {
305 case DeclaratorChunk::Pointer:
306 case DeclaratorChunk::BlockPointer:
307 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
308 chunk.getAttrListRef());
311 case DeclaratorChunk::Paren:
312 case DeclaratorChunk::Array:
315 // Don't walk through these.
316 case DeclaratorChunk::Reference:
317 case DeclaratorChunk::Function:
318 case DeclaratorChunk::MemberPointer:
324 diagnoseBadTypeAttribute(state.getSema(), attr, type);
327 /// Distribute an objc_gc type attribute that was written on the
330 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
332 QualType &declSpecType) {
333 Declarator &declarator = state.getDeclarator();
335 // objc_gc goes on the innermost pointer to something that's not a
337 unsigned innermost = -1U;
338 bool considerDeclSpec = true;
339 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
340 DeclaratorChunk &chunk = declarator.getTypeObject(i);
341 switch (chunk.Kind) {
342 case DeclaratorChunk::Pointer:
343 case DeclaratorChunk::BlockPointer:
347 case DeclaratorChunk::Reference:
348 case DeclaratorChunk::MemberPointer:
349 case DeclaratorChunk::Paren:
350 case DeclaratorChunk::Array:
353 case DeclaratorChunk::Function:
354 considerDeclSpec = false;
360 // That might actually be the decl spec if we weren't blocked by
361 // anything in the declarator.
362 if (considerDeclSpec) {
363 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
364 // Splice the attribute into the decl spec. Prevents the
365 // attribute from being applied multiple times and gives
366 // the source-location-filler something to work with.
367 state.saveDeclSpecAttrs();
368 moveAttrFromListToList(attr, declarator.getAttrListRef(),
369 declarator.getMutableDeclSpec().getAttributes().getListRef());
374 // Otherwise, if we found an appropriate chunk, splice the attribute
376 if (innermost != -1U) {
377 moveAttrFromListToList(attr, declarator.getAttrListRef(),
378 declarator.getTypeObject(innermost).getAttrListRef());
382 // Otherwise, diagnose when we're done building the type.
383 spliceAttrOutOfList(attr, declarator.getAttrListRef());
384 state.addIgnoredTypeAttr(attr);
387 /// A function type attribute was written somewhere in a declaration
388 /// *other* than on the declarator itself or in the decl spec. Given
389 /// that it didn't apply in whatever position it was written in, try
390 /// to move it to a more appropriate position.
391 static void distributeFunctionTypeAttr(TypeProcessingState &state,
394 Declarator &declarator = state.getDeclarator();
396 // Try to push the attribute from the return type of a function to
397 // the function itself.
398 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
399 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
400 switch (chunk.Kind) {
401 case DeclaratorChunk::Function:
402 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
403 chunk.getAttrListRef());
406 case DeclaratorChunk::Paren:
407 case DeclaratorChunk::Pointer:
408 case DeclaratorChunk::BlockPointer:
409 case DeclaratorChunk::Array:
410 case DeclaratorChunk::Reference:
411 case DeclaratorChunk::MemberPointer:
416 diagnoseBadTypeAttribute(state.getSema(), attr, type);
419 /// Try to distribute a function type attribute to the innermost
420 /// function chunk or type. Returns true if the attribute was
421 /// distributed, false if no location was found.
423 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
425 AttributeList *&attrList,
426 QualType &declSpecType) {
427 Declarator &declarator = state.getDeclarator();
429 // Put it on the innermost function chunk, if there is one.
430 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
431 DeclaratorChunk &chunk = declarator.getTypeObject(i);
432 if (chunk.Kind != DeclaratorChunk::Function) continue;
434 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
438 if (handleFunctionTypeAttr(state, attr, declSpecType)) {
439 spliceAttrOutOfList(attr, attrList);
446 /// A function type attribute was written in the decl spec. Try to
447 /// apply it somewhere.
449 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
451 QualType &declSpecType) {
452 state.saveDeclSpecAttrs();
454 // Try to distribute to the innermost.
455 if (distributeFunctionTypeAttrToInnermost(state, attr,
456 state.getCurrentAttrListRef(),
460 // If that failed, diagnose the bad attribute when the declarator is
462 state.addIgnoredTypeAttr(attr);
465 /// A function type attribute was written on the declarator. Try to
466 /// apply it somewhere.
468 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
470 QualType &declSpecType) {
471 Declarator &declarator = state.getDeclarator();
473 // Try to distribute to the innermost.
474 if (distributeFunctionTypeAttrToInnermost(state, attr,
475 declarator.getAttrListRef(),
479 // If that failed, diagnose the bad attribute when the declarator is
481 spliceAttrOutOfList(attr, declarator.getAttrListRef());
482 state.addIgnoredTypeAttr(attr);
485 /// \brief Given that there are attributes written on the declarator
486 /// itself, try to distribute any type attributes to the appropriate
487 /// declarator chunk.
489 /// These are attributes like the following:
492 /// but not necessarily this:
494 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
495 QualType &declSpecType) {
496 // Collect all the type attributes from the declarator itself.
497 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
498 AttributeList *attr = state.getDeclarator().getAttributes();
501 next = attr->getNext();
503 switch (attr->getKind()) {
504 OBJC_POINTER_TYPE_ATTRS_CASELIST:
505 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
508 case AttributeList::AT_NSReturnsRetained:
509 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
513 FUNCTION_TYPE_ATTRS_CASELIST:
514 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
520 } while ((attr = next));
523 /// Add a synthetic '()' to a block-literal declarator if it is
524 /// required, given the return type.
525 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
526 QualType declSpecType) {
527 Declarator &declarator = state.getDeclarator();
529 // First, check whether the declarator would produce a function,
530 // i.e. whether the innermost semantic chunk is a function.
531 if (declarator.isFunctionDeclarator()) {
532 // If so, make that declarator a prototyped declarator.
533 declarator.getFunctionTypeInfo().hasPrototype = true;
537 // If there are any type objects, the type as written won't name a
538 // function, regardless of the decl spec type. This is because a
539 // block signature declarator is always an abstract-declarator, and
540 // abstract-declarators can't just be parentheses chunks. Therefore
541 // we need to build a function chunk unless there are no type
542 // objects and the decl spec type is a function.
543 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
546 // Note that there *are* cases with invalid declarators where
547 // declarators consist solely of parentheses. In general, these
548 // occur only in failed efforts to make function declarators, so
549 // faking up the function chunk is still the right thing to do.
551 // Otherwise, we need to fake up a function declarator.
552 SourceLocation loc = declarator.getLocStart();
554 // ...and *prepend* it to the declarator.
555 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
558 /*ambiguous*/ false, SourceLocation(),
561 /*ref-qualifier*/true, SourceLocation(),
562 /*const qualifier*/SourceLocation(),
563 /*volatile qualifier*/SourceLocation(),
564 /*mutable qualifier*/SourceLocation(),
565 /*EH*/ EST_None, SourceLocation(), 0, 0, 0, 0,
569 // For consistency, make sure the state still has us as processing
571 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
572 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
575 /// \brief Convert the specified declspec to the appropriate type
577 /// \param state Specifies the declarator containing the declaration specifier
578 /// to be converted, along with other associated processing state.
579 /// \returns The type described by the declaration specifiers. This function
580 /// never returns null.
581 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
582 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
585 Sema &S = state.getSema();
586 Declarator &declarator = state.getDeclarator();
587 const DeclSpec &DS = declarator.getDeclSpec();
588 SourceLocation DeclLoc = declarator.getIdentifierLoc();
589 if (DeclLoc.isInvalid())
590 DeclLoc = DS.getLocStart();
592 ASTContext &Context = S.Context;
595 switch (DS.getTypeSpecType()) {
596 case DeclSpec::TST_void:
597 Result = Context.VoidTy;
599 case DeclSpec::TST_char:
600 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
601 Result = Context.CharTy;
602 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
603 Result = Context.SignedCharTy;
605 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
606 "Unknown TSS value");
607 Result = Context.UnsignedCharTy;
610 case DeclSpec::TST_wchar:
611 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
612 Result = Context.WCharTy;
613 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
614 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
615 << DS.getSpecifierName(DS.getTypeSpecType());
616 Result = Context.getSignedWCharType();
618 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
619 "Unknown TSS value");
620 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
621 << DS.getSpecifierName(DS.getTypeSpecType());
622 Result = Context.getUnsignedWCharType();
625 case DeclSpec::TST_char16:
626 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
627 "Unknown TSS value");
628 Result = Context.Char16Ty;
630 case DeclSpec::TST_char32:
631 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
632 "Unknown TSS value");
633 Result = Context.Char32Ty;
635 case DeclSpec::TST_unspecified:
636 // "<proto1,proto2>" is an objc qualified ID with a missing id.
637 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
638 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
639 (ObjCProtocolDecl**)PQ,
640 DS.getNumProtocolQualifiers());
641 Result = Context.getObjCObjectPointerType(Result);
645 // If this is a missing declspec in a block literal return context, then it
646 // is inferred from the return statements inside the block.
647 // The declspec is always missing in a lambda expr context; it is either
648 // specified with a trailing return type or inferred.
649 if (declarator.getContext() == Declarator::LambdaExprContext ||
650 isOmittedBlockReturnType(declarator)) {
651 Result = Context.DependentTy;
655 // Unspecified typespec defaults to int in C90. However, the C90 grammar
656 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
657 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
658 // Note that the one exception to this is function definitions, which are
659 // allowed to be completely missing a declspec. This is handled in the
660 // parser already though by it pretending to have seen an 'int' in this
662 if (S.getLangOpts().ImplicitInt) {
663 // In C89 mode, we only warn if there is a completely missing declspec
664 // when one is not allowed.
666 S.Diag(DeclLoc, diag::ext_missing_declspec)
667 << DS.getSourceRange()
668 << FixItHint::CreateInsertion(DS.getLocStart(), "int");
670 } else if (!DS.hasTypeSpecifier()) {
671 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
672 // "At least one type specifier shall be given in the declaration
673 // specifiers in each declaration, and in the specifier-qualifier list in
674 // each struct declaration and type name."
675 // FIXME: Does Microsoft really have the implicit int extension in C++?
676 if (S.getLangOpts().CPlusPlus &&
677 !S.getLangOpts().MicrosoftExt) {
678 S.Diag(DeclLoc, diag::err_missing_type_specifier)
679 << DS.getSourceRange();
681 // When this occurs in C++ code, often something is very broken with the
682 // value being declared, poison it as invalid so we don't get chains of
684 declarator.setInvalidType(true);
686 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
687 << DS.getSourceRange();
692 case DeclSpec::TST_int: {
693 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
694 switch (DS.getTypeSpecWidth()) {
695 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
696 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
697 case DeclSpec::TSW_long: Result = Context.LongTy; break;
698 case DeclSpec::TSW_longlong:
699 Result = Context.LongLongTy;
701 // long long is a C99 feature.
702 if (!S.getLangOpts().C99)
703 S.Diag(DS.getTypeSpecWidthLoc(),
704 S.getLangOpts().CPlusPlus0x ?
705 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
709 switch (DS.getTypeSpecWidth()) {
710 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
711 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
712 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
713 case DeclSpec::TSW_longlong:
714 Result = Context.UnsignedLongLongTy;
716 // long long is a C99 feature.
717 if (!S.getLangOpts().C99)
718 S.Diag(DS.getTypeSpecWidthLoc(),
719 S.getLangOpts().CPlusPlus0x ?
720 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
726 case DeclSpec::TST_int128:
727 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
728 Result = Context.UnsignedInt128Ty;
730 Result = Context.Int128Ty;
732 case DeclSpec::TST_half: Result = Context.HalfTy; break;
733 case DeclSpec::TST_float: Result = Context.FloatTy; break;
734 case DeclSpec::TST_double:
735 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
736 Result = Context.LongDoubleTy;
738 Result = Context.DoubleTy;
740 if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
741 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
742 declarator.setInvalidType(true);
745 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
746 case DeclSpec::TST_decimal32: // _Decimal32
747 case DeclSpec::TST_decimal64: // _Decimal64
748 case DeclSpec::TST_decimal128: // _Decimal128
749 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
750 Result = Context.IntTy;
751 declarator.setInvalidType(true);
753 case DeclSpec::TST_class:
754 case DeclSpec::TST_enum:
755 case DeclSpec::TST_union:
756 case DeclSpec::TST_struct: {
757 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
759 // This can happen in C++ with ambiguous lookups.
760 Result = Context.IntTy;
761 declarator.setInvalidType(true);
765 // If the type is deprecated or unavailable, diagnose it.
766 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
768 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
769 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
771 // TypeQuals handled by caller.
772 Result = Context.getTypeDeclType(D);
774 // In both C and C++, make an ElaboratedType.
775 ElaboratedTypeKeyword Keyword
776 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
777 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
780 case DeclSpec::TST_typename: {
781 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
782 DS.getTypeSpecSign() == 0 &&
783 "Can't handle qualifiers on typedef names yet!");
784 Result = S.GetTypeFromParser(DS.getRepAsType());
786 declarator.setInvalidType(true);
787 else if (DeclSpec::ProtocolQualifierListTy PQ
788 = DS.getProtocolQualifiers()) {
789 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
790 // Silently drop any existing protocol qualifiers.
791 // TODO: determine whether that's the right thing to do.
792 if (ObjT->getNumProtocols())
793 Result = ObjT->getBaseType();
795 if (DS.getNumProtocolQualifiers())
796 Result = Context.getObjCObjectType(Result,
797 (ObjCProtocolDecl**) PQ,
798 DS.getNumProtocolQualifiers());
799 } else if (Result->isObjCIdType()) {
801 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
802 (ObjCProtocolDecl**) PQ,
803 DS.getNumProtocolQualifiers());
804 Result = Context.getObjCObjectPointerType(Result);
805 } else if (Result->isObjCClassType()) {
806 // Class<protocol-list>
807 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
808 (ObjCProtocolDecl**) PQ,
809 DS.getNumProtocolQualifiers());
810 Result = Context.getObjCObjectPointerType(Result);
812 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
813 << DS.getSourceRange();
814 declarator.setInvalidType(true);
818 // TypeQuals handled by caller.
821 case DeclSpec::TST_typeofType:
822 // FIXME: Preserve type source info.
823 Result = S.GetTypeFromParser(DS.getRepAsType());
824 assert(!Result.isNull() && "Didn't get a type for typeof?");
825 if (!Result->isDependentType())
826 if (const TagType *TT = Result->getAs<TagType>())
827 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
828 // TypeQuals handled by caller.
829 Result = Context.getTypeOfType(Result);
831 case DeclSpec::TST_typeofExpr: {
832 Expr *E = DS.getRepAsExpr();
833 assert(E && "Didn't get an expression for typeof?");
834 // TypeQuals handled by caller.
835 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
836 if (Result.isNull()) {
837 Result = Context.IntTy;
838 declarator.setInvalidType(true);
842 case DeclSpec::TST_decltype: {
843 Expr *E = DS.getRepAsExpr();
844 assert(E && "Didn't get an expression for decltype?");
845 // TypeQuals handled by caller.
846 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
847 if (Result.isNull()) {
848 Result = Context.IntTy;
849 declarator.setInvalidType(true);
853 case DeclSpec::TST_underlyingType:
854 Result = S.GetTypeFromParser(DS.getRepAsType());
855 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
856 Result = S.BuildUnaryTransformType(Result,
857 UnaryTransformType::EnumUnderlyingType,
858 DS.getTypeSpecTypeLoc());
859 if (Result.isNull()) {
860 Result = Context.IntTy;
861 declarator.setInvalidType(true);
865 case DeclSpec::TST_auto: {
866 // TypeQuals handled by caller.
867 Result = Context.getAutoType(QualType());
871 case DeclSpec::TST_unknown_anytype:
872 Result = Context.UnknownAnyTy;
875 case DeclSpec::TST_atomic:
876 Result = S.GetTypeFromParser(DS.getRepAsType());
877 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
878 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
879 if (Result.isNull()) {
880 Result = Context.IntTy;
881 declarator.setInvalidType(true);
885 case DeclSpec::TST_error:
886 Result = Context.IntTy;
887 declarator.setInvalidType(true);
891 // Handle complex types.
892 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
893 if (S.getLangOpts().Freestanding)
894 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
895 Result = Context.getComplexType(Result);
896 } else if (DS.isTypeAltiVecVector()) {
897 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
898 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
899 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
900 if (DS.isTypeAltiVecPixel())
901 VecKind = VectorType::AltiVecPixel;
902 else if (DS.isTypeAltiVecBool())
903 VecKind = VectorType::AltiVecBool;
904 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
908 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
909 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
911 // Before we process any type attributes, synthesize a block literal
912 // function declarator if necessary.
913 if (declarator.getContext() == Declarator::BlockLiteralContext)
914 maybeSynthesizeBlockSignature(state, Result);
916 // Apply any type attributes from the decl spec. This may cause the
917 // list of type attributes to be temporarily saved while the type
918 // attributes are pushed around.
919 if (AttributeList *attrs = DS.getAttributes().getList())
920 processTypeAttrs(state, Result, true, attrs);
922 // Apply const/volatile/restrict qualifiers to T.
923 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
925 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
926 // or incomplete types shall not be restrict-qualified." C++ also allows
927 // restrict-qualified references.
928 if (TypeQuals & DeclSpec::TQ_restrict) {
929 if (Result->isAnyPointerType() || Result->isReferenceType()) {
931 if (Result->isObjCObjectPointerType())
934 EltTy = Result->isPointerType() ?
935 Result->getAs<PointerType>()->getPointeeType() :
936 Result->getAs<ReferenceType>()->getPointeeType();
938 // If we have a pointer or reference, the pointee must have an object
940 if (!EltTy->isIncompleteOrObjectType()) {
941 S.Diag(DS.getRestrictSpecLoc(),
942 diag::err_typecheck_invalid_restrict_invalid_pointee)
943 << EltTy << DS.getSourceRange();
944 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
947 S.Diag(DS.getRestrictSpecLoc(),
948 diag::err_typecheck_invalid_restrict_not_pointer)
949 << Result << DS.getSourceRange();
950 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
954 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
955 // of a function type includes any type qualifiers, the behavior is
957 if (Result->isFunctionType() && TypeQuals) {
958 // Get some location to point at, either the C or V location.
960 if (TypeQuals & DeclSpec::TQ_const)
961 Loc = DS.getConstSpecLoc();
962 else if (TypeQuals & DeclSpec::TQ_volatile)
963 Loc = DS.getVolatileSpecLoc();
965 assert((TypeQuals & DeclSpec::TQ_restrict) &&
966 "Has CVR quals but not C, V, or R?");
967 Loc = DS.getRestrictSpecLoc();
969 S.Diag(Loc, diag::warn_typecheck_function_qualifiers)
970 << Result << DS.getSourceRange();
974 // Cv-qualified references are ill-formed except when the
975 // cv-qualifiers are introduced through the use of a typedef
976 // (7.1.3) or of a template type argument (14.3), in which
977 // case the cv-qualifiers are ignored.
978 // FIXME: Shouldn't we be checking SCS_typedef here?
979 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
980 TypeQuals && Result->isReferenceType()) {
981 TypeQuals &= ~DeclSpec::TQ_const;
982 TypeQuals &= ~DeclSpec::TQ_volatile;
985 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
986 // than once in the same specifier-list or qualifier-list, either directly
987 // or via one or more typedefs."
988 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
989 && TypeQuals & Result.getCVRQualifiers()) {
990 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
991 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
995 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
996 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1000 // C90 doesn't have restrict, so it doesn't force us to produce a warning
1004 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
1005 Result = Context.getQualifiedType(Result, Quals);
1011 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1013 return Entity.getAsString();
1018 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1020 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1021 // object or incomplete types shall not be restrict-qualified."
1022 if (Qs.hasRestrict()) {
1023 unsigned DiagID = 0;
1026 const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
1027 if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) {
1028 if (!RTy->getPointeeType()->isIncompleteOrObjectType()) {
1029 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1030 ProblemTy = T->getAs<ReferenceType>()->getPointeeType();
1032 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
1033 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
1034 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1035 ProblemTy = T->getAs<PointerType>()->getPointeeType();
1037 } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) {
1038 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
1039 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1040 ProblemTy = T->getAs<PointerType>()->getPointeeType();
1042 } else if (!Ty->isDependentType()) {
1043 // FIXME: this deserves a proper diagnostic
1044 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1049 Diag(Loc, DiagID) << ProblemTy;
1050 Qs.removeRestrict();
1054 return Context.getQualifiedType(T, Qs);
1057 /// \brief Build a paren type including \p T.
1058 QualType Sema::BuildParenType(QualType T) {
1059 return Context.getParenType(T);
1062 /// Given that we're building a pointer or reference to the given
1063 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1066 // Bail out if retention is unrequired or already specified.
1067 if (!type->isObjCLifetimeType() ||
1068 type.getObjCLifetime() != Qualifiers::OCL_None)
1071 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1073 // If the object type is const-qualified, we can safely use
1074 // __unsafe_unretained. This is safe (because there are no read
1075 // barriers), and it'll be safe to coerce anything but __weak* to
1076 // the resulting type.
1077 if (type.isConstQualified()) {
1078 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1080 // Otherwise, check whether the static type does not require
1081 // retaining. This currently only triggers for Class (possibly
1082 // protocol-qualifed, and arrays thereof).
1083 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1084 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1086 // If we are in an unevaluated context, like sizeof, skip adding a
1088 } else if (S.isUnevaluatedContext()) {
1091 // If that failed, give an error and recover using __strong. __strong
1092 // is the option most likely to prevent spurious second-order diagnostics,
1093 // like when binding a reference to a field.
1095 // These types can show up in private ivars in system headers, so
1096 // we need this to not be an error in those cases. Instead we
1098 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1099 S.DelayedDiagnostics.add(
1100 sema::DelayedDiagnostic::makeForbiddenType(loc,
1101 diag::err_arc_indirect_no_ownership, type, isReference));
1103 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1105 implicitLifetime = Qualifiers::OCL_Strong;
1107 assert(implicitLifetime && "didn't infer any lifetime!");
1110 qs.addObjCLifetime(implicitLifetime);
1111 return S.Context.getQualifiedType(type, qs);
1114 /// \brief Build a pointer type.
1116 /// \param T The type to which we'll be building a pointer.
1118 /// \param Loc The location of the entity whose type involves this
1119 /// pointer type or, if there is no such entity, the location of the
1120 /// type that will have pointer type.
1122 /// \param Entity The name of the entity that involves the pointer
1125 /// \returns A suitable pointer type, if there are no
1126 /// errors. Otherwise, returns a NULL type.
1127 QualType Sema::BuildPointerType(QualType T,
1128 SourceLocation Loc, DeclarationName Entity) {
1129 if (T->isReferenceType()) {
1130 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1131 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1132 << getPrintableNameForEntity(Entity) << T;
1136 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1138 // In ARC, it is forbidden to build pointers to unqualified pointers.
1139 if (getLangOpts().ObjCAutoRefCount)
1140 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1142 // Build the pointer type.
1143 return Context.getPointerType(T);
1146 /// \brief Build a reference type.
1148 /// \param T The type to which we'll be building a reference.
1150 /// \param Loc The location of the entity whose type involves this
1151 /// reference type or, if there is no such entity, the location of the
1152 /// type that will have reference type.
1154 /// \param Entity The name of the entity that involves the reference
1157 /// \returns A suitable reference type, if there are no
1158 /// errors. Otherwise, returns a NULL type.
1159 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1161 DeclarationName Entity) {
1162 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1163 "Unresolved overloaded function type");
1165 // C++0x [dcl.ref]p6:
1166 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1167 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1168 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1169 // the type "lvalue reference to T", while an attempt to create the type
1170 // "rvalue reference to cv TR" creates the type TR.
1171 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1173 // C++ [dcl.ref]p4: There shall be no references to references.
1175 // According to C++ DR 106, references to references are only
1176 // diagnosed when they are written directly (e.g., "int & &"),
1177 // but not when they happen via a typedef:
1179 // typedef int& intref;
1180 // typedef intref& intref2;
1182 // Parser::ParseDeclaratorInternal diagnoses the case where
1183 // references are written directly; here, we handle the
1184 // collapsing of references-to-references as described in C++0x.
1185 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1188 // A declarator that specifies the type "reference to cv void"
1190 if (T->isVoidType()) {
1191 Diag(Loc, diag::err_reference_to_void);
1195 // In ARC, it is forbidden to build references to unqualified pointers.
1196 if (getLangOpts().ObjCAutoRefCount)
1197 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1199 // Handle restrict on references.
1201 return Context.getLValueReferenceType(T, SpelledAsLValue);
1202 return Context.getRValueReferenceType(T);
1205 /// Check whether the specified array size makes the array type a VLA. If so,
1206 /// return true, if not, return the size of the array in SizeVal.
1207 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1208 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1209 // (like gnu99, but not c99) accept any evaluatable value as an extension.
1210 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1212 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
1214 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1217 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) {
1218 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
1222 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
1223 S.LangOpts.GNUMode).isInvalid();
1227 /// \brief Build an array type.
1229 /// \param T The type of each element in the array.
1231 /// \param ASM C99 array size modifier (e.g., '*', 'static').
1233 /// \param ArraySize Expression describing the size of the array.
1235 /// \param Brackets The range from the opening '[' to the closing ']'.
1237 /// \param Entity The name of the entity that involves the array
1240 /// \returns A suitable array type, if there are no errors. Otherwise,
1241 /// returns a NULL type.
1242 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1243 Expr *ArraySize, unsigned Quals,
1244 SourceRange Brackets, DeclarationName Entity) {
1246 SourceLocation Loc = Brackets.getBegin();
1247 if (getLangOpts().CPlusPlus) {
1248 // C++ [dcl.array]p1:
1249 // T is called the array element type; this type shall not be a reference
1250 // type, the (possibly cv-qualified) type void, a function type or an
1251 // abstract class type.
1253 // C++ [dcl.array]p3:
1254 // When several "array of" specifications are adjacent, [...] only the
1255 // first of the constant expressions that specify the bounds of the arrays
1258 // Note: function types are handled in the common path with C.
1259 if (T->isReferenceType()) {
1260 Diag(Loc, diag::err_illegal_decl_array_of_references)
1261 << getPrintableNameForEntity(Entity) << T;
1265 if (T->isVoidType() || T->isIncompleteArrayType()) {
1266 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1270 if (RequireNonAbstractType(Brackets.getBegin(), T,
1271 diag::err_array_of_abstract_type))
1275 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1276 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
1277 if (RequireCompleteType(Loc, T,
1278 diag::err_illegal_decl_array_incomplete_type))
1282 if (T->isFunctionType()) {
1283 Diag(Loc, diag::err_illegal_decl_array_of_functions)
1284 << getPrintableNameForEntity(Entity) << T;
1288 if (T->getContainedAutoType()) {
1289 Diag(Loc, diag::err_illegal_decl_array_of_auto)
1290 << getPrintableNameForEntity(Entity) << T;
1294 if (const RecordType *EltTy = T->getAs<RecordType>()) {
1295 // If the element type is a struct or union that contains a variadic
1296 // array, accept it as a GNU extension: C99 6.7.2.1p2.
1297 if (EltTy->getDecl()->hasFlexibleArrayMember())
1298 Diag(Loc, diag::ext_flexible_array_in_array) << T;
1299 } else if (T->isObjCObjectType()) {
1300 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1304 // Do placeholder conversions on the array size expression.
1305 if (ArraySize && ArraySize->hasPlaceholderType()) {
1306 ExprResult Result = CheckPlaceholderExpr(ArraySize);
1307 if (Result.isInvalid()) return QualType();
1308 ArraySize = Result.take();
1311 // Do lvalue-to-rvalue conversions on the array size expression.
1312 if (ArraySize && !ArraySize->isRValue()) {
1313 ExprResult Result = DefaultLvalueConversion(ArraySize);
1314 if (Result.isInvalid())
1317 ArraySize = Result.take();
1320 // C99 6.7.5.2p1: The size expression shall have integer type.
1321 // C++11 allows contextual conversions to such types.
1322 if (!getLangOpts().CPlusPlus0x &&
1323 ArraySize && !ArraySize->isTypeDependent() &&
1324 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1325 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1326 << ArraySize->getType() << ArraySize->getSourceRange();
1330 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
1332 if (ASM == ArrayType::Star)
1333 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
1335 T = Context.getIncompleteArrayType(T, ASM, Quals);
1336 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
1337 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
1338 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
1339 !T->isConstantSizeType()) ||
1340 isArraySizeVLA(*this, ArraySize, ConstVal)) {
1341 // Even in C++11, don't allow contextual conversions in the array bound
1343 if (getLangOpts().CPlusPlus0x &&
1344 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1345 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1346 << ArraySize->getType() << ArraySize->getSourceRange();
1350 // C99: an array with an element type that has a non-constant-size is a VLA.
1351 // C99: an array with a non-ICE size is a VLA. We accept any expression
1352 // that we can fold to a non-zero positive value as an extension.
1353 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1355 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1356 // have a value greater than zero.
1357 if (ConstVal.isSigned() && ConstVal.isNegative()) {
1359 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1360 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1362 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1363 << ArraySize->getSourceRange();
1366 if (ConstVal == 0) {
1367 // GCC accepts zero sized static arrays. We allow them when
1368 // we're not in a SFINAE context.
1369 Diag(ArraySize->getLocStart(),
1370 isSFINAEContext()? diag::err_typecheck_zero_array_size
1371 : diag::ext_typecheck_zero_array_size)
1372 << ArraySize->getSourceRange();
1374 if (ASM == ArrayType::Static) {
1375 Diag(ArraySize->getLocStart(),
1376 diag::warn_typecheck_zero_static_array_size)
1377 << ArraySize->getSourceRange();
1378 ASM = ArrayType::Normal;
1380 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1381 !T->isIncompleteType()) {
1382 // Is the array too large?
1383 unsigned ActiveSizeBits
1384 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1385 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1386 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1387 << ConstVal.toString(10)
1388 << ArraySize->getSourceRange();
1391 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
1393 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1394 if (!getLangOpts().C99) {
1395 if (T->isVariableArrayType()) {
1396 // Prohibit the use of non-POD types in VLAs.
1397 QualType BaseT = Context.getBaseElementType(T);
1398 if (!T->isDependentType() &&
1399 !BaseT.isPODType(Context) &&
1400 !BaseT->isObjCLifetimeType()) {
1401 Diag(Loc, diag::err_vla_non_pod)
1405 // Prohibit the use of VLAs during template argument deduction.
1406 else if (isSFINAEContext()) {
1407 Diag(Loc, diag::err_vla_in_sfinae);
1410 // Just extwarn about VLAs.
1412 Diag(Loc, diag::ext_vla);
1413 } else if (ASM != ArrayType::Normal || Quals != 0)
1415 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
1416 : diag::ext_c99_array_usage) << ASM;
1422 /// \brief Build an ext-vector type.
1424 /// Run the required checks for the extended vector type.
1425 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
1426 SourceLocation AttrLoc) {
1427 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1428 // in conjunction with complex types (pointers, arrays, functions, etc.).
1429 if (!T->isDependentType() &&
1430 !T->isIntegerType() && !T->isRealFloatingType()) {
1431 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1435 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
1436 llvm::APSInt vecSize(32);
1437 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
1438 Diag(AttrLoc, diag::err_attribute_argument_not_int)
1439 << "ext_vector_type" << ArraySize->getSourceRange();
1443 // unlike gcc's vector_size attribute, the size is specified as the
1444 // number of elements, not the number of bytes.
1445 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1447 if (vectorSize == 0) {
1448 Diag(AttrLoc, diag::err_attribute_zero_size)
1449 << ArraySize->getSourceRange();
1453 return Context.getExtVectorType(T, vectorSize);
1456 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
1459 /// \brief Build a function type.
1461 /// This routine checks the function type according to C++ rules and
1462 /// under the assumption that the result type and parameter types have
1463 /// just been instantiated from a template. It therefore duplicates
1464 /// some of the behavior of GetTypeForDeclarator, but in a much
1465 /// simpler form that is only suitable for this narrow use case.
1467 /// \param T The return type of the function.
1469 /// \param ParamTypes The parameter types of the function. This array
1470 /// will be modified to account for adjustments to the types of the
1471 /// function parameters.
1473 /// \param NumParamTypes The number of parameter types in ParamTypes.
1475 /// \param Variadic Whether this is a variadic function type.
1477 /// \param HasTrailingReturn Whether this function has a trailing return type.
1479 /// \param Quals The cvr-qualifiers to be applied to the function type.
1481 /// \param Loc The location of the entity whose type involves this
1482 /// function type or, if there is no such entity, the location of the
1483 /// type that will have function type.
1485 /// \param Entity The name of the entity that involves the function
1488 /// \returns A suitable function type, if there are no
1489 /// errors. Otherwise, returns a NULL type.
1490 QualType Sema::BuildFunctionType(QualType T,
1491 QualType *ParamTypes,
1492 unsigned NumParamTypes,
1493 bool Variadic, bool HasTrailingReturn,
1495 RefQualifierKind RefQualifier,
1496 SourceLocation Loc, DeclarationName Entity,
1497 FunctionType::ExtInfo Info) {
1498 if (T->isArrayType() || T->isFunctionType()) {
1499 Diag(Loc, diag::err_func_returning_array_function)
1500 << T->isFunctionType() << T;
1504 // Functions cannot return half FP.
1505 if (T->isHalfType()) {
1506 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
1507 FixItHint::CreateInsertion(Loc, "*");
1511 bool Invalid = false;
1512 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
1513 // FIXME: Loc is too inprecise here, should use proper locations for args.
1514 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
1515 if (ParamType->isVoidType()) {
1516 Diag(Loc, diag::err_param_with_void_type);
1518 } else if (ParamType->isHalfType()) {
1519 // Disallow half FP arguments.
1520 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
1521 FixItHint::CreateInsertion(Loc, "*");
1525 ParamTypes[Idx] = ParamType;
1531 FunctionProtoType::ExtProtoInfo EPI;
1532 EPI.Variadic = Variadic;
1533 EPI.HasTrailingReturn = HasTrailingReturn;
1534 EPI.TypeQuals = Quals;
1535 EPI.RefQualifier = RefQualifier;
1538 return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI);
1541 /// \brief Build a member pointer type \c T Class::*.
1543 /// \param T the type to which the member pointer refers.
1544 /// \param Class the class type into which the member pointer points.
1545 /// \param Loc the location where this type begins
1546 /// \param Entity the name of the entity that will have this member pointer type
1548 /// \returns a member pointer type, if successful, or a NULL type if there was
1550 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
1552 DeclarationName Entity) {
1553 // Verify that we're not building a pointer to pointer to function with
1554 // exception specification.
1555 if (CheckDistantExceptionSpec(T)) {
1556 Diag(Loc, diag::err_distant_exception_spec);
1558 // FIXME: If we're doing this as part of template instantiation,
1559 // we should return immediately.
1561 // Build the type anyway, but use the canonical type so that the
1562 // exception specifiers are stripped off.
1563 T = Context.getCanonicalType(T);
1566 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
1567 // with reference type, or "cv void."
1568 if (T->isReferenceType()) {
1569 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
1570 << (Entity? Entity.getAsString() : "type name") << T;
1574 if (T->isVoidType()) {
1575 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1576 << (Entity? Entity.getAsString() : "type name");
1580 if (!Class->isDependentType() && !Class->isRecordType()) {
1581 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1585 // In the Microsoft ABI, the class is allowed to be an incomplete
1586 // type. In such cases, the compiler makes a worst-case assumption.
1587 // We make no such assumption right now, so emit an error if the
1588 // class isn't a complete type.
1589 if (Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft &&
1590 RequireCompleteType(Loc, Class, diag::err_incomplete_type))
1593 return Context.getMemberPointerType(T, Class.getTypePtr());
1596 /// \brief Build a block pointer type.
1598 /// \param T The type to which we'll be building a block pointer.
1600 /// \param Loc The source location, used for diagnostics.
1602 /// \param Entity The name of the entity that involves the block pointer
1605 /// \returns A suitable block pointer type, if there are no
1606 /// errors. Otherwise, returns a NULL type.
1607 QualType Sema::BuildBlockPointerType(QualType T,
1609 DeclarationName Entity) {
1610 if (!T->isFunctionType()) {
1611 Diag(Loc, diag::err_nonfunction_block_type);
1615 return Context.getBlockPointerType(T);
1618 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1619 QualType QT = Ty.get();
1621 if (TInfo) *TInfo = 0;
1625 TypeSourceInfo *DI = 0;
1626 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
1627 QT = LIT->getType();
1628 DI = LIT->getTypeSourceInfo();
1631 if (TInfo) *TInfo = DI;
1635 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1636 Qualifiers::ObjCLifetime ownership,
1637 unsigned chunkIndex);
1639 /// Given that this is the declaration of a parameter under ARC,
1640 /// attempt to infer attributes and such for pointer-to-whatever
1642 static void inferARCWriteback(TypeProcessingState &state,
1643 QualType &declSpecType) {
1644 Sema &S = state.getSema();
1645 Declarator &declarator = state.getDeclarator();
1647 // TODO: should we care about decl qualifiers?
1649 // Check whether the declarator has the expected form. We walk
1650 // from the inside out in order to make the block logic work.
1651 unsigned outermostPointerIndex = 0;
1652 bool isBlockPointer = false;
1653 unsigned numPointers = 0;
1654 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1655 unsigned chunkIndex = i;
1656 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1657 switch (chunk.Kind) {
1658 case DeclaratorChunk::Paren:
1662 case DeclaratorChunk::Reference:
1663 case DeclaratorChunk::Pointer:
1664 // Count the number of pointers. Treat references
1665 // interchangeably as pointers; if they're mis-ordered, normal
1666 // type building will discover that.
1667 outermostPointerIndex = chunkIndex;
1671 case DeclaratorChunk::BlockPointer:
1672 // If we have a pointer to block pointer, that's an acceptable
1673 // indirect reference; anything else is not an application of
1675 if (numPointers != 1) return;
1677 outermostPointerIndex = chunkIndex;
1678 isBlockPointer = true;
1680 // We don't care about pointer structure in return values here.
1683 case DeclaratorChunk::Array: // suppress if written (id[])?
1684 case DeclaratorChunk::Function:
1685 case DeclaratorChunk::MemberPointer:
1691 // If we have *one* pointer, then we want to throw the qualifier on
1692 // the declaration-specifiers, which means that it needs to be a
1693 // retainable object type.
1694 if (numPointers == 1) {
1695 // If it's not a retainable object type, the rule doesn't apply.
1696 if (!declSpecType->isObjCRetainableType()) return;
1698 // If it already has lifetime, don't do anything.
1699 if (declSpecType.getObjCLifetime()) return;
1701 // Otherwise, modify the type in-place.
1704 if (declSpecType->isObjCARCImplicitlyUnretainedType())
1705 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
1707 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
1708 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
1710 // If we have *two* pointers, then we want to throw the qualifier on
1711 // the outermost pointer.
1712 } else if (numPointers == 2) {
1713 // If we don't have a block pointer, we need to check whether the
1714 // declaration-specifiers gave us something that will turn into a
1715 // retainable object pointer after we slap the first pointer on it.
1716 if (!isBlockPointer && !declSpecType->isObjCObjectType())
1719 // Look for an explicit lifetime attribute there.
1720 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
1721 if (chunk.Kind != DeclaratorChunk::Pointer &&
1722 chunk.Kind != DeclaratorChunk::BlockPointer)
1724 for (const AttributeList *attr = chunk.getAttrs(); attr;
1725 attr = attr->getNext())
1726 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
1729 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
1730 outermostPointerIndex);
1732 // Any other number of pointers/references does not trigger the rule.
1735 // TODO: mark whether we did this inference?
1738 static void DiagnoseIgnoredQualifiers(unsigned Quals,
1739 SourceLocation ConstQualLoc,
1740 SourceLocation VolatileQualLoc,
1741 SourceLocation RestrictQualLoc,
1743 std::string QualStr;
1744 unsigned NumQuals = 0;
1747 FixItHint ConstFixIt;
1748 FixItHint VolatileFixIt;
1749 FixItHint RestrictFixIt;
1751 const SourceManager &SM = S.getSourceManager();
1753 // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to
1754 // find a range and grow it to encompass all the qualifiers, regardless of
1755 // the order in which they textually appear.
1756 if (Quals & Qualifiers::Const) {
1757 ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc);
1760 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc))
1763 if (Quals & Qualifiers::Volatile) {
1764 VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc);
1765 QualStr += (NumQuals == 0 ? "volatile" : " volatile");
1767 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc))
1768 Loc = VolatileQualLoc;
1770 if (Quals & Qualifiers::Restrict) {
1771 RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc);
1772 QualStr += (NumQuals == 0 ? "restrict" : " restrict");
1774 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc))
1775 Loc = RestrictQualLoc;
1778 assert(NumQuals > 0 && "No known qualifiers?");
1780 S.Diag(Loc, diag::warn_qual_return_type)
1781 << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt;
1784 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
1785 TypeSourceInfo *&ReturnTypeInfo) {
1786 Sema &SemaRef = state.getSema();
1787 Declarator &D = state.getDeclarator();
1791 // The TagDecl owned by the DeclSpec.
1792 TagDecl *OwnedTagDecl = 0;
1794 switch (D.getName().getKind()) {
1795 case UnqualifiedId::IK_ImplicitSelfParam:
1796 case UnqualifiedId::IK_OperatorFunctionId:
1797 case UnqualifiedId::IK_Identifier:
1798 case UnqualifiedId::IK_LiteralOperatorId:
1799 case UnqualifiedId::IK_TemplateId:
1800 T = ConvertDeclSpecToType(state);
1802 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
1803 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
1804 // Owned declaration is embedded in declarator.
1805 OwnedTagDecl->setEmbeddedInDeclarator(true);
1809 case UnqualifiedId::IK_ConstructorName:
1810 case UnqualifiedId::IK_ConstructorTemplateId:
1811 case UnqualifiedId::IK_DestructorName:
1812 // Constructors and destructors don't have return types. Use
1814 T = SemaRef.Context.VoidTy;
1815 if (AttributeList *attrs = D.getDeclSpec().getAttributes().getList())
1816 processTypeAttrs(state, T, true, attrs);
1819 case UnqualifiedId::IK_ConversionFunctionId:
1820 // The result type of a conversion function is the type that it
1822 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
1827 if (D.getAttributes())
1828 distributeTypeAttrsFromDeclarator(state, T);
1830 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
1831 // In C++11, a function declarator using 'auto' must have a trailing return
1832 // type (this is checked later) and we can skip this. In other languages
1833 // using auto, we need to check regardless.
1834 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
1835 (!SemaRef.getLangOpts().CPlusPlus0x || !D.isFunctionDeclarator())) {
1838 switch (D.getContext()) {
1839 case Declarator::KNRTypeListContext:
1840 llvm_unreachable("K&R type lists aren't allowed in C++");
1841 case Declarator::LambdaExprContext:
1842 llvm_unreachable("Can't specify a type specifier in lambda grammar");
1843 case Declarator::ObjCParameterContext:
1844 case Declarator::ObjCResultContext:
1845 case Declarator::PrototypeContext:
1846 Error = 0; // Function prototype
1848 case Declarator::MemberContext:
1849 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
1851 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
1852 case TTK_Enum: llvm_unreachable("unhandled tag kind");
1853 case TTK_Struct: Error = 1; /* Struct member */ break;
1854 case TTK_Union: Error = 2; /* Union member */ break;
1855 case TTK_Class: Error = 3; /* Class member */ break;
1858 case Declarator::CXXCatchContext:
1859 case Declarator::ObjCCatchContext:
1860 Error = 4; // Exception declaration
1862 case Declarator::TemplateParamContext:
1863 Error = 5; // Template parameter
1865 case Declarator::BlockLiteralContext:
1866 Error = 6; // Block literal
1868 case Declarator::TemplateTypeArgContext:
1869 Error = 7; // Template type argument
1871 case Declarator::AliasDeclContext:
1872 case Declarator::AliasTemplateContext:
1873 Error = 9; // Type alias
1875 case Declarator::TrailingReturnContext:
1876 Error = 10; // Function return type
1878 case Declarator::TypeNameContext:
1879 Error = 11; // Generic
1881 case Declarator::FileContext:
1882 case Declarator::BlockContext:
1883 case Declarator::ForContext:
1884 case Declarator::ConditionContext:
1885 case Declarator::CXXNewContext:
1889 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1892 // In Objective-C it is an error to use 'auto' on a function declarator.
1893 if (D.isFunctionDeclarator())
1896 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
1897 // contains a trailing return type. That is only legal at the outermost
1898 // level. Check all declarator chunks (outermost first) anyway, to give
1899 // better diagnostics.
1900 if (SemaRef.getLangOpts().CPlusPlus0x && Error != -1) {
1901 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1902 unsigned chunkIndex = e - i - 1;
1903 state.setCurrentChunkIndex(chunkIndex);
1904 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1905 if (DeclType.Kind == DeclaratorChunk::Function) {
1906 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1907 if (FTI.hasTrailingReturnType()) {
1916 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1917 diag::err_auto_not_allowed)
1919 T = SemaRef.Context.IntTy;
1920 D.setInvalidType(true);
1922 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1923 diag::warn_cxx98_compat_auto_type_specifier);
1926 if (SemaRef.getLangOpts().CPlusPlus &&
1927 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
1928 // Check the contexts where C++ forbids the declaration of a new class
1929 // or enumeration in a type-specifier-seq.
1930 switch (D.getContext()) {
1931 case Declarator::TrailingReturnContext:
1932 // Class and enumeration definitions are syntactically not allowed in
1933 // trailing return types.
1934 llvm_unreachable("parser should not have allowed this");
1936 case Declarator::FileContext:
1937 case Declarator::MemberContext:
1938 case Declarator::BlockContext:
1939 case Declarator::ForContext:
1940 case Declarator::BlockLiteralContext:
1941 case Declarator::LambdaExprContext:
1942 // C++11 [dcl.type]p3:
1943 // A type-specifier-seq shall not define a class or enumeration unless
1944 // it appears in the type-id of an alias-declaration (7.1.3) that is not
1945 // the declaration of a template-declaration.
1946 case Declarator::AliasDeclContext:
1948 case Declarator::AliasTemplateContext:
1949 SemaRef.Diag(OwnedTagDecl->getLocation(),
1950 diag::err_type_defined_in_alias_template)
1951 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1953 case Declarator::TypeNameContext:
1954 case Declarator::TemplateParamContext:
1955 case Declarator::CXXNewContext:
1956 case Declarator::CXXCatchContext:
1957 case Declarator::ObjCCatchContext:
1958 case Declarator::TemplateTypeArgContext:
1959 SemaRef.Diag(OwnedTagDecl->getLocation(),
1960 diag::err_type_defined_in_type_specifier)
1961 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1963 case Declarator::PrototypeContext:
1964 case Declarator::ObjCParameterContext:
1965 case Declarator::ObjCResultContext:
1966 case Declarator::KNRTypeListContext:
1968 // Types shall not be defined in return or parameter types.
1969 SemaRef.Diag(OwnedTagDecl->getLocation(),
1970 diag::err_type_defined_in_param_type)
1971 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1973 case Declarator::ConditionContext:
1975 // The type-specifier-seq shall not contain typedef and shall not declare
1976 // a new class or enumeration.
1977 SemaRef.Diag(OwnedTagDecl->getLocation(),
1978 diag::err_type_defined_in_condition);
1986 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1988 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1990 switch (FnTy->getRefQualifier()) {
2010 /// Check that the function type T, which has a cv-qualifier or a ref-qualifier,
2011 /// can be contained within the declarator chunk DeclType, and produce an
2012 /// appropriate diagnostic if not.
2013 static void checkQualifiedFunction(Sema &S, QualType T,
2014 DeclaratorChunk &DeclType) {
2015 // C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: a function type with a
2016 // cv-qualifier or a ref-qualifier can only appear at the topmost level
2019 switch (DeclType.Kind) {
2020 case DeclaratorChunk::Paren:
2021 case DeclaratorChunk::MemberPointer:
2022 // These cases are permitted.
2024 case DeclaratorChunk::Array:
2025 case DeclaratorChunk::Function:
2026 // These cases don't allow function types at all; no need to diagnose the
2027 // qualifiers separately.
2029 case DeclaratorChunk::BlockPointer:
2032 case DeclaratorChunk::Pointer:
2035 case DeclaratorChunk::Reference:
2040 assert(DiagKind != -1);
2041 S.Diag(DeclType.Loc, diag::err_compound_qualified_function_type)
2042 << DiagKind << isa<FunctionType>(T.IgnoreParens()) << T
2043 << getFunctionQualifiersAsString(T->castAs<FunctionProtoType>());
2046 /// Produce an approprioate diagnostic for an ambiguity between a function
2047 /// declarator and a C++ direct-initializer.
2048 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
2049 DeclaratorChunk &DeclType, QualType RT) {
2050 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2051 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
2053 // If the return type is void there is no ambiguity.
2054 if (RT->isVoidType())
2057 // An initializer for a non-class type can have at most one argument.
2058 if (!RT->isRecordType() && FTI.NumArgs > 1)
2061 // An initializer for a reference must have exactly one argument.
2062 if (RT->isReferenceType() && FTI.NumArgs != 1)
2065 // Only warn if this declarator is declaring a function at block scope, and
2066 // doesn't have a storage class (such as 'extern') specified.
2067 if (!D.isFunctionDeclarator() ||
2068 D.getFunctionDefinitionKind() != FDK_Declaration ||
2069 !S.CurContext->isFunctionOrMethod() ||
2070 D.getDeclSpec().getStorageClassSpecAsWritten()
2071 != DeclSpec::SCS_unspecified)
2074 // Inside a condition, a direct initializer is not permitted. We allow one to
2075 // be parsed in order to give better diagnostics in condition parsing.
2076 if (D.getContext() == Declarator::ConditionContext)
2079 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
2081 S.Diag(DeclType.Loc,
2082 FTI.NumArgs ? diag::warn_parens_disambiguated_as_function_declaration
2083 : diag::warn_empty_parens_are_function_decl)
2086 // If the declaration looks like:
2089 // and name lookup finds a function named 'f', then the ',' was
2090 // probably intended to be a ';'.
2091 if (!D.isFirstDeclarator() && D.getIdentifier()) {
2092 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
2093 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
2094 if (Comma.getFileID() != Name.getFileID() ||
2095 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
2096 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
2097 Sema::LookupOrdinaryName);
2098 if (S.LookupName(Result, S.getCurScope()))
2099 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
2100 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
2101 << D.getIdentifier();
2105 if (FTI.NumArgs > 0) {
2106 // For a declaration with parameters, eg. "T var(T());", suggest adding parens
2107 // around the first parameter to turn the declaration into a variable
2109 SourceRange Range = FTI.ArgInfo[0].Param->getSourceRange();
2110 SourceLocation B = Range.getBegin();
2111 SourceLocation E = S.PP.getLocForEndOfToken(Range.getEnd());
2112 // FIXME: Maybe we should suggest adding braces instead of parens
2113 // in C++11 for classes that don't have an initializer_list constructor.
2114 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
2115 << FixItHint::CreateInsertion(B, "(")
2116 << FixItHint::CreateInsertion(E, ")");
2118 // For a declaration without parameters, eg. "T var();", suggest replacing the
2119 // parens with an initializer to turn the declaration into a variable
2121 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
2123 // Empty parens mean value-initialization, and no parens mean
2124 // default initialization. These are equivalent if the default
2125 // constructor is user-provided or if zero-initialization is a
2127 if (RD && RD->hasDefinition() &&
2128 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
2129 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
2130 << FixItHint::CreateRemoval(ParenRange);
2132 std::string Init = S.getFixItZeroInitializerForType(RT);
2133 if (Init.empty() && S.LangOpts.CPlusPlus0x)
2136 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
2137 << FixItHint::CreateReplacement(ParenRange, Init);
2142 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
2143 QualType declSpecType,
2144 TypeSourceInfo *TInfo) {
2146 QualType T = declSpecType;
2147 Declarator &D = state.getDeclarator();
2148 Sema &S = state.getSema();
2149 ASTContext &Context = S.Context;
2150 const LangOptions &LangOpts = S.getLangOpts();
2152 bool ImplicitlyNoexcept = false;
2153 if (D.getName().getKind() == UnqualifiedId::IK_OperatorFunctionId &&
2154 LangOpts.CPlusPlus0x) {
2155 OverloadedOperatorKind OO = D.getName().OperatorFunctionId.Operator;
2156 /// In C++0x, deallocation functions (normal and array operator delete)
2157 /// are implicitly noexcept.
2158 if (OO == OO_Delete || OO == OO_Array_Delete)
2159 ImplicitlyNoexcept = true;
2162 // The name we're declaring, if any.
2163 DeclarationName Name;
2164 if (D.getIdentifier())
2165 Name = D.getIdentifier();
2167 // Does this declaration declare a typedef-name?
2168 bool IsTypedefName =
2169 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
2170 D.getContext() == Declarator::AliasDeclContext ||
2171 D.getContext() == Declarator::AliasTemplateContext;
2173 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2174 bool IsQualifiedFunction = T->isFunctionProtoType() &&
2175 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
2176 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
2178 // Walk the DeclTypeInfo, building the recursive type as we go.
2179 // DeclTypeInfos are ordered from the identifier out, which is
2180 // opposite of what we want :).
2181 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2182 unsigned chunkIndex = e - i - 1;
2183 state.setCurrentChunkIndex(chunkIndex);
2184 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2185 if (IsQualifiedFunction) {
2186 checkQualifiedFunction(S, T, DeclType);
2187 IsQualifiedFunction = DeclType.Kind == DeclaratorChunk::Paren;
2189 switch (DeclType.Kind) {
2190 case DeclaratorChunk::Paren:
2191 T = S.BuildParenType(T);
2193 case DeclaratorChunk::BlockPointer:
2194 // If blocks are disabled, emit an error.
2195 if (!LangOpts.Blocks)
2196 S.Diag(DeclType.Loc, diag::err_blocks_disable);
2198 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
2199 if (DeclType.Cls.TypeQuals)
2200 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
2202 case DeclaratorChunk::Pointer:
2203 // Verify that we're not building a pointer to pointer to function with
2204 // exception specification.
2205 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2206 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2207 D.setInvalidType(true);
2208 // Build the type anyway.
2210 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
2211 T = Context.getObjCObjectPointerType(T);
2212 if (DeclType.Ptr.TypeQuals)
2213 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
2216 T = S.BuildPointerType(T, DeclType.Loc, Name);
2217 if (DeclType.Ptr.TypeQuals)
2218 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
2221 case DeclaratorChunk::Reference: {
2222 // Verify that we're not building a reference to pointer to function with
2223 // exception specification.
2224 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2225 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2226 D.setInvalidType(true);
2227 // Build the type anyway.
2229 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
2232 if (DeclType.Ref.HasRestrict)
2233 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
2236 case DeclaratorChunk::Array: {
2237 // Verify that we're not building an array of pointers to function with
2238 // exception specification.
2239 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2240 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2241 D.setInvalidType(true);
2242 // Build the type anyway.
2244 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
2245 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
2246 ArrayType::ArraySizeModifier ASM;
2248 ASM = ArrayType::Star;
2249 else if (ATI.hasStatic)
2250 ASM = ArrayType::Static;
2252 ASM = ArrayType::Normal;
2253 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
2254 // FIXME: This check isn't quite right: it allows star in prototypes
2255 // for function definitions, and disallows some edge cases detailed
2256 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
2257 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
2258 ASM = ArrayType::Normal;
2259 D.setInvalidType(true);
2262 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
2263 // shall appear only in a declaration of a function parameter with an
2265 if (ASM == ArrayType::Static || ATI.TypeQuals) {
2266 if (!(D.isPrototypeContext() ||
2267 D.getContext() == Declarator::KNRTypeListContext)) {
2268 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
2269 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
2270 // Remove the 'static' and the type qualifiers.
2271 if (ASM == ArrayType::Static)
2272 ASM = ArrayType::Normal;
2274 D.setInvalidType(true);
2277 // C99 6.7.5.2p1: ... and then only in the outermost array type
2279 unsigned x = chunkIndex;
2281 // Walk outwards along the declarator chunks.
2283 const DeclaratorChunk &DC = D.getTypeObject(x);
2285 case DeclaratorChunk::Paren:
2287 case DeclaratorChunk::Array:
2288 case DeclaratorChunk::Pointer:
2289 case DeclaratorChunk::Reference:
2290 case DeclaratorChunk::MemberPointer:
2291 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
2292 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
2293 if (ASM == ArrayType::Static)
2294 ASM = ArrayType::Normal;
2296 D.setInvalidType(true);
2298 case DeclaratorChunk::Function:
2299 case DeclaratorChunk::BlockPointer:
2300 // These are invalid anyway, so just ignore.
2306 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
2307 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
2310 case DeclaratorChunk::Function: {
2311 // If the function declarator has a prototype (i.e. it is not () and
2312 // does not have a K&R-style identifier list), then the arguments are part
2313 // of the type, otherwise the argument list is ().
2314 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2315 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
2317 // Check for auto functions and trailing return type and adjust the
2318 // return type accordingly.
2319 if (!D.isInvalidType()) {
2320 // trailing-return-type is only required if we're declaring a function,
2321 // and not, for instance, a pointer to a function.
2322 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
2323 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
2324 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2325 diag::err_auto_missing_trailing_return);
2327 D.setInvalidType(true);
2328 } else if (FTI.hasTrailingReturnType()) {
2329 // T must be exactly 'auto' at this point. See CWG issue 681.
2330 if (isa<ParenType>(T)) {
2331 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2332 diag::err_trailing_return_in_parens)
2333 << T << D.getDeclSpec().getSourceRange();
2334 D.setInvalidType(true);
2335 } else if (D.getContext() != Declarator::LambdaExprContext &&
2336 (T.hasQualifiers() || !isa<AutoType>(T))) {
2337 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2338 diag::err_trailing_return_without_auto)
2339 << T << D.getDeclSpec().getSourceRange();
2340 D.setInvalidType(true);
2342 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
2344 // An error occurred parsing the trailing return type.
2346 D.setInvalidType(true);
2351 // C99 6.7.5.3p1: The return type may not be a function or array type.
2352 // For conversion functions, we'll diagnose this particular error later.
2353 if ((T->isArrayType() || T->isFunctionType()) &&
2354 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
2355 unsigned diagID = diag::err_func_returning_array_function;
2356 // Last processing chunk in block context means this function chunk
2357 // represents the block.
2358 if (chunkIndex == 0 &&
2359 D.getContext() == Declarator::BlockLiteralContext)
2360 diagID = diag::err_block_returning_array_function;
2361 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
2363 D.setInvalidType(true);
2366 // Do not allow returning half FP value.
2367 // FIXME: This really should be in BuildFunctionType.
2368 if (T->isHalfType()) {
2369 S.Diag(D.getIdentifierLoc(),
2370 diag::err_parameters_retval_cannot_have_fp16_type) << 1
2371 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
2372 D.setInvalidType(true);
2375 // cv-qualifiers on return types are pointless except when the type is a
2376 // class type in C++.
2377 if (isa<PointerType>(T) && T.getLocalCVRQualifiers() &&
2378 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) &&
2379 (!LangOpts.CPlusPlus || !T->isDependentType())) {
2380 assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?");
2381 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2382 assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer);
2384 DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr;
2386 DiagnoseIgnoredQualifiers(PTI.TypeQuals,
2387 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2388 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2389 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2392 } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
2393 (!LangOpts.CPlusPlus ||
2394 (!T->isDependentType() && !T->isRecordType()))) {
2396 DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(),
2397 D.getDeclSpec().getConstSpecLoc(),
2398 D.getDeclSpec().getVolatileSpecLoc(),
2399 D.getDeclSpec().getRestrictSpecLoc(),
2403 if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
2405 // Types shall not be defined in return or parameter types.
2406 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2407 if (Tag->isCompleteDefinition())
2408 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
2409 << Context.getTypeDeclType(Tag);
2412 // Exception specs are not allowed in typedefs. Complain, but add it
2414 if (IsTypedefName && FTI.getExceptionSpecType())
2415 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
2416 << (D.getContext() == Declarator::AliasDeclContext ||
2417 D.getContext() == Declarator::AliasTemplateContext);
2419 // If we see "T var();" or "T var(T());" at block scope, it is probably
2420 // an attempt to initialize a variable, not a function declaration.
2421 if (FTI.isAmbiguous)
2422 warnAboutAmbiguousFunction(S, D, DeclType, T);
2424 if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) {
2425 // Simple void foo(), where the incoming T is the result type.
2426 T = Context.getFunctionNoProtoType(T);
2428 // We allow a zero-parameter variadic function in C if the
2429 // function is marked with the "overloadable" attribute. Scan
2430 // for this attribute now.
2431 if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) {
2432 bool Overloadable = false;
2433 for (const AttributeList *Attrs = D.getAttributes();
2434 Attrs; Attrs = Attrs->getNext()) {
2435 if (Attrs->getKind() == AttributeList::AT_Overloadable) {
2436 Overloadable = true;
2442 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
2445 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
2446 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
2448 S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
2449 D.setInvalidType(true);
2453 FunctionProtoType::ExtProtoInfo EPI;
2454 EPI.Variadic = FTI.isVariadic;
2455 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
2456 EPI.TypeQuals = FTI.TypeQuals;
2457 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
2458 : FTI.RefQualifierIsLValueRef? RQ_LValue
2461 // Otherwise, we have a function with an argument list that is
2462 // potentially variadic.
2463 SmallVector<QualType, 16> ArgTys;
2464 ArgTys.reserve(FTI.NumArgs);
2466 SmallVector<bool, 16> ConsumedArguments;
2467 ConsumedArguments.reserve(FTI.NumArgs);
2468 bool HasAnyConsumedArguments = false;
2470 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2471 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
2472 QualType ArgTy = Param->getType();
2473 assert(!ArgTy.isNull() && "Couldn't parse type?");
2475 // Adjust the parameter type.
2476 assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) &&
2477 "Unadjusted type?");
2479 // Look for 'void'. void is allowed only as a single argument to a
2480 // function with no other parameters (C99 6.7.5.3p10). We record
2481 // int(void) as a FunctionProtoType with an empty argument list.
2482 if (ArgTy->isVoidType()) {
2483 // If this is something like 'float(int, void)', reject it. 'void'
2484 // is an incomplete type (C99 6.2.5p19) and function decls cannot
2485 // have arguments of incomplete type.
2486 if (FTI.NumArgs != 1 || FTI.isVariadic) {
2487 S.Diag(DeclType.Loc, diag::err_void_only_param);
2488 ArgTy = Context.IntTy;
2489 Param->setType(ArgTy);
2490 } else if (FTI.ArgInfo[i].Ident) {
2491 // Reject, but continue to parse 'int(void abc)'.
2492 S.Diag(FTI.ArgInfo[i].IdentLoc,
2493 diag::err_param_with_void_type);
2494 ArgTy = Context.IntTy;
2495 Param->setType(ArgTy);
2497 // Reject, but continue to parse 'float(const void)'.
2498 if (ArgTy.hasQualifiers())
2499 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
2501 // Do not add 'void' to the ArgTys list.
2504 } else if (ArgTy->isHalfType()) {
2505 // Disallow half FP arguments.
2506 // FIXME: This really should be in BuildFunctionType.
2507 S.Diag(Param->getLocation(),
2508 diag::err_parameters_retval_cannot_have_fp16_type) << 0
2509 << FixItHint::CreateInsertion(Param->getLocation(), "*");
2511 } else if (!FTI.hasPrototype) {
2512 if (ArgTy->isPromotableIntegerType()) {
2513 ArgTy = Context.getPromotedIntegerType(ArgTy);
2514 Param->setKNRPromoted(true);
2515 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
2516 if (BTy->getKind() == BuiltinType::Float) {
2517 ArgTy = Context.DoubleTy;
2518 Param->setKNRPromoted(true);
2523 if (LangOpts.ObjCAutoRefCount) {
2524 bool Consumed = Param->hasAttr<NSConsumedAttr>();
2525 ConsumedArguments.push_back(Consumed);
2526 HasAnyConsumedArguments |= Consumed;
2529 ArgTys.push_back(ArgTy);
2532 if (HasAnyConsumedArguments)
2533 EPI.ConsumedArguments = ConsumedArguments.data();
2535 SmallVector<QualType, 4> Exceptions;
2536 SmallVector<ParsedType, 2> DynamicExceptions;
2537 SmallVector<SourceRange, 2> DynamicExceptionRanges;
2538 Expr *NoexceptExpr = 0;
2540 if (FTI.getExceptionSpecType() == EST_Dynamic) {
2541 // FIXME: It's rather inefficient to have to split into two vectors
2543 unsigned N = FTI.NumExceptions;
2544 DynamicExceptions.reserve(N);
2545 DynamicExceptionRanges.reserve(N);
2546 for (unsigned I = 0; I != N; ++I) {
2547 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
2548 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
2550 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
2551 NoexceptExpr = FTI.NoexceptExpr;
2554 S.checkExceptionSpecification(FTI.getExceptionSpecType(),
2556 DynamicExceptionRanges,
2561 if (FTI.getExceptionSpecType() == EST_None &&
2562 ImplicitlyNoexcept && chunkIndex == 0) {
2563 // Only the outermost chunk is marked noexcept, of course.
2564 EPI.ExceptionSpecType = EST_BasicNoexcept;
2567 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI);
2572 case DeclaratorChunk::MemberPointer:
2573 // The scope spec must refer to a class, or be dependent.
2574 CXXScopeSpec &SS = DeclType.Mem.Scope();
2576 if (SS.isInvalid()) {
2577 // Avoid emitting extra errors if we already errored on the scope.
2578 D.setInvalidType(true);
2579 } else if (S.isDependentScopeSpecifier(SS) ||
2580 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
2581 NestedNameSpecifier *NNS
2582 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2583 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
2584 switch (NNS->getKind()) {
2585 case NestedNameSpecifier::Identifier:
2586 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
2587 NNS->getAsIdentifier());
2590 case NestedNameSpecifier::Namespace:
2591 case NestedNameSpecifier::NamespaceAlias:
2592 case NestedNameSpecifier::Global:
2593 llvm_unreachable("Nested-name-specifier must name a type");
2595 case NestedNameSpecifier::TypeSpec:
2596 case NestedNameSpecifier::TypeSpecWithTemplate:
2597 ClsType = QualType(NNS->getAsType(), 0);
2598 // Note: if the NNS has a prefix and ClsType is a nondependent
2599 // TemplateSpecializationType, then the NNS prefix is NOT included
2600 // in ClsType; hence we wrap ClsType into an ElaboratedType.
2601 // NOTE: in particular, no wrap occurs if ClsType already is an
2602 // Elaborated, DependentName, or DependentTemplateSpecialization.
2603 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
2604 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
2608 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
2609 diag::err_illegal_decl_mempointer_in_nonclass)
2610 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
2611 << DeclType.Mem.Scope().getRange();
2612 D.setInvalidType(true);
2615 if (!ClsType.isNull())
2616 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
2619 D.setInvalidType(true);
2620 } else if (DeclType.Mem.TypeQuals) {
2621 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
2627 D.setInvalidType(true);
2631 // See if there are any attributes on this declarator chunk.
2632 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
2633 processTypeAttrs(state, T, false, attrs);
2636 if (LangOpts.CPlusPlus && T->isFunctionType()) {
2637 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
2638 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
2641 // A cv-qualifier-seq shall only be part of the function type
2642 // for a nonstatic member function, the function type to which a pointer
2643 // to member refers, or the top-level function type of a function typedef
2646 // Core issue 547 also allows cv-qualifiers on function types that are
2647 // top-level template type arguments.
2649 if (!D.getCXXScopeSpec().isSet()) {
2650 FreeFunction = ((D.getContext() != Declarator::MemberContext &&
2651 D.getContext() != Declarator::LambdaExprContext) ||
2652 D.getDeclSpec().isFriendSpecified());
2654 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
2655 FreeFunction = (DC && !DC->isRecord());
2658 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
2659 // function that is not a constructor declares that function to be const.
2660 if (D.getDeclSpec().isConstexprSpecified() && !FreeFunction &&
2661 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static &&
2662 D.getName().getKind() != UnqualifiedId::IK_ConstructorName &&
2663 D.getName().getKind() != UnqualifiedId::IK_ConstructorTemplateId &&
2664 !(FnTy->getTypeQuals() & DeclSpec::TQ_const)) {
2665 // Rebuild function type adding a 'const' qualifier.
2666 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2667 EPI.TypeQuals |= DeclSpec::TQ_const;
2668 T = Context.getFunctionType(FnTy->getResultType(),
2669 FnTy->arg_type_begin(),
2670 FnTy->getNumArgs(), EPI);
2673 // C++11 [dcl.fct]p6 (w/DR1417):
2674 // An attempt to specify a function type with a cv-qualifier-seq or a
2675 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
2676 // - the function type for a non-static member function,
2677 // - the function type to which a pointer to member refers,
2678 // - the top-level function type of a function typedef declaration or
2679 // alias-declaration,
2680 // - the type-id in the default argument of a type-parameter, or
2681 // - the type-id of a template-argument for a type-parameter
2682 if (IsQualifiedFunction &&
2684 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
2686 D.getContext() != Declarator::TemplateTypeArgContext) {
2687 SourceLocation Loc = D.getLocStart();
2688 SourceRange RemovalRange;
2690 if (D.isFunctionDeclarator(I)) {
2691 SmallVector<SourceLocation, 4> RemovalLocs;
2692 const DeclaratorChunk &Chunk = D.getTypeObject(I);
2693 assert(Chunk.Kind == DeclaratorChunk::Function);
2694 if (Chunk.Fun.hasRefQualifier())
2695 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
2696 if (Chunk.Fun.TypeQuals & Qualifiers::Const)
2697 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
2698 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
2699 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
2700 // FIXME: We do not track the location of the __restrict qualifier.
2701 //if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
2702 // RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
2703 if (!RemovalLocs.empty()) {
2704 std::sort(RemovalLocs.begin(), RemovalLocs.end(),
2705 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
2706 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
2707 Loc = RemovalLocs.front();
2711 S.Diag(Loc, diag::err_invalid_qualified_function_type)
2712 << FreeFunction << D.isFunctionDeclarator() << T
2713 << getFunctionQualifiersAsString(FnTy)
2714 << FixItHint::CreateRemoval(RemovalRange);
2716 // Strip the cv-qualifiers and ref-qualifiers from the type.
2717 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2719 EPI.RefQualifier = RQ_None;
2721 T = Context.getFunctionType(FnTy->getResultType(),
2722 FnTy->arg_type_begin(),
2723 FnTy->getNumArgs(), EPI);
2727 // Apply any undistributed attributes from the declarator.
2729 if (AttributeList *attrs = D.getAttributes())
2730 processTypeAttrs(state, T, false, attrs);
2732 // Diagnose any ignored type attributes.
2733 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
2735 // C++0x [dcl.constexpr]p9:
2736 // A constexpr specifier used in an object declaration declares the object
2738 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
2742 // If there was an ellipsis in the declarator, the declaration declares a
2743 // parameter pack whose type may be a pack expansion type.
2744 if (D.hasEllipsis() && !T.isNull()) {
2745 // C++0x [dcl.fct]p13:
2746 // A declarator-id or abstract-declarator containing an ellipsis shall
2747 // only be used in a parameter-declaration. Such a parameter-declaration
2748 // is a parameter pack (14.5.3). [...]
2749 switch (D.getContext()) {
2750 case Declarator::PrototypeContext:
2751 // C++0x [dcl.fct]p13:
2752 // [...] When it is part of a parameter-declaration-clause, the
2753 // parameter pack is a function parameter pack (14.5.3). The type T
2754 // of the declarator-id of the function parameter pack shall contain
2755 // a template parameter pack; each template parameter pack in T is
2756 // expanded by the function parameter pack.
2758 // We represent function parameter packs as function parameters whose
2759 // type is a pack expansion.
2760 if (!T->containsUnexpandedParameterPack()) {
2761 S.Diag(D.getEllipsisLoc(),
2762 diag::err_function_parameter_pack_without_parameter_packs)
2763 << T << D.getSourceRange();
2764 D.setEllipsisLoc(SourceLocation());
2766 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
2770 case Declarator::TemplateParamContext:
2771 // C++0x [temp.param]p15:
2772 // If a template-parameter is a [...] is a parameter-declaration that
2773 // declares a parameter pack (8.3.5), then the template-parameter is a
2774 // template parameter pack (14.5.3).
2776 // Note: core issue 778 clarifies that, if there are any unexpanded
2777 // parameter packs in the type of the non-type template parameter, then
2778 // it expands those parameter packs.
2779 if (T->containsUnexpandedParameterPack())
2780 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
2782 S.Diag(D.getEllipsisLoc(),
2783 LangOpts.CPlusPlus0x
2784 ? diag::warn_cxx98_compat_variadic_templates
2785 : diag::ext_variadic_templates);
2788 case Declarator::FileContext:
2789 case Declarator::KNRTypeListContext:
2790 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
2791 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
2792 case Declarator::TypeNameContext:
2793 case Declarator::CXXNewContext:
2794 case Declarator::AliasDeclContext:
2795 case Declarator::AliasTemplateContext:
2796 case Declarator::MemberContext:
2797 case Declarator::BlockContext:
2798 case Declarator::ForContext:
2799 case Declarator::ConditionContext:
2800 case Declarator::CXXCatchContext:
2801 case Declarator::ObjCCatchContext:
2802 case Declarator::BlockLiteralContext:
2803 case Declarator::LambdaExprContext:
2804 case Declarator::TrailingReturnContext:
2805 case Declarator::TemplateTypeArgContext:
2806 // FIXME: We may want to allow parameter packs in block-literal contexts
2808 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
2809 D.setEllipsisLoc(SourceLocation());
2815 return Context.getNullTypeSourceInfo();
2816 else if (D.isInvalidType())
2817 return Context.getTrivialTypeSourceInfo(T);
2819 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
2822 /// GetTypeForDeclarator - Convert the type for the specified
2823 /// declarator to Type instances.
2825 /// The result of this call will never be null, but the associated
2826 /// type may be a null type if there's an unrecoverable error.
2827 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
2828 // Determine the type of the declarator. Not all forms of declarator
2831 TypeProcessingState state(*this, D);
2833 TypeSourceInfo *ReturnTypeInfo = 0;
2834 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2836 return Context.getNullTypeSourceInfo();
2838 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
2839 inferARCWriteback(state, T);
2841 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
2844 static void transferARCOwnershipToDeclSpec(Sema &S,
2845 QualType &declSpecTy,
2846 Qualifiers::ObjCLifetime ownership) {
2847 if (declSpecTy->isObjCRetainableType() &&
2848 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
2850 qs.addObjCLifetime(ownership);
2851 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
2855 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2856 Qualifiers::ObjCLifetime ownership,
2857 unsigned chunkIndex) {
2858 Sema &S = state.getSema();
2859 Declarator &D = state.getDeclarator();
2861 // Look for an explicit lifetime attribute.
2862 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
2863 for (const AttributeList *attr = chunk.getAttrs(); attr;
2864 attr = attr->getNext())
2865 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
2868 const char *attrStr = 0;
2869 switch (ownership) {
2870 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
2871 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
2872 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
2873 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
2874 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
2877 // If there wasn't one, add one (with an invalid source location
2878 // so that we don't make an AttributedType for it).
2879 AttributeList *attr = D.getAttributePool()
2880 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
2881 /*scope*/ 0, SourceLocation(),
2882 &S.Context.Idents.get(attrStr), SourceLocation(),
2883 /*args*/ 0, 0, AttributeList::AS_GNU);
2884 spliceAttrIntoList(*attr, chunk.getAttrListRef());
2886 // TODO: mark whether we did this inference?
2889 /// \brief Used for transferring ownership in casts resulting in l-values.
2890 static void transferARCOwnership(TypeProcessingState &state,
2891 QualType &declSpecTy,
2892 Qualifiers::ObjCLifetime ownership) {
2893 Sema &S = state.getSema();
2894 Declarator &D = state.getDeclarator();
2897 bool hasIndirection = false;
2898 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2899 DeclaratorChunk &chunk = D.getTypeObject(i);
2900 switch (chunk.Kind) {
2901 case DeclaratorChunk::Paren:
2905 case DeclaratorChunk::Array:
2906 case DeclaratorChunk::Reference:
2907 case DeclaratorChunk::Pointer:
2909 hasIndirection = true;
2913 case DeclaratorChunk::BlockPointer:
2915 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
2918 case DeclaratorChunk::Function:
2919 case DeclaratorChunk::MemberPointer:
2927 DeclaratorChunk &chunk = D.getTypeObject(inner);
2928 if (chunk.Kind == DeclaratorChunk::Pointer) {
2929 if (declSpecTy->isObjCRetainableType())
2930 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2931 if (declSpecTy->isObjCObjectType() && hasIndirection)
2932 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
2934 assert(chunk.Kind == DeclaratorChunk::Array ||
2935 chunk.Kind == DeclaratorChunk::Reference);
2936 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2940 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
2941 TypeProcessingState state(*this, D);
2943 TypeSourceInfo *ReturnTypeInfo = 0;
2944 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2945 if (declSpecTy.isNull())
2946 return Context.getNullTypeSourceInfo();
2948 if (getLangOpts().ObjCAutoRefCount) {
2949 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
2950 if (ownership != Qualifiers::OCL_None)
2951 transferARCOwnership(state, declSpecTy, ownership);
2954 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
2957 /// Map an AttributedType::Kind to an AttributeList::Kind.
2958 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
2960 case AttributedType::attr_address_space:
2961 return AttributeList::AT_AddressSpace;
2962 case AttributedType::attr_regparm:
2963 return AttributeList::AT_Regparm;
2964 case AttributedType::attr_vector_size:
2965 return AttributeList::AT_VectorSize;
2966 case AttributedType::attr_neon_vector_type:
2967 return AttributeList::AT_NeonVectorType;
2968 case AttributedType::attr_neon_polyvector_type:
2969 return AttributeList::AT_NeonPolyVectorType;
2970 case AttributedType::attr_objc_gc:
2971 return AttributeList::AT_ObjCGC;
2972 case AttributedType::attr_objc_ownership:
2973 return AttributeList::AT_ObjCOwnership;
2974 case AttributedType::attr_noreturn:
2975 return AttributeList::AT_NoReturn;
2976 case AttributedType::attr_cdecl:
2977 return AttributeList::AT_CDecl;
2978 case AttributedType::attr_fastcall:
2979 return AttributeList::AT_FastCall;
2980 case AttributedType::attr_stdcall:
2981 return AttributeList::AT_StdCall;
2982 case AttributedType::attr_thiscall:
2983 return AttributeList::AT_ThisCall;
2984 case AttributedType::attr_pascal:
2985 return AttributeList::AT_Pascal;
2986 case AttributedType::attr_pcs:
2987 return AttributeList::AT_Pcs;
2989 llvm_unreachable("unexpected attribute kind!");
2992 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
2993 const AttributeList *attrs) {
2994 AttributedType::Kind kind = TL.getAttrKind();
2996 assert(attrs && "no type attributes in the expected location!");
2997 AttributeList::Kind parsedKind = getAttrListKind(kind);
2998 while (attrs->getKind() != parsedKind) {
2999 attrs = attrs->getNext();
3000 assert(attrs && "no matching attribute in expected location!");
3003 TL.setAttrNameLoc(attrs->getLoc());
3004 if (TL.hasAttrExprOperand())
3005 TL.setAttrExprOperand(attrs->getArg(0));
3006 else if (TL.hasAttrEnumOperand())
3007 TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
3009 // FIXME: preserve this information to here.
3010 if (TL.hasAttrOperand())
3011 TL.setAttrOperandParensRange(SourceRange());
3015 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
3016 ASTContext &Context;
3020 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
3021 : Context(Context), DS(DS) {}
3023 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3024 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
3025 Visit(TL.getModifiedLoc());
3027 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3028 Visit(TL.getUnqualifiedLoc());
3030 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
3031 TL.setNameLoc(DS.getTypeSpecTypeLoc());
3033 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
3034 TL.setNameLoc(DS.getTypeSpecTypeLoc());
3035 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
3036 // addition field. What we have is good enough for dispay of location
3037 // of 'fixit' on interface name.
3038 TL.setNameEndLoc(DS.getLocEnd());
3040 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
3041 // Handle the base type, which might not have been written explicitly.
3042 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
3043 TL.setHasBaseTypeAsWritten(false);
3044 TL.getBaseLoc().initialize(Context, SourceLocation());
3046 TL.setHasBaseTypeAsWritten(true);
3047 Visit(TL.getBaseLoc());
3050 // Protocol qualifiers.
3051 if (DS.getProtocolQualifiers()) {
3052 assert(TL.getNumProtocols() > 0);
3053 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
3054 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
3055 TL.setRAngleLoc(DS.getSourceRange().getEnd());
3056 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
3057 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
3059 assert(TL.getNumProtocols() == 0);
3060 TL.setLAngleLoc(SourceLocation());
3061 TL.setRAngleLoc(SourceLocation());
3064 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3065 TL.setStarLoc(SourceLocation());
3066 Visit(TL.getPointeeLoc());
3068 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
3069 TypeSourceInfo *TInfo = 0;
3070 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3072 // If we got no declarator info from previous Sema routines,
3073 // just fill with the typespec loc.
3075 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
3079 TypeLoc OldTL = TInfo->getTypeLoc();
3080 if (TInfo->getType()->getAs<ElaboratedType>()) {
3081 ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
3082 TemplateSpecializationTypeLoc NamedTL =
3083 cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
3087 TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
3089 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
3090 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
3091 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3092 TL.setParensRange(DS.getTypeofParensRange());
3094 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
3095 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
3096 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3097 TL.setParensRange(DS.getTypeofParensRange());
3098 assert(DS.getRepAsType());
3099 TypeSourceInfo *TInfo = 0;
3100 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3101 TL.setUnderlyingTInfo(TInfo);
3103 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
3104 // FIXME: This holds only because we only have one unary transform.
3105 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
3106 TL.setKWLoc(DS.getTypeSpecTypeLoc());
3107 TL.setParensRange(DS.getTypeofParensRange());
3108 assert(DS.getRepAsType());
3109 TypeSourceInfo *TInfo = 0;
3110 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3111 TL.setUnderlyingTInfo(TInfo);
3113 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
3114 // By default, use the source location of the type specifier.
3115 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
3116 if (TL.needsExtraLocalData()) {
3117 // Set info for the written builtin specifiers.
3118 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
3119 // Try to have a meaningful source location.
3120 if (TL.getWrittenSignSpec() != TSS_unspecified)
3121 // Sign spec loc overrides the others (e.g., 'unsigned long').
3122 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
3123 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
3124 // Width spec loc overrides type spec loc (e.g., 'short int').
3125 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
3128 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
3129 ElaboratedTypeKeyword Keyword
3130 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
3131 if (DS.getTypeSpecType() == TST_typename) {
3132 TypeSourceInfo *TInfo = 0;
3133 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3135 TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
3139 TL.setElaboratedKeywordLoc(Keyword != ETK_None
3140 ? DS.getTypeSpecTypeLoc()
3141 : SourceLocation());
3142 const CXXScopeSpec& SS = DS.getTypeSpecScope();
3143 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3144 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
3146 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
3147 assert(DS.getTypeSpecType() == TST_typename);
3148 TypeSourceInfo *TInfo = 0;
3149 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3151 TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
3153 void VisitDependentTemplateSpecializationTypeLoc(
3154 DependentTemplateSpecializationTypeLoc TL) {
3155 assert(DS.getTypeSpecType() == TST_typename);
3156 TypeSourceInfo *TInfo = 0;
3157 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3159 TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
3160 TInfo->getTypeLoc()));
3162 void VisitTagTypeLoc(TagTypeLoc TL) {
3163 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
3165 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
3166 TL.setKWLoc(DS.getTypeSpecTypeLoc());
3167 TL.setParensRange(DS.getTypeofParensRange());
3169 TypeSourceInfo *TInfo = 0;
3170 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3171 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
3174 void VisitTypeLoc(TypeLoc TL) {
3175 // FIXME: add other typespec types and change this to an assert.
3176 TL.initialize(Context, DS.getTypeSpecTypeLoc());
3180 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
3181 ASTContext &Context;
3182 const DeclaratorChunk &Chunk;
3185 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
3186 : Context(Context), Chunk(Chunk) {}
3188 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3189 llvm_unreachable("qualified type locs not expected here!");
3192 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3193 fillAttributedTypeLoc(TL, Chunk.getAttrs());
3195 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3196 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
3197 TL.setCaretLoc(Chunk.Loc);
3199 void VisitPointerTypeLoc(PointerTypeLoc TL) {
3200 assert(Chunk.Kind == DeclaratorChunk::Pointer);
3201 TL.setStarLoc(Chunk.Loc);
3203 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3204 assert(Chunk.Kind == DeclaratorChunk::Pointer);
3205 TL.setStarLoc(Chunk.Loc);
3207 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3208 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
3209 const CXXScopeSpec& SS = Chunk.Mem.Scope();
3210 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
3212 const Type* ClsTy = TL.getClass();
3213 QualType ClsQT = QualType(ClsTy, 0);
3214 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
3215 // Now copy source location info into the type loc component.
3216 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
3217 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
3218 case NestedNameSpecifier::Identifier:
3219 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
3221 DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL);
3222 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
3223 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
3224 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
3228 case NestedNameSpecifier::TypeSpec:
3229 case NestedNameSpecifier::TypeSpecWithTemplate:
3230 if (isa<ElaboratedType>(ClsTy)) {
3231 ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL);
3232 ETLoc.setElaboratedKeywordLoc(SourceLocation());
3233 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
3234 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
3235 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
3237 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
3241 case NestedNameSpecifier::Namespace:
3242 case NestedNameSpecifier::NamespaceAlias:
3243 case NestedNameSpecifier::Global:
3244 llvm_unreachable("Nested-name-specifier must name a type");
3247 // Finally fill in MemberPointerLocInfo fields.
3248 TL.setStarLoc(Chunk.Loc);
3249 TL.setClassTInfo(ClsTInfo);
3251 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3252 assert(Chunk.Kind == DeclaratorChunk::Reference);
3253 // 'Amp' is misleading: this might have been originally
3254 /// spelled with AmpAmp.
3255 TL.setAmpLoc(Chunk.Loc);
3257 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3258 assert(Chunk.Kind == DeclaratorChunk::Reference);
3259 assert(!Chunk.Ref.LValueRef);
3260 TL.setAmpAmpLoc(Chunk.Loc);
3262 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
3263 assert(Chunk.Kind == DeclaratorChunk::Array);
3264 TL.setLBracketLoc(Chunk.Loc);
3265 TL.setRBracketLoc(Chunk.EndLoc);
3266 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
3268 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3269 assert(Chunk.Kind == DeclaratorChunk::Function);
3270 TL.setLocalRangeBegin(Chunk.Loc);
3271 TL.setLocalRangeEnd(Chunk.EndLoc);
3273 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
3274 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
3275 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
3276 TL.setArg(tpi++, Param);
3278 // FIXME: exception specs
3280 void VisitParenTypeLoc(ParenTypeLoc TL) {
3281 assert(Chunk.Kind == DeclaratorChunk::Paren);
3282 TL.setLParenLoc(Chunk.Loc);
3283 TL.setRParenLoc(Chunk.EndLoc);
3286 void VisitTypeLoc(TypeLoc TL) {
3287 llvm_unreachable("unsupported TypeLoc kind in declarator!");
3292 /// \brief Create and instantiate a TypeSourceInfo with type source information.
3294 /// \param T QualType referring to the type as written in source code.
3296 /// \param ReturnTypeInfo For declarators whose return type does not show
3297 /// up in the normal place in the declaration specifiers (such as a C++
3298 /// conversion function), this pointer will refer to a type source information
3299 /// for that return type.
3301 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
3302 TypeSourceInfo *ReturnTypeInfo) {
3303 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
3304 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
3306 // Handle parameter packs whose type is a pack expansion.
3307 if (isa<PackExpansionType>(T)) {
3308 cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc());
3309 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3312 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3313 while (isa<AttributedTypeLoc>(CurrTL)) {
3314 AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL);
3315 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
3316 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3319 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
3320 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3323 // If we have different source information for the return type, use
3324 // that. This really only applies to C++ conversion functions.
3325 if (ReturnTypeInfo) {
3326 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
3327 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
3328 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
3330 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
3336 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
3337 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
3338 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
3339 // and Sema during declaration parsing. Try deallocating/caching them when
3340 // it's appropriate, instead of allocating them and keeping them around.
3341 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
3343 new (LocT) LocInfoType(T, TInfo);
3344 assert(LocT->getTypeClass() != T->getTypeClass() &&
3345 "LocInfoType's TypeClass conflicts with an existing Type class");
3346 return ParsedType::make(QualType(LocT, 0));
3349 void LocInfoType::getAsStringInternal(std::string &Str,
3350 const PrintingPolicy &Policy) const {
3351 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
3352 " was used directly instead of getting the QualType through"
3353 " GetTypeFromParser");
3356 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
3357 // C99 6.7.6: Type names have no identifier. This is already validated by
3359 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
3361 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3362 QualType T = TInfo->getType();
3363 if (D.isInvalidType())
3366 // Make sure there are no unused decl attributes on the declarator.
3367 // We don't want to do this for ObjC parameters because we're going
3368 // to apply them to the actual parameter declaration.
3369 if (D.getContext() != Declarator::ObjCParameterContext)
3370 checkUnusedDeclAttributes(D);
3372 if (getLangOpts().CPlusPlus) {
3373 // Check that there are no default arguments (C++ only).
3374 CheckExtraCXXDefaultArguments(D);
3377 return CreateParsedType(T, TInfo);
3380 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
3381 QualType T = Context.getObjCInstanceType();
3382 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
3383 return CreateParsedType(T, TInfo);
3387 //===----------------------------------------------------------------------===//
3388 // Type Attribute Processing
3389 //===----------------------------------------------------------------------===//
3391 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
3392 /// specified type. The attribute contains 1 argument, the id of the address
3393 /// space for the type.
3394 static void HandleAddressSpaceTypeAttribute(QualType &Type,
3395 const AttributeList &Attr, Sema &S){
3397 // If this type is already address space qualified, reject it.
3398 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
3399 // qualifiers for two or more different address spaces."
3400 if (Type.getAddressSpace()) {
3401 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
3406 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
3407 // qualified by an address-space qualifier."
3408 if (Type->isFunctionType()) {
3409 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
3414 // Check the attribute arguments.
3415 if (Attr.getNumArgs() != 1) {
3416 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3420 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
3421 llvm::APSInt addrSpace(32);
3422 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
3423 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
3424 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
3425 << ASArgExpr->getSourceRange();
3431 if (addrSpace.isSigned()) {
3432 if (addrSpace.isNegative()) {
3433 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
3434 << ASArgExpr->getSourceRange();
3438 addrSpace.setIsSigned(false);
3440 llvm::APSInt max(addrSpace.getBitWidth());
3441 max = Qualifiers::MaxAddressSpace;
3442 if (addrSpace > max) {
3443 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
3444 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
3449 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
3450 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
3453 /// Does this type have a "direct" ownership qualifier? That is,
3454 /// is it written like "__strong id", as opposed to something like
3455 /// "typeof(foo)", where that happens to be strong?
3456 static bool hasDirectOwnershipQualifier(QualType type) {
3457 // Fast path: no qualifier at all.
3458 assert(type.getQualifiers().hasObjCLifetime());
3462 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
3463 if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
3466 type = attr->getModifiedType();
3468 // X *__strong (...)
3469 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
3470 type = paren->getInnerType();
3472 // That's it for things we want to complain about. In particular,
3473 // we do not want to look through typedefs, typeof(expr),
3474 // typeof(type), or any other way that the type is somehow
3483 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
3484 /// attribute on the specified type.
3486 /// Returns 'true' if the attribute was handled.
3487 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
3488 AttributeList &attr,
3490 bool NonObjCPointer = false;
3492 if (!type->isDependentType()) {
3493 if (const PointerType *ptr = type->getAs<PointerType>()) {
3494 QualType pointee = ptr->getPointeeType();
3495 if (pointee->isObjCRetainableType() || pointee->isPointerType())
3497 // It is important not to lose the source info that there was an attribute
3498 // applied to non-objc pointer. We will create an attributed type but
3499 // its type will be the same as the original type.
3500 NonObjCPointer = true;
3501 } else if (!type->isObjCRetainableType()) {
3506 Sema &S = state.getSema();
3507 SourceLocation AttrLoc = attr.getLoc();
3508 if (AttrLoc.isMacroID())
3509 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
3511 if (!attr.getParameterName()) {
3512 S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string)
3513 << "objc_ownership" << 1;
3518 // Consume lifetime attributes without further comment outside of
3520 if (!S.getLangOpts().ObjCAutoRefCount)
3523 Qualifiers::ObjCLifetime lifetime;
3524 if (attr.getParameterName()->isStr("none"))
3525 lifetime = Qualifiers::OCL_ExplicitNone;
3526 else if (attr.getParameterName()->isStr("strong"))
3527 lifetime = Qualifiers::OCL_Strong;
3528 else if (attr.getParameterName()->isStr("weak"))
3529 lifetime = Qualifiers::OCL_Weak;
3530 else if (attr.getParameterName()->isStr("autoreleasing"))
3531 lifetime = Qualifiers::OCL_Autoreleasing;
3533 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
3534 << "objc_ownership" << attr.getParameterName();
3539 SplitQualType underlyingType = type.split();
3541 // Check for redundant/conflicting ownership qualifiers.
3542 if (Qualifiers::ObjCLifetime previousLifetime
3543 = type.getQualifiers().getObjCLifetime()) {
3544 // If it's written directly, that's an error.
3545 if (hasDirectOwnershipQualifier(type)) {
3546 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
3551 // Otherwise, if the qualifiers actually conflict, pull sugar off
3552 // until we reach a type that is directly qualified.
3553 if (previousLifetime != lifetime) {
3554 // This should always terminate: the canonical type is
3555 // qualified, so some bit of sugar must be hiding it.
3556 while (!underlyingType.Quals.hasObjCLifetime()) {
3557 underlyingType = underlyingType.getSingleStepDesugaredType();
3559 underlyingType.Quals.removeObjCLifetime();
3563 underlyingType.Quals.addObjCLifetime(lifetime);
3565 if (NonObjCPointer) {
3566 StringRef name = attr.getName()->getName();
3568 case Qualifiers::OCL_None:
3569 case Qualifiers::OCL_ExplicitNone:
3571 case Qualifiers::OCL_Strong: name = "__strong"; break;
3572 case Qualifiers::OCL_Weak: name = "__weak"; break;
3573 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
3575 S.Diag(AttrLoc, diag::warn_objc_object_attribute_wrong_type)
3579 QualType origType = type;
3580 if (!NonObjCPointer)
3581 type = S.Context.getQualifiedType(underlyingType);
3583 // If we have a valid source location for the attribute, use an
3584 // AttributedType instead.
3585 if (AttrLoc.isValid())
3586 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
3589 // Forbid __weak if the runtime doesn't support it.
3590 if (lifetime == Qualifiers::OCL_Weak &&
3591 !S.getLangOpts().ObjCRuntimeHasWeak && !NonObjCPointer) {
3593 // Actually, delay this until we know what we're parsing.
3594 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
3595 S.DelayedDiagnostics.add(
3596 sema::DelayedDiagnostic::makeForbiddenType(
3597 S.getSourceManager().getExpansionLoc(AttrLoc),
3598 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
3600 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
3607 // Forbid __weak for class objects marked as
3608 // objc_arc_weak_reference_unavailable
3609 if (lifetime == Qualifiers::OCL_Weak) {
3611 while (const PointerType *ptr = T->getAs<PointerType>())
3612 T = ptr->getPointeeType();
3613 if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
3614 ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl();
3615 if (Class->isArcWeakrefUnavailable()) {
3616 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
3617 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
3618 diag::note_class_declared);
3626 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
3627 /// attribute on the specified type. Returns true to indicate that
3628 /// the attribute was handled, false to indicate that the type does
3629 /// not permit the attribute.
3630 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
3631 AttributeList &attr,
3633 Sema &S = state.getSema();
3635 // Delay if this isn't some kind of pointer.
3636 if (!type->isPointerType() &&
3637 !type->isObjCObjectPointerType() &&
3638 !type->isBlockPointerType())
3641 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
3642 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
3647 // Check the attribute arguments.
3648 if (!attr.getParameterName()) {
3649 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
3654 Qualifiers::GC GCAttr;
3655 if (attr.getNumArgs() != 0) {
3656 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3660 if (attr.getParameterName()->isStr("weak"))
3661 GCAttr = Qualifiers::Weak;
3662 else if (attr.getParameterName()->isStr("strong"))
3663 GCAttr = Qualifiers::Strong;
3665 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
3666 << "objc_gc" << attr.getParameterName();
3671 QualType origType = type;
3672 type = S.Context.getObjCGCQualType(origType, GCAttr);
3674 // Make an attributed type to preserve the source information.
3675 if (attr.getLoc().isValid())
3676 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
3683 /// A helper class to unwrap a type down to a function for the
3684 /// purposes of applying attributes there.
3687 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
3688 /// if (unwrapped.isFunctionType()) {
3689 /// const FunctionType *fn = unwrapped.get();
3690 /// // change fn somehow
3691 /// T = unwrapped.wrap(fn);
3693 struct FunctionTypeUnwrapper {
3704 const FunctionType *Fn;
3705 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
3707 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
3709 const Type *Ty = T.getTypePtr();
3710 if (isa<FunctionType>(Ty)) {
3711 Fn = cast<FunctionType>(Ty);
3713 } else if (isa<ParenType>(Ty)) {
3714 T = cast<ParenType>(Ty)->getInnerType();
3715 Stack.push_back(Parens);
3716 } else if (isa<PointerType>(Ty)) {
3717 T = cast<PointerType>(Ty)->getPointeeType();
3718 Stack.push_back(Pointer);
3719 } else if (isa<BlockPointerType>(Ty)) {
3720 T = cast<BlockPointerType>(Ty)->getPointeeType();
3721 Stack.push_back(BlockPointer);
3722 } else if (isa<MemberPointerType>(Ty)) {
3723 T = cast<MemberPointerType>(Ty)->getPointeeType();
3724 Stack.push_back(MemberPointer);
3725 } else if (isa<ReferenceType>(Ty)) {
3726 T = cast<ReferenceType>(Ty)->getPointeeType();
3727 Stack.push_back(Reference);
3729 const Type *DTy = Ty->getUnqualifiedDesugaredType();
3735 T = QualType(DTy, 0);
3736 Stack.push_back(Desugar);
3741 bool isFunctionType() const { return (Fn != 0); }
3742 const FunctionType *get() const { return Fn; }
3744 QualType wrap(Sema &S, const FunctionType *New) {
3745 // If T wasn't modified from the unwrapped type, do nothing.
3746 if (New == get()) return Original;
3749 return wrap(S.Context, Original, 0);
3753 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
3754 if (I == Stack.size())
3755 return C.getQualifiedType(Fn, Old.getQualifiers());
3757 // Build up the inner type, applying the qualifiers from the old
3758 // type to the new type.
3759 SplitQualType SplitOld = Old.split();
3761 // As a special case, tail-recurse if there are no qualifiers.
3762 if (SplitOld.Quals.empty())
3763 return wrap(C, SplitOld.Ty, I);
3764 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
3767 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
3768 if (I == Stack.size()) return QualType(Fn, 0);
3770 switch (static_cast<WrapKind>(Stack[I++])) {
3772 // This is the point at which we potentially lose source
3774 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
3777 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
3778 return C.getParenType(New);
3782 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
3783 return C.getPointerType(New);
3786 case BlockPointer: {
3787 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
3788 return C.getBlockPointerType(New);
3791 case MemberPointer: {
3792 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
3793 QualType New = wrap(C, OldMPT->getPointeeType(), I);
3794 return C.getMemberPointerType(New, OldMPT->getClass());
3798 const ReferenceType *OldRef = cast<ReferenceType>(Old);
3799 QualType New = wrap(C, OldRef->getPointeeType(), I);
3800 if (isa<LValueReferenceType>(OldRef))
3801 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
3803 return C.getRValueReferenceType(New);
3807 llvm_unreachable("unknown wrapping kind");
3812 /// Process an individual function attribute. Returns true to
3813 /// indicate that the attribute was handled, false if it wasn't.
3814 static bool handleFunctionTypeAttr(TypeProcessingState &state,
3815 AttributeList &attr,
3817 Sema &S = state.getSema();
3819 FunctionTypeUnwrapper unwrapped(S, type);
3821 if (attr.getKind() == AttributeList::AT_NoReturn) {
3822 if (S.CheckNoReturnAttr(attr))
3825 // Delay if this is not a function type.
3826 if (!unwrapped.isFunctionType())
3829 // Otherwise we can process right away.
3830 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
3831 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3835 // ns_returns_retained is not always a type attribute, but if we got
3836 // here, we're treating it as one right now.
3837 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
3838 assert(S.getLangOpts().ObjCAutoRefCount &&
3839 "ns_returns_retained treated as type attribute in non-ARC");
3840 if (attr.getNumArgs()) return true;
3842 // Delay if this is not a function type.
3843 if (!unwrapped.isFunctionType())
3846 FunctionType::ExtInfo EI
3847 = unwrapped.get()->getExtInfo().withProducesResult(true);
3848 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3852 if (attr.getKind() == AttributeList::AT_Regparm) {
3854 if (S.CheckRegparmAttr(attr, value))
3857 // Delay if this is not a function type.
3858 if (!unwrapped.isFunctionType())
3861 // Diagnose regparm with fastcall.
3862 const FunctionType *fn = unwrapped.get();
3863 CallingConv CC = fn->getCallConv();
3864 if (CC == CC_X86FastCall) {
3865 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3866 << FunctionType::getNameForCallConv(CC)
3872 FunctionType::ExtInfo EI =
3873 unwrapped.get()->getExtInfo().withRegParm(value);
3874 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3878 // Otherwise, a calling convention.
3880 if (S.CheckCallingConvAttr(attr, CC))
3883 // Delay if the type didn't work out to a function.
3884 if (!unwrapped.isFunctionType()) return false;
3886 const FunctionType *fn = unwrapped.get();
3887 CallingConv CCOld = fn->getCallConv();
3888 if (S.Context.getCanonicalCallConv(CC) ==
3889 S.Context.getCanonicalCallConv(CCOld)) {
3890 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
3891 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3895 if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) {
3896 // Should we diagnose reapplications of the same convention?
3897 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3898 << FunctionType::getNameForCallConv(CC)
3899 << FunctionType::getNameForCallConv(CCOld);
3904 // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
3905 if (CC == CC_X86FastCall) {
3906 if (isa<FunctionNoProtoType>(fn)) {
3907 S.Diag(attr.getLoc(), diag::err_cconv_knr)
3908 << FunctionType::getNameForCallConv(CC);
3913 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
3914 if (FnP->isVariadic()) {
3915 S.Diag(attr.getLoc(), diag::err_cconv_varargs)
3916 << FunctionType::getNameForCallConv(CC);
3921 // Also diagnose fastcall with regparm.
3922 if (fn->getHasRegParm()) {
3923 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3925 << FunctionType::getNameForCallConv(CC);
3931 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
3932 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3936 /// Handle OpenCL image access qualifiers: read_only, write_only, read_write
3937 static void HandleOpenCLImageAccessAttribute(QualType& CurType,
3938 const AttributeList &Attr,
3940 // Check the attribute arguments.
3941 if (Attr.getNumArgs() != 1) {
3942 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3946 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3947 llvm::APSInt arg(32);
3948 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3949 !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
3950 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3951 << "opencl_image_access" << sizeExpr->getSourceRange();
3955 unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
3957 case CLIA_read_only:
3958 case CLIA_write_only:
3959 case CLIA_read_write:
3960 // Implemented in a separate patch
3963 // Implemented in a separate patch
3964 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3965 << sizeExpr->getSourceRange();
3971 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
3972 /// and float scalars, although arrays, pointers, and function return values are
3973 /// allowed in conjunction with this construct. Aggregates with this attribute
3974 /// are invalid, even if they are of the same size as a corresponding scalar.
3975 /// The raw attribute should contain precisely 1 argument, the vector size for
3976 /// the variable, measured in bytes. If curType and rawAttr are well formed,
3977 /// this routine will return a new vector type.
3978 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
3980 // Check the attribute arguments.
3981 if (Attr.getNumArgs() != 1) {
3982 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3986 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3987 llvm::APSInt vecSize(32);
3988 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3989 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
3990 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3991 << "vector_size" << sizeExpr->getSourceRange();
3995 // the base type must be integer or float, and can't already be a vector.
3996 if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
3997 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
4001 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4002 // vecSize is specified in bytes - convert to bits.
4003 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
4005 // the vector size needs to be an integral multiple of the type size.
4006 if (vectorSize % typeSize) {
4007 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
4008 << sizeExpr->getSourceRange();
4012 if (vectorSize == 0) {
4013 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
4014 << sizeExpr->getSourceRange();
4019 // Success! Instantiate the vector type, the number of elements is > 0, and
4020 // not required to be a power of 2, unlike GCC.
4021 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
4022 VectorType::GenericVector);
4025 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
4027 static void HandleExtVectorTypeAttr(QualType &CurType,
4028 const AttributeList &Attr,
4032 // Special case where the argument is a template id.
4033 if (Attr.getParameterName()) {
4035 SourceLocation TemplateKWLoc;
4037 id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
4039 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
4041 if (Size.isInvalid())
4044 sizeExpr = Size.get();
4046 // check the attribute arguments.
4047 if (Attr.getNumArgs() != 1) {
4048 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4051 sizeExpr = Attr.getArg(0);
4054 // Create the vector type.
4055 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
4060 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
4061 /// "neon_polyvector_type" attributes are used to create vector types that
4062 /// are mangled according to ARM's ABI. Otherwise, these types are identical
4063 /// to those created with the "vector_size" attribute. Unlike "vector_size"
4064 /// the argument to these Neon attributes is the number of vector elements,
4065 /// not the vector size in bytes. The vector width and element type must
4066 /// match one of the standard Neon vector types.
4067 static void HandleNeonVectorTypeAttr(QualType& CurType,
4068 const AttributeList &Attr, Sema &S,
4069 VectorType::VectorKind VecKind,
4070 const char *AttrName) {
4071 // Check the attribute arguments.
4072 if (Attr.getNumArgs() != 1) {
4073 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4077 // The number of elements must be an ICE.
4078 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
4079 llvm::APSInt numEltsInt(32);
4080 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
4081 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
4082 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
4083 << AttrName << numEltsExpr->getSourceRange();
4087 // Only certain element types are supported for Neon vectors.
4088 const BuiltinType* BTy = CurType->getAs<BuiltinType>();
4090 (VecKind == VectorType::NeonPolyVector &&
4091 BTy->getKind() != BuiltinType::SChar &&
4092 BTy->getKind() != BuiltinType::Short) ||
4093 (BTy->getKind() != BuiltinType::SChar &&
4094 BTy->getKind() != BuiltinType::UChar &&
4095 BTy->getKind() != BuiltinType::Short &&
4096 BTy->getKind() != BuiltinType::UShort &&
4097 BTy->getKind() != BuiltinType::Int &&
4098 BTy->getKind() != BuiltinType::UInt &&
4099 BTy->getKind() != BuiltinType::LongLong &&
4100 BTy->getKind() != BuiltinType::ULongLong &&
4101 BTy->getKind() != BuiltinType::Float)) {
4102 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
4106 // The total size of the vector must be 64 or 128 bits.
4107 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4108 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
4109 unsigned vecSize = typeSize * numElts;
4110 if (vecSize != 64 && vecSize != 128) {
4111 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
4116 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
4119 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
4120 bool isDeclSpec, AttributeList *attrs) {
4121 // Scan through and apply attributes to this type where it makes sense. Some
4122 // attributes (such as __address_space__, __vector_size__, etc) apply to the
4123 // type, but others can be present in the type specifiers even though they
4124 // apply to the decl. Here we apply type attributes and ignore the rest.
4126 AttributeList *next;
4128 AttributeList &attr = *attrs;
4129 next = attr.getNext();
4131 // Skip attributes that were marked to be invalid.
4132 if (attr.isInvalid())
4135 // If this is an attribute we can handle, do so now,
4136 // otherwise, add it to the FnAttrs list for rechaining.
4137 switch (attr.getKind()) {
4140 case AttributeList::AT_MayAlias:
4141 // FIXME: This attribute needs to actually be handled, but if we ignore
4142 // it it breaks large amounts of Linux software.
4143 attr.setUsedAsTypeAttr();
4145 case AttributeList::AT_AddressSpace:
4146 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
4147 attr.setUsedAsTypeAttr();
4149 OBJC_POINTER_TYPE_ATTRS_CASELIST:
4150 if (!handleObjCPointerTypeAttr(state, attr, type))
4151 distributeObjCPointerTypeAttr(state, attr, type);
4152 attr.setUsedAsTypeAttr();
4154 case AttributeList::AT_VectorSize:
4155 HandleVectorSizeAttr(type, attr, state.getSema());
4156 attr.setUsedAsTypeAttr();
4158 case AttributeList::AT_ExtVectorType:
4159 if (state.getDeclarator().getDeclSpec().getStorageClassSpec()
4160 != DeclSpec::SCS_typedef)
4161 HandleExtVectorTypeAttr(type, attr, state.getSema());
4162 attr.setUsedAsTypeAttr();
4164 case AttributeList::AT_NeonVectorType:
4165 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4166 VectorType::NeonVector, "neon_vector_type");
4167 attr.setUsedAsTypeAttr();
4169 case AttributeList::AT_NeonPolyVectorType:
4170 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4171 VectorType::NeonPolyVector,
4172 "neon_polyvector_type");
4173 attr.setUsedAsTypeAttr();
4175 case AttributeList::AT_OpenCLImageAccess:
4176 HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
4177 attr.setUsedAsTypeAttr();
4180 case AttributeList::AT_Win64:
4181 case AttributeList::AT_Ptr32:
4182 case AttributeList::AT_Ptr64:
4183 // FIXME: don't ignore these
4184 attr.setUsedAsTypeAttr();
4187 case AttributeList::AT_NSReturnsRetained:
4188 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
4190 // fallthrough into the function attrs
4192 FUNCTION_TYPE_ATTRS_CASELIST:
4193 attr.setUsedAsTypeAttr();
4195 // Never process function type attributes as part of the
4196 // declaration-specifiers.
4198 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
4200 // Otherwise, handle the possible delays.
4201 else if (!handleFunctionTypeAttr(state, attr, type))
4202 distributeFunctionTypeAttr(state, attr, type);
4205 } while ((attrs = next));
4208 /// \brief Ensure that the type of the given expression is complete.
4210 /// This routine checks whether the expression \p E has a complete type. If the
4211 /// expression refers to an instantiable construct, that instantiation is
4212 /// performed as needed to complete its type. Furthermore
4213 /// Sema::RequireCompleteType is called for the expression's type (or in the
4214 /// case of a reference type, the referred-to type).
4216 /// \param E The expression whose type is required to be complete.
4217 /// \param Diagnoser The object that will emit a diagnostic if the type is
4220 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
4222 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){
4223 QualType T = E->getType();
4225 // Fast path the case where the type is already complete.
4226 if (!T->isIncompleteType())
4229 // Incomplete array types may be completed by the initializer attached to
4230 // their definitions. For static data members of class templates we need to
4231 // instantiate the definition to get this initializer and complete the type.
4232 if (T->isIncompleteArrayType()) {
4233 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4234 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
4235 if (Var->isStaticDataMember() &&
4236 Var->getInstantiatedFromStaticDataMember()) {
4238 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
4239 assert(MSInfo && "Missing member specialization information?");
4240 if (MSInfo->getTemplateSpecializationKind()
4241 != TSK_ExplicitSpecialization) {
4242 // If we don't already have a point of instantiation, this is it.
4243 if (MSInfo->getPointOfInstantiation().isInvalid()) {
4244 MSInfo->setPointOfInstantiation(E->getLocStart());
4246 // This is a modification of an existing AST node. Notify
4248 if (ASTMutationListener *L = getASTMutationListener())
4249 L->StaticDataMemberInstantiated(Var);
4252 InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
4254 // Update the type to the newly instantiated definition's type both
4255 // here and within the expression.
4256 if (VarDecl *Def = Var->getDefinition()) {
4264 // We still go on to try to complete the type independently, as it
4265 // may also require instantiations or diagnostics if it remains
4272 // FIXME: Are there other cases which require instantiating something other
4273 // than the type to complete the type of an expression?
4275 // Look through reference types and complete the referred type.
4276 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4277 T = Ref->getPointeeType();
4279 return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
4283 struct TypeDiagnoserDiag : Sema::TypeDiagnoser {
4286 TypeDiagnoserDiag(unsigned DiagID)
4287 : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {}
4289 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
4290 if (Suppressed) return;
4291 S.Diag(Loc, DiagID) << T;
4296 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
4297 TypeDiagnoserDiag Diagnoser(DiagID);
4298 return RequireCompleteExprType(E, Diagnoser);
4301 /// @brief Ensure that the type T is a complete type.
4303 /// This routine checks whether the type @p T is complete in any
4304 /// context where a complete type is required. If @p T is a complete
4305 /// type, returns false. If @p T is a class template specialization,
4306 /// this routine then attempts to perform class template
4307 /// instantiation. If instantiation fails, or if @p T is incomplete
4308 /// and cannot be completed, issues the diagnostic @p diag (giving it
4309 /// the type @p T) and returns true.
4311 /// @param Loc The location in the source that the incomplete type
4312 /// diagnostic should refer to.
4314 /// @param T The type that this routine is examining for completeness.
4316 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
4317 /// @c false otherwise.
4318 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4319 TypeDiagnoser &Diagnoser) {
4320 // FIXME: Add this assertion to make sure we always get instantiation points.
4321 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
4322 // FIXME: Add this assertion to help us flush out problems with
4323 // checking for dependent types and type-dependent expressions.
4325 // assert(!T->isDependentType() &&
4326 // "Can't ask whether a dependent type is complete");
4328 // If we have a complete type, we're done.
4330 if (!T->isIncompleteType(&Def)) {
4331 // If we know about the definition but it is not visible, complain.
4332 if (!Diagnoser.Suppressed && Def && !LookupResult::isVisible(Def)) {
4333 // Suppress this error outside of a SFINAE context if we've already
4334 // emitted the error once for this type. There's no usefulness in
4335 // repeating the diagnostic.
4336 // FIXME: Add a Fix-It that imports the corresponding module or includes
4338 if (isSFINAEContext() || HiddenDefinitions.insert(Def)) {
4339 Diag(Loc, diag::err_module_private_definition) << T;
4340 Diag(Def->getLocation(), diag::note_previous_definition);
4347 const TagType *Tag = T->getAs<TagType>();
4348 const ObjCInterfaceType *IFace = 0;
4351 // Avoid diagnosing invalid decls as incomplete.
4352 if (Tag->getDecl()->isInvalidDecl())
4355 // Give the external AST source a chance to complete the type.
4356 if (Tag->getDecl()->hasExternalLexicalStorage()) {
4357 Context.getExternalSource()->CompleteType(Tag->getDecl());
4358 if (!Tag->isIncompleteType())
4362 else if ((IFace = T->getAs<ObjCInterfaceType>())) {
4363 // Avoid diagnosing invalid decls as incomplete.
4364 if (IFace->getDecl()->isInvalidDecl())
4367 // Give the external AST source a chance to complete the type.
4368 if (IFace->getDecl()->hasExternalLexicalStorage()) {
4369 Context.getExternalSource()->CompleteType(IFace->getDecl());
4370 if (!IFace->isIncompleteType())
4375 // If we have a class template specialization or a class member of a
4376 // class template specialization, or an array with known size of such,
4377 // try to instantiate it.
4378 QualType MaybeTemplate = T;
4379 while (const ConstantArrayType *Array
4380 = Context.getAsConstantArrayType(MaybeTemplate))
4381 MaybeTemplate = Array->getElementType();
4382 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
4383 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
4384 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
4385 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
4386 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
4387 TSK_ImplicitInstantiation,
4388 /*Complain=*/!Diagnoser.Suppressed);
4389 } else if (CXXRecordDecl *Rec
4390 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
4391 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
4392 if (!Rec->isBeingDefined() && Pattern) {
4393 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
4394 assert(MSI && "Missing member specialization information?");
4395 // This record was instantiated from a class within a template.
4396 if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
4397 return InstantiateClass(Loc, Rec, Pattern,
4398 getTemplateInstantiationArgs(Rec),
4399 TSK_ImplicitInstantiation,
4400 /*Complain=*/!Diagnoser.Suppressed);
4405 if (Diagnoser.Suppressed)
4408 // We have an incomplete type. Produce a diagnostic.
4409 Diagnoser.diagnose(*this, Loc, T);
4411 // If the type was a forward declaration of a class/struct/union
4412 // type, produce a note.
4413 if (Tag && !Tag->getDecl()->isInvalidDecl())
4414 Diag(Tag->getDecl()->getLocation(),
4415 Tag->isBeingDefined() ? diag::note_type_being_defined
4416 : diag::note_forward_declaration)
4417 << QualType(Tag, 0);
4419 // If the Objective-C class was a forward declaration, produce a note.
4420 if (IFace && !IFace->getDecl()->isInvalidDecl())
4421 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
4426 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4428 TypeDiagnoserDiag Diagnoser(DiagID);
4429 return RequireCompleteType(Loc, T, Diagnoser);
4432 /// @brief Ensure that the type T is a literal type.
4434 /// This routine checks whether the type @p T is a literal type. If @p T is an
4435 /// incomplete type, an attempt is made to complete it. If @p T is a literal
4436 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
4437 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
4438 /// it the type @p T), along with notes explaining why the type is not a
4439 /// literal type, and returns true.
4441 /// @param Loc The location in the source that the non-literal type
4442 /// diagnostic should refer to.
4444 /// @param T The type that this routine is examining for literalness.
4446 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
4448 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
4449 /// @c false otherwise.
4450 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
4451 TypeDiagnoser &Diagnoser) {
4452 assert(!T->isDependentType() && "type should not be dependent");
4454 QualType ElemType = Context.getBaseElementType(T);
4455 RequireCompleteType(Loc, ElemType, 0);
4457 if (T->isLiteralType())
4460 if (Diagnoser.Suppressed)
4463 Diagnoser.diagnose(*this, Loc, T);
4465 if (T->isVariableArrayType())
4468 const RecordType *RT = ElemType->getAs<RecordType>();
4472 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4474 // A partially-defined class type can't be a literal type, because a literal
4475 // class type must have a trivial destructor (which can't be checked until
4476 // the class definition is complete).
4477 if (!RD->isCompleteDefinition()) {
4478 RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T);
4482 // If the class has virtual base classes, then it's not an aggregate, and
4483 // cannot have any constexpr constructors or a trivial default constructor,
4484 // so is non-literal. This is better to diagnose than the resulting absence
4485 // of constexpr constructors.
4486 if (RD->getNumVBases()) {
4487 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
4488 << RD->isStruct() << RD->getNumVBases();
4489 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
4490 E = RD->vbases_end(); I != E; ++I)
4491 Diag(I->getLocStart(),
4492 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
4493 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
4494 !RD->hasTrivialDefaultConstructor()) {
4495 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
4496 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
4497 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4498 E = RD->bases_end(); I != E; ++I) {
4499 if (!I->getType()->isLiteralType()) {
4500 Diag(I->getLocStart(),
4501 diag::note_non_literal_base_class)
4502 << RD << I->getType() << I->getSourceRange();
4506 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
4507 E = RD->field_end(); I != E; ++I) {
4508 if (!I->getType()->isLiteralType() ||
4509 I->getType().isVolatileQualified()) {
4510 Diag(I->getLocation(), diag::note_non_literal_field)
4511 << RD << *I << I->getType()
4512 << I->getType().isVolatileQualified();
4516 } else if (!RD->hasTrivialDestructor()) {
4517 // All fields and bases are of literal types, so have trivial destructors.
4518 // If this class's destructor is non-trivial it must be user-declared.
4519 CXXDestructorDecl *Dtor = RD->getDestructor();
4520 assert(Dtor && "class has literal fields and bases but no dtor?");
4524 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
4525 diag::note_non_literal_user_provided_dtor :
4526 diag::note_non_literal_nontrivial_dtor) << RD;
4532 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
4533 TypeDiagnoserDiag Diagnoser(DiagID);
4534 return RequireLiteralType(Loc, T, Diagnoser);
4537 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
4538 /// and qualified by the nested-name-specifier contained in SS.
4539 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
4540 const CXXScopeSpec &SS, QualType T) {
4543 NestedNameSpecifier *NNS;
4545 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4547 if (Keyword == ETK_None)
4551 return Context.getElaboratedType(Keyword, NNS, T);
4554 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
4555 ExprResult ER = CheckPlaceholderExpr(E);
4556 if (ER.isInvalid()) return QualType();
4559 if (!E->isTypeDependent()) {
4560 QualType T = E->getType();
4561 if (const TagType *TT = T->getAs<TagType>())
4562 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
4564 return Context.getTypeOfExprType(E);
4567 /// getDecltypeForExpr - Given an expr, will return the decltype for
4568 /// that expression, according to the rules in C++11
4569 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
4570 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
4571 if (E->isTypeDependent())
4572 return S.Context.DependentTy;
4574 // C++11 [dcl.type.simple]p4:
4575 // The type denoted by decltype(e) is defined as follows:
4577 // - if e is an unparenthesized id-expression or an unparenthesized class
4578 // member access (5.2.5), decltype(e) is the type of the entity named
4579 // by e. If there is no such entity, or if e names a set of overloaded
4580 // functions, the program is ill-formed;
4581 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4582 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
4583 return VD->getType();
4585 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
4586 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4587 return FD->getType();
4590 // C++11 [expr.lambda.prim]p18:
4591 // Every occurrence of decltype((x)) where x is a possibly
4592 // parenthesized id-expression that names an entity of automatic
4593 // storage duration is treated as if x were transformed into an
4594 // access to a corresponding data member of the closure type that
4595 // would have been declared if x were an odr-use of the denoted
4597 using namespace sema;
4598 if (S.getCurLambda()) {
4599 if (isa<ParenExpr>(E)) {
4600 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4601 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
4602 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
4604 return S.Context.getLValueReferenceType(T);
4611 // C++11 [dcl.type.simple]p4:
4613 QualType T = E->getType();
4614 switch (E->getValueKind()) {
4615 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
4617 case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
4618 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
4620 case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
4621 // - otherwise, decltype(e) is the type of e.
4622 case VK_RValue: break;
4628 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
4629 ExprResult ER = CheckPlaceholderExpr(E);
4630 if (ER.isInvalid()) return QualType();
4633 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
4636 QualType Sema::BuildUnaryTransformType(QualType BaseType,
4637 UnaryTransformType::UTTKind UKind,
4638 SourceLocation Loc) {
4640 case UnaryTransformType::EnumUnderlyingType:
4641 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
4642 Diag(Loc, diag::err_only_enums_have_underlying_types);
4645 QualType Underlying = BaseType;
4646 if (!BaseType->isDependentType()) {
4647 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
4648 assert(ED && "EnumType has no EnumDecl");
4649 DiagnoseUseOfDecl(ED, Loc);
4650 Underlying = ED->getIntegerType();
4652 assert(!Underlying.isNull());
4653 return Context.getUnaryTransformType(BaseType, Underlying,
4654 UnaryTransformType::EnumUnderlyingType);
4657 llvm_unreachable("unknown unary transform type");
4660 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
4661 if (!T->isDependentType()) {
4662 // FIXME: It isn't entirely clear whether incomplete atomic types
4663 // are allowed or not; for simplicity, ban them for the moment.
4664 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
4667 int DisallowedKind = -1;
4668 if (T->isArrayType())
4670 else if (T->isFunctionType())
4672 else if (T->isReferenceType())
4674 else if (T->isAtomicType())
4676 else if (T.hasQualifiers())
4678 else if (!T.isTriviallyCopyableType(Context))
4679 // Some other non-trivially-copyable type (probably a C++ class)
4682 if (DisallowedKind != -1) {
4683 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
4687 // FIXME: Do we need any handling for ARC here?
4690 // Build the pointer type.
4691 return Context.getAtomicType(T);