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 "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/ASTStructuralEquivalence.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/TypeLoc.h"
24 #include "clang/AST/TypeLocVisitor.h"
25 #include "clang/Basic/PartialDiagnostic.h"
26 #include "clang/Basic/TargetInfo.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/DelayedDiagnostic.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/ScopeInfo.h"
32 #include "clang/Sema/SemaInternal.h"
33 #include "clang/Sema/Template.h"
34 #include "clang/Sema/TemplateInstCallback.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallString.h"
37 #include "llvm/ADT/StringSwitch.h"
38 #include "llvm/Support/ErrorHandling.h"
40 using namespace clang;
42 enum TypeDiagSelector {
48 /// isOmittedBlockReturnType - Return true if this declarator is missing a
49 /// return type because this is a omitted return type on a block literal.
50 static bool isOmittedBlockReturnType(const Declarator &D) {
51 if (D.getContext() != DeclaratorContext::BlockLiteralContext ||
52 D.getDeclSpec().hasTypeSpecifier())
55 if (D.getNumTypeObjects() == 0)
56 return true; // ^{ ... }
58 if (D.getNumTypeObjects() == 1 &&
59 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
60 return true; // ^(int X, float Y) { ... }
65 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
66 /// doesn't apply to the given type.
67 static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
69 TypeDiagSelector WhichType;
70 bool useExpansionLoc = true;
71 switch (attr.getKind()) {
72 case ParsedAttr::AT_ObjCGC:
73 WhichType = TDS_Pointer;
75 case ParsedAttr::AT_ObjCOwnership:
76 WhichType = TDS_ObjCObjOrBlock;
79 // Assume everything else was a function attribute.
80 WhichType = TDS_Function;
81 useExpansionLoc = false;
85 SourceLocation loc = attr.getLoc();
86 StringRef name = attr.getName()->getName();
88 // The GC attributes are usually written with macros; special-case them.
89 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
91 if (useExpansionLoc && loc.isMacroID() && II) {
92 if (II->isStr("strong")) {
93 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
94 } else if (II->isStr("weak")) {
95 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
99 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
103 // objc_gc applies to Objective-C pointers or, otherwise, to the
104 // smallest available pointer type (i.e. 'void*' in 'void**').
105 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
106 case ParsedAttr::AT_ObjCGC: \
107 case ParsedAttr::AT_ObjCOwnership
109 // Calling convention attributes.
110 #define CALLING_CONV_ATTRS_CASELIST \
111 case ParsedAttr::AT_CDecl: \
112 case ParsedAttr::AT_FastCall: \
113 case ParsedAttr::AT_StdCall: \
114 case ParsedAttr::AT_ThisCall: \
115 case ParsedAttr::AT_RegCall: \
116 case ParsedAttr::AT_Pascal: \
117 case ParsedAttr::AT_SwiftCall: \
118 case ParsedAttr::AT_VectorCall: \
119 case ParsedAttr::AT_AArch64VectorPcs: \
120 case ParsedAttr::AT_MSABI: \
121 case ParsedAttr::AT_SysVABI: \
122 case ParsedAttr::AT_Pcs: \
123 case ParsedAttr::AT_IntelOclBicc: \
124 case ParsedAttr::AT_PreserveMost: \
125 case ParsedAttr::AT_PreserveAll
127 // Function type attributes.
128 #define FUNCTION_TYPE_ATTRS_CASELIST \
129 case ParsedAttr::AT_NSReturnsRetained: \
130 case ParsedAttr::AT_NoReturn: \
131 case ParsedAttr::AT_Regparm: \
132 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
133 case ParsedAttr::AT_AnyX86NoCfCheck: \
134 CALLING_CONV_ATTRS_CASELIST
136 // Microsoft-specific type qualifiers.
137 #define MS_TYPE_ATTRS_CASELIST \
138 case ParsedAttr::AT_Ptr32: \
139 case ParsedAttr::AT_Ptr64: \
140 case ParsedAttr::AT_SPtr: \
141 case ParsedAttr::AT_UPtr
143 // Nullability qualifiers.
144 #define NULLABILITY_TYPE_ATTRS_CASELIST \
145 case ParsedAttr::AT_TypeNonNull: \
146 case ParsedAttr::AT_TypeNullable: \
147 case ParsedAttr::AT_TypeNullUnspecified
150 /// An object which stores processing state for the entire
151 /// GetTypeForDeclarator process.
152 class TypeProcessingState {
155 /// The declarator being processed.
156 Declarator &declarator;
158 /// The index of the declarator chunk we're currently processing.
159 /// May be the total number of valid chunks, indicating the
163 /// Whether there are non-trivial modifications to the decl spec.
166 /// Whether we saved the attributes in the decl spec.
169 /// The original set of attributes on the DeclSpec.
170 SmallVector<ParsedAttr *, 2> savedAttrs;
172 /// A list of attributes to diagnose the uselessness of when the
173 /// processing is complete.
174 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
176 /// Attributes corresponding to AttributedTypeLocs that we have not yet
178 // FIXME: The two-phase mechanism by which we construct Types and fill
179 // their TypeLocs makes it hard to correctly assign these. We keep the
180 // attributes in creation order as an attempt to make them line up
182 using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
183 SmallVector<TypeAttrPair, 8> AttrsForTypes;
184 bool AttrsForTypesSorted = true;
186 /// Flag to indicate we parsed a noderef attribute. This is used for
187 /// validating that noderef was used on a pointer or array.
191 TypeProcessingState(Sema &sema, Declarator &declarator)
192 : sema(sema), declarator(declarator),
193 chunkIndex(declarator.getNumTypeObjects()), trivial(true),
194 hasSavedAttrs(false), parsedNoDeref(false) {}
196 Sema &getSema() const {
200 Declarator &getDeclarator() const {
204 bool isProcessingDeclSpec() const {
205 return chunkIndex == declarator.getNumTypeObjects();
208 unsigned getCurrentChunkIndex() const {
212 void setCurrentChunkIndex(unsigned idx) {
213 assert(idx <= declarator.getNumTypeObjects());
217 ParsedAttributesView &getCurrentAttributes() const {
218 if (isProcessingDeclSpec())
219 return getMutableDeclSpec().getAttributes();
220 return declarator.getTypeObject(chunkIndex).getAttrs();
223 /// Save the current set of attributes on the DeclSpec.
224 void saveDeclSpecAttrs() {
225 // Don't try to save them multiple times.
226 if (hasSavedAttrs) return;
228 DeclSpec &spec = getMutableDeclSpec();
229 for (ParsedAttr &AL : spec.getAttributes())
230 savedAttrs.push_back(&AL);
231 trivial &= savedAttrs.empty();
232 hasSavedAttrs = true;
235 /// Record that we had nowhere to put the given type attribute.
236 /// We will diagnose such attributes later.
237 void addIgnoredTypeAttr(ParsedAttr &attr) {
238 ignoredTypeAttrs.push_back(&attr);
241 /// Diagnose all the ignored type attributes, given that the
242 /// declarator worked out to the given type.
243 void diagnoseIgnoredTypeAttrs(QualType type) const {
244 for (auto *Attr : ignoredTypeAttrs)
245 diagnoseBadTypeAttribute(getSema(), *Attr, type);
248 /// Get an attributed type for the given attribute, and remember the Attr
249 /// object so that we can attach it to the AttributedTypeLoc.
250 QualType getAttributedType(Attr *A, QualType ModifiedType,
251 QualType EquivType) {
253 sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType);
254 AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
255 AttrsForTypesSorted = false;
259 /// Extract and remove the Attr* for a given attributed type.
260 const Attr *takeAttrForAttributedType(const AttributedType *AT) {
261 if (!AttrsForTypesSorted) {
262 std::stable_sort(AttrsForTypes.begin(), AttrsForTypes.end(),
263 [](const TypeAttrPair &A, const TypeAttrPair &B) {
264 return A.first < B.first;
266 AttrsForTypesSorted = true;
269 // FIXME: This is quadratic if we have lots of reuses of the same
271 for (auto It = std::partition_point(
272 AttrsForTypes.begin(), AttrsForTypes.end(),
273 [=](const TypeAttrPair &A) { return A.first < AT; });
274 It != AttrsForTypes.end() && It->first == AT; ++It) {
276 const Attr *Result = It->second;
277 It->second = nullptr;
282 llvm_unreachable("no Attr* for AttributedType*");
285 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
287 bool didParseNoDeref() const { return parsedNoDeref; }
289 ~TypeProcessingState() {
292 restoreDeclSpecAttrs();
296 DeclSpec &getMutableDeclSpec() const {
297 return const_cast<DeclSpec&>(declarator.getDeclSpec());
300 void restoreDeclSpecAttrs() {
301 assert(hasSavedAttrs);
303 getMutableDeclSpec().getAttributes().clearListOnly();
304 for (ParsedAttr *AL : savedAttrs)
305 getMutableDeclSpec().getAttributes().addAtEnd(AL);
308 } // end anonymous namespace
310 static void moveAttrFromListToList(ParsedAttr &attr,
311 ParsedAttributesView &fromList,
312 ParsedAttributesView &toList) {
313 fromList.remove(&attr);
314 toList.addAtEnd(&attr);
317 /// The location of a type attribute.
318 enum TypeAttrLocation {
319 /// The attribute is in the decl-specifier-seq.
321 /// The attribute is part of a DeclaratorChunk.
323 /// The attribute is immediately after the declaration's name.
327 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
328 TypeAttrLocation TAL, ParsedAttributesView &attrs);
330 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
333 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
334 ParsedAttr &attr, QualType &type);
336 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
339 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
340 ParsedAttr &attr, QualType &type);
342 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
343 ParsedAttr &attr, QualType &type) {
344 if (attr.getKind() == ParsedAttr::AT_ObjCGC)
345 return handleObjCGCTypeAttr(state, attr, type);
346 assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
347 return handleObjCOwnershipTypeAttr(state, attr, type);
350 /// Given the index of a declarator chunk, check whether that chunk
351 /// directly specifies the return type of a function and, if so, find
352 /// an appropriate place for it.
354 /// \param i - a notional index which the search will start
355 /// immediately inside
357 /// \param onlyBlockPointers Whether we should only look into block
358 /// pointer types (vs. all pointer types).
359 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
361 bool onlyBlockPointers) {
362 assert(i <= declarator.getNumTypeObjects());
364 DeclaratorChunk *result = nullptr;
366 // First, look inwards past parens for a function declarator.
367 for (; i != 0; --i) {
368 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
369 switch (fnChunk.Kind) {
370 case DeclaratorChunk::Paren:
373 // If we find anything except a function, bail out.
374 case DeclaratorChunk::Pointer:
375 case DeclaratorChunk::BlockPointer:
376 case DeclaratorChunk::Array:
377 case DeclaratorChunk::Reference:
378 case DeclaratorChunk::MemberPointer:
379 case DeclaratorChunk::Pipe:
382 // If we do find a function declarator, scan inwards from that,
383 // looking for a (block-)pointer declarator.
384 case DeclaratorChunk::Function:
385 for (--i; i != 0; --i) {
386 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
387 switch (ptrChunk.Kind) {
388 case DeclaratorChunk::Paren:
389 case DeclaratorChunk::Array:
390 case DeclaratorChunk::Function:
391 case DeclaratorChunk::Reference:
392 case DeclaratorChunk::Pipe:
395 case DeclaratorChunk::MemberPointer:
396 case DeclaratorChunk::Pointer:
397 if (onlyBlockPointers)
402 case DeclaratorChunk::BlockPointer:
406 llvm_unreachable("bad declarator chunk kind");
409 // If we run out of declarators doing that, we're done.
412 llvm_unreachable("bad declarator chunk kind");
414 // Okay, reconsider from our new point.
418 // Ran out of chunks, bail out.
422 /// Given that an objc_gc attribute was written somewhere on a
423 /// declaration *other* than on the declarator itself (for which, use
424 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
425 /// didn't apply in whatever position it was written in, try to move
426 /// it to a more appropriate position.
427 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
428 ParsedAttr &attr, QualType type) {
429 Declarator &declarator = state.getDeclarator();
431 // Move it to the outermost normal or block pointer declarator.
432 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
433 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
434 switch (chunk.Kind) {
435 case DeclaratorChunk::Pointer:
436 case DeclaratorChunk::BlockPointer: {
437 // But don't move an ARC ownership attribute to the return type
439 DeclaratorChunk *destChunk = nullptr;
440 if (state.isProcessingDeclSpec() &&
441 attr.getKind() == ParsedAttr::AT_ObjCOwnership)
442 destChunk = maybeMovePastReturnType(declarator, i - 1,
443 /*onlyBlockPointers=*/true);
444 if (!destChunk) destChunk = &chunk;
446 moveAttrFromListToList(attr, state.getCurrentAttributes(),
447 destChunk->getAttrs());
451 case DeclaratorChunk::Paren:
452 case DeclaratorChunk::Array:
455 // We may be starting at the return type of a block.
456 case DeclaratorChunk::Function:
457 if (state.isProcessingDeclSpec() &&
458 attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
459 if (DeclaratorChunk *dest = maybeMovePastReturnType(
461 /*onlyBlockPointers=*/true)) {
462 moveAttrFromListToList(attr, state.getCurrentAttributes(),
469 // Don't walk through these.
470 case DeclaratorChunk::Reference:
471 case DeclaratorChunk::MemberPointer:
472 case DeclaratorChunk::Pipe:
478 diagnoseBadTypeAttribute(state.getSema(), attr, type);
481 /// Distribute an objc_gc type attribute that was written on the
483 static void distributeObjCPointerTypeAttrFromDeclarator(
484 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
485 Declarator &declarator = state.getDeclarator();
487 // objc_gc goes on the innermost pointer to something that's not a
489 unsigned innermost = -1U;
490 bool considerDeclSpec = true;
491 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
492 DeclaratorChunk &chunk = declarator.getTypeObject(i);
493 switch (chunk.Kind) {
494 case DeclaratorChunk::Pointer:
495 case DeclaratorChunk::BlockPointer:
499 case DeclaratorChunk::Reference:
500 case DeclaratorChunk::MemberPointer:
501 case DeclaratorChunk::Paren:
502 case DeclaratorChunk::Array:
503 case DeclaratorChunk::Pipe:
506 case DeclaratorChunk::Function:
507 considerDeclSpec = false;
513 // That might actually be the decl spec if we weren't blocked by
514 // anything in the declarator.
515 if (considerDeclSpec) {
516 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
517 // Splice the attribute into the decl spec. Prevents the
518 // attribute from being applied multiple times and gives
519 // the source-location-filler something to work with.
520 state.saveDeclSpecAttrs();
521 moveAttrFromListToList(attr, declarator.getAttributes(),
522 declarator.getMutableDeclSpec().getAttributes());
527 // Otherwise, if we found an appropriate chunk, splice the attribute
529 if (innermost != -1U) {
530 moveAttrFromListToList(attr, declarator.getAttributes(),
531 declarator.getTypeObject(innermost).getAttrs());
535 // Otherwise, diagnose when we're done building the type.
536 declarator.getAttributes().remove(&attr);
537 state.addIgnoredTypeAttr(attr);
540 /// A function type attribute was written somewhere in a declaration
541 /// *other* than on the declarator itself or in the decl spec. Given
542 /// that it didn't apply in whatever position it was written in, try
543 /// to move it to a more appropriate position.
544 static void distributeFunctionTypeAttr(TypeProcessingState &state,
545 ParsedAttr &attr, QualType type) {
546 Declarator &declarator = state.getDeclarator();
548 // Try to push the attribute from the return type of a function to
549 // the function itself.
550 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
551 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
552 switch (chunk.Kind) {
553 case DeclaratorChunk::Function:
554 moveAttrFromListToList(attr, state.getCurrentAttributes(),
558 case DeclaratorChunk::Paren:
559 case DeclaratorChunk::Pointer:
560 case DeclaratorChunk::BlockPointer:
561 case DeclaratorChunk::Array:
562 case DeclaratorChunk::Reference:
563 case DeclaratorChunk::MemberPointer:
564 case DeclaratorChunk::Pipe:
569 diagnoseBadTypeAttribute(state.getSema(), attr, type);
572 /// Try to distribute a function type attribute to the innermost
573 /// function chunk or type. Returns true if the attribute was
574 /// distributed, false if no location was found.
575 static bool distributeFunctionTypeAttrToInnermost(
576 TypeProcessingState &state, ParsedAttr &attr,
577 ParsedAttributesView &attrList, QualType &declSpecType) {
578 Declarator &declarator = state.getDeclarator();
580 // Put it on the innermost function chunk, if there is one.
581 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
582 DeclaratorChunk &chunk = declarator.getTypeObject(i);
583 if (chunk.Kind != DeclaratorChunk::Function) continue;
585 moveAttrFromListToList(attr, attrList, chunk.getAttrs());
589 return handleFunctionTypeAttr(state, attr, declSpecType);
592 /// A function type attribute was written in the decl spec. Try to
593 /// apply it somewhere.
594 static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
596 QualType &declSpecType) {
597 state.saveDeclSpecAttrs();
599 // C++11 attributes before the decl specifiers actually appertain to
600 // the declarators. Move them straight there. We don't support the
601 // 'put them wherever you like' semantics we allow for GNU attributes.
602 if (attr.isCXX11Attribute()) {
603 moveAttrFromListToList(attr, state.getCurrentAttributes(),
604 state.getDeclarator().getAttributes());
608 // Try to distribute to the innermost.
609 if (distributeFunctionTypeAttrToInnermost(
610 state, attr, state.getCurrentAttributes(), declSpecType))
613 // If that failed, diagnose the bad attribute when the declarator is
615 state.addIgnoredTypeAttr(attr);
618 /// A function type attribute was written on the declarator. Try to
619 /// apply it somewhere.
620 static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
622 QualType &declSpecType) {
623 Declarator &declarator = state.getDeclarator();
625 // Try to distribute to the innermost.
626 if (distributeFunctionTypeAttrToInnermost(
627 state, attr, declarator.getAttributes(), declSpecType))
630 // If that failed, diagnose the bad attribute when the declarator is
632 declarator.getAttributes().remove(&attr);
633 state.addIgnoredTypeAttr(attr);
636 /// Given that there are attributes written on the declarator
637 /// itself, try to distribute any type attributes to the appropriate
638 /// declarator chunk.
640 /// These are attributes like the following:
643 /// but not necessarily this:
645 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
646 QualType &declSpecType) {
647 // Collect all the type attributes from the declarator itself.
648 assert(!state.getDeclarator().getAttributes().empty() &&
649 "declarator has no attrs!");
650 // The called functions in this loop actually remove things from the current
651 // list, so iterating over the existing list isn't possible. Instead, make a
652 // non-owning copy and iterate over that.
653 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
654 for (ParsedAttr &attr : AttrsCopy) {
655 // Do not distribute C++11 attributes. They have strict rules for what
656 // they appertain to.
657 if (attr.isCXX11Attribute())
660 switch (attr.getKind()) {
661 OBJC_POINTER_TYPE_ATTRS_CASELIST:
662 distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType);
665 FUNCTION_TYPE_ATTRS_CASELIST:
666 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType);
669 MS_TYPE_ATTRS_CASELIST:
670 // Microsoft type attributes cannot go after the declarator-id.
673 NULLABILITY_TYPE_ATTRS_CASELIST:
674 // Nullability specifiers cannot go after the declarator-id.
676 // Objective-C __kindof does not get distributed.
677 case ParsedAttr::AT_ObjCKindOf:
686 /// Add a synthetic '()' to a block-literal declarator if it is
687 /// required, given the return type.
688 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
689 QualType declSpecType) {
690 Declarator &declarator = state.getDeclarator();
692 // First, check whether the declarator would produce a function,
693 // i.e. whether the innermost semantic chunk is a function.
694 if (declarator.isFunctionDeclarator()) {
695 // If so, make that declarator a prototyped declarator.
696 declarator.getFunctionTypeInfo().hasPrototype = true;
700 // If there are any type objects, the type as written won't name a
701 // function, regardless of the decl spec type. This is because a
702 // block signature declarator is always an abstract-declarator, and
703 // abstract-declarators can't just be parentheses chunks. Therefore
704 // we need to build a function chunk unless there are no type
705 // objects and the decl spec type is a function.
706 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
709 // Note that there *are* cases with invalid declarators where
710 // declarators consist solely of parentheses. In general, these
711 // occur only in failed efforts to make function declarators, so
712 // faking up the function chunk is still the right thing to do.
714 // Otherwise, we need to fake up a function declarator.
715 SourceLocation loc = declarator.getBeginLoc();
717 // ...and *prepend* it to the declarator.
718 SourceLocation NoLoc;
719 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
721 /*IsAmbiguous=*/false,
725 /*EllipsisLoc=*/NoLoc,
727 /*RefQualifierIsLvalueRef=*/true,
728 /*RefQualifierLoc=*/NoLoc,
729 /*MutableLoc=*/NoLoc, EST_None,
730 /*ESpecRange=*/SourceRange(),
731 /*Exceptions=*/nullptr,
732 /*ExceptionRanges=*/nullptr,
734 /*NoexceptExpr=*/nullptr,
735 /*ExceptionSpecTokens=*/nullptr,
736 /*DeclsInPrototype=*/None, loc, loc, declarator));
738 // For consistency, make sure the state still has us as processing
740 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
741 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
744 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
749 // If this occurs outside a template instantiation, warn the user about
750 // it; they probably didn't mean to specify a redundant qualifier.
751 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
752 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
753 QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
754 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
755 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
756 if (!(RemoveTQs & Qual.first))
759 if (!S.inTemplateInstantiation()) {
760 if (TypeQuals & Qual.first)
761 S.Diag(Qual.second, DiagID)
762 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
763 << FixItHint::CreateRemoval(Qual.second);
766 TypeQuals &= ~Qual.first;
770 /// Return true if this is omitted block return type. Also check type
771 /// attributes and type qualifiers when returning true.
772 static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
774 if (!isOmittedBlockReturnType(declarator))
777 // Warn if we see type attributes for omitted return type on a block literal.
778 SmallVector<ParsedAttr *, 2> ToBeRemoved;
779 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
780 if (AL.isInvalid() || !AL.isTypeAttr())
783 diag::warn_block_literal_attributes_on_omitted_return_type)
785 ToBeRemoved.push_back(&AL);
787 // Remove bad attributes from the list.
788 for (ParsedAttr *AL : ToBeRemoved)
789 declarator.getMutableDeclSpec().getAttributes().remove(AL);
791 // Warn if we see type qualifiers for omitted return type on a block literal.
792 const DeclSpec &DS = declarator.getDeclSpec();
793 unsigned TypeQuals = DS.getTypeQualifiers();
794 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
795 diag::warn_block_literal_qualifiers_on_omitted_return_type);
796 declarator.getMutableDeclSpec().ClearTypeQualifiers();
801 /// Apply Objective-C type arguments to the given type.
802 static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
803 ArrayRef<TypeSourceInfo *> typeArgs,
804 SourceRange typeArgsRange,
805 bool failOnError = false) {
806 // We can only apply type arguments to an Objective-C class type.
807 const auto *objcObjectType = type->getAs<ObjCObjectType>();
808 if (!objcObjectType || !objcObjectType->getInterface()) {
809 S.Diag(loc, diag::err_objc_type_args_non_class)
818 // The class type must be parameterized.
819 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
820 ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
822 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
823 << objcClass->getDeclName()
824 << FixItHint::CreateRemoval(typeArgsRange);
832 // The type must not already be specialized.
833 if (objcObjectType->isSpecialized()) {
834 S.Diag(loc, diag::err_objc_type_args_specialized_class)
836 << FixItHint::CreateRemoval(typeArgsRange);
844 // Check the type arguments.
845 SmallVector<QualType, 4> finalTypeArgs;
846 unsigned numTypeParams = typeParams->size();
847 bool anyPackExpansions = false;
848 for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
849 TypeSourceInfo *typeArgInfo = typeArgs[i];
850 QualType typeArg = typeArgInfo->getType();
852 // Type arguments cannot have explicit qualifiers or nullability.
853 // We ignore indirect sources of these, e.g. behind typedefs or
854 // template arguments.
855 if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
856 bool diagnosed = false;
857 SourceRange rangeToRemove;
858 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
859 rangeToRemove = attr.getLocalSourceRange();
860 if (attr.getTypePtr()->getImmediateNullability()) {
861 typeArg = attr.getTypePtr()->getModifiedType();
862 S.Diag(attr.getBeginLoc(),
863 diag::err_objc_type_arg_explicit_nullability)
864 << typeArg << FixItHint::CreateRemoval(rangeToRemove);
870 S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified)
871 << typeArg << typeArg.getQualifiers().getAsString()
872 << FixItHint::CreateRemoval(rangeToRemove);
876 // Remove qualifiers even if they're non-local.
877 typeArg = typeArg.getUnqualifiedType();
879 finalTypeArgs.push_back(typeArg);
881 if (typeArg->getAs<PackExpansionType>())
882 anyPackExpansions = true;
884 // Find the corresponding type parameter, if there is one.
885 ObjCTypeParamDecl *typeParam = nullptr;
886 if (!anyPackExpansions) {
887 if (i < numTypeParams) {
888 typeParam = typeParams->begin()[i];
890 // Too many arguments.
891 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
893 << objcClass->getDeclName()
894 << (unsigned)typeArgs.size()
896 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
906 // Objective-C object pointer types must be substitutable for the bounds.
907 if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
908 // If we don't have a type parameter to match against, assume
909 // everything is fine. There was a prior pack expansion that
910 // means we won't be able to match anything.
912 assert(anyPackExpansions && "Too many arguments?");
916 // Retrieve the bound.
917 QualType bound = typeParam->getUnderlyingType();
918 const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
920 // Determine whether the type argument is substitutable for the bound.
921 if (typeArgObjC->isObjCIdType()) {
922 // When the type argument is 'id', the only acceptable type
923 // parameter bound is 'id'.
924 if (boundObjC->isObjCIdType())
926 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
927 // Otherwise, we follow the assignability rules.
931 // Diagnose the mismatch.
932 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
933 diag::err_objc_type_arg_does_not_match_bound)
934 << typeArg << bound << typeParam->getDeclName();
935 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
936 << typeParam->getDeclName();
944 // Block pointer types are permitted for unqualified 'id' bounds.
945 if (typeArg->isBlockPointerType()) {
946 // If we don't have a type parameter to match against, assume
947 // everything is fine. There was a prior pack expansion that
948 // means we won't be able to match anything.
950 assert(anyPackExpansions && "Too many arguments?");
954 // Retrieve the bound.
955 QualType bound = typeParam->getUnderlyingType();
956 if (bound->isBlockCompatibleObjCPointerType(S.Context))
959 // Diagnose the mismatch.
960 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
961 diag::err_objc_type_arg_does_not_match_bound)
962 << typeArg << bound << typeParam->getDeclName();
963 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
964 << typeParam->getDeclName();
972 // Dependent types will be checked at instantiation time.
973 if (typeArg->isDependentType()) {
977 // Diagnose non-id-compatible type arguments.
978 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
979 diag::err_objc_type_arg_not_id_compatible)
980 << typeArg << typeArgInfo->getTypeLoc().getSourceRange();
988 // Make sure we didn't have the wrong number of arguments.
989 if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
990 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
991 << (typeArgs.size() < typeParams->size())
992 << objcClass->getDeclName()
993 << (unsigned)finalTypeArgs.size()
994 << (unsigned)numTypeParams;
995 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
1004 // Success. Form the specialized type.
1005 return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1008 QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1009 SourceLocation ProtocolLAngleLoc,
1010 ArrayRef<ObjCProtocolDecl *> Protocols,
1011 ArrayRef<SourceLocation> ProtocolLocs,
1012 SourceLocation ProtocolRAngleLoc,
1014 QualType Result = QualType(Decl->getTypeForDecl(), 0);
1015 if (!Protocols.empty()) {
1017 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1020 Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1021 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1022 if (FailOnError) Result = QualType();
1024 if (FailOnError && Result.isNull())
1031 QualType Sema::BuildObjCObjectType(QualType BaseType,
1033 SourceLocation TypeArgsLAngleLoc,
1034 ArrayRef<TypeSourceInfo *> TypeArgs,
1035 SourceLocation TypeArgsRAngleLoc,
1036 SourceLocation ProtocolLAngleLoc,
1037 ArrayRef<ObjCProtocolDecl *> Protocols,
1038 ArrayRef<SourceLocation> ProtocolLocs,
1039 SourceLocation ProtocolRAngleLoc,
1041 QualType Result = BaseType;
1042 if (!TypeArgs.empty()) {
1043 Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1044 SourceRange(TypeArgsLAngleLoc,
1047 if (FailOnError && Result.isNull())
1051 if (!Protocols.empty()) {
1053 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1056 Diag(Loc, diag::err_invalid_protocol_qualifiers)
1057 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1058 if (FailOnError) Result = QualType();
1060 if (FailOnError && Result.isNull())
1067 TypeResult Sema::actOnObjCProtocolQualifierType(
1068 SourceLocation lAngleLoc,
1069 ArrayRef<Decl *> protocols,
1070 ArrayRef<SourceLocation> protocolLocs,
1071 SourceLocation rAngleLoc) {
1072 // Form id<protocol-list>.
1073 QualType Result = Context.getObjCObjectType(
1074 Context.ObjCBuiltinIdTy, { },
1076 (ObjCProtocolDecl * const *)protocols.data(),
1079 Result = Context.getObjCObjectPointerType(Result);
1081 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1082 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1084 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1085 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1087 auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1088 .castAs<ObjCObjectTypeLoc>();
1089 ObjCObjectTL.setHasBaseTypeAsWritten(false);
1090 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1092 // No type arguments.
1093 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1094 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1096 // Fill in protocol qualifiers.
1097 ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1098 ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1099 for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1100 ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1102 // We're done. Return the completed type to the parser.
1103 return CreateParsedType(Result, ResultTInfo);
1106 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1109 ParsedType BaseType,
1110 SourceLocation TypeArgsLAngleLoc,
1111 ArrayRef<ParsedType> TypeArgs,
1112 SourceLocation TypeArgsRAngleLoc,
1113 SourceLocation ProtocolLAngleLoc,
1114 ArrayRef<Decl *> Protocols,
1115 ArrayRef<SourceLocation> ProtocolLocs,
1116 SourceLocation ProtocolRAngleLoc) {
1117 TypeSourceInfo *BaseTypeInfo = nullptr;
1118 QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1122 // Handle missing type-source info.
1124 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1126 // Extract type arguments.
1127 SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1128 for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1129 TypeSourceInfo *TypeArgInfo = nullptr;
1130 QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1131 if (TypeArg.isNull()) {
1132 ActualTypeArgInfos.clear();
1136 assert(TypeArgInfo && "No type source info?");
1137 ActualTypeArgInfos.push_back(TypeArgInfo);
1140 // Build the object type.
1141 QualType Result = BuildObjCObjectType(
1142 T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1143 TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1145 llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1147 ProtocolLocs, ProtocolRAngleLoc,
1148 /*FailOnError=*/false);
1153 // Create source information for this type.
1154 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1155 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1157 // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1158 // object pointer type. Fill in source information for it.
1159 if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1160 // The '*' is implicit.
1161 ObjCObjectPointerTL.setStarLoc(SourceLocation());
1162 ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1165 if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1166 // Protocol qualifier information.
1167 if (OTPTL.getNumProtocols() > 0) {
1168 assert(OTPTL.getNumProtocols() == Protocols.size());
1169 OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1170 OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1171 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1172 OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1175 // We're done. Return the completed type to the parser.
1176 return CreateParsedType(Result, ResultTInfo);
1179 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1181 // Type argument information.
1182 if (ObjCObjectTL.getNumTypeArgs() > 0) {
1183 assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1184 ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1185 ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1186 for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1187 ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1189 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1190 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1193 // Protocol qualifier information.
1194 if (ObjCObjectTL.getNumProtocols() > 0) {
1195 assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1196 ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1197 ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1198 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1199 ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1201 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1202 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1206 ObjCObjectTL.setHasBaseTypeAsWritten(true);
1207 if (ObjCObjectTL.getType() == T)
1208 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1210 ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1212 // We're done. Return the completed type to the parser.
1213 return CreateParsedType(Result, ResultTInfo);
1216 static OpenCLAccessAttr::Spelling
1217 getImageAccess(const ParsedAttributesView &Attrs) {
1218 for (const ParsedAttr &AL : Attrs)
1219 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
1220 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
1221 return OpenCLAccessAttr::Keyword_read_only;
1224 /// Convert the specified declspec to the appropriate type
1226 /// \param state Specifies the declarator containing the declaration specifier
1227 /// to be converted, along with other associated processing state.
1228 /// \returns The type described by the declaration specifiers. This function
1229 /// never returns null.
1230 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1231 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1234 Sema &S = state.getSema();
1235 Declarator &declarator = state.getDeclarator();
1236 DeclSpec &DS = declarator.getMutableDeclSpec();
1237 SourceLocation DeclLoc = declarator.getIdentifierLoc();
1238 if (DeclLoc.isInvalid())
1239 DeclLoc = DS.getBeginLoc();
1241 ASTContext &Context = S.Context;
1244 switch (DS.getTypeSpecType()) {
1245 case DeclSpec::TST_void:
1246 Result = Context.VoidTy;
1248 case DeclSpec::TST_char:
1249 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1250 Result = Context.CharTy;
1251 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
1252 Result = Context.SignedCharTy;
1254 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1255 "Unknown TSS value");
1256 Result = Context.UnsignedCharTy;
1259 case DeclSpec::TST_wchar:
1260 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1261 Result = Context.WCharTy;
1262 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
1263 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1264 << DS.getSpecifierName(DS.getTypeSpecType(),
1265 Context.getPrintingPolicy());
1266 Result = Context.getSignedWCharType();
1268 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1269 "Unknown TSS value");
1270 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1271 << DS.getSpecifierName(DS.getTypeSpecType(),
1272 Context.getPrintingPolicy());
1273 Result = Context.getUnsignedWCharType();
1276 case DeclSpec::TST_char8:
1277 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1278 "Unknown TSS value");
1279 Result = Context.Char8Ty;
1281 case DeclSpec::TST_char16:
1282 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1283 "Unknown TSS value");
1284 Result = Context.Char16Ty;
1286 case DeclSpec::TST_char32:
1287 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1288 "Unknown TSS value");
1289 Result = Context.Char32Ty;
1291 case DeclSpec::TST_unspecified:
1292 // If this is a missing declspec in a block literal return context, then it
1293 // is inferred from the return statements inside the block.
1294 // The declspec is always missing in a lambda expr context; it is either
1295 // specified with a trailing return type or inferred.
1296 if (S.getLangOpts().CPlusPlus14 &&
1297 declarator.getContext() == DeclaratorContext::LambdaExprContext) {
1298 // In C++1y, a lambda's implicit return type is 'auto'.
1299 Result = Context.getAutoDeductType();
1301 } else if (declarator.getContext() ==
1302 DeclaratorContext::LambdaExprContext ||
1303 checkOmittedBlockReturnType(S, declarator,
1304 Context.DependentTy)) {
1305 Result = Context.DependentTy;
1309 // Unspecified typespec defaults to int in C90. However, the C90 grammar
1310 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1311 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
1312 // Note that the one exception to this is function definitions, which are
1313 // allowed to be completely missing a declspec. This is handled in the
1314 // parser already though by it pretending to have seen an 'int' in this
1316 if (S.getLangOpts().ImplicitInt) {
1317 // In C89 mode, we only warn if there is a completely missing declspec
1318 // when one is not allowed.
1320 S.Diag(DeclLoc, diag::ext_missing_declspec)
1321 << DS.getSourceRange()
1322 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1324 } else if (!DS.hasTypeSpecifier()) {
1325 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1326 // "At least one type specifier shall be given in the declaration
1327 // specifiers in each declaration, and in the specifier-qualifier list in
1328 // each struct declaration and type name."
1329 if (S.getLangOpts().CPlusPlus) {
1330 S.Diag(DeclLoc, diag::err_missing_type_specifier)
1331 << DS.getSourceRange();
1333 // When this occurs in C++ code, often something is very broken with the
1334 // value being declared, poison it as invalid so we don't get chains of
1336 declarator.setInvalidType(true);
1337 } else if (S.getLangOpts().OpenCLVersion >= 200 && DS.isTypeSpecPipe()){
1338 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1339 << DS.getSourceRange();
1340 declarator.setInvalidType(true);
1342 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1343 << DS.getSourceRange();
1348 case DeclSpec::TST_int: {
1349 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
1350 switch (DS.getTypeSpecWidth()) {
1351 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
1352 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
1353 case DeclSpec::TSW_long: Result = Context.LongTy; break;
1354 case DeclSpec::TSW_longlong:
1355 Result = Context.LongLongTy;
1357 // 'long long' is a C99 or C++11 feature.
1358 if (!S.getLangOpts().C99) {
1359 if (S.getLangOpts().CPlusPlus)
1360 S.Diag(DS.getTypeSpecWidthLoc(),
1361 S.getLangOpts().CPlusPlus11 ?
1362 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1364 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1369 switch (DS.getTypeSpecWidth()) {
1370 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
1371 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
1372 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
1373 case DeclSpec::TSW_longlong:
1374 Result = Context.UnsignedLongLongTy;
1376 // 'long long' is a C99 or C++11 feature.
1377 if (!S.getLangOpts().C99) {
1378 if (S.getLangOpts().CPlusPlus)
1379 S.Diag(DS.getTypeSpecWidthLoc(),
1380 S.getLangOpts().CPlusPlus11 ?
1381 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1383 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1390 case DeclSpec::TST_accum: {
1391 switch (DS.getTypeSpecWidth()) {
1392 case DeclSpec::TSW_short:
1393 Result = Context.ShortAccumTy;
1395 case DeclSpec::TSW_unspecified:
1396 Result = Context.AccumTy;
1398 case DeclSpec::TSW_long:
1399 Result = Context.LongAccumTy;
1401 case DeclSpec::TSW_longlong:
1402 llvm_unreachable("Unable to specify long long as _Accum width");
1405 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1406 Result = Context.getCorrespondingUnsignedType(Result);
1408 if (DS.isTypeSpecSat())
1409 Result = Context.getCorrespondingSaturatedType(Result);
1413 case DeclSpec::TST_fract: {
1414 switch (DS.getTypeSpecWidth()) {
1415 case DeclSpec::TSW_short:
1416 Result = Context.ShortFractTy;
1418 case DeclSpec::TSW_unspecified:
1419 Result = Context.FractTy;
1421 case DeclSpec::TSW_long:
1422 Result = Context.LongFractTy;
1424 case DeclSpec::TSW_longlong:
1425 llvm_unreachable("Unable to specify long long as _Fract width");
1428 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1429 Result = Context.getCorrespondingUnsignedType(Result);
1431 if (DS.isTypeSpecSat())
1432 Result = Context.getCorrespondingSaturatedType(Result);
1436 case DeclSpec::TST_int128:
1437 if (!S.Context.getTargetInfo().hasInt128Type())
1438 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1440 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1441 Result = Context.UnsignedInt128Ty;
1443 Result = Context.Int128Ty;
1445 case DeclSpec::TST_float16:
1446 if (!S.Context.getTargetInfo().hasFloat16Type())
1447 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1449 Result = Context.Float16Ty;
1451 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1452 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1453 case DeclSpec::TST_double:
1454 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
1455 Result = Context.LongDoubleTy;
1457 Result = Context.DoubleTy;
1459 case DeclSpec::TST_float128:
1460 if (!S.Context.getTargetInfo().hasFloat128Type())
1461 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1463 Result = Context.Float128Ty;
1465 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
1467 case DeclSpec::TST_decimal32: // _Decimal32
1468 case DeclSpec::TST_decimal64: // _Decimal64
1469 case DeclSpec::TST_decimal128: // _Decimal128
1470 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1471 Result = Context.IntTy;
1472 declarator.setInvalidType(true);
1474 case DeclSpec::TST_class:
1475 case DeclSpec::TST_enum:
1476 case DeclSpec::TST_union:
1477 case DeclSpec::TST_struct:
1478 case DeclSpec::TST_interface: {
1479 TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1481 // This can happen in C++ with ambiguous lookups.
1482 Result = Context.IntTy;
1483 declarator.setInvalidType(true);
1487 // If the type is deprecated or unavailable, diagnose it.
1488 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1490 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1491 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
1493 // TypeQuals handled by caller.
1494 Result = Context.getTypeDeclType(D);
1496 // In both C and C++, make an ElaboratedType.
1497 ElaboratedTypeKeyword Keyword
1498 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1499 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
1500 DS.isTypeSpecOwned() ? D : nullptr);
1503 case DeclSpec::TST_typename: {
1504 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1505 DS.getTypeSpecSign() == 0 &&
1506 "Can't handle qualifiers on typedef names yet!");
1507 Result = S.GetTypeFromParser(DS.getRepAsType());
1508 if (Result.isNull()) {
1509 declarator.setInvalidType(true);
1512 // TypeQuals handled by caller.
1515 case DeclSpec::TST_typeofType:
1516 // FIXME: Preserve type source info.
1517 Result = S.GetTypeFromParser(DS.getRepAsType());
1518 assert(!Result.isNull() && "Didn't get a type for typeof?");
1519 if (!Result->isDependentType())
1520 if (const TagType *TT = Result->getAs<TagType>())
1521 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1522 // TypeQuals handled by caller.
1523 Result = Context.getTypeOfType(Result);
1525 case DeclSpec::TST_typeofExpr: {
1526 Expr *E = DS.getRepAsExpr();
1527 assert(E && "Didn't get an expression for typeof?");
1528 // TypeQuals handled by caller.
1529 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1530 if (Result.isNull()) {
1531 Result = Context.IntTy;
1532 declarator.setInvalidType(true);
1536 case DeclSpec::TST_decltype: {
1537 Expr *E = DS.getRepAsExpr();
1538 assert(E && "Didn't get an expression for decltype?");
1539 // TypeQuals handled by caller.
1540 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1541 if (Result.isNull()) {
1542 Result = Context.IntTy;
1543 declarator.setInvalidType(true);
1547 case DeclSpec::TST_underlyingType:
1548 Result = S.GetTypeFromParser(DS.getRepAsType());
1549 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1550 Result = S.BuildUnaryTransformType(Result,
1551 UnaryTransformType::EnumUnderlyingType,
1552 DS.getTypeSpecTypeLoc());
1553 if (Result.isNull()) {
1554 Result = Context.IntTy;
1555 declarator.setInvalidType(true);
1559 case DeclSpec::TST_auto:
1560 Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
1563 case DeclSpec::TST_auto_type:
1564 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1567 case DeclSpec::TST_decltype_auto:
1568 Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto,
1569 /*IsDependent*/ false);
1572 case DeclSpec::TST_unknown_anytype:
1573 Result = Context.UnknownAnyTy;
1576 case DeclSpec::TST_atomic:
1577 Result = S.GetTypeFromParser(DS.getRepAsType());
1578 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1579 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1580 if (Result.isNull()) {
1581 Result = Context.IntTy;
1582 declarator.setInvalidType(true);
1586 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
1587 case DeclSpec::TST_##ImgType##_t: \
1588 switch (getImageAccess(DS.getAttributes())) { \
1589 case OpenCLAccessAttr::Keyword_write_only: \
1590 Result = Context.Id##WOTy; \
1592 case OpenCLAccessAttr::Keyword_read_write: \
1593 Result = Context.Id##RWTy; \
1595 case OpenCLAccessAttr::Keyword_read_only: \
1596 Result = Context.Id##ROTy; \
1600 #include "clang/Basic/OpenCLImageTypes.def"
1602 case DeclSpec::TST_error:
1603 Result = Context.IntTy;
1604 declarator.setInvalidType(true);
1608 if (S.getLangOpts().OpenCL &&
1609 S.checkOpenCLDisabledTypeDeclSpec(DS, Result))
1610 declarator.setInvalidType(true);
1612 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1613 DS.getTypeSpecType() == DeclSpec::TST_fract;
1615 // Only fixed point types can be saturated
1616 if (DS.isTypeSpecSat() && !IsFixedPointType)
1617 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1618 << DS.getSpecifierName(DS.getTypeSpecType(),
1619 Context.getPrintingPolicy());
1621 // Handle complex types.
1622 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1623 if (S.getLangOpts().Freestanding)
1624 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1625 Result = Context.getComplexType(Result);
1626 } else if (DS.isTypeAltiVecVector()) {
1627 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1628 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1629 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1630 if (DS.isTypeAltiVecPixel())
1631 VecKind = VectorType::AltiVecPixel;
1632 else if (DS.isTypeAltiVecBool())
1633 VecKind = VectorType::AltiVecBool;
1634 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1637 // FIXME: Imaginary.
1638 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1639 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1641 // Before we process any type attributes, synthesize a block literal
1642 // function declarator if necessary.
1643 if (declarator.getContext() == DeclaratorContext::BlockLiteralContext)
1644 maybeSynthesizeBlockSignature(state, Result);
1646 // Apply any type attributes from the decl spec. This may cause the
1647 // list of type attributes to be temporarily saved while the type
1648 // attributes are pushed around.
1649 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1650 if (!DS.isTypeSpecPipe())
1651 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
1653 // Apply const/volatile/restrict qualifiers to T.
1654 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1655 // Warn about CV qualifiers on function types.
1657 // If the specification of a function type includes any type qualifiers,
1658 // the behavior is undefined.
1659 // C++11 [dcl.fct]p7:
1660 // The effect of a cv-qualifier-seq in a function declarator is not the
1661 // same as adding cv-qualification on top of the function type. In the
1662 // latter case, the cv-qualifiers are ignored.
1663 if (TypeQuals && Result->isFunctionType()) {
1664 diagnoseAndRemoveTypeQualifiers(
1665 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1666 S.getLangOpts().CPlusPlus
1667 ? diag::warn_typecheck_function_qualifiers_ignored
1668 : diag::warn_typecheck_function_qualifiers_unspecified);
1669 // No diagnostic for 'restrict' or '_Atomic' applied to a
1670 // function type; we'll diagnose those later, in BuildQualifiedType.
1673 // C++11 [dcl.ref]p1:
1674 // Cv-qualified references are ill-formed except when the
1675 // cv-qualifiers are introduced through the use of a typedef-name
1676 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1678 // There don't appear to be any other contexts in which a cv-qualified
1679 // reference type could be formed, so the 'ill-formed' clause here appears
1681 if (TypeQuals && Result->isReferenceType()) {
1682 diagnoseAndRemoveTypeQualifiers(
1683 S, DS, TypeQuals, Result,
1684 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1685 diag::warn_typecheck_reference_qualifiers);
1688 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1689 // than once in the same specifier-list or qualifier-list, either directly
1690 // or via one or more typedefs."
1691 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1692 && TypeQuals & Result.getCVRQualifiers()) {
1693 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1694 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1698 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1699 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1703 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1704 // produce a warning in this case.
1707 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1709 // If adding qualifiers fails, just use the unqualified type.
1710 if (Qualified.isNull())
1711 declarator.setInvalidType(true);
1716 assert(!Result.isNull() && "This function should not return a null type");
1720 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1722 return Entity.getAsString();
1727 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1728 Qualifiers Qs, const DeclSpec *DS) {
1732 // Ignore any attempt to form a cv-qualified reference.
1733 if (T->isReferenceType()) {
1735 Qs.removeVolatile();
1738 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1739 // object or incomplete types shall not be restrict-qualified."
1740 if (Qs.hasRestrict()) {
1741 unsigned DiagID = 0;
1744 if (T->isAnyPointerType() || T->isReferenceType() ||
1745 T->isMemberPointerType()) {
1747 if (T->isObjCObjectPointerType())
1749 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1750 EltTy = PTy->getPointeeType();
1752 EltTy = T->getPointeeType();
1754 // If we have a pointer or reference, the pointee must have an object
1756 if (!EltTy->isIncompleteOrObjectType()) {
1757 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1760 } else if (!T->isDependentType()) {
1761 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1766 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1767 Qs.removeRestrict();
1771 return Context.getQualifiedType(T, Qs);
1774 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1775 unsigned CVRAU, const DeclSpec *DS) {
1779 // Ignore any attempt to form a cv-qualified reference.
1780 if (T->isReferenceType())
1782 ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1784 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1786 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1789 // If the same qualifier appears more than once in the same
1790 // specifier-qualifier-list, either directly or via one or more typedefs,
1791 // the behavior is the same as if it appeared only once.
1793 // It's not specified what happens when the _Atomic qualifier is applied to
1794 // a type specified with the _Atomic specifier, but we assume that this
1795 // should be treated as if the _Atomic qualifier appeared multiple times.
1796 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1798 // If other qualifiers appear along with the _Atomic qualifier in a
1799 // specifier-qualifier-list, the resulting type is the so-qualified
1802 // Don't need to worry about array types here, since _Atomic can't be
1803 // applied to such types.
1804 SplitQualType Split = T.getSplitUnqualifiedType();
1805 T = BuildAtomicType(QualType(Split.Ty, 0),
1806 DS ? DS->getAtomicSpecLoc() : Loc);
1809 Split.Quals.addCVRQualifiers(CVR);
1810 return BuildQualifiedType(T, Loc, Split.Quals);
1813 Qualifiers Q = Qualifiers::fromCVRMask(CVR);
1814 Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
1815 return BuildQualifiedType(T, Loc, Q, DS);
1818 /// Build a paren type including \p T.
1819 QualType Sema::BuildParenType(QualType T) {
1820 return Context.getParenType(T);
1823 /// Given that we're building a pointer or reference to the given
1824 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1827 // Bail out if retention is unrequired or already specified.
1828 if (!type->isObjCLifetimeType() ||
1829 type.getObjCLifetime() != Qualifiers::OCL_None)
1832 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1834 // If the object type is const-qualified, we can safely use
1835 // __unsafe_unretained. This is safe (because there are no read
1836 // barriers), and it'll be safe to coerce anything but __weak* to
1837 // the resulting type.
1838 if (type.isConstQualified()) {
1839 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1841 // Otherwise, check whether the static type does not require
1842 // retaining. This currently only triggers for Class (possibly
1843 // protocol-qualifed, and arrays thereof).
1844 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1845 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1847 // If we are in an unevaluated context, like sizeof, skip adding a
1849 } else if (S.isUnevaluatedContext()) {
1852 // If that failed, give an error and recover using __strong. __strong
1853 // is the option most likely to prevent spurious second-order diagnostics,
1854 // like when binding a reference to a field.
1856 // These types can show up in private ivars in system headers, so
1857 // we need this to not be an error in those cases. Instead we
1859 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1860 S.DelayedDiagnostics.add(
1861 sema::DelayedDiagnostic::makeForbiddenType(loc,
1862 diag::err_arc_indirect_no_ownership, type, isReference));
1864 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1866 implicitLifetime = Qualifiers::OCL_Strong;
1868 assert(implicitLifetime && "didn't infer any lifetime!");
1871 qs.addObjCLifetime(implicitLifetime);
1872 return S.Context.getQualifiedType(type, qs);
1875 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1876 std::string Quals = FnTy->getTypeQuals().getAsString();
1878 switch (FnTy->getRefQualifier()) {
1899 /// Kinds of declarator that cannot contain a qualified function type.
1901 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1902 /// a function type with a cv-qualifier or a ref-qualifier can only appear
1903 /// at the topmost level of a type.
1905 /// Parens and member pointers are permitted. We don't diagnose array and
1906 /// function declarators, because they don't allow function types at all.
1908 /// The values of this enum are used in diagnostics.
1909 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1910 } // end anonymous namespace
1912 /// Check whether the type T is a qualified function type, and if it is,
1913 /// diagnose that it cannot be contained within the given kind of declarator.
1914 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
1915 QualifiedFunctionKind QFK) {
1916 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1917 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1918 if (!FPT || (FPT->getTypeQuals().empty() && FPT->getRefQualifier() == RQ_None))
1921 S.Diag(Loc, diag::err_compound_qualified_function_type)
1922 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1923 << getFunctionQualifiersAsString(FPT);
1927 /// Build a pointer type.
1929 /// \param T The type to which we'll be building a pointer.
1931 /// \param Loc The location of the entity whose type involves this
1932 /// pointer type or, if there is no such entity, the location of the
1933 /// type that will have pointer type.
1935 /// \param Entity The name of the entity that involves the pointer
1938 /// \returns A suitable pointer type, if there are no
1939 /// errors. Otherwise, returns a NULL type.
1940 QualType Sema::BuildPointerType(QualType T,
1941 SourceLocation Loc, DeclarationName Entity) {
1942 if (T->isReferenceType()) {
1943 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1944 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1945 << getPrintableNameForEntity(Entity) << T;
1949 if (T->isFunctionType() && getLangOpts().OpenCL) {
1950 Diag(Loc, diag::err_opencl_function_pointer);
1954 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1957 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1959 // In ARC, it is forbidden to build pointers to unqualified pointers.
1960 if (getLangOpts().ObjCAutoRefCount)
1961 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1963 // Build the pointer type.
1964 return Context.getPointerType(T);
1967 /// Build a reference type.
1969 /// \param T The type to which we'll be building a reference.
1971 /// \param Loc The location of the entity whose type involves this
1972 /// reference type or, if there is no such entity, the location of the
1973 /// type that will have reference type.
1975 /// \param Entity The name of the entity that involves the reference
1978 /// \returns A suitable reference type, if there are no
1979 /// errors. Otherwise, returns a NULL type.
1980 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1982 DeclarationName Entity) {
1983 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1984 "Unresolved overloaded function type");
1986 // C++0x [dcl.ref]p6:
1987 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1988 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1989 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1990 // the type "lvalue reference to T", while an attempt to create the type
1991 // "rvalue reference to cv TR" creates the type TR.
1992 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1994 // C++ [dcl.ref]p4: There shall be no references to references.
1996 // According to C++ DR 106, references to references are only
1997 // diagnosed when they are written directly (e.g., "int & &"),
1998 // but not when they happen via a typedef:
2000 // typedef int& intref;
2001 // typedef intref& intref2;
2003 // Parser::ParseDeclaratorInternal diagnoses the case where
2004 // references are written directly; here, we handle the
2005 // collapsing of references-to-references as described in C++0x.
2006 // DR 106 and 540 introduce reference-collapsing into C++98/03.
2009 // A declarator that specifies the type "reference to cv void"
2011 if (T->isVoidType()) {
2012 Diag(Loc, diag::err_reference_to_void);
2016 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2019 // In ARC, it is forbidden to build references to unqualified pointers.
2020 if (getLangOpts().ObjCAutoRefCount)
2021 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2023 // Handle restrict on references.
2025 return Context.getLValueReferenceType(T, SpelledAsLValue);
2026 return Context.getRValueReferenceType(T);
2029 /// Build a Read-only Pipe type.
2031 /// \param T The type to which we'll be building a Pipe.
2033 /// \param Loc We do not use it for now.
2035 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2037 QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
2038 return Context.getReadPipeType(T);
2041 /// Build a Write-only Pipe type.
2043 /// \param T The type to which we'll be building a Pipe.
2045 /// \param Loc We do not use it for now.
2047 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2049 QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
2050 return Context.getWritePipeType(T);
2053 /// Check whether the specified array size makes the array type a VLA. If so,
2054 /// return true, if not, return the size of the array in SizeVal.
2055 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
2056 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2057 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2058 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2060 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
2062 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
2065 void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
2066 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
2070 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
2071 S.LangOpts.GNUMode ||
2072 S.LangOpts.OpenCL).isInvalid();
2075 /// Build an array type.
2077 /// \param T The type of each element in the array.
2079 /// \param ASM C99 array size modifier (e.g., '*', 'static').
2081 /// \param ArraySize Expression describing the size of the array.
2083 /// \param Brackets The range from the opening '[' to the closing ']'.
2085 /// \param Entity The name of the entity that involves the array
2088 /// \returns A suitable array type, if there are no errors. Otherwise,
2089 /// returns a NULL type.
2090 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2091 Expr *ArraySize, unsigned Quals,
2092 SourceRange Brackets, DeclarationName Entity) {
2094 SourceLocation Loc = Brackets.getBegin();
2095 if (getLangOpts().CPlusPlus) {
2096 // C++ [dcl.array]p1:
2097 // T is called the array element type; this type shall not be a reference
2098 // type, the (possibly cv-qualified) type void, a function type or an
2099 // abstract class type.
2101 // C++ [dcl.array]p3:
2102 // When several "array of" specifications are adjacent, [...] only the
2103 // first of the constant expressions that specify the bounds of the arrays
2106 // Note: function types are handled in the common path with C.
2107 if (T->isReferenceType()) {
2108 Diag(Loc, diag::err_illegal_decl_array_of_references)
2109 << getPrintableNameForEntity(Entity) << T;
2113 if (T->isVoidType() || T->isIncompleteArrayType()) {
2114 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
2118 if (RequireNonAbstractType(Brackets.getBegin(), T,
2119 diag::err_array_of_abstract_type))
2122 // Mentioning a member pointer type for an array type causes us to lock in
2123 // an inheritance model, even if it's inside an unused typedef.
2124 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2125 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2126 if (!MPTy->getClass()->isDependentType())
2127 (void)isCompleteType(Loc, T);
2130 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2131 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2132 if (RequireCompleteType(Loc, T,
2133 diag::err_illegal_decl_array_incomplete_type))
2137 if (T->isFunctionType()) {
2138 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2139 << getPrintableNameForEntity(Entity) << T;
2143 if (const RecordType *EltTy = T->getAs<RecordType>()) {
2144 // If the element type is a struct or union that contains a variadic
2145 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2146 if (EltTy->getDecl()->hasFlexibleArrayMember())
2147 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2148 } else if (T->isObjCObjectType()) {
2149 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2153 // Do placeholder conversions on the array size expression.
2154 if (ArraySize && ArraySize->hasPlaceholderType()) {
2155 ExprResult Result = CheckPlaceholderExpr(ArraySize);
2156 if (Result.isInvalid()) return QualType();
2157 ArraySize = Result.get();
2160 // Do lvalue-to-rvalue conversions on the array size expression.
2161 if (ArraySize && !ArraySize->isRValue()) {
2162 ExprResult Result = DefaultLvalueConversion(ArraySize);
2163 if (Result.isInvalid())
2166 ArraySize = Result.get();
2169 // C99 6.7.5.2p1: The size expression shall have integer type.
2170 // C++11 allows contextual conversions to such types.
2171 if (!getLangOpts().CPlusPlus11 &&
2172 ArraySize && !ArraySize->isTypeDependent() &&
2173 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2174 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2175 << ArraySize->getType() << ArraySize->getSourceRange();
2179 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2181 if (ASM == ArrayType::Star)
2182 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2184 T = Context.getIncompleteArrayType(T, ASM, Quals);
2185 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2186 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2187 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
2188 !T->isConstantSizeType()) ||
2189 isArraySizeVLA(*this, ArraySize, ConstVal)) {
2190 // Even in C++11, don't allow contextual conversions in the array bound
2192 if (getLangOpts().CPlusPlus11 &&
2193 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2194 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2195 << ArraySize->getType() << ArraySize->getSourceRange();
2199 // C99: an array with an element type that has a non-constant-size is a VLA.
2200 // C99: an array with a non-ICE size is a VLA. We accept any expression
2201 // that we can fold to a non-zero positive value as an extension.
2202 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2204 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2205 // have a value greater than zero.
2206 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2208 Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2209 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
2211 Diag(ArraySize->getBeginLoc(), diag::err_typecheck_negative_array_size)
2212 << ArraySize->getSourceRange();
2215 if (ConstVal == 0) {
2216 // GCC accepts zero sized static arrays. We allow them when
2217 // we're not in a SFINAE context.
2218 Diag(ArraySize->getBeginLoc(), isSFINAEContext()
2219 ? diag::err_typecheck_zero_array_size
2220 : diag::ext_typecheck_zero_array_size)
2221 << ArraySize->getSourceRange();
2223 if (ASM == ArrayType::Static) {
2224 Diag(ArraySize->getBeginLoc(),
2225 diag::warn_typecheck_zero_static_array_size)
2226 << ArraySize->getSourceRange();
2227 ASM = ArrayType::Normal;
2229 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
2230 !T->isIncompleteType() && !T->isUndeducedType()) {
2231 // Is the array too large?
2232 unsigned ActiveSizeBits
2233 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
2234 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2235 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2236 << ConstVal.toString(10) << ArraySize->getSourceRange();
2241 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
2244 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2245 if (getLangOpts().OpenCL && T->isVariableArrayType()) {
2246 Diag(Loc, diag::err_opencl_vla);
2250 if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) {
2251 if (getLangOpts().CUDA) {
2252 // CUDA device code doesn't support VLAs.
2253 CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget();
2254 } else if (!getLangOpts().OpenMP ||
2255 shouldDiagnoseTargetSupportFromOpenMP()) {
2256 // Some targets don't support VLAs.
2257 Diag(Loc, diag::err_vla_unsupported);
2262 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
2263 if (!getLangOpts().C99) {
2264 if (T->isVariableArrayType()) {
2265 // Prohibit the use of VLAs during template argument deduction.
2266 if (isSFINAEContext()) {
2267 Diag(Loc, diag::err_vla_in_sfinae);
2270 // Just extwarn about VLAs.
2272 Diag(Loc, diag::ext_vla);
2273 } else if (ASM != ArrayType::Normal || Quals != 0)
2275 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
2276 : diag::ext_c99_array_usage) << ASM;
2279 if (T->isVariableArrayType()) {
2280 // Warn about VLAs for -Wvla.
2281 Diag(Loc, diag::warn_vla_used);
2284 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2285 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2286 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2287 if (getLangOpts().OpenCL) {
2288 const QualType ArrType = Context.getBaseElementType(T);
2289 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2290 ArrType->isSamplerT() || ArrType->isImageType()) {
2291 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2299 QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
2300 SourceLocation AttrLoc) {
2301 // The base type must be integer (not Boolean or enumeration) or float, and
2302 // can't already be a vector.
2303 if (!CurType->isDependentType() &&
2304 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2305 (!CurType->isIntegerType() && !CurType->isRealFloatingType()))) {
2306 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2310 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2311 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2312 VectorType::GenericVector);
2314 llvm::APSInt VecSize(32);
2315 if (!SizeExpr->isIntegerConstantExpr(VecSize, Context)) {
2316 Diag(AttrLoc, diag::err_attribute_argument_type)
2317 << "vector_size" << AANT_ArgumentIntegerConstant
2318 << SizeExpr->getSourceRange();
2322 if (CurType->isDependentType())
2323 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2324 VectorType::GenericVector);
2326 unsigned VectorSize = static_cast<unsigned>(VecSize.getZExtValue() * 8);
2327 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2329 if (VectorSize == 0) {
2330 Diag(AttrLoc, diag::err_attribute_zero_size) << SizeExpr->getSourceRange();
2334 // vecSize is specified in bytes - convert to bits.
2335 if (VectorSize % TypeSize) {
2336 Diag(AttrLoc, diag::err_attribute_invalid_size)
2337 << SizeExpr->getSourceRange();
2341 if (VectorType::isVectorSizeTooLarge(VectorSize / TypeSize)) {
2342 Diag(AttrLoc, diag::err_attribute_size_too_large)
2343 << SizeExpr->getSourceRange();
2347 return Context.getVectorType(CurType, VectorSize / TypeSize,
2348 VectorType::GenericVector);
2351 /// Build an ext-vector type.
2353 /// Run the required checks for the extended vector type.
2354 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2355 SourceLocation AttrLoc) {
2356 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2357 // in conjunction with complex types (pointers, arrays, functions, etc.).
2359 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2360 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2361 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2362 // of bool aren't allowed.
2363 if ((!T->isDependentType() && !T->isIntegerType() &&
2364 !T->isRealFloatingType()) ||
2365 T->isBooleanType()) {
2366 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2370 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2371 llvm::APSInt vecSize(32);
2372 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
2373 Diag(AttrLoc, diag::err_attribute_argument_type)
2374 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2375 << ArraySize->getSourceRange();
2379 // Unlike gcc's vector_size attribute, the size is specified as the
2380 // number of elements, not the number of bytes.
2381 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
2383 if (vectorSize == 0) {
2384 Diag(AttrLoc, diag::err_attribute_zero_size)
2385 << ArraySize->getSourceRange();
2389 if (VectorType::isVectorSizeTooLarge(vectorSize)) {
2390 Diag(AttrLoc, diag::err_attribute_size_too_large)
2391 << ArraySize->getSourceRange();
2395 return Context.getExtVectorType(T, vectorSize);
2398 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2401 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2402 if (T->isArrayType() || T->isFunctionType()) {
2403 Diag(Loc, diag::err_func_returning_array_function)
2404 << T->isFunctionType() << T;
2408 // Functions cannot return half FP.
2409 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2410 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2411 FixItHint::CreateInsertion(Loc, "*");
2415 // Methods cannot return interface types. All ObjC objects are
2416 // passed by reference.
2417 if (T->isObjCObjectType()) {
2418 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2419 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2426 /// Check the extended parameter information. Most of the necessary
2427 /// checking should occur when applying the parameter attribute; the
2428 /// only other checks required are positional restrictions.
2429 static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2430 const FunctionProtoType::ExtProtoInfo &EPI,
2431 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2432 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2434 bool hasCheckedSwiftCall = false;
2435 auto checkForSwiftCC = [&](unsigned paramIndex) {
2436 // Only do this once.
2437 if (hasCheckedSwiftCall) return;
2438 hasCheckedSwiftCall = true;
2439 if (EPI.ExtInfo.getCC() == CC_Swift) return;
2440 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2441 << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI());
2444 for (size_t paramIndex = 0, numParams = paramTypes.size();
2445 paramIndex != numParams; ++paramIndex) {
2446 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2447 // Nothing interesting to check for orindary-ABI parameters.
2448 case ParameterABI::Ordinary:
2451 // swift_indirect_result parameters must be a prefix of the function
2453 case ParameterABI::SwiftIndirectResult:
2454 checkForSwiftCC(paramIndex);
2455 if (paramIndex != 0 &&
2456 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2457 != ParameterABI::SwiftIndirectResult) {
2458 S.Diag(getParamLoc(paramIndex),
2459 diag::err_swift_indirect_result_not_first);
2463 case ParameterABI::SwiftContext:
2464 checkForSwiftCC(paramIndex);
2467 // swift_error parameters must be preceded by a swift_context parameter.
2468 case ParameterABI::SwiftErrorResult:
2469 checkForSwiftCC(paramIndex);
2470 if (paramIndex == 0 ||
2471 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2472 ParameterABI::SwiftContext) {
2473 S.Diag(getParamLoc(paramIndex),
2474 diag::err_swift_error_result_not_after_swift_context);
2478 llvm_unreachable("bad ABI kind");
2482 QualType Sema::BuildFunctionType(QualType T,
2483 MutableArrayRef<QualType> ParamTypes,
2484 SourceLocation Loc, DeclarationName Entity,
2485 const FunctionProtoType::ExtProtoInfo &EPI) {
2486 bool Invalid = false;
2488 Invalid |= CheckFunctionReturnType(T, Loc);
2490 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2491 // FIXME: Loc is too inprecise here, should use proper locations for args.
2492 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2493 if (ParamType->isVoidType()) {
2494 Diag(Loc, diag::err_param_with_void_type);
2496 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2497 // Disallow half FP arguments.
2498 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2499 FixItHint::CreateInsertion(Loc, "*");
2503 ParamTypes[Idx] = ParamType;
2506 if (EPI.ExtParameterInfos) {
2507 checkExtParameterInfos(*this, ParamTypes, EPI,
2508 [=](unsigned i) { return Loc; });
2511 if (EPI.ExtInfo.getProducesResult()) {
2512 // This is just a warning, so we can't fail to build if we see it.
2513 checkNSReturnsRetainedReturnType(Loc, T);
2519 return Context.getFunctionType(T, ParamTypes, EPI);
2522 /// Build a member pointer type \c T Class::*.
2524 /// \param T the type to which the member pointer refers.
2525 /// \param Class the class type into which the member pointer points.
2526 /// \param Loc the location where this type begins
2527 /// \param Entity the name of the entity that will have this member pointer type
2529 /// \returns a member pointer type, if successful, or a NULL type if there was
2531 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
2533 DeclarationName Entity) {
2534 // Verify that we're not building a pointer to pointer to function with
2535 // exception specification.
2536 if (CheckDistantExceptionSpec(T)) {
2537 Diag(Loc, diag::err_distant_exception_spec);
2541 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2542 // with reference type, or "cv void."
2543 if (T->isReferenceType()) {
2544 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2545 << getPrintableNameForEntity(Entity) << T;
2549 if (T->isVoidType()) {
2550 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2551 << getPrintableNameForEntity(Entity);
2555 if (!Class->isDependentType() && !Class->isRecordType()) {
2556 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2560 // Adjust the default free function calling convention to the default method
2561 // calling convention.
2563 (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2564 (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2565 if (T->isFunctionType())
2566 adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2568 return Context.getMemberPointerType(T, Class.getTypePtr());
2571 /// Build a block pointer type.
2573 /// \param T The type to which we'll be building a block pointer.
2575 /// \param Loc The source location, used for diagnostics.
2577 /// \param Entity The name of the entity that involves the block pointer
2580 /// \returns A suitable block pointer type, if there are no
2581 /// errors. Otherwise, returns a NULL type.
2582 QualType Sema::BuildBlockPointerType(QualType T,
2584 DeclarationName Entity) {
2585 if (!T->isFunctionType()) {
2586 Diag(Loc, diag::err_nonfunction_block_type);
2590 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2593 return Context.getBlockPointerType(T);
2596 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2597 QualType QT = Ty.get();
2599 if (TInfo) *TInfo = nullptr;
2603 TypeSourceInfo *DI = nullptr;
2604 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2605 QT = LIT->getType();
2606 DI = LIT->getTypeSourceInfo();
2609 if (TInfo) *TInfo = DI;
2613 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2614 Qualifiers::ObjCLifetime ownership,
2615 unsigned chunkIndex);
2617 /// Given that this is the declaration of a parameter under ARC,
2618 /// attempt to infer attributes and such for pointer-to-whatever
2620 static void inferARCWriteback(TypeProcessingState &state,
2621 QualType &declSpecType) {
2622 Sema &S = state.getSema();
2623 Declarator &declarator = state.getDeclarator();
2625 // TODO: should we care about decl qualifiers?
2627 // Check whether the declarator has the expected form. We walk
2628 // from the inside out in order to make the block logic work.
2629 unsigned outermostPointerIndex = 0;
2630 bool isBlockPointer = false;
2631 unsigned numPointers = 0;
2632 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2633 unsigned chunkIndex = i;
2634 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2635 switch (chunk.Kind) {
2636 case DeclaratorChunk::Paren:
2640 case DeclaratorChunk::Reference:
2641 case DeclaratorChunk::Pointer:
2642 // Count the number of pointers. Treat references
2643 // interchangeably as pointers; if they're mis-ordered, normal
2644 // type building will discover that.
2645 outermostPointerIndex = chunkIndex;
2649 case DeclaratorChunk::BlockPointer:
2650 // If we have a pointer to block pointer, that's an acceptable
2651 // indirect reference; anything else is not an application of
2653 if (numPointers != 1) return;
2655 outermostPointerIndex = chunkIndex;
2656 isBlockPointer = true;
2658 // We don't care about pointer structure in return values here.
2661 case DeclaratorChunk::Array: // suppress if written (id[])?
2662 case DeclaratorChunk::Function:
2663 case DeclaratorChunk::MemberPointer:
2664 case DeclaratorChunk::Pipe:
2670 // If we have *one* pointer, then we want to throw the qualifier on
2671 // the declaration-specifiers, which means that it needs to be a
2672 // retainable object type.
2673 if (numPointers == 1) {
2674 // If it's not a retainable object type, the rule doesn't apply.
2675 if (!declSpecType->isObjCRetainableType()) return;
2677 // If it already has lifetime, don't do anything.
2678 if (declSpecType.getObjCLifetime()) return;
2680 // Otherwise, modify the type in-place.
2683 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2684 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
2686 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
2687 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2689 // If we have *two* pointers, then we want to throw the qualifier on
2690 // the outermost pointer.
2691 } else if (numPointers == 2) {
2692 // If we don't have a block pointer, we need to check whether the
2693 // declaration-specifiers gave us something that will turn into a
2694 // retainable object pointer after we slap the first pointer on it.
2695 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2698 // Look for an explicit lifetime attribute there.
2699 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2700 if (chunk.Kind != DeclaratorChunk::Pointer &&
2701 chunk.Kind != DeclaratorChunk::BlockPointer)
2703 for (const ParsedAttr &AL : chunk.getAttrs())
2704 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
2707 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
2708 outermostPointerIndex);
2710 // Any other number of pointers/references does not trigger the rule.
2713 // TODO: mark whether we did this inference?
2716 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2717 SourceLocation FallbackLoc,
2718 SourceLocation ConstQualLoc,
2719 SourceLocation VolatileQualLoc,
2720 SourceLocation RestrictQualLoc,
2721 SourceLocation AtomicQualLoc,
2722 SourceLocation UnalignedQualLoc) {
2730 } const QualKinds[5] = {
2731 { "const", DeclSpec::TQ_const, ConstQualLoc },
2732 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2733 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2734 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2735 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2738 SmallString<32> QualStr;
2739 unsigned NumQuals = 0;
2741 FixItHint FixIts[5];
2743 // Build a string naming the redundant qualifiers.
2744 for (auto &E : QualKinds) {
2745 if (Quals & E.Mask) {
2746 if (!QualStr.empty()) QualStr += ' ';
2749 // If we have a location for the qualifier, offer a fixit.
2750 SourceLocation QualLoc = E.Loc;
2751 if (QualLoc.isValid()) {
2752 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2753 if (Loc.isInvalid() ||
2754 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2762 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2763 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2766 // Diagnose pointless type qualifiers on the return type of a function.
2767 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
2769 unsigned FunctionChunkIndex) {
2770 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2771 // FIXME: TypeSourceInfo doesn't preserve location information for
2773 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2774 RetTy.getLocalCVRQualifiers(),
2775 D.getIdentifierLoc());
2779 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2780 End = D.getNumTypeObjects();
2781 OuterChunkIndex != End; ++OuterChunkIndex) {
2782 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2783 switch (OuterChunk.Kind) {
2784 case DeclaratorChunk::Paren:
2787 case DeclaratorChunk::Pointer: {
2788 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2789 S.diagnoseIgnoredQualifiers(
2790 diag::warn_qual_return_type,
2793 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2794 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2795 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2796 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc),
2797 SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc));
2801 case DeclaratorChunk::Function:
2802 case DeclaratorChunk::BlockPointer:
2803 case DeclaratorChunk::Reference:
2804 case DeclaratorChunk::Array:
2805 case DeclaratorChunk::MemberPointer:
2806 case DeclaratorChunk::Pipe:
2807 // FIXME: We can't currently provide an accurate source location and a
2808 // fix-it hint for these.
2809 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2810 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2811 RetTy.getCVRQualifiers() | AtomicQual,
2812 D.getIdentifierLoc());
2816 llvm_unreachable("unknown declarator chunk kind");
2819 // If the qualifiers come from a conversion function type, don't diagnose
2820 // them -- they're not necessarily redundant, since such a conversion
2821 // operator can be explicitly called as "x.operator const int()".
2822 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
2825 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2826 // which are present there.
2827 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2828 D.getDeclSpec().getTypeQualifiers(),
2829 D.getIdentifierLoc(),
2830 D.getDeclSpec().getConstSpecLoc(),
2831 D.getDeclSpec().getVolatileSpecLoc(),
2832 D.getDeclSpec().getRestrictSpecLoc(),
2833 D.getDeclSpec().getAtomicSpecLoc(),
2834 D.getDeclSpec().getUnalignedSpecLoc());
2837 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2838 TypeSourceInfo *&ReturnTypeInfo) {
2839 Sema &SemaRef = state.getSema();
2840 Declarator &D = state.getDeclarator();
2842 ReturnTypeInfo = nullptr;
2844 // The TagDecl owned by the DeclSpec.
2845 TagDecl *OwnedTagDecl = nullptr;
2847 switch (D.getName().getKind()) {
2848 case UnqualifiedIdKind::IK_ImplicitSelfParam:
2849 case UnqualifiedIdKind::IK_OperatorFunctionId:
2850 case UnqualifiedIdKind::IK_Identifier:
2851 case UnqualifiedIdKind::IK_LiteralOperatorId:
2852 case UnqualifiedIdKind::IK_TemplateId:
2853 T = ConvertDeclSpecToType(state);
2855 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2856 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2857 // Owned declaration is embedded in declarator.
2858 OwnedTagDecl->setEmbeddedInDeclarator(true);
2862 case UnqualifiedIdKind::IK_ConstructorName:
2863 case UnqualifiedIdKind::IK_ConstructorTemplateId:
2864 case UnqualifiedIdKind::IK_DestructorName:
2865 // Constructors and destructors don't have return types. Use
2867 T = SemaRef.Context.VoidTy;
2868 processTypeAttrs(state, T, TAL_DeclSpec,
2869 D.getMutableDeclSpec().getAttributes());
2872 case UnqualifiedIdKind::IK_DeductionGuideName:
2873 // Deduction guides have a trailing return type and no type in their
2874 // decl-specifier sequence. Use a placeholder return type for now.
2875 T = SemaRef.Context.DependentTy;
2878 case UnqualifiedIdKind::IK_ConversionFunctionId:
2879 // The result type of a conversion function is the type that it
2881 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2886 if (!D.getAttributes().empty())
2887 distributeTypeAttrsFromDeclarator(state, T);
2889 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2890 if (DeducedType *Deduced = T->getContainedDeducedType()) {
2891 AutoType *Auto = dyn_cast<AutoType>(Deduced);
2894 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
2895 // class template argument deduction)?
2896 bool IsCXXAutoType =
2897 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
2898 bool IsDeducedReturnType = false;
2900 switch (D.getContext()) {
2901 case DeclaratorContext::LambdaExprContext:
2902 // Declared return type of a lambda-declarator is implicit and is always
2905 case DeclaratorContext::ObjCParameterContext:
2906 case DeclaratorContext::ObjCResultContext:
2907 case DeclaratorContext::PrototypeContext:
2910 case DeclaratorContext::LambdaExprParameterContext:
2911 // In C++14, generic lambdas allow 'auto' in their parameters.
2912 if (!SemaRef.getLangOpts().CPlusPlus14 ||
2913 !Auto || Auto->getKeyword() != AutoTypeKeyword::Auto)
2916 // If auto is mentioned in a lambda parameter context, convert it to a
2917 // template parameter type.
2918 sema::LambdaScopeInfo *LSI = SemaRef.getCurLambda();
2919 assert(LSI && "No LambdaScopeInfo on the stack!");
2920 const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
2921 const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
2922 const bool IsParameterPack = D.hasEllipsis();
2924 // Create the TemplateTypeParmDecl here to retrieve the corresponding
2925 // template parameter type. Template parameters are temporarily added
2926 // to the TU until the associated TemplateDecl is created.
2927 TemplateTypeParmDecl *CorrespondingTemplateParam =
2928 TemplateTypeParmDecl::Create(
2929 SemaRef.Context, SemaRef.Context.getTranslationUnitDecl(),
2930 /*KeyLoc*/ SourceLocation(), /*NameLoc*/ D.getBeginLoc(),
2931 TemplateParameterDepth, AutoParameterPosition,
2932 /*Identifier*/ nullptr, false, IsParameterPack);
2933 LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
2934 // Replace the 'auto' in the function parameter with this invented
2935 // template type parameter.
2936 // FIXME: Retain some type sugar to indicate that this was written
2938 T = SemaRef.ReplaceAutoType(
2939 T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0));
2942 case DeclaratorContext::MemberContext: {
2943 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
2944 D.isFunctionDeclarator())
2946 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
2947 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2948 case TTK_Enum: llvm_unreachable("unhandled tag kind");
2949 case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
2950 case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
2951 case TTK_Class: Error = 5; /* Class member */ break;
2952 case TTK_Interface: Error = 6; /* Interface member */ break;
2954 if (D.getDeclSpec().isFriendSpecified())
2955 Error = 20; // Friend type
2958 case DeclaratorContext::CXXCatchContext:
2959 case DeclaratorContext::ObjCCatchContext:
2960 Error = 7; // Exception declaration
2962 case DeclaratorContext::TemplateParamContext:
2963 if (isa<DeducedTemplateSpecializationType>(Deduced))
2964 Error = 19; // Template parameter
2965 else if (!SemaRef.getLangOpts().CPlusPlus17)
2966 Error = 8; // Template parameter (until C++17)
2968 case DeclaratorContext::BlockLiteralContext:
2969 Error = 9; // Block literal
2971 case DeclaratorContext::TemplateArgContext:
2972 // Within a template argument list, a deduced template specialization
2973 // type will be reinterpreted as a template template argument.
2974 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
2975 !D.getNumTypeObjects() &&
2976 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier)
2979 case DeclaratorContext::TemplateTypeArgContext:
2980 Error = 10; // Template type argument
2982 case DeclaratorContext::AliasDeclContext:
2983 case DeclaratorContext::AliasTemplateContext:
2984 Error = 12; // Type alias
2986 case DeclaratorContext::TrailingReturnContext:
2987 case DeclaratorContext::TrailingReturnVarContext:
2988 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
2989 Error = 13; // Function return type
2990 IsDeducedReturnType = true;
2992 case DeclaratorContext::ConversionIdContext:
2993 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
2994 Error = 14; // conversion-type-id
2995 IsDeducedReturnType = true;
2997 case DeclaratorContext::FunctionalCastContext:
2998 if (isa<DeducedTemplateSpecializationType>(Deduced))
3001 case DeclaratorContext::TypeNameContext:
3002 Error = 15; // Generic
3004 case DeclaratorContext::FileContext:
3005 case DeclaratorContext::BlockContext:
3006 case DeclaratorContext::ForContext:
3007 case DeclaratorContext::InitStmtContext:
3008 case DeclaratorContext::ConditionContext:
3009 // FIXME: P0091R3 (erroneously) does not permit class template argument
3010 // deduction in conditions, for-init-statements, and other declarations
3011 // that are not simple-declarations.
3013 case DeclaratorContext::CXXNewContext:
3014 // FIXME: P0091R3 does not permit class template argument deduction here,
3015 // but we follow GCC and allow it anyway.
3016 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3017 Error = 17; // 'new' type
3019 case DeclaratorContext::KNRTypeListContext:
3020 Error = 18; // K&R function parameter
3024 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3027 // In Objective-C it is an error to use 'auto' on a function declarator
3028 // (and everywhere for '__auto_type').
3029 if (D.isFunctionDeclarator() &&
3030 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3033 bool HaveTrailing = false;
3035 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
3036 // contains a trailing return type. That is only legal at the outermost
3037 // level. Check all declarator chunks (outermost first) anyway, to give
3038 // better diagnostics.
3039 // We don't support '__auto_type' with trailing return types.
3040 // FIXME: Should we only do this for 'auto' and not 'decltype(auto)'?
3041 if (SemaRef.getLangOpts().CPlusPlus11 && IsCXXAutoType &&
3042 D.hasTrailingReturnType()) {
3043 HaveTrailing = true;
3047 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3048 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3049 AutoRange = D.getName().getSourceRange();
3054 switch (Auto->getKeyword()) {
3055 case AutoTypeKeyword::Auto: Kind = 0; break;
3056 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3057 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3060 assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3061 "unknown auto type");
3065 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3066 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3068 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3069 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3070 << QualType(Deduced, 0) << AutoRange;
3071 if (auto *TD = TN.getAsTemplateDecl())
3072 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
3074 T = SemaRef.Context.IntTy;
3075 D.setInvalidType(true);
3076 } else if (!HaveTrailing &&
3077 D.getContext() != DeclaratorContext::LambdaExprContext) {
3078 // If there was a trailing return type, we already got
3079 // warn_cxx98_compat_trailing_return_type in the parser.
3080 SemaRef.Diag(AutoRange.getBegin(),
3082 DeclaratorContext::LambdaExprParameterContext
3083 ? diag::warn_cxx11_compat_generic_lambda
3084 : IsDeducedReturnType
3085 ? diag::warn_cxx11_compat_deduced_return_type
3086 : diag::warn_cxx98_compat_auto_type_specifier)
3091 if (SemaRef.getLangOpts().CPlusPlus &&
3092 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3093 // Check the contexts where C++ forbids the declaration of a new class
3094 // or enumeration in a type-specifier-seq.
3095 unsigned DiagID = 0;
3096 switch (D.getContext()) {
3097 case DeclaratorContext::TrailingReturnContext:
3098 case DeclaratorContext::TrailingReturnVarContext:
3099 // Class and enumeration definitions are syntactically not allowed in
3100 // trailing return types.
3101 llvm_unreachable("parser should not have allowed this");
3103 case DeclaratorContext::FileContext:
3104 case DeclaratorContext::MemberContext:
3105 case DeclaratorContext::BlockContext:
3106 case DeclaratorContext::ForContext:
3107 case DeclaratorContext::InitStmtContext:
3108 case DeclaratorContext::BlockLiteralContext:
3109 case DeclaratorContext::LambdaExprContext:
3110 // C++11 [dcl.type]p3:
3111 // A type-specifier-seq shall not define a class or enumeration unless
3112 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3113 // the declaration of a template-declaration.
3114 case DeclaratorContext::AliasDeclContext:
3116 case DeclaratorContext::AliasTemplateContext:
3117 DiagID = diag::err_type_defined_in_alias_template;
3119 case DeclaratorContext::TypeNameContext:
3120 case DeclaratorContext::FunctionalCastContext:
3121 case DeclaratorContext::ConversionIdContext:
3122 case DeclaratorContext::TemplateParamContext:
3123 case DeclaratorContext::CXXNewContext:
3124 case DeclaratorContext::CXXCatchContext:
3125 case DeclaratorContext::ObjCCatchContext:
3126 case DeclaratorContext::TemplateArgContext:
3127 case DeclaratorContext::TemplateTypeArgContext:
3128 DiagID = diag::err_type_defined_in_type_specifier;
3130 case DeclaratorContext::PrototypeContext:
3131 case DeclaratorContext::LambdaExprParameterContext:
3132 case DeclaratorContext::ObjCParameterContext:
3133 case DeclaratorContext::ObjCResultContext:
3134 case DeclaratorContext::KNRTypeListContext:
3136 // Types shall not be defined in return or parameter types.
3137 DiagID = diag::err_type_defined_in_param_type;
3139 case DeclaratorContext::ConditionContext:
3141 // The type-specifier-seq shall not contain typedef and shall not declare
3142 // a new class or enumeration.
3143 DiagID = diag::err_type_defined_in_condition;
3148 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3149 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3150 D.setInvalidType(true);
3154 assert(!T.isNull() && "This function should not return a null type");
3158 /// Produce an appropriate diagnostic for an ambiguity between a function
3159 /// declarator and a C++ direct-initializer.
3160 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3161 DeclaratorChunk &DeclType, QualType RT) {
3162 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3163 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3165 // If the return type is void there is no ambiguity.
3166 if (RT->isVoidType())
3169 // An initializer for a non-class type can have at most one argument.
3170 if (!RT->isRecordType() && FTI.NumParams > 1)
3173 // An initializer for a reference must have exactly one argument.
3174 if (RT->isReferenceType() && FTI.NumParams != 1)
3177 // Only warn if this declarator is declaring a function at block scope, and
3178 // doesn't have a storage class (such as 'extern') specified.
3179 if (!D.isFunctionDeclarator() ||
3180 D.getFunctionDefinitionKind() != FDK_Declaration ||
3181 !S.CurContext->isFunctionOrMethod() ||
3182 D.getDeclSpec().getStorageClassSpec()
3183 != DeclSpec::SCS_unspecified)
3186 // Inside a condition, a direct initializer is not permitted. We allow one to
3187 // be parsed in order to give better diagnostics in condition parsing.
3188 if (D.getContext() == DeclaratorContext::ConditionContext)
3191 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3193 S.Diag(DeclType.Loc,
3194 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3195 : diag::warn_empty_parens_are_function_decl)
3198 // If the declaration looks like:
3201 // and name lookup finds a function named 'f', then the ',' was
3202 // probably intended to be a ';'.
3203 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3204 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3205 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3206 if (Comma.getFileID() != Name.getFileID() ||
3207 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3208 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3209 Sema::LookupOrdinaryName);
3210 if (S.LookupName(Result, S.getCurScope()))
3211 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3212 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3213 << D.getIdentifier();
3214 Result.suppressDiagnostics();
3218 if (FTI.NumParams > 0) {
3219 // For a declaration with parameters, eg. "T var(T());", suggest adding
3220 // parens around the first parameter to turn the declaration into a
3221 // variable declaration.
3222 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3223 SourceLocation B = Range.getBegin();
3224 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3225 // FIXME: Maybe we should suggest adding braces instead of parens
3226 // in C++11 for classes that don't have an initializer_list constructor.
3227 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3228 << FixItHint::CreateInsertion(B, "(")
3229 << FixItHint::CreateInsertion(E, ")");
3231 // For a declaration without parameters, eg. "T var();", suggest replacing
3232 // the parens with an initializer to turn the declaration into a variable
3234 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3236 // Empty parens mean value-initialization, and no parens mean
3237 // default initialization. These are equivalent if the default
3238 // constructor is user-provided or if zero-initialization is a
3240 if (RD && RD->hasDefinition() &&
3241 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3242 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3243 << FixItHint::CreateRemoval(ParenRange);
3246 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3247 if (Init.empty() && S.LangOpts.CPlusPlus11)
3250 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3251 << FixItHint::CreateReplacement(ParenRange, Init);
3256 /// Produce an appropriate diagnostic for a declarator with top-level
3258 static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
3259 DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
3260 assert(Paren.Kind == DeclaratorChunk::Paren &&
3261 "do not have redundant top-level parentheses");
3263 // This is a syntactic check; we're not interested in cases that arise
3264 // during template instantiation.
3265 if (S.inTemplateInstantiation())
3268 // Check whether this could be intended to be a construction of a temporary
3269 // object in C++ via a function-style cast.
3270 bool CouldBeTemporaryObject =
3271 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3272 !D.isInvalidType() && D.getIdentifier() &&
3273 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3274 (T->isRecordType() || T->isDependentType()) &&
3275 D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator();
3277 bool StartsWithDeclaratorId = true;
3278 for (auto &C : D.type_objects()) {
3280 case DeclaratorChunk::Paren:
3284 case DeclaratorChunk::Pointer:
3285 StartsWithDeclaratorId = false;
3288 case DeclaratorChunk::Array:
3290 CouldBeTemporaryObject = false;
3293 case DeclaratorChunk::Reference:
3294 // FIXME: Suppress the warning here if there is no initializer; we're
3295 // going to give an error anyway.
3296 // We assume that something like 'T (&x) = y;' is highly likely to not
3297 // be intended to be a temporary object.
3298 CouldBeTemporaryObject = false;
3299 StartsWithDeclaratorId = false;
3302 case DeclaratorChunk::Function:
3303 // In a new-type-id, function chunks require parentheses.
3304 if (D.getContext() == DeclaratorContext::CXXNewContext)
3306 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3307 // redundant-parens warning, but we don't know whether the function
3308 // chunk was syntactically valid as an expression here.
3309 CouldBeTemporaryObject = false;
3312 case DeclaratorChunk::BlockPointer:
3313 case DeclaratorChunk::MemberPointer:
3314 case DeclaratorChunk::Pipe:
3315 // These cannot appear in expressions.
3316 CouldBeTemporaryObject = false;
3317 StartsWithDeclaratorId = false;
3322 // FIXME: If there is an initializer, assume that this is not intended to be
3323 // a construction of a temporary object.
3325 // Check whether the name has already been declared; if not, this is not a
3326 // function-style cast.
3327 if (CouldBeTemporaryObject) {
3328 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3329 Sema::LookupOrdinaryName);
3330 if (!S.LookupName(Result, S.getCurScope()))
3331 CouldBeTemporaryObject = false;
3332 Result.suppressDiagnostics();
3335 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3337 if (!CouldBeTemporaryObject) {
3338 // If we have A (::B), the parentheses affect the meaning of the program.
3339 // Suppress the warning in that case. Don't bother looking at the DeclSpec
3340 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3341 // formally unambiguous.
3342 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3343 for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
3344 NNS = NNS->getPrefix()) {
3345 if (NNS->getKind() == NestedNameSpecifier::Global)
3350 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3351 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3352 << FixItHint::CreateRemoval(Paren.EndLoc);
3356 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3357 << ParenRange << D.getIdentifier();
3358 auto *RD = T->getAsCXXRecordDecl();
3359 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3360 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3361 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3362 << D.getIdentifier();
3363 // FIXME: A cast to void is probably a better suggestion in cases where it's
3364 // valid (when there is no initializer and we're not in a condition).
3365 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3366 << FixItHint::CreateInsertion(D.getBeginLoc(), "(")
3367 << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")");
3368 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3369 << FixItHint::CreateRemoval(Paren.Loc)
3370 << FixItHint::CreateRemoval(Paren.EndLoc);
3373 /// Helper for figuring out the default CC for a function declarator type. If
3374 /// this is the outermost chunk, then we can determine the CC from the
3375 /// declarator context. If not, then this could be either a member function
3376 /// type or normal function type.
3377 static CallingConv getCCForDeclaratorChunk(
3378 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3379 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3380 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3382 // Check for an explicit CC attribute.
3383 for (const ParsedAttr &AL : AttrList) {
3384 switch (AL.getKind()) {
3385 CALLING_CONV_ATTRS_CASELIST : {
3386 // Ignore attributes that don't validate or can't apply to the
3387 // function type. We'll diagnose the failure to apply them in
3388 // handleFunctionTypeAttr.
3390 if (!S.CheckCallingConvAttr(AL, CC) &&
3391 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3402 bool IsCXXInstanceMethod = false;
3404 if (S.getLangOpts().CPlusPlus) {
3405 // Look inwards through parentheses to see if this chunk will form a
3406 // member pointer type or if we're the declarator. Any type attributes
3407 // between here and there will override the CC we choose here.
3408 unsigned I = ChunkIndex;
3409 bool FoundNonParen = false;
3410 while (I && !FoundNonParen) {
3412 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
3413 FoundNonParen = true;
3416 if (FoundNonParen) {
3417 // If we're not the declarator, we're a regular function type unless we're
3418 // in a member pointer.
3419 IsCXXInstanceMethod =
3420 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
3421 } else if (D.getContext() == DeclaratorContext::LambdaExprContext) {
3422 // This can only be a call operator for a lambda, which is an instance
3424 IsCXXInstanceMethod = true;
3426 // We're the innermost decl chunk, so must be a function declarator.
3427 assert(D.isFunctionDeclarator());
3429 // If we're inside a record, we're declaring a method, but it could be
3430 // explicitly or implicitly static.
3431 IsCXXInstanceMethod =
3432 D.isFirstDeclarationOfMember() &&
3433 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
3434 !D.isStaticMember();
3438 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
3439 IsCXXInstanceMethod);
3441 // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3442 // and AMDGPU targets, hence it cannot be treated as a calling
3443 // convention attribute. This is the simplest place to infer
3444 // calling convention for OpenCL kernels.
3445 if (S.getLangOpts().OpenCL) {
3446 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3447 if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
3448 CC = CC_OpenCLKernel;
3458 /// A simple notion of pointer kinds, which matches up with the various
3459 /// pointer declarators.
3460 enum class SimplePointerKind {
3466 } // end anonymous namespace
3468 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
3469 switch (nullability) {
3470 case NullabilityKind::NonNull:
3471 if (!Ident__Nonnull)
3472 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3473 return Ident__Nonnull;
3475 case NullabilityKind::Nullable:
3476 if (!Ident__Nullable)
3477 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3478 return Ident__Nullable;
3480 case NullabilityKind::Unspecified:
3481 if (!Ident__Null_unspecified)
3482 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3483 return Ident__Null_unspecified;
3485 llvm_unreachable("Unknown nullability kind.");
3488 /// Retrieve the identifier "NSError".
3489 IdentifierInfo *Sema::getNSErrorIdent() {
3491 Ident_NSError = PP.getIdentifierInfo("NSError");
3493 return Ident_NSError;
3496 /// Check whether there is a nullability attribute of any kind in the given
3498 static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
3499 for (const ParsedAttr &AL : attrs) {
3500 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
3501 AL.getKind() == ParsedAttr::AT_TypeNullable ||
3502 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
3510 /// Describes the kind of a pointer a declarator describes.
3511 enum class PointerDeclaratorKind {
3514 // Single-level pointer.
3516 // Multi-level pointer (of any pointer kind).
3519 MaybePointerToCFRef,
3523 NSErrorPointerPointer,
3526 /// Describes a declarator chunk wrapping a pointer that marks inference as
3528 // These values must be kept in sync with diagnostics.
3529 enum class PointerWrappingDeclaratorKind {
3530 /// Pointer is top-level.
3532 /// Pointer is an array element.
3534 /// Pointer is the referent type of a C++ reference.
3537 } // end anonymous namespace
3539 /// Classify the given declarator, whose type-specified is \c type, based on
3540 /// what kind of pointer it refers to.
3542 /// This is used to determine the default nullability.
3543 static PointerDeclaratorKind
3544 classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
3545 PointerWrappingDeclaratorKind &wrappingKind) {
3546 unsigned numNormalPointers = 0;
3548 // For any dependent type, we consider it a non-pointer.
3549 if (type->isDependentType())
3550 return PointerDeclaratorKind::NonPointer;
3552 // Look through the declarator chunks to identify pointers.
3553 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3554 DeclaratorChunk &chunk = declarator.getTypeObject(i);
3555 switch (chunk.Kind) {
3556 case DeclaratorChunk::Array:
3557 if (numNormalPointers == 0)
3558 wrappingKind = PointerWrappingDeclaratorKind::Array;
3561 case DeclaratorChunk::Function:
3562 case DeclaratorChunk::Pipe:
3565 case DeclaratorChunk::BlockPointer:
3566 case DeclaratorChunk::MemberPointer:
3567 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3568 : PointerDeclaratorKind::SingleLevelPointer;
3570 case DeclaratorChunk::Paren:
3573 case DeclaratorChunk::Reference:
3574 if (numNormalPointers == 0)
3575 wrappingKind = PointerWrappingDeclaratorKind::Reference;
3578 case DeclaratorChunk::Pointer:
3579 ++numNormalPointers;
3580 if (numNormalPointers > 2)
3581 return PointerDeclaratorKind::MultiLevelPointer;
3586 // Then, dig into the type specifier itself.
3587 unsigned numTypeSpecifierPointers = 0;
3589 // Decompose normal pointers.
3590 if (auto ptrType = type->getAs<PointerType>()) {
3591 ++numNormalPointers;
3593 if (numNormalPointers > 2)
3594 return PointerDeclaratorKind::MultiLevelPointer;
3596 type = ptrType->getPointeeType();
3597 ++numTypeSpecifierPointers;
3601 // Decompose block pointers.
3602 if (type->getAs<BlockPointerType>()) {
3603 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3604 : PointerDeclaratorKind::SingleLevelPointer;
3607 // Decompose member pointers.
3608 if (type->getAs<MemberPointerType>()) {
3609 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3610 : PointerDeclaratorKind::SingleLevelPointer;
3613 // Look at Objective-C object pointers.
3614 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3615 ++numNormalPointers;
3616 ++numTypeSpecifierPointers;
3618 // If this is NSError**, report that.
3619 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3620 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
3621 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3622 return PointerDeclaratorKind::NSErrorPointerPointer;
3629 // Look at Objective-C class types.
3630 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3631 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
3632 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3633 return PointerDeclaratorKind::NSErrorPointerPointer;
3639 // If at this point we haven't seen a pointer, we won't see one.
3640 if (numNormalPointers == 0)
3641 return PointerDeclaratorKind::NonPointer;
3643 if (auto recordType = type->getAs<RecordType>()) {
3644 RecordDecl *recordDecl = recordType->getDecl();
3646 bool isCFError = false;
3648 // If we already know about CFError, test it directly.
3649 isCFError = (S.CFError == recordDecl);
3651 // Check whether this is CFError, which we identify based on its bridge
3652 // to NSError. CFErrorRef used to be declared with "objc_bridge" but is
3653 // now declared with "objc_bridge_mutable", so look for either one of
3654 // the two attributes.
3655 if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
3656 IdentifierInfo *bridgedType = nullptr;
3657 if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>())
3658 bridgedType = bridgeAttr->getBridgedType();
3659 else if (auto bridgeAttr =
3660 recordDecl->getAttr<ObjCBridgeMutableAttr>())
3661 bridgedType = bridgeAttr->getBridgedType();
3663 if (bridgedType == S.getNSErrorIdent()) {
3664 S.CFError = recordDecl;
3670 // If this is CFErrorRef*, report it as such.
3671 if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3672 return PointerDeclaratorKind::CFErrorRefPointer;
3680 switch (numNormalPointers) {
3682 return PointerDeclaratorKind::NonPointer;
3685 return PointerDeclaratorKind::SingleLevelPointer;
3688 return PointerDeclaratorKind::MaybePointerToCFRef;
3691 return PointerDeclaratorKind::MultiLevelPointer;
3695 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
3696 SourceLocation loc) {
3697 // If we're anywhere in a function, method, or closure context, don't perform
3698 // completeness checks.
3699 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
3700 if (ctx->isFunctionOrMethod())
3703 if (ctx->isFileContext())
3707 // We only care about the expansion location.
3708 loc = S.SourceMgr.getExpansionLoc(loc);
3709 FileID file = S.SourceMgr.getFileID(loc);
3710 if (file.isInvalid())
3713 // Retrieve file information.
3714 bool invalid = false;
3715 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
3716 if (invalid || !sloc.isFile())
3719 // We don't want to perform completeness checks on the main file or in
3721 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
3722 if (fileInfo.getIncludeLoc().isInvalid())
3724 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
3725 S.Diags.getSuppressSystemWarnings()) {
3732 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
3733 /// taking into account whitespace before and after.
3734 static void fixItNullability(Sema &S, DiagnosticBuilder &Diag,
3735 SourceLocation PointerLoc,
3736 NullabilityKind Nullability) {
3737 assert(PointerLoc.isValid());
3738 if (PointerLoc.isMacroID())
3741 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
3742 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
3745 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
3749 SmallString<32> InsertionTextBuf{" "};
3750 InsertionTextBuf += getNullabilitySpelling(Nullability);
3751 InsertionTextBuf += " ";
3752 StringRef InsertionText = InsertionTextBuf.str();
3754 if (isWhitespace(*NextChar)) {
3755 InsertionText = InsertionText.drop_back();
3756 } else if (NextChar[-1] == '[') {
3757 if (NextChar[0] == ']')
3758 InsertionText = InsertionText.drop_back().drop_front();
3760 InsertionText = InsertionText.drop_front();
3761 } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) &&
3762 !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) {
3763 InsertionText = InsertionText.drop_back().drop_front();
3766 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
3769 static void emitNullabilityConsistencyWarning(Sema &S,
3770 SimplePointerKind PointerKind,
3771 SourceLocation PointerLoc,
3772 SourceLocation PointerEndLoc) {
3773 assert(PointerLoc.isValid());
3775 if (PointerKind == SimplePointerKind::Array) {
3776 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
3778 S.Diag(PointerLoc, diag::warn_nullability_missing)
3779 << static_cast<unsigned>(PointerKind);
3782 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
3783 if (FixItLoc.isMacroID())
3786 auto addFixIt = [&](NullabilityKind Nullability) {
3787 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
3788 Diag << static_cast<unsigned>(Nullability);
3789 Diag << static_cast<unsigned>(PointerKind);
3790 fixItNullability(S, Diag, FixItLoc, Nullability);
3792 addFixIt(NullabilityKind::Nullable);
3793 addFixIt(NullabilityKind::NonNull);
3796 /// Complains about missing nullability if the file containing \p pointerLoc
3797 /// has other uses of nullability (either the keywords or the \c assume_nonnull
3800 /// If the file has \e not seen other uses of nullability, this particular
3801 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
3803 checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
3804 SourceLocation pointerLoc,
3805 SourceLocation pointerEndLoc = SourceLocation()) {
3806 // Determine which file we're performing consistency checking for.
3807 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
3808 if (file.isInvalid())
3811 // If we haven't seen any type nullability in this file, we won't warn now
3813 FileNullability &fileNullability = S.NullabilityMap[file];
3814 if (!fileNullability.SawTypeNullability) {
3815 // If this is the first pointer declarator in the file, and the appropriate
3816 // warning is on, record it in case we need to diagnose it retroactively.
3817 diag::kind diagKind;
3818 if (pointerKind == SimplePointerKind::Array)
3819 diagKind = diag::warn_nullability_missing_array;
3821 diagKind = diag::warn_nullability_missing;
3823 if (fileNullability.PointerLoc.isInvalid() &&
3824 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
3825 fileNullability.PointerLoc = pointerLoc;
3826 fileNullability.PointerEndLoc = pointerEndLoc;
3827 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
3833 // Complain about missing nullability.
3834 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
3837 /// Marks that a nullability feature has been used in the file containing
3840 /// If this file already had pointer types in it that were missing nullability,
3841 /// the first such instance is retroactively diagnosed.
3843 /// \sa checkNullabilityConsistency
3844 static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
3845 FileID file = getNullabilityCompletenessCheckFileID(S, loc);
3846 if (file.isInvalid())
3849 FileNullability &fileNullability = S.NullabilityMap[file];
3850 if (fileNullability.SawTypeNullability)
3852 fileNullability.SawTypeNullability = true;
3854 // If we haven't seen any type nullability before, now we have. Retroactively
3855 // diagnose the first unannotated pointer, if there was one.
3856 if (fileNullability.PointerLoc.isInvalid())
3859 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
3860 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
3861 fileNullability.PointerEndLoc);
3864 /// Returns true if any of the declarator chunks before \p endIndex include a
3865 /// level of indirection: array, pointer, reference, or pointer-to-member.
3867 /// Because declarator chunks are stored in outer-to-inner order, testing
3868 /// every chunk before \p endIndex is testing all chunks that embed the current
3869 /// chunk as part of their type.
3871 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the
3872 /// end index, in which case all chunks are tested.
3873 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
3874 unsigned i = endIndex;
3876 // Walk outwards along the declarator chunks.
3878 const DeclaratorChunk &DC = D.getTypeObject(i);
3880 case DeclaratorChunk::Paren:
3882 case DeclaratorChunk::Array:
3883 case DeclaratorChunk::Pointer:
3884 case DeclaratorChunk::Reference:
3885 case DeclaratorChunk::MemberPointer:
3887 case DeclaratorChunk::Function:
3888 case DeclaratorChunk::BlockPointer:
3889 case DeclaratorChunk::Pipe:
3890 // These are invalid anyway, so just ignore.
3897 static bool IsNoDerefableChunk(DeclaratorChunk Chunk) {
3898 return (Chunk.Kind == DeclaratorChunk::Pointer ||
3899 Chunk.Kind == DeclaratorChunk::Array);
3902 template<typename AttrT>
3903 static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &Attr) {
3904 Attr.setUsedAsTypeAttr();
3906 AttrT(Attr.getRange(), Ctx, Attr.getAttributeSpellingListIndex());
3909 static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr,
3910 NullabilityKind NK) {
3912 case NullabilityKind::NonNull:
3913 return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
3915 case NullabilityKind::Nullable:
3916 return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
3918 case NullabilityKind::Unspecified:
3919 return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
3921 llvm_unreachable("unknown NullabilityKind");
3924 static TypeSourceInfo *
3925 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3926 QualType T, TypeSourceInfo *ReturnTypeInfo);
3928 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
3929 QualType declSpecType,
3930 TypeSourceInfo *TInfo) {
3931 // The TypeSourceInfo that this function returns will not be a null type.
3932 // If there is an error, this function will fill in a dummy type as fallback.
3933 QualType T = declSpecType;
3934 Declarator &D = state.getDeclarator();
3935 Sema &S = state.getSema();
3936 ASTContext &Context = S.Context;
3937 const LangOptions &LangOpts = S.getLangOpts();
3939 // The name we're declaring, if any.
3940 DeclarationName Name;
3941 if (D.getIdentifier())
3942 Name = D.getIdentifier();
3944 // Does this declaration declare a typedef-name?
3945 bool IsTypedefName =
3946 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
3947 D.getContext() == DeclaratorContext::AliasDeclContext ||
3948 D.getContext() == DeclaratorContext::AliasTemplateContext;
3950 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
3951 bool IsQualifiedFunction = T->isFunctionProtoType() &&
3952 (!T->castAs<FunctionProtoType>()->getTypeQuals().empty() ||
3953 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
3955 // If T is 'decltype(auto)', the only declarators we can have are parens
3956 // and at most one function declarator if this is a function declaration.
3957 // If T is a deduced class template specialization type, we can have no
3958 // declarator chunks at all.
3959 if (auto *DT = T->getAs<DeducedType>()) {
3960 const AutoType *AT = T->getAs<AutoType>();
3961 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
3962 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
3963 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3964 unsigned Index = E - I - 1;
3965 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
3966 unsigned DiagId = IsClassTemplateDeduction
3967 ? diag::err_deduced_class_template_compound_type
3968 : diag::err_decltype_auto_compound_type;
3969 unsigned DiagKind = 0;
3970 switch (DeclChunk.Kind) {
3971 case DeclaratorChunk::Paren:
3972 // FIXME: Rejecting this is a little silly.
3973 if (IsClassTemplateDeduction) {
3978 case DeclaratorChunk::Function: {
3979 if (IsClassTemplateDeduction) {
3984 if (D.isFunctionDeclarationContext() &&
3985 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
3987 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
3990 case DeclaratorChunk::Pointer:
3991 case DeclaratorChunk::BlockPointer:
3992 case DeclaratorChunk::MemberPointer:
3995 case DeclaratorChunk::Reference:
3998 case DeclaratorChunk::Array:
4001 case DeclaratorChunk::Pipe:
4005 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4006 D.setInvalidType(true);
4012 // Determine whether we should infer _Nonnull on pointer types.
4013 Optional<NullabilityKind> inferNullability;
4014 bool inferNullabilityCS = false;
4015 bool inferNullabilityInnerOnly = false;
4016 bool inferNullabilityInnerOnlyComplete = false;
4018 // Are we in an assume-nonnull region?
4019 bool inAssumeNonNullRegion = false;
4020 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4021 if (assumeNonNullLoc.isValid()) {
4022 inAssumeNonNullRegion = true;
4023 recordNullabilitySeen(S, assumeNonNullLoc);
4026 // Whether to complain about missing nullability specifiers or not.
4030 /// Complain on the inner pointers (but not the outermost
4033 /// Complain about any pointers that don't have nullability
4034 /// specified or inferred.
4036 } complainAboutMissingNullability = CAMN_No;
4037 unsigned NumPointersRemaining = 0;
4038 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4040 if (IsTypedefName) {
4041 // For typedefs, we do not infer any nullability (the default),
4042 // and we only complain about missing nullability specifiers on
4044 complainAboutMissingNullability = CAMN_InnerPointers;
4046 if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4047 !T->getNullability(S.Context)) {
4048 // Note that we allow but don't require nullability on dependent types.
4049 ++NumPointersRemaining;
4052 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4053 DeclaratorChunk &chunk = D.getTypeObject(i);
4054 switch (chunk.Kind) {
4055 case DeclaratorChunk::Array:
4056 case DeclaratorChunk::Function:
4057 case DeclaratorChunk::Pipe:
4060 case DeclaratorChunk::BlockPointer:
4061 case DeclaratorChunk::MemberPointer:
4062 ++NumPointersRemaining;
4065 case DeclaratorChunk::Paren:
4066 case DeclaratorChunk::Reference:
4069 case DeclaratorChunk::Pointer:
4070 ++NumPointersRemaining;
4075 bool isFunctionOrMethod = false;
4076 switch (auto context = state.getDeclarator().getContext()) {
4077 case DeclaratorContext::ObjCParameterContext:
4078 case DeclaratorContext::ObjCResultContext:
4079 case DeclaratorContext::PrototypeContext:
4080 case DeclaratorContext::TrailingReturnContext:
4081 case DeclaratorContext::TrailingReturnVarContext:
4082 isFunctionOrMethod = true;
4085 case DeclaratorContext::MemberContext:
4086 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4087 complainAboutMissingNullability = CAMN_No;
4091 // Weak properties are inferred to be nullable.
4092 if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
4093 inferNullability = NullabilityKind::Nullable;
4099 case DeclaratorContext::FileContext:
4100 case DeclaratorContext::KNRTypeListContext: {
4101 complainAboutMissingNullability = CAMN_Yes;
4103 // Nullability inference depends on the type and declarator.
4104 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4105 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4106 case PointerDeclaratorKind::NonPointer:
4107 case PointerDeclaratorKind::MultiLevelPointer:
4108 // Cannot infer nullability.
4111 case PointerDeclaratorKind::SingleLevelPointer:
4112 // Infer _Nonnull if we are in an assumes-nonnull region.
4113 if (inAssumeNonNullRegion) {
4114 complainAboutInferringWithinChunk = wrappingKind;
4115 inferNullability = NullabilityKind::NonNull;
4116 inferNullabilityCS =
4117 (context == DeclaratorContext::ObjCParameterContext ||
4118 context == DeclaratorContext::ObjCResultContext);
4122 case PointerDeclaratorKind::CFErrorRefPointer:
4123 case PointerDeclaratorKind::NSErrorPointerPointer:
4124 // Within a function or method signature, infer _Nullable at both
4126 if (isFunctionOrMethod && inAssumeNonNullRegion)
4127 inferNullability = NullabilityKind::Nullable;
4130 case PointerDeclaratorKind::MaybePointerToCFRef:
4131 if (isFunctionOrMethod) {
4132 // On pointer-to-pointer parameters marked cf_returns_retained or
4133 // cf_returns_not_retained, if the outer pointer is explicit then
4134 // infer the inner pointer as _Nullable.
4135 auto hasCFReturnsAttr =
4136 [](const ParsedAttributesView &AttrList) -> bool {
4137 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4138 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4140 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4141 if (hasCFReturnsAttr(D.getAttributes()) ||
4142 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4143 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4144 inferNullability = NullabilityKind::Nullable;
4145 inferNullabilityInnerOnly = true;
4154 case DeclaratorContext::ConversionIdContext:
4155 complainAboutMissingNullability = CAMN_Yes;
4158 case DeclaratorContext::AliasDeclContext:
4159 case DeclaratorContext::AliasTemplateContext:
4160 case DeclaratorContext::BlockContext:
4161 case DeclaratorContext::BlockLiteralContext:
4162 case DeclaratorContext::ConditionContext:
4163 case DeclaratorContext::CXXCatchContext:
4164 case DeclaratorContext::CXXNewContext:
4165 case DeclaratorContext::ForContext:
4166 case DeclaratorContext::InitStmtContext:
4167 case DeclaratorContext::LambdaExprContext:
4168 case DeclaratorContext::LambdaExprParameterContext:
4169 case DeclaratorContext::ObjCCatchContext:
4170 case DeclaratorContext::TemplateParamContext:
4171 case DeclaratorContext::TemplateArgContext:
4172 case DeclaratorContext::TemplateTypeArgContext:
4173 case DeclaratorContext::TypeNameContext:
4174 case DeclaratorContext::FunctionalCastContext:
4175 // Don't infer in these contexts.
4180 // Local function that returns true if its argument looks like a va_list.
4181 auto isVaList = [&S](QualType T) -> bool {
4182 auto *typedefTy = T->getAs<TypedefType>();
4185 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4187 if (typedefTy->getDecl() == vaListTypedef)
4189 if (auto *name = typedefTy->getDecl()->getIdentifier())
4190 if (name->isStr("va_list"))
4192 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4193 } while (typedefTy);
4197 // Local function that checks the nullability for a given pointer declarator.
4198 // Returns true if _Nonnull was inferred.
4199 auto inferPointerNullability =
4200 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4201 SourceLocation pointerEndLoc,
4202 ParsedAttributesView &attrs) -> ParsedAttr * {
4203 // We've seen a pointer.
4204 if (NumPointersRemaining > 0)
4205 --NumPointersRemaining;
4207 // If a nullability attribute is present, there's nothing to do.
4208 if (hasNullabilityAttr(attrs))
4211 // If we're supposed to infer nullability, do so now.
4212 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4213 ParsedAttr::Syntax syntax = inferNullabilityCS
4214 ? ParsedAttr::AS_ContextSensitiveKeyword
4215 : ParsedAttr::AS_Keyword;
4216 ParsedAttr *nullabilityAttr =
4217 state.getDeclarator().getAttributePool().create(
4218 S.getNullabilityKeyword(*inferNullability),
4219 SourceRange(pointerLoc), nullptr, SourceLocation(), nullptr, 0,
4222 attrs.addAtEnd(nullabilityAttr);
4224 if (inferNullabilityCS) {
4225 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4226 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4229 if (pointerLoc.isValid() &&
4230 complainAboutInferringWithinChunk !=
4231 PointerWrappingDeclaratorKind::None) {
4233 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4234 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4235 fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
4238 if (inferNullabilityInnerOnly)
4239 inferNullabilityInnerOnlyComplete = true;
4240 return nullabilityAttr;
4243 // If we're supposed to complain about missing nullability, do so
4244 // now if it's truly missing.
4245 switch (complainAboutMissingNullability) {
4249 case CAMN_InnerPointers:
4250 if (NumPointersRemaining == 0)
4255 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4260 // If the type itself could have nullability but does not, infer pointer
4261 // nullability and perform consistency checking.
4262 if (S.CodeSynthesisContexts.empty()) {
4263 if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4264 !T->getNullability(S.Context)) {
4266 // Record that we've seen a pointer, but do nothing else.
4267 if (NumPointersRemaining > 0)
4268 --NumPointersRemaining;
4270 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4271 if (T->isBlockPointerType())
4272 pointerKind = SimplePointerKind::BlockPointer;
4273 else if (T->isMemberPointerType())
4274 pointerKind = SimplePointerKind::MemberPointer;
4276 if (auto *attr = inferPointerNullability(
4277 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4278 D.getDeclSpec().getEndLoc(),
4279 D.getMutableDeclSpec().getAttributes())) {
4280 T = state.getAttributedType(
4281 createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4286 if (complainAboutMissingNullability == CAMN_Yes &&
4287 T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
4288 D.isPrototypeContext() &&
4289 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
4290 checkNullabilityConsistency(S, SimplePointerKind::Array,
4291 D.getDeclSpec().getTypeSpecTypeLoc());
4295 bool ExpectNoDerefChunk =
4296 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4298 // Walk the DeclTypeInfo, building the recursive type as we go.
4299 // DeclTypeInfos are ordered from the identifier out, which is
4300 // opposite of what we want :).
4301 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4302 unsigned chunkIndex = e - i - 1;
4303 state.setCurrentChunkIndex(chunkIndex);
4304 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4305 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4306 switch (DeclType.Kind) {
4307 case DeclaratorChunk::Paren:
4309 warnAboutRedundantParens(S, D, T);
4310 T = S.BuildParenType(T);
4312 case DeclaratorChunk::BlockPointer:
4313 // If blocks are disabled, emit an error.
4314 if (!LangOpts.Blocks)
4315 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4317 // Handle pointer nullability.
4318 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4319 DeclType.EndLoc, DeclType.getAttrs());
4321 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4322 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4323 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4324 // qualified with const.
4325 if (LangOpts.OpenCL)
4326 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4327 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4330 case DeclaratorChunk::Pointer:
4331 // Verify that we're not building a pointer to pointer to function with
4332 // exception specification.
4333 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4334 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4335 D.setInvalidType(true);
4336 // Build the type anyway.
4339 // Handle pointer nullability
4340 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4341 DeclType.EndLoc, DeclType.getAttrs());
4343 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
4344 T = Context.getObjCObjectPointerType(T);
4345 if (DeclType.Ptr.TypeQuals)
4346 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4350 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4351 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4352 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4353 if (LangOpts.OpenCL) {
4354 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4355 T->isBlockPointerType()) {
4356 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4357 D.setInvalidType(true);
4361 T = S.BuildPointerType(T, DeclType.Loc, Name);
4362 if (DeclType.Ptr.TypeQuals)
4363 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4365 case DeclaratorChunk::Reference: {
4366 // Verify that we're not building a reference to pointer to function with
4367 // exception specification.
4368 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4369 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4370 D.setInvalidType(true);
4371 // Build the type anyway.
4373 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4375 if (DeclType.Ref.HasRestrict)
4376 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4379 case DeclaratorChunk::Array: {
4380 // Verify that we're not building an array of pointers to function with
4381 // exception specification.
4382 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4383 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4384 D.setInvalidType(true);
4385 // Build the type anyway.
4387 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4388 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4389 ArrayType::ArraySizeModifier ASM;
4391 ASM = ArrayType::Star;
4392 else if (ATI.hasStatic)
4393 ASM = ArrayType::Static;
4395 ASM = ArrayType::Normal;
4396 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
4397 // FIXME: This check isn't quite right: it allows star in prototypes
4398 // for function definitions, and disallows some edge cases detailed
4399 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4400 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4401 ASM = ArrayType::Normal;
4402 D.setInvalidType(true);
4405 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4406 // shall appear only in a declaration of a function parameter with an
4408 if (ASM == ArrayType::Static || ATI.TypeQuals) {
4409 if (!(D.isPrototypeContext() ||
4410 D.getContext() == DeclaratorContext::KNRTypeListContext)) {
4411 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
4412 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4413 // Remove the 'static' and the type qualifiers.
4414 if (ASM == ArrayType::Static)
4415 ASM = ArrayType::Normal;
4417 D.setInvalidType(true);
4420 // C99 6.7.5.2p1: ... and then only in the outermost array type
4422 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4423 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
4424 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4425 if (ASM == ArrayType::Static)
4426 ASM = ArrayType::Normal;
4428 D.setInvalidType(true);
4431 const AutoType *AT = T->getContainedAutoType();
4432 // Allow arrays of auto if we are a generic lambda parameter.
4433 // i.e. [](auto (&array)[5]) { return array[0]; }; OK
4435 D.getContext() != DeclaratorContext::LambdaExprParameterContext) {
4436 // We've already diagnosed this for decltype(auto).
4437 if (!AT->isDecltypeAuto())
4438 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
4439 << getPrintableNameForEntity(Name) << T;
4444 // Array parameters can be marked nullable as well, although it's not
4445 // necessary if they're marked 'static'.
4446 if (complainAboutMissingNullability == CAMN_Yes &&
4447 !hasNullabilityAttr(DeclType.getAttrs()) &&
4448 ASM != ArrayType::Static &&
4449 D.isPrototypeContext() &&
4450 !hasOuterPointerLikeChunk(D, chunkIndex)) {
4451 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4454 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4455 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4458 case DeclaratorChunk::Function: {
4459 // If the function declarator has a prototype (i.e. it is not () and
4460 // does not have a K&R-style identifier list), then the arguments are part
4461 // of the type, otherwise the argument list is ().
4462 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4463 IsQualifiedFunction =
4464 FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier();
4466 // Check for auto functions and trailing return type and adjust the
4467 // return type accordingly.
4468 if (!D.isInvalidType()) {
4469 // trailing-return-type is only required if we're declaring a function,
4470 // and not, for instance, a pointer to a function.
4471 if (D.getDeclSpec().hasAutoTypeSpec() &&
4472 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
4473 if (!S.getLangOpts().CPlusPlus14) {
4474 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4475 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
4476 ? diag::err_auto_missing_trailing_return
4477 : diag::err_deduced_return_type);
4479 D.setInvalidType(true);
4481 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4482 diag::warn_cxx11_compat_deduced_return_type);
4484 } else if (FTI.hasTrailingReturnType()) {
4485 // T must be exactly 'auto' at this point. See CWG issue 681.
4486 if (isa<ParenType>(T)) {
4487 S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
4488 << T << D.getSourceRange();
4489 D.setInvalidType(true);
4490 } else if (D.getName().getKind() ==
4491 UnqualifiedIdKind::IK_DeductionGuideName) {
4492 if (T != Context.DependentTy) {
4493 S.Diag(D.getDeclSpec().getBeginLoc(),
4494 diag::err_deduction_guide_with_complex_decl)
4495 << D.getSourceRange();
4496 D.setInvalidType(true);
4498 } else if (D.getContext() != DeclaratorContext::LambdaExprContext &&
4499 (T.hasQualifiers() || !isa<AutoType>(T) ||
4500 cast<AutoType>(T)->getKeyword() !=
4501 AutoTypeKeyword::Auto)) {
4502 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4503 diag::err_trailing_return_without_auto)
4504 << T << D.getDeclSpec().getSourceRange();
4505 D.setInvalidType(true);
4507 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
4509 // An error occurred parsing the trailing return type.
4511 D.setInvalidType(true);
4514 // This function type is not the type of the entity being declared,
4515 // so checking the 'auto' is not the responsibility of this chunk.
4519 // C99 6.7.5.3p1: The return type may not be a function or array type.
4520 // For conversion functions, we'll diagnose this particular error later.
4521 if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
4522 (D.getName().getKind() !=
4523 UnqualifiedIdKind::IK_ConversionFunctionId)) {
4524 unsigned diagID = diag::err_func_returning_array_function;
4525 // Last processing chunk in block context means this function chunk
4526 // represents the block.
4527 if (chunkIndex == 0 &&
4528 D.getContext() == DeclaratorContext::BlockLiteralContext)
4529 diagID = diag::err_block_returning_array_function;
4530 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
4532 D.setInvalidType(true);
4535 // Do not allow returning half FP value.
4536 // FIXME: This really should be in BuildFunctionType.
4537 if (T->isHalfType()) {
4538 if (S.getLangOpts().OpenCL) {
4539 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4540 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4541 << T << 0 /*pointer hint*/;
4542 D.setInvalidType(true);
4544 } else if (!S.getLangOpts().HalfArgsAndReturns) {
4545 S.Diag(D.getIdentifierLoc(),
4546 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
4547 D.setInvalidType(true);
4551 if (LangOpts.OpenCL) {
4552 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
4554 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
4556 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4557 << T << 1 /*hint off*/;
4558 D.setInvalidType(true);
4560 // OpenCL doesn't support variadic functions and blocks
4561 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
4562 // We also allow here any toolchain reserved identifiers.
4563 if (FTI.isVariadic &&
4564 !(D.getIdentifier() &&
4565 ((D.getIdentifier()->getName() == "printf" &&
4566 LangOpts.OpenCLVersion >= 120) ||
4567 D.getIdentifier()->getName().startswith("__")))) {
4568 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
4569 D.setInvalidType(true);
4573 // Methods cannot return interface types. All ObjC objects are
4574 // passed by reference.
4575 if (T->isObjCObjectType()) {
4576 SourceLocation DiagLoc, FixitLoc;
4578 DiagLoc = TInfo->getTypeLoc().getBeginLoc();
4579 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
4581 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
4582 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
4584 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
4586 << FixItHint::CreateInsertion(FixitLoc, "*");
4588 T = Context.getObjCObjectPointerType(T);
4591 TLB.pushFullCopy(TInfo->getTypeLoc());
4592 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
4593 TLoc.setStarLoc(FixitLoc);
4594 TInfo = TLB.getTypeSourceInfo(Context, T);
4597 D.setInvalidType(true);
4600 // cv-qualifiers on return types are pointless except when the type is a
4601 // class type in C++.
4602 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
4603 !(S.getLangOpts().CPlusPlus &&
4604 (T->isDependentType() || T->isRecordType()))) {
4605 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
4606 D.getFunctionDefinitionKind() == FDK_Definition) {
4607 // [6.9.1/3] qualified void return is invalid on a C
4608 // function definition. Apparently ok on declarations and
4609 // in C++ though (!)
4610 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
4612 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
4615 // Objective-C ARC ownership qualifiers are ignored on the function
4616 // return type (by type canonicalization). Complain if this attribute
4617 // was written here.
4618 if (T.getQualifiers().hasObjCLifetime()) {
4619 SourceLocation AttrLoc;
4620 if (chunkIndex + 1 < D.getNumTypeObjects()) {
4621 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
4622 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
4623 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
4624 AttrLoc = AL.getLoc();
4629 if (AttrLoc.isInvalid()) {
4630 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4631 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
4632 AttrLoc = AL.getLoc();
4638 if (AttrLoc.isValid()) {
4639 // The ownership attributes are almost always written via
4641 // __strong/__weak/__autoreleasing/__unsafe_unretained.
4642 if (AttrLoc.isMacroID())
4644 S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin();
4646 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
4647 << T.getQualifiers().getObjCLifetime();
4651 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
4653 // Types shall not be defined in return or parameter types.
4654 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
4655 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
4656 << Context.getTypeDeclType(Tag);
4659 // Exception specs are not allowed in typedefs. Complain, but add it
4661 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
4662 S.Diag(FTI.getExceptionSpecLocBeg(),
4663 diag::err_exception_spec_in_typedef)
4664 << (D.getContext() == DeclaratorContext::AliasDeclContext ||
4665 D.getContext() == DeclaratorContext::AliasTemplateContext);
4667 // If we see "T var();" or "T var(T());" at block scope, it is probably
4668 // an attempt to initialize a variable, not a function declaration.
4669 if (FTI.isAmbiguous)
4670 warnAboutAmbiguousFunction(S, D, DeclType, T);
4672 FunctionType::ExtInfo EI(
4673 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
4675 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus
4676 && !LangOpts.OpenCL) {
4677 // Simple void foo(), where the incoming T is the result type.
4678 T = Context.getFunctionNoProtoType(T, EI);
4680 // We allow a zero-parameter variadic function in C if the
4681 // function is marked with the "overloadable" attribute. Scan
4682 // for this attribute now.
4683 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus)
4684 if (!D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable))
4685 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
4687 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
4688 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
4690 S.Diag(FTI.Params[0].IdentLoc,
4691 diag::err_ident_list_in_fn_declaration);
4692 D.setInvalidType(true);
4693 // Recover by creating a K&R-style function type.
4694 T = Context.getFunctionNoProtoType(T, EI);
4698 FunctionProtoType::ExtProtoInfo EPI;
4700 EPI.Variadic = FTI.isVariadic;
4701 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
4702 EPI.TypeQuals.addCVRUQualifiers(
4703 FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers()
4705 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
4706 : FTI.RefQualifierIsLValueRef? RQ_LValue
4709 // Otherwise, we have a function with a parameter list that is
4710 // potentially variadic.
4711 SmallVector<QualType, 16> ParamTys;
4712 ParamTys.reserve(FTI.NumParams);
4714 SmallVector<FunctionProtoType::ExtParameterInfo, 16>
4715 ExtParameterInfos(FTI.NumParams);
4716 bool HasAnyInterestingExtParameterInfos = false;
4718 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
4719 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4720 QualType ParamTy = Param->getType();
4721 assert(!ParamTy.isNull() && "Couldn't parse type?");
4723 // Look for 'void'. void is allowed only as a single parameter to a
4724 // function with no other parameters (C99 6.7.5.3p10). We record
4725 // int(void) as a FunctionProtoType with an empty parameter list.
4726 if (ParamTy->isVoidType()) {
4727 // If this is something like 'float(int, void)', reject it. 'void'
4728 // is an incomplete type (C99 6.2.5p19) and function decls cannot
4729 // have parameters of incomplete type.
4730 if (FTI.NumParams != 1 || FTI.isVariadic) {
4731 S.Diag(DeclType.Loc, diag::err_void_only_param);
4732 ParamTy = Context.IntTy;
4733 Param->setType(ParamTy);
4734 } else if (FTI.Params[i].Ident) {
4735 // Reject, but continue to parse 'int(void abc)'.
4736 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
4737 ParamTy = Context.IntTy;
4738 Param->setType(ParamTy);
4740 // Reject, but continue to parse 'float(const void)'.
4741 if (ParamTy.hasQualifiers())
4742 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
4744 // Do not add 'void' to the list.
4747 } else if (ParamTy->isHalfType()) {
4748 // Disallow half FP parameters.
4749 // FIXME: This really should be in BuildFunctionType.
4750 if (S.getLangOpts().OpenCL) {
4751 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4752 S.Diag(Param->getLocation(),
4753 diag::err_opencl_half_param) << ParamTy;
4755 Param->setInvalidDecl();
4757 } else if (!S.getLangOpts().HalfArgsAndReturns) {
4758 S.Diag(Param->getLocation(),
4759 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
4762 } else if (!FTI.hasPrototype) {
4763 if (ParamTy->isPromotableIntegerType()) {
4764 ParamTy = Context.getPromotedIntegerType(ParamTy);
4765 Param->setKNRPromoted(true);
4766 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
4767 if (BTy->getKind() == BuiltinType::Float) {
4768 ParamTy = Context.DoubleTy;
4769 Param->setKNRPromoted(true);
4774 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
4775 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
4776 HasAnyInterestingExtParameterInfos = true;
4779 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
4780 ExtParameterInfos[i] =
4781 ExtParameterInfos[i].withABI(attr->getABI());
4782 HasAnyInterestingExtParameterInfos = true;
4785 if (Param->hasAttr<PassObjectSizeAttr>()) {
4786 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
4787 HasAnyInterestingExtParameterInfos = true;
4790 if (Param->hasAttr<NoEscapeAttr>()) {
4791 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
4792 HasAnyInterestingExtParameterInfos = true;
4795 ParamTys.push_back(ParamTy);
4798 if (HasAnyInterestingExtParameterInfos) {
4799 EPI.ExtParameterInfos = ExtParameterInfos.data();
4800 checkExtParameterInfos(S, ParamTys, EPI,
4801 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
4804 SmallVector<QualType, 4> Exceptions;
4805 SmallVector<ParsedType, 2> DynamicExceptions;
4806 SmallVector<SourceRange, 2> DynamicExceptionRanges;
4807 Expr *NoexceptExpr = nullptr;
4809 if (FTI.getExceptionSpecType() == EST_Dynamic) {
4810 // FIXME: It's rather inefficient to have to split into two vectors
4812 unsigned N = FTI.getNumExceptions();
4813 DynamicExceptions.reserve(N);
4814 DynamicExceptionRanges.reserve(N);
4815 for (unsigned I = 0; I != N; ++I) {
4816 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
4817 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
4819 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
4820 NoexceptExpr = FTI.NoexceptExpr;
4823 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
4824 FTI.getExceptionSpecType(),
4826 DynamicExceptionRanges,
4831 const auto &Spec = D.getCXXScopeSpec();
4832 // OpenCLCPlusPlus: A class member function has an address space.
4833 if (state.getSema().getLangOpts().OpenCLCPlusPlus &&
4834 ((!Spec.isEmpty() &&
4835 Spec.getScopeRep()->getKind() == NestedNameSpecifier::TypeSpec) ||
4836 state.getDeclarator().getContext() ==
4837 DeclaratorContext::MemberContext)) {
4838 LangAS CurAS = EPI.TypeQuals.getAddressSpace();
4839 // If a class member function's address space is not set, set it to
4842 (CurAS == LangAS::Default ? LangAS::opencl_generic : CurAS);
4843 EPI.TypeQuals.addAddressSpace(AS);
4845 T = Context.getFunctionType(T, ParamTys, EPI);
4849 case DeclaratorChunk::MemberPointer: {
4850 // The scope spec must refer to a class, or be dependent.
4851 CXXScopeSpec &SS = DeclType.Mem.Scope();
4854 // Handle pointer nullability.
4855 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
4856 DeclType.EndLoc, DeclType.getAttrs());
4858 if (SS.isInvalid()) {
4859 // Avoid emitting extra errors if we already errored on the scope.
4860 D.setInvalidType(true);
4861 } else if (S.isDependentScopeSpecifier(SS) ||
4862 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
4863 NestedNameSpecifier *NNS = SS.getScopeRep();
4864 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
4865 switch (NNS->getKind()) {
4866 case NestedNameSpecifier::Identifier:
4867 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
4868 NNS->getAsIdentifier());
4871 case NestedNameSpecifier::Namespace:
4872 case NestedNameSpecifier::NamespaceAlias:
4873 case NestedNameSpecifier::Global:
4874 case NestedNameSpecifier::Super:
4875 llvm_unreachable("Nested-name-specifier must name a type");
4877 case NestedNameSpecifier::TypeSpec:
4878 case NestedNameSpecifier::TypeSpecWithTemplate:
4879 ClsType = QualType(NNS->getAsType(), 0);
4880 // Note: if the NNS has a prefix and ClsType is a nondependent
4881 // TemplateSpecializationType, then the NNS prefix is NOT included
4882 // in ClsType; hence we wrap ClsType into an ElaboratedType.
4883 // NOTE: in particular, no wrap occurs if ClsType already is an
4884 // Elaborated, DependentName, or DependentTemplateSpecialization.
4885 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
4886 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
4890 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
4891 diag::err_illegal_decl_mempointer_in_nonclass)
4892 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
4893 << DeclType.Mem.Scope().getRange();
4894 D.setInvalidType(true);
4897 if (!ClsType.isNull())
4898 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
4902 D.setInvalidType(true);
4903 } else if (DeclType.Mem.TypeQuals) {
4904 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
4909 case DeclaratorChunk::Pipe: {
4910 T = S.BuildReadPipeType(T, DeclType.Loc);
4911 processTypeAttrs(state, T, TAL_DeclSpec,
4912 D.getMutableDeclSpec().getAttributes());
4918 D.setInvalidType(true);
4922 // See if there are any attributes on this declarator chunk.
4923 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs());
4925 if (DeclType.Kind != DeclaratorChunk::Paren) {
4926 if (ExpectNoDerefChunk) {
4927 if (!IsNoDerefableChunk(DeclType))
4928 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
4929 ExpectNoDerefChunk = false;
4932 ExpectNoDerefChunk = state.didParseNoDeref();
4936 if (ExpectNoDerefChunk)
4937 S.Diag(state.getDeclarator().getBeginLoc(),
4938 diag::warn_noderef_on_non_pointer_or_array);
4940 // GNU warning -Wstrict-prototypes
4941 // Warn if a function declaration is without a prototype.
4942 // This warning is issued for all kinds of unprototyped function
4943 // declarations (i.e. function type typedef, function pointer etc.)
4945 // The empty list in a function declarator that is not part of a definition
4946 // of that function specifies that no information about the number or types
4947 // of the parameters is supplied.
4948 if (!LangOpts.CPlusPlus && D.getFunctionDefinitionKind() == FDK_Declaration) {
4949 bool IsBlock = false;
4950 for (const DeclaratorChunk &DeclType : D.type_objects()) {
4951 switch (DeclType.Kind) {
4952 case DeclaratorChunk::BlockPointer:
4955 case DeclaratorChunk::Function: {
4956 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4957 if (FTI.NumParams == 0 && !FTI.isVariadic)
4958 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
4960 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
4970 assert(!T.isNull() && "T must not be null after this point");
4972 if (LangOpts.CPlusPlus && T->isFunctionType()) {
4973 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
4974 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
4977 // A cv-qualifier-seq shall only be part of the function type
4978 // for a nonstatic member function, the function type to which a pointer
4979 // to member refers, or the top-level function type of a function typedef
4982 // Core issue 547 also allows cv-qualifiers on function types that are
4983 // top-level template type arguments.
4984 enum { NonMember, Member, DeductionGuide } Kind = NonMember;
4985 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
4986 Kind = DeductionGuide;
4987 else if (!D.getCXXScopeSpec().isSet()) {
4988 if ((D.getContext() == DeclaratorContext::MemberContext ||
4989 D.getContext() == DeclaratorContext::LambdaExprContext) &&
4990 !D.getDeclSpec().isFriendSpecified())
4993 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
4994 if (!DC || DC->isRecord())
4998 // C++11 [dcl.fct]p6 (w/DR1417):
4999 // An attempt to specify a function type with a cv-qualifier-seq or a
5000 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5001 // - the function type for a non-static member function,
5002 // - the function type to which a pointer to member refers,
5003 // - the top-level function type of a function typedef declaration or
5004 // alias-declaration,
5005 // - the type-id in the default argument of a type-parameter, or
5006 // - the type-id of a template-argument for a type-parameter
5008 // FIXME: Checking this here is insufficient. We accept-invalid on:
5010 // template<typename T> struct S { void f(T); };
5011 // S<int() const> s;
5013 // ... for instance.
5014 if (IsQualifiedFunction &&
5016 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
5018 D.getContext() != DeclaratorContext::TemplateArgContext &&
5019 D.getContext() != DeclaratorContext::TemplateTypeArgContext) {
5020 SourceLocation Loc = D.getBeginLoc();
5021 SourceRange RemovalRange;
5023 if (D.isFunctionDeclarator(I)) {
5024 SmallVector<SourceLocation, 4> RemovalLocs;
5025 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5026 assert(Chunk.Kind == DeclaratorChunk::Function);
5028 if (Chunk.Fun.hasRefQualifier())
5029 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5031 if (Chunk.Fun.hasMethodTypeQualifiers())
5032 Chunk.Fun.MethodQualifiers->forEachQualifier(
5033 [&](DeclSpec::TQ TypeQual, StringRef QualName,
5034 SourceLocation SL) { RemovalLocs.push_back(SL); });
5036 if (!RemovalLocs.empty()) {
5037 llvm::sort(RemovalLocs,
5038 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
5039 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5040 Loc = RemovalLocs.front();
5044 S.Diag(Loc, diag::err_invalid_qualified_function_type)
5045 << Kind << D.isFunctionDeclarator() << T
5046 << getFunctionQualifiersAsString(FnTy)
5047 << FixItHint::CreateRemoval(RemovalRange);
5049 // Strip the cv-qualifiers and ref-qualifiers from the type.
5050 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
5051 EPI.TypeQuals.removeCVRQualifiers();
5052 EPI.RefQualifier = RQ_None;
5054 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5056 // Rebuild any parens around the identifier in the function type.
5057 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5058 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
5060 T = S.BuildParenType(T);
5065 // Apply any undistributed attributes from the declarator.
5066 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
5068 // Diagnose any ignored type attributes.
5069 state.diagnoseIgnoredTypeAttrs(T);
5071 // C++0x [dcl.constexpr]p9:
5072 // A constexpr specifier used in an object declaration declares the object
5074 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
5078 // If there was an ellipsis in the declarator, the declaration declares a
5079 // parameter pack whose type may be a pack expansion type.
5080 if (D.hasEllipsis()) {
5081 // C++0x [dcl.fct]p13:
5082 // A declarator-id or abstract-declarator containing an ellipsis shall
5083 // only be used in a parameter-declaration. Such a parameter-declaration
5084 // is a parameter pack (14.5.3). [...]
5085 switch (D.getContext()) {
5086 case DeclaratorContext::PrototypeContext:
5087 case DeclaratorContext::LambdaExprParameterContext:
5088 // C++0x [dcl.fct]p13:
5089 // [...] When it is part of a parameter-declaration-clause, the
5090 // parameter pack is a function parameter pack (14.5.3). The type T
5091 // of the declarator-id of the function parameter pack shall contain
5092 // a template parameter pack; each template parameter pack in T is
5093 // expanded by the function parameter pack.
5095 // We represent function parameter packs as function parameters whose
5096 // type is a pack expansion.
5097 if (!T->containsUnexpandedParameterPack()) {
5098 S.Diag(D.getEllipsisLoc(),
5099 diag::err_function_parameter_pack_without_parameter_packs)
5100 << T << D.getSourceRange();
5101 D.setEllipsisLoc(SourceLocation());
5103 T = Context.getPackExpansionType(T, None);
5106 case DeclaratorContext::TemplateParamContext:
5107 // C++0x [temp.param]p15:
5108 // If a template-parameter is a [...] is a parameter-declaration that
5109 // declares a parameter pack (8.3.5), then the template-parameter is a
5110 // template parameter pack (14.5.3).
5112 // Note: core issue 778 clarifies that, if there are any unexpanded
5113 // parameter packs in the type of the non-type template parameter, then
5114 // it expands those parameter packs.
5115 if (T->containsUnexpandedParameterPack())
5116 T = Context.getPackExpansionType(T, None);
5118 S.Diag(D.getEllipsisLoc(),
5119 LangOpts.CPlusPlus11
5120 ? diag::warn_cxx98_compat_variadic_templates
5121 : diag::ext_variadic_templates);
5124 case DeclaratorContext::FileContext:
5125 case DeclaratorContext::KNRTypeListContext:
5126 case DeclaratorContext::ObjCParameterContext: // FIXME: special diagnostic
5128 case DeclaratorContext::ObjCResultContext: // FIXME: special diagnostic
5130 case DeclaratorContext::TypeNameContext:
5131 case DeclaratorContext::FunctionalCastContext:
5132 case DeclaratorContext::CXXNewContext:
5133 case DeclaratorContext::AliasDeclContext:
5134 case DeclaratorContext::AliasTemplateContext:
5135 case DeclaratorContext::MemberContext:
5136 case DeclaratorContext::BlockContext:
5137 case DeclaratorContext::ForContext:
5138 case DeclaratorContext::InitStmtContext:
5139 case DeclaratorContext::ConditionContext:
5140 case DeclaratorContext::CXXCatchContext:
5141 case DeclaratorContext::ObjCCatchContext:
5142 case DeclaratorContext::BlockLiteralContext:
5143 case DeclaratorContext::LambdaExprContext:
5144 case DeclaratorContext::ConversionIdContext:
5145 case DeclaratorContext::TrailingReturnContext:
5146 case DeclaratorContext::TrailingReturnVarContext:
5147 case DeclaratorContext::TemplateArgContext:
5148 case DeclaratorContext::TemplateTypeArgContext:
5149 // FIXME: We may want to allow parameter packs in block-literal contexts
5151 S.Diag(D.getEllipsisLoc(),
5152 diag::err_ellipsis_in_declarator_not_parameter);
5153 D.setEllipsisLoc(SourceLocation());
5158 assert(!T.isNull() && "T must not be null at the end of this function");
5159 if (D.isInvalidType())
5160 return Context.getTrivialTypeSourceInfo(T);
5162 return GetTypeSourceInfoForDeclarator(state, T, TInfo);
5165 /// GetTypeForDeclarator - Convert the type for the specified
5166 /// declarator to Type instances.
5168 /// The result of this call will never be null, but the associated
5169 /// type may be a null type if there's an unrecoverable error.
5170 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
5171 // Determine the type of the declarator. Not all forms of declarator
5174 TypeProcessingState state(*this, D);
5176 TypeSourceInfo *ReturnTypeInfo = nullptr;
5177 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5178 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5179 inferARCWriteback(state, T);
5181 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5184 static void transferARCOwnershipToDeclSpec(Sema &S,
5185 QualType &declSpecTy,
5186 Qualifiers::ObjCLifetime ownership) {
5187 if (declSpecTy->isObjCRetainableType() &&
5188 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5190 qs.addObjCLifetime(ownership);
5191 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5195 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5196 Qualifiers::ObjCLifetime ownership,
5197 unsigned chunkIndex) {
5198 Sema &S = state.getSema();
5199 Declarator &D = state.getDeclarator();
5201 // Look for an explicit lifetime attribute.
5202 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5203 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
5206 const char *attrStr = nullptr;
5207 switch (ownership) {
5208 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5209 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5210 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5211 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5212 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5215 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5216 Arg->Ident = &S.Context.Idents.get(attrStr);
5217 Arg->Loc = SourceLocation();
5219 ArgsUnion Args(Arg);
5221 // If there wasn't one, add one (with an invalid source location
5222 // so that we don't make an AttributedType for it).
5223 ParsedAttr *attr = D.getAttributePool().create(
5224 &S.Context.Idents.get("objc_ownership"), SourceLocation(),
5225 /*scope*/ nullptr, SourceLocation(),
5226 /*args*/ &Args, 1, ParsedAttr::AS_GNU);
5227 chunk.getAttrs().addAtEnd(attr);
5228 // TODO: mark whether we did this inference?
5231 /// Used for transferring ownership in casts resulting in l-values.
5232 static void transferARCOwnership(TypeProcessingState &state,
5233 QualType &declSpecTy,
5234 Qualifiers::ObjCLifetime ownership) {
5235 Sema &S = state.getSema();
5236 Declarator &D = state.getDeclarator();
5239 bool hasIndirection = false;
5240 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5241 DeclaratorChunk &chunk = D.getTypeObject(i);
5242 switch (chunk.Kind) {
5243 case DeclaratorChunk::Paren:
5247 case DeclaratorChunk::Array:
5248 case DeclaratorChunk::Reference:
5249 case DeclaratorChunk::Pointer:
5251 hasIndirection = true;
5255 case DeclaratorChunk::BlockPointer:
5257 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5260 case DeclaratorChunk::Function:
5261 case DeclaratorChunk::MemberPointer:
5262 case DeclaratorChunk::Pipe:
5270 DeclaratorChunk &chunk = D.getTypeObject(inner);
5271 if (chunk.Kind == DeclaratorChunk::Pointer) {
5272 if (declSpecTy->isObjCRetainableType())
5273 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5274 if (declSpecTy->isObjCObjectType() && hasIndirection)
5275 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5277 assert(chunk.Kind == DeclaratorChunk::Array ||
5278 chunk.Kind == DeclaratorChunk::Reference);
5279 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5283 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
5284 TypeProcessingState state(*this, D);
5286 TypeSourceInfo *ReturnTypeInfo = nullptr;
5287 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5289 if (getLangOpts().ObjC) {
5290 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
5291 if (ownership != Qualifiers::OCL_None)
5292 transferARCOwnership(state, declSpecTy, ownership);
5295 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
5298 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
5299 TypeProcessingState &State) {
5300 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
5304 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5305 ASTContext &Context;
5306 TypeProcessingState &State;
5310 TypeSpecLocFiller(ASTContext &Context, TypeProcessingState &State,
5312 : Context(Context), State(State), DS(DS) {}
5314 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5315 Visit(TL.getModifiedLoc());
5316 fillAttributedTypeLoc(TL, State);
5318 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5319 Visit(TL.getUnqualifiedLoc());
5321 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5322 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5324 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5325 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5326 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
5327 // addition field. What we have is good enough for dispay of location
5328 // of 'fixit' on interface name.
5329 TL.setNameEndLoc(DS.getEndLoc());
5331 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5332 TypeSourceInfo *RepTInfo = nullptr;
5333 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5334 TL.copy(RepTInfo->getTypeLoc());
5336 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5337 TypeSourceInfo *RepTInfo = nullptr;
5338 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5339 TL.copy(RepTInfo->getTypeLoc());
5341 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
5342 TypeSourceInfo *TInfo = nullptr;
5343 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5345 // If we got no declarator info from previous Sema routines,
5346 // just fill with the typespec loc.
5348 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
5352 TypeLoc OldTL = TInfo->getTypeLoc();
5353 if (TInfo->getType()->getAs<ElaboratedType>()) {
5354 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
5355 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
5356 .castAs<TemplateSpecializationTypeLoc>();
5359 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
5360 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
5364 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5365 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
5366 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5367 TL.setParensRange(DS.getTypeofParensRange());
5369 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5370 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
5371 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5372 TL.setParensRange(DS.getTypeofParensRange());
5373 assert(DS.getRepAsType());
5374 TypeSourceInfo *TInfo = nullptr;
5375 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5376 TL.setUnderlyingTInfo(TInfo);
5378 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5379 // FIXME: This holds only because we only have one unary transform.
5380 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
5381 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5382 TL.setParensRange(DS.getTypeofParensRange());
5383 assert(DS.getRepAsType());
5384 TypeSourceInfo *TInfo = nullptr;
5385 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5386 TL.setUnderlyingTInfo(TInfo);
5388 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5389 // By default, use the source location of the type specifier.
5390 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
5391 if (TL.needsExtraLocalData()) {
5392 // Set info for the written builtin specifiers.
5393 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
5394 // Try to have a meaningful source location.
5395 if (TL.getWrittenSignSpec() != TSS_unspecified)
5396 TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
5397 if (TL.getWrittenWidthSpec() != TSW_unspecified)
5398 TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
5401 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5402 ElaboratedTypeKeyword Keyword
5403 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
5404 if (DS.getTypeSpecType() == TST_typename) {
5405 TypeSourceInfo *TInfo = nullptr;
5406 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5408 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
5412 TL.setElaboratedKeywordLoc(Keyword != ETK_None
5413 ? DS.getTypeSpecTypeLoc()
5414 : SourceLocation());
5415 const CXXScopeSpec& SS = DS.getTypeSpecScope();
5416 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5417 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
5419 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5420 assert(DS.getTypeSpecType() == TST_typename);
5421 TypeSourceInfo *TInfo = nullptr;
5422 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5424 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
5426 void VisitDependentTemplateSpecializationTypeLoc(
5427 DependentTemplateSpecializationTypeLoc TL) {
5428 assert(DS.getTypeSpecType() == TST_typename);
5429 TypeSourceInfo *TInfo = nullptr;
5430 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5433 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
5435 void VisitTagTypeLoc(TagTypeLoc TL) {
5436 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
5438 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5439 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
5440 // or an _Atomic qualifier.
5441 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
5442 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5443 TL.setParensRange(DS.getTypeofParensRange());
5445 TypeSourceInfo *TInfo = nullptr;
5446 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5448 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5450 TL.setKWLoc(DS.getAtomicSpecLoc());
5451 // No parens, to indicate this was spelled as an _Atomic qualifier.
5452 TL.setParensRange(SourceRange());
5453 Visit(TL.getValueLoc());
5457 void VisitPipeTypeLoc(PipeTypeLoc TL) {
5458 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5460 TypeSourceInfo *TInfo = nullptr;
5461 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5462 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5465 void VisitTypeLoc(TypeLoc TL) {
5466 // FIXME: add other typespec types and change this to an assert.
5467 TL.initialize(Context, DS.getTypeSpecTypeLoc());
5471 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
5472 ASTContext &Context;
5473 TypeProcessingState &State;
5474 const DeclaratorChunk &Chunk;
5477 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
5478 const DeclaratorChunk &Chunk)
5479 : Context(Context), State(State), Chunk(Chunk) {}
5481 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5482 llvm_unreachable("qualified type locs not expected here!");
5484 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5485 llvm_unreachable("decayed type locs not expected here!");
5488 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5489 fillAttributedTypeLoc(TL, State);
5491 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5494 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5495 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
5496 TL.setCaretLoc(Chunk.Loc);
5498 void VisitPointerTypeLoc(PointerTypeLoc TL) {
5499 assert(Chunk.Kind == DeclaratorChunk::Pointer);
5500 TL.setStarLoc(Chunk.Loc);
5502 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5503 assert(Chunk.Kind == DeclaratorChunk::Pointer);
5504 TL.setStarLoc(Chunk.Loc);
5506 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5507 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
5508 const CXXScopeSpec& SS = Chunk.Mem.Scope();
5509 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
5511 const Type* ClsTy = TL.getClass();
5512 QualType ClsQT = QualType(ClsTy, 0);
5513 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
5514 // Now copy source location info into the type loc component.
5515 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
5516 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
5517 case NestedNameSpecifier::Identifier:
5518 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
5520 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
5521 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
5522 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
5523 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
5527 case NestedNameSpecifier::TypeSpec:
5528 case NestedNameSpecifier::TypeSpecWithTemplate:
5529 if (isa<ElaboratedType>(ClsTy)) {
5530 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
5531 ETLoc.setElaboratedKeywordLoc(SourceLocation());
5532 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
5533 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
5534 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
5536 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
5540 case NestedNameSpecifier::Namespace:
5541 case NestedNameSpecifier::NamespaceAlias:
5542 case NestedNameSpecifier::Global:
5543 case NestedNameSpecifier::Super:
5544 llvm_unreachable("Nested-name-specifier must name a type");
5547 // Finally fill in MemberPointerLocInfo fields.
5548 TL.setStarLoc(Chunk.Loc);
5549 TL.setClassTInfo(ClsTInfo);
5551 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5552 assert(Chunk.Kind == DeclaratorChunk::Reference);
5553 // 'Amp' is misleading: this might have been originally
5554 /// spelled with AmpAmp.
5555 TL.setAmpLoc(Chunk.Loc);
5557 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5558 assert(Chunk.Kind == DeclaratorChunk::Reference);
5559 assert(!Chunk.Ref.LValueRef);
5560 TL.setAmpAmpLoc(Chunk.Loc);
5562 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
5563 assert(Chunk.Kind == DeclaratorChunk::Array);
5564 TL.setLBracketLoc(Chunk.Loc);
5565 TL.setRBracketLoc(Chunk.EndLoc);
5566 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
5568 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5569 assert(Chunk.Kind == DeclaratorChunk::Function);
5570 TL.setLocalRangeBegin(Chunk.Loc);
5571 TL.setLocalRangeEnd(Chunk.EndLoc);
5573 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
5574 TL.setLParenLoc(FTI.getLParenLoc());
5575 TL.setRParenLoc(FTI.getRParenLoc());
5576 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
5577 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5578 TL.setParam(tpi++, Param);
5580 TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
5582 void VisitParenTypeLoc(ParenTypeLoc TL) {
5583 assert(Chunk.Kind == DeclaratorChunk::Paren);
5584 TL.setLParenLoc(Chunk.Loc);
5585 TL.setRParenLoc(Chunk.EndLoc);
5587 void VisitPipeTypeLoc(PipeTypeLoc TL) {
5588 assert(Chunk.Kind == DeclaratorChunk::Pipe);
5589 TL.setKWLoc(Chunk.Loc);
5592 void VisitTypeLoc(TypeLoc TL) {
5593 llvm_unreachable("unsupported TypeLoc kind in declarator!");
5596 } // end anonymous namespace
5598 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5600 switch (Chunk.Kind) {
5601 case DeclaratorChunk::Function:
5602 case DeclaratorChunk::Array:
5603 case DeclaratorChunk::Paren:
5604 case DeclaratorChunk::Pipe:
5605 llvm_unreachable("cannot be _Atomic qualified");
5607 case DeclaratorChunk::Pointer:
5608 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
5611 case DeclaratorChunk::BlockPointer:
5612 case DeclaratorChunk::Reference:
5613 case DeclaratorChunk::MemberPointer:
5614 // FIXME: Provide a source location for the _Atomic keyword.
5619 ATL.setParensRange(SourceRange());
5623 fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL,
5624 const ParsedAttributesView &Attrs) {
5625 for (const ParsedAttr &AL : Attrs) {
5626 if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
5627 DASTL.setAttrNameLoc(AL.getLoc());
5628 DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
5629 DASTL.setAttrOperandParensRange(SourceRange());
5635 "no address_space attribute found at the expected location!");
5638 /// Create and instantiate a TypeSourceInfo with type source information.
5640 /// \param T QualType referring to the type as written in source code.
5642 /// \param ReturnTypeInfo For declarators whose return type does not show
5643 /// up in the normal place in the declaration specifiers (such as a C++
5644 /// conversion function), this pointer will refer to a type source information
5645 /// for that return type.
5646 static TypeSourceInfo *
5647 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
5648 QualType T, TypeSourceInfo *ReturnTypeInfo) {
5649 Sema &S = State.getSema();
5650 Declarator &D = State.getDeclarator();
5652 TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T);
5653 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
5655 // Handle parameter packs whose type is a pack expansion.
5656 if (isa<PackExpansionType>(T)) {
5657 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
5658 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5661 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5662 // An AtomicTypeLoc might be produced by an atomic qualifier in this
5663 // declarator chunk.
5664 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
5665 fillAtomicQualLoc(ATL, D.getTypeObject(i));
5666 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
5669 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
5670 fillAttributedTypeLoc(TL, State);
5671 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5674 while (DependentAddressSpaceTypeLoc TL =
5675 CurrTL.getAs<DependentAddressSpaceTypeLoc>()) {
5676 fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs());
5677 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
5680 // FIXME: Ordering here?
5681 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
5682 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5684 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
5685 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5688 // If we have different source information for the return type, use
5689 // that. This really only applies to C++ conversion functions.
5690 if (ReturnTypeInfo) {
5691 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
5692 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
5693 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
5695 TypeSpecLocFiller(S.Context, State, D.getDeclSpec()).Visit(CurrTL);
5701 /// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
5702 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
5703 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
5704 // and Sema during declaration parsing. Try deallocating/caching them when
5705 // it's appropriate, instead of allocating them and keeping them around.
5706 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
5708 new (LocT) LocInfoType(T, TInfo);
5709 assert(LocT->getTypeClass() != T->getTypeClass() &&
5710 "LocInfoType's TypeClass conflicts with an existing Type class");
5711 return ParsedType::make(QualType(LocT, 0));
5714 void LocInfoType::getAsStringInternal(std::string &Str,
5715 const PrintingPolicy &Policy) const {
5716 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
5717 " was used directly instead of getting the QualType through"
5718 " GetTypeFromParser");
5721 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
5722 // C99 6.7.6: Type names have no identifier. This is already validated by
5724 assert(D.getIdentifier() == nullptr &&
5725 "Type name should have no identifier!");
5727 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5728 QualType T = TInfo->getType();
5729 if (D.isInvalidType())
5732 // Make sure there are no unused decl attributes on the declarator.
5733 // We don't want to do this for ObjC parameters because we're going
5734 // to apply them to the actual parameter declaration.
5735 // Likewise, we don't want to do this for alias declarations, because
5736 // we are actually going to build a declaration from this eventually.
5737 if (D.getContext() != DeclaratorContext::ObjCParameterContext &&
5738 D.getContext() != DeclaratorContext::AliasDeclContext &&
5739 D.getContext() != DeclaratorContext::AliasTemplateContext)
5740 checkUnusedDeclAttributes(D);
5742 if (getLangOpts().CPlusPlus) {
5743 // Check that there are no default arguments (C++ only).
5744 CheckExtraCXXDefaultArguments(D);
5747 return CreateParsedType(T, TInfo);
5750 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
5751 QualType T = Context.getObjCInstanceType();
5752 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
5753 return CreateParsedType(T, TInfo);
5756 //===----------------------------------------------------------------------===//
5757 // Type Attribute Processing
5758 //===----------------------------------------------------------------------===//
5760 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression
5761 /// is uninstantiated. If instantiated it will apply the appropriate address space
5762 /// to the type. This function allows dependent template variables to be used in
5763 /// conjunction with the address_space attribute
5764 QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
5765 SourceLocation AttrLoc) {
5766 if (!AddrSpace->isValueDependent()) {
5768 llvm::APSInt addrSpace(32);
5769 if (!AddrSpace->isIntegerConstantExpr(addrSpace, Context)) {
5770 Diag(AttrLoc, diag::err_attribute_argument_type)
5771 << "'address_space'" << AANT_ArgumentIntegerConstant
5772 << AddrSpace->getSourceRange();
5777 if (addrSpace.isSigned()) {
5778 if (addrSpace.isNegative()) {
5779 Diag(AttrLoc, diag::err_attribute_address_space_negative)
5780 << AddrSpace->getSourceRange();
5783 addrSpace.setIsSigned(false);
5786 llvm::APSInt max(addrSpace.getBitWidth());
5788 Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace;
5789 if (addrSpace > max) {
5790 Diag(AttrLoc, diag::err_attribute_address_space_too_high)
5791 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
5796 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
5798 // If this type is already address space qualified with a different
5799 // address space, reject it.
5800 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
5801 // by qualifiers for two or more different address spaces."
5802 if (T.getAddressSpace() != LangAS::Default) {
5803 if (T.getAddressSpace() != ASIdx) {
5804 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
5807 // Emit a warning if they are identical; it's likely unintended.
5809 diag::warn_attribute_address_multiple_identical_qualifiers);
5812 return Context.getAddrSpaceQualType(T, ASIdx);
5815 // A check with similar intentions as checking if a type already has an
5816 // address space except for on a dependent types, basically if the
5817 // current type is already a DependentAddressSpaceType then its already
5818 // lined up to have another address space on it and we can't have
5819 // multiple address spaces on the one pointer indirection
5820 if (T->getAs<DependentAddressSpaceType>()) {
5821 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
5825 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
5828 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
5829 /// specified type. The attribute contains 1 argument, the id of the address
5830 /// space for the type.
5831 static void HandleAddressSpaceTypeAttribute(QualType &Type,
5832 const ParsedAttr &Attr,
5833 TypeProcessingState &State) {
5834 Sema &S = State.getSema();
5836 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
5837 // qualified by an address-space qualifier."
5838 if (Type->isFunctionType()) {
5839 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
5845 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
5847 // Check the attribute arguments.
5848 if (Attr.getNumArgs() != 1) {
5849 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
5856 if (Attr.isArgIdent(0)) {
5857 // Special case where the argument is a template id.
5859 SourceLocation TemplateKWLoc;
5861 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
5863 ExprResult AddrSpace = S.ActOnIdExpression(
5864 S.getCurScope(), SS, TemplateKWLoc, id, false, false);
5865 if (AddrSpace.isInvalid())
5868 ASArgExpr = static_cast<Expr *>(AddrSpace.get());
5870 ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5873 // Create the DependentAddressSpaceType or append an address space onto
5875 QualType T = S.BuildAddressSpaceAttr(Type, ASArgExpr, Attr.getLoc());
5878 ASTContext &Ctx = S.Context;
5879 auto *ASAttr = ::new (Ctx) AddressSpaceAttr(
5880 Attr.getRange(), Ctx, Attr.getAttributeSpellingListIndex(),
5881 static_cast<unsigned>(T.getQualifiers().getAddressSpace()));
5882 Type = State.getAttributedType(ASAttr, T, T);
5887 // The keyword-based type attributes imply which address space to use.
5888 switch (Attr.getKind()) {
5889 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
5890 ASIdx = LangAS::opencl_global; break;
5891 case ParsedAttr::AT_OpenCLLocalAddressSpace:
5892 ASIdx = LangAS::opencl_local; break;
5893 case ParsedAttr::AT_OpenCLConstantAddressSpace:
5894 ASIdx = LangAS::opencl_constant; break;
5895 case ParsedAttr::AT_OpenCLGenericAddressSpace:
5896 ASIdx = LangAS::opencl_generic; break;
5897 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
5898 ASIdx = LangAS::opencl_private; break;
5900 llvm_unreachable("Invalid address space");
5903 // If this type is already address space qualified with a different
5904 // address space, reject it.
5905 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
5906 // qualifiers for two or more different address spaces."
5907 if (Type.getAddressSpace() != LangAS::Default) {
5908 if (Type.getAddressSpace() != ASIdx) {
5909 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
5913 // Emit a warning if they are identical; it's likely unintended.
5914 S.Diag(Attr.getLoc(),
5915 diag::warn_attribute_address_multiple_identical_qualifiers);
5918 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
5922 /// Does this type have a "direct" ownership qualifier? That is,
5923 /// is it written like "__strong id", as opposed to something like
5924 /// "typeof(foo)", where that happens to be strong?
5925 static bool hasDirectOwnershipQualifier(QualType type) {
5926 // Fast path: no qualifier at all.
5927 assert(type.getQualifiers().hasObjCLifetime());
5931 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
5932 if (attr->getAttrKind() == attr::ObjCOwnership)
5935 type = attr->getModifiedType();
5937 // X *__strong (...)
5938 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
5939 type = paren->getInnerType();
5941 // That's it for things we want to complain about. In particular,
5942 // we do not want to look through typedefs, typeof(expr),
5943 // typeof(type), or any other way that the type is somehow
5952 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
5953 /// attribute on the specified type.
5955 /// Returns 'true' if the attribute was handled.
5956 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
5957 ParsedAttr &attr, QualType &type) {
5958 bool NonObjCPointer = false;
5960 if (!type->isDependentType() && !type->isUndeducedType()) {
5961 if (const PointerType *ptr = type->getAs<PointerType>()) {
5962 QualType pointee = ptr->getPointeeType();
5963 if (pointee->isObjCRetainableType() || pointee->isPointerType())
5965 // It is important not to lose the source info that there was an attribute
5966 // applied to non-objc pointer. We will create an attributed type but
5967 // its type will be the same as the original type.
5968 NonObjCPointer = true;
5969 } else if (!type->isObjCRetainableType()) {
5973 // Don't accept an ownership attribute in the declspec if it would
5974 // just be the return type of a block pointer.
5975 if (state.isProcessingDeclSpec()) {
5976 Declarator &D = state.getDeclarator();
5977 if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
5978 /*onlyBlockPointers=*/true))
5983 Sema &S = state.getSema();
5984 SourceLocation AttrLoc = attr.getLoc();
5985 if (AttrLoc.isMacroID())
5987 S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin();
5989 if (!attr.isArgIdent(0)) {
5990 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
5991 << AANT_ArgumentString;
5996 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5997 Qualifiers::ObjCLifetime lifetime;
5998 if (II->isStr("none"))
5999 lifetime = Qualifiers::OCL_ExplicitNone;
6000 else if (II->isStr("strong"))
6001 lifetime = Qualifiers::OCL_Strong;
6002 else if (II->isStr("weak"))
6003 lifetime = Qualifiers::OCL_Weak;
6004 else if (II->isStr("autoreleasing"))
6005 lifetime = Qualifiers::OCL_Autoreleasing;
6007 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
6008 << attr.getName() << II;
6013 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6014 // outside of ARC mode.
6015 if (!S.getLangOpts().ObjCAutoRefCount &&
6016 lifetime != Qualifiers::OCL_Weak &&
6017 lifetime != Qualifiers::OCL_ExplicitNone) {
6021 SplitQualType underlyingType = type.split();
6023 // Check for redundant/conflicting ownership qualifiers.
6024 if (Qualifiers::ObjCLifetime previousLifetime
6025 = type.getQualifiers().getObjCLifetime()) {
6026 // If it's written directly, that's an error.
6027 if (hasDirectOwnershipQualifier(type)) {
6028 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
6033 // Otherwise, if the qualifiers actually conflict, pull sugar off
6034 // and remove the ObjCLifetime qualifiers.
6035 if (previousLifetime != lifetime) {
6036 // It's possible to have multiple local ObjCLifetime qualifiers. We
6037 // can't stop after we reach a type that is directly qualified.
6038 const Type *prevTy = nullptr;
6039 while (!prevTy || prevTy != underlyingType.Ty) {
6040 prevTy = underlyingType.Ty;
6041 underlyingType = underlyingType.getSingleStepDesugaredType();
6043 underlyingType.Quals.removeObjCLifetime();
6047 underlyingType.Quals.addObjCLifetime(lifetime);
6049 if (NonObjCPointer) {
6050 StringRef name = attr.getName()->getName();
6052 case Qualifiers::OCL_None:
6053 case Qualifiers::OCL_ExplicitNone:
6055 case Qualifiers::OCL_Strong: name = "__strong"; break;
6056 case Qualifiers::OCL_Weak: name = "__weak"; break;
6057 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
6059 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
6060 << TDS_ObjCObjOrBlock << type;
6063 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
6064 // because having both 'T' and '__unsafe_unretained T' exist in the type
6065 // system causes unfortunate widespread consistency problems. (For example,
6066 // they're not considered compatible types, and we mangle them identicially
6067 // as template arguments.) These problems are all individually fixable,
6068 // but it's easier to just not add the qualifier and instead sniff it out
6069 // in specific places using isObjCInertUnsafeUnretainedType().
6071 // Doing this does means we miss some trivial consistency checks that
6072 // would've triggered in ARC, but that's better than trying to solve all
6073 // the coexistence problems with __unsafe_unretained.
6074 if (!S.getLangOpts().ObjCAutoRefCount &&
6075 lifetime == Qualifiers::OCL_ExplicitNone) {
6076 type = state.getAttributedType(
6077 createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr),
6082 QualType origType = type;
6083 if (!NonObjCPointer)
6084 type = S.Context.getQualifiedType(underlyingType);
6086 // If we have a valid source location for the attribute, use an
6087 // AttributedType instead.
6088 if (AttrLoc.isValid()) {
6089 type = state.getAttributedType(::new (S.Context) ObjCOwnershipAttr(
6090 attr.getRange(), S.Context, II,
6091 attr.getAttributeSpellingListIndex()),
6095 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
6096 unsigned diagnostic, QualType type) {
6097 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
6098 S.DelayedDiagnostics.add(
6099 sema::DelayedDiagnostic::makeForbiddenType(
6100 S.getSourceManager().getExpansionLoc(loc),
6101 diagnostic, type, /*ignored*/ 0));
6103 S.Diag(loc, diagnostic);
6107 // Sometimes, __weak isn't allowed.
6108 if (lifetime == Qualifiers::OCL_Weak &&
6109 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
6111 // Use a specialized diagnostic if the runtime just doesn't support them.
6112 unsigned diagnostic =
6113 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
6114 : diag::err_arc_weak_no_runtime);
6116 // In any case, delay the diagnostic until we know what we're parsing.
6117 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
6123 // Forbid __weak for class objects marked as
6124 // objc_arc_weak_reference_unavailable
6125 if (lifetime == Qualifiers::OCL_Weak) {
6126 if (const ObjCObjectPointerType *ObjT =
6127 type->getAs<ObjCObjectPointerType>()) {
6128 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
6129 if (Class->isArcWeakrefUnavailable()) {
6130 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
6131 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
6132 diag::note_class_declared);
6141 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
6142 /// attribute on the specified type. Returns true to indicate that
6143 /// the attribute was handled, false to indicate that the type does
6144 /// not permit the attribute.
6145 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
6147 Sema &S = state.getSema();
6149 // Delay if this isn't some kind of pointer.
6150 if (!type->isPointerType() &&
6151 !type->isObjCObjectPointerType() &&
6152 !type->isBlockPointerType())
6155 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
6156 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
6161 // Check the attribute arguments.
6162 if (!attr.isArgIdent(0)) {
6163 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
6164 << attr << AANT_ArgumentString;
6168 Qualifiers::GC GCAttr;
6169 if (attr.getNumArgs() > 1) {
6170 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
6176 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
6177 if (II->isStr("weak"))
6178 GCAttr = Qualifiers::Weak;
6179 else if (II->isStr("strong"))
6180 GCAttr = Qualifiers::Strong;
6182 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
6183 << attr.getName() << II;
6188 QualType origType = type;
6189 type = S.Context.getObjCGCQualType(origType, GCAttr);
6191 // Make an attributed type to preserve the source information.
6192 if (attr.getLoc().isValid())
6193 type = state.getAttributedType(
6194 ::new (S.Context) ObjCGCAttr(attr.getRange(), S.Context, II,
6195 attr.getAttributeSpellingListIndex()),
6202 /// A helper class to unwrap a type down to a function for the
6203 /// purposes of applying attributes there.
6206 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
6207 /// if (unwrapped.isFunctionType()) {
6208 /// const FunctionType *fn = unwrapped.get();
6209 /// // change fn somehow
6210 /// T = unwrapped.wrap(fn);
6212 struct FunctionTypeUnwrapper {
6224 const FunctionType *Fn;
6225 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
6227 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
6229 const Type *Ty = T.getTypePtr();
6230 if (isa<FunctionType>(Ty)) {
6231 Fn = cast<FunctionType>(Ty);
6233 } else if (isa<ParenType>(Ty)) {
6234 T = cast<ParenType>(Ty)->getInnerType();
6235 Stack.push_back(Parens);
6236 } else if (isa<PointerType>(Ty)) {
6237 T = cast<PointerType>(Ty)->getPointeeType();
6238 Stack.push_back(Pointer);
6239 } else if (isa<BlockPointerType>(Ty)) {
6240 T = cast<BlockPointerType>(Ty)->getPointeeType();
6241 Stack.push_back(BlockPointer);
6242 } else if (isa<MemberPointerType>(Ty)) {
6243 T = cast<MemberPointerType>(Ty)->getPointeeType();
6244 Stack.push_back(MemberPointer);
6245 } else if (isa<ReferenceType>(Ty)) {
6246 T = cast<ReferenceType>(Ty)->getPointeeType();
6247 Stack.push_back(Reference);
6248 } else if (isa<AttributedType>(Ty)) {
6249 T = cast<AttributedType>(Ty)->getEquivalentType();
6250 Stack.push_back(Attributed);
6252 const Type *DTy = Ty->getUnqualifiedDesugaredType();
6258 T = QualType(DTy, 0);
6259 Stack.push_back(Desugar);
6264 bool isFunctionType() const { return (Fn != nullptr); }
6265 const FunctionType *get() const { return Fn; }
6267 QualType wrap(Sema &S, const FunctionType *New) {
6268 // If T wasn't modified from the unwrapped type, do nothing.
6269 if (New == get()) return Original;
6272 return wrap(S.Context, Original, 0);
6276 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
6277 if (I == Stack.size())
6278 return C.getQualifiedType(Fn, Old.getQualifiers());
6280 // Build up the inner type, applying the qualifiers from the old
6281 // type to the new type.
6282 SplitQualType SplitOld = Old.split();
6284 // As a special case, tail-recurse if there are no qualifiers.
6285 if (SplitOld.Quals.empty())
6286 return wrap(C, SplitOld.Ty, I);
6287 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
6290 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
6291 if (I == Stack.size()) return QualType(Fn, 0);
6293 switch (static_cast<WrapKind>(Stack[I++])) {
6295 // This is the point at which we potentially lose source
6297 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
6300 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
6303 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
6304 return C.getParenType(New);
6308 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
6309 return C.getPointerType(New);
6312 case BlockPointer: {
6313 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
6314 return C.getBlockPointerType(New);
6317 case MemberPointer: {
6318 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
6319 QualType New = wrap(C, OldMPT->getPointeeType(), I);
6320 return C.getMemberPointerType(New, OldMPT->getClass());
6324 const ReferenceType *OldRef = cast<ReferenceType>(Old);
6325 QualType New = wrap(C, OldRef->getPointeeType(), I);
6326 if (isa<LValueReferenceType>(OldRef))
6327 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
6329 return C.getRValueReferenceType(New);
6333 llvm_unreachable("unknown wrapping kind");
6336 } // end anonymous namespace
6338 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
6339 ParsedAttr &PAttr, QualType &Type) {
6340 Sema &S = State.getSema();
6343 switch (PAttr.getKind()) {
6344 default: llvm_unreachable("Unknown attribute kind");
6345 case ParsedAttr::AT_Ptr32:
6346 A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr);
6348 case ParsedAttr::AT_Ptr64:
6349 A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr);
6351 case ParsedAttr::AT_SPtr:
6352 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
6354 case ParsedAttr::AT_UPtr:
6355 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
6359 attr::Kind NewAttrKind = A->getKind();
6360 QualType Desugared = Type;
6361 const AttributedType *AT = dyn_cast<AttributedType>(Type);
6363 attr::Kind CurAttrKind = AT->getAttrKind();
6365 // You cannot specify duplicate type attributes, so if the attribute has
6366 // already been applied, flag it.
6367 if (NewAttrKind == CurAttrKind) {
6368 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact)
6373 // You cannot have both __sptr and __uptr on the same type, nor can you
6374 // have __ptr32 and __ptr64.
6375 if ((CurAttrKind == attr::Ptr32 && NewAttrKind == attr::Ptr64) ||
6376 (CurAttrKind == attr::Ptr64 && NewAttrKind == attr::Ptr32)) {
6377 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
6378 << "'__ptr32'" << "'__ptr64'";
6380 } else if ((CurAttrKind == attr::SPtr && NewAttrKind == attr::UPtr) ||
6381 (CurAttrKind == attr::UPtr && NewAttrKind == attr::SPtr)) {
6382 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
6383 << "'__sptr'" << "'__uptr'";
6387 Desugared = AT->getEquivalentType();
6388 AT = dyn_cast<AttributedType>(Desugared);
6391 // Pointer type qualifiers can only operate on pointer types, but not
6392 // pointer-to-member types.
6394 // FIXME: Should we really be disallowing this attribute if there is any
6395 // type sugar between it and the pointer (other than attributes)? Eg, this
6396 // disallows the attribute on a parenthesized pointer.
6397 // And if so, should we really allow *any* type attribute?
6398 if (!isa<PointerType>(Desugared)) {
6399 if (Type->isMemberPointerType())
6400 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
6402 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
6406 Type = State.getAttributedType(A, Type, Type);
6410 /// Map a nullability attribute kind to a nullability kind.
6411 static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) {
6413 case ParsedAttr::AT_TypeNonNull:
6414 return NullabilityKind::NonNull;
6416 case ParsedAttr::AT_TypeNullable:
6417 return NullabilityKind::Nullable;
6419 case ParsedAttr::AT_TypeNullUnspecified:
6420 return NullabilityKind::Unspecified;
6423 llvm_unreachable("not a nullability attribute kind");
6427 /// Applies a nullability type specifier to the given type, if possible.
6429 /// \param state The type processing state.
6431 /// \param type The type to which the nullability specifier will be
6432 /// added. On success, this type will be updated appropriately.
6434 /// \param attr The attribute as written on the type.
6436 /// \param allowOnArrayType Whether to accept nullability specifiers on an
6437 /// array type (e.g., because it will decay to a pointer).
6439 /// \returns true if a problem has been diagnosed, false on success.
6440 static bool checkNullabilityTypeSpecifier(TypeProcessingState &state,
6443 bool allowOnArrayType) {
6444 Sema &S = state.getSema();
6446 NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind());
6447 SourceLocation nullabilityLoc = attr.getLoc();
6448 bool isContextSensitive = attr.isContextSensitiveKeywordAttribute();
6450 recordNullabilitySeen(S, nullabilityLoc);
6452 // Check for existing nullability attributes on the type.
6453 QualType desugared = type;
6454 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
6455 // Check whether there is already a null
6456 if (auto existingNullability = attributed->getImmediateNullability()) {
6457 // Duplicated nullability.
6458 if (nullability == *existingNullability) {
6459 S.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
6460 << DiagNullabilityKind(nullability, isContextSensitive)
6461 << FixItHint::CreateRemoval(nullabilityLoc);
6466 // Conflicting nullability.
6467 S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
6468 << DiagNullabilityKind(nullability, isContextSensitive)
6469 << DiagNullabilityKind(*existingNullability, false);
6473 desugared = attributed->getModifiedType();
6476 // If there is already a different nullability specifier, complain.
6477 // This (unlike the code above) looks through typedefs that might
6478 // have nullability specifiers on them, which means we cannot
6479 // provide a useful Fix-It.
6480 if (auto existingNullability = desugared->getNullability(S.Context)) {
6481 if (nullability != *existingNullability) {
6482 S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
6483 << DiagNullabilityKind(nullability, isContextSensitive)
6484 << DiagNullabilityKind(*existingNullability, false);
6486 // Try to find the typedef with the existing nullability specifier.
6487 if (auto typedefType = desugared->getAs<TypedefType>()) {
6488 TypedefNameDecl *typedefDecl = typedefType->getDecl();
6489 QualType underlyingType = typedefDecl->getUnderlyingType();
6490 if (auto typedefNullability
6491 = AttributedType::stripOuterNullability(underlyingType)) {
6492 if (*typedefNullability == *existingNullability) {
6493 S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
6494 << DiagNullabilityKind(*existingNullability, false);
6503 // If this definitely isn't a pointer type, reject the specifier.
6504 if (!desugared->canHaveNullability() &&
6505 !(allowOnArrayType && desugared->isArrayType())) {
6506 S.Diag(nullabilityLoc, diag::err_nullability_nonpointer)
6507 << DiagNullabilityKind(nullability, isContextSensitive) << type;
6511 // For the context-sensitive keywords/Objective-C property
6512 // attributes, require that the type be a single-level pointer.
6513 if (isContextSensitive) {
6514 // Make sure that the pointee isn't itself a pointer type.
6515 const Type *pointeeType;
6516 if (desugared->isArrayType())
6517 pointeeType = desugared->getArrayElementTypeNoTypeQual();
6519 pointeeType = desugared->getPointeeType().getTypePtr();
6521 if (pointeeType->isAnyPointerType() ||
6522 pointeeType->isObjCObjectPointerType() ||
6523 pointeeType->isMemberPointerType()) {
6524 S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
6525 << DiagNullabilityKind(nullability, true)
6527 S.Diag(nullabilityLoc, diag::note_nullability_type_specifier)
6528 << DiagNullabilityKind(nullability, false)
6530 << FixItHint::CreateReplacement(nullabilityLoc,
6531 getNullabilitySpelling(nullability));
6536 // Form the attributed type.
6537 type = state.getAttributedType(
6538 createNullabilityAttr(S.Context, attr, nullability), type, type);
6542 /// Check the application of the Objective-C '__kindof' qualifier to
6544 static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
6546 Sema &S = state.getSema();
6548 if (isa<ObjCTypeParamType>(type)) {
6549 // Build the attributed type to record where __kindof occurred.
6550 type = state.getAttributedType(
6551 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type);
6555 // Find out if it's an Objective-C object or object pointer type;
6556 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
6557 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
6558 : type->getAs<ObjCObjectType>();
6560 // If not, we can't apply __kindof.
6562 // FIXME: Handle dependent types that aren't yet object types.
6563 S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
6568 // Rebuild the "equivalent" type, which pushes __kindof down into
6570 // There is no need to apply kindof on an unqualified id type.
6571 QualType equivType = S.Context.getObjCObjectType(
6572 objType->getBaseType(), objType->getTypeArgsAsWritten(),
6573 objType->getProtocols(),
6574 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
6576 // If we started with an object pointer type, rebuild it.
6578 equivType = S.Context.getObjCObjectPointerType(equivType);
6579 if (auto nullability = type->getNullability(S.Context)) {
6580 // We create a nullability attribute from the __kindof attribute.
6581 // Make sure that will make sense.
6582 assert(attr.getAttributeSpellingListIndex() == 0 &&
6583 "multiple spellings for __kindof?");
6584 Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
6585 A->setImplicit(true);
6586 equivType = state.getAttributedType(A, equivType, equivType);
6590 // Build the attributed type to record where __kindof occurred.
6591 type = state.getAttributedType(
6592 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType);
6596 /// Distribute a nullability type attribute that cannot be applied to
6597 /// the type specifier to a pointer, block pointer, or member pointer
6598 /// declarator, complaining if necessary.
6600 /// \returns true if the nullability annotation was distributed, false
6602 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
6603 QualType type, ParsedAttr &attr) {
6604 Declarator &declarator = state.getDeclarator();
6606 /// Attempt to move the attribute to the specified chunk.
6607 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
6608 // If there is already a nullability attribute there, don't add
6610 if (hasNullabilityAttr(chunk.getAttrs()))
6613 // Complain about the nullability qualifier being in the wrong
6620 PK_MemberFunctionPointer,
6622 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
6624 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
6625 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
6627 auto diag = state.getSema().Diag(attr.getLoc(),
6628 diag::warn_nullability_declspec)
6629 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
6630 attr.isContextSensitiveKeywordAttribute())
6632 << static_cast<unsigned>(pointerKind);
6634 // FIXME: MemberPointer chunks don't carry the location of the *.
6635 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
6636 diag << FixItHint::CreateRemoval(attr.getLoc())
6637 << FixItHint::CreateInsertion(
6638 state.getSema().getPreprocessor()
6639 .getLocForEndOfToken(chunk.Loc),
6640 " " + attr.getName()->getName().str() + " ");
6643 moveAttrFromListToList(attr, state.getCurrentAttributes(),
6648 // Move it to the outermost pointer, member pointer, or block
6649 // pointer declarator.
6650 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
6651 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
6652 switch (chunk.Kind) {
6653 case DeclaratorChunk::Pointer:
6654 case DeclaratorChunk::BlockPointer:
6655 case DeclaratorChunk::MemberPointer:
6656 return moveToChunk(chunk, false);
6658 case DeclaratorChunk::Paren:
6659 case DeclaratorChunk::Array:
6662 case DeclaratorChunk::Function:
6663 // Try to move past the return type to a function/block/member
6664 // function pointer.
6665 if (DeclaratorChunk *dest = maybeMovePastReturnType(
6667 /*onlyBlockPointers=*/false)) {
6668 return moveToChunk(*dest, true);
6673 // Don't walk through these.
6674 case DeclaratorChunk::Reference:
6675 case DeclaratorChunk::Pipe:
6683 static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) {
6684 assert(!Attr.isInvalid());
6685 switch (Attr.getKind()) {
6687 llvm_unreachable("not a calling convention attribute");
6688 case ParsedAttr::AT_CDecl:
6689 return createSimpleAttr<CDeclAttr>(Ctx, Attr);
6690 case ParsedAttr::AT_FastCall:
6691 return createSimpleAttr<FastCallAttr>(Ctx, Attr);
6692 case ParsedAttr::AT_StdCall:
6693 return createSimpleAttr<StdCallAttr>(Ctx, Attr);
6694 case ParsedAttr::AT_ThisCall:
6695 return createSimpleAttr<ThisCallAttr>(Ctx, Attr);
6696 case ParsedAttr::AT_RegCall:
6697 return createSimpleAttr<RegCallAttr>(Ctx, Attr);
6698 case ParsedAttr::AT_Pascal:
6699 return createSimpleAttr<PascalAttr>(Ctx, Attr);
6700 case ParsedAttr::AT_SwiftCall:
6701 return createSimpleAttr<SwiftCallAttr>(Ctx, Attr);
6702 case ParsedAttr::AT_VectorCall:
6703 return createSimpleAttr<VectorCallAttr>(Ctx, Attr);
6704 case ParsedAttr::AT_AArch64VectorPcs:
6705 return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr);
6706 case ParsedAttr::AT_Pcs: {
6707 // The attribute may have had a fixit applied where we treated an
6708 // identifier as a string literal. The contents of the string are valid,
6709 // but the form may not be.
6711 if (Attr.isArgExpr(0))
6712 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
6714 Str = Attr.getArgAsIdent(0)->Ident->getName();
6715 PcsAttr::PCSType Type;
6716 if (!PcsAttr::ConvertStrToPCSType(Str, Type))
6717 llvm_unreachable("already validated the attribute");
6718 return ::new (Ctx) PcsAttr(Attr.getRange(), Ctx, Type,
6719 Attr.getAttributeSpellingListIndex());
6721 case ParsedAttr::AT_IntelOclBicc:
6722 return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr);
6723 case ParsedAttr::AT_MSABI:
6724 return createSimpleAttr<MSABIAttr>(Ctx, Attr);
6725 case ParsedAttr::AT_SysVABI:
6726 return createSimpleAttr<SysVABIAttr>(Ctx, Attr);
6727 case ParsedAttr::AT_PreserveMost:
6728 return createSimpleAttr<PreserveMostAttr>(Ctx, Attr);
6729 case ParsedAttr::AT_PreserveAll:
6730 return createSimpleAttr<PreserveAllAttr>(Ctx, Attr);
6732 llvm_unreachable("unexpected attribute kind!");
6735 /// Process an individual function attribute. Returns true to
6736 /// indicate that the attribute was handled, false if it wasn't.
6737 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
6739 Sema &S = state.getSema();
6741 FunctionTypeUnwrapper unwrapped(S, type);
6743 if (attr.getKind() == ParsedAttr::AT_NoReturn) {
6744 if (S.CheckAttrNoArgs(attr))
6747 // Delay if this is not a function type.
6748 if (!unwrapped.isFunctionType())
6751 // Otherwise we can process right away.
6752 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
6753 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6757 // ns_returns_retained is not always a type attribute, but if we got
6758 // here, we're treating it as one right now.
6759 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
6760 if (attr.getNumArgs()) return true;
6762 // Delay if this is not a function type.
6763 if (!unwrapped.isFunctionType())
6766 // Check whether the return type is reasonable.
6767 if (S.checkNSReturnsRetainedReturnType(attr.getLoc(),
6768 unwrapped.get()->getReturnType()))
6771 // Only actually change the underlying type in ARC builds.
6772 QualType origType = type;
6773 if (state.getSema().getLangOpts().ObjCAutoRefCount) {
6774 FunctionType::ExtInfo EI
6775 = unwrapped.get()->getExtInfo().withProducesResult(true);
6776 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6778 type = state.getAttributedType(
6779 createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr),
6784 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
6785 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
6788 // Delay if this is not a function type.
6789 if (!unwrapped.isFunctionType())
6792 FunctionType::ExtInfo EI =
6793 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
6794 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6798 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
6799 if (!S.getLangOpts().CFProtectionBranch) {
6800 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
6805 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
6808 // If this is not a function type, warning will be asserted by subject
6810 if (!unwrapped.isFunctionType())
6813 FunctionType::ExtInfo EI =
6814 unwrapped.get()->getExtInfo().withNoCfCheck(true);
6815 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6819 if (attr.getKind() == ParsedAttr::AT_Regparm) {
6821 if (S.CheckRegparmAttr(attr, value))
6824 // Delay if this is not a function type.
6825 if (!unwrapped.isFunctionType())
6828 // Diagnose regparm with fastcall.
6829 const FunctionType *fn = unwrapped.get();
6830 CallingConv CC = fn->getCallConv();
6831 if (CC == CC_X86FastCall) {
6832 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6833 << FunctionType::getNameForCallConv(CC)
6839 FunctionType::ExtInfo EI =
6840 unwrapped.get()->getExtInfo().withRegParm(value);
6841 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6845 // Delay if the type didn't work out to a function.
6846 if (!unwrapped.isFunctionType()) return false;
6848 // Otherwise, a calling convention.
6850 if (S.CheckCallingConvAttr(attr, CC))
6853 const FunctionType *fn = unwrapped.get();
6854 CallingConv CCOld = fn->getCallConv();
6855 Attr *CCAttr = getCCTypeAttr(S.Context, attr);
6858 // Error out on when there's already an attribute on the type
6859 // and the CCs don't match.
6860 if (S.getCallingConvAttributedType(type)) {
6861 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6862 << FunctionType::getNameForCallConv(CC)
6863 << FunctionType::getNameForCallConv(CCOld);
6869 // Diagnose use of variadic functions with calling conventions that
6870 // don't support them (e.g. because they're callee-cleanup).
6871 // We delay warning about this on unprototyped function declarations
6872 // until after redeclaration checking, just in case we pick up a
6873 // prototype that way. And apparently we also "delay" warning about
6874 // unprototyped function types in general, despite not necessarily having
6875 // much ability to diagnose it later.
6876 if (!supportsVariadicCall(CC)) {
6877 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
6878 if (FnP && FnP->isVariadic()) {
6879 unsigned DiagID = diag::err_cconv_varargs;
6881 // stdcall and fastcall are ignored with a warning for GCC and MS
6883 bool IsInvalid = true;
6884 if (CC == CC_X86StdCall || CC == CC_X86FastCall) {
6885 DiagID = diag::warn_cconv_varargs;
6889 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
6890 if (IsInvalid) attr.setInvalid();
6895 // Also diagnose fastcall with regparm.
6896 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
6897 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6898 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
6903 // Modify the CC from the wrapped function type, wrap it all back, and then
6904 // wrap the whole thing in an AttributedType as written. The modified type
6905 // might have a different CC if we ignored the attribute.
6906 QualType Equivalent;
6910 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
6912 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6914 type = state.getAttributedType(CCAttr, type, Equivalent);
6918 bool Sema::hasExplicitCallingConv(QualType &T) {
6919 QualType R = T.IgnoreParens();
6920 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
6921 if (AT->isCallingConv())
6923 R = AT->getModifiedType().IgnoreParens();
6928 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
6929 SourceLocation Loc) {
6930 FunctionTypeUnwrapper Unwrapped(*this, T);
6931 const FunctionType *FT = Unwrapped.get();
6932 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
6933 cast<FunctionProtoType>(FT)->isVariadic());
6934 CallingConv CurCC = FT->getCallConv();
6935 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
6940 // MS compiler ignores explicit calling convention attributes on structors. We
6941 // should do the same.
6942 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
6943 // Issue a warning on ignored calling convention -- except of __stdcall.
6944 // Again, this is what MS compiler does.
6945 if (CurCC != CC_X86StdCall)
6946 Diag(Loc, diag::warn_cconv_structors)
6947 << FunctionType::getNameForCallConv(CurCC);
6948 // Default adjustment.
6950 // Only adjust types with the default convention. For example, on Windows
6951 // we should adjust a __cdecl type to __thiscall for instance methods, and a
6952 // __thiscall type to __cdecl for static methods.
6953 CallingConv DefaultCC =
6954 Context.getDefaultCallingConvention(IsVariadic, IsStatic);
6956 if (CurCC != DefaultCC || DefaultCC == ToCC)
6959 if (hasExplicitCallingConv(T))
6963 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
6964 QualType Wrapped = Unwrapped.wrap(*this, FT);
6965 T = Context.getAdjustedType(T, Wrapped);
6968 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
6969 /// and float scalars, although arrays, pointers, and function return values are
6970 /// allowed in conjunction with this construct. Aggregates with this attribute
6971 /// are invalid, even if they are of the same size as a corresponding scalar.
6972 /// The raw attribute should contain precisely 1 argument, the vector size for
6973 /// the variable, measured in bytes. If curType and rawAttr are well formed,
6974 /// this routine will return a new vector type.
6975 static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
6977 // Check the attribute arguments.
6978 if (Attr.getNumArgs() != 1) {
6979 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
6986 // Special case where the argument is a template id.
6987 if (Attr.isArgIdent(0)) {
6989 SourceLocation TemplateKWLoc;
6991 Id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
6993 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
6996 if (Size.isInvalid())
6998 SizeExpr = Size.get();
7000 SizeExpr = Attr.getArgAsExpr(0);
7003 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
7010 /// Process the OpenCL-like ext_vector_type attribute when it occurs on
7012 static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
7014 // check the attribute arguments.
7015 if (Attr.getNumArgs() != 1) {
7016 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
7023 // Special case where the argument is a template id.
7024 if (Attr.isArgIdent(0)) {
7026 SourceLocation TemplateKWLoc;
7028 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
7030 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
7032 if (Size.isInvalid())
7035 sizeExpr = Size.get();
7037 sizeExpr = Attr.getArgAsExpr(0);
7040 // Create the vector type.
7041 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
7046 static bool isPermittedNeonBaseType(QualType &Ty,
7047 VectorType::VectorKind VecKind, Sema &S) {
7048 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
7052 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
7054 // Signed poly is mathematically wrong, but has been baked into some ABIs by
7056 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
7057 Triple.getArch() == llvm::Triple::aarch64_be;
7058 if (VecKind == VectorType::NeonPolyVector) {
7059 if (IsPolyUnsigned) {
7060 // AArch64 polynomial vectors are unsigned and support poly64.
7061 return BTy->getKind() == BuiltinType::UChar ||
7062 BTy->getKind() == BuiltinType::UShort ||
7063 BTy->getKind() == BuiltinType::ULong ||
7064 BTy->getKind() == BuiltinType::ULongLong;
7066 // AArch32 polynomial vector are signed.
7067 return BTy->getKind() == BuiltinType::SChar ||
7068 BTy->getKind() == BuiltinType::Short;
7072 // Non-polynomial vector types: the usual suspects are allowed, as well as
7073 // float64_t on AArch64.
7074 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
7075 Triple.getArch() == llvm::Triple::aarch64_be;
7077 if (Is64Bit && BTy->getKind() == BuiltinType::Double)
7080 return BTy->getKind() == BuiltinType::SChar ||
7081 BTy->getKind() == BuiltinType::UChar ||
7082 BTy->getKind() == BuiltinType::Short ||
7083 BTy->getKind() == BuiltinType::UShort ||
7084 BTy->getKind() == BuiltinType::Int ||
7085 BTy->getKind() == BuiltinType::UInt ||
7086 BTy->getKind() == BuiltinType::Long ||
7087 BTy->getKind() == BuiltinType::ULong ||
7088 BTy->getKind() == BuiltinType::LongLong ||
7089 BTy->getKind() == BuiltinType::ULongLong ||
7090 BTy->getKind() == BuiltinType::Float ||
7091 BTy->getKind() == BuiltinType::Half;
7094 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
7095 /// "neon_polyvector_type" attributes are used to create vector types that
7096 /// are mangled according to ARM's ABI. Otherwise, these types are identical
7097 /// to those created with the "vector_size" attribute. Unlike "vector_size"
7098 /// the argument to these Neon attributes is the number of vector elements,
7099 /// not the vector size in bytes. The vector width and element type must
7100 /// match one of the standard Neon vector types.
7101 static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
7102 Sema &S, VectorType::VectorKind VecKind) {
7103 // Target must have NEON
7104 if (!S.Context.getTargetInfo().hasFeature("neon")) {
7105 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr;
7109 // Check the attribute arguments.
7110 if (Attr.getNumArgs() != 1) {
7111 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
7116 // The number of elements must be an ICE.
7117 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
7118 llvm::APSInt numEltsInt(32);
7119 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
7120 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
7121 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
7122 << Attr << AANT_ArgumentIntegerConstant
7123 << numEltsExpr->getSourceRange();
7127 // Only certain element types are supported for Neon vectors.
7128 if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
7129 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
7134 // The total size of the vector must be 64 or 128 bits.
7135 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
7136 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
7137 unsigned vecSize = typeSize * numElts;
7138 if (vecSize != 64 && vecSize != 128) {
7139 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
7144 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
7147 /// Handle OpenCL Access Qualifier Attribute.
7148 static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
7150 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
7151 if (!(CurType->isImageType() || CurType->isPipeType())) {
7152 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
7157 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
7158 QualType BaseTy = TypedefTy->desugar();
7160 std::string PrevAccessQual;
7161 if (BaseTy->isPipeType()) {
7162 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
7163 OpenCLAccessAttr *Attr =
7164 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
7165 PrevAccessQual = Attr->getSpelling();
7167 PrevAccessQual = "read_only";
7169 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
7171 switch (ImgType->getKind()) {
7172 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7173 case BuiltinType::Id: \
7174 PrevAccessQual = #Access; \
7176 #include "clang/Basic/OpenCLImageTypes.def"
7178 llvm_unreachable("Unable to find corresponding image type.");
7181 llvm_unreachable("unexpected type");
7183 StringRef AttrName = Attr.getName()->getName();
7184 if (PrevAccessQual == AttrName.ltrim("_")) {
7185 // Duplicated qualifiers
7186 S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
7187 << AttrName << Attr.getRange();
7189 // Contradicting qualifiers
7190 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
7193 S.Diag(TypedefTy->getDecl()->getBeginLoc(),
7194 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
7195 } else if (CurType->isPipeType()) {
7196 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
7197 QualType ElemType = CurType->getAs<PipeType>()->getElementType();
7198 CurType = S.Context.getWritePipeType(ElemType);
7203 static void deduceOpenCLImplicitAddrSpace(TypeProcessingState &State,
7204 QualType &T, TypeAttrLocation TAL) {
7205 Declarator &D = State.getDeclarator();
7207 // Handle the cases where address space should not be deduced.
7209 // The pointee type of a pointer type is always deduced since a pointer always
7210 // points to some memory location which should has an address space.
7212 // There are situations that at the point of certain declarations, the address
7213 // space may be unknown and better to be left as default. For example, when
7214 // defining a typedef or struct type, they are not associated with any
7215 // specific address space. Later on, they may be used with any address space
7216 // to declare a variable.
7218 // The return value of a function is r-value, therefore should not have
7221 // The void type does not occupy memory, therefore should not have address
7222 // space, except when it is used as a pointee type.
7224 // Since LLVM assumes function type is in default address space, it should not
7225 // have address space.
7226 auto ChunkIndex = State.getCurrentChunkIndex();
7229 (D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Pointer ||
7230 D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::BlockPointer ||
7231 D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Reference);
7232 bool IsFuncReturnType =
7234 D.getTypeObject(ChunkIndex - 1).Kind == DeclaratorChunk::Function;
7236 ChunkIndex < D.getNumTypeObjects() &&
7237 D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function;
7238 if ( // Do not deduce addr space for function return type and function type,
7239 // otherwise it will fail some sema check.
7240 IsFuncReturnType || IsFuncType ||
7241 // Do not deduce addr space for member types of struct, except the pointee
7242 // type of a pointer member type.
7243 (D.getContext() == DeclaratorContext::MemberContext && !IsPointee) ||
7244 // Do not deduce addr space for types used to define a typedef and the
7245 // typedef itself, except the pointee type of a pointer type which is used
7246 // to define the typedef.
7247 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef &&
7249 // Do not deduce addr space of the void type, e.g. in f(void), otherwise
7250 // it will fail some sema check.
7251 (T->isVoidType() && !IsPointee) ||
7252 // Do not deduce address spaces for dependent types because they might end
7253 // up instantiating to a type with an explicit address space qualifier.
7254 T->isDependentType())
7257 LangAS ImpAddr = LangAS::Default;
7258 // Put OpenCL automatic variable in private address space.
7259 // OpenCL v1.2 s6.5:
7260 // The default address space name for arguments to a function in a
7261 // program, or local variables of a function is __private. All function
7262 // arguments shall be in the __private address space.
7263 if (State.getSema().getLangOpts().OpenCLVersion <= 120 &&
7264 !State.getSema().getLangOpts().OpenCLCPlusPlus) {
7265 ImpAddr = LangAS::opencl_private;
7267 // If address space is not set, OpenCL 2.0 defines non private default
7268 // address spaces for some cases:
7269 // OpenCL 2.0, section 6.5:
7270 // The address space for a variable at program scope or a static variable
7271 // inside a function can either be __global or __constant, but defaults to
7272 // __global if not specified.
7274 // Pointers that are declared without pointing to a named address space
7275 // point to the generic address space.
7277 ImpAddr = LangAS::opencl_generic;
7279 if (D.getContext() == DeclaratorContext::TemplateArgContext) {
7280 // Do not deduce address space for non-pointee type in template arg.
7281 } else if (D.getContext() == DeclaratorContext::FileContext) {
7282 ImpAddr = LangAS::opencl_global;
7284 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
7285 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern) {
7286 ImpAddr = LangAS::opencl_global;
7288 ImpAddr = LangAS::opencl_private;
7293 T = State.getSema().Context.getAddrSpaceQualType(T, ImpAddr);
7296 static void HandleLifetimeBoundAttr(TypeProcessingState &State,
7299 if (State.getDeclarator().isDeclarationOfFunction()) {
7300 CurType = State.getAttributedType(
7301 createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
7304 Attr.diagnoseAppertainsTo(State.getSema(), nullptr);
7309 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
7310 TypeAttrLocation TAL,
7311 ParsedAttributesView &attrs) {
7312 // Scan through and apply attributes to this type where it makes sense. Some
7313 // attributes (such as __address_space__, __vector_size__, etc) apply to the
7314 // type, but others can be present in the type specifiers even though they
7315 // apply to the decl. Here we apply type attributes and ignore the rest.
7317 // This loop modifies the list pretty frequently, but we still need to make
7318 // sure we visit every element once. Copy the attributes list, and iterate
7320 ParsedAttributesView AttrsCopy{attrs};
7322 state.setParsedNoDeref(false);
7324 for (ParsedAttr &attr : AttrsCopy) {
7326 // Skip attributes that were marked to be invalid.
7327 if (attr.isInvalid())
7330 if (attr.isCXX11Attribute()) {
7331 // [[gnu::...]] attributes are treated as declaration attributes, so may
7332 // not appertain to a DeclaratorChunk. If we handle them as type
7333 // attributes, accept them in that position and diagnose the GCC
7335 if (attr.isGNUScope()) {
7336 bool IsTypeAttr = attr.isTypeAttr();
7337 if (TAL == TAL_DeclChunk) {
7338 state.getSema().Diag(attr.getLoc(),
7340 ? diag::warn_gcc_ignores_type_attr
7341 : diag::warn_cxx11_gnu_attribute_on_type)
7346 } else if (TAL != TAL_DeclChunk) {
7347 // Otherwise, only consider type processing for a C++11 attribute if
7348 // it's actually been applied to a type.
7353 // If this is an attribute we can handle, do so now,
7354 // otherwise, add it to the FnAttrs list for rechaining.
7355 switch (attr.getKind()) {
7357 // A C++11 attribute on a declarator chunk must appertain to a type.
7358 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
7359 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
7361 attr.setUsedAsTypeAttr();
7365 case ParsedAttr::UnknownAttribute:
7366 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
7367 state.getSema().Diag(attr.getLoc(),
7368 diag::warn_unknown_attribute_ignored)
7372 case ParsedAttr::IgnoredAttribute:
7375 case ParsedAttr::AT_MayAlias:
7376 // FIXME: This attribute needs to actually be handled, but if we ignore
7377 // it it breaks large amounts of Linux software.
7378 attr.setUsedAsTypeAttr();
7380 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
7381 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
7382 case ParsedAttr::AT_OpenCLLocalAddressSpace:
7383 case ParsedAttr::AT_OpenCLConstantAddressSpace:
7384 case ParsedAttr::AT_OpenCLGenericAddressSpace:
7385 case ParsedAttr::AT_AddressSpace:
7386 HandleAddressSpaceTypeAttribute(type, attr, state);
7387 attr.setUsedAsTypeAttr();
7389 OBJC_POINTER_TYPE_ATTRS_CASELIST:
7390 if (!handleObjCPointerTypeAttr(state, attr, type))
7391 distributeObjCPointerTypeAttr(state, attr, type);
7392 attr.setUsedAsTypeAttr();
7394 case ParsedAttr::AT_VectorSize:
7395 HandleVectorSizeAttr(type, attr, state.getSema());
7396 attr.setUsedAsTypeAttr();
7398 case ParsedAttr::AT_ExtVectorType:
7399 HandleExtVectorTypeAttr(type, attr, state.getSema());
7400 attr.setUsedAsTypeAttr();
7402 case ParsedAttr::AT_NeonVectorType:
7403 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
7404 VectorType::NeonVector);
7405 attr.setUsedAsTypeAttr();
7407 case ParsedAttr::AT_NeonPolyVectorType:
7408 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
7409 VectorType::NeonPolyVector);
7410 attr.setUsedAsTypeAttr();
7412 case ParsedAttr::AT_OpenCLAccess:
7413 HandleOpenCLAccessAttr(type, attr, state.getSema());
7414 attr.setUsedAsTypeAttr();
7416 case ParsedAttr::AT_LifetimeBound:
7417 if (TAL == TAL_DeclChunk)
7418 HandleLifetimeBoundAttr(state, type, attr);
7421 case ParsedAttr::AT_NoDeref: {
7422 ASTContext &Ctx = state.getSema().Context;
7423 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
7425 attr.setUsedAsTypeAttr();
7426 state.setParsedNoDeref(true);
7430 MS_TYPE_ATTRS_CASELIST:
7431 if (!handleMSPointerTypeQualifierAttr(state, attr, type))
7432 attr.setUsedAsTypeAttr();
7436 NULLABILITY_TYPE_ATTRS_CASELIST:
7437 // Either add nullability here or try to distribute it. We
7438 // don't want to distribute the nullability specifier past any
7439 // dependent type, because that complicates the user model.
7440 if (type->canHaveNullability() || type->isDependentType() ||
7441 type->isArrayType() ||
7442 !distributeNullabilityTypeAttr(state, type, attr)) {
7444 if (TAL == TAL_DeclChunk)
7445 endIndex = state.getCurrentChunkIndex();
7447 endIndex = state.getDeclarator().getNumTypeObjects();
7448 bool allowOnArrayType =
7449 state.getDeclarator().isPrototypeContext() &&
7450 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
7451 if (checkNullabilityTypeSpecifier(
7455 allowOnArrayType)) {
7459 attr.setUsedAsTypeAttr();
7463 case ParsedAttr::AT_ObjCKindOf:
7464 // '__kindof' must be part of the decl-specifiers.
7471 state.getSema().Diag(attr.getLoc(),
7472 diag::err_objc_kindof_wrong_position)
7473 << FixItHint::CreateRemoval(attr.getLoc())
7474 << FixItHint::CreateInsertion(
7475 state.getDeclarator().getDeclSpec().getBeginLoc(),
7480 // Apply it regardless.
7481 if (checkObjCKindOfType(state, type, attr))
7485 FUNCTION_TYPE_ATTRS_CASELIST:
7486 attr.setUsedAsTypeAttr();
7488 // Never process function type attributes as part of the
7489 // declaration-specifiers.
7490 if (TAL == TAL_DeclSpec)
7491 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
7493 // Otherwise, handle the possible delays.
7494 else if (!handleFunctionTypeAttr(state, attr, type))
7495 distributeFunctionTypeAttr(state, attr, type);
7500 if (!state.getSema().getLangOpts().OpenCL ||
7501 type.getAddressSpace() != LangAS::Default)
7504 deduceOpenCLImplicitAddrSpace(state, type, TAL);
7507 void Sema::completeExprArrayBound(Expr *E) {
7508 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
7509 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
7510 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
7511 auto *Def = Var->getDefinition();
7513 SourceLocation PointOfInstantiation = E->getExprLoc();
7514 InstantiateVariableDefinition(PointOfInstantiation, Var);
7515 Def = Var->getDefinition();
7517 // If we don't already have a point of instantiation, and we managed
7518 // to instantiate a definition, this is the point of instantiation.
7519 // Otherwise, we don't request an end-of-TU instantiation, so this is
7520 // not a point of instantiation.
7521 // FIXME: Is this really the right behavior?
7522 if (Var->getPointOfInstantiation().isInvalid() && Def) {
7523 assert(Var->getTemplateSpecializationKind() ==
7524 TSK_ImplicitInstantiation &&
7525 "explicit instantiation with no point of instantiation");
7526 Var->setTemplateSpecializationKind(
7527 Var->getTemplateSpecializationKind(), PointOfInstantiation);
7531 // Update the type to the definition's type both here and within the
7535 QualType T = Def->getType();
7537 // FIXME: Update the type on all intervening expressions.
7541 // We still go on to try to complete the type independently, as it
7542 // may also require instantiations or diagnostics if it remains
7549 /// Ensure that the type of the given expression is complete.
7551 /// This routine checks whether the expression \p E has a complete type. If the
7552 /// expression refers to an instantiable construct, that instantiation is
7553 /// performed as needed to complete its type. Furthermore
7554 /// Sema::RequireCompleteType is called for the expression's type (or in the
7555 /// case of a reference type, the referred-to type).
7557 /// \param E The expression whose type is required to be complete.
7558 /// \param Diagnoser The object that will emit a diagnostic if the type is
7561 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
7563 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) {
7564 QualType T = E->getType();
7566 // Incomplete array types may be completed by the initializer attached to
7567 // their definitions. For static data members of class templates and for
7568 // variable templates, we need to instantiate the definition to get this
7569 // initializer and complete the type.
7570 if (T->isIncompleteArrayType()) {
7571 completeExprArrayBound(E);
7575 // FIXME: Are there other cases which require instantiating something other
7576 // than the type to complete the type of an expression?
7578 return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
7581 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
7582 BoundTypeDiagnoser<> Diagnoser(DiagID);
7583 return RequireCompleteExprType(E, Diagnoser);
7586 /// Ensure that the type T is a complete type.
7588 /// This routine checks whether the type @p T is complete in any
7589 /// context where a complete type is required. If @p T is a complete
7590 /// type, returns false. If @p T is a class template specialization,
7591 /// this routine then attempts to perform class template
7592 /// instantiation. If instantiation fails, or if @p T is incomplete
7593 /// and cannot be completed, issues the diagnostic @p diag (giving it
7594 /// the type @p T) and returns true.
7596 /// @param Loc The location in the source that the incomplete type
7597 /// diagnostic should refer to.
7599 /// @param T The type that this routine is examining for completeness.
7601 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
7602 /// @c false otherwise.
7603 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7604 TypeDiagnoser &Diagnoser) {
7605 if (RequireCompleteTypeImpl(Loc, T, &Diagnoser))
7607 if (const TagType *Tag = T->getAs<TagType>()) {
7608 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
7609 Tag->getDecl()->setCompleteDefinitionRequired();
7610 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
7616 bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) {
7617 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
7621 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
7622 // and isolate from other C++ specific checks.
7623 StructuralEquivalenceContext Ctx(
7624 D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls,
7625 StructuralEquivalenceKind::Default,
7626 false /*StrictTypeSpelling*/, true /*Complain*/,
7627 true /*ErrorOnTagTypeMismatch*/);
7628 return Ctx.IsEquivalent(D, Suggested);
7631 /// Determine whether there is any declaration of \p D that was ever a
7632 /// definition (perhaps before module merging) and is currently visible.
7633 /// \param D The definition of the entity.
7634 /// \param Suggested Filled in with the declaration that should be made visible
7635 /// in order to provide a definition of this entity.
7636 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
7637 /// not defined. This only matters for enums with a fixed underlying
7638 /// type, since in all other cases, a type is complete if and only if it
7640 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
7641 bool OnlyNeedComplete) {
7642 // Easy case: if we don't have modules, all declarations are visible.
7643 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
7646 // If this definition was instantiated from a template, map back to the
7647 // pattern from which it was instantiated.
7648 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
7649 // We're in the middle of defining it; this definition should be treated
7652 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
7653 if (auto *Pattern = RD->getTemplateInstantiationPattern())
7655 D = RD->getDefinition();
7656 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
7657 if (auto *Pattern = ED->getTemplateInstantiationPattern())
7659 if (OnlyNeedComplete && ED->isFixed()) {
7660 // If the enum has a fixed underlying type, and we're only looking for a
7661 // complete type (not a definition), any visible declaration of it will
7663 *Suggested = nullptr;
7664 for (auto *Redecl : ED->redecls()) {
7665 if (isVisible(Redecl))
7667 if (Redecl->isThisDeclarationADefinition() ||
7668 (Redecl->isCanonicalDecl() && !*Suggested))
7669 *Suggested = Redecl;
7673 D = ED->getDefinition();
7674 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7675 if (auto *Pattern = FD->getTemplateInstantiationPattern())
7677 D = FD->getDefinition();
7678 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
7679 if (auto *Pattern = VD->getTemplateInstantiationPattern())
7681 D = VD->getDefinition();
7683 assert(D && "missing definition for pattern of instantiated definition");
7687 auto DefinitionIsVisible = [&] {
7688 // The (primary) definition might be in a visible module.
7692 // A visible module might have a merged definition instead.
7693 if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D)
7694 : hasVisibleMergedDefinition(D)) {
7695 if (CodeSynthesisContexts.empty() &&
7696 !getLangOpts().ModulesLocalVisibility) {
7697 // Cache the fact that this definition is implicitly visible because
7698 // there is a visible merged definition.
7699 D->setVisibleDespiteOwningModule();
7707 if (DefinitionIsVisible())
7710 // The external source may have additional definitions of this entity that are
7711 // visible, so complete the redeclaration chain now and ask again.
7712 if (auto *Source = Context.getExternalSource()) {
7713 Source->CompleteRedeclChain(D);
7714 return DefinitionIsVisible();
7720 /// Locks in the inheritance model for the given class and all of its bases.
7721 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
7722 RD = RD->getMostRecentNonInjectedDecl();
7723 if (!RD->hasAttr<MSInheritanceAttr>()) {
7724 MSInheritanceAttr::Spelling IM;
7726 switch (S.MSPointerToMemberRepresentationMethod) {
7727 case LangOptions::PPTMK_BestCase:
7728 IM = RD->calculateInheritanceModel();
7730 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
7731 IM = MSInheritanceAttr::Keyword_single_inheritance;
7733 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
7734 IM = MSInheritanceAttr::Keyword_multiple_inheritance;
7736 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
7737 IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
7741 RD->addAttr(MSInheritanceAttr::CreateImplicit(
7742 S.getASTContext(), IM,
7743 /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
7744 LangOptions::PPTMK_BestCase,
7745 S.ImplicitMSInheritanceAttrLoc.isValid()
7746 ? S.ImplicitMSInheritanceAttrLoc
7747 : RD->getSourceRange()));
7748 S.Consumer.AssignInheritanceModel(RD);
7752 /// The implementation of RequireCompleteType
7753 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
7754 TypeDiagnoser *Diagnoser) {
7755 // FIXME: Add this assertion to make sure we always get instantiation points.
7756 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
7757 // FIXME: Add this assertion to help us flush out problems with
7758 // checking for dependent types and type-dependent expressions.
7760 // assert(!T->isDependentType() &&
7761 // "Can't ask whether a dependent type is complete");
7763 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
7764 if (!MPTy->getClass()->isDependentType()) {
7765 if (getLangOpts().CompleteMemberPointers &&
7766 !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() &&
7767 RequireCompleteType(Loc, QualType(MPTy->getClass(), 0),
7768 diag::err_memptr_incomplete))
7771 // We lock in the inheritance model once somebody has asked us to ensure
7772 // that a pointer-to-member type is complete.
7773 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7774 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
7775 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
7780 NamedDecl *Def = nullptr;
7781 bool Incomplete = T->isIncompleteType(&Def);
7783 // Check that any necessary explicit specializations are visible. For an
7784 // enum, we just need the declaration, so don't check this.
7785 if (Def && !isa<EnumDecl>(Def))
7786 checkSpecializationVisibility(Loc, Def);
7788 // If we have a complete type, we're done.
7790 // If we know about the definition but it is not visible, complain.
7791 NamedDecl *SuggestedDef = nullptr;
7793 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
7794 // If the user is going to see an error here, recover by making the
7795 // definition visible.
7796 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
7797 if (Diagnoser && SuggestedDef)
7798 diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition,
7799 /*Recover*/TreatAsComplete);
7800 return !TreatAsComplete;
7801 } else if (Def && !TemplateInstCallbacks.empty()) {
7802 CodeSynthesisContext TempInst;
7803 TempInst.Kind = CodeSynthesisContext::Memoization;
7804 TempInst.Template = Def;
7805 TempInst.Entity = Def;
7806 TempInst.PointOfInstantiation = Loc;
7807 atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
7808 atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
7814 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
7815 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
7817 // Give the external source a chance to provide a definition of the type.
7818 // This is kept separate from completing the redeclaration chain so that
7819 // external sources such as LLDB can avoid synthesizing a type definition
7820 // unless it's actually needed.
7822 // Avoid diagnosing invalid decls as incomplete.
7823 if (Def->isInvalidDecl())
7826 // Give the external AST source a chance to complete the type.
7827 if (auto *Source = Context.getExternalSource()) {
7828 if (Tag && Tag->hasExternalLexicalStorage())
7829 Source->CompleteType(Tag);
7830 if (IFace && IFace->hasExternalLexicalStorage())
7831 Source->CompleteType(IFace);
7832 // If the external source completed the type, go through the motions
7833 // again to ensure we're allowed to use the completed type.
7834 if (!T->isIncompleteType())
7835 return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7839 // If we have a class template specialization or a class member of a
7840 // class template specialization, or an array with known size of such,
7841 // try to instantiate it.
7842 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
7843 bool Instantiated = false;
7844 bool Diagnosed = false;
7845 if (RD->isDependentContext()) {
7846 // Don't try to instantiate a dependent class (eg, a member template of
7847 // an instantiated class template specialization).
7848 // FIXME: Can this ever happen?
7849 } else if (auto *ClassTemplateSpec =
7850 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
7851 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
7852 Diagnosed = InstantiateClassTemplateSpecialization(
7853 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
7854 /*Complain=*/Diagnoser);
7855 Instantiated = true;
7858 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
7859 if (!RD->isBeingDefined() && Pattern) {
7860 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
7861 assert(MSI && "Missing member specialization information?");
7862 // This record was instantiated from a class within a template.
7863 if (MSI->getTemplateSpecializationKind() !=
7864 TSK_ExplicitSpecialization) {
7865 Diagnosed = InstantiateClass(Loc, RD, Pattern,
7866 getTemplateInstantiationArgs(RD),
7867 TSK_ImplicitInstantiation,
7868 /*Complain=*/Diagnoser);
7869 Instantiated = true;
7875 // Instantiate* might have already complained that the template is not
7876 // defined, if we asked it to.
7877 if (Diagnoser && Diagnosed)
7879 // If we instantiated a definition, check that it's usable, even if
7880 // instantiation produced an error, so that repeated calls to this
7881 // function give consistent answers.
7882 if (!T->isIncompleteType())
7883 return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7887 // FIXME: If we didn't instantiate a definition because of an explicit
7888 // specialization declaration, check that it's visible.
7893 Diagnoser->diagnose(*this, Loc, T);
7895 // If the type was a forward declaration of a class/struct/union
7896 // type, produce a note.
7897 if (Tag && !Tag->isInvalidDecl())
7898 Diag(Tag->getLocation(),
7899 Tag->isBeingDefined() ? diag::note_type_being_defined
7900 : diag::note_forward_declaration)
7901 << Context.getTagDeclType(Tag);
7903 // If the Objective-C class was a forward declaration, produce a note.
7904 if (IFace && !IFace->isInvalidDecl())
7905 Diag(IFace->getLocation(), diag::note_forward_class);
7907 // If we have external information that we can use to suggest a fix,
7910 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
7915 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7917 BoundTypeDiagnoser<> Diagnoser(DiagID);
7918 return RequireCompleteType(Loc, T, Diagnoser);
7921 /// Get diagnostic %select index for tag kind for
7922 /// literal type diagnostic message.
7923 /// WARNING: Indexes apply to particular diagnostics only!
7925 /// \returns diagnostic %select index.
7926 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
7928 case TTK_Struct: return 0;
7929 case TTK_Interface: return 1;
7930 case TTK_Class: return 2;
7931 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
7935 /// Ensure that the type T is a literal type.
7937 /// This routine checks whether the type @p T is a literal type. If @p T is an
7938 /// incomplete type, an attempt is made to complete it. If @p T is a literal
7939 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
7940 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
7941 /// it the type @p T), along with notes explaining why the type is not a
7942 /// literal type, and returns true.
7944 /// @param Loc The location in the source that the non-literal type
7945 /// diagnostic should refer to.
7947 /// @param T The type that this routine is examining for literalness.
7949 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
7951 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
7952 /// @c false otherwise.
7953 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
7954 TypeDiagnoser &Diagnoser) {
7955 assert(!T->isDependentType() && "type should not be dependent");
7957 QualType ElemType = Context.getBaseElementType(T);
7958 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
7959 T->isLiteralType(Context))
7962 Diagnoser.diagnose(*this, Loc, T);
7964 if (T->isVariableArrayType())
7967 const RecordType *RT = ElemType->getAs<RecordType>();
7971 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7973 // A partially-defined class type can't be a literal type, because a literal
7974 // class type must have a trivial destructor (which can't be checked until
7975 // the class definition is complete).
7976 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
7979 // [expr.prim.lambda]p3:
7980 // This class type is [not] a literal type.
7981 if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
7982 Diag(RD->getLocation(), diag::note_non_literal_lambda);
7986 // If the class has virtual base classes, then it's not an aggregate, and
7987 // cannot have any constexpr constructors or a trivial default constructor,
7988 // so is non-literal. This is better to diagnose than the resulting absence
7989 // of constexpr constructors.
7990 if (RD->getNumVBases()) {
7991 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
7992 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
7993 for (const auto &I : RD->vbases())
7994 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
7995 << I.getSourceRange();
7996 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
7997 !RD->hasTrivialDefaultConstructor()) {
7998 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
7999 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
8000 for (const auto &I : RD->bases()) {
8001 if (!I.getType()->isLiteralType(Context)) {
8002 Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
8003 << RD << I.getType() << I.getSourceRange();
8007 for (const auto *I : RD->fields()) {
8008 if (!I->getType()->isLiteralType(Context) ||
8009 I->getType().isVolatileQualified()) {
8010 Diag(I->getLocation(), diag::note_non_literal_field)
8011 << RD << I << I->getType()
8012 << I->getType().isVolatileQualified();
8016 } else if (!RD->hasTrivialDestructor()) {
8017 // All fields and bases are of literal types, so have trivial destructors.
8018 // If this class's destructor is non-trivial it must be user-declared.
8019 CXXDestructorDecl *Dtor = RD->getDestructor();
8020 assert(Dtor && "class has literal fields and bases but no dtor?");
8024 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
8025 diag::note_non_literal_user_provided_dtor :
8026 diag::note_non_literal_nontrivial_dtor) << RD;
8027 if (!Dtor->isUserProvided())
8028 SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI,
8035 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
8036 BoundTypeDiagnoser<> Diagnoser(DiagID);
8037 return RequireLiteralType(Loc, T, Diagnoser);
8040 /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified
8041 /// by the nested-name-specifier contained in SS, and that is (re)declared by
8042 /// OwnedTagDecl, which is nullptr if this is not a (re)declaration.
8043 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
8044 const CXXScopeSpec &SS, QualType T,
8045 TagDecl *OwnedTagDecl) {
8048 NestedNameSpecifier *NNS;
8050 NNS = SS.getScopeRep();
8052 if (Keyword == ETK_None)
8056 return Context.getElaboratedType(Keyword, NNS, T, OwnedTagDecl);
8059 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
8060 assert(!E->hasPlaceholderType() && "unexpected placeholder");
8062 if (!getLangOpts().CPlusPlus && E->refersToBitField())
8063 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
8065 if (!E->isTypeDependent()) {
8066 QualType T = E->getType();
8067 if (const TagType *TT = T->getAs<TagType>())
8068 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
8070 return Context.getTypeOfExprType(E);
8073 /// getDecltypeForExpr - Given an expr, will return the decltype for
8074 /// that expression, according to the rules in C++11
8075 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
8076 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
8077 if (E->isTypeDependent())
8078 return S.Context.DependentTy;
8080 // C++11 [dcl.type.simple]p4:
8081 // The type denoted by decltype(e) is defined as follows:
8083 // - if e is an unparenthesized id-expression or an unparenthesized class
8084 // member access (5.2.5), decltype(e) is the type of the entity named
8085 // by e. If there is no such entity, or if e names a set of overloaded
8086 // functions, the program is ill-formed;
8088 // We apply the same rules for Objective-C ivar and property references.
8089 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8090 const ValueDecl *VD = DRE->getDecl();
8091 return VD->getType();
8092 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8093 if (const ValueDecl *VD = ME->getMemberDecl())
8094 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
8095 return VD->getType();
8096 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
8097 return IR->getDecl()->getType();
8098 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
8099 if (PR->isExplicitProperty())
8100 return PR->getExplicitProperty()->getType();
8101 } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
8102 return PE->getType();
8105 // C++11 [expr.lambda.prim]p18:
8106 // Every occurrence of decltype((x)) where x is a possibly
8107 // parenthesized id-expression that names an entity of automatic
8108 // storage duration is treated as if x were transformed into an
8109 // access to a corresponding data member of the closure type that
8110 // would have been declared if x were an odr-use of the denoted
8112 using namespace sema;
8113 if (S.getCurLambda()) {
8114 if (isa<ParenExpr>(E)) {
8115 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
8116 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
8117 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
8119 return S.Context.getLValueReferenceType(T);
8126 // C++11 [dcl.type.simple]p4:
8128 QualType T = E->getType();
8129 switch (E->getValueKind()) {
8130 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
8132 case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
8133 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
8135 case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
8136 // - otherwise, decltype(e) is the type of e.
8137 case VK_RValue: break;
8143 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
8144 bool AsUnevaluated) {
8145 assert(!E->hasPlaceholderType() && "unexpected placeholder");
8147 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
8148 E->HasSideEffects(Context, false)) {
8149 // The expression operand for decltype is in an unevaluated expression
8150 // context, so side effects could result in unintended consequences.
8151 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
8154 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
8157 QualType Sema::BuildUnaryTransformType(QualType BaseType,
8158 UnaryTransformType::UTTKind UKind,
8159 SourceLocation Loc) {
8161 case UnaryTransformType::EnumUnderlyingType:
8162 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
8163 Diag(Loc, diag::err_only_enums_have_underlying_types);
8166 QualType Underlying = BaseType;
8167 if (!BaseType->isDependentType()) {
8168 // The enum could be incomplete if we're parsing its definition or
8169 // recovering from an error.
8170 NamedDecl *FwdDecl = nullptr;
8171 if (BaseType->isIncompleteType(&FwdDecl)) {
8172 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
8173 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
8177 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
8178 assert(ED && "EnumType has no EnumDecl");
8180 DiagnoseUseOfDecl(ED, Loc);
8182 Underlying = ED->getIntegerType();
8183 assert(!Underlying.isNull());
8185 return Context.getUnaryTransformType(BaseType, Underlying,
8186 UnaryTransformType::EnumUnderlyingType);
8189 llvm_unreachable("unknown unary transform type");
8192 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
8193 if (!T->isDependentType()) {
8194 // FIXME: It isn't entirely clear whether incomplete atomic types
8195 // are allowed or not; for simplicity, ban them for the moment.
8196 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
8199 int DisallowedKind = -1;
8200 if (T->isArrayType())
8202 else if (T->isFunctionType())
8204 else if (T->isReferenceType())
8206 else if (T->isAtomicType())
8208 else if (T.hasQualifiers())
8210 else if (!T.isTriviallyCopyableType(Context))
8211 // Some other non-trivially-copyable type (probably a C++ class)
8214 if (DisallowedKind != -1) {
8215 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
8219 // FIXME: Do we need any handling for ARC here?
8222 // Build the pointer type.
8223 return Context.getAtomicType(T);