1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements type-related semantic analysis.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Template.h"
16 #include "clang/Basic/OpenCL.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/TypeLoc.h"
23 #include "clang/AST/TypeLocVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/Basic/PartialDiagnostic.h"
26 #include "clang/Basic/TargetInfo.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/DelayedDiagnostic.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/Support/ErrorHandling.h"
32 using namespace clang;
34 /// isOmittedBlockReturnType - Return true if this declarator is missing a
35 /// return type because this is a omitted return type on a block literal.
36 static bool isOmittedBlockReturnType(const Declarator &D) {
37 if (D.getContext() != Declarator::BlockLiteralContext ||
38 D.getDeclSpec().hasTypeSpecifier())
41 if (D.getNumTypeObjects() == 0)
42 return true; // ^{ ... }
44 if (D.getNumTypeObjects() == 1 &&
45 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
46 return true; // ^(int X, float Y) { ... }
51 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
52 /// doesn't apply to the given type.
53 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
55 bool useExpansionLoc = false;
58 switch (attr.getKind()) {
59 case AttributeList::AT_objc_gc:
60 diagID = diag::warn_pointer_attribute_wrong_type;
61 useExpansionLoc = true;
64 case AttributeList::AT_objc_ownership:
65 diagID = diag::warn_objc_object_attribute_wrong_type;
66 useExpansionLoc = true;
70 // Assume everything else was a function attribute.
71 diagID = diag::warn_function_attribute_wrong_type;
75 SourceLocation loc = attr.getLoc();
76 StringRef name = attr.getName()->getName();
78 // The GC attributes are usually written with macros; special-case them.
79 if (useExpansionLoc && loc.isMacroID() && attr.getParameterName()) {
80 if (attr.getParameterName()->isStr("strong")) {
81 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
82 } else if (attr.getParameterName()->isStr("weak")) {
83 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
87 S.Diag(loc, diagID) << name << type;
90 // objc_gc applies to Objective-C pointers or, otherwise, to the
91 // smallest available pointer type (i.e. 'void*' in 'void**').
92 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
93 case AttributeList::AT_objc_gc: \
94 case AttributeList::AT_objc_ownership
96 // Function type attributes.
97 #define FUNCTION_TYPE_ATTRS_CASELIST \
98 case AttributeList::AT_noreturn: \
99 case AttributeList::AT_cdecl: \
100 case AttributeList::AT_fastcall: \
101 case AttributeList::AT_stdcall: \
102 case AttributeList::AT_thiscall: \
103 case AttributeList::AT_pascal: \
104 case AttributeList::AT_regparm: \
105 case AttributeList::AT_pcs \
108 /// An object which stores processing state for the entire
109 /// GetTypeForDeclarator process.
110 class TypeProcessingState {
113 /// The declarator being processed.
114 Declarator &declarator;
116 /// The index of the declarator chunk we're currently processing.
117 /// May be the total number of valid chunks, indicating the
121 /// Whether there are non-trivial modifications to the decl spec.
124 /// Whether we saved the attributes in the decl spec.
127 /// The original set of attributes on the DeclSpec.
128 SmallVector<AttributeList*, 2> savedAttrs;
130 /// A list of attributes to diagnose the uselessness of when the
131 /// processing is complete.
132 SmallVector<AttributeList*, 2> ignoredTypeAttrs;
135 TypeProcessingState(Sema &sema, Declarator &declarator)
136 : sema(sema), declarator(declarator),
137 chunkIndex(declarator.getNumTypeObjects()),
138 trivial(true), hasSavedAttrs(false) {}
140 Sema &getSema() const {
144 Declarator &getDeclarator() const {
148 unsigned getCurrentChunkIndex() const {
152 void setCurrentChunkIndex(unsigned idx) {
153 assert(idx <= declarator.getNumTypeObjects());
157 AttributeList *&getCurrentAttrListRef() const {
158 assert(chunkIndex <= declarator.getNumTypeObjects());
159 if (chunkIndex == declarator.getNumTypeObjects())
160 return getMutableDeclSpec().getAttributes().getListRef();
161 return declarator.getTypeObject(chunkIndex).getAttrListRef();
164 /// Save the current set of attributes on the DeclSpec.
165 void saveDeclSpecAttrs() {
166 // Don't try to save them multiple times.
167 if (hasSavedAttrs) return;
169 DeclSpec &spec = getMutableDeclSpec();
170 for (AttributeList *attr = spec.getAttributes().getList(); attr;
171 attr = attr->getNext())
172 savedAttrs.push_back(attr);
173 trivial &= savedAttrs.empty();
174 hasSavedAttrs = true;
177 /// Record that we had nowhere to put the given type attribute.
178 /// We will diagnose such attributes later.
179 void addIgnoredTypeAttr(AttributeList &attr) {
180 ignoredTypeAttrs.push_back(&attr);
183 /// Diagnose all the ignored type attributes, given that the
184 /// declarator worked out to the given type.
185 void diagnoseIgnoredTypeAttrs(QualType type) const {
186 for (SmallVectorImpl<AttributeList*>::const_iterator
187 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
189 diagnoseBadTypeAttribute(getSema(), **i, type);
192 ~TypeProcessingState() {
195 restoreDeclSpecAttrs();
199 DeclSpec &getMutableDeclSpec() const {
200 return const_cast<DeclSpec&>(declarator.getDeclSpec());
203 void restoreDeclSpecAttrs() {
204 assert(hasSavedAttrs);
206 if (savedAttrs.empty()) {
207 getMutableDeclSpec().getAttributes().set(0);
211 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
212 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
213 savedAttrs[i]->setNext(savedAttrs[i+1]);
214 savedAttrs.back()->setNext(0);
218 /// Basically std::pair except that we really want to avoid an
219 /// implicit operator= for safety concerns. It's also a minor
220 /// link-time optimization for this to be a private type.
223 AttributeList &first;
225 /// The head of the list the attribute is currently in.
226 AttributeList *&second;
228 AttrAndList(AttributeList &attr, AttributeList *&head)
229 : first(attr), second(head) {}
234 template <> struct isPodLike<AttrAndList> {
235 static const bool value = true;
239 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
244 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
246 head = attr.getNext();
250 AttributeList *cur = head;
252 assert(cur && cur->getNext() && "ran out of attrs?");
253 if (cur->getNext() == &attr) {
254 cur->setNext(attr.getNext());
257 cur = cur->getNext();
261 static void moveAttrFromListToList(AttributeList &attr,
262 AttributeList *&fromList,
263 AttributeList *&toList) {
264 spliceAttrOutOfList(attr, fromList);
265 spliceAttrIntoList(attr, toList);
268 static void processTypeAttrs(TypeProcessingState &state,
269 QualType &type, bool isDeclSpec,
270 AttributeList *attrs);
272 static bool handleFunctionTypeAttr(TypeProcessingState &state,
276 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
277 AttributeList &attr, QualType &type);
279 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
280 AttributeList &attr, QualType &type);
282 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
283 AttributeList &attr, QualType &type) {
284 if (attr.getKind() == AttributeList::AT_objc_gc)
285 return handleObjCGCTypeAttr(state, attr, type);
286 assert(attr.getKind() == AttributeList::AT_objc_ownership);
287 return handleObjCOwnershipTypeAttr(state, attr, type);
290 /// Given that an objc_gc attribute was written somewhere on a
291 /// declaration *other* than on the declarator itself (for which, use
292 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
293 /// didn't apply in whatever position it was written in, try to move
294 /// it to a more appropriate position.
295 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
298 Declarator &declarator = state.getDeclarator();
299 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
300 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
301 switch (chunk.Kind) {
302 case DeclaratorChunk::Pointer:
303 case DeclaratorChunk::BlockPointer:
304 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
305 chunk.getAttrListRef());
308 case DeclaratorChunk::Paren:
309 case DeclaratorChunk::Array:
312 // Don't walk through these.
313 case DeclaratorChunk::Reference:
314 case DeclaratorChunk::Function:
315 case DeclaratorChunk::MemberPointer:
321 diagnoseBadTypeAttribute(state.getSema(), attr, type);
324 /// Distribute an objc_gc type attribute that was written on the
327 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
329 QualType &declSpecType) {
330 Declarator &declarator = state.getDeclarator();
332 // objc_gc goes on the innermost pointer to something that's not a
334 unsigned innermost = -1U;
335 bool considerDeclSpec = true;
336 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
337 DeclaratorChunk &chunk = declarator.getTypeObject(i);
338 switch (chunk.Kind) {
339 case DeclaratorChunk::Pointer:
340 case DeclaratorChunk::BlockPointer:
344 case DeclaratorChunk::Reference:
345 case DeclaratorChunk::MemberPointer:
346 case DeclaratorChunk::Paren:
347 case DeclaratorChunk::Array:
350 case DeclaratorChunk::Function:
351 considerDeclSpec = false;
357 // That might actually be the decl spec if we weren't blocked by
358 // anything in the declarator.
359 if (considerDeclSpec) {
360 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
361 // Splice the attribute into the decl spec. Prevents the
362 // attribute from being applied multiple times and gives
363 // the source-location-filler something to work with.
364 state.saveDeclSpecAttrs();
365 moveAttrFromListToList(attr, declarator.getAttrListRef(),
366 declarator.getMutableDeclSpec().getAttributes().getListRef());
371 // Otherwise, if we found an appropriate chunk, splice the attribute
373 if (innermost != -1U) {
374 moveAttrFromListToList(attr, declarator.getAttrListRef(),
375 declarator.getTypeObject(innermost).getAttrListRef());
379 // Otherwise, diagnose when we're done building the type.
380 spliceAttrOutOfList(attr, declarator.getAttrListRef());
381 state.addIgnoredTypeAttr(attr);
384 /// A function type attribute was written somewhere in a declaration
385 /// *other* than on the declarator itself or in the decl spec. Given
386 /// that it didn't apply in whatever position it was written in, try
387 /// to move it to a more appropriate position.
388 static void distributeFunctionTypeAttr(TypeProcessingState &state,
391 Declarator &declarator = state.getDeclarator();
393 // Try to push the attribute from the return type of a function to
394 // the function itself.
395 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
396 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
397 switch (chunk.Kind) {
398 case DeclaratorChunk::Function:
399 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
400 chunk.getAttrListRef());
403 case DeclaratorChunk::Paren:
404 case DeclaratorChunk::Pointer:
405 case DeclaratorChunk::BlockPointer:
406 case DeclaratorChunk::Array:
407 case DeclaratorChunk::Reference:
408 case DeclaratorChunk::MemberPointer:
413 diagnoseBadTypeAttribute(state.getSema(), attr, type);
416 /// Try to distribute a function type attribute to the innermost
417 /// function chunk or type. Returns true if the attribute was
418 /// distributed, false if no location was found.
420 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
422 AttributeList *&attrList,
423 QualType &declSpecType) {
424 Declarator &declarator = state.getDeclarator();
426 // Put it on the innermost function chunk, if there is one.
427 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
428 DeclaratorChunk &chunk = declarator.getTypeObject(i);
429 if (chunk.Kind != DeclaratorChunk::Function) continue;
431 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
435 if (handleFunctionTypeAttr(state, attr, declSpecType)) {
436 spliceAttrOutOfList(attr, attrList);
443 /// A function type attribute was written in the decl spec. Try to
444 /// apply it somewhere.
446 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
448 QualType &declSpecType) {
449 state.saveDeclSpecAttrs();
451 // Try to distribute to the innermost.
452 if (distributeFunctionTypeAttrToInnermost(state, attr,
453 state.getCurrentAttrListRef(),
457 // If that failed, diagnose the bad attribute when the declarator is
459 state.addIgnoredTypeAttr(attr);
462 /// A function type attribute was written on the declarator. Try to
463 /// apply it somewhere.
465 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
467 QualType &declSpecType) {
468 Declarator &declarator = state.getDeclarator();
470 // Try to distribute to the innermost.
471 if (distributeFunctionTypeAttrToInnermost(state, attr,
472 declarator.getAttrListRef(),
476 // If that failed, diagnose the bad attribute when the declarator is
478 spliceAttrOutOfList(attr, declarator.getAttrListRef());
479 state.addIgnoredTypeAttr(attr);
482 /// \brief Given that there are attributes written on the declarator
483 /// itself, try to distribute any type attributes to the appropriate
484 /// declarator chunk.
486 /// These are attributes like the following:
489 /// but not necessarily this:
491 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
492 QualType &declSpecType) {
493 // Collect all the type attributes from the declarator itself.
494 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
495 AttributeList *attr = state.getDeclarator().getAttributes();
498 next = attr->getNext();
500 switch (attr->getKind()) {
501 OBJC_POINTER_TYPE_ATTRS_CASELIST:
502 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
505 case AttributeList::AT_ns_returns_retained:
506 if (!state.getSema().getLangOptions().ObjCAutoRefCount)
510 FUNCTION_TYPE_ATTRS_CASELIST:
511 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
517 } while ((attr = next));
520 /// Add a synthetic '()' to a block-literal declarator if it is
521 /// required, given the return type.
522 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
523 QualType declSpecType) {
524 Declarator &declarator = state.getDeclarator();
526 // First, check whether the declarator would produce a function,
527 // i.e. whether the innermost semantic chunk is a function.
528 if (declarator.isFunctionDeclarator()) {
529 // If so, make that declarator a prototyped declarator.
530 declarator.getFunctionTypeInfo().hasPrototype = true;
534 // If there are any type objects, the type as written won't name a
535 // function, regardless of the decl spec type. This is because a
536 // block signature declarator is always an abstract-declarator, and
537 // abstract-declarators can't just be parentheses chunks. Therefore
538 // we need to build a function chunk unless there are no type
539 // objects and the decl spec type is a function.
540 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
543 // Note that there *are* cases with invalid declarators where
544 // declarators consist solely of parentheses. In general, these
545 // occur only in failed efforts to make function declarators, so
546 // faking up the function chunk is still the right thing to do.
548 // Otherwise, we need to fake up a function declarator.
549 SourceLocation loc = declarator.getSourceRange().getBegin();
551 // ...and *prepend* it to the declarator.
552 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
554 /*variadic*/ false, SourceLocation(),
557 /*ref-qualifier*/true, SourceLocation(),
558 /*mutable qualifier*/SourceLocation(),
559 /*EH*/ EST_None, SourceLocation(), 0, 0, 0, 0,
563 // For consistency, make sure the state still has us as processing
565 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
566 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
569 /// \brief Convert the specified declspec to the appropriate type
571 /// \param D the declarator containing the declaration specifier.
572 /// \returns The type described by the declaration specifiers. This function
573 /// never returns null.
574 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
575 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
578 Sema &S = state.getSema();
579 Declarator &declarator = state.getDeclarator();
580 const DeclSpec &DS = declarator.getDeclSpec();
581 SourceLocation DeclLoc = declarator.getIdentifierLoc();
582 if (DeclLoc.isInvalid())
583 DeclLoc = DS.getSourceRange().getBegin();
585 ASTContext &Context = S.Context;
588 switch (DS.getTypeSpecType()) {
589 case DeclSpec::TST_void:
590 Result = Context.VoidTy;
592 case DeclSpec::TST_char:
593 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
594 Result = Context.CharTy;
595 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
596 Result = Context.SignedCharTy;
598 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
599 "Unknown TSS value");
600 Result = Context.UnsignedCharTy;
603 case DeclSpec::TST_wchar:
604 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
605 Result = Context.WCharTy;
606 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
607 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
608 << DS.getSpecifierName(DS.getTypeSpecType());
609 Result = Context.getSignedWCharType();
611 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
612 "Unknown TSS value");
613 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
614 << DS.getSpecifierName(DS.getTypeSpecType());
615 Result = Context.getUnsignedWCharType();
618 case DeclSpec::TST_char16:
619 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
620 "Unknown TSS value");
621 Result = Context.Char16Ty;
623 case DeclSpec::TST_char32:
624 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
625 "Unknown TSS value");
626 Result = Context.Char32Ty;
628 case DeclSpec::TST_unspecified:
629 // "<proto1,proto2>" is an objc qualified ID with a missing id.
630 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
631 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
632 (ObjCProtocolDecl**)PQ,
633 DS.getNumProtocolQualifiers());
634 Result = Context.getObjCObjectPointerType(Result);
638 // If this is a missing declspec in a block literal return context, then it
639 // is inferred from the return statements inside the block.
640 if (isOmittedBlockReturnType(declarator)) {
641 Result = Context.DependentTy;
645 // Unspecified typespec defaults to int in C90. However, the C90 grammar
646 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
647 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
648 // Note that the one exception to this is function definitions, which are
649 // allowed to be completely missing a declspec. This is handled in the
650 // parser already though by it pretending to have seen an 'int' in this
652 if (S.getLangOptions().ImplicitInt) {
653 // In C89 mode, we only warn if there is a completely missing declspec
654 // when one is not allowed.
656 S.Diag(DeclLoc, diag::ext_missing_declspec)
657 << DS.getSourceRange()
658 << FixItHint::CreateInsertion(DS.getSourceRange().getBegin(), "int");
660 } else if (!DS.hasTypeSpecifier()) {
661 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
662 // "At least one type specifier shall be given in the declaration
663 // specifiers in each declaration, and in the specifier-qualifier list in
664 // each struct declaration and type name."
665 // FIXME: Does Microsoft really have the implicit int extension in C++?
666 if (S.getLangOptions().CPlusPlus &&
667 !S.getLangOptions().MicrosoftExt) {
668 S.Diag(DeclLoc, diag::err_missing_type_specifier)
669 << DS.getSourceRange();
671 // When this occurs in C++ code, often something is very broken with the
672 // value being declared, poison it as invalid so we don't get chains of
674 declarator.setInvalidType(true);
676 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
677 << DS.getSourceRange();
682 case DeclSpec::TST_int: {
683 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
684 switch (DS.getTypeSpecWidth()) {
685 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
686 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
687 case DeclSpec::TSW_long: Result = Context.LongTy; break;
688 case DeclSpec::TSW_longlong:
689 Result = Context.LongLongTy;
691 // long long is a C99 feature.
692 if (!S.getLangOptions().C99 &&
693 !S.getLangOptions().CPlusPlus0x)
694 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
698 switch (DS.getTypeSpecWidth()) {
699 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
700 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
701 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
702 case DeclSpec::TSW_longlong:
703 Result = Context.UnsignedLongLongTy;
705 // long long is a C99 feature.
706 if (!S.getLangOptions().C99 &&
707 !S.getLangOptions().CPlusPlus0x)
708 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
714 case DeclSpec::TST_half: Result = Context.HalfTy; break;
715 case DeclSpec::TST_float: Result = Context.FloatTy; break;
716 case DeclSpec::TST_double:
717 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
718 Result = Context.LongDoubleTy;
720 Result = Context.DoubleTy;
722 if (S.getLangOptions().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
723 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
724 declarator.setInvalidType(true);
727 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
728 case DeclSpec::TST_decimal32: // _Decimal32
729 case DeclSpec::TST_decimal64: // _Decimal64
730 case DeclSpec::TST_decimal128: // _Decimal128
731 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
732 Result = Context.IntTy;
733 declarator.setInvalidType(true);
735 case DeclSpec::TST_class:
736 case DeclSpec::TST_enum:
737 case DeclSpec::TST_union:
738 case DeclSpec::TST_struct: {
739 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
741 // This can happen in C++ with ambiguous lookups.
742 Result = Context.IntTy;
743 declarator.setInvalidType(true);
747 // If the type is deprecated or unavailable, diagnose it.
748 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
750 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
751 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
753 // TypeQuals handled by caller.
754 Result = Context.getTypeDeclType(D);
756 // In both C and C++, make an ElaboratedType.
757 ElaboratedTypeKeyword Keyword
758 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
759 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
761 if (D->isInvalidDecl())
762 declarator.setInvalidType(true);
765 case DeclSpec::TST_typename: {
766 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
767 DS.getTypeSpecSign() == 0 &&
768 "Can't handle qualifiers on typedef names yet!");
769 Result = S.GetTypeFromParser(DS.getRepAsType());
771 declarator.setInvalidType(true);
772 else if (DeclSpec::ProtocolQualifierListTy PQ
773 = DS.getProtocolQualifiers()) {
774 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
775 // Silently drop any existing protocol qualifiers.
776 // TODO: determine whether that's the right thing to do.
777 if (ObjT->getNumProtocols())
778 Result = ObjT->getBaseType();
780 if (DS.getNumProtocolQualifiers())
781 Result = Context.getObjCObjectType(Result,
782 (ObjCProtocolDecl**) PQ,
783 DS.getNumProtocolQualifiers());
784 } else if (Result->isObjCIdType()) {
786 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
787 (ObjCProtocolDecl**) PQ,
788 DS.getNumProtocolQualifiers());
789 Result = Context.getObjCObjectPointerType(Result);
790 } else if (Result->isObjCClassType()) {
791 // Class<protocol-list>
792 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
793 (ObjCProtocolDecl**) PQ,
794 DS.getNumProtocolQualifiers());
795 Result = Context.getObjCObjectPointerType(Result);
797 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
798 << DS.getSourceRange();
799 declarator.setInvalidType(true);
803 // TypeQuals handled by caller.
806 case DeclSpec::TST_typeofType:
807 // FIXME: Preserve type source info.
808 Result = S.GetTypeFromParser(DS.getRepAsType());
809 assert(!Result.isNull() && "Didn't get a type for typeof?");
810 if (!Result->isDependentType())
811 if (const TagType *TT = Result->getAs<TagType>())
812 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
813 // TypeQuals handled by caller.
814 Result = Context.getTypeOfType(Result);
816 case DeclSpec::TST_typeofExpr: {
817 Expr *E = DS.getRepAsExpr();
818 assert(E && "Didn't get an expression for typeof?");
819 // TypeQuals handled by caller.
820 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
821 if (Result.isNull()) {
822 Result = Context.IntTy;
823 declarator.setInvalidType(true);
827 case DeclSpec::TST_decltype: {
828 Expr *E = DS.getRepAsExpr();
829 assert(E && "Didn't get an expression for decltype?");
830 // TypeQuals handled by caller.
831 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
832 if (Result.isNull()) {
833 Result = Context.IntTy;
834 declarator.setInvalidType(true);
838 case DeclSpec::TST_underlyingType:
839 Result = S.GetTypeFromParser(DS.getRepAsType());
840 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
841 Result = S.BuildUnaryTransformType(Result,
842 UnaryTransformType::EnumUnderlyingType,
843 DS.getTypeSpecTypeLoc());
844 if (Result.isNull()) {
845 Result = Context.IntTy;
846 declarator.setInvalidType(true);
850 case DeclSpec::TST_auto: {
851 // TypeQuals handled by caller.
852 Result = Context.getAutoType(QualType());
856 case DeclSpec::TST_unknown_anytype:
857 Result = Context.UnknownAnyTy;
860 case DeclSpec::TST_atomic:
861 Result = S.GetTypeFromParser(DS.getRepAsType());
862 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
863 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
864 if (Result.isNull()) {
865 Result = Context.IntTy;
866 declarator.setInvalidType(true);
870 case DeclSpec::TST_error:
871 Result = Context.IntTy;
872 declarator.setInvalidType(true);
876 // Handle complex types.
877 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
878 if (S.getLangOptions().Freestanding)
879 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
880 Result = Context.getComplexType(Result);
881 } else if (DS.isTypeAltiVecVector()) {
882 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
883 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
884 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
885 if (DS.isTypeAltiVecPixel())
886 VecKind = VectorType::AltiVecPixel;
887 else if (DS.isTypeAltiVecBool())
888 VecKind = VectorType::AltiVecBool;
889 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
893 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
894 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
896 // Before we process any type attributes, synthesize a block literal
897 // function declarator if necessary.
898 if (declarator.getContext() == Declarator::BlockLiteralContext)
899 maybeSynthesizeBlockSignature(state, Result);
901 // Apply any type attributes from the decl spec. This may cause the
902 // list of type attributes to be temporarily saved while the type
903 // attributes are pushed around.
904 if (AttributeList *attrs = DS.getAttributes().getList())
905 processTypeAttrs(state, Result, true, attrs);
907 // Apply const/volatile/restrict qualifiers to T.
908 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
910 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
911 // or incomplete types shall not be restrict-qualified." C++ also allows
912 // restrict-qualified references.
913 if (TypeQuals & DeclSpec::TQ_restrict) {
914 if (Result->isAnyPointerType() || Result->isReferenceType()) {
916 if (Result->isObjCObjectPointerType())
919 EltTy = Result->isPointerType() ?
920 Result->getAs<PointerType>()->getPointeeType() :
921 Result->getAs<ReferenceType>()->getPointeeType();
923 // If we have a pointer or reference, the pointee must have an object
925 if (!EltTy->isIncompleteOrObjectType()) {
926 S.Diag(DS.getRestrictSpecLoc(),
927 diag::err_typecheck_invalid_restrict_invalid_pointee)
928 << EltTy << DS.getSourceRange();
929 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
932 S.Diag(DS.getRestrictSpecLoc(),
933 diag::err_typecheck_invalid_restrict_not_pointer)
934 << Result << DS.getSourceRange();
935 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
939 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
940 // of a function type includes any type qualifiers, the behavior is
942 if (Result->isFunctionType() && TypeQuals) {
943 // Get some location to point at, either the C or V location.
945 if (TypeQuals & DeclSpec::TQ_const)
946 Loc = DS.getConstSpecLoc();
947 else if (TypeQuals & DeclSpec::TQ_volatile)
948 Loc = DS.getVolatileSpecLoc();
950 assert((TypeQuals & DeclSpec::TQ_restrict) &&
951 "Has CVR quals but not C, V, or R?");
952 Loc = DS.getRestrictSpecLoc();
954 S.Diag(Loc, diag::warn_typecheck_function_qualifiers)
955 << Result << DS.getSourceRange();
959 // Cv-qualified references are ill-formed except when the
960 // cv-qualifiers are introduced through the use of a typedef
961 // (7.1.3) or of a template type argument (14.3), in which
962 // case the cv-qualifiers are ignored.
963 // FIXME: Shouldn't we be checking SCS_typedef here?
964 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
965 TypeQuals && Result->isReferenceType()) {
966 TypeQuals &= ~DeclSpec::TQ_const;
967 TypeQuals &= ~DeclSpec::TQ_volatile;
970 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
971 Result = Context.getQualifiedType(Result, Quals);
977 static std::string getPrintableNameForEntity(DeclarationName Entity) {
979 return Entity.getAsString();
984 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
986 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
987 // object or incomplete types shall not be restrict-qualified."
988 if (Qs.hasRestrict()) {
992 const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
993 if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) {
994 if (!RTy->getPointeeType()->isIncompleteOrObjectType()) {
995 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
996 ProblemTy = T->getAs<ReferenceType>()->getPointeeType();
998 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
999 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
1000 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1001 ProblemTy = T->getAs<PointerType>()->getPointeeType();
1003 } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) {
1004 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
1005 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1006 ProblemTy = T->getAs<PointerType>()->getPointeeType();
1008 } else if (!Ty->isDependentType()) {
1009 // FIXME: this deserves a proper diagnostic
1010 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1015 Diag(Loc, DiagID) << ProblemTy;
1016 Qs.removeRestrict();
1020 return Context.getQualifiedType(T, Qs);
1023 /// \brief Build a paren type including \p T.
1024 QualType Sema::BuildParenType(QualType T) {
1025 return Context.getParenType(T);
1028 /// Given that we're building a pointer or reference to the given
1029 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1032 // Bail out if retention is unrequired or already specified.
1033 if (!type->isObjCLifetimeType() ||
1034 type.getObjCLifetime() != Qualifiers::OCL_None)
1037 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1039 // If the object type is const-qualified, we can safely use
1040 // __unsafe_unretained. This is safe (because there are no read
1041 // barriers), and it'll be safe to coerce anything but __weak* to
1042 // the resulting type.
1043 if (type.isConstQualified()) {
1044 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1046 // Otherwise, check whether the static type does not require
1047 // retaining. This currently only triggers for Class (possibly
1048 // protocol-qualifed, and arrays thereof).
1049 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1050 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1052 // If we are in an unevaluated context, like sizeof, assume ExplicitNone and
1053 // don't give error.
1054 } else if (S.ExprEvalContexts.back().Context == Sema::Unevaluated) {
1055 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1057 // If that failed, give an error and recover using __autoreleasing.
1059 // These types can show up in private ivars in system headers, so
1060 // we need this to not be an error in those cases. Instead we
1062 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1063 S.DelayedDiagnostics.add(
1064 sema::DelayedDiagnostic::makeForbiddenType(loc,
1065 diag::err_arc_indirect_no_ownership, type, isReference));
1067 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1069 implicitLifetime = Qualifiers::OCL_Autoreleasing;
1071 assert(implicitLifetime && "didn't infer any lifetime!");
1074 qs.addObjCLifetime(implicitLifetime);
1075 return S.Context.getQualifiedType(type, qs);
1078 /// \brief Build a pointer type.
1080 /// \param T The type to which we'll be building a pointer.
1082 /// \param Loc The location of the entity whose type involves this
1083 /// pointer type or, if there is no such entity, the location of the
1084 /// type that will have pointer type.
1086 /// \param Entity The name of the entity that involves the pointer
1089 /// \returns A suitable pointer type, if there are no
1090 /// errors. Otherwise, returns a NULL type.
1091 QualType Sema::BuildPointerType(QualType T,
1092 SourceLocation Loc, DeclarationName Entity) {
1093 if (T->isReferenceType()) {
1094 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1095 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1096 << getPrintableNameForEntity(Entity) << T;
1100 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1102 // In ARC, it is forbidden to build pointers to unqualified pointers.
1103 if (getLangOptions().ObjCAutoRefCount)
1104 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1106 // Build the pointer type.
1107 return Context.getPointerType(T);
1110 /// \brief Build a reference type.
1112 /// \param T The type to which we'll be building a reference.
1114 /// \param Loc The location of the entity whose type involves this
1115 /// reference type or, if there is no such entity, the location of the
1116 /// type that will have reference type.
1118 /// \param Entity The name of the entity that involves the reference
1121 /// \returns A suitable reference type, if there are no
1122 /// errors. Otherwise, returns a NULL type.
1123 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1125 DeclarationName Entity) {
1126 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1127 "Unresolved overloaded function type");
1129 // C++0x [dcl.ref]p6:
1130 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1131 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1132 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1133 // the type "lvalue reference to T", while an attempt to create the type
1134 // "rvalue reference to cv TR" creates the type TR.
1135 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1137 // C++ [dcl.ref]p4: There shall be no references to references.
1139 // According to C++ DR 106, references to references are only
1140 // diagnosed when they are written directly (e.g., "int & &"),
1141 // but not when they happen via a typedef:
1143 // typedef int& intref;
1144 // typedef intref& intref2;
1146 // Parser::ParseDeclaratorInternal diagnoses the case where
1147 // references are written directly; here, we handle the
1148 // collapsing of references-to-references as described in C++0x.
1149 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1152 // A declarator that specifies the type "reference to cv void"
1154 if (T->isVoidType()) {
1155 Diag(Loc, diag::err_reference_to_void);
1159 // In ARC, it is forbidden to build references to unqualified pointers.
1160 if (getLangOptions().ObjCAutoRefCount)
1161 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1163 // Handle restrict on references.
1165 return Context.getLValueReferenceType(T, SpelledAsLValue);
1166 return Context.getRValueReferenceType(T);
1169 /// Check whether the specified array size makes the array type a VLA. If so,
1170 /// return true, if not, return the size of the array in SizeVal.
1171 static bool isArraySizeVLA(Expr *ArraySize, llvm::APSInt &SizeVal, Sema &S) {
1172 // If the size is an ICE, it certainly isn't a VLA.
1173 if (ArraySize->isIntegerConstantExpr(SizeVal, S.Context))
1176 // If we're in a GNU mode (like gnu99, but not c99) accept any evaluatable
1177 // value as an extension.
1178 Expr::EvalResult Result;
1179 if (S.LangOpts.GNUMode && ArraySize->Evaluate(Result, S.Context)) {
1180 if (!Result.hasSideEffects() && Result.Val.isInt()) {
1181 SizeVal = Result.Val.getInt();
1182 S.Diag(ArraySize->getLocStart(), diag::ext_vla_folded_to_constant);
1191 /// \brief Build an array type.
1193 /// \param T The type of each element in the array.
1195 /// \param ASM C99 array size modifier (e.g., '*', 'static').
1197 /// \param ArraySize Expression describing the size of the array.
1199 /// \param Loc The location of the entity whose type involves this
1200 /// array type or, if there is no such entity, the location of the
1201 /// type that will have array type.
1203 /// \param Entity The name of the entity that involves the array
1206 /// \returns A suitable array type, if there are no errors. Otherwise,
1207 /// returns a NULL type.
1208 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1209 Expr *ArraySize, unsigned Quals,
1210 SourceRange Brackets, DeclarationName Entity) {
1212 SourceLocation Loc = Brackets.getBegin();
1213 if (getLangOptions().CPlusPlus) {
1214 // C++ [dcl.array]p1:
1215 // T is called the array element type; this type shall not be a reference
1216 // type, the (possibly cv-qualified) type void, a function type or an
1217 // abstract class type.
1219 // Note: function types are handled in the common path with C.
1220 if (T->isReferenceType()) {
1221 Diag(Loc, diag::err_illegal_decl_array_of_references)
1222 << getPrintableNameForEntity(Entity) << T;
1226 if (T->isVoidType()) {
1227 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1231 if (RequireNonAbstractType(Brackets.getBegin(), T,
1232 diag::err_array_of_abstract_type))
1236 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1237 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
1238 if (RequireCompleteType(Loc, T,
1239 diag::err_illegal_decl_array_incomplete_type))
1243 if (T->isFunctionType()) {
1244 Diag(Loc, diag::err_illegal_decl_array_of_functions)
1245 << getPrintableNameForEntity(Entity) << T;
1249 if (T->getContainedAutoType()) {
1250 Diag(Loc, diag::err_illegal_decl_array_of_auto)
1251 << getPrintableNameForEntity(Entity) << T;
1255 if (const RecordType *EltTy = T->getAs<RecordType>()) {
1256 // If the element type is a struct or union that contains a variadic
1257 // array, accept it as a GNU extension: C99 6.7.2.1p2.
1258 if (EltTy->getDecl()->hasFlexibleArrayMember())
1259 Diag(Loc, diag::ext_flexible_array_in_array) << T;
1260 } else if (T->isObjCObjectType()) {
1261 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1265 // Do lvalue-to-rvalue conversions on the array size expression.
1266 if (ArraySize && !ArraySize->isRValue()) {
1267 ExprResult Result = DefaultLvalueConversion(ArraySize);
1268 if (Result.isInvalid())
1271 ArraySize = Result.take();
1274 // C99 6.7.5.2p1: The size expression shall have integer type.
1275 // TODO: in theory, if we were insane, we could allow contextual
1276 // conversions to integer type here.
1277 if (ArraySize && !ArraySize->isTypeDependent() &&
1278 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1279 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1280 << ArraySize->getType() << ArraySize->getSourceRange();
1283 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
1285 if (ASM == ArrayType::Star)
1286 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
1288 T = Context.getIncompleteArrayType(T, ASM, Quals);
1289 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
1290 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
1291 } else if (!T->isDependentType() && !T->isIncompleteType() &&
1292 !T->isConstantSizeType()) {
1293 // C99: an array with an element type that has a non-constant-size is a VLA.
1294 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1295 } else if (isArraySizeVLA(ArraySize, ConstVal, *this)) {
1296 // C99: an array with a non-ICE size is a VLA. We accept any expression
1297 // that we can fold to a non-zero positive value as an extension.
1298 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1300 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1301 // have a value greater than zero.
1302 if (ConstVal.isSigned() && ConstVal.isNegative()) {
1304 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1305 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1307 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1308 << ArraySize->getSourceRange();
1311 if (ConstVal == 0) {
1312 // GCC accepts zero sized static arrays. We allow them when
1313 // we're not in a SFINAE context.
1314 Diag(ArraySize->getLocStart(),
1315 isSFINAEContext()? diag::err_typecheck_zero_array_size
1316 : diag::ext_typecheck_zero_array_size)
1317 << ArraySize->getSourceRange();
1318 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1319 !T->isIncompleteType()) {
1320 // Is the array too large?
1321 unsigned ActiveSizeBits
1322 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1323 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1324 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1325 << ConstVal.toString(10)
1326 << ArraySize->getSourceRange();
1329 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
1331 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1332 if (!getLangOptions().C99) {
1333 if (T->isVariableArrayType()) {
1334 // Prohibit the use of non-POD types in VLAs.
1335 QualType BaseT = Context.getBaseElementType(T);
1336 if (!T->isDependentType() &&
1337 !BaseT.isPODType(Context) &&
1338 !BaseT->isObjCLifetimeType()) {
1339 Diag(Loc, diag::err_vla_non_pod)
1343 // Prohibit the use of VLAs during template argument deduction.
1344 else if (isSFINAEContext()) {
1345 Diag(Loc, diag::err_vla_in_sfinae);
1348 // Just extwarn about VLAs.
1350 Diag(Loc, diag::ext_vla);
1351 } else if (ASM != ArrayType::Normal || Quals != 0)
1353 getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
1354 : diag::ext_c99_array_usage);
1360 /// \brief Build an ext-vector type.
1362 /// Run the required checks for the extended vector type.
1363 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
1364 SourceLocation AttrLoc) {
1365 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1366 // in conjunction with complex types (pointers, arrays, functions, etc.).
1367 if (!T->isDependentType() &&
1368 !T->isIntegerType() && !T->isRealFloatingType()) {
1369 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1373 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
1374 llvm::APSInt vecSize(32);
1375 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
1376 Diag(AttrLoc, diag::err_attribute_argument_not_int)
1377 << "ext_vector_type" << ArraySize->getSourceRange();
1381 // unlike gcc's vector_size attribute, the size is specified as the
1382 // number of elements, not the number of bytes.
1383 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1385 if (vectorSize == 0) {
1386 Diag(AttrLoc, diag::err_attribute_zero_size)
1387 << ArraySize->getSourceRange();
1391 return Context.getExtVectorType(T, vectorSize);
1394 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
1397 /// \brief Build a function type.
1399 /// This routine checks the function type according to C++ rules and
1400 /// under the assumption that the result type and parameter types have
1401 /// just been instantiated from a template. It therefore duplicates
1402 /// some of the behavior of GetTypeForDeclarator, but in a much
1403 /// simpler form that is only suitable for this narrow use case.
1405 /// \param T The return type of the function.
1407 /// \param ParamTypes The parameter types of the function. This array
1408 /// will be modified to account for adjustments to the types of the
1409 /// function parameters.
1411 /// \param NumParamTypes The number of parameter types in ParamTypes.
1413 /// \param Variadic Whether this is a variadic function type.
1415 /// \param Quals The cvr-qualifiers to be applied to the function type.
1417 /// \param Loc The location of the entity whose type involves this
1418 /// function type or, if there is no such entity, the location of the
1419 /// type that will have function type.
1421 /// \param Entity The name of the entity that involves the function
1424 /// \returns A suitable function type, if there are no
1425 /// errors. Otherwise, returns a NULL type.
1426 QualType Sema::BuildFunctionType(QualType T,
1427 QualType *ParamTypes,
1428 unsigned NumParamTypes,
1429 bool Variadic, unsigned Quals,
1430 RefQualifierKind RefQualifier,
1431 SourceLocation Loc, DeclarationName Entity,
1432 FunctionType::ExtInfo Info) {
1433 if (T->isArrayType() || T->isFunctionType()) {
1434 Diag(Loc, diag::err_func_returning_array_function)
1435 << T->isFunctionType() << T;
1439 // Functions cannot return half FP.
1440 if (T->isHalfType()) {
1441 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
1442 FixItHint::CreateInsertion(Loc, "*");
1446 bool Invalid = false;
1447 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
1448 // FIXME: Loc is too inprecise here, should use proper locations for args.
1449 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
1450 if (ParamType->isVoidType()) {
1451 Diag(Loc, diag::err_param_with_void_type);
1453 } else if (ParamType->isHalfType()) {
1454 // Disallow half FP arguments.
1455 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
1456 FixItHint::CreateInsertion(Loc, "*");
1460 ParamTypes[Idx] = ParamType;
1466 FunctionProtoType::ExtProtoInfo EPI;
1467 EPI.Variadic = Variadic;
1468 EPI.TypeQuals = Quals;
1469 EPI.RefQualifier = RefQualifier;
1472 return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI);
1475 /// \brief Build a member pointer type \c T Class::*.
1477 /// \param T the type to which the member pointer refers.
1478 /// \param Class the class type into which the member pointer points.
1479 /// \param CVR Qualifiers applied to the member pointer type
1480 /// \param Loc the location where this type begins
1481 /// \param Entity the name of the entity that will have this member pointer type
1483 /// \returns a member pointer type, if successful, or a NULL type if there was
1485 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
1487 DeclarationName Entity) {
1488 // Verify that we're not building a pointer to pointer to function with
1489 // exception specification.
1490 if (CheckDistantExceptionSpec(T)) {
1491 Diag(Loc, diag::err_distant_exception_spec);
1493 // FIXME: If we're doing this as part of template instantiation,
1494 // we should return immediately.
1496 // Build the type anyway, but use the canonical type so that the
1497 // exception specifiers are stripped off.
1498 T = Context.getCanonicalType(T);
1501 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
1502 // with reference type, or "cv void."
1503 if (T->isReferenceType()) {
1504 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
1505 << (Entity? Entity.getAsString() : "type name") << T;
1509 if (T->isVoidType()) {
1510 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1511 << (Entity? Entity.getAsString() : "type name");
1515 if (!Class->isDependentType() && !Class->isRecordType()) {
1516 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1520 // In the Microsoft ABI, the class is allowed to be an incomplete
1521 // type. In such cases, the compiler makes a worst-case assumption.
1522 // We make no such assumption right now, so emit an error if the
1523 // class isn't a complete type.
1524 if (Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft &&
1525 RequireCompleteType(Loc, Class, diag::err_incomplete_type))
1528 return Context.getMemberPointerType(T, Class.getTypePtr());
1531 /// \brief Build a block pointer type.
1533 /// \param T The type to which we'll be building a block pointer.
1535 /// \param CVR The cvr-qualifiers to be applied to the block pointer type.
1537 /// \param Loc The location of the entity whose type involves this
1538 /// block pointer type or, if there is no such entity, the location of the
1539 /// type that will have block pointer type.
1541 /// \param Entity The name of the entity that involves the block pointer
1544 /// \returns A suitable block pointer type, if there are no
1545 /// errors. Otherwise, returns a NULL type.
1546 QualType Sema::BuildBlockPointerType(QualType T,
1548 DeclarationName Entity) {
1549 if (!T->isFunctionType()) {
1550 Diag(Loc, diag::err_nonfunction_block_type);
1554 return Context.getBlockPointerType(T);
1557 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1558 QualType QT = Ty.get();
1560 if (TInfo) *TInfo = 0;
1564 TypeSourceInfo *DI = 0;
1565 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
1566 QT = LIT->getType();
1567 DI = LIT->getTypeSourceInfo();
1570 if (TInfo) *TInfo = DI;
1574 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1575 Qualifiers::ObjCLifetime ownership,
1576 unsigned chunkIndex);
1578 /// Given that this is the declaration of a parameter under ARC,
1579 /// attempt to infer attributes and such for pointer-to-whatever
1581 static void inferARCWriteback(TypeProcessingState &state,
1582 QualType &declSpecType) {
1583 Sema &S = state.getSema();
1584 Declarator &declarator = state.getDeclarator();
1586 // TODO: should we care about decl qualifiers?
1588 // Check whether the declarator has the expected form. We walk
1589 // from the inside out in order to make the block logic work.
1590 unsigned outermostPointerIndex = 0;
1591 bool isBlockPointer = false;
1592 unsigned numPointers = 0;
1593 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1594 unsigned chunkIndex = i;
1595 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1596 switch (chunk.Kind) {
1597 case DeclaratorChunk::Paren:
1601 case DeclaratorChunk::Reference:
1602 case DeclaratorChunk::Pointer:
1603 // Count the number of pointers. Treat references
1604 // interchangeably as pointers; if they're mis-ordered, normal
1605 // type building will discover that.
1606 outermostPointerIndex = chunkIndex;
1610 case DeclaratorChunk::BlockPointer:
1611 // If we have a pointer to block pointer, that's an acceptable
1612 // indirect reference; anything else is not an application of
1614 if (numPointers != 1) return;
1616 outermostPointerIndex = chunkIndex;
1617 isBlockPointer = true;
1619 // We don't care about pointer structure in return values here.
1622 case DeclaratorChunk::Array: // suppress if written (id[])?
1623 case DeclaratorChunk::Function:
1624 case DeclaratorChunk::MemberPointer:
1630 // If we have *one* pointer, then we want to throw the qualifier on
1631 // the declaration-specifiers, which means that it needs to be a
1632 // retainable object type.
1633 if (numPointers == 1) {
1634 // If it's not a retainable object type, the rule doesn't apply.
1635 if (!declSpecType->isObjCRetainableType()) return;
1637 // If it already has lifetime, don't do anything.
1638 if (declSpecType.getObjCLifetime()) return;
1640 // Otherwise, modify the type in-place.
1643 if (declSpecType->isObjCARCImplicitlyUnretainedType())
1644 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
1646 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
1647 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
1649 // If we have *two* pointers, then we want to throw the qualifier on
1650 // the outermost pointer.
1651 } else if (numPointers == 2) {
1652 // If we don't have a block pointer, we need to check whether the
1653 // declaration-specifiers gave us something that will turn into a
1654 // retainable object pointer after we slap the first pointer on it.
1655 if (!isBlockPointer && !declSpecType->isObjCObjectType())
1658 // Look for an explicit lifetime attribute there.
1659 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
1660 if (chunk.Kind != DeclaratorChunk::Pointer &&
1661 chunk.Kind != DeclaratorChunk::BlockPointer)
1663 for (const AttributeList *attr = chunk.getAttrs(); attr;
1664 attr = attr->getNext())
1665 if (attr->getKind() == AttributeList::AT_objc_ownership)
1668 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
1669 outermostPointerIndex);
1671 // Any other number of pointers/references does not trigger the rule.
1674 // TODO: mark whether we did this inference?
1677 static void DiagnoseIgnoredQualifiers(unsigned Quals,
1678 SourceLocation ConstQualLoc,
1679 SourceLocation VolatileQualLoc,
1680 SourceLocation RestrictQualLoc,
1682 std::string QualStr;
1683 unsigned NumQuals = 0;
1686 FixItHint ConstFixIt;
1687 FixItHint VolatileFixIt;
1688 FixItHint RestrictFixIt;
1690 const SourceManager &SM = S.getSourceManager();
1692 // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to
1693 // find a range and grow it to encompass all the qualifiers, regardless of
1694 // the order in which they textually appear.
1695 if (Quals & Qualifiers::Const) {
1696 ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc);
1699 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc))
1702 if (Quals & Qualifiers::Volatile) {
1703 VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc);
1704 QualStr += (NumQuals == 0 ? "volatile" : " volatile");
1706 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc))
1707 Loc = VolatileQualLoc;
1709 if (Quals & Qualifiers::Restrict) {
1710 RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc);
1711 QualStr += (NumQuals == 0 ? "restrict" : " restrict");
1713 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc))
1714 Loc = RestrictQualLoc;
1717 assert(NumQuals > 0 && "No known qualifiers?");
1719 S.Diag(Loc, diag::warn_qual_return_type)
1720 << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt;
1723 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
1724 TypeSourceInfo *&ReturnTypeInfo) {
1725 Sema &SemaRef = state.getSema();
1726 Declarator &D = state.getDeclarator();
1730 // The TagDecl owned by the DeclSpec.
1731 TagDecl *OwnedTagDecl = 0;
1733 switch (D.getName().getKind()) {
1734 case UnqualifiedId::IK_ImplicitSelfParam:
1735 case UnqualifiedId::IK_OperatorFunctionId:
1736 case UnqualifiedId::IK_Identifier:
1737 case UnqualifiedId::IK_LiteralOperatorId:
1738 case UnqualifiedId::IK_TemplateId:
1739 T = ConvertDeclSpecToType(state);
1741 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
1742 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
1743 // Owned declaration is embedded in declarator.
1744 OwnedTagDecl->setEmbeddedInDeclarator(true);
1748 case UnqualifiedId::IK_ConstructorName:
1749 case UnqualifiedId::IK_ConstructorTemplateId:
1750 case UnqualifiedId::IK_DestructorName:
1751 // Constructors and destructors don't have return types. Use
1753 T = SemaRef.Context.VoidTy;
1756 case UnqualifiedId::IK_ConversionFunctionId:
1757 // The result type of a conversion function is the type that it
1759 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
1764 if (D.getAttributes())
1765 distributeTypeAttrsFromDeclarator(state, T);
1767 // C++0x [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
1768 // In C++0x, a function declarator using 'auto' must have a trailing return
1769 // type (this is checked later) and we can skip this. In other languages
1770 // using auto, we need to check regardless.
1771 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
1772 (!SemaRef.getLangOptions().CPlusPlus0x || !D.isFunctionDeclarator())) {
1775 switch (D.getContext()) {
1776 case Declarator::KNRTypeListContext:
1777 llvm_unreachable("K&R type lists aren't allowed in C++");
1779 case Declarator::ObjCParameterContext:
1780 case Declarator::ObjCResultContext:
1781 case Declarator::PrototypeContext:
1782 Error = 0; // Function prototype
1784 case Declarator::MemberContext:
1785 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
1787 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
1788 case TTK_Enum: llvm_unreachable("unhandled tag kind");
1789 case TTK_Struct: Error = 1; /* Struct member */ break;
1790 case TTK_Union: Error = 2; /* Union member */ break;
1791 case TTK_Class: Error = 3; /* Class member */ break;
1794 case Declarator::CXXCatchContext:
1795 case Declarator::ObjCCatchContext:
1796 Error = 4; // Exception declaration
1798 case Declarator::TemplateParamContext:
1799 Error = 5; // Template parameter
1801 case Declarator::BlockLiteralContext:
1802 Error = 6; // Block literal
1804 case Declarator::TemplateTypeArgContext:
1805 Error = 7; // Template type argument
1807 case Declarator::AliasDeclContext:
1808 case Declarator::AliasTemplateContext:
1809 Error = 9; // Type alias
1811 case Declarator::TypeNameContext:
1812 Error = 11; // Generic
1814 case Declarator::FileContext:
1815 case Declarator::BlockContext:
1816 case Declarator::ForContext:
1817 case Declarator::ConditionContext:
1818 case Declarator::CXXNewContext:
1822 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1825 // In Objective-C it is an error to use 'auto' on a function declarator.
1826 if (D.isFunctionDeclarator())
1829 // C++0x [dcl.spec.auto]p2: 'auto' is always fine if the declarator
1830 // contains a trailing return type. That is only legal at the outermost
1831 // level. Check all declarator chunks (outermost first) anyway, to give
1832 // better diagnostics.
1833 if (SemaRef.getLangOptions().CPlusPlus0x && Error != -1) {
1834 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1835 unsigned chunkIndex = e - i - 1;
1836 state.setCurrentChunkIndex(chunkIndex);
1837 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1838 if (DeclType.Kind == DeclaratorChunk::Function) {
1839 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1840 if (FTI.TrailingReturnType) {
1849 SemaRef.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1850 diag::err_auto_not_allowed)
1852 T = SemaRef.Context.IntTy;
1853 D.setInvalidType(true);
1857 if (SemaRef.getLangOptions().CPlusPlus &&
1858 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
1859 // Check the contexts where C++ forbids the declaration of a new class
1860 // or enumeration in a type-specifier-seq.
1861 switch (D.getContext()) {
1862 case Declarator::FileContext:
1863 case Declarator::MemberContext:
1864 case Declarator::BlockContext:
1865 case Declarator::ForContext:
1866 case Declarator::BlockLiteralContext:
1867 // C++0x [dcl.type]p3:
1868 // A type-specifier-seq shall not define a class or enumeration unless
1869 // it appears in the type-id of an alias-declaration (7.1.3) that is not
1870 // the declaration of a template-declaration.
1871 case Declarator::AliasDeclContext:
1873 case Declarator::AliasTemplateContext:
1874 SemaRef.Diag(OwnedTagDecl->getLocation(),
1875 diag::err_type_defined_in_alias_template)
1876 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1878 case Declarator::TypeNameContext:
1879 case Declarator::TemplateParamContext:
1880 case Declarator::CXXNewContext:
1881 case Declarator::CXXCatchContext:
1882 case Declarator::ObjCCatchContext:
1883 case Declarator::TemplateTypeArgContext:
1884 SemaRef.Diag(OwnedTagDecl->getLocation(),
1885 diag::err_type_defined_in_type_specifier)
1886 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1888 case Declarator::PrototypeContext:
1889 case Declarator::ObjCParameterContext:
1890 case Declarator::ObjCResultContext:
1891 case Declarator::KNRTypeListContext:
1893 // Types shall not be defined in return or parameter types.
1894 SemaRef.Diag(OwnedTagDecl->getLocation(),
1895 diag::err_type_defined_in_param_type)
1896 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
1898 case Declarator::ConditionContext:
1900 // The type-specifier-seq shall not contain typedef and shall not declare
1901 // a new class or enumeration.
1902 SemaRef.Diag(OwnedTagDecl->getLocation(),
1903 diag::err_type_defined_in_condition);
1911 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
1912 QualType declSpecType,
1913 TypeSourceInfo *TInfo) {
1915 QualType T = declSpecType;
1916 Declarator &D = state.getDeclarator();
1917 Sema &S = state.getSema();
1918 ASTContext &Context = S.Context;
1919 const LangOptions &LangOpts = S.getLangOptions();
1921 bool ImplicitlyNoexcept = false;
1922 if (D.getName().getKind() == UnqualifiedId::IK_OperatorFunctionId &&
1923 LangOpts.CPlusPlus0x) {
1924 OverloadedOperatorKind OO = D.getName().OperatorFunctionId.Operator;
1925 /// In C++0x, deallocation functions (normal and array operator delete)
1926 /// are implicitly noexcept.
1927 if (OO == OO_Delete || OO == OO_Array_Delete)
1928 ImplicitlyNoexcept = true;
1931 // The name we're declaring, if any.
1932 DeclarationName Name;
1933 if (D.getIdentifier())
1934 Name = D.getIdentifier();
1936 // Does this declaration declare a typedef-name?
1937 bool IsTypedefName =
1938 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
1939 D.getContext() == Declarator::AliasDeclContext ||
1940 D.getContext() == Declarator::AliasTemplateContext;
1942 // Walk the DeclTypeInfo, building the recursive type as we go.
1943 // DeclTypeInfos are ordered from the identifier out, which is
1944 // opposite of what we want :).
1945 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1946 unsigned chunkIndex = e - i - 1;
1947 state.setCurrentChunkIndex(chunkIndex);
1948 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1949 switch (DeclType.Kind) {
1950 default: llvm_unreachable("Unknown decltype!");
1951 case DeclaratorChunk::Paren:
1952 T = S.BuildParenType(T);
1954 case DeclaratorChunk::BlockPointer:
1955 // If blocks are disabled, emit an error.
1956 if (!LangOpts.Blocks)
1957 S.Diag(DeclType.Loc, diag::err_blocks_disable);
1959 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
1960 if (DeclType.Cls.TypeQuals)
1961 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
1963 case DeclaratorChunk::Pointer:
1964 // Verify that we're not building a pointer to pointer to function with
1965 // exception specification.
1966 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
1967 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1968 D.setInvalidType(true);
1969 // Build the type anyway.
1971 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
1972 T = Context.getObjCObjectPointerType(T);
1973 if (DeclType.Ptr.TypeQuals)
1974 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
1977 T = S.BuildPointerType(T, DeclType.Loc, Name);
1978 if (DeclType.Ptr.TypeQuals)
1979 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
1982 case DeclaratorChunk::Reference: {
1983 // Verify that we're not building a reference to pointer to function with
1984 // exception specification.
1985 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
1986 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1987 D.setInvalidType(true);
1988 // Build the type anyway.
1990 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
1993 if (DeclType.Ref.HasRestrict)
1994 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
1997 case DeclaratorChunk::Array: {
1998 // Verify that we're not building an array of pointers to function with
1999 // exception specification.
2000 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2001 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2002 D.setInvalidType(true);
2003 // Build the type anyway.
2005 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
2006 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
2007 ArrayType::ArraySizeModifier ASM;
2009 ASM = ArrayType::Star;
2010 else if (ATI.hasStatic)
2011 ASM = ArrayType::Static;
2013 ASM = ArrayType::Normal;
2014 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
2015 // FIXME: This check isn't quite right: it allows star in prototypes
2016 // for function definitions, and disallows some edge cases detailed
2017 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
2018 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
2019 ASM = ArrayType::Normal;
2020 D.setInvalidType(true);
2022 T = S.BuildArrayType(T, ASM, ArraySize,
2023 Qualifiers::fromCVRMask(ATI.TypeQuals),
2024 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
2027 case DeclaratorChunk::Function: {
2028 // If the function declarator has a prototype (i.e. it is not () and
2029 // does not have a K&R-style identifier list), then the arguments are part
2030 // of the type, otherwise the argument list is ().
2031 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2033 // Check for auto functions and trailing return type and adjust the
2034 // return type accordingly.
2035 if (!D.isInvalidType()) {
2036 // trailing-return-type is only required if we're declaring a function,
2037 // and not, for instance, a pointer to a function.
2038 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
2039 !FTI.TrailingReturnType && chunkIndex == 0) {
2040 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2041 diag::err_auto_missing_trailing_return);
2043 D.setInvalidType(true);
2044 } else if (FTI.TrailingReturnType) {
2045 // T must be exactly 'auto' at this point. See CWG issue 681.
2046 if (isa<ParenType>(T)) {
2047 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2048 diag::err_trailing_return_in_parens)
2049 << T << D.getDeclSpec().getSourceRange();
2050 D.setInvalidType(true);
2051 } else if (T.hasQualifiers() || !isa<AutoType>(T)) {
2052 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2053 diag::err_trailing_return_without_auto)
2054 << T << D.getDeclSpec().getSourceRange();
2055 D.setInvalidType(true);
2058 T = S.GetTypeFromParser(
2059 ParsedType::getFromOpaquePtr(FTI.TrailingReturnType),
2064 // C99 6.7.5.3p1: The return type may not be a function or array type.
2065 // For conversion functions, we'll diagnose this particular error later.
2066 if ((T->isArrayType() || T->isFunctionType()) &&
2067 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
2068 unsigned diagID = diag::err_func_returning_array_function;
2069 // Last processing chunk in block context means this function chunk
2070 // represents the block.
2071 if (chunkIndex == 0 &&
2072 D.getContext() == Declarator::BlockLiteralContext)
2073 diagID = diag::err_block_returning_array_function;
2074 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
2076 D.setInvalidType(true);
2079 // Do not allow returning half FP value.
2080 // FIXME: This really should be in BuildFunctionType.
2081 if (T->isHalfType()) {
2082 S.Diag(D.getIdentifierLoc(),
2083 diag::err_parameters_retval_cannot_have_fp16_type) << 1
2084 << FixItHint::CreateInsertion(D.getIdentifierLoc(), "*");
2085 D.setInvalidType(true);
2088 // cv-qualifiers on return types are pointless except when the type is a
2089 // class type in C++.
2090 if (isa<PointerType>(T) && T.getLocalCVRQualifiers() &&
2091 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) &&
2092 (!LangOpts.CPlusPlus || !T->isDependentType())) {
2093 assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?");
2094 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2095 assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer);
2097 DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr;
2099 DiagnoseIgnoredQualifiers(PTI.TypeQuals,
2100 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2101 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2102 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2105 } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
2106 (!LangOpts.CPlusPlus ||
2107 (!T->isDependentType() && !T->isRecordType()))) {
2109 DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(),
2110 D.getDeclSpec().getConstSpecLoc(),
2111 D.getDeclSpec().getVolatileSpecLoc(),
2112 D.getDeclSpec().getRestrictSpecLoc(),
2116 if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
2118 // Types shall not be defined in return or parameter types.
2119 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2120 if (Tag->isCompleteDefinition())
2121 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
2122 << Context.getTypeDeclType(Tag);
2125 // Exception specs are not allowed in typedefs. Complain, but add it
2127 if (IsTypedefName && FTI.getExceptionSpecType())
2128 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
2129 << (D.getContext() == Declarator::AliasDeclContext ||
2130 D.getContext() == Declarator::AliasTemplateContext);
2132 if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) {
2133 // Simple void foo(), where the incoming T is the result type.
2134 T = Context.getFunctionNoProtoType(T);
2136 // We allow a zero-parameter variadic function in C if the
2137 // function is marked with the "overloadable" attribute. Scan
2138 // for this attribute now.
2139 if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) {
2140 bool Overloadable = false;
2141 for (const AttributeList *Attrs = D.getAttributes();
2142 Attrs; Attrs = Attrs->getNext()) {
2143 if (Attrs->getKind() == AttributeList::AT_overloadable) {
2144 Overloadable = true;
2150 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
2153 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
2154 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
2156 S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
2157 D.setInvalidType(true);
2161 FunctionProtoType::ExtProtoInfo EPI;
2162 EPI.Variadic = FTI.isVariadic;
2163 EPI.TypeQuals = FTI.TypeQuals;
2164 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
2165 : FTI.RefQualifierIsLValueRef? RQ_LValue
2168 // Otherwise, we have a function with an argument list that is
2169 // potentially variadic.
2170 SmallVector<QualType, 16> ArgTys;
2171 ArgTys.reserve(FTI.NumArgs);
2173 SmallVector<bool, 16> ConsumedArguments;
2174 ConsumedArguments.reserve(FTI.NumArgs);
2175 bool HasAnyConsumedArguments = false;
2177 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2178 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
2179 QualType ArgTy = Param->getType();
2180 assert(!ArgTy.isNull() && "Couldn't parse type?");
2182 // Adjust the parameter type.
2183 assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) &&
2184 "Unadjusted type?");
2186 // Look for 'void'. void is allowed only as a single argument to a
2187 // function with no other parameters (C99 6.7.5.3p10). We record
2188 // int(void) as a FunctionProtoType with an empty argument list.
2189 if (ArgTy->isVoidType()) {
2190 // If this is something like 'float(int, void)', reject it. 'void'
2191 // is an incomplete type (C99 6.2.5p19) and function decls cannot
2192 // have arguments of incomplete type.
2193 if (FTI.NumArgs != 1 || FTI.isVariadic) {
2194 S.Diag(DeclType.Loc, diag::err_void_only_param);
2195 ArgTy = Context.IntTy;
2196 Param->setType(ArgTy);
2197 } else if (FTI.ArgInfo[i].Ident) {
2198 // Reject, but continue to parse 'int(void abc)'.
2199 S.Diag(FTI.ArgInfo[i].IdentLoc,
2200 diag::err_param_with_void_type);
2201 ArgTy = Context.IntTy;
2202 Param->setType(ArgTy);
2204 // Reject, but continue to parse 'float(const void)'.
2205 if (ArgTy.hasQualifiers())
2206 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
2208 // Do not add 'void' to the ArgTys list.
2211 } else if (ArgTy->isHalfType()) {
2212 // Disallow half FP arguments.
2213 // FIXME: This really should be in BuildFunctionType.
2214 S.Diag(Param->getLocation(),
2215 diag::err_parameters_retval_cannot_have_fp16_type) << 0
2216 << FixItHint::CreateInsertion(Param->getLocation(), "*");
2218 } else if (!FTI.hasPrototype) {
2219 if (ArgTy->isPromotableIntegerType()) {
2220 ArgTy = Context.getPromotedIntegerType(ArgTy);
2221 Param->setKNRPromoted(true);
2222 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
2223 if (BTy->getKind() == BuiltinType::Float) {
2224 ArgTy = Context.DoubleTy;
2225 Param->setKNRPromoted(true);
2230 if (LangOpts.ObjCAutoRefCount) {
2231 bool Consumed = Param->hasAttr<NSConsumedAttr>();
2232 ConsumedArguments.push_back(Consumed);
2233 HasAnyConsumedArguments |= Consumed;
2236 ArgTys.push_back(ArgTy);
2239 if (HasAnyConsumedArguments)
2240 EPI.ConsumedArguments = ConsumedArguments.data();
2242 SmallVector<QualType, 4> Exceptions;
2243 EPI.ExceptionSpecType = FTI.getExceptionSpecType();
2244 if (FTI.getExceptionSpecType() == EST_Dynamic) {
2245 Exceptions.reserve(FTI.NumExceptions);
2246 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
2247 // FIXME: Preserve type source info.
2248 QualType ET = S.GetTypeFromParser(FTI.Exceptions[ei].Ty);
2249 // Check that the type is valid for an exception spec, and
2251 if (!S.CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
2252 Exceptions.push_back(ET);
2254 EPI.NumExceptions = Exceptions.size();
2255 EPI.Exceptions = Exceptions.data();
2256 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
2257 // If an error occurred, there's no expression here.
2258 if (Expr *NoexceptExpr = FTI.NoexceptExpr) {
2259 assert((NoexceptExpr->isTypeDependent() ||
2260 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
2262 "Parser should have made sure that the expression is boolean");
2263 SourceLocation ErrLoc;
2265 if (!NoexceptExpr->isValueDependent() &&
2266 !NoexceptExpr->isIntegerConstantExpr(Dummy, Context, &ErrLoc,
2267 /*evaluated*/false))
2268 S.Diag(ErrLoc, diag::err_noexcept_needs_constant_expression)
2269 << NoexceptExpr->getSourceRange();
2271 EPI.NoexceptExpr = NoexceptExpr;
2273 } else if (FTI.getExceptionSpecType() == EST_None &&
2274 ImplicitlyNoexcept && chunkIndex == 0) {
2275 // Only the outermost chunk is marked noexcept, of course.
2276 EPI.ExceptionSpecType = EST_BasicNoexcept;
2279 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI);
2284 case DeclaratorChunk::MemberPointer:
2285 // The scope spec must refer to a class, or be dependent.
2286 CXXScopeSpec &SS = DeclType.Mem.Scope();
2288 if (SS.isInvalid()) {
2289 // Avoid emitting extra errors if we already errored on the scope.
2290 D.setInvalidType(true);
2291 } else if (S.isDependentScopeSpecifier(SS) ||
2292 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
2293 NestedNameSpecifier *NNS
2294 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2295 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
2296 switch (NNS->getKind()) {
2297 case NestedNameSpecifier::Identifier:
2298 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
2299 NNS->getAsIdentifier());
2302 case NestedNameSpecifier::Namespace:
2303 case NestedNameSpecifier::NamespaceAlias:
2304 case NestedNameSpecifier::Global:
2305 llvm_unreachable("Nested-name-specifier must name a type");
2308 case NestedNameSpecifier::TypeSpec:
2309 case NestedNameSpecifier::TypeSpecWithTemplate:
2310 ClsType = QualType(NNS->getAsType(), 0);
2311 // Note: if the NNS has a prefix and ClsType is a nondependent
2312 // TemplateSpecializationType, then the NNS prefix is NOT included
2313 // in ClsType; hence we wrap ClsType into an ElaboratedType.
2314 // NOTE: in particular, no wrap occurs if ClsType already is an
2315 // Elaborated, DependentName, or DependentTemplateSpecialization.
2316 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
2317 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
2321 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
2322 diag::err_illegal_decl_mempointer_in_nonclass)
2323 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
2324 << DeclType.Mem.Scope().getRange();
2325 D.setInvalidType(true);
2328 if (!ClsType.isNull())
2329 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
2332 D.setInvalidType(true);
2333 } else if (DeclType.Mem.TypeQuals) {
2334 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
2340 D.setInvalidType(true);
2344 // See if there are any attributes on this declarator chunk.
2345 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
2346 processTypeAttrs(state, T, false, attrs);
2349 if (LangOpts.CPlusPlus && T->isFunctionType()) {
2350 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
2351 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
2354 // A cv-qualifier-seq shall only be part of the function type
2355 // for a nonstatic member function, the function type to which a pointer
2356 // to member refers, or the top-level function type of a function typedef
2359 // Core issue 547 also allows cv-qualifiers on function types that are
2360 // top-level template type arguments.
2362 if (!D.getCXXScopeSpec().isSet()) {
2363 FreeFunction = (D.getContext() != Declarator::MemberContext ||
2364 D.getDeclSpec().isFriendSpecified());
2366 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
2367 FreeFunction = (DC && !DC->isRecord());
2370 // C++0x [dcl.constexpr]p8: A constexpr specifier for a non-static member
2371 // function that is not a constructor declares that function to be const.
2372 if (D.getDeclSpec().isConstexprSpecified() && !FreeFunction &&
2373 D.getName().getKind() != UnqualifiedId::IK_ConstructorName &&
2374 D.getName().getKind() != UnqualifiedId::IK_ConstructorTemplateId &&
2375 !(FnTy->getTypeQuals() & DeclSpec::TQ_const)) {
2376 // Rebuild function type adding a 'const' qualifier.
2377 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2378 EPI.TypeQuals |= DeclSpec::TQ_const;
2379 T = Context.getFunctionType(FnTy->getResultType(),
2380 FnTy->arg_type_begin(),
2381 FnTy->getNumArgs(), EPI);
2384 // C++0x [dcl.fct]p6:
2385 // A ref-qualifier shall only be part of the function type for a
2386 // non-static member function, the function type to which a pointer to
2387 // member refers, or the top-level function type of a function typedef
2389 if ((FnTy->getTypeQuals() != 0 || FnTy->getRefQualifier()) &&
2390 !(D.getContext() == Declarator::TemplateTypeArgContext &&
2391 !D.isFunctionDeclarator()) && !IsTypedefName &&
2393 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
2394 if (D.getContext() == Declarator::TemplateTypeArgContext) {
2395 // Accept qualified function types as template type arguments as a GNU
2396 // extension. This is also the subject of C++ core issue 547.
2398 if (FnTy->getTypeQuals() != 0)
2399 Quals = Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
2401 switch (FnTy->getRefQualifier()) {
2418 S.Diag(D.getIdentifierLoc(),
2419 diag::ext_qualified_function_type_template_arg)
2422 if (FnTy->getTypeQuals() != 0) {
2423 if (D.isFunctionDeclarator())
2424 S.Diag(D.getIdentifierLoc(),
2425 diag::err_invalid_qualified_function_type);
2427 S.Diag(D.getIdentifierLoc(),
2428 diag::err_invalid_qualified_typedef_function_type_use)
2432 if (FnTy->getRefQualifier()) {
2433 if (D.isFunctionDeclarator()) {
2434 SourceLocation Loc = D.getIdentifierLoc();
2435 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
2436 const DeclaratorChunk &Chunk = D.getTypeObject(N-I-1);
2437 if (Chunk.Kind == DeclaratorChunk::Function &&
2438 Chunk.Fun.hasRefQualifier()) {
2439 Loc = Chunk.Fun.getRefQualifierLoc();
2444 S.Diag(Loc, diag::err_invalid_ref_qualifier_function_type)
2445 << (FnTy->getRefQualifier() == RQ_LValue)
2446 << FixItHint::CreateRemoval(Loc);
2448 S.Diag(D.getIdentifierLoc(),
2449 diag::err_invalid_ref_qualifier_typedef_function_type_use)
2451 << (FnTy->getRefQualifier() == RQ_LValue);
2455 // Strip the cv-qualifiers and ref-qualifiers from the type.
2456 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2458 EPI.RefQualifier = RQ_None;
2460 T = Context.getFunctionType(FnTy->getResultType(),
2461 FnTy->arg_type_begin(),
2462 FnTy->getNumArgs(), EPI);
2467 // Apply any undistributed attributes from the declarator.
2469 if (AttributeList *attrs = D.getAttributes())
2470 processTypeAttrs(state, T, false, attrs);
2472 // Diagnose any ignored type attributes.
2473 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
2475 // C++0x [dcl.constexpr]p9:
2476 // A constexpr specifier used in an object declaration declares the object
2478 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
2482 // If there was an ellipsis in the declarator, the declaration declares a
2483 // parameter pack whose type may be a pack expansion type.
2484 if (D.hasEllipsis() && !T.isNull()) {
2485 // C++0x [dcl.fct]p13:
2486 // A declarator-id or abstract-declarator containing an ellipsis shall
2487 // only be used in a parameter-declaration. Such a parameter-declaration
2488 // is a parameter pack (14.5.3). [...]
2489 switch (D.getContext()) {
2490 case Declarator::PrototypeContext:
2491 // C++0x [dcl.fct]p13:
2492 // [...] When it is part of a parameter-declaration-clause, the
2493 // parameter pack is a function parameter pack (14.5.3). The type T
2494 // of the declarator-id of the function parameter pack shall contain
2495 // a template parameter pack; each template parameter pack in T is
2496 // expanded by the function parameter pack.
2498 // We represent function parameter packs as function parameters whose
2499 // type is a pack expansion.
2500 if (!T->containsUnexpandedParameterPack()) {
2501 S.Diag(D.getEllipsisLoc(),
2502 diag::err_function_parameter_pack_without_parameter_packs)
2503 << T << D.getSourceRange();
2504 D.setEllipsisLoc(SourceLocation());
2506 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
2510 case Declarator::TemplateParamContext:
2511 // C++0x [temp.param]p15:
2512 // If a template-parameter is a [...] is a parameter-declaration that
2513 // declares a parameter pack (8.3.5), then the template-parameter is a
2514 // template parameter pack (14.5.3).
2516 // Note: core issue 778 clarifies that, if there are any unexpanded
2517 // parameter packs in the type of the non-type template parameter, then
2518 // it expands those parameter packs.
2519 if (T->containsUnexpandedParameterPack())
2520 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
2522 S.Diag(D.getEllipsisLoc(),
2523 LangOpts.CPlusPlus0x
2524 ? diag::warn_cxx98_compat_variadic_templates
2525 : diag::ext_variadic_templates);
2528 case Declarator::FileContext:
2529 case Declarator::KNRTypeListContext:
2530 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
2531 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
2532 case Declarator::TypeNameContext:
2533 case Declarator::CXXNewContext:
2534 case Declarator::AliasDeclContext:
2535 case Declarator::AliasTemplateContext:
2536 case Declarator::MemberContext:
2537 case Declarator::BlockContext:
2538 case Declarator::ForContext:
2539 case Declarator::ConditionContext:
2540 case Declarator::CXXCatchContext:
2541 case Declarator::ObjCCatchContext:
2542 case Declarator::BlockLiteralContext:
2543 case Declarator::TemplateTypeArgContext:
2544 // FIXME: We may want to allow parameter packs in block-literal contexts
2546 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
2547 D.setEllipsisLoc(SourceLocation());
2553 return Context.getNullTypeSourceInfo();
2554 else if (D.isInvalidType())
2555 return Context.getTrivialTypeSourceInfo(T);
2557 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
2560 /// GetTypeForDeclarator - Convert the type for the specified
2561 /// declarator to Type instances.
2563 /// The result of this call will never be null, but the associated
2564 /// type may be a null type if there's an unrecoverable error.
2565 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
2566 // Determine the type of the declarator. Not all forms of declarator
2569 TypeProcessingState state(*this, D);
2571 TypeSourceInfo *ReturnTypeInfo = 0;
2572 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2574 return Context.getNullTypeSourceInfo();
2576 if (D.isPrototypeContext() && getLangOptions().ObjCAutoRefCount)
2577 inferARCWriteback(state, T);
2579 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
2582 static void transferARCOwnershipToDeclSpec(Sema &S,
2583 QualType &declSpecTy,
2584 Qualifiers::ObjCLifetime ownership) {
2585 if (declSpecTy->isObjCRetainableType() &&
2586 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
2588 qs.addObjCLifetime(ownership);
2589 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
2593 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2594 Qualifiers::ObjCLifetime ownership,
2595 unsigned chunkIndex) {
2596 Sema &S = state.getSema();
2597 Declarator &D = state.getDeclarator();
2599 // Look for an explicit lifetime attribute.
2600 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
2601 for (const AttributeList *attr = chunk.getAttrs(); attr;
2602 attr = attr->getNext())
2603 if (attr->getKind() == AttributeList::AT_objc_ownership)
2606 const char *attrStr = 0;
2607 switch (ownership) {
2608 case Qualifiers::OCL_None: llvm_unreachable("no ownership!"); break;
2609 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
2610 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
2611 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
2612 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
2615 // If there wasn't one, add one (with an invalid source location
2616 // so that we don't make an AttributedType for it).
2617 AttributeList *attr = D.getAttributePool()
2618 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
2619 /*scope*/ 0, SourceLocation(),
2620 &S.Context.Idents.get(attrStr), SourceLocation(),
2622 /*declspec*/ false, /*C++0x*/ false);
2623 spliceAttrIntoList(*attr, chunk.getAttrListRef());
2625 // TODO: mark whether we did this inference?
2628 static void transferARCOwnership(TypeProcessingState &state,
2629 QualType &declSpecTy,
2630 Qualifiers::ObjCLifetime ownership) {
2631 Sema &S = state.getSema();
2632 Declarator &D = state.getDeclarator();
2635 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2636 DeclaratorChunk &chunk = D.getTypeObject(i);
2637 switch (chunk.Kind) {
2638 case DeclaratorChunk::Paren:
2642 case DeclaratorChunk::Array:
2643 case DeclaratorChunk::Reference:
2644 case DeclaratorChunk::Pointer:
2648 case DeclaratorChunk::BlockPointer:
2649 return transferARCOwnershipToDeclaratorChunk(state, ownership, i);
2651 case DeclaratorChunk::Function:
2652 case DeclaratorChunk::MemberPointer:
2658 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2660 DeclaratorChunk &chunk = D.getTypeObject(inner);
2661 if (chunk.Kind == DeclaratorChunk::Pointer) {
2662 if (declSpecTy->isObjCRetainableType())
2663 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2664 if (declSpecTy->isObjCObjectType())
2665 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
2667 assert(chunk.Kind == DeclaratorChunk::Array ||
2668 chunk.Kind == DeclaratorChunk::Reference);
2669 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
2673 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
2674 TypeProcessingState state(*this, D);
2676 TypeSourceInfo *ReturnTypeInfo = 0;
2677 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
2678 if (declSpecTy.isNull())
2679 return Context.getNullTypeSourceInfo();
2681 if (getLangOptions().ObjCAutoRefCount) {
2682 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
2683 if (ownership != Qualifiers::OCL_None)
2684 transferARCOwnership(state, declSpecTy, ownership);
2687 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
2690 /// Map an AttributedType::Kind to an AttributeList::Kind.
2691 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
2693 case AttributedType::attr_address_space:
2694 return AttributeList::AT_address_space;
2695 case AttributedType::attr_regparm:
2696 return AttributeList::AT_regparm;
2697 case AttributedType::attr_vector_size:
2698 return AttributeList::AT_vector_size;
2699 case AttributedType::attr_neon_vector_type:
2700 return AttributeList::AT_neon_vector_type;
2701 case AttributedType::attr_neon_polyvector_type:
2702 return AttributeList::AT_neon_polyvector_type;
2703 case AttributedType::attr_objc_gc:
2704 return AttributeList::AT_objc_gc;
2705 case AttributedType::attr_objc_ownership:
2706 return AttributeList::AT_objc_ownership;
2707 case AttributedType::attr_noreturn:
2708 return AttributeList::AT_noreturn;
2709 case AttributedType::attr_cdecl:
2710 return AttributeList::AT_cdecl;
2711 case AttributedType::attr_fastcall:
2712 return AttributeList::AT_fastcall;
2713 case AttributedType::attr_stdcall:
2714 return AttributeList::AT_stdcall;
2715 case AttributedType::attr_thiscall:
2716 return AttributeList::AT_thiscall;
2717 case AttributedType::attr_pascal:
2718 return AttributeList::AT_pascal;
2719 case AttributedType::attr_pcs:
2720 return AttributeList::AT_pcs;
2722 llvm_unreachable("unexpected attribute kind!");
2723 return AttributeList::Kind();
2726 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
2727 const AttributeList *attrs) {
2728 AttributedType::Kind kind = TL.getAttrKind();
2730 assert(attrs && "no type attributes in the expected location!");
2731 AttributeList::Kind parsedKind = getAttrListKind(kind);
2732 while (attrs->getKind() != parsedKind) {
2733 attrs = attrs->getNext();
2734 assert(attrs && "no matching attribute in expected location!");
2737 TL.setAttrNameLoc(attrs->getLoc());
2738 if (TL.hasAttrExprOperand())
2739 TL.setAttrExprOperand(attrs->getArg(0));
2740 else if (TL.hasAttrEnumOperand())
2741 TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
2743 // FIXME: preserve this information to here.
2744 if (TL.hasAttrOperand())
2745 TL.setAttrOperandParensRange(SourceRange());
2749 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
2750 ASTContext &Context;
2754 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
2755 : Context(Context), DS(DS) {}
2757 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
2758 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
2759 Visit(TL.getModifiedLoc());
2761 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2762 Visit(TL.getUnqualifiedLoc());
2764 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2765 TL.setNameLoc(DS.getTypeSpecTypeLoc());
2767 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2768 TL.setNameLoc(DS.getTypeSpecTypeLoc());
2770 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2771 // Handle the base type, which might not have been written explicitly.
2772 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
2773 TL.setHasBaseTypeAsWritten(false);
2774 TL.getBaseLoc().initialize(Context, SourceLocation());
2776 TL.setHasBaseTypeAsWritten(true);
2777 Visit(TL.getBaseLoc());
2780 // Protocol qualifiers.
2781 if (DS.getProtocolQualifiers()) {
2782 assert(TL.getNumProtocols() > 0);
2783 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
2784 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
2785 TL.setRAngleLoc(DS.getSourceRange().getEnd());
2786 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
2787 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
2789 assert(TL.getNumProtocols() == 0);
2790 TL.setLAngleLoc(SourceLocation());
2791 TL.setRAngleLoc(SourceLocation());
2794 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2795 TL.setStarLoc(SourceLocation());
2796 Visit(TL.getPointeeLoc());
2798 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
2799 TypeSourceInfo *TInfo = 0;
2800 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2802 // If we got no declarator info from previous Sema routines,
2803 // just fill with the typespec loc.
2805 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
2809 TypeLoc OldTL = TInfo->getTypeLoc();
2810 if (TInfo->getType()->getAs<ElaboratedType>()) {
2811 ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
2812 TemplateSpecializationTypeLoc NamedTL =
2813 cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
2817 TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
2819 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2820 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
2821 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2822 TL.setParensRange(DS.getTypeofParensRange());
2824 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2825 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
2826 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2827 TL.setParensRange(DS.getTypeofParensRange());
2828 assert(DS.getRepAsType());
2829 TypeSourceInfo *TInfo = 0;
2830 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2831 TL.setUnderlyingTInfo(TInfo);
2833 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
2834 // FIXME: This holds only because we only have one unary transform.
2835 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
2836 TL.setKWLoc(DS.getTypeSpecTypeLoc());
2837 TL.setParensRange(DS.getTypeofParensRange());
2838 assert(DS.getRepAsType());
2839 TypeSourceInfo *TInfo = 0;
2840 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2841 TL.setUnderlyingTInfo(TInfo);
2843 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2844 // By default, use the source location of the type specifier.
2845 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
2846 if (TL.needsExtraLocalData()) {
2847 // Set info for the written builtin specifiers.
2848 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
2849 // Try to have a meaningful source location.
2850 if (TL.getWrittenSignSpec() != TSS_unspecified)
2851 // Sign spec loc overrides the others (e.g., 'unsigned long').
2852 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
2853 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
2854 // Width spec loc overrides type spec loc (e.g., 'short int').
2855 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
2858 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2859 ElaboratedTypeKeyword Keyword
2860 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2861 if (DS.getTypeSpecType() == TST_typename) {
2862 TypeSourceInfo *TInfo = 0;
2863 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2865 TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
2869 TL.setKeywordLoc(Keyword != ETK_None
2870 ? DS.getTypeSpecTypeLoc()
2871 : SourceLocation());
2872 const CXXScopeSpec& SS = DS.getTypeSpecScope();
2873 TL.setQualifierLoc(SS.getWithLocInContext(Context));
2874 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
2876 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
2877 ElaboratedTypeKeyword Keyword
2878 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2879 if (DS.getTypeSpecType() == TST_typename) {
2880 TypeSourceInfo *TInfo = 0;
2881 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2883 TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
2887 TL.setKeywordLoc(Keyword != ETK_None
2888 ? DS.getTypeSpecTypeLoc()
2889 : SourceLocation());
2890 const CXXScopeSpec& SS = DS.getTypeSpecScope();
2891 TL.setQualifierLoc(SS.getWithLocInContext(Context));
2892 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2894 void VisitDependentTemplateSpecializationTypeLoc(
2895 DependentTemplateSpecializationTypeLoc TL) {
2896 ElaboratedTypeKeyword Keyword
2897 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2898 if (Keyword == ETK_Typename) {
2899 TypeSourceInfo *TInfo = 0;
2900 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2902 TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
2903 TInfo->getTypeLoc()));
2907 TL.initializeLocal(Context, SourceLocation());
2908 TL.setKeywordLoc(Keyword != ETK_None
2909 ? DS.getTypeSpecTypeLoc()
2910 : SourceLocation());
2911 const CXXScopeSpec& SS = DS.getTypeSpecScope();
2912 TL.setQualifierLoc(SS.getWithLocInContext(Context));
2913 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2915 void VisitTagTypeLoc(TagTypeLoc TL) {
2916 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2918 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
2919 TL.setKWLoc(DS.getTypeSpecTypeLoc());
2920 TL.setParensRange(DS.getTypeofParensRange());
2922 TypeSourceInfo *TInfo = 0;
2923 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2924 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
2927 void VisitTypeLoc(TypeLoc TL) {
2928 // FIXME: add other typespec types and change this to an assert.
2929 TL.initialize(Context, DS.getTypeSpecTypeLoc());
2933 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
2934 ASTContext &Context;
2935 const DeclaratorChunk &Chunk;
2938 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
2939 : Context(Context), Chunk(Chunk) {}
2941 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2942 llvm_unreachable("qualified type locs not expected here!");
2945 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
2946 fillAttributedTypeLoc(TL, Chunk.getAttrs());
2948 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2949 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
2950 TL.setCaretLoc(Chunk.Loc);
2952 void VisitPointerTypeLoc(PointerTypeLoc TL) {
2953 assert(Chunk.Kind == DeclaratorChunk::Pointer);
2954 TL.setStarLoc(Chunk.Loc);
2956 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2957 assert(Chunk.Kind == DeclaratorChunk::Pointer);
2958 TL.setStarLoc(Chunk.Loc);
2960 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2961 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
2962 const CXXScopeSpec& SS = Chunk.Mem.Scope();
2963 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
2965 const Type* ClsTy = TL.getClass();
2966 QualType ClsQT = QualType(ClsTy, 0);
2967 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
2968 // Now copy source location info into the type loc component.
2969 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
2970 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
2971 case NestedNameSpecifier::Identifier:
2972 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
2974 DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL);
2975 DNTLoc.setKeywordLoc(SourceLocation());
2976 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
2977 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
2981 case NestedNameSpecifier::TypeSpec:
2982 case NestedNameSpecifier::TypeSpecWithTemplate:
2983 if (isa<ElaboratedType>(ClsTy)) {
2984 ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL);
2985 ETLoc.setKeywordLoc(SourceLocation());
2986 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
2987 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
2988 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
2990 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
2994 case NestedNameSpecifier::Namespace:
2995 case NestedNameSpecifier::NamespaceAlias:
2996 case NestedNameSpecifier::Global:
2997 llvm_unreachable("Nested-name-specifier must name a type");
3001 // Finally fill in MemberPointerLocInfo fields.
3002 TL.setStarLoc(Chunk.Loc);
3003 TL.setClassTInfo(ClsTInfo);
3005 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3006 assert(Chunk.Kind == DeclaratorChunk::Reference);
3007 // 'Amp' is misleading: this might have been originally
3008 /// spelled with AmpAmp.
3009 TL.setAmpLoc(Chunk.Loc);
3011 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3012 assert(Chunk.Kind == DeclaratorChunk::Reference);
3013 assert(!Chunk.Ref.LValueRef);
3014 TL.setAmpAmpLoc(Chunk.Loc);
3016 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
3017 assert(Chunk.Kind == DeclaratorChunk::Array);
3018 TL.setLBracketLoc(Chunk.Loc);
3019 TL.setRBracketLoc(Chunk.EndLoc);
3020 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
3022 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3023 assert(Chunk.Kind == DeclaratorChunk::Function);
3024 TL.setLocalRangeBegin(Chunk.Loc);
3025 TL.setLocalRangeEnd(Chunk.EndLoc);
3026 TL.setTrailingReturn(!!Chunk.Fun.TrailingReturnType);
3028 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
3029 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
3030 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
3031 TL.setArg(tpi++, Param);
3033 // FIXME: exception specs
3035 void VisitParenTypeLoc(ParenTypeLoc TL) {
3036 assert(Chunk.Kind == DeclaratorChunk::Paren);
3037 TL.setLParenLoc(Chunk.Loc);
3038 TL.setRParenLoc(Chunk.EndLoc);
3041 void VisitTypeLoc(TypeLoc TL) {
3042 llvm_unreachable("unsupported TypeLoc kind in declarator!");
3047 /// \brief Create and instantiate a TypeSourceInfo with type source information.
3049 /// \param T QualType referring to the type as written in source code.
3051 /// \param ReturnTypeInfo For declarators whose return type does not show
3052 /// up in the normal place in the declaration specifiers (such as a C++
3053 /// conversion function), this pointer will refer to a type source information
3054 /// for that return type.
3056 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
3057 TypeSourceInfo *ReturnTypeInfo) {
3058 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
3059 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
3061 // Handle parameter packs whose type is a pack expansion.
3062 if (isa<PackExpansionType>(T)) {
3063 cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc());
3064 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3067 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3068 while (isa<AttributedTypeLoc>(CurrTL)) {
3069 AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL);
3070 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
3071 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3074 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
3075 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3078 // If we have different source information for the return type, use
3079 // that. This really only applies to C++ conversion functions.
3080 if (ReturnTypeInfo) {
3081 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
3082 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
3083 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
3085 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
3091 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
3092 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
3093 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
3094 // and Sema during declaration parsing. Try deallocating/caching them when
3095 // it's appropriate, instead of allocating them and keeping them around.
3096 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
3098 new (LocT) LocInfoType(T, TInfo);
3099 assert(LocT->getTypeClass() != T->getTypeClass() &&
3100 "LocInfoType's TypeClass conflicts with an existing Type class");
3101 return ParsedType::make(QualType(LocT, 0));
3104 void LocInfoType::getAsStringInternal(std::string &Str,
3105 const PrintingPolicy &Policy) const {
3106 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
3107 " was used directly instead of getting the QualType through"
3108 " GetTypeFromParser");
3111 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
3112 // C99 6.7.6: Type names have no identifier. This is already validated by
3114 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
3116 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3117 QualType T = TInfo->getType();
3118 if (D.isInvalidType())
3121 // Make sure there are no unused decl attributes on the declarator.
3122 // We don't want to do this for ObjC parameters because we're going
3123 // to apply them to the actual parameter declaration.
3124 if (D.getContext() != Declarator::ObjCParameterContext)
3125 checkUnusedDeclAttributes(D);
3127 if (getLangOptions().CPlusPlus) {
3128 // Check that there are no default arguments (C++ only).
3129 CheckExtraCXXDefaultArguments(D);
3132 return CreateParsedType(T, TInfo);
3135 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
3136 QualType T = Context.getObjCInstanceType();
3137 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
3138 return CreateParsedType(T, TInfo);
3142 //===----------------------------------------------------------------------===//
3143 // Type Attribute Processing
3144 //===----------------------------------------------------------------------===//
3146 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
3147 /// specified type. The attribute contains 1 argument, the id of the address
3148 /// space for the type.
3149 static void HandleAddressSpaceTypeAttribute(QualType &Type,
3150 const AttributeList &Attr, Sema &S){
3152 // If this type is already address space qualified, reject it.
3153 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
3154 // qualifiers for two or more different address spaces."
3155 if (Type.getAddressSpace()) {
3156 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
3161 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
3162 // qualified by an address-space qualifier."
3163 if (Type->isFunctionType()) {
3164 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
3169 // Check the attribute arguments.
3170 if (Attr.getNumArgs() != 1) {
3171 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3175 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
3176 llvm::APSInt addrSpace(32);
3177 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
3178 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
3179 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
3180 << ASArgExpr->getSourceRange();
3186 if (addrSpace.isSigned()) {
3187 if (addrSpace.isNegative()) {
3188 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
3189 << ASArgExpr->getSourceRange();
3193 addrSpace.setIsSigned(false);
3195 llvm::APSInt max(addrSpace.getBitWidth());
3196 max = Qualifiers::MaxAddressSpace;
3197 if (addrSpace > max) {
3198 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
3199 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
3204 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
3205 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
3208 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
3209 /// attribute on the specified type.
3211 /// Returns 'true' if the attribute was handled.
3212 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
3213 AttributeList &attr,
3215 if (!type->isObjCRetainableType() && !type->isDependentType())
3218 Sema &S = state.getSema();
3219 SourceLocation AttrLoc = attr.getLoc();
3220 if (AttrLoc.isMacroID())
3221 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
3223 if (type.getQualifiers().getObjCLifetime()) {
3224 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
3229 if (!attr.getParameterName()) {
3230 S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string)
3231 << "objc_ownership" << 1;
3236 Qualifiers::ObjCLifetime lifetime;
3237 if (attr.getParameterName()->isStr("none"))
3238 lifetime = Qualifiers::OCL_ExplicitNone;
3239 else if (attr.getParameterName()->isStr("strong"))
3240 lifetime = Qualifiers::OCL_Strong;
3241 else if (attr.getParameterName()->isStr("weak"))
3242 lifetime = Qualifiers::OCL_Weak;
3243 else if (attr.getParameterName()->isStr("autoreleasing"))
3244 lifetime = Qualifiers::OCL_Autoreleasing;
3246 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
3247 << "objc_ownership" << attr.getParameterName();
3252 // Consume lifetime attributes without further comment outside of
3254 if (!S.getLangOptions().ObjCAutoRefCount)
3258 qs.setObjCLifetime(lifetime);
3259 QualType origType = type;
3260 type = S.Context.getQualifiedType(type, qs);
3262 // If we have a valid source location for the attribute, use an
3263 // AttributedType instead.
3264 if (AttrLoc.isValid())
3265 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
3268 // Forbid __weak if the runtime doesn't support it.
3269 if (lifetime == Qualifiers::OCL_Weak &&
3270 !S.getLangOptions().ObjCRuntimeHasWeak) {
3272 // Actually, delay this until we know what we're parsing.
3273 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
3274 S.DelayedDiagnostics.add(
3275 sema::DelayedDiagnostic::makeForbiddenType(
3276 S.getSourceManager().getExpansionLoc(AttrLoc),
3277 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
3279 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
3286 // Forbid __weak for class objects marked as
3287 // objc_arc_weak_reference_unavailable
3288 if (lifetime == Qualifiers::OCL_Weak) {
3290 while (const PointerType *ptr = T->getAs<PointerType>())
3291 T = ptr->getPointeeType();
3292 if (const ObjCObjectPointerType *ObjT = T->getAs<ObjCObjectPointerType>()) {
3293 ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl();
3294 if (Class->isArcWeakrefUnavailable()) {
3295 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
3296 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
3297 diag::note_class_declared);
3305 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
3306 /// attribute on the specified type. Returns true to indicate that
3307 /// the attribute was handled, false to indicate that the type does
3308 /// not permit the attribute.
3309 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
3310 AttributeList &attr,
3312 Sema &S = state.getSema();
3314 // Delay if this isn't some kind of pointer.
3315 if (!type->isPointerType() &&
3316 !type->isObjCObjectPointerType() &&
3317 !type->isBlockPointerType())
3320 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
3321 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
3326 // Check the attribute arguments.
3327 if (!attr.getParameterName()) {
3328 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
3333 Qualifiers::GC GCAttr;
3334 if (attr.getNumArgs() != 0) {
3335 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3339 if (attr.getParameterName()->isStr("weak"))
3340 GCAttr = Qualifiers::Weak;
3341 else if (attr.getParameterName()->isStr("strong"))
3342 GCAttr = Qualifiers::Strong;
3344 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
3345 << "objc_gc" << attr.getParameterName();
3350 QualType origType = type;
3351 type = S.Context.getObjCGCQualType(origType, GCAttr);
3353 // Make an attributed type to preserve the source information.
3354 if (attr.getLoc().isValid())
3355 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
3362 /// A helper class to unwrap a type down to a function for the
3363 /// purposes of applying attributes there.
3366 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
3367 /// if (unwrapped.isFunctionType()) {
3368 /// const FunctionType *fn = unwrapped.get();
3369 /// // change fn somehow
3370 /// T = unwrapped.wrap(fn);
3372 struct FunctionTypeUnwrapper {
3383 const FunctionType *Fn;
3384 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
3386 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
3388 const Type *Ty = T.getTypePtr();
3389 if (isa<FunctionType>(Ty)) {
3390 Fn = cast<FunctionType>(Ty);
3392 } else if (isa<ParenType>(Ty)) {
3393 T = cast<ParenType>(Ty)->getInnerType();
3394 Stack.push_back(Parens);
3395 } else if (isa<PointerType>(Ty)) {
3396 T = cast<PointerType>(Ty)->getPointeeType();
3397 Stack.push_back(Pointer);
3398 } else if (isa<BlockPointerType>(Ty)) {
3399 T = cast<BlockPointerType>(Ty)->getPointeeType();
3400 Stack.push_back(BlockPointer);
3401 } else if (isa<MemberPointerType>(Ty)) {
3402 T = cast<MemberPointerType>(Ty)->getPointeeType();
3403 Stack.push_back(MemberPointer);
3404 } else if (isa<ReferenceType>(Ty)) {
3405 T = cast<ReferenceType>(Ty)->getPointeeType();
3406 Stack.push_back(Reference);
3408 const Type *DTy = Ty->getUnqualifiedDesugaredType();
3414 T = QualType(DTy, 0);
3415 Stack.push_back(Desugar);
3420 bool isFunctionType() const { return (Fn != 0); }
3421 const FunctionType *get() const { return Fn; }
3423 QualType wrap(Sema &S, const FunctionType *New) {
3424 // If T wasn't modified from the unwrapped type, do nothing.
3425 if (New == get()) return Original;
3428 return wrap(S.Context, Original, 0);
3432 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
3433 if (I == Stack.size())
3434 return C.getQualifiedType(Fn, Old.getQualifiers());
3436 // Build up the inner type, applying the qualifiers from the old
3437 // type to the new type.
3438 SplitQualType SplitOld = Old.split();
3440 // As a special case, tail-recurse if there are no qualifiers.
3441 if (SplitOld.second.empty())
3442 return wrap(C, SplitOld.first, I);
3443 return C.getQualifiedType(wrap(C, SplitOld.first, I), SplitOld.second);
3446 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
3447 if (I == Stack.size()) return QualType(Fn, 0);
3449 switch (static_cast<WrapKind>(Stack[I++])) {
3451 // This is the point at which we potentially lose source
3453 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
3456 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
3457 return C.getParenType(New);
3461 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
3462 return C.getPointerType(New);
3465 case BlockPointer: {
3466 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
3467 return C.getBlockPointerType(New);
3470 case MemberPointer: {
3471 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
3472 QualType New = wrap(C, OldMPT->getPointeeType(), I);
3473 return C.getMemberPointerType(New, OldMPT->getClass());
3477 const ReferenceType *OldRef = cast<ReferenceType>(Old);
3478 QualType New = wrap(C, OldRef->getPointeeType(), I);
3479 if (isa<LValueReferenceType>(OldRef))
3480 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
3482 return C.getRValueReferenceType(New);
3486 llvm_unreachable("unknown wrapping kind");
3492 /// Process an individual function attribute. Returns true to
3493 /// indicate that the attribute was handled, false if it wasn't.
3494 static bool handleFunctionTypeAttr(TypeProcessingState &state,
3495 AttributeList &attr,
3497 Sema &S = state.getSema();
3499 FunctionTypeUnwrapper unwrapped(S, type);
3501 if (attr.getKind() == AttributeList::AT_noreturn) {
3502 if (S.CheckNoReturnAttr(attr))
3505 // Delay if this is not a function type.
3506 if (!unwrapped.isFunctionType())
3509 // Otherwise we can process right away.
3510 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
3511 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3515 // ns_returns_retained is not always a type attribute, but if we got
3516 // here, we're treating it as one right now.
3517 if (attr.getKind() == AttributeList::AT_ns_returns_retained) {
3518 assert(S.getLangOptions().ObjCAutoRefCount &&
3519 "ns_returns_retained treated as type attribute in non-ARC");
3520 if (attr.getNumArgs()) return true;
3522 // Delay if this is not a function type.
3523 if (!unwrapped.isFunctionType())
3526 FunctionType::ExtInfo EI
3527 = unwrapped.get()->getExtInfo().withProducesResult(true);
3528 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3532 if (attr.getKind() == AttributeList::AT_regparm) {
3534 if (S.CheckRegparmAttr(attr, value))
3537 // Delay if this is not a function type.
3538 if (!unwrapped.isFunctionType())
3541 // Diagnose regparm with fastcall.
3542 const FunctionType *fn = unwrapped.get();
3543 CallingConv CC = fn->getCallConv();
3544 if (CC == CC_X86FastCall) {
3545 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3546 << FunctionType::getNameForCallConv(CC)
3552 FunctionType::ExtInfo EI =
3553 unwrapped.get()->getExtInfo().withRegParm(value);
3554 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3558 // Otherwise, a calling convention.
3560 if (S.CheckCallingConvAttr(attr, CC))
3563 // Delay if the type didn't work out to a function.
3564 if (!unwrapped.isFunctionType()) return false;
3566 const FunctionType *fn = unwrapped.get();
3567 CallingConv CCOld = fn->getCallConv();
3568 if (S.Context.getCanonicalCallConv(CC) ==
3569 S.Context.getCanonicalCallConv(CCOld)) {
3570 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
3571 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3575 if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) {
3576 // Should we diagnose reapplications of the same convention?
3577 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3578 << FunctionType::getNameForCallConv(CC)
3579 << FunctionType::getNameForCallConv(CCOld);
3584 // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
3585 if (CC == CC_X86FastCall) {
3586 if (isa<FunctionNoProtoType>(fn)) {
3587 S.Diag(attr.getLoc(), diag::err_cconv_knr)
3588 << FunctionType::getNameForCallConv(CC);
3593 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
3594 if (FnP->isVariadic()) {
3595 S.Diag(attr.getLoc(), diag::err_cconv_varargs)
3596 << FunctionType::getNameForCallConv(CC);
3601 // Also diagnose fastcall with regparm.
3602 if (fn->getHasRegParm()) {
3603 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3605 << FunctionType::getNameForCallConv(CC);
3611 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
3612 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3616 /// Handle OpenCL image access qualifiers: read_only, write_only, read_write
3617 static void HandleOpenCLImageAccessAttribute(QualType& CurType,
3618 const AttributeList &Attr,
3620 // Check the attribute arguments.
3621 if (Attr.getNumArgs() != 1) {
3622 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3626 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3627 llvm::APSInt arg(32);
3628 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3629 !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
3630 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3631 << "opencl_image_access" << sizeExpr->getSourceRange();
3635 unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
3637 case CLIA_read_only:
3638 case CLIA_write_only:
3639 case CLIA_read_write:
3640 // Implemented in a separate patch
3643 // Implemented in a separate patch
3644 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3645 << sizeExpr->getSourceRange();
3651 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
3652 /// and float scalars, although arrays, pointers, and function return values are
3653 /// allowed in conjunction with this construct. Aggregates with this attribute
3654 /// are invalid, even if they are of the same size as a corresponding scalar.
3655 /// The raw attribute should contain precisely 1 argument, the vector size for
3656 /// the variable, measured in bytes. If curType and rawAttr are well formed,
3657 /// this routine will return a new vector type.
3658 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
3660 // Check the attribute arguments.
3661 if (Attr.getNumArgs() != 1) {
3662 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3666 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3667 llvm::APSInt vecSize(32);
3668 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3669 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
3670 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3671 << "vector_size" << sizeExpr->getSourceRange();
3675 // the base type must be integer or float, and can't already be a vector.
3676 if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
3677 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
3681 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3682 // vecSize is specified in bytes - convert to bits.
3683 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
3685 // the vector size needs to be an integral multiple of the type size.
3686 if (vectorSize % typeSize) {
3687 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3688 << sizeExpr->getSourceRange();
3692 if (vectorSize == 0) {
3693 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
3694 << sizeExpr->getSourceRange();
3699 // Success! Instantiate the vector type, the number of elements is > 0, and
3700 // not required to be a power of 2, unlike GCC.
3701 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
3702 VectorType::GenericVector);
3705 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
3707 static void HandleExtVectorTypeAttr(QualType &CurType,
3708 const AttributeList &Attr,
3712 // Special case where the argument is a template id.
3713 if (Attr.getParameterName()) {
3716 id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
3718 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, id, false,
3720 if (Size.isInvalid())
3723 sizeExpr = Size.get();
3725 // check the attribute arguments.
3726 if (Attr.getNumArgs() != 1) {
3727 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3730 sizeExpr = Attr.getArg(0);
3733 // Create the vector type.
3734 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
3739 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
3740 /// "neon_polyvector_type" attributes are used to create vector types that
3741 /// are mangled according to ARM's ABI. Otherwise, these types are identical
3742 /// to those created with the "vector_size" attribute. Unlike "vector_size"
3743 /// the argument to these Neon attributes is the number of vector elements,
3744 /// not the vector size in bytes. The vector width and element type must
3745 /// match one of the standard Neon vector types.
3746 static void HandleNeonVectorTypeAttr(QualType& CurType,
3747 const AttributeList &Attr, Sema &S,
3748 VectorType::VectorKind VecKind,
3749 const char *AttrName) {
3750 // Check the attribute arguments.
3751 if (Attr.getNumArgs() != 1) {
3752 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3756 // The number of elements must be an ICE.
3757 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
3758 llvm::APSInt numEltsInt(32);
3759 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
3760 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
3761 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3762 << AttrName << numEltsExpr->getSourceRange();
3766 // Only certain element types are supported for Neon vectors.
3767 const BuiltinType* BTy = CurType->getAs<BuiltinType>();
3769 (VecKind == VectorType::NeonPolyVector &&
3770 BTy->getKind() != BuiltinType::SChar &&
3771 BTy->getKind() != BuiltinType::Short) ||
3772 (BTy->getKind() != BuiltinType::SChar &&
3773 BTy->getKind() != BuiltinType::UChar &&
3774 BTy->getKind() != BuiltinType::Short &&
3775 BTy->getKind() != BuiltinType::UShort &&
3776 BTy->getKind() != BuiltinType::Int &&
3777 BTy->getKind() != BuiltinType::UInt &&
3778 BTy->getKind() != BuiltinType::LongLong &&
3779 BTy->getKind() != BuiltinType::ULongLong &&
3780 BTy->getKind() != BuiltinType::Float)) {
3781 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
3785 // The total size of the vector must be 64 or 128 bits.
3786 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3787 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
3788 unsigned vecSize = typeSize * numElts;
3789 if (vecSize != 64 && vecSize != 128) {
3790 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
3795 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
3798 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
3799 bool isDeclSpec, AttributeList *attrs) {
3800 // Scan through and apply attributes to this type where it makes sense. Some
3801 // attributes (such as __address_space__, __vector_size__, etc) apply to the
3802 // type, but others can be present in the type specifiers even though they
3803 // apply to the decl. Here we apply type attributes and ignore the rest.
3805 AttributeList *next;
3807 AttributeList &attr = *attrs;
3808 next = attr.getNext();
3810 // Skip attributes that were marked to be invalid.
3811 if (attr.isInvalid())
3814 // If this is an attribute we can handle, do so now,
3815 // otherwise, add it to the FnAttrs list for rechaining.
3816 switch (attr.getKind()) {
3819 case AttributeList::AT_may_alias:
3820 // FIXME: This attribute needs to actually be handled, but if we ignore
3821 // it it breaks large amounts of Linux software.
3822 attr.setUsedAsTypeAttr();
3824 case AttributeList::AT_address_space:
3825 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
3826 attr.setUsedAsTypeAttr();
3828 OBJC_POINTER_TYPE_ATTRS_CASELIST:
3829 if (!handleObjCPointerTypeAttr(state, attr, type))
3830 distributeObjCPointerTypeAttr(state, attr, type);
3831 attr.setUsedAsTypeAttr();
3833 case AttributeList::AT_vector_size:
3834 HandleVectorSizeAttr(type, attr, state.getSema());
3835 attr.setUsedAsTypeAttr();
3837 case AttributeList::AT_ext_vector_type:
3838 if (state.getDeclarator().getDeclSpec().getStorageClassSpec()
3839 != DeclSpec::SCS_typedef)
3840 HandleExtVectorTypeAttr(type, attr, state.getSema());
3841 attr.setUsedAsTypeAttr();
3843 case AttributeList::AT_neon_vector_type:
3844 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3845 VectorType::NeonVector, "neon_vector_type");
3846 attr.setUsedAsTypeAttr();
3848 case AttributeList::AT_neon_polyvector_type:
3849 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3850 VectorType::NeonPolyVector,
3851 "neon_polyvector_type");
3852 attr.setUsedAsTypeAttr();
3854 case AttributeList::AT_opencl_image_access:
3855 HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
3856 attr.setUsedAsTypeAttr();
3859 case AttributeList::AT_ns_returns_retained:
3860 if (!state.getSema().getLangOptions().ObjCAutoRefCount)
3862 // fallthrough into the function attrs
3864 FUNCTION_TYPE_ATTRS_CASELIST:
3865 attr.setUsedAsTypeAttr();
3867 // Never process function type attributes as part of the
3868 // declaration-specifiers.
3870 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
3872 // Otherwise, handle the possible delays.
3873 else if (!handleFunctionTypeAttr(state, attr, type))
3874 distributeFunctionTypeAttr(state, attr, type);
3877 } while ((attrs = next));
3880 /// \brief Ensure that the type of the given expression is complete.
3882 /// This routine checks whether the expression \p E has a complete type. If the
3883 /// expression refers to an instantiable construct, that instantiation is
3884 /// performed as needed to complete its type. Furthermore
3885 /// Sema::RequireCompleteType is called for the expression's type (or in the
3886 /// case of a reference type, the referred-to type).
3888 /// \param E The expression whose type is required to be complete.
3889 /// \param PD The partial diagnostic that will be printed out if the type cannot
3892 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
3894 bool Sema::RequireCompleteExprType(Expr *E, const PartialDiagnostic &PD,
3895 std::pair<SourceLocation,
3896 PartialDiagnostic> Note) {
3897 QualType T = E->getType();
3899 // Fast path the case where the type is already complete.
3900 if (!T->isIncompleteType())
3903 // Incomplete array types may be completed by the initializer attached to
3904 // their definitions. For static data members of class templates we need to
3905 // instantiate the definition to get this initializer and complete the type.
3906 if (T->isIncompleteArrayType()) {
3907 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3908 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
3909 if (Var->isStaticDataMember() &&
3910 Var->getInstantiatedFromStaticDataMember()) {
3912 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
3913 assert(MSInfo && "Missing member specialization information?");
3914 if (MSInfo->getTemplateSpecializationKind()
3915 != TSK_ExplicitSpecialization) {
3916 // If we don't already have a point of instantiation, this is it.
3917 if (MSInfo->getPointOfInstantiation().isInvalid()) {
3918 MSInfo->setPointOfInstantiation(E->getLocStart());
3920 // This is a modification of an existing AST node. Notify
3922 if (ASTMutationListener *L = getASTMutationListener())
3923 L->StaticDataMemberInstantiated(Var);
3926 InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
3928 // Update the type to the newly instantiated definition's type both
3929 // here and within the expression.
3930 if (VarDecl *Def = Var->getDefinition()) {
3938 // We still go on to try to complete the type independently, as it
3939 // may also require instantiations or diagnostics if it remains
3946 // FIXME: Are there other cases which require instantiating something other
3947 // than the type to complete the type of an expression?
3949 // Look through reference types and complete the referred type.
3950 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3951 T = Ref->getPointeeType();
3953 return RequireCompleteType(E->getExprLoc(), T, PD, Note);
3956 /// @brief Ensure that the type T is a complete type.
3958 /// This routine checks whether the type @p T is complete in any
3959 /// context where a complete type is required. If @p T is a complete
3960 /// type, returns false. If @p T is a class template specialization,
3961 /// this routine then attempts to perform class template
3962 /// instantiation. If instantiation fails, or if @p T is incomplete
3963 /// and cannot be completed, issues the diagnostic @p diag (giving it
3964 /// the type @p T) and returns true.
3966 /// @param Loc The location in the source that the incomplete type
3967 /// diagnostic should refer to.
3969 /// @param T The type that this routine is examining for completeness.
3971 /// @param PD The partial diagnostic that will be printed out if T is not a
3974 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
3975 /// @c false otherwise.
3976 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
3977 const PartialDiagnostic &PD,
3978 std::pair<SourceLocation,
3979 PartialDiagnostic> Note) {
3980 unsigned diag = PD.getDiagID();
3982 // FIXME: Add this assertion to make sure we always get instantiation points.
3983 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
3984 // FIXME: Add this assertion to help us flush out problems with
3985 // checking for dependent types and type-dependent expressions.
3987 // assert(!T->isDependentType() &&
3988 // "Can't ask whether a dependent type is complete");
3990 // If we have a complete type, we're done.
3991 if (!T->isIncompleteType())
3994 // If we have a class template specialization or a class member of a
3995 // class template specialization, or an array with known size of such,
3996 // try to instantiate it.
3997 QualType MaybeTemplate = T;
3998 if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
3999 MaybeTemplate = Array->getElementType();
4000 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
4001 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
4002 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
4003 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
4004 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
4005 TSK_ImplicitInstantiation,
4006 /*Complain=*/diag != 0);
4007 } else if (CXXRecordDecl *Rec
4008 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
4009 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
4010 MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
4011 assert(MSInfo && "Missing member specialization information?");
4012 // This record was instantiated from a class within a template.
4013 if (MSInfo->getTemplateSpecializationKind()
4014 != TSK_ExplicitSpecialization)
4015 return InstantiateClass(Loc, Rec, Pattern,
4016 getTemplateInstantiationArgs(Rec),
4017 TSK_ImplicitInstantiation,
4018 /*Complain=*/diag != 0);
4026 const TagType *Tag = T->getAs<TagType>();
4028 // Avoid diagnosing invalid decls as incomplete.
4029 if (Tag && Tag->getDecl()->isInvalidDecl())
4032 // Give the external AST source a chance to complete the type.
4033 if (Tag && Tag->getDecl()->hasExternalLexicalStorage()) {
4034 Context.getExternalSource()->CompleteType(Tag->getDecl());
4035 if (!Tag->isIncompleteType())
4039 // We have an incomplete type. Produce a diagnostic.
4042 // If we have a note, produce it.
4043 if (!Note.first.isInvalid())
4044 Diag(Note.first, Note.second);
4046 // If the type was a forward declaration of a class/struct/union
4047 // type, produce a note.
4048 if (Tag && !Tag->getDecl()->isInvalidDecl())
4049 Diag(Tag->getDecl()->getLocation(),
4050 Tag->isBeingDefined() ? diag::note_type_being_defined
4051 : diag::note_forward_declaration)
4052 << QualType(Tag, 0);
4057 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4058 const PartialDiagnostic &PD) {
4059 return RequireCompleteType(Loc, T, PD,
4060 std::make_pair(SourceLocation(), PDiag(0)));
4063 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4065 return RequireCompleteType(Loc, T, PDiag(DiagID),
4066 std::make_pair(SourceLocation(), PDiag(0)));
4069 /// @brief Ensure that the type T is a literal type.
4071 /// This routine checks whether the type @p T is a literal type. If @p T is an
4072 /// incomplete type, an attempt is made to complete it. If @p T is a literal
4073 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
4074 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
4075 /// it the type @p T), along with notes explaining why the type is not a
4076 /// literal type, and returns true.
4078 /// @param Loc The location in the source that the non-literal type
4079 /// diagnostic should refer to.
4081 /// @param T The type that this routine is examining for literalness.
4083 /// @param PD The partial diagnostic that will be printed out if T is not a
4086 /// @param AllowIncompleteType If true, an incomplete type will be considered
4089 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
4090 /// @c false otherwise.
4091 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
4092 const PartialDiagnostic &PD,
4093 bool AllowIncompleteType) {
4094 assert(!T->isDependentType() && "type should not be dependent");
4096 bool Incomplete = RequireCompleteType(Loc, T, 0);
4097 if (T->isLiteralType() || (AllowIncompleteType && Incomplete))
4100 if (PD.getDiagID() == 0)
4105 if (T->isVariableArrayType())
4108 const RecordType *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>();
4112 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4114 // If the class has virtual base classes, then it's not an aggregate, and
4115 // cannot have any constexpr constructors, so is non-literal. This is better
4116 // to diagnose than the resulting absence of constexpr constructors.
4117 if (RD->getNumVBases()) {
4118 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
4119 << RD->isStruct() << RD->getNumVBases();
4120 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
4121 E = RD->vbases_end(); I != E; ++I)
4122 Diag(I->getSourceRange().getBegin(),
4123 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
4124 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor()) {
4125 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
4127 switch (RD->getTemplateSpecializationKind()) {
4128 case TSK_Undeclared:
4129 case TSK_ExplicitSpecialization:
4132 case TSK_ImplicitInstantiation:
4133 case TSK_ExplicitInstantiationDeclaration:
4134 case TSK_ExplicitInstantiationDefinition:
4135 // If the base template had constexpr constructors which were
4136 // instantiated as non-constexpr constructors, explain why.
4137 for (CXXRecordDecl::ctor_iterator I = RD->ctor_begin(),
4138 E = RD->ctor_end(); I != E; ++I) {
4139 if ((*I)->isCopyConstructor() || (*I)->isMoveConstructor())
4142 FunctionDecl *Base = (*I)->getInstantiatedFromMemberFunction();
4143 if (Base && Base->isConstexpr())
4144 CheckConstexprFunctionDecl(*I, CCK_NoteNonConstexprInstantiation);
4147 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
4148 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4149 E = RD->bases_end(); I != E; ++I) {
4150 if (!I->getType()->isLiteralType()) {
4151 Diag(I->getSourceRange().getBegin(),
4152 diag::note_non_literal_base_class)
4153 << RD << I->getType() << I->getSourceRange();
4157 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
4158 E = RD->field_end(); I != E; ++I) {
4159 if (!(*I)->getType()->isLiteralType()) {
4160 Diag((*I)->getLocation(), diag::note_non_literal_field)
4161 << RD << (*I) << (*I)->getType();
4163 } else if ((*I)->isMutable()) {
4164 Diag((*I)->getLocation(), diag::note_non_literal_mutable_field) << RD;
4168 } else if (!RD->hasTrivialDestructor()) {
4169 // All fields and bases are of literal types, so have trivial destructors.
4170 // If this class's destructor is non-trivial it must be user-declared.
4171 CXXDestructorDecl *Dtor = RD->getDestructor();
4172 assert(Dtor && "class has literal fields and bases but no dtor?");
4176 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
4177 diag::note_non_literal_user_provided_dtor :
4178 diag::note_non_literal_nontrivial_dtor) << RD;
4184 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
4185 /// and qualified by the nested-name-specifier contained in SS.
4186 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
4187 const CXXScopeSpec &SS, QualType T) {
4190 NestedNameSpecifier *NNS;
4192 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4194 if (Keyword == ETK_None)
4198 return Context.getElaboratedType(Keyword, NNS, T);
4201 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
4202 ExprResult ER = CheckPlaceholderExpr(E);
4203 if (ER.isInvalid()) return QualType();
4206 if (!E->isTypeDependent()) {
4207 QualType T = E->getType();
4208 if (const TagType *TT = T->getAs<TagType>())
4209 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
4211 return Context.getTypeOfExprType(E);
4214 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
4215 ExprResult ER = CheckPlaceholderExpr(E);
4216 if (ER.isInvalid()) return QualType();
4219 return Context.getDecltypeType(E);
4222 QualType Sema::BuildUnaryTransformType(QualType BaseType,
4223 UnaryTransformType::UTTKind UKind,
4224 SourceLocation Loc) {
4226 case UnaryTransformType::EnumUnderlyingType:
4227 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
4228 Diag(Loc, diag::err_only_enums_have_underlying_types);
4231 QualType Underlying = BaseType;
4232 if (!BaseType->isDependentType()) {
4233 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
4234 assert(ED && "EnumType has no EnumDecl");
4235 DiagnoseUseOfDecl(ED, Loc);
4236 Underlying = ED->getIntegerType();
4238 assert(!Underlying.isNull());
4239 return Context.getUnaryTransformType(BaseType, Underlying,
4240 UnaryTransformType::EnumUnderlyingType);
4243 llvm_unreachable("unknown unary transform type");
4246 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
4247 if (!T->isDependentType()) {
4248 int DisallowedKind = -1;
4249 if (T->isIncompleteType())
4250 // FIXME: It isn't entirely clear whether incomplete atomic types
4251 // are allowed or not; for simplicity, ban them for the moment.
4253 else if (T->isArrayType())
4255 else if (T->isFunctionType())
4257 else if (T->isReferenceType())
4259 else if (T->isAtomicType())
4261 else if (T.hasQualifiers())
4263 else if (!T.isTriviallyCopyableType(Context))
4264 // Some other non-trivially-copyable type (probably a C++ class)
4267 if (DisallowedKind != -1) {
4268 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
4272 // FIXME: Do we need any handling for ARC here?
4275 // Build the pointer type.
4276 return Context.getAtomicType(T);