[lld][WebAssembly] Add `--table-base` setting
[llvm-project.git] / clang / lib / Sema / SemaType.cpp
blob9ae287d6cf0eaddad15d19215953b24695f0d793
1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements type-related semantic analysis.
11 //===----------------------------------------------------------------------===//
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/ASTStructuralEquivalence.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/Type.h"
23 #include "clang/AST/TypeLoc.h"
24 #include "clang/AST/TypeLocVisitor.h"
25 #include "clang/Basic/PartialDiagnostic.h"
26 #include "clang/Basic/SourceLocation.h"
27 #include "clang/Basic/Specifiers.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Sema/DeclSpec.h"
31 #include "clang/Sema/DelayedDiagnostic.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ParsedTemplate.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "clang/Sema/SemaInternal.h"
36 #include "clang/Sema/Template.h"
37 #include "clang/Sema/TemplateInstCallback.h"
38 #include "llvm/ADT/ArrayRef.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/ADT/StringExtras.h"
42 #include "llvm/IR/DerivedTypes.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include <bitset>
45 #include <optional>
47 using namespace clang;
49 enum TypeDiagSelector {
50 TDS_Function,
51 TDS_Pointer,
52 TDS_ObjCObjOrBlock
55 /// isOmittedBlockReturnType - Return true if this declarator is missing a
56 /// return type because this is a omitted return type on a block literal.
57 static bool isOmittedBlockReturnType(const Declarator &D) {
58 if (D.getContext() != DeclaratorContext::BlockLiteral ||
59 D.getDeclSpec().hasTypeSpecifier())
60 return false;
62 if (D.getNumTypeObjects() == 0)
63 return true; // ^{ ... }
65 if (D.getNumTypeObjects() == 1 &&
66 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
67 return true; // ^(int X, float Y) { ... }
69 return false;
72 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
73 /// doesn't apply to the given type.
74 static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
75 QualType type) {
76 TypeDiagSelector WhichType;
77 bool useExpansionLoc = true;
78 switch (attr.getKind()) {
79 case ParsedAttr::AT_ObjCGC:
80 WhichType = TDS_Pointer;
81 break;
82 case ParsedAttr::AT_ObjCOwnership:
83 WhichType = TDS_ObjCObjOrBlock;
84 break;
85 default:
86 // Assume everything else was a function attribute.
87 WhichType = TDS_Function;
88 useExpansionLoc = false;
89 break;
92 SourceLocation loc = attr.getLoc();
93 StringRef name = attr.getAttrName()->getName();
95 // The GC attributes are usually written with macros; special-case them.
96 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
97 : nullptr;
98 if (useExpansionLoc && loc.isMacroID() && II) {
99 if (II->isStr("strong")) {
100 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
101 } else if (II->isStr("weak")) {
102 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
106 S.Diag(loc, attr.isRegularKeywordAttribute()
107 ? diag::err_type_attribute_wrong_type
108 : diag::warn_type_attribute_wrong_type)
109 << name << WhichType << type;
112 // objc_gc applies to Objective-C pointers or, otherwise, to the
113 // smallest available pointer type (i.e. 'void*' in 'void**').
114 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
115 case ParsedAttr::AT_ObjCGC: \
116 case ParsedAttr::AT_ObjCOwnership
118 // Calling convention attributes.
119 #define CALLING_CONV_ATTRS_CASELIST \
120 case ParsedAttr::AT_CDecl: \
121 case ParsedAttr::AT_FastCall: \
122 case ParsedAttr::AT_StdCall: \
123 case ParsedAttr::AT_ThisCall: \
124 case ParsedAttr::AT_RegCall: \
125 case ParsedAttr::AT_Pascal: \
126 case ParsedAttr::AT_SwiftCall: \
127 case ParsedAttr::AT_SwiftAsyncCall: \
128 case ParsedAttr::AT_VectorCall: \
129 case ParsedAttr::AT_AArch64VectorPcs: \
130 case ParsedAttr::AT_AArch64SVEPcs: \
131 case ParsedAttr::AT_AMDGPUKernelCall: \
132 case ParsedAttr::AT_MSABI: \
133 case ParsedAttr::AT_SysVABI: \
134 case ParsedAttr::AT_Pcs: \
135 case ParsedAttr::AT_IntelOclBicc: \
136 case ParsedAttr::AT_PreserveMost: \
137 case ParsedAttr::AT_PreserveAll
139 // Function type attributes.
140 #define FUNCTION_TYPE_ATTRS_CASELIST \
141 case ParsedAttr::AT_NSReturnsRetained: \
142 case ParsedAttr::AT_NoReturn: \
143 case ParsedAttr::AT_Regparm: \
144 case ParsedAttr::AT_CmseNSCall: \
145 case ParsedAttr::AT_ArmStreaming: \
146 case ParsedAttr::AT_ArmStreamingCompatible: \
147 case ParsedAttr::AT_ArmSharedZA: \
148 case ParsedAttr::AT_ArmPreservesZA: \
149 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
150 case ParsedAttr::AT_AnyX86NoCfCheck: \
151 CALLING_CONV_ATTRS_CASELIST
153 // Microsoft-specific type qualifiers.
154 #define MS_TYPE_ATTRS_CASELIST \
155 case ParsedAttr::AT_Ptr32: \
156 case ParsedAttr::AT_Ptr64: \
157 case ParsedAttr::AT_SPtr: \
158 case ParsedAttr::AT_UPtr
160 // Nullability qualifiers.
161 #define NULLABILITY_TYPE_ATTRS_CASELIST \
162 case ParsedAttr::AT_TypeNonNull: \
163 case ParsedAttr::AT_TypeNullable: \
164 case ParsedAttr::AT_TypeNullableResult: \
165 case ParsedAttr::AT_TypeNullUnspecified
167 namespace {
168 /// An object which stores processing state for the entire
169 /// GetTypeForDeclarator process.
170 class TypeProcessingState {
171 Sema &sema;
173 /// The declarator being processed.
174 Declarator &declarator;
176 /// The index of the declarator chunk we're currently processing.
177 /// May be the total number of valid chunks, indicating the
178 /// DeclSpec.
179 unsigned chunkIndex;
181 /// The original set of attributes on the DeclSpec.
182 SmallVector<ParsedAttr *, 2> savedAttrs;
184 /// A list of attributes to diagnose the uselessness of when the
185 /// processing is complete.
186 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
188 /// Attributes corresponding to AttributedTypeLocs that we have not yet
189 /// populated.
190 // FIXME: The two-phase mechanism by which we construct Types and fill
191 // their TypeLocs makes it hard to correctly assign these. We keep the
192 // attributes in creation order as an attempt to make them line up
193 // properly.
194 using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
195 SmallVector<TypeAttrPair, 8> AttrsForTypes;
196 bool AttrsForTypesSorted = true;
198 /// MacroQualifiedTypes mapping to macro expansion locations that will be
199 /// stored in a MacroQualifiedTypeLoc.
200 llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
202 /// Flag to indicate we parsed a noderef attribute. This is used for
203 /// validating that noderef was used on a pointer or array.
204 bool parsedNoDeref;
206 public:
207 TypeProcessingState(Sema &sema, Declarator &declarator)
208 : sema(sema), declarator(declarator),
209 chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false) {}
211 Sema &getSema() const {
212 return sema;
215 Declarator &getDeclarator() const {
216 return declarator;
219 bool isProcessingDeclSpec() const {
220 return chunkIndex == declarator.getNumTypeObjects();
223 unsigned getCurrentChunkIndex() const {
224 return chunkIndex;
227 void setCurrentChunkIndex(unsigned idx) {
228 assert(idx <= declarator.getNumTypeObjects());
229 chunkIndex = idx;
232 ParsedAttributesView &getCurrentAttributes() const {
233 if (isProcessingDeclSpec())
234 return getMutableDeclSpec().getAttributes();
235 return declarator.getTypeObject(chunkIndex).getAttrs();
238 /// Save the current set of attributes on the DeclSpec.
239 void saveDeclSpecAttrs() {
240 // Don't try to save them multiple times.
241 if (!savedAttrs.empty())
242 return;
244 DeclSpec &spec = getMutableDeclSpec();
245 llvm::append_range(savedAttrs,
246 llvm::make_pointer_range(spec.getAttributes()));
249 /// Record that we had nowhere to put the given type attribute.
250 /// We will diagnose such attributes later.
251 void addIgnoredTypeAttr(ParsedAttr &attr) {
252 ignoredTypeAttrs.push_back(&attr);
255 /// Diagnose all the ignored type attributes, given that the
256 /// declarator worked out to the given type.
257 void diagnoseIgnoredTypeAttrs(QualType type) const {
258 for (auto *Attr : ignoredTypeAttrs)
259 diagnoseBadTypeAttribute(getSema(), *Attr, type);
262 /// Get an attributed type for the given attribute, and remember the Attr
263 /// object so that we can attach it to the AttributedTypeLoc.
264 QualType getAttributedType(Attr *A, QualType ModifiedType,
265 QualType EquivType) {
266 QualType T =
267 sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType);
268 AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
269 AttrsForTypesSorted = false;
270 return T;
273 /// Get a BTFTagAttributed type for the btf_type_tag attribute.
274 QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
275 QualType WrappedType) {
276 return sema.Context.getBTFTagAttributedType(BTFAttr, WrappedType);
279 /// Completely replace the \c auto in \p TypeWithAuto by
280 /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
281 /// necessary.
282 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
283 QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
284 if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
285 // Attributed type still should be an attributed type after replacement.
286 auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
287 for (TypeAttrPair &A : AttrsForTypes) {
288 if (A.first == AttrTy)
289 A.first = NewAttrTy;
291 AttrsForTypesSorted = false;
293 return T;
296 /// Extract and remove the Attr* for a given attributed type.
297 const Attr *takeAttrForAttributedType(const AttributedType *AT) {
298 if (!AttrsForTypesSorted) {
299 llvm::stable_sort(AttrsForTypes, llvm::less_first());
300 AttrsForTypesSorted = true;
303 // FIXME: This is quadratic if we have lots of reuses of the same
304 // attributed type.
305 for (auto It = std::partition_point(
306 AttrsForTypes.begin(), AttrsForTypes.end(),
307 [=](const TypeAttrPair &A) { return A.first < AT; });
308 It != AttrsForTypes.end() && It->first == AT; ++It) {
309 if (It->second) {
310 const Attr *Result = It->second;
311 It->second = nullptr;
312 return Result;
316 llvm_unreachable("no Attr* for AttributedType*");
319 SourceLocation
320 getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
321 auto FoundLoc = LocsForMacros.find(MQT);
322 assert(FoundLoc != LocsForMacros.end() &&
323 "Unable to find macro expansion location for MacroQualifedType");
324 return FoundLoc->second;
327 void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
328 SourceLocation Loc) {
329 LocsForMacros[MQT] = Loc;
332 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
334 bool didParseNoDeref() const { return parsedNoDeref; }
336 ~TypeProcessingState() {
337 if (savedAttrs.empty())
338 return;
340 getMutableDeclSpec().getAttributes().clearListOnly();
341 for (ParsedAttr *AL : savedAttrs)
342 getMutableDeclSpec().getAttributes().addAtEnd(AL);
345 private:
346 DeclSpec &getMutableDeclSpec() const {
347 return const_cast<DeclSpec&>(declarator.getDeclSpec());
350 } // end anonymous namespace
352 static void moveAttrFromListToList(ParsedAttr &attr,
353 ParsedAttributesView &fromList,
354 ParsedAttributesView &toList) {
355 fromList.remove(&attr);
356 toList.addAtEnd(&attr);
359 /// The location of a type attribute.
360 enum TypeAttrLocation {
361 /// The attribute is in the decl-specifier-seq.
362 TAL_DeclSpec,
363 /// The attribute is part of a DeclaratorChunk.
364 TAL_DeclChunk,
365 /// The attribute is immediately after the declaration's name.
366 TAL_DeclName
369 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
370 TypeAttrLocation TAL,
371 const ParsedAttributesView &attrs);
373 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
374 QualType &type);
376 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
377 ParsedAttr &attr, QualType &type);
379 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
380 QualType &type);
382 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
383 ParsedAttr &attr, QualType &type);
385 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
386 ParsedAttr &attr, QualType &type) {
387 if (attr.getKind() == ParsedAttr::AT_ObjCGC)
388 return handleObjCGCTypeAttr(state, attr, type);
389 assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
390 return handleObjCOwnershipTypeAttr(state, attr, type);
393 /// Given the index of a declarator chunk, check whether that chunk
394 /// directly specifies the return type of a function and, if so, find
395 /// an appropriate place for it.
397 /// \param i - a notional index which the search will start
398 /// immediately inside
400 /// \param onlyBlockPointers Whether we should only look into block
401 /// pointer types (vs. all pointer types).
402 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
403 unsigned i,
404 bool onlyBlockPointers) {
405 assert(i <= declarator.getNumTypeObjects());
407 DeclaratorChunk *result = nullptr;
409 // First, look inwards past parens for a function declarator.
410 for (; i != 0; --i) {
411 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
412 switch (fnChunk.Kind) {
413 case DeclaratorChunk::Paren:
414 continue;
416 // If we find anything except a function, bail out.
417 case DeclaratorChunk::Pointer:
418 case DeclaratorChunk::BlockPointer:
419 case DeclaratorChunk::Array:
420 case DeclaratorChunk::Reference:
421 case DeclaratorChunk::MemberPointer:
422 case DeclaratorChunk::Pipe:
423 return result;
425 // If we do find a function declarator, scan inwards from that,
426 // looking for a (block-)pointer declarator.
427 case DeclaratorChunk::Function:
428 for (--i; i != 0; --i) {
429 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
430 switch (ptrChunk.Kind) {
431 case DeclaratorChunk::Paren:
432 case DeclaratorChunk::Array:
433 case DeclaratorChunk::Function:
434 case DeclaratorChunk::Reference:
435 case DeclaratorChunk::Pipe:
436 continue;
438 case DeclaratorChunk::MemberPointer:
439 case DeclaratorChunk::Pointer:
440 if (onlyBlockPointers)
441 continue;
443 [[fallthrough]];
445 case DeclaratorChunk::BlockPointer:
446 result = &ptrChunk;
447 goto continue_outer;
449 llvm_unreachable("bad declarator chunk kind");
452 // If we run out of declarators doing that, we're done.
453 return result;
455 llvm_unreachable("bad declarator chunk kind");
457 // Okay, reconsider from our new point.
458 continue_outer: ;
461 // Ran out of chunks, bail out.
462 return result;
465 /// Given that an objc_gc attribute was written somewhere on a
466 /// declaration *other* than on the declarator itself (for which, use
467 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
468 /// didn't apply in whatever position it was written in, try to move
469 /// it to a more appropriate position.
470 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
471 ParsedAttr &attr, QualType type) {
472 Declarator &declarator = state.getDeclarator();
474 // Move it to the outermost normal or block pointer declarator.
475 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
476 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
477 switch (chunk.Kind) {
478 case DeclaratorChunk::Pointer:
479 case DeclaratorChunk::BlockPointer: {
480 // But don't move an ARC ownership attribute to the return type
481 // of a block.
482 DeclaratorChunk *destChunk = nullptr;
483 if (state.isProcessingDeclSpec() &&
484 attr.getKind() == ParsedAttr::AT_ObjCOwnership)
485 destChunk = maybeMovePastReturnType(declarator, i - 1,
486 /*onlyBlockPointers=*/true);
487 if (!destChunk) destChunk = &chunk;
489 moveAttrFromListToList(attr, state.getCurrentAttributes(),
490 destChunk->getAttrs());
491 return;
494 case DeclaratorChunk::Paren:
495 case DeclaratorChunk::Array:
496 continue;
498 // We may be starting at the return type of a block.
499 case DeclaratorChunk::Function:
500 if (state.isProcessingDeclSpec() &&
501 attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
502 if (DeclaratorChunk *dest = maybeMovePastReturnType(
503 declarator, i,
504 /*onlyBlockPointers=*/true)) {
505 moveAttrFromListToList(attr, state.getCurrentAttributes(),
506 dest->getAttrs());
507 return;
510 goto error;
512 // Don't walk through these.
513 case DeclaratorChunk::Reference:
514 case DeclaratorChunk::MemberPointer:
515 case DeclaratorChunk::Pipe:
516 goto error;
519 error:
521 diagnoseBadTypeAttribute(state.getSema(), attr, type);
524 /// Distribute an objc_gc type attribute that was written on the
525 /// declarator.
526 static void distributeObjCPointerTypeAttrFromDeclarator(
527 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
528 Declarator &declarator = state.getDeclarator();
530 // objc_gc goes on the innermost pointer to something that's not a
531 // pointer.
532 unsigned innermost = -1U;
533 bool considerDeclSpec = true;
534 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
535 DeclaratorChunk &chunk = declarator.getTypeObject(i);
536 switch (chunk.Kind) {
537 case DeclaratorChunk::Pointer:
538 case DeclaratorChunk::BlockPointer:
539 innermost = i;
540 continue;
542 case DeclaratorChunk::Reference:
543 case DeclaratorChunk::MemberPointer:
544 case DeclaratorChunk::Paren:
545 case DeclaratorChunk::Array:
546 case DeclaratorChunk::Pipe:
547 continue;
549 case DeclaratorChunk::Function:
550 considerDeclSpec = false;
551 goto done;
554 done:
556 // That might actually be the decl spec if we weren't blocked by
557 // anything in the declarator.
558 if (considerDeclSpec) {
559 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
560 // Splice the attribute into the decl spec. Prevents the
561 // attribute from being applied multiple times and gives
562 // the source-location-filler something to work with.
563 state.saveDeclSpecAttrs();
564 declarator.getMutableDeclSpec().getAttributes().takeOneFrom(
565 declarator.getAttributes(), &attr);
566 return;
570 // Otherwise, if we found an appropriate chunk, splice the attribute
571 // into it.
572 if (innermost != -1U) {
573 moveAttrFromListToList(attr, declarator.getAttributes(),
574 declarator.getTypeObject(innermost).getAttrs());
575 return;
578 // Otherwise, diagnose when we're done building the type.
579 declarator.getAttributes().remove(&attr);
580 state.addIgnoredTypeAttr(attr);
583 /// A function type attribute was written somewhere in a declaration
584 /// *other* than on the declarator itself or in the decl spec. Given
585 /// that it didn't apply in whatever position it was written in, try
586 /// to move it to a more appropriate position.
587 static void distributeFunctionTypeAttr(TypeProcessingState &state,
588 ParsedAttr &attr, QualType type) {
589 Declarator &declarator = state.getDeclarator();
591 // Try to push the attribute from the return type of a function to
592 // the function itself.
593 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
594 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
595 switch (chunk.Kind) {
596 case DeclaratorChunk::Function:
597 moveAttrFromListToList(attr, state.getCurrentAttributes(),
598 chunk.getAttrs());
599 return;
601 case DeclaratorChunk::Paren:
602 case DeclaratorChunk::Pointer:
603 case DeclaratorChunk::BlockPointer:
604 case DeclaratorChunk::Array:
605 case DeclaratorChunk::Reference:
606 case DeclaratorChunk::MemberPointer:
607 case DeclaratorChunk::Pipe:
608 continue;
612 diagnoseBadTypeAttribute(state.getSema(), attr, type);
615 /// Try to distribute a function type attribute to the innermost
616 /// function chunk or type. Returns true if the attribute was
617 /// distributed, false if no location was found.
618 static bool distributeFunctionTypeAttrToInnermost(
619 TypeProcessingState &state, ParsedAttr &attr,
620 ParsedAttributesView &attrList, QualType &declSpecType) {
621 Declarator &declarator = state.getDeclarator();
623 // Put it on the innermost function chunk, if there is one.
624 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
625 DeclaratorChunk &chunk = declarator.getTypeObject(i);
626 if (chunk.Kind != DeclaratorChunk::Function) continue;
628 moveAttrFromListToList(attr, attrList, chunk.getAttrs());
629 return true;
632 return handleFunctionTypeAttr(state, attr, declSpecType);
635 /// A function type attribute was written in the decl spec. Try to
636 /// apply it somewhere.
637 static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
638 ParsedAttr &attr,
639 QualType &declSpecType) {
640 state.saveDeclSpecAttrs();
642 // Try to distribute to the innermost.
643 if (distributeFunctionTypeAttrToInnermost(
644 state, attr, state.getCurrentAttributes(), declSpecType))
645 return;
647 // If that failed, diagnose the bad attribute when the declarator is
648 // fully built.
649 state.addIgnoredTypeAttr(attr);
652 /// A function type attribute was written on the declarator or declaration.
653 /// Try to apply it somewhere.
654 /// `Attrs` is the attribute list containing the declaration (either of the
655 /// declarator or the declaration).
656 static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
657 ParsedAttr &attr,
658 QualType &declSpecType) {
659 Declarator &declarator = state.getDeclarator();
661 // Try to distribute to the innermost.
662 if (distributeFunctionTypeAttrToInnermost(
663 state, attr, declarator.getAttributes(), declSpecType))
664 return;
666 // If that failed, diagnose the bad attribute when the declarator is
667 // fully built.
668 declarator.getAttributes().remove(&attr);
669 state.addIgnoredTypeAttr(attr);
672 /// Given that there are attributes written on the declarator or declaration
673 /// itself, try to distribute any type attributes to the appropriate
674 /// declarator chunk.
676 /// These are attributes like the following:
677 /// int f ATTR;
678 /// int (f ATTR)();
679 /// but not necessarily this:
680 /// int f() ATTR;
682 /// `Attrs` is the attribute list containing the declaration (either of the
683 /// declarator or the declaration).
684 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
685 QualType &declSpecType) {
686 // The called functions in this loop actually remove things from the current
687 // list, so iterating over the existing list isn't possible. Instead, make a
688 // non-owning copy and iterate over that.
689 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
690 for (ParsedAttr &attr : AttrsCopy) {
691 // Do not distribute [[]] attributes. They have strict rules for what
692 // they appertain to.
693 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute())
694 continue;
696 switch (attr.getKind()) {
697 OBJC_POINTER_TYPE_ATTRS_CASELIST:
698 distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType);
699 break;
701 FUNCTION_TYPE_ATTRS_CASELIST:
702 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType);
703 break;
705 MS_TYPE_ATTRS_CASELIST:
706 // Microsoft type attributes cannot go after the declarator-id.
707 continue;
709 NULLABILITY_TYPE_ATTRS_CASELIST:
710 // Nullability specifiers cannot go after the declarator-id.
712 // Objective-C __kindof does not get distributed.
713 case ParsedAttr::AT_ObjCKindOf:
714 continue;
716 default:
717 break;
722 /// Add a synthetic '()' to a block-literal declarator if it is
723 /// required, given the return type.
724 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
725 QualType declSpecType) {
726 Declarator &declarator = state.getDeclarator();
728 // First, check whether the declarator would produce a function,
729 // i.e. whether the innermost semantic chunk is a function.
730 if (declarator.isFunctionDeclarator()) {
731 // If so, make that declarator a prototyped declarator.
732 declarator.getFunctionTypeInfo().hasPrototype = true;
733 return;
736 // If there are any type objects, the type as written won't name a
737 // function, regardless of the decl spec type. This is because a
738 // block signature declarator is always an abstract-declarator, and
739 // abstract-declarators can't just be parentheses chunks. Therefore
740 // we need to build a function chunk unless there are no type
741 // objects and the decl spec type is a function.
742 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
743 return;
745 // Note that there *are* cases with invalid declarators where
746 // declarators consist solely of parentheses. In general, these
747 // occur only in failed efforts to make function declarators, so
748 // faking up the function chunk is still the right thing to do.
750 // Otherwise, we need to fake up a function declarator.
751 SourceLocation loc = declarator.getBeginLoc();
753 // ...and *prepend* it to the declarator.
754 SourceLocation NoLoc;
755 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
756 /*HasProto=*/true,
757 /*IsAmbiguous=*/false,
758 /*LParenLoc=*/NoLoc,
759 /*ArgInfo=*/nullptr,
760 /*NumParams=*/0,
761 /*EllipsisLoc=*/NoLoc,
762 /*RParenLoc=*/NoLoc,
763 /*RefQualifierIsLvalueRef=*/true,
764 /*RefQualifierLoc=*/NoLoc,
765 /*MutableLoc=*/NoLoc, EST_None,
766 /*ESpecRange=*/SourceRange(),
767 /*Exceptions=*/nullptr,
768 /*ExceptionRanges=*/nullptr,
769 /*NumExceptions=*/0,
770 /*NoexceptExpr=*/nullptr,
771 /*ExceptionSpecTokens=*/nullptr,
772 /*DeclsInPrototype=*/std::nullopt, loc, loc, declarator));
774 // For consistency, make sure the state still has us as processing
775 // the decl spec.
776 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
777 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
780 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
781 unsigned &TypeQuals,
782 QualType TypeSoFar,
783 unsigned RemoveTQs,
784 unsigned DiagID) {
785 // If this occurs outside a template instantiation, warn the user about
786 // it; they probably didn't mean to specify a redundant qualifier.
787 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
788 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
789 QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
790 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
791 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
792 if (!(RemoveTQs & Qual.first))
793 continue;
795 if (!S.inTemplateInstantiation()) {
796 if (TypeQuals & Qual.first)
797 S.Diag(Qual.second, DiagID)
798 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
799 << FixItHint::CreateRemoval(Qual.second);
802 TypeQuals &= ~Qual.first;
806 /// Return true if this is omitted block return type. Also check type
807 /// attributes and type qualifiers when returning true.
808 static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
809 QualType Result) {
810 if (!isOmittedBlockReturnType(declarator))
811 return false;
813 // Warn if we see type attributes for omitted return type on a block literal.
814 SmallVector<ParsedAttr *, 2> ToBeRemoved;
815 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
816 if (AL.isInvalid() || !AL.isTypeAttr())
817 continue;
818 S.Diag(AL.getLoc(),
819 diag::warn_block_literal_attributes_on_omitted_return_type)
820 << AL;
821 ToBeRemoved.push_back(&AL);
823 // Remove bad attributes from the list.
824 for (ParsedAttr *AL : ToBeRemoved)
825 declarator.getMutableDeclSpec().getAttributes().remove(AL);
827 // Warn if we see type qualifiers for omitted return type on a block literal.
828 const DeclSpec &DS = declarator.getDeclSpec();
829 unsigned TypeQuals = DS.getTypeQualifiers();
830 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
831 diag::warn_block_literal_qualifiers_on_omitted_return_type);
832 declarator.getMutableDeclSpec().ClearTypeQualifiers();
834 return true;
837 /// Apply Objective-C type arguments to the given type.
838 static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
839 ArrayRef<TypeSourceInfo *> typeArgs,
840 SourceRange typeArgsRange, bool failOnError,
841 bool rebuilding) {
842 // We can only apply type arguments to an Objective-C class type.
843 const auto *objcObjectType = type->getAs<ObjCObjectType>();
844 if (!objcObjectType || !objcObjectType->getInterface()) {
845 S.Diag(loc, diag::err_objc_type_args_non_class)
846 << type
847 << typeArgsRange;
849 if (failOnError)
850 return QualType();
851 return type;
854 // The class type must be parameterized.
855 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
856 ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
857 if (!typeParams) {
858 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
859 << objcClass->getDeclName()
860 << FixItHint::CreateRemoval(typeArgsRange);
862 if (failOnError)
863 return QualType();
865 return type;
868 // The type must not already be specialized.
869 if (objcObjectType->isSpecialized()) {
870 S.Diag(loc, diag::err_objc_type_args_specialized_class)
871 << type
872 << FixItHint::CreateRemoval(typeArgsRange);
874 if (failOnError)
875 return QualType();
877 return type;
880 // Check the type arguments.
881 SmallVector<QualType, 4> finalTypeArgs;
882 unsigned numTypeParams = typeParams->size();
883 bool anyPackExpansions = false;
884 for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
885 TypeSourceInfo *typeArgInfo = typeArgs[i];
886 QualType typeArg = typeArgInfo->getType();
888 // Type arguments cannot have explicit qualifiers or nullability.
889 // We ignore indirect sources of these, e.g. behind typedefs or
890 // template arguments.
891 if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
892 bool diagnosed = false;
893 SourceRange rangeToRemove;
894 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
895 rangeToRemove = attr.getLocalSourceRange();
896 if (attr.getTypePtr()->getImmediateNullability()) {
897 typeArg = attr.getTypePtr()->getModifiedType();
898 S.Diag(attr.getBeginLoc(),
899 diag::err_objc_type_arg_explicit_nullability)
900 << typeArg << FixItHint::CreateRemoval(rangeToRemove);
901 diagnosed = true;
905 // When rebuilding, qualifiers might have gotten here through a
906 // final substitution.
907 if (!rebuilding && !diagnosed) {
908 S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified)
909 << typeArg << typeArg.getQualifiers().getAsString()
910 << FixItHint::CreateRemoval(rangeToRemove);
914 // Remove qualifiers even if they're non-local.
915 typeArg = typeArg.getUnqualifiedType();
917 finalTypeArgs.push_back(typeArg);
919 if (typeArg->getAs<PackExpansionType>())
920 anyPackExpansions = true;
922 // Find the corresponding type parameter, if there is one.
923 ObjCTypeParamDecl *typeParam = nullptr;
924 if (!anyPackExpansions) {
925 if (i < numTypeParams) {
926 typeParam = typeParams->begin()[i];
927 } else {
928 // Too many arguments.
929 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
930 << false
931 << objcClass->getDeclName()
932 << (unsigned)typeArgs.size()
933 << numTypeParams;
934 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
935 << objcClass;
937 if (failOnError)
938 return QualType();
940 return type;
944 // Objective-C object pointer types must be substitutable for the bounds.
945 if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
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.
949 if (!typeParam) {
950 assert(anyPackExpansions && "Too many arguments?");
951 continue;
954 // Retrieve the bound.
955 QualType bound = typeParam->getUnderlyingType();
956 const auto *boundObjC = bound->castAs<ObjCObjectPointerType>();
958 // Determine whether the type argument is substitutable for the bound.
959 if (typeArgObjC->isObjCIdType()) {
960 // When the type argument is 'id', the only acceptable type
961 // parameter bound is 'id'.
962 if (boundObjC->isObjCIdType())
963 continue;
964 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
965 // Otherwise, we follow the assignability rules.
966 continue;
969 // Diagnose the mismatch.
970 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
971 diag::err_objc_type_arg_does_not_match_bound)
972 << typeArg << bound << typeParam->getDeclName();
973 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
974 << typeParam->getDeclName();
976 if (failOnError)
977 return QualType();
979 return type;
982 // Block pointer types are permitted for unqualified 'id' bounds.
983 if (typeArg->isBlockPointerType()) {
984 // If we don't have a type parameter to match against, assume
985 // everything is fine. There was a prior pack expansion that
986 // means we won't be able to match anything.
987 if (!typeParam) {
988 assert(anyPackExpansions && "Too many arguments?");
989 continue;
992 // Retrieve the bound.
993 QualType bound = typeParam->getUnderlyingType();
994 if (bound->isBlockCompatibleObjCPointerType(S.Context))
995 continue;
997 // Diagnose the mismatch.
998 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
999 diag::err_objc_type_arg_does_not_match_bound)
1000 << typeArg << bound << typeParam->getDeclName();
1001 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
1002 << typeParam->getDeclName();
1004 if (failOnError)
1005 return QualType();
1007 return type;
1010 // Dependent types will be checked at instantiation time.
1011 if (typeArg->isDependentType()) {
1012 continue;
1015 // Diagnose non-id-compatible type arguments.
1016 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
1017 diag::err_objc_type_arg_not_id_compatible)
1018 << typeArg << typeArgInfo->getTypeLoc().getSourceRange();
1020 if (failOnError)
1021 return QualType();
1023 return type;
1026 // Make sure we didn't have the wrong number of arguments.
1027 if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
1028 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
1029 << (typeArgs.size() < typeParams->size())
1030 << objcClass->getDeclName()
1031 << (unsigned)finalTypeArgs.size()
1032 << (unsigned)numTypeParams;
1033 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
1034 << objcClass;
1036 if (failOnError)
1037 return QualType();
1039 return type;
1042 // Success. Form the specialized type.
1043 return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1046 QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1047 SourceLocation ProtocolLAngleLoc,
1048 ArrayRef<ObjCProtocolDecl *> Protocols,
1049 ArrayRef<SourceLocation> ProtocolLocs,
1050 SourceLocation ProtocolRAngleLoc,
1051 bool FailOnError) {
1052 QualType Result = QualType(Decl->getTypeForDecl(), 0);
1053 if (!Protocols.empty()) {
1054 bool HasError;
1055 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1056 HasError);
1057 if (HasError) {
1058 Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1059 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1060 if (FailOnError) Result = QualType();
1062 if (FailOnError && Result.isNull())
1063 return QualType();
1066 return Result;
1069 QualType Sema::BuildObjCObjectType(
1070 QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc,
1071 ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc,
1072 SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols,
1073 ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc,
1074 bool FailOnError, bool Rebuilding) {
1075 QualType Result = BaseType;
1076 if (!TypeArgs.empty()) {
1077 Result =
1078 applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1079 SourceRange(TypeArgsLAngleLoc, TypeArgsRAngleLoc),
1080 FailOnError, Rebuilding);
1081 if (FailOnError && Result.isNull())
1082 return QualType();
1085 if (!Protocols.empty()) {
1086 bool HasError;
1087 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1088 HasError);
1089 if (HasError) {
1090 Diag(Loc, diag::err_invalid_protocol_qualifiers)
1091 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1092 if (FailOnError) Result = QualType();
1094 if (FailOnError && Result.isNull())
1095 return QualType();
1098 return Result;
1101 TypeResult Sema::actOnObjCProtocolQualifierType(
1102 SourceLocation lAngleLoc,
1103 ArrayRef<Decl *> protocols,
1104 ArrayRef<SourceLocation> protocolLocs,
1105 SourceLocation rAngleLoc) {
1106 // Form id<protocol-list>.
1107 QualType Result = Context.getObjCObjectType(
1108 Context.ObjCBuiltinIdTy, {},
1109 llvm::ArrayRef((ObjCProtocolDecl *const *)protocols.data(),
1110 protocols.size()),
1111 false);
1112 Result = Context.getObjCObjectPointerType(Result);
1114 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1115 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1117 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1118 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1120 auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1121 .castAs<ObjCObjectTypeLoc>();
1122 ObjCObjectTL.setHasBaseTypeAsWritten(false);
1123 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1125 // No type arguments.
1126 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1127 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1129 // Fill in protocol qualifiers.
1130 ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1131 ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1132 for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1133 ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1135 // We're done. Return the completed type to the parser.
1136 return CreateParsedType(Result, ResultTInfo);
1139 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1140 Scope *S,
1141 SourceLocation Loc,
1142 ParsedType BaseType,
1143 SourceLocation TypeArgsLAngleLoc,
1144 ArrayRef<ParsedType> TypeArgs,
1145 SourceLocation TypeArgsRAngleLoc,
1146 SourceLocation ProtocolLAngleLoc,
1147 ArrayRef<Decl *> Protocols,
1148 ArrayRef<SourceLocation> ProtocolLocs,
1149 SourceLocation ProtocolRAngleLoc) {
1150 TypeSourceInfo *BaseTypeInfo = nullptr;
1151 QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1152 if (T.isNull())
1153 return true;
1155 // Handle missing type-source info.
1156 if (!BaseTypeInfo)
1157 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1159 // Extract type arguments.
1160 SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1161 for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1162 TypeSourceInfo *TypeArgInfo = nullptr;
1163 QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1164 if (TypeArg.isNull()) {
1165 ActualTypeArgInfos.clear();
1166 break;
1169 assert(TypeArgInfo && "No type source info?");
1170 ActualTypeArgInfos.push_back(TypeArgInfo);
1173 // Build the object type.
1174 QualType Result = BuildObjCObjectType(
1175 T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1176 TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1177 ProtocolLAngleLoc,
1178 llvm::ArrayRef((ObjCProtocolDecl *const *)Protocols.data(),
1179 Protocols.size()),
1180 ProtocolLocs, ProtocolRAngleLoc,
1181 /*FailOnError=*/false,
1182 /*Rebuilding=*/false);
1184 if (Result == T)
1185 return BaseType;
1187 // Create source information for this type.
1188 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1189 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1191 // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1192 // object pointer type. Fill in source information for it.
1193 if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1194 // The '*' is implicit.
1195 ObjCObjectPointerTL.setStarLoc(SourceLocation());
1196 ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1199 if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1200 // Protocol qualifier information.
1201 if (OTPTL.getNumProtocols() > 0) {
1202 assert(OTPTL.getNumProtocols() == Protocols.size());
1203 OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1204 OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1205 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1206 OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1209 // We're done. Return the completed type to the parser.
1210 return CreateParsedType(Result, ResultTInfo);
1213 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1215 // Type argument information.
1216 if (ObjCObjectTL.getNumTypeArgs() > 0) {
1217 assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1218 ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1219 ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1220 for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1221 ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1222 } else {
1223 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1224 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1227 // Protocol qualifier information.
1228 if (ObjCObjectTL.getNumProtocols() > 0) {
1229 assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1230 ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1231 ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1232 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1233 ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1234 } else {
1235 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1236 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1239 // Base type.
1240 ObjCObjectTL.setHasBaseTypeAsWritten(true);
1241 if (ObjCObjectTL.getType() == T)
1242 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1243 else
1244 ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1246 // We're done. Return the completed type to the parser.
1247 return CreateParsedType(Result, ResultTInfo);
1250 static OpenCLAccessAttr::Spelling
1251 getImageAccess(const ParsedAttributesView &Attrs) {
1252 for (const ParsedAttr &AL : Attrs)
1253 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
1254 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
1255 return OpenCLAccessAttr::Keyword_read_only;
1258 static UnaryTransformType::UTTKind
1259 TSTToUnaryTransformType(DeclSpec::TST SwitchTST) {
1260 switch (SwitchTST) {
1261 #define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
1262 case TST_##Trait: \
1263 return UnaryTransformType::Enum;
1264 #include "clang/Basic/TransformTypeTraits.def"
1265 default:
1266 llvm_unreachable("attempted to parse a non-unary transform builtin");
1270 /// Convert the specified declspec to the appropriate type
1271 /// object.
1272 /// \param state Specifies the declarator containing the declaration specifier
1273 /// to be converted, along with other associated processing state.
1274 /// \returns The type described by the declaration specifiers. This function
1275 /// never returns null.
1276 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1277 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1278 // checking.
1280 Sema &S = state.getSema();
1281 Declarator &declarator = state.getDeclarator();
1282 DeclSpec &DS = declarator.getMutableDeclSpec();
1283 SourceLocation DeclLoc = declarator.getIdentifierLoc();
1284 if (DeclLoc.isInvalid())
1285 DeclLoc = DS.getBeginLoc();
1287 ASTContext &Context = S.Context;
1289 QualType Result;
1290 switch (DS.getTypeSpecType()) {
1291 case DeclSpec::TST_void:
1292 Result = Context.VoidTy;
1293 break;
1294 case DeclSpec::TST_char:
1295 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1296 Result = Context.CharTy;
1297 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed)
1298 Result = Context.SignedCharTy;
1299 else {
1300 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
1301 "Unknown TSS value");
1302 Result = Context.UnsignedCharTy;
1304 break;
1305 case DeclSpec::TST_wchar:
1306 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1307 Result = Context.WCharTy;
1308 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) {
1309 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1310 << DS.getSpecifierName(DS.getTypeSpecType(),
1311 Context.getPrintingPolicy());
1312 Result = Context.getSignedWCharType();
1313 } else {
1314 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
1315 "Unknown TSS value");
1316 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1317 << DS.getSpecifierName(DS.getTypeSpecType(),
1318 Context.getPrintingPolicy());
1319 Result = Context.getUnsignedWCharType();
1321 break;
1322 case DeclSpec::TST_char8:
1323 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1324 "Unknown TSS value");
1325 Result = Context.Char8Ty;
1326 break;
1327 case DeclSpec::TST_char16:
1328 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1329 "Unknown TSS value");
1330 Result = Context.Char16Ty;
1331 break;
1332 case DeclSpec::TST_char32:
1333 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1334 "Unknown TSS value");
1335 Result = Context.Char32Ty;
1336 break;
1337 case DeclSpec::TST_unspecified:
1338 // If this is a missing declspec in a block literal return context, then it
1339 // is inferred from the return statements inside the block.
1340 // The declspec is always missing in a lambda expr context; it is either
1341 // specified with a trailing return type or inferred.
1342 if (S.getLangOpts().CPlusPlus14 &&
1343 declarator.getContext() == DeclaratorContext::LambdaExpr) {
1344 // In C++1y, a lambda's implicit return type is 'auto'.
1345 Result = Context.getAutoDeductType();
1346 break;
1347 } else if (declarator.getContext() == DeclaratorContext::LambdaExpr ||
1348 checkOmittedBlockReturnType(S, declarator,
1349 Context.DependentTy)) {
1350 Result = Context.DependentTy;
1351 break;
1354 // Unspecified typespec defaults to int in C90. However, the C90 grammar
1355 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1356 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
1357 // Note that the one exception to this is function definitions, which are
1358 // allowed to be completely missing a declspec. This is handled in the
1359 // parser already though by it pretending to have seen an 'int' in this
1360 // case.
1361 if (S.getLangOpts().isImplicitIntRequired()) {
1362 S.Diag(DeclLoc, diag::warn_missing_type_specifier)
1363 << DS.getSourceRange()
1364 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1365 } else if (!DS.hasTypeSpecifier()) {
1366 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1367 // "At least one type specifier shall be given in the declaration
1368 // specifiers in each declaration, and in the specifier-qualifier list in
1369 // each struct declaration and type name."
1370 if (!S.getLangOpts().isImplicitIntAllowed() && !DS.isTypeSpecPipe()) {
1371 S.Diag(DeclLoc, diag::err_missing_type_specifier)
1372 << DS.getSourceRange();
1374 // When this occurs, often something is very broken with the value
1375 // being declared, poison it as invalid so we don't get chains of
1376 // errors.
1377 declarator.setInvalidType(true);
1378 } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 &&
1379 DS.isTypeSpecPipe()) {
1380 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1381 << DS.getSourceRange();
1382 declarator.setInvalidType(true);
1383 } else {
1384 assert(S.getLangOpts().isImplicitIntAllowed() &&
1385 "implicit int is disabled?");
1386 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1387 << DS.getSourceRange()
1388 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1392 [[fallthrough]];
1393 case DeclSpec::TST_int: {
1394 if (DS.getTypeSpecSign() != TypeSpecifierSign::Unsigned) {
1395 switch (DS.getTypeSpecWidth()) {
1396 case TypeSpecifierWidth::Unspecified:
1397 Result = Context.IntTy;
1398 break;
1399 case TypeSpecifierWidth::Short:
1400 Result = Context.ShortTy;
1401 break;
1402 case TypeSpecifierWidth::Long:
1403 Result = Context.LongTy;
1404 break;
1405 case TypeSpecifierWidth::LongLong:
1406 Result = Context.LongLongTy;
1408 // 'long long' is a C99 or C++11 feature.
1409 if (!S.getLangOpts().C99) {
1410 if (S.getLangOpts().CPlusPlus)
1411 S.Diag(DS.getTypeSpecWidthLoc(),
1412 S.getLangOpts().CPlusPlus11 ?
1413 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1414 else
1415 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1417 break;
1419 } else {
1420 switch (DS.getTypeSpecWidth()) {
1421 case TypeSpecifierWidth::Unspecified:
1422 Result = Context.UnsignedIntTy;
1423 break;
1424 case TypeSpecifierWidth::Short:
1425 Result = Context.UnsignedShortTy;
1426 break;
1427 case TypeSpecifierWidth::Long:
1428 Result = Context.UnsignedLongTy;
1429 break;
1430 case TypeSpecifierWidth::LongLong:
1431 Result = Context.UnsignedLongLongTy;
1433 // 'long long' is a C99 or C++11 feature.
1434 if (!S.getLangOpts().C99) {
1435 if (S.getLangOpts().CPlusPlus)
1436 S.Diag(DS.getTypeSpecWidthLoc(),
1437 S.getLangOpts().CPlusPlus11 ?
1438 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1439 else
1440 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1442 break;
1445 break;
1447 case DeclSpec::TST_bitint: {
1448 if (!S.Context.getTargetInfo().hasBitIntType())
1449 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_BitInt";
1450 Result =
1451 S.BuildBitIntType(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned,
1452 DS.getRepAsExpr(), DS.getBeginLoc());
1453 if (Result.isNull()) {
1454 Result = Context.IntTy;
1455 declarator.setInvalidType(true);
1457 break;
1459 case DeclSpec::TST_accum: {
1460 switch (DS.getTypeSpecWidth()) {
1461 case TypeSpecifierWidth::Short:
1462 Result = Context.ShortAccumTy;
1463 break;
1464 case TypeSpecifierWidth::Unspecified:
1465 Result = Context.AccumTy;
1466 break;
1467 case TypeSpecifierWidth::Long:
1468 Result = Context.LongAccumTy;
1469 break;
1470 case TypeSpecifierWidth::LongLong:
1471 llvm_unreachable("Unable to specify long long as _Accum width");
1474 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1475 Result = Context.getCorrespondingUnsignedType(Result);
1477 if (DS.isTypeSpecSat())
1478 Result = Context.getCorrespondingSaturatedType(Result);
1480 break;
1482 case DeclSpec::TST_fract: {
1483 switch (DS.getTypeSpecWidth()) {
1484 case TypeSpecifierWidth::Short:
1485 Result = Context.ShortFractTy;
1486 break;
1487 case TypeSpecifierWidth::Unspecified:
1488 Result = Context.FractTy;
1489 break;
1490 case TypeSpecifierWidth::Long:
1491 Result = Context.LongFractTy;
1492 break;
1493 case TypeSpecifierWidth::LongLong:
1494 llvm_unreachable("Unable to specify long long as _Fract width");
1497 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1498 Result = Context.getCorrespondingUnsignedType(Result);
1500 if (DS.isTypeSpecSat())
1501 Result = Context.getCorrespondingSaturatedType(Result);
1503 break;
1505 case DeclSpec::TST_int128:
1506 if (!S.Context.getTargetInfo().hasInt128Type() &&
1507 !(S.getLangOpts().SYCLIsDevice || S.getLangOpts().CUDAIsDevice ||
1508 (S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice)))
1509 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1510 << "__int128";
1511 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1512 Result = Context.UnsignedInt128Ty;
1513 else
1514 Result = Context.Int128Ty;
1515 break;
1516 case DeclSpec::TST_float16:
1517 // CUDA host and device may have different _Float16 support, therefore
1518 // do not diagnose _Float16 usage to avoid false alarm.
1519 // ToDo: more precise diagnostics for CUDA.
1520 if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
1521 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1522 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1523 << "_Float16";
1524 Result = Context.Float16Ty;
1525 break;
1526 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1527 case DeclSpec::TST_BFloat16:
1528 if (!S.Context.getTargetInfo().hasBFloat16Type() &&
1529 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice) &&
1530 !S.getLangOpts().SYCLIsDevice)
1531 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__bf16";
1532 Result = Context.BFloat16Ty;
1533 break;
1534 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1535 case DeclSpec::TST_double:
1536 if (DS.getTypeSpecWidth() == TypeSpecifierWidth::Long)
1537 Result = Context.LongDoubleTy;
1538 else
1539 Result = Context.DoubleTy;
1540 if (S.getLangOpts().OpenCL) {
1541 if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts()))
1542 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1543 << 0 << Result
1544 << (S.getLangOpts().getOpenCLCompatibleVersion() == 300
1545 ? "cl_khr_fp64 and __opencl_c_fp64"
1546 : "cl_khr_fp64");
1547 else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts()))
1548 S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma);
1550 break;
1551 case DeclSpec::TST_float128:
1552 if (!S.Context.getTargetInfo().hasFloat128Type() &&
1553 !S.getLangOpts().SYCLIsDevice &&
1554 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1555 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1556 << "__float128";
1557 Result = Context.Float128Ty;
1558 break;
1559 case DeclSpec::TST_ibm128:
1560 if (!S.Context.getTargetInfo().hasIbm128Type() &&
1561 !S.getLangOpts().SYCLIsDevice &&
1562 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1563 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128";
1564 Result = Context.Ibm128Ty;
1565 break;
1566 case DeclSpec::TST_bool:
1567 Result = Context.BoolTy; // _Bool or bool
1568 break;
1569 case DeclSpec::TST_decimal32: // _Decimal32
1570 case DeclSpec::TST_decimal64: // _Decimal64
1571 case DeclSpec::TST_decimal128: // _Decimal128
1572 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1573 Result = Context.IntTy;
1574 declarator.setInvalidType(true);
1575 break;
1576 case DeclSpec::TST_class:
1577 case DeclSpec::TST_enum:
1578 case DeclSpec::TST_union:
1579 case DeclSpec::TST_struct:
1580 case DeclSpec::TST_interface: {
1581 TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1582 if (!D) {
1583 // This can happen in C++ with ambiguous lookups.
1584 Result = Context.IntTy;
1585 declarator.setInvalidType(true);
1586 break;
1589 // If the type is deprecated or unavailable, diagnose it.
1590 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1592 assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1593 DS.getTypeSpecComplex() == 0 &&
1594 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1595 "No qualifiers on tag names!");
1597 // TypeQuals handled by caller.
1598 Result = Context.getTypeDeclType(D);
1600 // In both C and C++, make an ElaboratedType.
1601 ElaboratedTypeKeyword Keyword
1602 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1603 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
1604 DS.isTypeSpecOwned() ? D : nullptr);
1605 break;
1607 case DeclSpec::TST_typename: {
1608 assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1609 DS.getTypeSpecComplex() == 0 &&
1610 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1611 "Can't handle qualifiers on typedef names yet!");
1612 Result = S.GetTypeFromParser(DS.getRepAsType());
1613 if (Result.isNull()) {
1614 declarator.setInvalidType(true);
1617 // TypeQuals handled by caller.
1618 break;
1620 case DeclSpec::TST_typeof_unqualType:
1621 case DeclSpec::TST_typeofType:
1622 // FIXME: Preserve type source info.
1623 Result = S.GetTypeFromParser(DS.getRepAsType());
1624 assert(!Result.isNull() && "Didn't get a type for typeof?");
1625 if (!Result->isDependentType())
1626 if (const TagType *TT = Result->getAs<TagType>())
1627 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1628 // TypeQuals handled by caller.
1629 Result = Context.getTypeOfType(
1630 Result, DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType
1631 ? TypeOfKind::Unqualified
1632 : TypeOfKind::Qualified);
1633 break;
1634 case DeclSpec::TST_typeof_unqualExpr:
1635 case DeclSpec::TST_typeofExpr: {
1636 Expr *E = DS.getRepAsExpr();
1637 assert(E && "Didn't get an expression for typeof?");
1638 // TypeQuals handled by caller.
1639 Result = S.BuildTypeofExprType(E, DS.getTypeSpecType() ==
1640 DeclSpec::TST_typeof_unqualExpr
1641 ? TypeOfKind::Unqualified
1642 : TypeOfKind::Qualified);
1643 if (Result.isNull()) {
1644 Result = Context.IntTy;
1645 declarator.setInvalidType(true);
1647 break;
1649 case DeclSpec::TST_decltype: {
1650 Expr *E = DS.getRepAsExpr();
1651 assert(E && "Didn't get an expression for decltype?");
1652 // TypeQuals handled by caller.
1653 Result = S.BuildDecltypeType(E);
1654 if (Result.isNull()) {
1655 Result = Context.IntTy;
1656 declarator.setInvalidType(true);
1658 break;
1660 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
1661 #include "clang/Basic/TransformTypeTraits.def"
1662 Result = S.GetTypeFromParser(DS.getRepAsType());
1663 assert(!Result.isNull() && "Didn't get a type for the transformation?");
1664 Result = S.BuildUnaryTransformType(
1665 Result, TSTToUnaryTransformType(DS.getTypeSpecType()),
1666 DS.getTypeSpecTypeLoc());
1667 if (Result.isNull()) {
1668 Result = Context.IntTy;
1669 declarator.setInvalidType(true);
1671 break;
1673 case DeclSpec::TST_auto:
1674 case DeclSpec::TST_decltype_auto: {
1675 auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1676 ? AutoTypeKeyword::DecltypeAuto
1677 : AutoTypeKeyword::Auto;
1679 ConceptDecl *TypeConstraintConcept = nullptr;
1680 llvm::SmallVector<TemplateArgument, 8> TemplateArgs;
1681 if (DS.isConstrainedAuto()) {
1682 if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1683 TypeConstraintConcept =
1684 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl());
1685 TemplateArgumentListInfo TemplateArgsInfo;
1686 TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1687 TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1688 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1689 TemplateId->NumArgs);
1690 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1691 for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1692 TemplateArgs.push_back(ArgLoc.getArgument());
1693 } else {
1694 declarator.setInvalidType(true);
1697 Result = S.Context.getAutoType(QualType(), AutoKW,
1698 /*IsDependent*/ false, /*IsPack=*/false,
1699 TypeConstraintConcept, TemplateArgs);
1700 break;
1703 case DeclSpec::TST_auto_type:
1704 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1705 break;
1707 case DeclSpec::TST_unknown_anytype:
1708 Result = Context.UnknownAnyTy;
1709 break;
1711 case DeclSpec::TST_atomic:
1712 Result = S.GetTypeFromParser(DS.getRepAsType());
1713 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1714 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1715 if (Result.isNull()) {
1716 Result = Context.IntTy;
1717 declarator.setInvalidType(true);
1719 break;
1721 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
1722 case DeclSpec::TST_##ImgType##_t: \
1723 switch (getImageAccess(DS.getAttributes())) { \
1724 case OpenCLAccessAttr::Keyword_write_only: \
1725 Result = Context.Id##WOTy; \
1726 break; \
1727 case OpenCLAccessAttr::Keyword_read_write: \
1728 Result = Context.Id##RWTy; \
1729 break; \
1730 case OpenCLAccessAttr::Keyword_read_only: \
1731 Result = Context.Id##ROTy; \
1732 break; \
1733 case OpenCLAccessAttr::SpellingNotCalculated: \
1734 llvm_unreachable("Spelling not yet calculated"); \
1736 break;
1737 #include "clang/Basic/OpenCLImageTypes.def"
1739 case DeclSpec::TST_error:
1740 Result = Context.IntTy;
1741 declarator.setInvalidType(true);
1742 break;
1745 // FIXME: we want resulting declarations to be marked invalid, but claiming
1746 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1747 // a null type.
1748 if (Result->containsErrors())
1749 declarator.setInvalidType();
1751 if (S.getLangOpts().OpenCL) {
1752 const auto &OpenCLOptions = S.getOpenCLOptions();
1753 bool IsOpenCLC30Compatible =
1754 S.getLangOpts().getOpenCLCompatibleVersion() == 300;
1755 // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1756 // support.
1757 // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1758 // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1759 // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1760 // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1761 // only when the optional feature is supported
1762 if ((Result->isImageType() || Result->isSamplerT()) &&
1763 (IsOpenCLC30Compatible &&
1764 !OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts()))) {
1765 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1766 << 0 << Result << "__opencl_c_images";
1767 declarator.setInvalidType();
1768 } else if (Result->isOCLImage3dWOType() &&
1769 !OpenCLOptions.isSupported("cl_khr_3d_image_writes",
1770 S.getLangOpts())) {
1771 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1772 << 0 << Result
1773 << (IsOpenCLC30Compatible
1774 ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes"
1775 : "cl_khr_3d_image_writes");
1776 declarator.setInvalidType();
1780 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1781 DS.getTypeSpecType() == DeclSpec::TST_fract;
1783 // Only fixed point types can be saturated
1784 if (DS.isTypeSpecSat() && !IsFixedPointType)
1785 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1786 << DS.getSpecifierName(DS.getTypeSpecType(),
1787 Context.getPrintingPolicy());
1789 // Handle complex types.
1790 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1791 if (S.getLangOpts().Freestanding)
1792 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1793 Result = Context.getComplexType(Result);
1794 } else if (DS.isTypeAltiVecVector()) {
1795 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1796 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1797 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1798 if (DS.isTypeAltiVecPixel())
1799 VecKind = VectorType::AltiVecPixel;
1800 else if (DS.isTypeAltiVecBool())
1801 VecKind = VectorType::AltiVecBool;
1802 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1805 // FIXME: Imaginary.
1806 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1807 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1809 // Before we process any type attributes, synthesize a block literal
1810 // function declarator if necessary.
1811 if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1812 maybeSynthesizeBlockSignature(state, Result);
1814 // Apply any type attributes from the decl spec. This may cause the
1815 // list of type attributes to be temporarily saved while the type
1816 // attributes are pushed around.
1817 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1818 if (!DS.isTypeSpecPipe()) {
1819 // We also apply declaration attributes that "slide" to the decl spec.
1820 // Ordering can be important for attributes. The decalaration attributes
1821 // come syntactically before the decl spec attributes, so we process them
1822 // in that order.
1823 ParsedAttributesView SlidingAttrs;
1824 for (ParsedAttr &AL : declarator.getDeclarationAttributes()) {
1825 if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
1826 SlidingAttrs.addAtEnd(&AL);
1828 // For standard syntax attributes, which would normally appertain to the
1829 // declaration here, suggest moving them to the type instead. But only
1830 // do this for our own vendor attributes; moving other vendors'
1831 // attributes might hurt portability.
1832 // There's one special case that we need to deal with here: The
1833 // `MatrixType` attribute may only be used in a typedef declaration. If
1834 // it's being used anywhere else, don't output the warning as
1835 // ProcessDeclAttributes() will output an error anyway.
1836 if (AL.isStandardAttributeSyntax() && AL.isClangScope() &&
1837 !(AL.getKind() == ParsedAttr::AT_MatrixType &&
1838 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)) {
1839 S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl)
1840 << AL;
1844 // During this call to processTypeAttrs(),
1845 // TypeProcessingState::getCurrentAttributes() will erroneously return a
1846 // reference to the DeclSpec attributes, rather than the declaration
1847 // attributes. However, this doesn't matter, as getCurrentAttributes()
1848 // is only called when distributing attributes from one attribute list
1849 // to another. Declaration attributes are always C++11 attributes, and these
1850 // are never distributed.
1851 processTypeAttrs(state, Result, TAL_DeclSpec, SlidingAttrs);
1852 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
1855 // Apply const/volatile/restrict qualifiers to T.
1856 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1857 // Warn about CV qualifiers on function types.
1858 // C99 6.7.3p8:
1859 // If the specification of a function type includes any type qualifiers,
1860 // the behavior is undefined.
1861 // C++11 [dcl.fct]p7:
1862 // The effect of a cv-qualifier-seq in a function declarator is not the
1863 // same as adding cv-qualification on top of the function type. In the
1864 // latter case, the cv-qualifiers are ignored.
1865 if (Result->isFunctionType()) {
1866 diagnoseAndRemoveTypeQualifiers(
1867 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1868 S.getLangOpts().CPlusPlus
1869 ? diag::warn_typecheck_function_qualifiers_ignored
1870 : diag::warn_typecheck_function_qualifiers_unspecified);
1871 // No diagnostic for 'restrict' or '_Atomic' applied to a
1872 // function type; we'll diagnose those later, in BuildQualifiedType.
1875 // C++11 [dcl.ref]p1:
1876 // Cv-qualified references are ill-formed except when the
1877 // cv-qualifiers are introduced through the use of a typedef-name
1878 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1880 // There don't appear to be any other contexts in which a cv-qualified
1881 // reference type could be formed, so the 'ill-formed' clause here appears
1882 // to never happen.
1883 if (TypeQuals && Result->isReferenceType()) {
1884 diagnoseAndRemoveTypeQualifiers(
1885 S, DS, TypeQuals, Result,
1886 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1887 diag::warn_typecheck_reference_qualifiers);
1890 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1891 // than once in the same specifier-list or qualifier-list, either directly
1892 // or via one or more typedefs."
1893 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1894 && TypeQuals & Result.getCVRQualifiers()) {
1895 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1896 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1897 << "const";
1900 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1901 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1902 << "volatile";
1905 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1906 // produce a warning in this case.
1909 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1911 // If adding qualifiers fails, just use the unqualified type.
1912 if (Qualified.isNull())
1913 declarator.setInvalidType(true);
1914 else
1915 Result = Qualified;
1918 assert(!Result.isNull() && "This function should not return a null type");
1919 return Result;
1922 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1923 if (Entity)
1924 return Entity.getAsString();
1926 return "type name";
1929 static bool isDependentOrGNUAutoType(QualType T) {
1930 if (T->isDependentType())
1931 return true;
1933 const auto *AT = dyn_cast<AutoType>(T);
1934 return AT && AT->isGNUAutoType();
1937 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1938 Qualifiers Qs, const DeclSpec *DS) {
1939 if (T.isNull())
1940 return QualType();
1942 // Ignore any attempt to form a cv-qualified reference.
1943 if (T->isReferenceType()) {
1944 Qs.removeConst();
1945 Qs.removeVolatile();
1948 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1949 // object or incomplete types shall not be restrict-qualified."
1950 if (Qs.hasRestrict()) {
1951 unsigned DiagID = 0;
1952 QualType ProblemTy;
1954 if (T->isAnyPointerType() || T->isReferenceType() ||
1955 T->isMemberPointerType()) {
1956 QualType EltTy;
1957 if (T->isObjCObjectPointerType())
1958 EltTy = T;
1959 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1960 EltTy = PTy->getPointeeType();
1961 else
1962 EltTy = T->getPointeeType();
1964 // If we have a pointer or reference, the pointee must have an object
1965 // incomplete type.
1966 if (!EltTy->isIncompleteOrObjectType()) {
1967 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1968 ProblemTy = EltTy;
1970 } else if (!isDependentOrGNUAutoType(T)) {
1971 // For an __auto_type variable, we may not have seen the initializer yet
1972 // and so have no idea whether the underlying type is a pointer type or
1973 // not.
1974 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1975 ProblemTy = T;
1978 if (DiagID) {
1979 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1980 Qs.removeRestrict();
1984 return Context.getQualifiedType(T, Qs);
1987 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1988 unsigned CVRAU, const DeclSpec *DS) {
1989 if (T.isNull())
1990 return QualType();
1992 // Ignore any attempt to form a cv-qualified reference.
1993 if (T->isReferenceType())
1994 CVRAU &=
1995 ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1997 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1998 // TQ_unaligned;
1999 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
2001 // C11 6.7.3/5:
2002 // If the same qualifier appears more than once in the same
2003 // specifier-qualifier-list, either directly or via one or more typedefs,
2004 // the behavior is the same as if it appeared only once.
2006 // It's not specified what happens when the _Atomic qualifier is applied to
2007 // a type specified with the _Atomic specifier, but we assume that this
2008 // should be treated as if the _Atomic qualifier appeared multiple times.
2009 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
2010 // C11 6.7.3/5:
2011 // If other qualifiers appear along with the _Atomic qualifier in a
2012 // specifier-qualifier-list, the resulting type is the so-qualified
2013 // atomic type.
2015 // Don't need to worry about array types here, since _Atomic can't be
2016 // applied to such types.
2017 SplitQualType Split = T.getSplitUnqualifiedType();
2018 T = BuildAtomicType(QualType(Split.Ty, 0),
2019 DS ? DS->getAtomicSpecLoc() : Loc);
2020 if (T.isNull())
2021 return T;
2022 Split.Quals.addCVRQualifiers(CVR);
2023 return BuildQualifiedType(T, Loc, Split.Quals);
2026 Qualifiers Q = Qualifiers::fromCVRMask(CVR);
2027 Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
2028 return BuildQualifiedType(T, Loc, Q, DS);
2031 /// Build a paren type including \p T.
2032 QualType Sema::BuildParenType(QualType T) {
2033 return Context.getParenType(T);
2036 /// Given that we're building a pointer or reference to the given
2037 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
2038 SourceLocation loc,
2039 bool isReference) {
2040 // Bail out if retention is unrequired or already specified.
2041 if (!type->isObjCLifetimeType() ||
2042 type.getObjCLifetime() != Qualifiers::OCL_None)
2043 return type;
2045 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
2047 // If the object type is const-qualified, we can safely use
2048 // __unsafe_unretained. This is safe (because there are no read
2049 // barriers), and it'll be safe to coerce anything but __weak* to
2050 // the resulting type.
2051 if (type.isConstQualified()) {
2052 implicitLifetime = Qualifiers::OCL_ExplicitNone;
2054 // Otherwise, check whether the static type does not require
2055 // retaining. This currently only triggers for Class (possibly
2056 // protocol-qualifed, and arrays thereof).
2057 } else if (type->isObjCARCImplicitlyUnretainedType()) {
2058 implicitLifetime = Qualifiers::OCL_ExplicitNone;
2060 // If we are in an unevaluated context, like sizeof, skip adding a
2061 // qualification.
2062 } else if (S.isUnevaluatedContext()) {
2063 return type;
2065 // If that failed, give an error and recover using __strong. __strong
2066 // is the option most likely to prevent spurious second-order diagnostics,
2067 // like when binding a reference to a field.
2068 } else {
2069 // These types can show up in private ivars in system headers, so
2070 // we need this to not be an error in those cases. Instead we
2071 // want to delay.
2072 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
2073 S.DelayedDiagnostics.add(
2074 sema::DelayedDiagnostic::makeForbiddenType(loc,
2075 diag::err_arc_indirect_no_ownership, type, isReference));
2076 } else {
2077 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
2079 implicitLifetime = Qualifiers::OCL_Strong;
2081 assert(implicitLifetime && "didn't infer any lifetime!");
2083 Qualifiers qs;
2084 qs.addObjCLifetime(implicitLifetime);
2085 return S.Context.getQualifiedType(type, qs);
2088 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
2089 std::string Quals = FnTy->getMethodQuals().getAsString();
2091 switch (FnTy->getRefQualifier()) {
2092 case RQ_None:
2093 break;
2095 case RQ_LValue:
2096 if (!Quals.empty())
2097 Quals += ' ';
2098 Quals += '&';
2099 break;
2101 case RQ_RValue:
2102 if (!Quals.empty())
2103 Quals += ' ';
2104 Quals += "&&";
2105 break;
2108 return Quals;
2111 namespace {
2112 /// Kinds of declarator that cannot contain a qualified function type.
2114 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
2115 /// a function type with a cv-qualifier or a ref-qualifier can only appear
2116 /// at the topmost level of a type.
2118 /// Parens and member pointers are permitted. We don't diagnose array and
2119 /// function declarators, because they don't allow function types at all.
2121 /// The values of this enum are used in diagnostics.
2122 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
2123 } // end anonymous namespace
2125 /// Check whether the type T is a qualified function type, and if it is,
2126 /// diagnose that it cannot be contained within the given kind of declarator.
2127 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
2128 QualifiedFunctionKind QFK) {
2129 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2130 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2131 if (!FPT ||
2132 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2133 return false;
2135 S.Diag(Loc, diag::err_compound_qualified_function_type)
2136 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
2137 << getFunctionQualifiersAsString(FPT);
2138 return true;
2141 bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) {
2142 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2143 if (!FPT ||
2144 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2145 return false;
2147 Diag(Loc, diag::err_qualified_function_typeid)
2148 << T << getFunctionQualifiersAsString(FPT);
2149 return true;
2152 // Helper to deduce addr space of a pointee type in OpenCL mode.
2153 static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType) {
2154 if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
2155 !PointeeType->isSamplerT() &&
2156 !PointeeType.hasAddressSpace())
2157 PointeeType = S.getASTContext().getAddrSpaceQualType(
2158 PointeeType, S.getASTContext().getDefaultOpenCLPointeeAddrSpace());
2159 return PointeeType;
2162 /// Build a pointer type.
2164 /// \param T The type to which we'll be building a pointer.
2166 /// \param Loc The location of the entity whose type involves this
2167 /// pointer type or, if there is no such entity, the location of the
2168 /// type that will have pointer type.
2170 /// \param Entity The name of the entity that involves the pointer
2171 /// type, if known.
2173 /// \returns A suitable pointer type, if there are no
2174 /// errors. Otherwise, returns a NULL type.
2175 QualType Sema::BuildPointerType(QualType T,
2176 SourceLocation Loc, DeclarationName Entity) {
2177 if (T->isReferenceType()) {
2178 // C++ 8.3.2p4: There shall be no ... pointers to references ...
2179 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
2180 << getPrintableNameForEntity(Entity) << T;
2181 return QualType();
2184 if (T->isFunctionType() && getLangOpts().OpenCL &&
2185 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2186 getLangOpts())) {
2187 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2188 return QualType();
2191 if (getLangOpts().HLSL && Loc.isValid()) {
2192 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
2193 return QualType();
2196 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
2197 return QualType();
2199 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
2201 // In ARC, it is forbidden to build pointers to unqualified pointers.
2202 if (getLangOpts().ObjCAutoRefCount)
2203 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
2205 if (getLangOpts().OpenCL)
2206 T = deduceOpenCLPointeeAddrSpace(*this, T);
2208 // In WebAssembly, pointers to reference types and pointers to tables are
2209 // illegal.
2210 if (getASTContext().getTargetInfo().getTriple().isWasm()) {
2211 if (T.isWebAssemblyReferenceType()) {
2212 Diag(Loc, diag::err_wasm_reference_pr) << 0;
2213 return QualType();
2216 // We need to desugar the type here in case T is a ParenType.
2217 if (T->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
2218 Diag(Loc, diag::err_wasm_table_pr) << 0;
2219 return QualType();
2223 // Build the pointer type.
2224 return Context.getPointerType(T);
2227 /// Build a reference type.
2229 /// \param T The type to which we'll be building a reference.
2231 /// \param Loc The location of the entity whose type involves this
2232 /// reference type or, if there is no such entity, the location of the
2233 /// type that will have reference type.
2235 /// \param Entity The name of the entity that involves the reference
2236 /// type, if known.
2238 /// \returns A suitable reference type, if there are no
2239 /// errors. Otherwise, returns a NULL type.
2240 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
2241 SourceLocation Loc,
2242 DeclarationName Entity) {
2243 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
2244 "Unresolved overloaded function type");
2246 // C++0x [dcl.ref]p6:
2247 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
2248 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
2249 // type T, an attempt to create the type "lvalue reference to cv TR" creates
2250 // the type "lvalue reference to T", while an attempt to create the type
2251 // "rvalue reference to cv TR" creates the type TR.
2252 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
2254 // C++ [dcl.ref]p4: There shall be no references to references.
2256 // According to C++ DR 106, references to references are only
2257 // diagnosed when they are written directly (e.g., "int & &"),
2258 // but not when they happen via a typedef:
2260 // typedef int& intref;
2261 // typedef intref& intref2;
2263 // Parser::ParseDeclaratorInternal diagnoses the case where
2264 // references are written directly; here, we handle the
2265 // collapsing of references-to-references as described in C++0x.
2266 // DR 106 and 540 introduce reference-collapsing into C++98/03.
2268 // C++ [dcl.ref]p1:
2269 // A declarator that specifies the type "reference to cv void"
2270 // is ill-formed.
2271 if (T->isVoidType()) {
2272 Diag(Loc, diag::err_reference_to_void);
2273 return QualType();
2276 if (getLangOpts().HLSL && Loc.isValid()) {
2277 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1;
2278 return QualType();
2281 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2282 return QualType();
2284 if (T->isFunctionType() && getLangOpts().OpenCL &&
2285 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2286 getLangOpts())) {
2287 Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1;
2288 return QualType();
2291 // In ARC, it is forbidden to build references to unqualified pointers.
2292 if (getLangOpts().ObjCAutoRefCount)
2293 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2295 if (getLangOpts().OpenCL)
2296 T = deduceOpenCLPointeeAddrSpace(*this, T);
2298 // In WebAssembly, references to reference types and tables are illegal.
2299 if (getASTContext().getTargetInfo().getTriple().isWasm() &&
2300 T.isWebAssemblyReferenceType()) {
2301 Diag(Loc, diag::err_wasm_reference_pr) << 1;
2302 return QualType();
2304 if (T->isWebAssemblyTableType()) {
2305 Diag(Loc, diag::err_wasm_table_pr) << 1;
2306 return QualType();
2309 // Handle restrict on references.
2310 if (LValueRef)
2311 return Context.getLValueReferenceType(T, SpelledAsLValue);
2312 return Context.getRValueReferenceType(T);
2315 /// Build a Read-only Pipe type.
2317 /// \param T The type to which we'll be building a Pipe.
2319 /// \param Loc We do not use it for now.
2321 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2322 /// NULL type.
2323 QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
2324 return Context.getReadPipeType(T);
2327 /// Build a Write-only Pipe type.
2329 /// \param T The type to which we'll be building a Pipe.
2331 /// \param Loc We do not use it for now.
2333 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2334 /// NULL type.
2335 QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
2336 return Context.getWritePipeType(T);
2339 /// Build a bit-precise integer type.
2341 /// \param IsUnsigned Boolean representing the signedness of the type.
2343 /// \param BitWidth Size of this int type in bits, or an expression representing
2344 /// that.
2346 /// \param Loc Location of the keyword.
2347 QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth,
2348 SourceLocation Loc) {
2349 if (BitWidth->isInstantiationDependent())
2350 return Context.getDependentBitIntType(IsUnsigned, BitWidth);
2352 llvm::APSInt Bits(32);
2353 ExprResult ICE =
2354 VerifyIntegerConstantExpression(BitWidth, &Bits, /*FIXME*/ AllowFold);
2356 if (ICE.isInvalid())
2357 return QualType();
2359 size_t NumBits = Bits.getZExtValue();
2360 if (!IsUnsigned && NumBits < 2) {
2361 Diag(Loc, diag::err_bit_int_bad_size) << 0;
2362 return QualType();
2365 if (IsUnsigned && NumBits < 1) {
2366 Diag(Loc, diag::err_bit_int_bad_size) << 1;
2367 return QualType();
2370 const TargetInfo &TI = getASTContext().getTargetInfo();
2371 if (NumBits > TI.getMaxBitIntWidth()) {
2372 Diag(Loc, diag::err_bit_int_max_size)
2373 << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth());
2374 return QualType();
2377 return Context.getBitIntType(IsUnsigned, NumBits);
2380 /// Check whether the specified array bound can be evaluated using the relevant
2381 /// language rules. If so, returns the possibly-converted expression and sets
2382 /// SizeVal to the size. If not, but the expression might be a VLA bound,
2383 /// returns ExprResult(). Otherwise, produces a diagnostic and returns
2384 /// ExprError().
2385 static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
2386 llvm::APSInt &SizeVal, unsigned VLADiag,
2387 bool VLAIsError) {
2388 if (S.getLangOpts().CPlusPlus14 &&
2389 (VLAIsError ||
2390 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) {
2391 // C++14 [dcl.array]p1:
2392 // The constant-expression shall be a converted constant expression of
2393 // type std::size_t.
2395 // Don't apply this rule if we might be forming a VLA: in that case, we
2396 // allow non-constant expressions and constant-folding. We only need to use
2397 // the converted constant expression rules (to properly convert the source)
2398 // when the source expression is of class type.
2399 return S.CheckConvertedConstantExpression(
2400 ArraySize, S.Context.getSizeType(), SizeVal, Sema::CCEK_ArrayBound);
2403 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2404 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2405 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2406 public:
2407 unsigned VLADiag;
2408 bool VLAIsError;
2409 bool IsVLA = false;
2411 VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2412 : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2414 Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2415 QualType T) override {
2416 return S.Diag(Loc, diag::err_array_size_non_int) << T;
2419 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2420 SourceLocation Loc) override {
2421 IsVLA = !VLAIsError;
2422 return S.Diag(Loc, VLADiag);
2425 Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2426 SourceLocation Loc) override {
2427 return S.Diag(Loc, diag::ext_vla_folded_to_constant);
2429 } Diagnoser(VLADiag, VLAIsError);
2431 ExprResult R =
2432 S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser);
2433 if (Diagnoser.IsVLA)
2434 return ExprResult();
2435 return R;
2438 bool Sema::checkArrayElementAlignment(QualType EltTy, SourceLocation Loc) {
2439 EltTy = Context.getBaseElementType(EltTy);
2440 if (EltTy->isIncompleteType() || EltTy->isDependentType() ||
2441 EltTy->isUndeducedType())
2442 return true;
2444 CharUnits Size = Context.getTypeSizeInChars(EltTy);
2445 CharUnits Alignment = Context.getTypeAlignInChars(EltTy);
2447 if (Size.isMultipleOf(Alignment))
2448 return true;
2450 Diag(Loc, diag::err_array_element_alignment)
2451 << EltTy << Size.getQuantity() << Alignment.getQuantity();
2452 return false;
2455 /// Build an array type.
2457 /// \param T The type of each element in the array.
2459 /// \param ASM C99 array size modifier (e.g., '*', 'static').
2461 /// \param ArraySize Expression describing the size of the array.
2463 /// \param Brackets The range from the opening '[' to the closing ']'.
2465 /// \param Entity The name of the entity that involves the array
2466 /// type, if known.
2468 /// \returns A suitable array type, if there are no errors. Otherwise,
2469 /// returns a NULL type.
2470 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2471 Expr *ArraySize, unsigned Quals,
2472 SourceRange Brackets, DeclarationName Entity) {
2474 SourceLocation Loc = Brackets.getBegin();
2475 if (getLangOpts().CPlusPlus) {
2476 // C++ [dcl.array]p1:
2477 // T is called the array element type; this type shall not be a reference
2478 // type, the (possibly cv-qualified) type void, a function type or an
2479 // abstract class type.
2481 // C++ [dcl.array]p3:
2482 // When several "array of" specifications are adjacent, [...] only the
2483 // first of the constant expressions that specify the bounds of the arrays
2484 // may be omitted.
2486 // Note: function types are handled in the common path with C.
2487 if (T->isReferenceType()) {
2488 Diag(Loc, diag::err_illegal_decl_array_of_references)
2489 << getPrintableNameForEntity(Entity) << T;
2490 return QualType();
2493 if (T->isVoidType() || T->isIncompleteArrayType()) {
2494 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2495 return QualType();
2498 if (RequireNonAbstractType(Brackets.getBegin(), T,
2499 diag::err_array_of_abstract_type))
2500 return QualType();
2502 // Mentioning a member pointer type for an array type causes us to lock in
2503 // an inheritance model, even if it's inside an unused typedef.
2504 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2505 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2506 if (!MPTy->getClass()->isDependentType())
2507 (void)isCompleteType(Loc, T);
2509 } else {
2510 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2511 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2512 if (!T.isWebAssemblyReferenceType() &&
2513 RequireCompleteSizedType(Loc, T,
2514 diag::err_array_incomplete_or_sizeless_type))
2515 return QualType();
2518 // Multi-dimensional arrays of WebAssembly references are not allowed.
2519 if (Context.getTargetInfo().getTriple().isWasm() && T->isArrayType()) {
2520 const auto *ATy = dyn_cast<ArrayType>(T);
2521 if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
2522 Diag(Loc, diag::err_wasm_reftype_multidimensional_array);
2523 return QualType();
2527 if (T->isSizelessType() && !T.isWebAssemblyReferenceType()) {
2528 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2529 return QualType();
2532 if (T->isFunctionType()) {
2533 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2534 << getPrintableNameForEntity(Entity) << T;
2535 return QualType();
2538 if (const RecordType *EltTy = T->getAs<RecordType>()) {
2539 // If the element type is a struct or union that contains a variadic
2540 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2541 if (EltTy->getDecl()->hasFlexibleArrayMember())
2542 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2543 } else if (T->isObjCObjectType()) {
2544 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2545 return QualType();
2548 if (!checkArrayElementAlignment(T, Loc))
2549 return QualType();
2551 // Do placeholder conversions on the array size expression.
2552 if (ArraySize && ArraySize->hasPlaceholderType()) {
2553 ExprResult Result = CheckPlaceholderExpr(ArraySize);
2554 if (Result.isInvalid()) return QualType();
2555 ArraySize = Result.get();
2558 // Do lvalue-to-rvalue conversions on the array size expression.
2559 if (ArraySize && !ArraySize->isPRValue()) {
2560 ExprResult Result = DefaultLvalueConversion(ArraySize);
2561 if (Result.isInvalid())
2562 return QualType();
2564 ArraySize = Result.get();
2567 // C99 6.7.5.2p1: The size expression shall have integer type.
2568 // C++11 allows contextual conversions to such types.
2569 if (!getLangOpts().CPlusPlus11 &&
2570 ArraySize && !ArraySize->isTypeDependent() &&
2571 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2572 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2573 << ArraySize->getType() << ArraySize->getSourceRange();
2574 return QualType();
2577 // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2578 unsigned VLADiag;
2579 bool VLAIsError;
2580 if (getLangOpts().OpenCL) {
2581 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2582 VLADiag = diag::err_opencl_vla;
2583 VLAIsError = true;
2584 } else if (getLangOpts().C99) {
2585 VLADiag = diag::warn_vla_used;
2586 VLAIsError = false;
2587 } else if (isSFINAEContext()) {
2588 VLADiag = diag::err_vla_in_sfinae;
2589 VLAIsError = true;
2590 } else if (getLangOpts().OpenMP && isInOpenMPTaskUntiedContext()) {
2591 VLADiag = diag::err_openmp_vla_in_task_untied;
2592 VLAIsError = true;
2593 } else {
2594 VLADiag = diag::ext_vla;
2595 VLAIsError = false;
2598 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2599 if (!ArraySize) {
2600 if (ASM == ArrayType::Star) {
2601 Diag(Loc, VLADiag);
2602 if (VLAIsError)
2603 return QualType();
2605 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2606 } else {
2607 T = Context.getIncompleteArrayType(T, ASM, Quals);
2609 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2610 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2611 } else {
2612 ExprResult R =
2613 checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError);
2614 if (R.isInvalid())
2615 return QualType();
2617 if (!R.isUsable()) {
2618 // C99: an array with a non-ICE size is a VLA. We accept any expression
2619 // that we can fold to a non-zero positive value as a non-VLA as an
2620 // extension.
2621 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2622 } else if (!T->isDependentType() && !T->isIncompleteType() &&
2623 !T->isConstantSizeType()) {
2624 // C99: an array with an element type that has a non-constant-size is a
2625 // VLA.
2626 // FIXME: Add a note to explain why this isn't a VLA.
2627 Diag(Loc, VLADiag);
2628 if (VLAIsError)
2629 return QualType();
2630 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2631 } else {
2632 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2633 // have a value greater than zero.
2634 // In C++, this follows from narrowing conversions being disallowed.
2635 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2636 if (Entity)
2637 Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2638 << getPrintableNameForEntity(Entity)
2639 << ArraySize->getSourceRange();
2640 else
2641 Diag(ArraySize->getBeginLoc(),
2642 diag::err_typecheck_negative_array_size)
2643 << ArraySize->getSourceRange();
2644 return QualType();
2646 if (ConstVal == 0 && !T.isWebAssemblyReferenceType()) {
2647 // GCC accepts zero sized static arrays. We allow them when
2648 // we're not in a SFINAE context.
2649 Diag(ArraySize->getBeginLoc(),
2650 isSFINAEContext() ? diag::err_typecheck_zero_array_size
2651 : diag::ext_typecheck_zero_array_size)
2652 << 0 << ArraySize->getSourceRange();
2655 // Is the array too large?
2656 unsigned ActiveSizeBits =
2657 (!T->isDependentType() && !T->isVariablyModifiedType() &&
2658 !T->isIncompleteType() && !T->isUndeducedType())
2659 ? ConstantArrayType::getNumAddressingBits(Context, T, ConstVal)
2660 : ConstVal.getActiveBits();
2661 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2662 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2663 << toString(ConstVal, 10) << ArraySize->getSourceRange();
2664 return QualType();
2667 T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2671 if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) {
2672 // CUDA device code and some other targets don't support VLAs.
2673 bool IsCUDADevice = (getLangOpts().CUDA && getLangOpts().CUDAIsDevice);
2674 targetDiag(Loc,
2675 IsCUDADevice ? diag::err_cuda_vla : diag::err_vla_unsupported)
2676 << (IsCUDADevice ? CurrentCUDATarget() : 0);
2679 // If this is not C99, diagnose array size modifiers on non-VLAs.
2680 if (!getLangOpts().C99 && !T->isVariableArrayType() &&
2681 (ASM != ArrayType::Normal || Quals != 0)) {
2682 Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx
2683 : diag::ext_c99_array_usage)
2684 << ASM;
2687 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2688 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2689 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2690 if (getLangOpts().OpenCL) {
2691 const QualType ArrType = Context.getBaseElementType(T);
2692 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2693 ArrType->isSamplerT() || ArrType->isImageType()) {
2694 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2695 return QualType();
2699 return T;
2702 QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
2703 SourceLocation AttrLoc) {
2704 // The base type must be integer (not Boolean or enumeration) or float, and
2705 // can't already be a vector.
2706 if ((!CurType->isDependentType() &&
2707 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2708 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) &&
2709 !CurType->isBitIntType()) ||
2710 CurType->isArrayType()) {
2711 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2712 return QualType();
2714 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2715 if (const auto *BIT = CurType->getAs<BitIntType>()) {
2716 unsigned NumBits = BIT->getNumBits();
2717 if (!llvm::isPowerOf2_32(NumBits) || NumBits < 8) {
2718 Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2719 << (NumBits < 8);
2720 return QualType();
2724 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2725 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2726 VectorType::GenericVector);
2728 std::optional<llvm::APSInt> VecSize =
2729 SizeExpr->getIntegerConstantExpr(Context);
2730 if (!VecSize) {
2731 Diag(AttrLoc, diag::err_attribute_argument_type)
2732 << "vector_size" << AANT_ArgumentIntegerConstant
2733 << SizeExpr->getSourceRange();
2734 return QualType();
2737 if (CurType->isDependentType())
2738 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2739 VectorType::GenericVector);
2741 // vecSize is specified in bytes - convert to bits.
2742 if (!VecSize->isIntN(61)) {
2743 // Bit size will overflow uint64.
2744 Diag(AttrLoc, diag::err_attribute_size_too_large)
2745 << SizeExpr->getSourceRange() << "vector";
2746 return QualType();
2748 uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2749 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2751 if (VectorSizeBits == 0) {
2752 Diag(AttrLoc, diag::err_attribute_zero_size)
2753 << SizeExpr->getSourceRange() << "vector";
2754 return QualType();
2757 if (!TypeSize || VectorSizeBits % TypeSize) {
2758 Diag(AttrLoc, diag::err_attribute_invalid_size)
2759 << SizeExpr->getSourceRange();
2760 return QualType();
2763 if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2764 Diag(AttrLoc, diag::err_attribute_size_too_large)
2765 << SizeExpr->getSourceRange() << "vector";
2766 return QualType();
2769 return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2770 VectorType::GenericVector);
2773 /// Build an ext-vector type.
2775 /// Run the required checks for the extended vector type.
2776 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2777 SourceLocation AttrLoc) {
2778 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2779 // in conjunction with complex types (pointers, arrays, functions, etc.).
2781 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2782 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2783 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2784 // of bool aren't allowed.
2786 // We explictly allow bool elements in ext_vector_type for C/C++.
2787 bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus;
2788 if ((!T->isDependentType() && !T->isIntegerType() &&
2789 !T->isRealFloatingType()) ||
2790 (IsNoBoolVecLang && T->isBooleanType())) {
2791 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2792 return QualType();
2795 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2796 if (T->isBitIntType()) {
2797 unsigned NumBits = T->castAs<BitIntType>()->getNumBits();
2798 if (!llvm::isPowerOf2_32(NumBits) || NumBits < 8) {
2799 Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2800 << (NumBits < 8);
2801 return QualType();
2805 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2806 std::optional<llvm::APSInt> vecSize =
2807 ArraySize->getIntegerConstantExpr(Context);
2808 if (!vecSize) {
2809 Diag(AttrLoc, diag::err_attribute_argument_type)
2810 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2811 << ArraySize->getSourceRange();
2812 return QualType();
2815 if (!vecSize->isIntN(32)) {
2816 Diag(AttrLoc, diag::err_attribute_size_too_large)
2817 << ArraySize->getSourceRange() << "vector";
2818 return QualType();
2820 // Unlike gcc's vector_size attribute, the size is specified as the
2821 // number of elements, not the number of bytes.
2822 unsigned vectorSize = static_cast<unsigned>(vecSize->getZExtValue());
2824 if (vectorSize == 0) {
2825 Diag(AttrLoc, diag::err_attribute_zero_size)
2826 << ArraySize->getSourceRange() << "vector";
2827 return QualType();
2830 return Context.getExtVectorType(T, vectorSize);
2833 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2836 QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2837 SourceLocation AttrLoc) {
2838 assert(Context.getLangOpts().MatrixTypes &&
2839 "Should never build a matrix type when it is disabled");
2841 // Check element type, if it is not dependent.
2842 if (!ElementTy->isDependentType() &&
2843 !MatrixType::isValidElementType(ElementTy)) {
2844 Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2845 return QualType();
2848 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2849 NumRows->isValueDependent() || NumCols->isValueDependent())
2850 return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2851 AttrLoc);
2853 std::optional<llvm::APSInt> ValueRows =
2854 NumRows->getIntegerConstantExpr(Context);
2855 std::optional<llvm::APSInt> ValueColumns =
2856 NumCols->getIntegerConstantExpr(Context);
2858 auto const RowRange = NumRows->getSourceRange();
2859 auto const ColRange = NumCols->getSourceRange();
2861 // Both are row and column expressions are invalid.
2862 if (!ValueRows && !ValueColumns) {
2863 Diag(AttrLoc, diag::err_attribute_argument_type)
2864 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2865 << ColRange;
2866 return QualType();
2869 // Only the row expression is invalid.
2870 if (!ValueRows) {
2871 Diag(AttrLoc, diag::err_attribute_argument_type)
2872 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2873 return QualType();
2876 // Only the column expression is invalid.
2877 if (!ValueColumns) {
2878 Diag(AttrLoc, diag::err_attribute_argument_type)
2879 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2880 return QualType();
2883 // Check the matrix dimensions.
2884 unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2885 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2886 if (MatrixRows == 0 && MatrixColumns == 0) {
2887 Diag(AttrLoc, diag::err_attribute_zero_size)
2888 << "matrix" << RowRange << ColRange;
2889 return QualType();
2891 if (MatrixRows == 0) {
2892 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2893 return QualType();
2895 if (MatrixColumns == 0) {
2896 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2897 return QualType();
2899 if (!ConstantMatrixType::isDimensionValid(MatrixRows)) {
2900 Diag(AttrLoc, diag::err_attribute_size_too_large)
2901 << RowRange << "matrix row";
2902 return QualType();
2904 if (!ConstantMatrixType::isDimensionValid(MatrixColumns)) {
2905 Diag(AttrLoc, diag::err_attribute_size_too_large)
2906 << ColRange << "matrix column";
2907 return QualType();
2909 return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2912 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2913 if (T->isArrayType() || T->isFunctionType()) {
2914 Diag(Loc, diag::err_func_returning_array_function)
2915 << T->isFunctionType() << T;
2916 return true;
2919 // Functions cannot return half FP.
2920 if (T->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2921 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2922 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2923 FixItHint::CreateInsertion(Loc, "*");
2924 return true;
2927 // Methods cannot return interface types. All ObjC objects are
2928 // passed by reference.
2929 if (T->isObjCObjectType()) {
2930 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2931 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2932 return true;
2935 if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2936 T.hasNonTrivialToPrimitiveCopyCUnion())
2937 checkNonTrivialCUnion(T, Loc, NTCUC_FunctionReturn,
2938 NTCUK_Destruct|NTCUK_Copy);
2940 // C++2a [dcl.fct]p12:
2941 // A volatile-qualified return type is deprecated
2942 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2943 Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2945 if (T.getAddressSpace() != LangAS::Default && getLangOpts().HLSL)
2946 return true;
2947 return false;
2950 /// Check the extended parameter information. Most of the necessary
2951 /// checking should occur when applying the parameter attribute; the
2952 /// only other checks required are positional restrictions.
2953 static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2954 const FunctionProtoType::ExtProtoInfo &EPI,
2955 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2956 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2958 bool emittedError = false;
2959 auto actualCC = EPI.ExtInfo.getCC();
2960 enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
2961 auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
2962 bool isCompatible =
2963 (required == RequiredCC::OnlySwift)
2964 ? (actualCC == CC_Swift)
2965 : (actualCC == CC_Swift || actualCC == CC_SwiftAsync);
2966 if (isCompatible || emittedError)
2967 return;
2968 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2969 << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI())
2970 << (required == RequiredCC::OnlySwift);
2971 emittedError = true;
2973 for (size_t paramIndex = 0, numParams = paramTypes.size();
2974 paramIndex != numParams; ++paramIndex) {
2975 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2976 // Nothing interesting to check for orindary-ABI parameters.
2977 case ParameterABI::Ordinary:
2978 continue;
2980 // swift_indirect_result parameters must be a prefix of the function
2981 // arguments.
2982 case ParameterABI::SwiftIndirectResult:
2983 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2984 if (paramIndex != 0 &&
2985 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2986 != ParameterABI::SwiftIndirectResult) {
2987 S.Diag(getParamLoc(paramIndex),
2988 diag::err_swift_indirect_result_not_first);
2990 continue;
2992 case ParameterABI::SwiftContext:
2993 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2994 continue;
2996 // SwiftAsyncContext is not limited to swiftasynccall functions.
2997 case ParameterABI::SwiftAsyncContext:
2998 continue;
3000 // swift_error parameters must be preceded by a swift_context parameter.
3001 case ParameterABI::SwiftErrorResult:
3002 checkCompatible(paramIndex, RequiredCC::OnlySwift);
3003 if (paramIndex == 0 ||
3004 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
3005 ParameterABI::SwiftContext) {
3006 S.Diag(getParamLoc(paramIndex),
3007 diag::err_swift_error_result_not_after_swift_context);
3009 continue;
3011 llvm_unreachable("bad ABI kind");
3015 QualType Sema::BuildFunctionType(QualType T,
3016 MutableArrayRef<QualType> ParamTypes,
3017 SourceLocation Loc, DeclarationName Entity,
3018 const FunctionProtoType::ExtProtoInfo &EPI) {
3019 bool Invalid = false;
3021 Invalid |= CheckFunctionReturnType(T, Loc);
3023 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
3024 // FIXME: Loc is too inprecise here, should use proper locations for args.
3025 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
3026 if (ParamType->isVoidType()) {
3027 Diag(Loc, diag::err_param_with_void_type);
3028 Invalid = true;
3029 } else if (ParamType->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
3030 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
3031 // Disallow half FP arguments.
3032 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
3033 FixItHint::CreateInsertion(Loc, "*");
3034 Invalid = true;
3035 } else if (ParamType->isWebAssemblyTableType()) {
3036 Diag(Loc, diag::err_wasm_table_as_function_parameter);
3037 Invalid = true;
3040 // C++2a [dcl.fct]p4:
3041 // A parameter with volatile-qualified type is deprecated
3042 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
3043 Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
3045 ParamTypes[Idx] = ParamType;
3048 if (EPI.ExtParameterInfos) {
3049 checkExtParameterInfos(*this, ParamTypes, EPI,
3050 [=](unsigned i) { return Loc; });
3053 if (EPI.ExtInfo.getProducesResult()) {
3054 // This is just a warning, so we can't fail to build if we see it.
3055 checkNSReturnsRetainedReturnType(Loc, T);
3058 if (Invalid)
3059 return QualType();
3061 return Context.getFunctionType(T, ParamTypes, EPI);
3064 /// Build a member pointer type \c T Class::*.
3066 /// \param T the type to which the member pointer refers.
3067 /// \param Class the class type into which the member pointer points.
3068 /// \param Loc the location where this type begins
3069 /// \param Entity the name of the entity that will have this member pointer type
3071 /// \returns a member pointer type, if successful, or a NULL type if there was
3072 /// an error.
3073 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
3074 SourceLocation Loc,
3075 DeclarationName Entity) {
3076 // Verify that we're not building a pointer to pointer to function with
3077 // exception specification.
3078 if (CheckDistantExceptionSpec(T)) {
3079 Diag(Loc, diag::err_distant_exception_spec);
3080 return QualType();
3083 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
3084 // with reference type, or "cv void."
3085 if (T->isReferenceType()) {
3086 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
3087 << getPrintableNameForEntity(Entity) << T;
3088 return QualType();
3091 if (T->isVoidType()) {
3092 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
3093 << getPrintableNameForEntity(Entity);
3094 return QualType();
3097 if (!Class->isDependentType() && !Class->isRecordType()) {
3098 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
3099 return QualType();
3102 if (T->isFunctionType() && getLangOpts().OpenCL &&
3103 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
3104 getLangOpts())) {
3105 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
3106 return QualType();
3109 if (getLangOpts().HLSL && Loc.isValid()) {
3110 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
3111 return QualType();
3114 // Adjust the default free function calling convention to the default method
3115 // calling convention.
3116 bool IsCtorOrDtor =
3117 (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
3118 (Entity.getNameKind() == DeclarationName::CXXDestructorName);
3119 if (T->isFunctionType())
3120 adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
3122 return Context.getMemberPointerType(T, Class.getTypePtr());
3125 /// Build a block pointer type.
3127 /// \param T The type to which we'll be building a block pointer.
3129 /// \param Loc The source location, used for diagnostics.
3131 /// \param Entity The name of the entity that involves the block pointer
3132 /// type, if known.
3134 /// \returns A suitable block pointer type, if there are no
3135 /// errors. Otherwise, returns a NULL type.
3136 QualType Sema::BuildBlockPointerType(QualType T,
3137 SourceLocation Loc,
3138 DeclarationName Entity) {
3139 if (!T->isFunctionType()) {
3140 Diag(Loc, diag::err_nonfunction_block_type);
3141 return QualType();
3144 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
3145 return QualType();
3147 if (getLangOpts().OpenCL)
3148 T = deduceOpenCLPointeeAddrSpace(*this, T);
3150 return Context.getBlockPointerType(T);
3153 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
3154 QualType QT = Ty.get();
3155 if (QT.isNull()) {
3156 if (TInfo) *TInfo = nullptr;
3157 return QualType();
3160 TypeSourceInfo *DI = nullptr;
3161 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
3162 QT = LIT->getType();
3163 DI = LIT->getTypeSourceInfo();
3166 if (TInfo) *TInfo = DI;
3167 return QT;
3170 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
3171 Qualifiers::ObjCLifetime ownership,
3172 unsigned chunkIndex);
3174 /// Given that this is the declaration of a parameter under ARC,
3175 /// attempt to infer attributes and such for pointer-to-whatever
3176 /// types.
3177 static void inferARCWriteback(TypeProcessingState &state,
3178 QualType &declSpecType) {
3179 Sema &S = state.getSema();
3180 Declarator &declarator = state.getDeclarator();
3182 // TODO: should we care about decl qualifiers?
3184 // Check whether the declarator has the expected form. We walk
3185 // from the inside out in order to make the block logic work.
3186 unsigned outermostPointerIndex = 0;
3187 bool isBlockPointer = false;
3188 unsigned numPointers = 0;
3189 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
3190 unsigned chunkIndex = i;
3191 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
3192 switch (chunk.Kind) {
3193 case DeclaratorChunk::Paren:
3194 // Ignore parens.
3195 break;
3197 case DeclaratorChunk::Reference:
3198 case DeclaratorChunk::Pointer:
3199 // Count the number of pointers. Treat references
3200 // interchangeably as pointers; if they're mis-ordered, normal
3201 // type building will discover that.
3202 outermostPointerIndex = chunkIndex;
3203 numPointers++;
3204 break;
3206 case DeclaratorChunk::BlockPointer:
3207 // If we have a pointer to block pointer, that's an acceptable
3208 // indirect reference; anything else is not an application of
3209 // the rules.
3210 if (numPointers != 1) return;
3211 numPointers++;
3212 outermostPointerIndex = chunkIndex;
3213 isBlockPointer = true;
3215 // We don't care about pointer structure in return values here.
3216 goto done;
3218 case DeclaratorChunk::Array: // suppress if written (id[])?
3219 case DeclaratorChunk::Function:
3220 case DeclaratorChunk::MemberPointer:
3221 case DeclaratorChunk::Pipe:
3222 return;
3225 done:
3227 // If we have *one* pointer, then we want to throw the qualifier on
3228 // the declaration-specifiers, which means that it needs to be a
3229 // retainable object type.
3230 if (numPointers == 1) {
3231 // If it's not a retainable object type, the rule doesn't apply.
3232 if (!declSpecType->isObjCRetainableType()) return;
3234 // If it already has lifetime, don't do anything.
3235 if (declSpecType.getObjCLifetime()) return;
3237 // Otherwise, modify the type in-place.
3238 Qualifiers qs;
3240 if (declSpecType->isObjCARCImplicitlyUnretainedType())
3241 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
3242 else
3243 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
3244 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
3246 // If we have *two* pointers, then we want to throw the qualifier on
3247 // the outermost pointer.
3248 } else if (numPointers == 2) {
3249 // If we don't have a block pointer, we need to check whether the
3250 // declaration-specifiers gave us something that will turn into a
3251 // retainable object pointer after we slap the first pointer on it.
3252 if (!isBlockPointer && !declSpecType->isObjCObjectType())
3253 return;
3255 // Look for an explicit lifetime attribute there.
3256 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
3257 if (chunk.Kind != DeclaratorChunk::Pointer &&
3258 chunk.Kind != DeclaratorChunk::BlockPointer)
3259 return;
3260 for (const ParsedAttr &AL : chunk.getAttrs())
3261 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
3262 return;
3264 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
3265 outermostPointerIndex);
3267 // Any other number of pointers/references does not trigger the rule.
3268 } else return;
3270 // TODO: mark whether we did this inference?
3273 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
3274 SourceLocation FallbackLoc,
3275 SourceLocation ConstQualLoc,
3276 SourceLocation VolatileQualLoc,
3277 SourceLocation RestrictQualLoc,
3278 SourceLocation AtomicQualLoc,
3279 SourceLocation UnalignedQualLoc) {
3280 if (!Quals)
3281 return;
3283 struct Qual {
3284 const char *Name;
3285 unsigned Mask;
3286 SourceLocation Loc;
3287 } const QualKinds[5] = {
3288 { "const", DeclSpec::TQ_const, ConstQualLoc },
3289 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
3290 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
3291 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
3292 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
3295 SmallString<32> QualStr;
3296 unsigned NumQuals = 0;
3297 SourceLocation Loc;
3298 FixItHint FixIts[5];
3300 // Build a string naming the redundant qualifiers.
3301 for (auto &E : QualKinds) {
3302 if (Quals & E.Mask) {
3303 if (!QualStr.empty()) QualStr += ' ';
3304 QualStr += E.Name;
3306 // If we have a location for the qualifier, offer a fixit.
3307 SourceLocation QualLoc = E.Loc;
3308 if (QualLoc.isValid()) {
3309 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
3310 if (Loc.isInvalid() ||
3311 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
3312 Loc = QualLoc;
3315 ++NumQuals;
3319 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
3320 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
3323 // Diagnose pointless type qualifiers on the return type of a function.
3324 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
3325 Declarator &D,
3326 unsigned FunctionChunkIndex) {
3327 const DeclaratorChunk::FunctionTypeInfo &FTI =
3328 D.getTypeObject(FunctionChunkIndex).Fun;
3329 if (FTI.hasTrailingReturnType()) {
3330 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3331 RetTy.getLocalCVRQualifiers(),
3332 FTI.getTrailingReturnTypeLoc());
3333 return;
3336 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3337 End = D.getNumTypeObjects();
3338 OuterChunkIndex != End; ++OuterChunkIndex) {
3339 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
3340 switch (OuterChunk.Kind) {
3341 case DeclaratorChunk::Paren:
3342 continue;
3344 case DeclaratorChunk::Pointer: {
3345 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3346 S.diagnoseIgnoredQualifiers(
3347 diag::warn_qual_return_type,
3348 PTI.TypeQuals,
3349 SourceLocation(),
3350 PTI.ConstQualLoc,
3351 PTI.VolatileQualLoc,
3352 PTI.RestrictQualLoc,
3353 PTI.AtomicQualLoc,
3354 PTI.UnalignedQualLoc);
3355 return;
3358 case DeclaratorChunk::Function:
3359 case DeclaratorChunk::BlockPointer:
3360 case DeclaratorChunk::Reference:
3361 case DeclaratorChunk::Array:
3362 case DeclaratorChunk::MemberPointer:
3363 case DeclaratorChunk::Pipe:
3364 // FIXME: We can't currently provide an accurate source location and a
3365 // fix-it hint for these.
3366 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
3367 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3368 RetTy.getCVRQualifiers() | AtomicQual,
3369 D.getIdentifierLoc());
3370 return;
3373 llvm_unreachable("unknown declarator chunk kind");
3376 // If the qualifiers come from a conversion function type, don't diagnose
3377 // them -- they're not necessarily redundant, since such a conversion
3378 // operator can be explicitly called as "x.operator const int()".
3379 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3380 return;
3382 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3383 // which are present there.
3384 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3385 D.getDeclSpec().getTypeQualifiers(),
3386 D.getIdentifierLoc(),
3387 D.getDeclSpec().getConstSpecLoc(),
3388 D.getDeclSpec().getVolatileSpecLoc(),
3389 D.getDeclSpec().getRestrictSpecLoc(),
3390 D.getDeclSpec().getAtomicSpecLoc(),
3391 D.getDeclSpec().getUnalignedSpecLoc());
3394 static std::pair<QualType, TypeSourceInfo *>
3395 InventTemplateParameter(TypeProcessingState &state, QualType T,
3396 TypeSourceInfo *TrailingTSI, AutoType *Auto,
3397 InventedTemplateParameterInfo &Info) {
3398 Sema &S = state.getSema();
3399 Declarator &D = state.getDeclarator();
3401 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3402 const unsigned AutoParameterPosition = Info.TemplateParams.size();
3403 const bool IsParameterPack = D.hasEllipsis();
3405 // If auto is mentioned in a lambda parameter or abbreviated function
3406 // template context, convert it to a template parameter type.
3408 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3409 // template parameter type. Template parameters are temporarily added
3410 // to the TU until the associated TemplateDecl is created.
3411 TemplateTypeParmDecl *InventedTemplateParam =
3412 TemplateTypeParmDecl::Create(
3413 S.Context, S.Context.getTranslationUnitDecl(),
3414 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3415 /*NameLoc=*/D.getIdentifierLoc(),
3416 TemplateParameterDepth, AutoParameterPosition,
3417 S.InventAbbreviatedTemplateParameterTypeName(
3418 D.getIdentifier(), AutoParameterPosition), false,
3419 IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3420 InventedTemplateParam->setImplicit();
3421 Info.TemplateParams.push_back(InventedTemplateParam);
3423 // Attach type constraints to the new parameter.
3424 if (Auto->isConstrained()) {
3425 if (TrailingTSI) {
3426 // The 'auto' appears in a trailing return type we've already built;
3427 // extract its type constraints to attach to the template parameter.
3428 AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3429 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3430 bool Invalid = false;
3431 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3432 if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3433 S.DiagnoseUnexpandedParameterPack(AutoLoc.getArgLoc(Idx),
3434 Sema::UPPC_TypeConstraint))
3435 Invalid = true;
3436 TAL.addArgument(AutoLoc.getArgLoc(Idx));
3439 if (!Invalid) {
3440 S.AttachTypeConstraint(
3441 AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3442 AutoLoc.getNamedConcept(),
3443 AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3444 InventedTemplateParam, D.getEllipsisLoc());
3446 } else {
3447 // The 'auto' appears in the decl-specifiers; we've not finished forming
3448 // TypeSourceInfo for it yet.
3449 TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId();
3450 TemplateArgumentListInfo TemplateArgsInfo;
3451 bool Invalid = false;
3452 if (TemplateId->LAngleLoc.isValid()) {
3453 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3454 TemplateId->NumArgs);
3455 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3457 if (D.getEllipsisLoc().isInvalid()) {
3458 for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3459 if (S.DiagnoseUnexpandedParameterPack(Arg,
3460 Sema::UPPC_TypeConstraint)) {
3461 Invalid = true;
3462 break;
3467 if (!Invalid) {
3468 S.AttachTypeConstraint(
3469 D.getDeclSpec().getTypeSpecScope().getWithLocInContext(S.Context),
3470 DeclarationNameInfo(DeclarationName(TemplateId->Name),
3471 TemplateId->TemplateNameLoc),
3472 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl()),
3473 TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3474 InventedTemplateParam, D.getEllipsisLoc());
3479 // Replace the 'auto' in the function parameter with this invented
3480 // template type parameter.
3481 // FIXME: Retain some type sugar to indicate that this was written
3482 // as 'auto'?
3483 QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3484 QualType NewT = state.ReplaceAutoType(T, Replacement);
3485 TypeSourceInfo *NewTSI =
3486 TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)
3487 : nullptr;
3488 return {NewT, NewTSI};
3491 static TypeSourceInfo *
3492 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3493 QualType T, TypeSourceInfo *ReturnTypeInfo);
3495 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3496 TypeSourceInfo *&ReturnTypeInfo) {
3497 Sema &SemaRef = state.getSema();
3498 Declarator &D = state.getDeclarator();
3499 QualType T;
3500 ReturnTypeInfo = nullptr;
3502 // The TagDecl owned by the DeclSpec.
3503 TagDecl *OwnedTagDecl = nullptr;
3505 switch (D.getName().getKind()) {
3506 case UnqualifiedIdKind::IK_ImplicitSelfParam:
3507 case UnqualifiedIdKind::IK_OperatorFunctionId:
3508 case UnqualifiedIdKind::IK_Identifier:
3509 case UnqualifiedIdKind::IK_LiteralOperatorId:
3510 case UnqualifiedIdKind::IK_TemplateId:
3511 T = ConvertDeclSpecToType(state);
3513 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3514 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3515 // Owned declaration is embedded in declarator.
3516 OwnedTagDecl->setEmbeddedInDeclarator(true);
3518 break;
3520 case UnqualifiedIdKind::IK_ConstructorName:
3521 case UnqualifiedIdKind::IK_ConstructorTemplateId:
3522 case UnqualifiedIdKind::IK_DestructorName:
3523 // Constructors and destructors don't have return types. Use
3524 // "void" instead.
3525 T = SemaRef.Context.VoidTy;
3526 processTypeAttrs(state, T, TAL_DeclSpec,
3527 D.getMutableDeclSpec().getAttributes());
3528 break;
3530 case UnqualifiedIdKind::IK_DeductionGuideName:
3531 // Deduction guides have a trailing return type and no type in their
3532 // decl-specifier sequence. Use a placeholder return type for now.
3533 T = SemaRef.Context.DependentTy;
3534 break;
3536 case UnqualifiedIdKind::IK_ConversionFunctionId:
3537 // The result type of a conversion function is the type that it
3538 // converts to.
3539 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
3540 &ReturnTypeInfo);
3541 break;
3544 // Note: We don't need to distribute declaration attributes (i.e.
3545 // D.getDeclarationAttributes()) because those are always C++11 attributes,
3546 // and those don't get distributed.
3547 distributeTypeAttrsFromDeclarator(state, T);
3549 // Find the deduced type in this type. Look in the trailing return type if we
3550 // have one, otherwise in the DeclSpec type.
3551 // FIXME: The standard wording doesn't currently describe this.
3552 DeducedType *Deduced = T->getContainedDeducedType();
3553 bool DeducedIsTrailingReturnType = false;
3554 if (Deduced && isa<AutoType>(Deduced) && D.hasTrailingReturnType()) {
3555 QualType T = SemaRef.GetTypeFromParser(D.getTrailingReturnType());
3556 Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3557 DeducedIsTrailingReturnType = true;
3560 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3561 if (Deduced) {
3562 AutoType *Auto = dyn_cast<AutoType>(Deduced);
3563 int Error = -1;
3565 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3566 // class template argument deduction)?
3567 bool IsCXXAutoType =
3568 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3569 bool IsDeducedReturnType = false;
3571 switch (D.getContext()) {
3572 case DeclaratorContext::LambdaExpr:
3573 // Declared return type of a lambda-declarator is implicit and is always
3574 // 'auto'.
3575 break;
3576 case DeclaratorContext::ObjCParameter:
3577 case DeclaratorContext::ObjCResult:
3578 Error = 0;
3579 break;
3580 case DeclaratorContext::RequiresExpr:
3581 Error = 22;
3582 break;
3583 case DeclaratorContext::Prototype:
3584 case DeclaratorContext::LambdaExprParameter: {
3585 InventedTemplateParameterInfo *Info = nullptr;
3586 if (D.getContext() == DeclaratorContext::Prototype) {
3587 // With concepts we allow 'auto' in function parameters.
3588 if (!SemaRef.getLangOpts().CPlusPlus20 || !Auto ||
3589 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3590 Error = 0;
3591 break;
3592 } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3593 Error = 21;
3594 break;
3597 Info = &SemaRef.InventedParameterInfos.back();
3598 } else {
3599 // In C++14, generic lambdas allow 'auto' in their parameters.
3600 if (!SemaRef.getLangOpts().CPlusPlus14 || !Auto ||
3601 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3602 Error = 16;
3603 break;
3605 Info = SemaRef.getCurLambda();
3606 assert(Info && "No LambdaScopeInfo on the stack!");
3609 // We'll deal with inventing template parameters for 'auto' in trailing
3610 // return types when we pick up the trailing return type when processing
3611 // the function chunk.
3612 if (!DeducedIsTrailingReturnType)
3613 T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3614 break;
3616 case DeclaratorContext::Member: {
3617 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
3618 D.isFunctionDeclarator())
3619 break;
3620 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3621 if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3622 Error = 6; // Interface member.
3623 } else {
3624 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3625 case TTK_Enum: llvm_unreachable("unhandled tag kind");
3626 case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
3627 case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
3628 case TTK_Class: Error = 5; /* Class member */ break;
3629 case TTK_Interface: Error = 6; /* Interface member */ break;
3632 if (D.getDeclSpec().isFriendSpecified())
3633 Error = 20; // Friend type
3634 break;
3636 case DeclaratorContext::CXXCatch:
3637 case DeclaratorContext::ObjCCatch:
3638 Error = 7; // Exception declaration
3639 break;
3640 case DeclaratorContext::TemplateParam:
3641 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3642 !SemaRef.getLangOpts().CPlusPlus20)
3643 Error = 19; // Template parameter (until C++20)
3644 else if (!SemaRef.getLangOpts().CPlusPlus17)
3645 Error = 8; // Template parameter (until C++17)
3646 break;
3647 case DeclaratorContext::BlockLiteral:
3648 Error = 9; // Block literal
3649 break;
3650 case DeclaratorContext::TemplateArg:
3651 // Within a template argument list, a deduced template specialization
3652 // type will be reinterpreted as a template template argument.
3653 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3654 !D.getNumTypeObjects() &&
3655 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier)
3656 break;
3657 [[fallthrough]];
3658 case DeclaratorContext::TemplateTypeArg:
3659 Error = 10; // Template type argument
3660 break;
3661 case DeclaratorContext::AliasDecl:
3662 case DeclaratorContext::AliasTemplate:
3663 Error = 12; // Type alias
3664 break;
3665 case DeclaratorContext::TrailingReturn:
3666 case DeclaratorContext::TrailingReturnVar:
3667 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3668 Error = 13; // Function return type
3669 IsDeducedReturnType = true;
3670 break;
3671 case DeclaratorContext::ConversionId:
3672 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3673 Error = 14; // conversion-type-id
3674 IsDeducedReturnType = true;
3675 break;
3676 case DeclaratorContext::FunctionalCast:
3677 if (isa<DeducedTemplateSpecializationType>(Deduced))
3678 break;
3679 if (SemaRef.getLangOpts().CPlusPlus23 && IsCXXAutoType &&
3680 !Auto->isDecltypeAuto())
3681 break; // auto(x)
3682 [[fallthrough]];
3683 case DeclaratorContext::TypeName:
3684 case DeclaratorContext::Association:
3685 Error = 15; // Generic
3686 break;
3687 case DeclaratorContext::File:
3688 case DeclaratorContext::Block:
3689 case DeclaratorContext::ForInit:
3690 case DeclaratorContext::SelectionInit:
3691 case DeclaratorContext::Condition:
3692 // FIXME: P0091R3 (erroneously) does not permit class template argument
3693 // deduction in conditions, for-init-statements, and other declarations
3694 // that are not simple-declarations.
3695 break;
3696 case DeclaratorContext::CXXNew:
3697 // FIXME: P0091R3 does not permit class template argument deduction here,
3698 // but we follow GCC and allow it anyway.
3699 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3700 Error = 17; // 'new' type
3701 break;
3702 case DeclaratorContext::KNRTypeList:
3703 Error = 18; // K&R function parameter
3704 break;
3707 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3708 Error = 11;
3710 // In Objective-C it is an error to use 'auto' on a function declarator
3711 // (and everywhere for '__auto_type').
3712 if (D.isFunctionDeclarator() &&
3713 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3714 Error = 13;
3716 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3717 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3718 AutoRange = D.getName().getSourceRange();
3720 if (Error != -1) {
3721 unsigned Kind;
3722 if (Auto) {
3723 switch (Auto->getKeyword()) {
3724 case AutoTypeKeyword::Auto: Kind = 0; break;
3725 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3726 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3728 } else {
3729 assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3730 "unknown auto type");
3731 Kind = 3;
3734 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3735 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3737 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3738 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3739 << QualType(Deduced, 0) << AutoRange;
3740 if (auto *TD = TN.getAsTemplateDecl())
3741 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
3743 T = SemaRef.Context.IntTy;
3744 D.setInvalidType(true);
3745 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) {
3746 // If there was a trailing return type, we already got
3747 // warn_cxx98_compat_trailing_return_type in the parser.
3748 SemaRef.Diag(AutoRange.getBegin(),
3749 D.getContext() == DeclaratorContext::LambdaExprParameter
3750 ? diag::warn_cxx11_compat_generic_lambda
3751 : IsDeducedReturnType
3752 ? diag::warn_cxx11_compat_deduced_return_type
3753 : diag::warn_cxx98_compat_auto_type_specifier)
3754 << AutoRange;
3758 if (SemaRef.getLangOpts().CPlusPlus &&
3759 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3760 // Check the contexts where C++ forbids the declaration of a new class
3761 // or enumeration in a type-specifier-seq.
3762 unsigned DiagID = 0;
3763 switch (D.getContext()) {
3764 case DeclaratorContext::TrailingReturn:
3765 case DeclaratorContext::TrailingReturnVar:
3766 // Class and enumeration definitions are syntactically not allowed in
3767 // trailing return types.
3768 llvm_unreachable("parser should not have allowed this");
3769 break;
3770 case DeclaratorContext::File:
3771 case DeclaratorContext::Member:
3772 case DeclaratorContext::Block:
3773 case DeclaratorContext::ForInit:
3774 case DeclaratorContext::SelectionInit:
3775 case DeclaratorContext::BlockLiteral:
3776 case DeclaratorContext::LambdaExpr:
3777 // C++11 [dcl.type]p3:
3778 // A type-specifier-seq shall not define a class or enumeration unless
3779 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3780 // the declaration of a template-declaration.
3781 case DeclaratorContext::AliasDecl:
3782 break;
3783 case DeclaratorContext::AliasTemplate:
3784 DiagID = diag::err_type_defined_in_alias_template;
3785 break;
3786 case DeclaratorContext::TypeName:
3787 case DeclaratorContext::FunctionalCast:
3788 case DeclaratorContext::ConversionId:
3789 case DeclaratorContext::TemplateParam:
3790 case DeclaratorContext::CXXNew:
3791 case DeclaratorContext::CXXCatch:
3792 case DeclaratorContext::ObjCCatch:
3793 case DeclaratorContext::TemplateArg:
3794 case DeclaratorContext::TemplateTypeArg:
3795 case DeclaratorContext::Association:
3796 DiagID = diag::err_type_defined_in_type_specifier;
3797 break;
3798 case DeclaratorContext::Prototype:
3799 case DeclaratorContext::LambdaExprParameter:
3800 case DeclaratorContext::ObjCParameter:
3801 case DeclaratorContext::ObjCResult:
3802 case DeclaratorContext::KNRTypeList:
3803 case DeclaratorContext::RequiresExpr:
3804 // C++ [dcl.fct]p6:
3805 // Types shall not be defined in return or parameter types.
3806 DiagID = diag::err_type_defined_in_param_type;
3807 break;
3808 case DeclaratorContext::Condition:
3809 // C++ 6.4p2:
3810 // The type-specifier-seq shall not contain typedef and shall not declare
3811 // a new class or enumeration.
3812 DiagID = diag::err_type_defined_in_condition;
3813 break;
3816 if (DiagID != 0) {
3817 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3818 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3819 D.setInvalidType(true);
3823 assert(!T.isNull() && "This function should not return a null type");
3824 return T;
3827 /// Produce an appropriate diagnostic for an ambiguity between a function
3828 /// declarator and a C++ direct-initializer.
3829 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3830 DeclaratorChunk &DeclType, QualType RT) {
3831 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3832 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3834 // If the return type is void there is no ambiguity.
3835 if (RT->isVoidType())
3836 return;
3838 // An initializer for a non-class type can have at most one argument.
3839 if (!RT->isRecordType() && FTI.NumParams > 1)
3840 return;
3842 // An initializer for a reference must have exactly one argument.
3843 if (RT->isReferenceType() && FTI.NumParams != 1)
3844 return;
3846 // Only warn if this declarator is declaring a function at block scope, and
3847 // doesn't have a storage class (such as 'extern') specified.
3848 if (!D.isFunctionDeclarator() ||
3849 D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration ||
3850 !S.CurContext->isFunctionOrMethod() ||
3851 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified)
3852 return;
3854 // Inside a condition, a direct initializer is not permitted. We allow one to
3855 // be parsed in order to give better diagnostics in condition parsing.
3856 if (D.getContext() == DeclaratorContext::Condition)
3857 return;
3859 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3861 S.Diag(DeclType.Loc,
3862 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3863 : diag::warn_empty_parens_are_function_decl)
3864 << ParenRange;
3866 // If the declaration looks like:
3867 // T var1,
3868 // f();
3869 // and name lookup finds a function named 'f', then the ',' was
3870 // probably intended to be a ';'.
3871 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3872 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3873 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3874 if (Comma.getFileID() != Name.getFileID() ||
3875 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3876 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3877 Sema::LookupOrdinaryName);
3878 if (S.LookupName(Result, S.getCurScope()))
3879 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3880 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3881 << D.getIdentifier();
3882 Result.suppressDiagnostics();
3886 if (FTI.NumParams > 0) {
3887 // For a declaration with parameters, eg. "T var(T());", suggest adding
3888 // parens around the first parameter to turn the declaration into a
3889 // variable declaration.
3890 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3891 SourceLocation B = Range.getBegin();
3892 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3893 // FIXME: Maybe we should suggest adding braces instead of parens
3894 // in C++11 for classes that don't have an initializer_list constructor.
3895 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3896 << FixItHint::CreateInsertion(B, "(")
3897 << FixItHint::CreateInsertion(E, ")");
3898 } else {
3899 // For a declaration without parameters, eg. "T var();", suggest replacing
3900 // the parens with an initializer to turn the declaration into a variable
3901 // declaration.
3902 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3904 // Empty parens mean value-initialization, and no parens mean
3905 // default initialization. These are equivalent if the default
3906 // constructor is user-provided or if zero-initialization is a
3907 // no-op.
3908 if (RD && RD->hasDefinition() &&
3909 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3910 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3911 << FixItHint::CreateRemoval(ParenRange);
3912 else {
3913 std::string Init =
3914 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3915 if (Init.empty() && S.LangOpts.CPlusPlus11)
3916 Init = "{}";
3917 if (!Init.empty())
3918 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3919 << FixItHint::CreateReplacement(ParenRange, Init);
3924 /// Produce an appropriate diagnostic for a declarator with top-level
3925 /// parentheses.
3926 static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
3927 DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
3928 assert(Paren.Kind == DeclaratorChunk::Paren &&
3929 "do not have redundant top-level parentheses");
3931 // This is a syntactic check; we're not interested in cases that arise
3932 // during template instantiation.
3933 if (S.inTemplateInstantiation())
3934 return;
3936 // Check whether this could be intended to be a construction of a temporary
3937 // object in C++ via a function-style cast.
3938 bool CouldBeTemporaryObject =
3939 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3940 !D.isInvalidType() && D.getIdentifier() &&
3941 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3942 (T->isRecordType() || T->isDependentType()) &&
3943 D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator();
3945 bool StartsWithDeclaratorId = true;
3946 for (auto &C : D.type_objects()) {
3947 switch (C.Kind) {
3948 case DeclaratorChunk::Paren:
3949 if (&C == &Paren)
3950 continue;
3951 [[fallthrough]];
3952 case DeclaratorChunk::Pointer:
3953 StartsWithDeclaratorId = false;
3954 continue;
3956 case DeclaratorChunk::Array:
3957 if (!C.Arr.NumElts)
3958 CouldBeTemporaryObject = false;
3959 continue;
3961 case DeclaratorChunk::Reference:
3962 // FIXME: Suppress the warning here if there is no initializer; we're
3963 // going to give an error anyway.
3964 // We assume that something like 'T (&x) = y;' is highly likely to not
3965 // be intended to be a temporary object.
3966 CouldBeTemporaryObject = false;
3967 StartsWithDeclaratorId = false;
3968 continue;
3970 case DeclaratorChunk::Function:
3971 // In a new-type-id, function chunks require parentheses.
3972 if (D.getContext() == DeclaratorContext::CXXNew)
3973 return;
3974 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3975 // redundant-parens warning, but we don't know whether the function
3976 // chunk was syntactically valid as an expression here.
3977 CouldBeTemporaryObject = false;
3978 continue;
3980 case DeclaratorChunk::BlockPointer:
3981 case DeclaratorChunk::MemberPointer:
3982 case DeclaratorChunk::Pipe:
3983 // These cannot appear in expressions.
3984 CouldBeTemporaryObject = false;
3985 StartsWithDeclaratorId = false;
3986 continue;
3990 // FIXME: If there is an initializer, assume that this is not intended to be
3991 // a construction of a temporary object.
3993 // Check whether the name has already been declared; if not, this is not a
3994 // function-style cast.
3995 if (CouldBeTemporaryObject) {
3996 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3997 Sema::LookupOrdinaryName);
3998 if (!S.LookupName(Result, S.getCurScope()))
3999 CouldBeTemporaryObject = false;
4000 Result.suppressDiagnostics();
4003 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
4005 if (!CouldBeTemporaryObject) {
4006 // If we have A (::B), the parentheses affect the meaning of the program.
4007 // Suppress the warning in that case. Don't bother looking at the DeclSpec
4008 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
4009 // formally unambiguous.
4010 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
4011 for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
4012 NNS = NNS->getPrefix()) {
4013 if (NNS->getKind() == NestedNameSpecifier::Global)
4014 return;
4018 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
4019 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
4020 << FixItHint::CreateRemoval(Paren.EndLoc);
4021 return;
4024 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
4025 << ParenRange << D.getIdentifier();
4026 auto *RD = T->getAsCXXRecordDecl();
4027 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
4028 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
4029 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
4030 << D.getIdentifier();
4031 // FIXME: A cast to void is probably a better suggestion in cases where it's
4032 // valid (when there is no initializer and we're not in a condition).
4033 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
4034 << FixItHint::CreateInsertion(D.getBeginLoc(), "(")
4035 << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")");
4036 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
4037 << FixItHint::CreateRemoval(Paren.Loc)
4038 << FixItHint::CreateRemoval(Paren.EndLoc);
4041 /// Helper for figuring out the default CC for a function declarator type. If
4042 /// this is the outermost chunk, then we can determine the CC from the
4043 /// declarator context. If not, then this could be either a member function
4044 /// type or normal function type.
4045 static CallingConv getCCForDeclaratorChunk(
4046 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
4047 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
4048 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
4050 // Check for an explicit CC attribute.
4051 for (const ParsedAttr &AL : AttrList) {
4052 switch (AL.getKind()) {
4053 CALLING_CONV_ATTRS_CASELIST : {
4054 // Ignore attributes that don't validate or can't apply to the
4055 // function type. We'll diagnose the failure to apply them in
4056 // handleFunctionTypeAttr.
4057 CallingConv CC;
4058 if (!S.CheckCallingConvAttr(AL, CC) &&
4059 (!FTI.isVariadic || supportsVariadicCall(CC))) {
4060 return CC;
4062 break;
4065 default:
4066 break;
4070 bool IsCXXInstanceMethod = false;
4072 if (S.getLangOpts().CPlusPlus) {
4073 // Look inwards through parentheses to see if this chunk will form a
4074 // member pointer type or if we're the declarator. Any type attributes
4075 // between here and there will override the CC we choose here.
4076 unsigned I = ChunkIndex;
4077 bool FoundNonParen = false;
4078 while (I && !FoundNonParen) {
4079 --I;
4080 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
4081 FoundNonParen = true;
4084 if (FoundNonParen) {
4085 // If we're not the declarator, we're a regular function type unless we're
4086 // in a member pointer.
4087 IsCXXInstanceMethod =
4088 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
4089 } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
4090 // This can only be a call operator for a lambda, which is an instance
4091 // method.
4092 IsCXXInstanceMethod = true;
4093 } else {
4094 // We're the innermost decl chunk, so must be a function declarator.
4095 assert(D.isFunctionDeclarator());
4097 // If we're inside a record, we're declaring a method, but it could be
4098 // explicitly or implicitly static.
4099 IsCXXInstanceMethod =
4100 D.isFirstDeclarationOfMember() &&
4101 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
4102 !D.isStaticMember();
4106 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
4107 IsCXXInstanceMethod);
4109 // Attribute AT_OpenCLKernel affects the calling convention for SPIR
4110 // and AMDGPU targets, hence it cannot be treated as a calling
4111 // convention attribute. This is the simplest place to infer
4112 // calling convention for OpenCL kernels.
4113 if (S.getLangOpts().OpenCL) {
4114 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4115 if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
4116 CC = CC_OpenCLKernel;
4117 break;
4120 } else if (S.getLangOpts().CUDA) {
4121 // If we're compiling CUDA/HIP code and targeting SPIR-V we need to make
4122 // sure the kernels will be marked with the right calling convention so that
4123 // they will be visible by the APIs that ingest SPIR-V.
4124 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
4125 if (Triple.getArch() == llvm::Triple::spirv32 ||
4126 Triple.getArch() == llvm::Triple::spirv64) {
4127 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4128 if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) {
4129 CC = CC_OpenCLKernel;
4130 break;
4136 return CC;
4139 namespace {
4140 /// A simple notion of pointer kinds, which matches up with the various
4141 /// pointer declarators.
4142 enum class SimplePointerKind {
4143 Pointer,
4144 BlockPointer,
4145 MemberPointer,
4146 Array,
4148 } // end anonymous namespace
4150 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
4151 switch (nullability) {
4152 case NullabilityKind::NonNull:
4153 if (!Ident__Nonnull)
4154 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
4155 return Ident__Nonnull;
4157 case NullabilityKind::Nullable:
4158 if (!Ident__Nullable)
4159 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
4160 return Ident__Nullable;
4162 case NullabilityKind::NullableResult:
4163 if (!Ident__Nullable_result)
4164 Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
4165 return Ident__Nullable_result;
4167 case NullabilityKind::Unspecified:
4168 if (!Ident__Null_unspecified)
4169 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
4170 return Ident__Null_unspecified;
4172 llvm_unreachable("Unknown nullability kind.");
4175 /// Retrieve the identifier "NSError".
4176 IdentifierInfo *Sema::getNSErrorIdent() {
4177 if (!Ident_NSError)
4178 Ident_NSError = PP.getIdentifierInfo("NSError");
4180 return Ident_NSError;
4183 /// Check whether there is a nullability attribute of any kind in the given
4184 /// attribute list.
4185 static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
4186 for (const ParsedAttr &AL : attrs) {
4187 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
4188 AL.getKind() == ParsedAttr::AT_TypeNullable ||
4189 AL.getKind() == ParsedAttr::AT_TypeNullableResult ||
4190 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
4191 return true;
4194 return false;
4197 namespace {
4198 /// Describes the kind of a pointer a declarator describes.
4199 enum class PointerDeclaratorKind {
4200 // Not a pointer.
4201 NonPointer,
4202 // Single-level pointer.
4203 SingleLevelPointer,
4204 // Multi-level pointer (of any pointer kind).
4205 MultiLevelPointer,
4206 // CFFooRef*
4207 MaybePointerToCFRef,
4208 // CFErrorRef*
4209 CFErrorRefPointer,
4210 // NSError**
4211 NSErrorPointerPointer,
4214 /// Describes a declarator chunk wrapping a pointer that marks inference as
4215 /// unexpected.
4216 // These values must be kept in sync with diagnostics.
4217 enum class PointerWrappingDeclaratorKind {
4218 /// Pointer is top-level.
4219 None = -1,
4220 /// Pointer is an array element.
4221 Array = 0,
4222 /// Pointer is the referent type of a C++ reference.
4223 Reference = 1
4225 } // end anonymous namespace
4227 /// Classify the given declarator, whose type-specified is \c type, based on
4228 /// what kind of pointer it refers to.
4230 /// This is used to determine the default nullability.
4231 static PointerDeclaratorKind
4232 classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
4233 PointerWrappingDeclaratorKind &wrappingKind) {
4234 unsigned numNormalPointers = 0;
4236 // For any dependent type, we consider it a non-pointer.
4237 if (type->isDependentType())
4238 return PointerDeclaratorKind::NonPointer;
4240 // Look through the declarator chunks to identify pointers.
4241 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
4242 DeclaratorChunk &chunk = declarator.getTypeObject(i);
4243 switch (chunk.Kind) {
4244 case DeclaratorChunk::Array:
4245 if (numNormalPointers == 0)
4246 wrappingKind = PointerWrappingDeclaratorKind::Array;
4247 break;
4249 case DeclaratorChunk::Function:
4250 case DeclaratorChunk::Pipe:
4251 break;
4253 case DeclaratorChunk::BlockPointer:
4254 case DeclaratorChunk::MemberPointer:
4255 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4256 : PointerDeclaratorKind::SingleLevelPointer;
4258 case DeclaratorChunk::Paren:
4259 break;
4261 case DeclaratorChunk::Reference:
4262 if (numNormalPointers == 0)
4263 wrappingKind = PointerWrappingDeclaratorKind::Reference;
4264 break;
4266 case DeclaratorChunk::Pointer:
4267 ++numNormalPointers;
4268 if (numNormalPointers > 2)
4269 return PointerDeclaratorKind::MultiLevelPointer;
4270 break;
4274 // Then, dig into the type specifier itself.
4275 unsigned numTypeSpecifierPointers = 0;
4276 do {
4277 // Decompose normal pointers.
4278 if (auto ptrType = type->getAs<PointerType>()) {
4279 ++numNormalPointers;
4281 if (numNormalPointers > 2)
4282 return PointerDeclaratorKind::MultiLevelPointer;
4284 type = ptrType->getPointeeType();
4285 ++numTypeSpecifierPointers;
4286 continue;
4289 // Decompose block pointers.
4290 if (type->getAs<BlockPointerType>()) {
4291 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4292 : PointerDeclaratorKind::SingleLevelPointer;
4295 // Decompose member pointers.
4296 if (type->getAs<MemberPointerType>()) {
4297 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4298 : PointerDeclaratorKind::SingleLevelPointer;
4301 // Look at Objective-C object pointers.
4302 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
4303 ++numNormalPointers;
4304 ++numTypeSpecifierPointers;
4306 // If this is NSError**, report that.
4307 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
4308 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
4309 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
4310 return PointerDeclaratorKind::NSErrorPointerPointer;
4314 break;
4317 // Look at Objective-C class types.
4318 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
4319 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
4320 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
4321 return PointerDeclaratorKind::NSErrorPointerPointer;
4324 break;
4327 // If at this point we haven't seen a pointer, we won't see one.
4328 if (numNormalPointers == 0)
4329 return PointerDeclaratorKind::NonPointer;
4331 if (auto recordType = type->getAs<RecordType>()) {
4332 RecordDecl *recordDecl = recordType->getDecl();
4334 // If this is CFErrorRef*, report it as such.
4335 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 &&
4336 S.isCFError(recordDecl)) {
4337 return PointerDeclaratorKind::CFErrorRefPointer;
4339 break;
4342 break;
4343 } while (true);
4345 switch (numNormalPointers) {
4346 case 0:
4347 return PointerDeclaratorKind::NonPointer;
4349 case 1:
4350 return PointerDeclaratorKind::SingleLevelPointer;
4352 case 2:
4353 return PointerDeclaratorKind::MaybePointerToCFRef;
4355 default:
4356 return PointerDeclaratorKind::MultiLevelPointer;
4360 bool Sema::isCFError(RecordDecl *RD) {
4361 // If we already know about CFError, test it directly.
4362 if (CFError)
4363 return CFError == RD;
4365 // Check whether this is CFError, which we identify based on its bridge to
4366 // NSError. CFErrorRef used to be declared with "objc_bridge" but is now
4367 // declared with "objc_bridge_mutable", so look for either one of the two
4368 // attributes.
4369 if (RD->getTagKind() == TTK_Struct) {
4370 IdentifierInfo *bridgedType = nullptr;
4371 if (auto bridgeAttr = RD->getAttr<ObjCBridgeAttr>())
4372 bridgedType = bridgeAttr->getBridgedType();
4373 else if (auto bridgeAttr = RD->getAttr<ObjCBridgeMutableAttr>())
4374 bridgedType = bridgeAttr->getBridgedType();
4376 if (bridgedType == getNSErrorIdent()) {
4377 CFError = RD;
4378 return true;
4382 return false;
4385 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
4386 SourceLocation loc) {
4387 // If we're anywhere in a function, method, or closure context, don't perform
4388 // completeness checks.
4389 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
4390 if (ctx->isFunctionOrMethod())
4391 return FileID();
4393 if (ctx->isFileContext())
4394 break;
4397 // We only care about the expansion location.
4398 loc = S.SourceMgr.getExpansionLoc(loc);
4399 FileID file = S.SourceMgr.getFileID(loc);
4400 if (file.isInvalid())
4401 return FileID();
4403 // Retrieve file information.
4404 bool invalid = false;
4405 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4406 if (invalid || !sloc.isFile())
4407 return FileID();
4409 // We don't want to perform completeness checks on the main file or in
4410 // system headers.
4411 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4412 if (fileInfo.getIncludeLoc().isInvalid())
4413 return FileID();
4414 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4415 S.Diags.getSuppressSystemWarnings()) {
4416 return FileID();
4419 return file;
4422 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4423 /// taking into account whitespace before and after.
4424 template <typename DiagBuilderT>
4425 static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4426 SourceLocation PointerLoc,
4427 NullabilityKind Nullability) {
4428 assert(PointerLoc.isValid());
4429 if (PointerLoc.isMacroID())
4430 return;
4432 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4433 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4434 return;
4436 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4437 if (!NextChar)
4438 return;
4440 SmallString<32> InsertionTextBuf{" "};
4441 InsertionTextBuf += getNullabilitySpelling(Nullability);
4442 InsertionTextBuf += " ";
4443 StringRef InsertionText = InsertionTextBuf.str();
4445 if (isWhitespace(*NextChar)) {
4446 InsertionText = InsertionText.drop_back();
4447 } else if (NextChar[-1] == '[') {
4448 if (NextChar[0] == ']')
4449 InsertionText = InsertionText.drop_back().drop_front();
4450 else
4451 InsertionText = InsertionText.drop_front();
4452 } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) &&
4453 !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) {
4454 InsertionText = InsertionText.drop_back().drop_front();
4457 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4460 static void emitNullabilityConsistencyWarning(Sema &S,
4461 SimplePointerKind PointerKind,
4462 SourceLocation PointerLoc,
4463 SourceLocation PointerEndLoc) {
4464 assert(PointerLoc.isValid());
4466 if (PointerKind == SimplePointerKind::Array) {
4467 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4468 } else {
4469 S.Diag(PointerLoc, diag::warn_nullability_missing)
4470 << static_cast<unsigned>(PointerKind);
4473 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4474 if (FixItLoc.isMacroID())
4475 return;
4477 auto addFixIt = [&](NullabilityKind Nullability) {
4478 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4479 Diag << static_cast<unsigned>(Nullability);
4480 Diag << static_cast<unsigned>(PointerKind);
4481 fixItNullability(S, Diag, FixItLoc, Nullability);
4483 addFixIt(NullabilityKind::Nullable);
4484 addFixIt(NullabilityKind::NonNull);
4487 /// Complains about missing nullability if the file containing \p pointerLoc
4488 /// has other uses of nullability (either the keywords or the \c assume_nonnull
4489 /// pragma).
4491 /// If the file has \e not seen other uses of nullability, this particular
4492 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4493 static void
4494 checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4495 SourceLocation pointerLoc,
4496 SourceLocation pointerEndLoc = SourceLocation()) {
4497 // Determine which file we're performing consistency checking for.
4498 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4499 if (file.isInvalid())
4500 return;
4502 // If we haven't seen any type nullability in this file, we won't warn now
4503 // about anything.
4504 FileNullability &fileNullability = S.NullabilityMap[file];
4505 if (!fileNullability.SawTypeNullability) {
4506 // If this is the first pointer declarator in the file, and the appropriate
4507 // warning is on, record it in case we need to diagnose it retroactively.
4508 diag::kind diagKind;
4509 if (pointerKind == SimplePointerKind::Array)
4510 diagKind = diag::warn_nullability_missing_array;
4511 else
4512 diagKind = diag::warn_nullability_missing;
4514 if (fileNullability.PointerLoc.isInvalid() &&
4515 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
4516 fileNullability.PointerLoc = pointerLoc;
4517 fileNullability.PointerEndLoc = pointerEndLoc;
4518 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4521 return;
4524 // Complain about missing nullability.
4525 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4528 /// Marks that a nullability feature has been used in the file containing
4529 /// \p loc.
4531 /// If this file already had pointer types in it that were missing nullability,
4532 /// the first such instance is retroactively diagnosed.
4534 /// \sa checkNullabilityConsistency
4535 static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
4536 FileID file = getNullabilityCompletenessCheckFileID(S, loc);
4537 if (file.isInvalid())
4538 return;
4540 FileNullability &fileNullability = S.NullabilityMap[file];
4541 if (fileNullability.SawTypeNullability)
4542 return;
4543 fileNullability.SawTypeNullability = true;
4545 // If we haven't seen any type nullability before, now we have. Retroactively
4546 // diagnose the first unannotated pointer, if there was one.
4547 if (fileNullability.PointerLoc.isInvalid())
4548 return;
4550 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4551 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
4552 fileNullability.PointerEndLoc);
4555 /// Returns true if any of the declarator chunks before \p endIndex include a
4556 /// level of indirection: array, pointer, reference, or pointer-to-member.
4558 /// Because declarator chunks are stored in outer-to-inner order, testing
4559 /// every chunk before \p endIndex is testing all chunks that embed the current
4560 /// chunk as part of their type.
4562 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4563 /// end index, in which case all chunks are tested.
4564 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4565 unsigned i = endIndex;
4566 while (i != 0) {
4567 // Walk outwards along the declarator chunks.
4568 --i;
4569 const DeclaratorChunk &DC = D.getTypeObject(i);
4570 switch (DC.Kind) {
4571 case DeclaratorChunk::Paren:
4572 break;
4573 case DeclaratorChunk::Array:
4574 case DeclaratorChunk::Pointer:
4575 case DeclaratorChunk::Reference:
4576 case DeclaratorChunk::MemberPointer:
4577 return true;
4578 case DeclaratorChunk::Function:
4579 case DeclaratorChunk::BlockPointer:
4580 case DeclaratorChunk::Pipe:
4581 // These are invalid anyway, so just ignore.
4582 break;
4585 return false;
4588 static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk) {
4589 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4590 Chunk.Kind == DeclaratorChunk::Array);
4593 template<typename AttrT>
4594 static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4595 AL.setUsedAsTypeAttr();
4596 return ::new (Ctx) AttrT(Ctx, AL);
4599 static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr,
4600 NullabilityKind NK) {
4601 switch (NK) {
4602 case NullabilityKind::NonNull:
4603 return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
4605 case NullabilityKind::Nullable:
4606 return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
4608 case NullabilityKind::NullableResult:
4609 return createSimpleAttr<TypeNullableResultAttr>(Ctx, Attr);
4611 case NullabilityKind::Unspecified:
4612 return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
4614 llvm_unreachable("unknown NullabilityKind");
4617 // Diagnose whether this is a case with the multiple addr spaces.
4618 // Returns true if this is an invalid case.
4619 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4620 // by qualifiers for two or more different address spaces."
4621 static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld,
4622 LangAS ASNew,
4623 SourceLocation AttrLoc) {
4624 if (ASOld != LangAS::Default) {
4625 if (ASOld != ASNew) {
4626 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4627 return true;
4629 // Emit a warning if they are identical; it's likely unintended.
4630 S.Diag(AttrLoc,
4631 diag::warn_attribute_address_multiple_identical_qualifiers);
4633 return false;
4636 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4637 QualType declSpecType,
4638 TypeSourceInfo *TInfo) {
4639 // The TypeSourceInfo that this function returns will not be a null type.
4640 // If there is an error, this function will fill in a dummy type as fallback.
4641 QualType T = declSpecType;
4642 Declarator &D = state.getDeclarator();
4643 Sema &S = state.getSema();
4644 ASTContext &Context = S.Context;
4645 const LangOptions &LangOpts = S.getLangOpts();
4647 // The name we're declaring, if any.
4648 DeclarationName Name;
4649 if (D.getIdentifier())
4650 Name = D.getIdentifier();
4652 // Does this declaration declare a typedef-name?
4653 bool IsTypedefName =
4654 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
4655 D.getContext() == DeclaratorContext::AliasDecl ||
4656 D.getContext() == DeclaratorContext::AliasTemplate;
4658 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4659 bool IsQualifiedFunction = T->isFunctionProtoType() &&
4660 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4661 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4663 // If T is 'decltype(auto)', the only declarators we can have are parens
4664 // and at most one function declarator if this is a function declaration.
4665 // If T is a deduced class template specialization type, we can have no
4666 // declarator chunks at all.
4667 if (auto *DT = T->getAs<DeducedType>()) {
4668 const AutoType *AT = T->getAs<AutoType>();
4669 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4670 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4671 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4672 unsigned Index = E - I - 1;
4673 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4674 unsigned DiagId = IsClassTemplateDeduction
4675 ? diag::err_deduced_class_template_compound_type
4676 : diag::err_decltype_auto_compound_type;
4677 unsigned DiagKind = 0;
4678 switch (DeclChunk.Kind) {
4679 case DeclaratorChunk::Paren:
4680 // FIXME: Rejecting this is a little silly.
4681 if (IsClassTemplateDeduction) {
4682 DiagKind = 4;
4683 break;
4685 continue;
4686 case DeclaratorChunk::Function: {
4687 if (IsClassTemplateDeduction) {
4688 DiagKind = 3;
4689 break;
4691 unsigned FnIndex;
4692 if (D.isFunctionDeclarationContext() &&
4693 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4694 continue;
4695 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4696 break;
4698 case DeclaratorChunk::Pointer:
4699 case DeclaratorChunk::BlockPointer:
4700 case DeclaratorChunk::MemberPointer:
4701 DiagKind = 0;
4702 break;
4703 case DeclaratorChunk::Reference:
4704 DiagKind = 1;
4705 break;
4706 case DeclaratorChunk::Array:
4707 DiagKind = 2;
4708 break;
4709 case DeclaratorChunk::Pipe:
4710 break;
4713 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4714 D.setInvalidType(true);
4715 break;
4720 // Determine whether we should infer _Nonnull on pointer types.
4721 std::optional<NullabilityKind> inferNullability;
4722 bool inferNullabilityCS = false;
4723 bool inferNullabilityInnerOnly = false;
4724 bool inferNullabilityInnerOnlyComplete = false;
4726 // Are we in an assume-nonnull region?
4727 bool inAssumeNonNullRegion = false;
4728 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4729 if (assumeNonNullLoc.isValid()) {
4730 inAssumeNonNullRegion = true;
4731 recordNullabilitySeen(S, assumeNonNullLoc);
4734 // Whether to complain about missing nullability specifiers or not.
4735 enum {
4736 /// Never complain.
4737 CAMN_No,
4738 /// Complain on the inner pointers (but not the outermost
4739 /// pointer).
4740 CAMN_InnerPointers,
4741 /// Complain about any pointers that don't have nullability
4742 /// specified or inferred.
4743 CAMN_Yes
4744 } complainAboutMissingNullability = CAMN_No;
4745 unsigned NumPointersRemaining = 0;
4746 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4748 if (IsTypedefName) {
4749 // For typedefs, we do not infer any nullability (the default),
4750 // and we only complain about missing nullability specifiers on
4751 // inner pointers.
4752 complainAboutMissingNullability = CAMN_InnerPointers;
4754 if (T->canHaveNullability(/*ResultIfUnknown*/ false) &&
4755 !T->getNullability()) {
4756 // Note that we allow but don't require nullability on dependent types.
4757 ++NumPointersRemaining;
4760 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4761 DeclaratorChunk &chunk = D.getTypeObject(i);
4762 switch (chunk.Kind) {
4763 case DeclaratorChunk::Array:
4764 case DeclaratorChunk::Function:
4765 case DeclaratorChunk::Pipe:
4766 break;
4768 case DeclaratorChunk::BlockPointer:
4769 case DeclaratorChunk::MemberPointer:
4770 ++NumPointersRemaining;
4771 break;
4773 case DeclaratorChunk::Paren:
4774 case DeclaratorChunk::Reference:
4775 continue;
4777 case DeclaratorChunk::Pointer:
4778 ++NumPointersRemaining;
4779 continue;
4782 } else {
4783 bool isFunctionOrMethod = false;
4784 switch (auto context = state.getDeclarator().getContext()) {
4785 case DeclaratorContext::ObjCParameter:
4786 case DeclaratorContext::ObjCResult:
4787 case DeclaratorContext::Prototype:
4788 case DeclaratorContext::TrailingReturn:
4789 case DeclaratorContext::TrailingReturnVar:
4790 isFunctionOrMethod = true;
4791 [[fallthrough]];
4793 case DeclaratorContext::Member:
4794 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4795 complainAboutMissingNullability = CAMN_No;
4796 break;
4799 // Weak properties are inferred to be nullable.
4800 if (state.getDeclarator().isObjCWeakProperty()) {
4801 // Weak properties cannot be nonnull, and should not complain about
4802 // missing nullable attributes during completeness checks.
4803 complainAboutMissingNullability = CAMN_No;
4804 if (inAssumeNonNullRegion) {
4805 inferNullability = NullabilityKind::Nullable;
4807 break;
4810 [[fallthrough]];
4812 case DeclaratorContext::File:
4813 case DeclaratorContext::KNRTypeList: {
4814 complainAboutMissingNullability = CAMN_Yes;
4816 // Nullability inference depends on the type and declarator.
4817 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4818 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4819 case PointerDeclaratorKind::NonPointer:
4820 case PointerDeclaratorKind::MultiLevelPointer:
4821 // Cannot infer nullability.
4822 break;
4824 case PointerDeclaratorKind::SingleLevelPointer:
4825 // Infer _Nonnull if we are in an assumes-nonnull region.
4826 if (inAssumeNonNullRegion) {
4827 complainAboutInferringWithinChunk = wrappingKind;
4828 inferNullability = NullabilityKind::NonNull;
4829 inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4830 context == DeclaratorContext::ObjCResult);
4832 break;
4834 case PointerDeclaratorKind::CFErrorRefPointer:
4835 case PointerDeclaratorKind::NSErrorPointerPointer:
4836 // Within a function or method signature, infer _Nullable at both
4837 // levels.
4838 if (isFunctionOrMethod && inAssumeNonNullRegion)
4839 inferNullability = NullabilityKind::Nullable;
4840 break;
4842 case PointerDeclaratorKind::MaybePointerToCFRef:
4843 if (isFunctionOrMethod) {
4844 // On pointer-to-pointer parameters marked cf_returns_retained or
4845 // cf_returns_not_retained, if the outer pointer is explicit then
4846 // infer the inner pointer as _Nullable.
4847 auto hasCFReturnsAttr =
4848 [](const ParsedAttributesView &AttrList) -> bool {
4849 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4850 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4852 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4853 if (hasCFReturnsAttr(D.getDeclarationAttributes()) ||
4854 hasCFReturnsAttr(D.getAttributes()) ||
4855 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4856 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4857 inferNullability = NullabilityKind::Nullable;
4858 inferNullabilityInnerOnly = true;
4862 break;
4864 break;
4867 case DeclaratorContext::ConversionId:
4868 complainAboutMissingNullability = CAMN_Yes;
4869 break;
4871 case DeclaratorContext::AliasDecl:
4872 case DeclaratorContext::AliasTemplate:
4873 case DeclaratorContext::Block:
4874 case DeclaratorContext::BlockLiteral:
4875 case DeclaratorContext::Condition:
4876 case DeclaratorContext::CXXCatch:
4877 case DeclaratorContext::CXXNew:
4878 case DeclaratorContext::ForInit:
4879 case DeclaratorContext::SelectionInit:
4880 case DeclaratorContext::LambdaExpr:
4881 case DeclaratorContext::LambdaExprParameter:
4882 case DeclaratorContext::ObjCCatch:
4883 case DeclaratorContext::TemplateParam:
4884 case DeclaratorContext::TemplateArg:
4885 case DeclaratorContext::TemplateTypeArg:
4886 case DeclaratorContext::TypeName:
4887 case DeclaratorContext::FunctionalCast:
4888 case DeclaratorContext::RequiresExpr:
4889 case DeclaratorContext::Association:
4890 // Don't infer in these contexts.
4891 break;
4895 // Local function that returns true if its argument looks like a va_list.
4896 auto isVaList = [&S](QualType T) -> bool {
4897 auto *typedefTy = T->getAs<TypedefType>();
4898 if (!typedefTy)
4899 return false;
4900 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4901 do {
4902 if (typedefTy->getDecl() == vaListTypedef)
4903 return true;
4904 if (auto *name = typedefTy->getDecl()->getIdentifier())
4905 if (name->isStr("va_list"))
4906 return true;
4907 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4908 } while (typedefTy);
4909 return false;
4912 // Local function that checks the nullability for a given pointer declarator.
4913 // Returns true if _Nonnull was inferred.
4914 auto inferPointerNullability =
4915 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4916 SourceLocation pointerEndLoc,
4917 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4918 // We've seen a pointer.
4919 if (NumPointersRemaining > 0)
4920 --NumPointersRemaining;
4922 // If a nullability attribute is present, there's nothing to do.
4923 if (hasNullabilityAttr(attrs))
4924 return nullptr;
4926 // If we're supposed to infer nullability, do so now.
4927 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4928 ParsedAttr::Form form =
4929 inferNullabilityCS
4930 ? ParsedAttr::Form::ContextSensitiveKeyword()
4931 : ParsedAttr::Form::Keyword(false /*IsAlignAs*/,
4932 false /*IsRegularKeywordAttribute*/);
4933 ParsedAttr *nullabilityAttr = Pool.create(
4934 S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4935 nullptr, SourceLocation(), nullptr, 0, form);
4937 attrs.addAtEnd(nullabilityAttr);
4939 if (inferNullabilityCS) {
4940 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4941 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4944 if (pointerLoc.isValid() &&
4945 complainAboutInferringWithinChunk !=
4946 PointerWrappingDeclaratorKind::None) {
4947 auto Diag =
4948 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4949 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4950 fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
4953 if (inferNullabilityInnerOnly)
4954 inferNullabilityInnerOnlyComplete = true;
4955 return nullabilityAttr;
4958 // If we're supposed to complain about missing nullability, do so
4959 // now if it's truly missing.
4960 switch (complainAboutMissingNullability) {
4961 case CAMN_No:
4962 break;
4964 case CAMN_InnerPointers:
4965 if (NumPointersRemaining == 0)
4966 break;
4967 [[fallthrough]];
4969 case CAMN_Yes:
4970 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4972 return nullptr;
4975 // If the type itself could have nullability but does not, infer pointer
4976 // nullability and perform consistency checking.
4977 if (S.CodeSynthesisContexts.empty()) {
4978 if (T->canHaveNullability(/*ResultIfUnknown*/ false) &&
4979 !T->getNullability()) {
4980 if (isVaList(T)) {
4981 // Record that we've seen a pointer, but do nothing else.
4982 if (NumPointersRemaining > 0)
4983 --NumPointersRemaining;
4984 } else {
4985 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4986 if (T->isBlockPointerType())
4987 pointerKind = SimplePointerKind::BlockPointer;
4988 else if (T->isMemberPointerType())
4989 pointerKind = SimplePointerKind::MemberPointer;
4991 if (auto *attr = inferPointerNullability(
4992 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4993 D.getDeclSpec().getEndLoc(),
4994 D.getMutableDeclSpec().getAttributes(),
4995 D.getMutableDeclSpec().getAttributePool())) {
4996 T = state.getAttributedType(
4997 createNullabilityAttr(Context, *attr, *inferNullability), T, T);
5002 if (complainAboutMissingNullability == CAMN_Yes && T->isArrayType() &&
5003 !T->getNullability() && !isVaList(T) && D.isPrototypeContext() &&
5004 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
5005 checkNullabilityConsistency(S, SimplePointerKind::Array,
5006 D.getDeclSpec().getTypeSpecTypeLoc());
5010 bool ExpectNoDerefChunk =
5011 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
5013 // Walk the DeclTypeInfo, building the recursive type as we go.
5014 // DeclTypeInfos are ordered from the identifier out, which is
5015 // opposite of what we want :).
5017 // Track if the produced type matches the structure of the declarator.
5018 // This is used later to decide if we can fill `TypeLoc` from
5019 // `DeclaratorChunk`s. E.g. it must be false if Clang recovers from
5020 // an error by replacing the type with `int`.
5021 bool AreDeclaratorChunksValid = true;
5022 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5023 unsigned chunkIndex = e - i - 1;
5024 state.setCurrentChunkIndex(chunkIndex);
5025 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
5026 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
5027 switch (DeclType.Kind) {
5028 case DeclaratorChunk::Paren:
5029 if (i == 0)
5030 warnAboutRedundantParens(S, D, T);
5031 T = S.BuildParenType(T);
5032 break;
5033 case DeclaratorChunk::BlockPointer:
5034 // If blocks are disabled, emit an error.
5035 if (!LangOpts.Blocks)
5036 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
5038 // Handle pointer nullability.
5039 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
5040 DeclType.EndLoc, DeclType.getAttrs(),
5041 state.getDeclarator().getAttributePool());
5043 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
5044 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
5045 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
5046 // qualified with const.
5047 if (LangOpts.OpenCL)
5048 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
5049 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
5051 break;
5052 case DeclaratorChunk::Pointer:
5053 // Verify that we're not building a pointer to pointer to function with
5054 // exception specification.
5055 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
5056 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
5057 D.setInvalidType(true);
5058 // Build the type anyway.
5061 // Handle pointer nullability
5062 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
5063 DeclType.EndLoc, DeclType.getAttrs(),
5064 state.getDeclarator().getAttributePool());
5066 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
5067 T = Context.getObjCObjectPointerType(T);
5068 if (DeclType.Ptr.TypeQuals)
5069 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
5070 break;
5073 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
5074 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
5075 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
5076 if (LangOpts.OpenCL) {
5077 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
5078 T->isBlockPointerType()) {
5079 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
5080 D.setInvalidType(true);
5084 T = S.BuildPointerType(T, DeclType.Loc, Name);
5085 if (DeclType.Ptr.TypeQuals)
5086 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
5087 break;
5088 case DeclaratorChunk::Reference: {
5089 // Verify that we're not building a reference to pointer to function with
5090 // exception specification.
5091 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
5092 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
5093 D.setInvalidType(true);
5094 // Build the type anyway.
5096 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
5098 if (DeclType.Ref.HasRestrict)
5099 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
5100 break;
5102 case DeclaratorChunk::Array: {
5103 // Verify that we're not building an array of pointers to function with
5104 // exception specification.
5105 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
5106 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
5107 D.setInvalidType(true);
5108 // Build the type anyway.
5110 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
5111 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
5112 ArrayType::ArraySizeModifier ASM;
5114 // Microsoft property fields can have multiple sizeless array chunks
5115 // (i.e. int x[][][]). Skip all of these except one to avoid creating
5116 // bad incomplete array types.
5117 if (chunkIndex != 0 && !ArraySize &&
5118 D.getDeclSpec().getAttributes().hasMSPropertyAttr()) {
5119 // This is a sizeless chunk. If the next is also, skip this one.
5120 DeclaratorChunk &NextDeclType = D.getTypeObject(chunkIndex - 1);
5121 if (NextDeclType.Kind == DeclaratorChunk::Array &&
5122 !NextDeclType.Arr.NumElts)
5123 break;
5126 if (ATI.isStar)
5127 ASM = ArrayType::Star;
5128 else if (ATI.hasStatic)
5129 ASM = ArrayType::Static;
5130 else
5131 ASM = ArrayType::Normal;
5132 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
5133 // FIXME: This check isn't quite right: it allows star in prototypes
5134 // for function definitions, and disallows some edge cases detailed
5135 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
5136 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
5137 ASM = ArrayType::Normal;
5138 D.setInvalidType(true);
5141 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
5142 // shall appear only in a declaration of a function parameter with an
5143 // array type, ...
5144 if (ASM == ArrayType::Static || ATI.TypeQuals) {
5145 if (!(D.isPrototypeContext() ||
5146 D.getContext() == DeclaratorContext::KNRTypeList)) {
5147 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
5148 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
5149 // Remove the 'static' and the type qualifiers.
5150 if (ASM == ArrayType::Static)
5151 ASM = ArrayType::Normal;
5152 ATI.TypeQuals = 0;
5153 D.setInvalidType(true);
5156 // C99 6.7.5.2p1: ... and then only in the outermost array type
5157 // derivation.
5158 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
5159 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
5160 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
5161 if (ASM == ArrayType::Static)
5162 ASM = ArrayType::Normal;
5163 ATI.TypeQuals = 0;
5164 D.setInvalidType(true);
5168 // Array parameters can be marked nullable as well, although it's not
5169 // necessary if they're marked 'static'.
5170 if (complainAboutMissingNullability == CAMN_Yes &&
5171 !hasNullabilityAttr(DeclType.getAttrs()) &&
5172 ASM != ArrayType::Static &&
5173 D.isPrototypeContext() &&
5174 !hasOuterPointerLikeChunk(D, chunkIndex)) {
5175 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
5178 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
5179 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
5180 break;
5182 case DeclaratorChunk::Function: {
5183 // If the function declarator has a prototype (i.e. it is not () and
5184 // does not have a K&R-style identifier list), then the arguments are part
5185 // of the type, otherwise the argument list is ().
5186 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5187 IsQualifiedFunction =
5188 FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier();
5190 // Check for auto functions and trailing return type and adjust the
5191 // return type accordingly.
5192 if (!D.isInvalidType()) {
5193 // trailing-return-type is only required if we're declaring a function,
5194 // and not, for instance, a pointer to a function.
5195 if (D.getDeclSpec().hasAutoTypeSpec() &&
5196 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
5197 if (!S.getLangOpts().CPlusPlus14) {
5198 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5199 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
5200 ? diag::err_auto_missing_trailing_return
5201 : diag::err_deduced_return_type);
5202 T = Context.IntTy;
5203 D.setInvalidType(true);
5204 AreDeclaratorChunksValid = false;
5205 } else {
5206 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5207 diag::warn_cxx11_compat_deduced_return_type);
5209 } else if (FTI.hasTrailingReturnType()) {
5210 // T must be exactly 'auto' at this point. See CWG issue 681.
5211 if (isa<ParenType>(T)) {
5212 S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
5213 << T << D.getSourceRange();
5214 D.setInvalidType(true);
5215 // FIXME: recover and fill decls in `TypeLoc`s.
5216 AreDeclaratorChunksValid = false;
5217 } else if (D.getName().getKind() ==
5218 UnqualifiedIdKind::IK_DeductionGuideName) {
5219 if (T != Context.DependentTy) {
5220 S.Diag(D.getDeclSpec().getBeginLoc(),
5221 diag::err_deduction_guide_with_complex_decl)
5222 << D.getSourceRange();
5223 D.setInvalidType(true);
5224 // FIXME: recover and fill decls in `TypeLoc`s.
5225 AreDeclaratorChunksValid = false;
5227 } else if (D.getContext() != DeclaratorContext::LambdaExpr &&
5228 (T.hasQualifiers() || !isa<AutoType>(T) ||
5229 cast<AutoType>(T)->getKeyword() !=
5230 AutoTypeKeyword::Auto ||
5231 cast<AutoType>(T)->isConstrained())) {
5232 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5233 diag::err_trailing_return_without_auto)
5234 << T << D.getDeclSpec().getSourceRange();
5235 D.setInvalidType(true);
5236 // FIXME: recover and fill decls in `TypeLoc`s.
5237 AreDeclaratorChunksValid = false;
5239 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
5240 if (T.isNull()) {
5241 // An error occurred parsing the trailing return type.
5242 T = Context.IntTy;
5243 D.setInvalidType(true);
5244 } else if (AutoType *Auto = T->getContainedAutoType()) {
5245 // If the trailing return type contains an `auto`, we may need to
5246 // invent a template parameter for it, for cases like
5247 // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
5248 InventedTemplateParameterInfo *InventedParamInfo = nullptr;
5249 if (D.getContext() == DeclaratorContext::Prototype)
5250 InventedParamInfo = &S.InventedParameterInfos.back();
5251 else if (D.getContext() == DeclaratorContext::LambdaExprParameter)
5252 InventedParamInfo = S.getCurLambda();
5253 if (InventedParamInfo) {
5254 std::tie(T, TInfo) = InventTemplateParameter(
5255 state, T, TInfo, Auto, *InventedParamInfo);
5258 } else {
5259 // This function type is not the type of the entity being declared,
5260 // so checking the 'auto' is not the responsibility of this chunk.
5264 // C99 6.7.5.3p1: The return type may not be a function or array type.
5265 // For conversion functions, we'll diagnose this particular error later.
5266 if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
5267 (D.getName().getKind() !=
5268 UnqualifiedIdKind::IK_ConversionFunctionId)) {
5269 unsigned diagID = diag::err_func_returning_array_function;
5270 // Last processing chunk in block context means this function chunk
5271 // represents the block.
5272 if (chunkIndex == 0 &&
5273 D.getContext() == DeclaratorContext::BlockLiteral)
5274 diagID = diag::err_block_returning_array_function;
5275 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
5276 T = Context.IntTy;
5277 D.setInvalidType(true);
5278 AreDeclaratorChunksValid = false;
5281 // Do not allow returning half FP value.
5282 // FIXME: This really should be in BuildFunctionType.
5283 if (T->isHalfType()) {
5284 if (S.getLangOpts().OpenCL) {
5285 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5286 S.getLangOpts())) {
5287 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5288 << T << 0 /*pointer hint*/;
5289 D.setInvalidType(true);
5291 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5292 !S.Context.getTargetInfo().allowHalfArgsAndReturns()) {
5293 S.Diag(D.getIdentifierLoc(),
5294 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
5295 D.setInvalidType(true);
5299 if (LangOpts.OpenCL) {
5300 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
5301 // function.
5302 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
5303 T->isPipeType()) {
5304 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5305 << T << 1 /*hint off*/;
5306 D.setInvalidType(true);
5308 // OpenCL doesn't support variadic functions and blocks
5309 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
5310 // We also allow here any toolchain reserved identifiers.
5311 if (FTI.isVariadic &&
5312 !S.getOpenCLOptions().isAvailableOption(
5313 "__cl_clang_variadic_functions", S.getLangOpts()) &&
5314 !(D.getIdentifier() &&
5315 ((D.getIdentifier()->getName() == "printf" &&
5316 LangOpts.getOpenCLCompatibleVersion() >= 120) ||
5317 D.getIdentifier()->getName().startswith("__")))) {
5318 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
5319 D.setInvalidType(true);
5323 // Methods cannot return interface types. All ObjC objects are
5324 // passed by reference.
5325 if (T->isObjCObjectType()) {
5326 SourceLocation DiagLoc, FixitLoc;
5327 if (TInfo) {
5328 DiagLoc = TInfo->getTypeLoc().getBeginLoc();
5329 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
5330 } else {
5331 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5332 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
5334 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
5335 << 0 << T
5336 << FixItHint::CreateInsertion(FixitLoc, "*");
5338 T = Context.getObjCObjectPointerType(T);
5339 if (TInfo) {
5340 TypeLocBuilder TLB;
5341 TLB.pushFullCopy(TInfo->getTypeLoc());
5342 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
5343 TLoc.setStarLoc(FixitLoc);
5344 TInfo = TLB.getTypeSourceInfo(Context, T);
5345 } else {
5346 AreDeclaratorChunksValid = false;
5349 D.setInvalidType(true);
5352 // cv-qualifiers on return types are pointless except when the type is a
5353 // class type in C++.
5354 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
5355 !(S.getLangOpts().CPlusPlus &&
5356 (T->isDependentType() || T->isRecordType()))) {
5357 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
5358 D.getFunctionDefinitionKind() ==
5359 FunctionDefinitionKind::Definition) {
5360 // [6.9.1/3] qualified void return is invalid on a C
5361 // function definition. Apparently ok on declarations and
5362 // in C++ though (!)
5363 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
5364 } else
5365 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
5367 // C++2a [dcl.fct]p12:
5368 // A volatile-qualified return type is deprecated
5369 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20)
5370 S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T;
5373 // Objective-C ARC ownership qualifiers are ignored on the function
5374 // return type (by type canonicalization). Complain if this attribute
5375 // was written here.
5376 if (T.getQualifiers().hasObjCLifetime()) {
5377 SourceLocation AttrLoc;
5378 if (chunkIndex + 1 < D.getNumTypeObjects()) {
5379 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
5380 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5381 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5382 AttrLoc = AL.getLoc();
5383 break;
5387 if (AttrLoc.isInvalid()) {
5388 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5389 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5390 AttrLoc = AL.getLoc();
5391 break;
5396 if (AttrLoc.isValid()) {
5397 // The ownership attributes are almost always written via
5398 // the predefined
5399 // __strong/__weak/__autoreleasing/__unsafe_unretained.
5400 if (AttrLoc.isMacroID())
5401 AttrLoc =
5402 S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin();
5404 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
5405 << T.getQualifiers().getObjCLifetime();
5409 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
5410 // C++ [dcl.fct]p6:
5411 // Types shall not be defined in return or parameter types.
5412 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
5413 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
5414 << Context.getTypeDeclType(Tag);
5417 // Exception specs are not allowed in typedefs. Complain, but add it
5418 // anyway.
5419 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
5420 S.Diag(FTI.getExceptionSpecLocBeg(),
5421 diag::err_exception_spec_in_typedef)
5422 << (D.getContext() == DeclaratorContext::AliasDecl ||
5423 D.getContext() == DeclaratorContext::AliasTemplate);
5425 // If we see "T var();" or "T var(T());" at block scope, it is probably
5426 // an attempt to initialize a variable, not a function declaration.
5427 if (FTI.isAmbiguous)
5428 warnAboutAmbiguousFunction(S, D, DeclType, T);
5430 FunctionType::ExtInfo EI(
5431 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
5433 // OpenCL disallows functions without a prototype, but it doesn't enforce
5434 // strict prototypes as in C23 because it allows a function definition to
5435 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
5436 if (!FTI.NumParams && !FTI.isVariadic &&
5437 !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) {
5438 // Simple void foo(), where the incoming T is the result type.
5439 T = Context.getFunctionNoProtoType(T, EI);
5440 } else {
5441 // We allow a zero-parameter variadic function in C if the
5442 // function is marked with the "overloadable" attribute. Scan
5443 // for this attribute now. We also allow it in C23 per WG14 N2975.
5444 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
5445 if (LangOpts.C23)
5446 S.Diag(FTI.getEllipsisLoc(),
5447 diag::warn_c17_compat_ellipsis_only_parameter);
5448 else if (!D.getDeclarationAttributes().hasAttribute(
5449 ParsedAttr::AT_Overloadable) &&
5450 !D.getAttributes().hasAttribute(
5451 ParsedAttr::AT_Overloadable) &&
5452 !D.getDeclSpec().getAttributes().hasAttribute(
5453 ParsedAttr::AT_Overloadable))
5454 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
5457 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
5458 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5459 // definition.
5460 S.Diag(FTI.Params[0].IdentLoc,
5461 diag::err_ident_list_in_fn_declaration);
5462 D.setInvalidType(true);
5463 // Recover by creating a K&R-style function type, if possible.
5464 T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL)
5465 ? Context.getFunctionNoProtoType(T, EI)
5466 : Context.IntTy;
5467 AreDeclaratorChunksValid = false;
5468 break;
5471 FunctionProtoType::ExtProtoInfo EPI;
5472 EPI.ExtInfo = EI;
5473 EPI.Variadic = FTI.isVariadic;
5474 EPI.EllipsisLoc = FTI.getEllipsisLoc();
5475 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
5476 EPI.TypeQuals.addCVRUQualifiers(
5477 FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers()
5478 : 0);
5479 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
5480 : FTI.RefQualifierIsLValueRef? RQ_LValue
5481 : RQ_RValue;
5483 // Otherwise, we have a function with a parameter list that is
5484 // potentially variadic.
5485 SmallVector<QualType, 16> ParamTys;
5486 ParamTys.reserve(FTI.NumParams);
5488 SmallVector<FunctionProtoType::ExtParameterInfo, 16>
5489 ExtParameterInfos(FTI.NumParams);
5490 bool HasAnyInterestingExtParameterInfos = false;
5492 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
5493 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5494 QualType ParamTy = Param->getType();
5495 assert(!ParamTy.isNull() && "Couldn't parse type?");
5497 // Look for 'void'. void is allowed only as a single parameter to a
5498 // function with no other parameters (C99 6.7.5.3p10). We record
5499 // int(void) as a FunctionProtoType with an empty parameter list.
5500 if (ParamTy->isVoidType()) {
5501 // If this is something like 'float(int, void)', reject it. 'void'
5502 // is an incomplete type (C99 6.2.5p19) and function decls cannot
5503 // have parameters of incomplete type.
5504 if (FTI.NumParams != 1 || FTI.isVariadic) {
5505 S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param);
5506 ParamTy = Context.IntTy;
5507 Param->setType(ParamTy);
5508 } else if (FTI.Params[i].Ident) {
5509 // Reject, but continue to parse 'int(void abc)'.
5510 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
5511 ParamTy = Context.IntTy;
5512 Param->setType(ParamTy);
5513 } else {
5514 // Reject, but continue to parse 'float(const void)'.
5515 if (ParamTy.hasQualifiers())
5516 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
5518 // Do not add 'void' to the list.
5519 break;
5521 } else if (ParamTy->isHalfType()) {
5522 // Disallow half FP parameters.
5523 // FIXME: This really should be in BuildFunctionType.
5524 if (S.getLangOpts().OpenCL) {
5525 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5526 S.getLangOpts())) {
5527 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5528 << ParamTy << 0;
5529 D.setInvalidType();
5530 Param->setInvalidDecl();
5532 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5533 !S.Context.getTargetInfo().allowHalfArgsAndReturns()) {
5534 S.Diag(Param->getLocation(),
5535 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5536 D.setInvalidType();
5538 } else if (!FTI.hasPrototype) {
5539 if (Context.isPromotableIntegerType(ParamTy)) {
5540 ParamTy = Context.getPromotedIntegerType(ParamTy);
5541 Param->setKNRPromoted(true);
5542 } else if (const BuiltinType *BTy = ParamTy->getAs<BuiltinType>()) {
5543 if (BTy->getKind() == BuiltinType::Float) {
5544 ParamTy = Context.DoubleTy;
5545 Param->setKNRPromoted(true);
5548 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) {
5549 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5550 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5551 << ParamTy << 1 /*hint off*/;
5552 D.setInvalidType();
5555 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
5556 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
5557 HasAnyInterestingExtParameterInfos = true;
5560 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5561 ExtParameterInfos[i] =
5562 ExtParameterInfos[i].withABI(attr->getABI());
5563 HasAnyInterestingExtParameterInfos = true;
5566 if (Param->hasAttr<PassObjectSizeAttr>()) {
5567 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5568 HasAnyInterestingExtParameterInfos = true;
5571 if (Param->hasAttr<NoEscapeAttr>()) {
5572 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
5573 HasAnyInterestingExtParameterInfos = true;
5576 ParamTys.push_back(ParamTy);
5579 if (HasAnyInterestingExtParameterInfos) {
5580 EPI.ExtParameterInfos = ExtParameterInfos.data();
5581 checkExtParameterInfos(S, ParamTys, EPI,
5582 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
5585 SmallVector<QualType, 4> Exceptions;
5586 SmallVector<ParsedType, 2> DynamicExceptions;
5587 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5588 Expr *NoexceptExpr = nullptr;
5590 if (FTI.getExceptionSpecType() == EST_Dynamic) {
5591 // FIXME: It's rather inefficient to have to split into two vectors
5592 // here.
5593 unsigned N = FTI.getNumExceptions();
5594 DynamicExceptions.reserve(N);
5595 DynamicExceptionRanges.reserve(N);
5596 for (unsigned I = 0; I != N; ++I) {
5597 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
5598 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
5600 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
5601 NoexceptExpr = FTI.NoexceptExpr;
5604 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
5605 FTI.getExceptionSpecType(),
5606 DynamicExceptions,
5607 DynamicExceptionRanges,
5608 NoexceptExpr,
5609 Exceptions,
5610 EPI.ExceptionSpec);
5612 // FIXME: Set address space from attrs for C++ mode here.
5613 // OpenCLCPlusPlus: A class member function has an address space.
5614 auto IsClassMember = [&]() {
5615 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5616 state.getDeclarator()
5617 .getCXXScopeSpec()
5618 .getScopeRep()
5619 ->getKind() == NestedNameSpecifier::TypeSpec) ||
5620 state.getDeclarator().getContext() ==
5621 DeclaratorContext::Member ||
5622 state.getDeclarator().getContext() ==
5623 DeclaratorContext::LambdaExpr;
5626 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
5627 LangAS ASIdx = LangAS::Default;
5628 // Take address space attr if any and mark as invalid to avoid adding
5629 // them later while creating QualType.
5630 if (FTI.MethodQualifiers)
5631 for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) {
5632 LangAS ASIdxNew = attr.asOpenCLLangAS();
5633 if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
5634 attr.getLoc()))
5635 D.setInvalidType(true);
5636 else
5637 ASIdx = ASIdxNew;
5639 // If a class member function's address space is not set, set it to
5640 // __generic.
5641 LangAS AS =
5642 (ASIdx == LangAS::Default ? S.getDefaultCXXMethodAddrSpace()
5643 : ASIdx);
5644 EPI.TypeQuals.addAddressSpace(AS);
5646 T = Context.getFunctionType(T, ParamTys, EPI);
5648 break;
5650 case DeclaratorChunk::MemberPointer: {
5651 // The scope spec must refer to a class, or be dependent.
5652 CXXScopeSpec &SS = DeclType.Mem.Scope();
5653 QualType ClsType;
5655 // Handle pointer nullability.
5656 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5657 DeclType.EndLoc, DeclType.getAttrs(),
5658 state.getDeclarator().getAttributePool());
5660 if (SS.isInvalid()) {
5661 // Avoid emitting extra errors if we already errored on the scope.
5662 D.setInvalidType(true);
5663 } else if (S.isDependentScopeSpecifier(SS) ||
5664 isa_and_nonnull<CXXRecordDecl>(S.computeDeclContext(SS))) {
5665 NestedNameSpecifier *NNS = SS.getScopeRep();
5666 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
5667 switch (NNS->getKind()) {
5668 case NestedNameSpecifier::Identifier:
5669 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
5670 NNS->getAsIdentifier());
5671 break;
5673 case NestedNameSpecifier::Namespace:
5674 case NestedNameSpecifier::NamespaceAlias:
5675 case NestedNameSpecifier::Global:
5676 case NestedNameSpecifier::Super:
5677 llvm_unreachable("Nested-name-specifier must name a type");
5679 case NestedNameSpecifier::TypeSpec:
5680 case NestedNameSpecifier::TypeSpecWithTemplate:
5681 ClsType = QualType(NNS->getAsType(), 0);
5682 // Note: if the NNS has a prefix and ClsType is a nondependent
5683 // TemplateSpecializationType, then the NNS prefix is NOT included
5684 // in ClsType; hence we wrap ClsType into an ElaboratedType.
5685 // NOTE: in particular, no wrap occurs if ClsType already is an
5686 // Elaborated, DependentName, or DependentTemplateSpecialization.
5687 if (isa<TemplateSpecializationType>(NNS->getAsType()))
5688 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
5689 break;
5691 } else {
5692 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
5693 diag::err_illegal_decl_mempointer_in_nonclass)
5694 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
5695 << DeclType.Mem.Scope().getRange();
5696 D.setInvalidType(true);
5699 if (!ClsType.isNull())
5700 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
5701 D.getIdentifier());
5702 else
5703 AreDeclaratorChunksValid = false;
5705 if (T.isNull()) {
5706 T = Context.IntTy;
5707 D.setInvalidType(true);
5708 AreDeclaratorChunksValid = false;
5709 } else if (DeclType.Mem.TypeQuals) {
5710 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
5712 break;
5715 case DeclaratorChunk::Pipe: {
5716 T = S.BuildReadPipeType(T, DeclType.Loc);
5717 processTypeAttrs(state, T, TAL_DeclSpec,
5718 D.getMutableDeclSpec().getAttributes());
5719 break;
5723 if (T.isNull()) {
5724 D.setInvalidType(true);
5725 T = Context.IntTy;
5726 AreDeclaratorChunksValid = false;
5729 // See if there are any attributes on this declarator chunk.
5730 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs());
5732 if (DeclType.Kind != DeclaratorChunk::Paren) {
5733 if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
5734 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5736 ExpectNoDerefChunk = state.didParseNoDeref();
5740 if (ExpectNoDerefChunk)
5741 S.Diag(state.getDeclarator().getBeginLoc(),
5742 diag::warn_noderef_on_non_pointer_or_array);
5744 // GNU warning -Wstrict-prototypes
5745 // Warn if a function declaration or definition is without a prototype.
5746 // This warning is issued for all kinds of unprototyped function
5747 // declarations (i.e. function type typedef, function pointer etc.)
5748 // C99 6.7.5.3p14:
5749 // The empty list in a function declarator that is not part of a definition
5750 // of that function specifies that no information about the number or types
5751 // of the parameters is supplied.
5752 // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of
5753 // function declarations whose behavior changes in C23.
5754 if (!LangOpts.requiresStrictPrototypes()) {
5755 bool IsBlock = false;
5756 for (const DeclaratorChunk &DeclType : D.type_objects()) {
5757 switch (DeclType.Kind) {
5758 case DeclaratorChunk::BlockPointer:
5759 IsBlock = true;
5760 break;
5761 case DeclaratorChunk::Function: {
5762 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5763 // We suppress the warning when there's no LParen location, as this
5764 // indicates the declaration was an implicit declaration, which gets
5765 // warned about separately via -Wimplicit-function-declaration. We also
5766 // suppress the warning when we know the function has a prototype.
5767 if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic &&
5768 FTI.getLParenLoc().isValid())
5769 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5770 << IsBlock
5771 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5772 IsBlock = false;
5773 break;
5775 default:
5776 break;
5781 assert(!T.isNull() && "T must not be null after this point");
5783 if (LangOpts.CPlusPlus && T->isFunctionType()) {
5784 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5785 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
5787 // C++ 8.3.5p4:
5788 // A cv-qualifier-seq shall only be part of the function type
5789 // for a nonstatic member function, the function type to which a pointer
5790 // to member refers, or the top-level function type of a function typedef
5791 // declaration.
5793 // Core issue 547 also allows cv-qualifiers on function types that are
5794 // top-level template type arguments.
5795 enum { NonMember, Member, DeductionGuide } Kind = NonMember;
5796 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
5797 Kind = DeductionGuide;
5798 else if (!D.getCXXScopeSpec().isSet()) {
5799 if ((D.getContext() == DeclaratorContext::Member ||
5800 D.getContext() == DeclaratorContext::LambdaExpr) &&
5801 !D.getDeclSpec().isFriendSpecified())
5802 Kind = Member;
5803 } else {
5804 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
5805 if (!DC || DC->isRecord())
5806 Kind = Member;
5809 // C++11 [dcl.fct]p6 (w/DR1417):
5810 // An attempt to specify a function type with a cv-qualifier-seq or a
5811 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5812 // - the function type for a non-static member function,
5813 // - the function type to which a pointer to member refers,
5814 // - the top-level function type of a function typedef declaration or
5815 // alias-declaration,
5816 // - the type-id in the default argument of a type-parameter, or
5817 // - the type-id of a template-argument for a type-parameter
5819 // FIXME: Checking this here is insufficient. We accept-invalid on:
5821 // template<typename T> struct S { void f(T); };
5822 // S<int() const> s;
5824 // ... for instance.
5825 if (IsQualifiedFunction &&
5826 !(Kind == Member &&
5827 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
5828 !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg &&
5829 D.getContext() != DeclaratorContext::TemplateTypeArg) {
5830 SourceLocation Loc = D.getBeginLoc();
5831 SourceRange RemovalRange;
5832 unsigned I;
5833 if (D.isFunctionDeclarator(I)) {
5834 SmallVector<SourceLocation, 4> RemovalLocs;
5835 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5836 assert(Chunk.Kind == DeclaratorChunk::Function);
5838 if (Chunk.Fun.hasRefQualifier())
5839 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5841 if (Chunk.Fun.hasMethodTypeQualifiers())
5842 Chunk.Fun.MethodQualifiers->forEachQualifier(
5843 [&](DeclSpec::TQ TypeQual, StringRef QualName,
5844 SourceLocation SL) { RemovalLocs.push_back(SL); });
5846 if (!RemovalLocs.empty()) {
5847 llvm::sort(RemovalLocs,
5848 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
5849 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5850 Loc = RemovalLocs.front();
5854 S.Diag(Loc, diag::err_invalid_qualified_function_type)
5855 << Kind << D.isFunctionDeclarator() << T
5856 << getFunctionQualifiersAsString(FnTy)
5857 << FixItHint::CreateRemoval(RemovalRange);
5859 // Strip the cv-qualifiers and ref-qualifiers from the type.
5860 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
5861 EPI.TypeQuals.removeCVRQualifiers();
5862 EPI.RefQualifier = RQ_None;
5864 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5865 EPI);
5866 // Rebuild any parens around the identifier in the function type.
5867 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5868 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
5869 break;
5870 T = S.BuildParenType(T);
5875 // Apply any undistributed attributes from the declaration or declarator.
5876 ParsedAttributesView NonSlidingAttrs;
5877 for (ParsedAttr &AL : D.getDeclarationAttributes()) {
5878 if (!AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
5879 NonSlidingAttrs.addAtEnd(&AL);
5882 processTypeAttrs(state, T, TAL_DeclName, NonSlidingAttrs);
5883 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
5885 // Diagnose any ignored type attributes.
5886 state.diagnoseIgnoredTypeAttrs(T);
5888 // C++0x [dcl.constexpr]p9:
5889 // A constexpr specifier used in an object declaration declares the object
5890 // as const.
5891 if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr &&
5892 T->isObjectType())
5893 T.addConst();
5895 // C++2a [dcl.fct]p4:
5896 // A parameter with volatile-qualified type is deprecated
5897 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 &&
5898 (D.getContext() == DeclaratorContext::Prototype ||
5899 D.getContext() == DeclaratorContext::LambdaExprParameter))
5900 S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T;
5902 // If there was an ellipsis in the declarator, the declaration declares a
5903 // parameter pack whose type may be a pack expansion type.
5904 if (D.hasEllipsis()) {
5905 // C++0x [dcl.fct]p13:
5906 // A declarator-id or abstract-declarator containing an ellipsis shall
5907 // only be used in a parameter-declaration. Such a parameter-declaration
5908 // is a parameter pack (14.5.3). [...]
5909 switch (D.getContext()) {
5910 case DeclaratorContext::Prototype:
5911 case DeclaratorContext::LambdaExprParameter:
5912 case DeclaratorContext::RequiresExpr:
5913 // C++0x [dcl.fct]p13:
5914 // [...] When it is part of a parameter-declaration-clause, the
5915 // parameter pack is a function parameter pack (14.5.3). The type T
5916 // of the declarator-id of the function parameter pack shall contain
5917 // a template parameter pack; each template parameter pack in T is
5918 // expanded by the function parameter pack.
5920 // We represent function parameter packs as function parameters whose
5921 // type is a pack expansion.
5922 if (!T->containsUnexpandedParameterPack() &&
5923 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) {
5924 S.Diag(D.getEllipsisLoc(),
5925 diag::err_function_parameter_pack_without_parameter_packs)
5926 << T << D.getSourceRange();
5927 D.setEllipsisLoc(SourceLocation());
5928 } else {
5929 T = Context.getPackExpansionType(T, std::nullopt,
5930 /*ExpectPackInType=*/false);
5932 break;
5933 case DeclaratorContext::TemplateParam:
5934 // C++0x [temp.param]p15:
5935 // If a template-parameter is a [...] is a parameter-declaration that
5936 // declares a parameter pack (8.3.5), then the template-parameter is a
5937 // template parameter pack (14.5.3).
5939 // Note: core issue 778 clarifies that, if there are any unexpanded
5940 // parameter packs in the type of the non-type template parameter, then
5941 // it expands those parameter packs.
5942 if (T->containsUnexpandedParameterPack())
5943 T = Context.getPackExpansionType(T, std::nullopt);
5944 else
5945 S.Diag(D.getEllipsisLoc(),
5946 LangOpts.CPlusPlus11
5947 ? diag::warn_cxx98_compat_variadic_templates
5948 : diag::ext_variadic_templates);
5949 break;
5951 case DeclaratorContext::File:
5952 case DeclaratorContext::KNRTypeList:
5953 case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here?
5954 case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here?
5955 case DeclaratorContext::TypeName:
5956 case DeclaratorContext::FunctionalCast:
5957 case DeclaratorContext::CXXNew:
5958 case DeclaratorContext::AliasDecl:
5959 case DeclaratorContext::AliasTemplate:
5960 case DeclaratorContext::Member:
5961 case DeclaratorContext::Block:
5962 case DeclaratorContext::ForInit:
5963 case DeclaratorContext::SelectionInit:
5964 case DeclaratorContext::Condition:
5965 case DeclaratorContext::CXXCatch:
5966 case DeclaratorContext::ObjCCatch:
5967 case DeclaratorContext::BlockLiteral:
5968 case DeclaratorContext::LambdaExpr:
5969 case DeclaratorContext::ConversionId:
5970 case DeclaratorContext::TrailingReturn:
5971 case DeclaratorContext::TrailingReturnVar:
5972 case DeclaratorContext::TemplateArg:
5973 case DeclaratorContext::TemplateTypeArg:
5974 case DeclaratorContext::Association:
5975 // FIXME: We may want to allow parameter packs in block-literal contexts
5976 // in the future.
5977 S.Diag(D.getEllipsisLoc(),
5978 diag::err_ellipsis_in_declarator_not_parameter);
5979 D.setEllipsisLoc(SourceLocation());
5980 break;
5984 assert(!T.isNull() && "T must not be null at the end of this function");
5985 if (!AreDeclaratorChunksValid)
5986 return Context.getTrivialTypeSourceInfo(T);
5987 return GetTypeSourceInfoForDeclarator(state, T, TInfo);
5990 /// GetTypeForDeclarator - Convert the type for the specified
5991 /// declarator to Type instances.
5993 /// The result of this call will never be null, but the associated
5994 /// type may be a null type if there's an unrecoverable error.
5995 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
5996 // Determine the type of the declarator. Not all forms of declarator
5997 // have a type.
5999 TypeProcessingState state(*this, D);
6001 TypeSourceInfo *ReturnTypeInfo = nullptr;
6002 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
6003 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
6004 inferARCWriteback(state, T);
6006 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
6009 static void transferARCOwnershipToDeclSpec(Sema &S,
6010 QualType &declSpecTy,
6011 Qualifiers::ObjCLifetime ownership) {
6012 if (declSpecTy->isObjCRetainableType() &&
6013 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
6014 Qualifiers qs;
6015 qs.addObjCLifetime(ownership);
6016 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
6020 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
6021 Qualifiers::ObjCLifetime ownership,
6022 unsigned chunkIndex) {
6023 Sema &S = state.getSema();
6024 Declarator &D = state.getDeclarator();
6026 // Look for an explicit lifetime attribute.
6027 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
6028 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
6029 return;
6031 const char *attrStr = nullptr;
6032 switch (ownership) {
6033 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
6034 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
6035 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
6036 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
6037 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
6040 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
6041 Arg->Ident = &S.Context.Idents.get(attrStr);
6042 Arg->Loc = SourceLocation();
6044 ArgsUnion Args(Arg);
6046 // If there wasn't one, add one (with an invalid source location
6047 // so that we don't make an AttributedType for it).
6048 ParsedAttr *attr = D.getAttributePool().create(
6049 &S.Context.Idents.get("objc_ownership"), SourceLocation(),
6050 /*scope*/ nullptr, SourceLocation(),
6051 /*args*/ &Args, 1, ParsedAttr::Form::GNU());
6052 chunk.getAttrs().addAtEnd(attr);
6053 // TODO: mark whether we did this inference?
6056 /// Used for transferring ownership in casts resulting in l-values.
6057 static void transferARCOwnership(TypeProcessingState &state,
6058 QualType &declSpecTy,
6059 Qualifiers::ObjCLifetime ownership) {
6060 Sema &S = state.getSema();
6061 Declarator &D = state.getDeclarator();
6063 int inner = -1;
6064 bool hasIndirection = false;
6065 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6066 DeclaratorChunk &chunk = D.getTypeObject(i);
6067 switch (chunk.Kind) {
6068 case DeclaratorChunk::Paren:
6069 // Ignore parens.
6070 break;
6072 case DeclaratorChunk::Array:
6073 case DeclaratorChunk::Reference:
6074 case DeclaratorChunk::Pointer:
6075 if (inner != -1)
6076 hasIndirection = true;
6077 inner = i;
6078 break;
6080 case DeclaratorChunk::BlockPointer:
6081 if (inner != -1)
6082 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
6083 return;
6085 case DeclaratorChunk::Function:
6086 case DeclaratorChunk::MemberPointer:
6087 case DeclaratorChunk::Pipe:
6088 return;
6092 if (inner == -1)
6093 return;
6095 DeclaratorChunk &chunk = D.getTypeObject(inner);
6096 if (chunk.Kind == DeclaratorChunk::Pointer) {
6097 if (declSpecTy->isObjCRetainableType())
6098 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
6099 if (declSpecTy->isObjCObjectType() && hasIndirection)
6100 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
6101 } else {
6102 assert(chunk.Kind == DeclaratorChunk::Array ||
6103 chunk.Kind == DeclaratorChunk::Reference);
6104 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
6108 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
6109 TypeProcessingState state(*this, D);
6111 TypeSourceInfo *ReturnTypeInfo = nullptr;
6112 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
6114 if (getLangOpts().ObjC) {
6115 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
6116 if (ownership != Qualifiers::OCL_None)
6117 transferARCOwnership(state, declSpecTy, ownership);
6120 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
6123 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
6124 TypeProcessingState &State) {
6125 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
6128 static void fillMatrixTypeLoc(MatrixTypeLoc MTL,
6129 const ParsedAttributesView &Attrs) {
6130 for (const ParsedAttr &AL : Attrs) {
6131 if (AL.getKind() == ParsedAttr::AT_MatrixType) {
6132 MTL.setAttrNameLoc(AL.getLoc());
6133 MTL.setAttrRowOperand(AL.getArgAsExpr(0));
6134 MTL.setAttrColumnOperand(AL.getArgAsExpr(1));
6135 MTL.setAttrOperandParensRange(SourceRange());
6136 return;
6140 llvm_unreachable("no matrix_type attribute found at the expected location!");
6143 namespace {
6144 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
6145 Sema &SemaRef;
6146 ASTContext &Context;
6147 TypeProcessingState &State;
6148 const DeclSpec &DS;
6150 public:
6151 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
6152 const DeclSpec &DS)
6153 : SemaRef(S), Context(Context), State(State), DS(DS) {}
6155 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6156 Visit(TL.getModifiedLoc());
6157 fillAttributedTypeLoc(TL, State);
6159 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6160 Visit(TL.getWrappedLoc());
6162 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6163 Visit(TL.getInnerLoc());
6164 TL.setExpansionLoc(
6165 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6167 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6168 Visit(TL.getUnqualifiedLoc());
6170 // Allow to fill pointee's type locations, e.g.,
6171 // int __attr * __attr * __attr *p;
6172 void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); }
6173 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6174 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6176 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6177 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6178 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
6179 // addition field. What we have is good enough for display of location
6180 // of 'fixit' on interface name.
6181 TL.setNameEndLoc(DS.getEndLoc());
6183 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6184 TypeSourceInfo *RepTInfo = nullptr;
6185 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6186 TL.copy(RepTInfo->getTypeLoc());
6188 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6189 TypeSourceInfo *RepTInfo = nullptr;
6190 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6191 TL.copy(RepTInfo->getTypeLoc());
6193 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
6194 TypeSourceInfo *TInfo = nullptr;
6195 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6197 // If we got no declarator info from previous Sema routines,
6198 // just fill with the typespec loc.
6199 if (!TInfo) {
6200 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
6201 return;
6204 TypeLoc OldTL = TInfo->getTypeLoc();
6205 if (TInfo->getType()->getAs<ElaboratedType>()) {
6206 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
6207 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
6208 .castAs<TemplateSpecializationTypeLoc>();
6209 TL.copy(NamedTL);
6210 } else {
6211 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
6212 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
6216 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6217 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
6218 DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualExpr);
6219 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
6220 TL.setParensRange(DS.getTypeofParensRange());
6222 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6223 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
6224 DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType);
6225 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
6226 TL.setParensRange(DS.getTypeofParensRange());
6227 assert(DS.getRepAsType());
6228 TypeSourceInfo *TInfo = nullptr;
6229 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6230 TL.setUnmodifiedTInfo(TInfo);
6232 void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6233 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
6234 TL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
6235 TL.setRParenLoc(DS.getTypeofParensRange().getEnd());
6237 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6238 assert(DS.isTransformTypeTrait(DS.getTypeSpecType()));
6239 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6240 TL.setParensRange(DS.getTypeofParensRange());
6241 assert(DS.getRepAsType());
6242 TypeSourceInfo *TInfo = nullptr;
6243 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6244 TL.setUnderlyingTInfo(TInfo);
6246 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6247 // By default, use the source location of the type specifier.
6248 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
6249 if (TL.needsExtraLocalData()) {
6250 // Set info for the written builtin specifiers.
6251 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
6252 // Try to have a meaningful source location.
6253 if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified)
6254 TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
6255 if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified)
6256 TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
6259 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6260 if (DS.getTypeSpecType() == TST_typename) {
6261 TypeSourceInfo *TInfo = nullptr;
6262 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6263 if (TInfo)
6264 if (auto ETL = TInfo->getTypeLoc().getAs<ElaboratedTypeLoc>()) {
6265 TL.copy(ETL);
6266 return;
6269 const ElaboratedType *T = TL.getTypePtr();
6270 TL.setElaboratedKeywordLoc(T->getKeyword() != ETK_None
6271 ? DS.getTypeSpecTypeLoc()
6272 : SourceLocation());
6273 const CXXScopeSpec& SS = DS.getTypeSpecScope();
6274 TL.setQualifierLoc(SS.getWithLocInContext(Context));
6275 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
6277 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6278 assert(DS.getTypeSpecType() == TST_typename);
6279 TypeSourceInfo *TInfo = nullptr;
6280 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6281 assert(TInfo);
6282 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
6284 void VisitDependentTemplateSpecializationTypeLoc(
6285 DependentTemplateSpecializationTypeLoc TL) {
6286 assert(DS.getTypeSpecType() == TST_typename);
6287 TypeSourceInfo *TInfo = nullptr;
6288 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6289 assert(TInfo);
6290 TL.copy(
6291 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
6293 void VisitAutoTypeLoc(AutoTypeLoc TL) {
6294 assert(DS.getTypeSpecType() == TST_auto ||
6295 DS.getTypeSpecType() == TST_decltype_auto ||
6296 DS.getTypeSpecType() == TST_auto_type ||
6297 DS.getTypeSpecType() == TST_unspecified);
6298 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6299 if (DS.getTypeSpecType() == TST_decltype_auto)
6300 TL.setRParenLoc(DS.getTypeofParensRange().getEnd());
6301 if (!DS.isConstrainedAuto())
6302 return;
6303 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
6304 if (!TemplateId)
6305 return;
6306 if (DS.getTypeSpecScope().isNotEmpty())
6307 TL.setNestedNameSpecifierLoc(
6308 DS.getTypeSpecScope().getWithLocInContext(Context));
6309 else
6310 TL.setNestedNameSpecifierLoc(NestedNameSpecifierLoc());
6311 TL.setTemplateKWLoc(TemplateId->TemplateKWLoc);
6312 TL.setConceptNameLoc(TemplateId->TemplateNameLoc);
6313 TL.setFoundDecl(nullptr);
6314 TL.setLAngleLoc(TemplateId->LAngleLoc);
6315 TL.setRAngleLoc(TemplateId->RAngleLoc);
6316 if (TemplateId->NumArgs == 0)
6317 return;
6318 TemplateArgumentListInfo TemplateArgsInfo;
6319 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6320 TemplateId->NumArgs);
6321 SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
6322 for (unsigned I = 0; I < TemplateId->NumArgs; ++I)
6323 TL.setArgLocInfo(I, TemplateArgsInfo.arguments()[I].getLocInfo());
6325 void VisitTagTypeLoc(TagTypeLoc TL) {
6326 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
6328 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6329 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
6330 // or an _Atomic qualifier.
6331 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
6332 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6333 TL.setParensRange(DS.getTypeofParensRange());
6335 TypeSourceInfo *TInfo = nullptr;
6336 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6337 assert(TInfo);
6338 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
6339 } else {
6340 TL.setKWLoc(DS.getAtomicSpecLoc());
6341 // No parens, to indicate this was spelled as an _Atomic qualifier.
6342 TL.setParensRange(SourceRange());
6343 Visit(TL.getValueLoc());
6347 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6348 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6350 TypeSourceInfo *TInfo = nullptr;
6351 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6352 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
6355 void VisitExtIntTypeLoc(BitIntTypeLoc TL) {
6356 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6359 void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) {
6360 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6363 void VisitTypeLoc(TypeLoc TL) {
6364 // FIXME: add other typespec types and change this to an assert.
6365 TL.initialize(Context, DS.getTypeSpecTypeLoc());
6369 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
6370 ASTContext &Context;
6371 TypeProcessingState &State;
6372 const DeclaratorChunk &Chunk;
6374 public:
6375 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
6376 const DeclaratorChunk &Chunk)
6377 : Context(Context), State(State), Chunk(Chunk) {}
6379 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6380 llvm_unreachable("qualified type locs not expected here!");
6382 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6383 llvm_unreachable("decayed type locs not expected here!");
6386 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6387 fillAttributedTypeLoc(TL, State);
6389 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6390 // nothing
6392 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6393 // nothing
6395 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6396 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
6397 TL.setCaretLoc(Chunk.Loc);
6399 void VisitPointerTypeLoc(PointerTypeLoc TL) {
6400 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6401 TL.setStarLoc(Chunk.Loc);
6403 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6404 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6405 TL.setStarLoc(Chunk.Loc);
6407 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6408 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
6409 const CXXScopeSpec& SS = Chunk.Mem.Scope();
6410 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
6412 const Type* ClsTy = TL.getClass();
6413 QualType ClsQT = QualType(ClsTy, 0);
6414 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
6415 // Now copy source location info into the type loc component.
6416 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
6417 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
6418 case NestedNameSpecifier::Identifier:
6419 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
6421 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
6422 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
6423 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
6424 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
6426 break;
6428 case NestedNameSpecifier::TypeSpec:
6429 case NestedNameSpecifier::TypeSpecWithTemplate:
6430 if (isa<ElaboratedType>(ClsTy)) {
6431 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
6432 ETLoc.setElaboratedKeywordLoc(SourceLocation());
6433 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
6434 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
6435 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
6436 } else {
6437 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
6439 break;
6441 case NestedNameSpecifier::Namespace:
6442 case NestedNameSpecifier::NamespaceAlias:
6443 case NestedNameSpecifier::Global:
6444 case NestedNameSpecifier::Super:
6445 llvm_unreachable("Nested-name-specifier must name a type");
6448 // Finally fill in MemberPointerLocInfo fields.
6449 TL.setStarLoc(Chunk.Mem.StarLoc);
6450 TL.setClassTInfo(ClsTInfo);
6452 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6453 assert(Chunk.Kind == DeclaratorChunk::Reference);
6454 // 'Amp' is misleading: this might have been originally
6455 /// spelled with AmpAmp.
6456 TL.setAmpLoc(Chunk.Loc);
6458 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6459 assert(Chunk.Kind == DeclaratorChunk::Reference);
6460 assert(!Chunk.Ref.LValueRef);
6461 TL.setAmpAmpLoc(Chunk.Loc);
6463 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
6464 assert(Chunk.Kind == DeclaratorChunk::Array);
6465 TL.setLBracketLoc(Chunk.Loc);
6466 TL.setRBracketLoc(Chunk.EndLoc);
6467 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
6469 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6470 assert(Chunk.Kind == DeclaratorChunk::Function);
6471 TL.setLocalRangeBegin(Chunk.Loc);
6472 TL.setLocalRangeEnd(Chunk.EndLoc);
6474 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
6475 TL.setLParenLoc(FTI.getLParenLoc());
6476 TL.setRParenLoc(FTI.getRParenLoc());
6477 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
6478 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
6479 TL.setParam(tpi++, Param);
6481 TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
6483 void VisitParenTypeLoc(ParenTypeLoc TL) {
6484 assert(Chunk.Kind == DeclaratorChunk::Paren);
6485 TL.setLParenLoc(Chunk.Loc);
6486 TL.setRParenLoc(Chunk.EndLoc);
6488 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6489 assert(Chunk.Kind == DeclaratorChunk::Pipe);
6490 TL.setKWLoc(Chunk.Loc);
6492 void VisitBitIntTypeLoc(BitIntTypeLoc TL) {
6493 TL.setNameLoc(Chunk.Loc);
6495 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6496 TL.setExpansionLoc(Chunk.Loc);
6498 void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); }
6499 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) {
6500 TL.setNameLoc(Chunk.Loc);
6502 void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6503 TL.setNameLoc(Chunk.Loc);
6505 void
6506 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) {
6507 TL.setNameLoc(Chunk.Loc);
6509 void VisitMatrixTypeLoc(MatrixTypeLoc TL) {
6510 fillMatrixTypeLoc(TL, Chunk.getAttrs());
6513 void VisitTypeLoc(TypeLoc TL) {
6514 llvm_unreachable("unsupported TypeLoc kind in declarator!");
6517 } // end anonymous namespace
6519 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
6520 SourceLocation Loc;
6521 switch (Chunk.Kind) {
6522 case DeclaratorChunk::Function:
6523 case DeclaratorChunk::Array:
6524 case DeclaratorChunk::Paren:
6525 case DeclaratorChunk::Pipe:
6526 llvm_unreachable("cannot be _Atomic qualified");
6528 case DeclaratorChunk::Pointer:
6529 Loc = Chunk.Ptr.AtomicQualLoc;
6530 break;
6532 case DeclaratorChunk::BlockPointer:
6533 case DeclaratorChunk::Reference:
6534 case DeclaratorChunk::MemberPointer:
6535 // FIXME: Provide a source location for the _Atomic keyword.
6536 break;
6539 ATL.setKWLoc(Loc);
6540 ATL.setParensRange(SourceRange());
6543 static void
6544 fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL,
6545 const ParsedAttributesView &Attrs) {
6546 for (const ParsedAttr &AL : Attrs) {
6547 if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
6548 DASTL.setAttrNameLoc(AL.getLoc());
6549 DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
6550 DASTL.setAttrOperandParensRange(SourceRange());
6551 return;
6555 llvm_unreachable(
6556 "no address_space attribute found at the expected location!");
6559 /// Create and instantiate a TypeSourceInfo with type source information.
6561 /// \param T QualType referring to the type as written in source code.
6563 /// \param ReturnTypeInfo For declarators whose return type does not show
6564 /// up in the normal place in the declaration specifiers (such as a C++
6565 /// conversion function), this pointer will refer to a type source information
6566 /// for that return type.
6567 static TypeSourceInfo *
6568 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
6569 QualType T, TypeSourceInfo *ReturnTypeInfo) {
6570 Sema &S = State.getSema();
6571 Declarator &D = State.getDeclarator();
6573 TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T);
6574 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
6576 // Handle parameter packs whose type is a pack expansion.
6577 if (isa<PackExpansionType>(T)) {
6578 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
6579 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6582 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6583 // Microsoft property fields can have multiple sizeless array chunks
6584 // (i.e. int x[][][]). Don't create more than one level of incomplete array.
6585 if (CurrTL.getTypeLocClass() == TypeLoc::IncompleteArray && e != 1 &&
6586 D.getDeclSpec().getAttributes().hasMSPropertyAttr())
6587 continue;
6589 // An AtomicTypeLoc might be produced by an atomic qualifier in this
6590 // declarator chunk.
6591 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
6592 fillAtomicQualLoc(ATL, D.getTypeObject(i));
6593 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
6596 bool HasDesugaredTypeLoc = true;
6597 while (HasDesugaredTypeLoc) {
6598 switch (CurrTL.getTypeLocClass()) {
6599 case TypeLoc::MacroQualified: {
6600 auto TL = CurrTL.castAs<MacroQualifiedTypeLoc>();
6601 TL.setExpansionLoc(
6602 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6603 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6604 break;
6607 case TypeLoc::Attributed: {
6608 auto TL = CurrTL.castAs<AttributedTypeLoc>();
6609 fillAttributedTypeLoc(TL, State);
6610 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6611 break;
6614 case TypeLoc::Adjusted:
6615 case TypeLoc::BTFTagAttributed: {
6616 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6617 break;
6620 case TypeLoc::DependentAddressSpace: {
6621 auto TL = CurrTL.castAs<DependentAddressSpaceTypeLoc>();
6622 fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs());
6623 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
6624 break;
6627 default:
6628 HasDesugaredTypeLoc = false;
6629 break;
6633 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
6634 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6637 // If we have different source information for the return type, use
6638 // that. This really only applies to C++ conversion functions.
6639 if (ReturnTypeInfo) {
6640 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
6641 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
6642 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
6643 } else {
6644 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL);
6647 return TInfo;
6650 /// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
6651 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
6652 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6653 // and Sema during declaration parsing. Try deallocating/caching them when
6654 // it's appropriate, instead of allocating them and keeping them around.
6655 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
6656 TypeAlignment);
6657 new (LocT) LocInfoType(T, TInfo);
6658 assert(LocT->getTypeClass() != T->getTypeClass() &&
6659 "LocInfoType's TypeClass conflicts with an existing Type class");
6660 return ParsedType::make(QualType(LocT, 0));
6663 void LocInfoType::getAsStringInternal(std::string &Str,
6664 const PrintingPolicy &Policy) const {
6665 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6666 " was used directly instead of getting the QualType through"
6667 " GetTypeFromParser");
6670 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
6671 // C99 6.7.6: Type names have no identifier. This is already validated by
6672 // the parser.
6673 assert(D.getIdentifier() == nullptr &&
6674 "Type name should have no identifier!");
6676 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6677 QualType T = TInfo->getType();
6678 if (D.isInvalidType())
6679 return true;
6681 // Make sure there are no unused decl attributes on the declarator.
6682 // We don't want to do this for ObjC parameters because we're going
6683 // to apply them to the actual parameter declaration.
6684 // Likewise, we don't want to do this for alias declarations, because
6685 // we are actually going to build a declaration from this eventually.
6686 if (D.getContext() != DeclaratorContext::ObjCParameter &&
6687 D.getContext() != DeclaratorContext::AliasDecl &&
6688 D.getContext() != DeclaratorContext::AliasTemplate)
6689 checkUnusedDeclAttributes(D);
6691 if (getLangOpts().CPlusPlus) {
6692 // Check that there are no default arguments (C++ only).
6693 CheckExtraCXXDefaultArguments(D);
6696 return CreateParsedType(T, TInfo);
6699 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
6700 QualType T = Context.getObjCInstanceType();
6701 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
6702 return CreateParsedType(T, TInfo);
6705 //===----------------------------------------------------------------------===//
6706 // Type Attribute Processing
6707 //===----------------------------------------------------------------------===//
6709 /// Build an AddressSpace index from a constant expression and diagnose any
6710 /// errors related to invalid address_spaces. Returns true on successfully
6711 /// building an AddressSpace index.
6712 static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
6713 const Expr *AddrSpace,
6714 SourceLocation AttrLoc) {
6715 if (!AddrSpace->isValueDependent()) {
6716 std::optional<llvm::APSInt> OptAddrSpace =
6717 AddrSpace->getIntegerConstantExpr(S.Context);
6718 if (!OptAddrSpace) {
6719 S.Diag(AttrLoc, diag::err_attribute_argument_type)
6720 << "'address_space'" << AANT_ArgumentIntegerConstant
6721 << AddrSpace->getSourceRange();
6722 return false;
6724 llvm::APSInt &addrSpace = *OptAddrSpace;
6726 // Bounds checking.
6727 if (addrSpace.isSigned()) {
6728 if (addrSpace.isNegative()) {
6729 S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
6730 << AddrSpace->getSourceRange();
6731 return false;
6733 addrSpace.setIsSigned(false);
6736 llvm::APSInt max(addrSpace.getBitWidth());
6737 max =
6738 Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace;
6740 if (addrSpace > max) {
6741 S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
6742 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
6743 return false;
6746 ASIdx =
6747 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
6748 return true;
6751 // Default value for DependentAddressSpaceTypes
6752 ASIdx = LangAS::Default;
6753 return true;
6756 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression
6757 /// is uninstantiated. If instantiated it will apply the appropriate address
6758 /// space to the type. This function allows dependent template variables to be
6759 /// used in conjunction with the address_space attribute
6760 QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
6761 SourceLocation AttrLoc) {
6762 if (!AddrSpace->isValueDependent()) {
6763 if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
6764 AttrLoc))
6765 return QualType();
6767 return Context.getAddrSpaceQualType(T, ASIdx);
6770 // A check with similar intentions as checking if a type already has an
6771 // address space except for on a dependent types, basically if the
6772 // current type is already a DependentAddressSpaceType then its already
6773 // lined up to have another address space on it and we can't have
6774 // multiple address spaces on the one pointer indirection
6775 if (T->getAs<DependentAddressSpaceType>()) {
6776 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
6777 return QualType();
6780 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
6783 QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
6784 SourceLocation AttrLoc) {
6785 LangAS ASIdx;
6786 if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
6787 return QualType();
6788 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
6791 static void HandleBTFTypeTagAttribute(QualType &Type, const ParsedAttr &Attr,
6792 TypeProcessingState &State) {
6793 Sema &S = State.getSema();
6795 // Check the number of attribute arguments.
6796 if (Attr.getNumArgs() != 1) {
6797 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6798 << Attr << 1;
6799 Attr.setInvalid();
6800 return;
6803 // Ensure the argument is a string.
6804 auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6805 if (!StrLiteral) {
6806 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6807 << Attr << AANT_ArgumentString;
6808 Attr.setInvalid();
6809 return;
6812 ASTContext &Ctx = S.Context;
6813 StringRef BTFTypeTag = StrLiteral->getString();
6814 Type = State.getBTFTagAttributedType(
6815 ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type);
6818 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6819 /// specified type. The attribute contains 1 argument, the id of the address
6820 /// space for the type.
6821 static void HandleAddressSpaceTypeAttribute(QualType &Type,
6822 const ParsedAttr &Attr,
6823 TypeProcessingState &State) {
6824 Sema &S = State.getSema();
6826 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6827 // qualified by an address-space qualifier."
6828 if (Type->isFunctionType()) {
6829 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
6830 Attr.setInvalid();
6831 return;
6834 LangAS ASIdx;
6835 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
6837 // Check the attribute arguments.
6838 if (Attr.getNumArgs() != 1) {
6839 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
6840 << 1;
6841 Attr.setInvalid();
6842 return;
6845 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6846 LangAS ASIdx;
6847 if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
6848 Attr.setInvalid();
6849 return;
6852 ASTContext &Ctx = S.Context;
6853 auto *ASAttr =
6854 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
6856 // If the expression is not value dependent (not templated), then we can
6857 // apply the address space qualifiers just to the equivalent type.
6858 // Otherwise, we make an AttributedType with the modified and equivalent
6859 // type the same, and wrap it in a DependentAddressSpaceType. When this
6860 // dependent type is resolved, the qualifier is added to the equivalent type
6861 // later.
6862 QualType T;
6863 if (!ASArgExpr->isValueDependent()) {
6864 QualType EquivType =
6865 S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
6866 if (EquivType.isNull()) {
6867 Attr.setInvalid();
6868 return;
6870 T = State.getAttributedType(ASAttr, Type, EquivType);
6871 } else {
6872 T = State.getAttributedType(ASAttr, Type, Type);
6873 T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
6876 if (!T.isNull())
6877 Type = T;
6878 else
6879 Attr.setInvalid();
6880 } else {
6881 // The keyword-based type attributes imply which address space to use.
6882 ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS()
6883 : Attr.asOpenCLLangAS();
6884 if (S.getLangOpts().HLSL)
6885 ASIdx = Attr.asHLSLLangAS();
6887 if (ASIdx == LangAS::Default)
6888 llvm_unreachable("Invalid address space");
6890 if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
6891 Attr.getLoc())) {
6892 Attr.setInvalid();
6893 return;
6896 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
6900 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
6901 /// attribute on the specified type.
6903 /// Returns 'true' if the attribute was handled.
6904 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6905 ParsedAttr &attr, QualType &type) {
6906 bool NonObjCPointer = false;
6908 if (!type->isDependentType() && !type->isUndeducedType()) {
6909 if (const PointerType *ptr = type->getAs<PointerType>()) {
6910 QualType pointee = ptr->getPointeeType();
6911 if (pointee->isObjCRetainableType() || pointee->isPointerType())
6912 return false;
6913 // It is important not to lose the source info that there was an attribute
6914 // applied to non-objc pointer. We will create an attributed type but
6915 // its type will be the same as the original type.
6916 NonObjCPointer = true;
6917 } else if (!type->isObjCRetainableType()) {
6918 return false;
6921 // Don't accept an ownership attribute in the declspec if it would
6922 // just be the return type of a block pointer.
6923 if (state.isProcessingDeclSpec()) {
6924 Declarator &D = state.getDeclarator();
6925 if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
6926 /*onlyBlockPointers=*/true))
6927 return false;
6931 Sema &S = state.getSema();
6932 SourceLocation AttrLoc = attr.getLoc();
6933 if (AttrLoc.isMacroID())
6934 AttrLoc =
6935 S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin();
6937 if (!attr.isArgIdent(0)) {
6938 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
6939 << AANT_ArgumentString;
6940 attr.setInvalid();
6941 return true;
6944 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
6945 Qualifiers::ObjCLifetime lifetime;
6946 if (II->isStr("none"))
6947 lifetime = Qualifiers::OCL_ExplicitNone;
6948 else if (II->isStr("strong"))
6949 lifetime = Qualifiers::OCL_Strong;
6950 else if (II->isStr("weak"))
6951 lifetime = Qualifiers::OCL_Weak;
6952 else if (II->isStr("autoreleasing"))
6953 lifetime = Qualifiers::OCL_Autoreleasing;
6954 else {
6955 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II;
6956 attr.setInvalid();
6957 return true;
6960 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6961 // outside of ARC mode.
6962 if (!S.getLangOpts().ObjCAutoRefCount &&
6963 lifetime != Qualifiers::OCL_Weak &&
6964 lifetime != Qualifiers::OCL_ExplicitNone) {
6965 return true;
6968 SplitQualType underlyingType = type.split();
6970 // Check for redundant/conflicting ownership qualifiers.
6971 if (Qualifiers::ObjCLifetime previousLifetime
6972 = type.getQualifiers().getObjCLifetime()) {
6973 // If it's written directly, that's an error.
6974 if (S.Context.hasDirectOwnershipQualifier(type)) {
6975 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
6976 << type;
6977 return true;
6980 // Otherwise, if the qualifiers actually conflict, pull sugar off
6981 // and remove the ObjCLifetime qualifiers.
6982 if (previousLifetime != lifetime) {
6983 // It's possible to have multiple local ObjCLifetime qualifiers. We
6984 // can't stop after we reach a type that is directly qualified.
6985 const Type *prevTy = nullptr;
6986 while (!prevTy || prevTy != underlyingType.Ty) {
6987 prevTy = underlyingType.Ty;
6988 underlyingType = underlyingType.getSingleStepDesugaredType();
6990 underlyingType.Quals.removeObjCLifetime();
6994 underlyingType.Quals.addObjCLifetime(lifetime);
6996 if (NonObjCPointer) {
6997 StringRef name = attr.getAttrName()->getName();
6998 switch (lifetime) {
6999 case Qualifiers::OCL_None:
7000 case Qualifiers::OCL_ExplicitNone:
7001 break;
7002 case Qualifiers::OCL_Strong: name = "__strong"; break;
7003 case Qualifiers::OCL_Weak: name = "__weak"; break;
7004 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
7006 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
7007 << TDS_ObjCObjOrBlock << type;
7010 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
7011 // because having both 'T' and '__unsafe_unretained T' exist in the type
7012 // system causes unfortunate widespread consistency problems. (For example,
7013 // they're not considered compatible types, and we mangle them identicially
7014 // as template arguments.) These problems are all individually fixable,
7015 // but it's easier to just not add the qualifier and instead sniff it out
7016 // in specific places using isObjCInertUnsafeUnretainedType().
7018 // Doing this does means we miss some trivial consistency checks that
7019 // would've triggered in ARC, but that's better than trying to solve all
7020 // the coexistence problems with __unsafe_unretained.
7021 if (!S.getLangOpts().ObjCAutoRefCount &&
7022 lifetime == Qualifiers::OCL_ExplicitNone) {
7023 type = state.getAttributedType(
7024 createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr),
7025 type, type);
7026 return true;
7029 QualType origType = type;
7030 if (!NonObjCPointer)
7031 type = S.Context.getQualifiedType(underlyingType);
7033 // If we have a valid source location for the attribute, use an
7034 // AttributedType instead.
7035 if (AttrLoc.isValid()) {
7036 type = state.getAttributedType(::new (S.Context)
7037 ObjCOwnershipAttr(S.Context, attr, II),
7038 origType, type);
7041 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
7042 unsigned diagnostic, QualType type) {
7043 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
7044 S.DelayedDiagnostics.add(
7045 sema::DelayedDiagnostic::makeForbiddenType(
7046 S.getSourceManager().getExpansionLoc(loc),
7047 diagnostic, type, /*ignored*/ 0));
7048 } else {
7049 S.Diag(loc, diagnostic);
7053 // Sometimes, __weak isn't allowed.
7054 if (lifetime == Qualifiers::OCL_Weak &&
7055 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
7057 // Use a specialized diagnostic if the runtime just doesn't support them.
7058 unsigned diagnostic =
7059 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
7060 : diag::err_arc_weak_no_runtime);
7062 // In any case, delay the diagnostic until we know what we're parsing.
7063 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
7065 attr.setInvalid();
7066 return true;
7069 // Forbid __weak for class objects marked as
7070 // objc_arc_weak_reference_unavailable
7071 if (lifetime == Qualifiers::OCL_Weak) {
7072 if (const ObjCObjectPointerType *ObjT =
7073 type->getAs<ObjCObjectPointerType>()) {
7074 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
7075 if (Class->isArcWeakrefUnavailable()) {
7076 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
7077 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
7078 diag::note_class_declared);
7084 return true;
7087 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
7088 /// attribute on the specified type. Returns true to indicate that
7089 /// the attribute was handled, false to indicate that the type does
7090 /// not permit the attribute.
7091 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7092 QualType &type) {
7093 Sema &S = state.getSema();
7095 // Delay if this isn't some kind of pointer.
7096 if (!type->isPointerType() &&
7097 !type->isObjCObjectPointerType() &&
7098 !type->isBlockPointerType())
7099 return false;
7101 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
7102 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
7103 attr.setInvalid();
7104 return true;
7107 // Check the attribute arguments.
7108 if (!attr.isArgIdent(0)) {
7109 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
7110 << attr << AANT_ArgumentString;
7111 attr.setInvalid();
7112 return true;
7114 Qualifiers::GC GCAttr;
7115 if (attr.getNumArgs() > 1) {
7116 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
7117 << 1;
7118 attr.setInvalid();
7119 return true;
7122 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
7123 if (II->isStr("weak"))
7124 GCAttr = Qualifiers::Weak;
7125 else if (II->isStr("strong"))
7126 GCAttr = Qualifiers::Strong;
7127 else {
7128 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
7129 << attr << II;
7130 attr.setInvalid();
7131 return true;
7134 QualType origType = type;
7135 type = S.Context.getObjCGCQualType(origType, GCAttr);
7137 // Make an attributed type to preserve the source information.
7138 if (attr.getLoc().isValid())
7139 type = state.getAttributedType(
7140 ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type);
7142 return true;
7145 namespace {
7146 /// A helper class to unwrap a type down to a function for the
7147 /// purposes of applying attributes there.
7149 /// Use:
7150 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
7151 /// if (unwrapped.isFunctionType()) {
7152 /// const FunctionType *fn = unwrapped.get();
7153 /// // change fn somehow
7154 /// T = unwrapped.wrap(fn);
7155 /// }
7156 struct FunctionTypeUnwrapper {
7157 enum WrapKind {
7158 Desugar,
7159 Attributed,
7160 Parens,
7161 Array,
7162 Pointer,
7163 BlockPointer,
7164 Reference,
7165 MemberPointer,
7166 MacroQualified,
7169 QualType Original;
7170 const FunctionType *Fn;
7171 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
7173 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
7174 while (true) {
7175 const Type *Ty = T.getTypePtr();
7176 if (isa<FunctionType>(Ty)) {
7177 Fn = cast<FunctionType>(Ty);
7178 return;
7179 } else if (isa<ParenType>(Ty)) {
7180 T = cast<ParenType>(Ty)->getInnerType();
7181 Stack.push_back(Parens);
7182 } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) ||
7183 isa<IncompleteArrayType>(Ty)) {
7184 T = cast<ArrayType>(Ty)->getElementType();
7185 Stack.push_back(Array);
7186 } else if (isa<PointerType>(Ty)) {
7187 T = cast<PointerType>(Ty)->getPointeeType();
7188 Stack.push_back(Pointer);
7189 } else if (isa<BlockPointerType>(Ty)) {
7190 T = cast<BlockPointerType>(Ty)->getPointeeType();
7191 Stack.push_back(BlockPointer);
7192 } else if (isa<MemberPointerType>(Ty)) {
7193 T = cast<MemberPointerType>(Ty)->getPointeeType();
7194 Stack.push_back(MemberPointer);
7195 } else if (isa<ReferenceType>(Ty)) {
7196 T = cast<ReferenceType>(Ty)->getPointeeType();
7197 Stack.push_back(Reference);
7198 } else if (isa<AttributedType>(Ty)) {
7199 T = cast<AttributedType>(Ty)->getEquivalentType();
7200 Stack.push_back(Attributed);
7201 } else if (isa<MacroQualifiedType>(Ty)) {
7202 T = cast<MacroQualifiedType>(Ty)->getUnderlyingType();
7203 Stack.push_back(MacroQualified);
7204 } else {
7205 const Type *DTy = Ty->getUnqualifiedDesugaredType();
7206 if (Ty == DTy) {
7207 Fn = nullptr;
7208 return;
7211 T = QualType(DTy, 0);
7212 Stack.push_back(Desugar);
7217 bool isFunctionType() const { return (Fn != nullptr); }
7218 const FunctionType *get() const { return Fn; }
7220 QualType wrap(Sema &S, const FunctionType *New) {
7221 // If T wasn't modified from the unwrapped type, do nothing.
7222 if (New == get()) return Original;
7224 Fn = New;
7225 return wrap(S.Context, Original, 0);
7228 private:
7229 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
7230 if (I == Stack.size())
7231 return C.getQualifiedType(Fn, Old.getQualifiers());
7233 // Build up the inner type, applying the qualifiers from the old
7234 // type to the new type.
7235 SplitQualType SplitOld = Old.split();
7237 // As a special case, tail-recurse if there are no qualifiers.
7238 if (SplitOld.Quals.empty())
7239 return wrap(C, SplitOld.Ty, I);
7240 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
7243 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
7244 if (I == Stack.size()) return QualType(Fn, 0);
7246 switch (static_cast<WrapKind>(Stack[I++])) {
7247 case Desugar:
7248 // This is the point at which we potentially lose source
7249 // information.
7250 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
7252 case Attributed:
7253 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
7255 case Parens: {
7256 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
7257 return C.getParenType(New);
7260 case MacroQualified:
7261 return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I);
7263 case Array: {
7264 if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) {
7265 QualType New = wrap(C, CAT->getElementType(), I);
7266 return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(),
7267 CAT->getSizeModifier(),
7268 CAT->getIndexTypeCVRQualifiers());
7271 if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) {
7272 QualType New = wrap(C, VAT->getElementType(), I);
7273 return C.getVariableArrayType(
7274 New, VAT->getSizeExpr(), VAT->getSizeModifier(),
7275 VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange());
7278 const auto *IAT = cast<IncompleteArrayType>(Old);
7279 QualType New = wrap(C, IAT->getElementType(), I);
7280 return C.getIncompleteArrayType(New, IAT->getSizeModifier(),
7281 IAT->getIndexTypeCVRQualifiers());
7284 case Pointer: {
7285 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
7286 return C.getPointerType(New);
7289 case BlockPointer: {
7290 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
7291 return C.getBlockPointerType(New);
7294 case MemberPointer: {
7295 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
7296 QualType New = wrap(C, OldMPT->getPointeeType(), I);
7297 return C.getMemberPointerType(New, OldMPT->getClass());
7300 case Reference: {
7301 const ReferenceType *OldRef = cast<ReferenceType>(Old);
7302 QualType New = wrap(C, OldRef->getPointeeType(), I);
7303 if (isa<LValueReferenceType>(OldRef))
7304 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
7305 else
7306 return C.getRValueReferenceType(New);
7310 llvm_unreachable("unknown wrapping kind");
7313 } // end anonymous namespace
7315 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
7316 ParsedAttr &PAttr, QualType &Type) {
7317 Sema &S = State.getSema();
7319 Attr *A;
7320 switch (PAttr.getKind()) {
7321 default: llvm_unreachable("Unknown attribute kind");
7322 case ParsedAttr::AT_Ptr32:
7323 A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr);
7324 break;
7325 case ParsedAttr::AT_Ptr64:
7326 A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr);
7327 break;
7328 case ParsedAttr::AT_SPtr:
7329 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
7330 break;
7331 case ParsedAttr::AT_UPtr:
7332 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
7333 break;
7336 std::bitset<attr::LastAttr> Attrs;
7337 QualType Desugared = Type;
7338 for (;;) {
7339 if (const TypedefType *TT = dyn_cast<TypedefType>(Desugared)) {
7340 Desugared = TT->desugar();
7341 continue;
7342 } else if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(Desugared)) {
7343 Desugared = ET->desugar();
7344 continue;
7346 const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
7347 if (!AT)
7348 break;
7349 Attrs[AT->getAttrKind()] = true;
7350 Desugared = AT->getModifiedType();
7353 // You cannot specify duplicate type attributes, so if the attribute has
7354 // already been applied, flag it.
7355 attr::Kind NewAttrKind = A->getKind();
7356 if (Attrs[NewAttrKind]) {
7357 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7358 return true;
7360 Attrs[NewAttrKind] = true;
7362 // You cannot have both __sptr and __uptr on the same type, nor can you
7363 // have __ptr32 and __ptr64.
7364 if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) {
7365 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7366 << "'__ptr32'"
7367 << "'__ptr64'" << /*isRegularKeyword=*/0;
7368 return true;
7369 } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) {
7370 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7371 << "'__sptr'"
7372 << "'__uptr'" << /*isRegularKeyword=*/0;
7373 return true;
7376 // Check the raw (i.e., desugared) Canonical type to see if it
7377 // is a pointer type.
7378 if (!isa<PointerType>(Desugared)) {
7379 // Pointer type qualifiers can only operate on pointer types, but not
7380 // pointer-to-member types.
7381 if (Type->isMemberPointerType())
7382 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
7383 else
7384 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
7385 return true;
7388 // Add address space to type based on its attributes.
7389 LangAS ASIdx = LangAS::Default;
7390 uint64_t PtrWidth =
7391 S.Context.getTargetInfo().getPointerWidth(LangAS::Default);
7392 if (PtrWidth == 32) {
7393 if (Attrs[attr::Ptr64])
7394 ASIdx = LangAS::ptr64;
7395 else if (Attrs[attr::UPtr])
7396 ASIdx = LangAS::ptr32_uptr;
7397 } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) {
7398 if (Attrs[attr::UPtr])
7399 ASIdx = LangAS::ptr32_uptr;
7400 else
7401 ASIdx = LangAS::ptr32_sptr;
7404 QualType Pointee = Type->getPointeeType();
7405 if (ASIdx != LangAS::Default)
7406 Pointee = S.Context.getAddrSpaceQualType(
7407 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7408 Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee));
7409 return false;
7412 static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State,
7413 QualType &QT, ParsedAttr &PAttr) {
7414 assert(PAttr.getKind() == ParsedAttr::AT_WebAssemblyFuncref);
7416 Sema &S = State.getSema();
7417 Attr *A = createSimpleAttr<WebAssemblyFuncrefAttr>(S.Context, PAttr);
7419 std::bitset<attr::LastAttr> Attrs;
7420 attr::Kind NewAttrKind = A->getKind();
7421 const auto *AT = dyn_cast<AttributedType>(QT);
7422 while (AT) {
7423 Attrs[AT->getAttrKind()] = true;
7424 AT = dyn_cast<AttributedType>(AT->getModifiedType());
7427 // You cannot specify duplicate type attributes, so if the attribute has
7428 // already been applied, flag it.
7429 if (Attrs[NewAttrKind]) {
7430 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7431 return true;
7434 // Add address space to type based on its attributes.
7435 LangAS ASIdx = LangAS::wasm_funcref;
7436 QualType Pointee = QT->getPointeeType();
7437 Pointee = S.Context.getAddrSpaceQualType(
7438 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7439 QT = State.getAttributedType(A, QT, S.Context.getPointerType(Pointee));
7440 return false;
7443 /// Map a nullability attribute kind to a nullability kind.
7444 static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) {
7445 switch (kind) {
7446 case ParsedAttr::AT_TypeNonNull:
7447 return NullabilityKind::NonNull;
7449 case ParsedAttr::AT_TypeNullable:
7450 return NullabilityKind::Nullable;
7452 case ParsedAttr::AT_TypeNullableResult:
7453 return NullabilityKind::NullableResult;
7455 case ParsedAttr::AT_TypeNullUnspecified:
7456 return NullabilityKind::Unspecified;
7458 default:
7459 llvm_unreachable("not a nullability attribute kind");
7463 /// Applies a nullability type specifier to the given type, if possible.
7465 /// \param state The type processing state.
7467 /// \param type The type to which the nullability specifier will be
7468 /// added. On success, this type will be updated appropriately.
7470 /// \param attr The attribute as written on the type.
7472 /// \param allowOnArrayType Whether to accept nullability specifiers on an
7473 /// array type (e.g., because it will decay to a pointer).
7475 /// \returns true if a problem has been diagnosed, false on success.
7476 static bool checkNullabilityTypeSpecifier(TypeProcessingState &state,
7477 QualType &type,
7478 ParsedAttr &attr,
7479 bool allowOnArrayType) {
7480 Sema &S = state.getSema();
7482 NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind());
7483 SourceLocation nullabilityLoc = attr.getLoc();
7484 bool isContextSensitive = attr.isContextSensitiveKeywordAttribute();
7486 recordNullabilitySeen(S, nullabilityLoc);
7488 // Check for existing nullability attributes on the type.
7489 QualType desugared = type;
7490 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
7491 // Check whether there is already a null
7492 if (auto existingNullability = attributed->getImmediateNullability()) {
7493 // Duplicated nullability.
7494 if (nullability == *existingNullability) {
7495 S.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
7496 << DiagNullabilityKind(nullability, isContextSensitive)
7497 << FixItHint::CreateRemoval(nullabilityLoc);
7499 break;
7502 // Conflicting nullability.
7503 S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
7504 << DiagNullabilityKind(nullability, isContextSensitive)
7505 << DiagNullabilityKind(*existingNullability, false);
7506 return true;
7509 desugared = attributed->getModifiedType();
7512 // If there is already a different nullability specifier, complain.
7513 // This (unlike the code above) looks through typedefs that might
7514 // have nullability specifiers on them, which means we cannot
7515 // provide a useful Fix-It.
7516 if (auto existingNullability = desugared->getNullability()) {
7517 if (nullability != *existingNullability) {
7518 S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
7519 << DiagNullabilityKind(nullability, isContextSensitive)
7520 << DiagNullabilityKind(*existingNullability, false);
7522 // Try to find the typedef with the existing nullability specifier.
7523 if (auto typedefType = desugared->getAs<TypedefType>()) {
7524 TypedefNameDecl *typedefDecl = typedefType->getDecl();
7525 QualType underlyingType = typedefDecl->getUnderlyingType();
7526 if (auto typedefNullability
7527 = AttributedType::stripOuterNullability(underlyingType)) {
7528 if (*typedefNullability == *existingNullability) {
7529 S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
7530 << DiagNullabilityKind(*existingNullability, false);
7535 return true;
7539 // If this definitely isn't a pointer type, reject the specifier.
7540 if (!desugared->canHaveNullability() &&
7541 !(allowOnArrayType && desugared->isArrayType())) {
7542 S.Diag(nullabilityLoc, diag::err_nullability_nonpointer)
7543 << DiagNullabilityKind(nullability, isContextSensitive) << type;
7544 return true;
7547 // For the context-sensitive keywords/Objective-C property
7548 // attributes, require that the type be a single-level pointer.
7549 if (isContextSensitive) {
7550 // Make sure that the pointee isn't itself a pointer type.
7551 const Type *pointeeType = nullptr;
7552 if (desugared->isArrayType())
7553 pointeeType = desugared->getArrayElementTypeNoTypeQual();
7554 else if (desugared->isAnyPointerType())
7555 pointeeType = desugared->getPointeeType().getTypePtr();
7557 if (pointeeType && (pointeeType->isAnyPointerType() ||
7558 pointeeType->isObjCObjectPointerType() ||
7559 pointeeType->isMemberPointerType())) {
7560 S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
7561 << DiagNullabilityKind(nullability, true)
7562 << type;
7563 S.Diag(nullabilityLoc, diag::note_nullability_type_specifier)
7564 << DiagNullabilityKind(nullability, false)
7565 << type
7566 << FixItHint::CreateReplacement(nullabilityLoc,
7567 getNullabilitySpelling(nullability));
7568 return true;
7572 // Form the attributed type.
7573 type = state.getAttributedType(
7574 createNullabilityAttr(S.Context, attr, nullability), type, type);
7575 return false;
7578 /// Check the application of the Objective-C '__kindof' qualifier to
7579 /// the given type.
7580 static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
7581 ParsedAttr &attr) {
7582 Sema &S = state.getSema();
7584 if (isa<ObjCTypeParamType>(type)) {
7585 // Build the attributed type to record where __kindof occurred.
7586 type = state.getAttributedType(
7587 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type);
7588 return false;
7591 // Find out if it's an Objective-C object or object pointer type;
7592 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
7593 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
7594 : type->getAs<ObjCObjectType>();
7596 // If not, we can't apply __kindof.
7597 if (!objType) {
7598 // FIXME: Handle dependent types that aren't yet object types.
7599 S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
7600 << type;
7601 return true;
7604 // Rebuild the "equivalent" type, which pushes __kindof down into
7605 // the object type.
7606 // There is no need to apply kindof on an unqualified id type.
7607 QualType equivType = S.Context.getObjCObjectType(
7608 objType->getBaseType(), objType->getTypeArgsAsWritten(),
7609 objType->getProtocols(),
7610 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
7612 // If we started with an object pointer type, rebuild it.
7613 if (ptrType) {
7614 equivType = S.Context.getObjCObjectPointerType(equivType);
7615 if (auto nullability = type->getNullability()) {
7616 // We create a nullability attribute from the __kindof attribute.
7617 // Make sure that will make sense.
7618 assert(attr.getAttributeSpellingListIndex() == 0 &&
7619 "multiple spellings for __kindof?");
7620 Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
7621 A->setImplicit(true);
7622 equivType = state.getAttributedType(A, equivType, equivType);
7626 // Build the attributed type to record where __kindof occurred.
7627 type = state.getAttributedType(
7628 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType);
7629 return false;
7632 /// Distribute a nullability type attribute that cannot be applied to
7633 /// the type specifier to a pointer, block pointer, or member pointer
7634 /// declarator, complaining if necessary.
7636 /// \returns true if the nullability annotation was distributed, false
7637 /// otherwise.
7638 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
7639 QualType type, ParsedAttr &attr) {
7640 Declarator &declarator = state.getDeclarator();
7642 /// Attempt to move the attribute to the specified chunk.
7643 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
7644 // If there is already a nullability attribute there, don't add
7645 // one.
7646 if (hasNullabilityAttr(chunk.getAttrs()))
7647 return false;
7649 // Complain about the nullability qualifier being in the wrong
7650 // place.
7651 enum {
7652 PK_Pointer,
7653 PK_BlockPointer,
7654 PK_MemberPointer,
7655 PK_FunctionPointer,
7656 PK_MemberFunctionPointer,
7657 } pointerKind
7658 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
7659 : PK_Pointer)
7660 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
7661 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
7663 auto diag = state.getSema().Diag(attr.getLoc(),
7664 diag::warn_nullability_declspec)
7665 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
7666 attr.isContextSensitiveKeywordAttribute())
7667 << type
7668 << static_cast<unsigned>(pointerKind);
7670 // FIXME: MemberPointer chunks don't carry the location of the *.
7671 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
7672 diag << FixItHint::CreateRemoval(attr.getLoc())
7673 << FixItHint::CreateInsertion(
7674 state.getSema().getPreprocessor().getLocForEndOfToken(
7675 chunk.Loc),
7676 " " + attr.getAttrName()->getName().str() + " ");
7679 moveAttrFromListToList(attr, state.getCurrentAttributes(),
7680 chunk.getAttrs());
7681 return true;
7684 // Move it to the outermost pointer, member pointer, or block
7685 // pointer declarator.
7686 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
7687 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
7688 switch (chunk.Kind) {
7689 case DeclaratorChunk::Pointer:
7690 case DeclaratorChunk::BlockPointer:
7691 case DeclaratorChunk::MemberPointer:
7692 return moveToChunk(chunk, false);
7694 case DeclaratorChunk::Paren:
7695 case DeclaratorChunk::Array:
7696 continue;
7698 case DeclaratorChunk::Function:
7699 // Try to move past the return type to a function/block/member
7700 // function pointer.
7701 if (DeclaratorChunk *dest = maybeMovePastReturnType(
7702 declarator, i,
7703 /*onlyBlockPointers=*/false)) {
7704 return moveToChunk(*dest, true);
7707 return false;
7709 // Don't walk through these.
7710 case DeclaratorChunk::Reference:
7711 case DeclaratorChunk::Pipe:
7712 return false;
7716 return false;
7719 static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) {
7720 assert(!Attr.isInvalid());
7721 switch (Attr.getKind()) {
7722 default:
7723 llvm_unreachable("not a calling convention attribute");
7724 case ParsedAttr::AT_CDecl:
7725 return createSimpleAttr<CDeclAttr>(Ctx, Attr);
7726 case ParsedAttr::AT_FastCall:
7727 return createSimpleAttr<FastCallAttr>(Ctx, Attr);
7728 case ParsedAttr::AT_StdCall:
7729 return createSimpleAttr<StdCallAttr>(Ctx, Attr);
7730 case ParsedAttr::AT_ThisCall:
7731 return createSimpleAttr<ThisCallAttr>(Ctx, Attr);
7732 case ParsedAttr::AT_RegCall:
7733 return createSimpleAttr<RegCallAttr>(Ctx, Attr);
7734 case ParsedAttr::AT_Pascal:
7735 return createSimpleAttr<PascalAttr>(Ctx, Attr);
7736 case ParsedAttr::AT_SwiftCall:
7737 return createSimpleAttr<SwiftCallAttr>(Ctx, Attr);
7738 case ParsedAttr::AT_SwiftAsyncCall:
7739 return createSimpleAttr<SwiftAsyncCallAttr>(Ctx, Attr);
7740 case ParsedAttr::AT_VectorCall:
7741 return createSimpleAttr<VectorCallAttr>(Ctx, Attr);
7742 case ParsedAttr::AT_AArch64VectorPcs:
7743 return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr);
7744 case ParsedAttr::AT_AArch64SVEPcs:
7745 return createSimpleAttr<AArch64SVEPcsAttr>(Ctx, Attr);
7746 case ParsedAttr::AT_ArmStreaming:
7747 return createSimpleAttr<ArmStreamingAttr>(Ctx, Attr);
7748 case ParsedAttr::AT_AMDGPUKernelCall:
7749 return createSimpleAttr<AMDGPUKernelCallAttr>(Ctx, Attr);
7750 case ParsedAttr::AT_Pcs: {
7751 // The attribute may have had a fixit applied where we treated an
7752 // identifier as a string literal. The contents of the string are valid,
7753 // but the form may not be.
7754 StringRef Str;
7755 if (Attr.isArgExpr(0))
7756 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
7757 else
7758 Str = Attr.getArgAsIdent(0)->Ident->getName();
7759 PcsAttr::PCSType Type;
7760 if (!PcsAttr::ConvertStrToPCSType(Str, Type))
7761 llvm_unreachable("already validated the attribute");
7762 return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
7764 case ParsedAttr::AT_IntelOclBicc:
7765 return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr);
7766 case ParsedAttr::AT_MSABI:
7767 return createSimpleAttr<MSABIAttr>(Ctx, Attr);
7768 case ParsedAttr::AT_SysVABI:
7769 return createSimpleAttr<SysVABIAttr>(Ctx, Attr);
7770 case ParsedAttr::AT_PreserveMost:
7771 return createSimpleAttr<PreserveMostAttr>(Ctx, Attr);
7772 case ParsedAttr::AT_PreserveAll:
7773 return createSimpleAttr<PreserveAllAttr>(Ctx, Attr);
7775 llvm_unreachable("unexpected attribute kind!");
7778 static bool checkMutualExclusion(TypeProcessingState &state,
7779 const FunctionProtoType::ExtProtoInfo &EPI,
7780 ParsedAttr &Attr,
7781 AttributeCommonInfo::Kind OtherKind) {
7782 auto OtherAttr = std::find_if(
7783 state.getCurrentAttributes().begin(), state.getCurrentAttributes().end(),
7784 [OtherKind](const ParsedAttr &A) { return A.getKind() == OtherKind; });
7785 if (OtherAttr == state.getCurrentAttributes().end() || OtherAttr->isInvalid())
7786 return false;
7788 Sema &S = state.getSema();
7789 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
7790 << *OtherAttr << Attr
7791 << (OtherAttr->isRegularKeywordAttribute() ||
7792 Attr.isRegularKeywordAttribute());
7793 S.Diag(OtherAttr->getLoc(), diag::note_conflicting_attribute);
7794 Attr.setInvalid();
7795 return true;
7798 /// Process an individual function attribute. Returns true to
7799 /// indicate that the attribute was handled, false if it wasn't.
7800 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7801 QualType &type) {
7802 Sema &S = state.getSema();
7804 FunctionTypeUnwrapper unwrapped(S, type);
7806 if (attr.getKind() == ParsedAttr::AT_NoReturn) {
7807 if (S.CheckAttrNoArgs(attr))
7808 return true;
7810 // Delay if this is not a function type.
7811 if (!unwrapped.isFunctionType())
7812 return false;
7814 // Otherwise we can process right away.
7815 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
7816 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7817 return true;
7820 if (attr.getKind() == ParsedAttr::AT_CmseNSCall) {
7821 // Delay if this is not a function type.
7822 if (!unwrapped.isFunctionType())
7823 return false;
7825 // Ignore if we don't have CMSE enabled.
7826 if (!S.getLangOpts().Cmse) {
7827 S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr;
7828 attr.setInvalid();
7829 return true;
7832 // Otherwise we can process right away.
7833 FunctionType::ExtInfo EI =
7834 unwrapped.get()->getExtInfo().withCmseNSCall(true);
7835 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7836 return true;
7839 // ns_returns_retained is not always a type attribute, but if we got
7840 // here, we're treating it as one right now.
7841 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
7842 if (attr.getNumArgs()) return true;
7844 // Delay if this is not a function type.
7845 if (!unwrapped.isFunctionType())
7846 return false;
7848 // Check whether the return type is reasonable.
7849 if (S.checkNSReturnsRetainedReturnType(attr.getLoc(),
7850 unwrapped.get()->getReturnType()))
7851 return true;
7853 // Only actually change the underlying type in ARC builds.
7854 QualType origType = type;
7855 if (state.getSema().getLangOpts().ObjCAutoRefCount) {
7856 FunctionType::ExtInfo EI
7857 = unwrapped.get()->getExtInfo().withProducesResult(true);
7858 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7860 type = state.getAttributedType(
7861 createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr),
7862 origType, type);
7863 return true;
7866 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
7867 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
7868 return true;
7870 // Delay if this is not a function type.
7871 if (!unwrapped.isFunctionType())
7872 return false;
7874 FunctionType::ExtInfo EI =
7875 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
7876 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7877 return true;
7880 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
7881 if (!S.getLangOpts().CFProtectionBranch) {
7882 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
7883 attr.setInvalid();
7884 return true;
7887 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
7888 return true;
7890 // If this is not a function type, warning will be asserted by subject
7891 // check.
7892 if (!unwrapped.isFunctionType())
7893 return true;
7895 FunctionType::ExtInfo EI =
7896 unwrapped.get()->getExtInfo().withNoCfCheck(true);
7897 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7898 return true;
7901 if (attr.getKind() == ParsedAttr::AT_Regparm) {
7902 unsigned value;
7903 if (S.CheckRegparmAttr(attr, value))
7904 return true;
7906 // Delay if this is not a function type.
7907 if (!unwrapped.isFunctionType())
7908 return false;
7910 // Diagnose regparm with fastcall.
7911 const FunctionType *fn = unwrapped.get();
7912 CallingConv CC = fn->getCallConv();
7913 if (CC == CC_X86FastCall) {
7914 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7915 << FunctionType::getNameForCallConv(CC) << "regparm"
7916 << attr.isRegularKeywordAttribute();
7917 attr.setInvalid();
7918 return true;
7921 FunctionType::ExtInfo EI =
7922 unwrapped.get()->getExtInfo().withRegParm(value);
7923 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7924 return true;
7927 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
7928 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible ||
7929 attr.getKind() == ParsedAttr::AT_ArmSharedZA ||
7930 attr.getKind() == ParsedAttr::AT_ArmPreservesZA){
7931 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
7932 return true;
7934 if (!unwrapped.isFunctionType())
7935 return false;
7937 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
7938 if (!FnTy) {
7939 // SME ACLE attributes are not supported on K&R-style unprototyped C
7940 // functions.
7941 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type) <<
7942 attr << attr.isRegularKeywordAttribute() << ExpectedFunctionWithProtoType;
7943 attr.setInvalid();
7944 return false;
7947 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
7948 switch (attr.getKind()) {
7949 case ParsedAttr::AT_ArmStreaming:
7950 if (checkMutualExclusion(state, EPI, attr,
7951 ParsedAttr::AT_ArmStreamingCompatible))
7952 return true;
7953 EPI.setArmSMEAttribute(FunctionType::SME_PStateSMEnabledMask);
7954 break;
7955 case ParsedAttr::AT_ArmStreamingCompatible:
7956 if (checkMutualExclusion(state, EPI, attr, ParsedAttr::AT_ArmStreaming))
7957 return true;
7958 EPI.setArmSMEAttribute(FunctionType::SME_PStateSMCompatibleMask);
7959 break;
7960 case ParsedAttr::AT_ArmSharedZA:
7961 EPI.setArmSMEAttribute(FunctionType::SME_PStateZASharedMask);
7962 break;
7963 case ParsedAttr::AT_ArmPreservesZA:
7964 EPI.setArmSMEAttribute(FunctionType::SME_PStateZAPreservedMask);
7965 break;
7966 default:
7967 llvm_unreachable("Unsupported attribute");
7970 QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(),
7971 FnTy->getParamTypes(), EPI);
7972 type = unwrapped.wrap(S, newtype->getAs<FunctionType>());
7973 return true;
7976 if (attr.getKind() == ParsedAttr::AT_NoThrow) {
7977 // Delay if this is not a function type.
7978 if (!unwrapped.isFunctionType())
7979 return false;
7981 if (S.CheckAttrNoArgs(attr)) {
7982 attr.setInvalid();
7983 return true;
7986 // Otherwise we can process right away.
7987 auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
7989 // MSVC ignores nothrow if it is in conflict with an explicit exception
7990 // specification.
7991 if (Proto->hasExceptionSpec()) {
7992 switch (Proto->getExceptionSpecType()) {
7993 case EST_None:
7994 llvm_unreachable("This doesn't have an exception spec!");
7996 case EST_DynamicNone:
7997 case EST_BasicNoexcept:
7998 case EST_NoexceptTrue:
7999 case EST_NoThrow:
8000 // Exception spec doesn't conflict with nothrow, so don't warn.
8001 [[fallthrough]];
8002 case EST_Unparsed:
8003 case EST_Uninstantiated:
8004 case EST_DependentNoexcept:
8005 case EST_Unevaluated:
8006 // We don't have enough information to properly determine if there is a
8007 // conflict, so suppress the warning.
8008 break;
8009 case EST_Dynamic:
8010 case EST_MSAny:
8011 case EST_NoexceptFalse:
8012 S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored);
8013 break;
8015 return true;
8018 type = unwrapped.wrap(
8019 S, S.Context
8020 .getFunctionTypeWithExceptionSpec(
8021 QualType{Proto, 0},
8022 FunctionProtoType::ExceptionSpecInfo{EST_NoThrow})
8023 ->getAs<FunctionType>());
8024 return true;
8027 // Delay if the type didn't work out to a function.
8028 if (!unwrapped.isFunctionType()) return false;
8030 // Otherwise, a calling convention.
8031 CallingConv CC;
8032 if (S.CheckCallingConvAttr(attr, CC))
8033 return true;
8035 const FunctionType *fn = unwrapped.get();
8036 CallingConv CCOld = fn->getCallConv();
8037 Attr *CCAttr = getCCTypeAttr(S.Context, attr);
8039 if (CCOld != CC) {
8040 // Error out on when there's already an attribute on the type
8041 // and the CCs don't match.
8042 if (S.getCallingConvAttributedType(type)) {
8043 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8044 << FunctionType::getNameForCallConv(CC)
8045 << FunctionType::getNameForCallConv(CCOld)
8046 << attr.isRegularKeywordAttribute();
8047 attr.setInvalid();
8048 return true;
8052 // Diagnose use of variadic functions with calling conventions that
8053 // don't support them (e.g. because they're callee-cleanup).
8054 // We delay warning about this on unprototyped function declarations
8055 // until after redeclaration checking, just in case we pick up a
8056 // prototype that way. And apparently we also "delay" warning about
8057 // unprototyped function types in general, despite not necessarily having
8058 // much ability to diagnose it later.
8059 if (!supportsVariadicCall(CC)) {
8060 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
8061 if (FnP && FnP->isVariadic()) {
8062 // stdcall and fastcall are ignored with a warning for GCC and MS
8063 // compatibility.
8064 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
8065 return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported)
8066 << FunctionType::getNameForCallConv(CC)
8067 << (int)Sema::CallingConventionIgnoredReason::VariadicFunction;
8069 attr.setInvalid();
8070 return S.Diag(attr.getLoc(), diag::err_cconv_varargs)
8071 << FunctionType::getNameForCallConv(CC);
8075 // Also diagnose fastcall with regparm.
8076 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
8077 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8078 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall)
8079 << attr.isRegularKeywordAttribute();
8080 attr.setInvalid();
8081 return true;
8084 // Modify the CC from the wrapped function type, wrap it all back, and then
8085 // wrap the whole thing in an AttributedType as written. The modified type
8086 // might have a different CC if we ignored the attribute.
8087 QualType Equivalent;
8088 if (CCOld == CC) {
8089 Equivalent = type;
8090 } else {
8091 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
8092 Equivalent =
8093 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8095 type = state.getAttributedType(CCAttr, type, Equivalent);
8096 return true;
8099 bool Sema::hasExplicitCallingConv(QualType T) {
8100 const AttributedType *AT;
8102 // Stop if we'd be stripping off a typedef sugar node to reach the
8103 // AttributedType.
8104 while ((AT = T->getAs<AttributedType>()) &&
8105 AT->getAs<TypedefType>() == T->getAs<TypedefType>()) {
8106 if (AT->isCallingConv())
8107 return true;
8108 T = AT->getModifiedType();
8110 return false;
8113 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
8114 SourceLocation Loc) {
8115 FunctionTypeUnwrapper Unwrapped(*this, T);
8116 const FunctionType *FT = Unwrapped.get();
8117 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
8118 cast<FunctionProtoType>(FT)->isVariadic());
8119 CallingConv CurCC = FT->getCallConv();
8120 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
8122 if (CurCC == ToCC)
8123 return;
8125 // MS compiler ignores explicit calling convention attributes on structors. We
8126 // should do the same.
8127 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
8128 // Issue a warning on ignored calling convention -- except of __stdcall.
8129 // Again, this is what MS compiler does.
8130 if (CurCC != CC_X86StdCall)
8131 Diag(Loc, diag::warn_cconv_unsupported)
8132 << FunctionType::getNameForCallConv(CurCC)
8133 << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor;
8134 // Default adjustment.
8135 } else {
8136 // Only adjust types with the default convention. For example, on Windows
8137 // we should adjust a __cdecl type to __thiscall for instance methods, and a
8138 // __thiscall type to __cdecl for static methods.
8139 CallingConv DefaultCC =
8140 Context.getDefaultCallingConvention(IsVariadic, IsStatic);
8142 if (CurCC != DefaultCC)
8143 return;
8145 if (hasExplicitCallingConv(T))
8146 return;
8149 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
8150 QualType Wrapped = Unwrapped.wrap(*this, FT);
8151 T = Context.getAdjustedType(T, Wrapped);
8154 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
8155 /// and float scalars, although arrays, pointers, and function return values are
8156 /// allowed in conjunction with this construct. Aggregates with this attribute
8157 /// are invalid, even if they are of the same size as a corresponding scalar.
8158 /// The raw attribute should contain precisely 1 argument, the vector size for
8159 /// the variable, measured in bytes. If curType and rawAttr are well formed,
8160 /// this routine will return a new vector type.
8161 static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
8162 Sema &S) {
8163 // Check the attribute arguments.
8164 if (Attr.getNumArgs() != 1) {
8165 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8166 << 1;
8167 Attr.setInvalid();
8168 return;
8171 Expr *SizeExpr = Attr.getArgAsExpr(0);
8172 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
8173 if (!T.isNull())
8174 CurType = T;
8175 else
8176 Attr.setInvalid();
8179 /// Process the OpenCL-like ext_vector_type attribute when it occurs on
8180 /// a type.
8181 static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8182 Sema &S) {
8183 // check the attribute arguments.
8184 if (Attr.getNumArgs() != 1) {
8185 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8186 << 1;
8187 return;
8190 Expr *SizeExpr = Attr.getArgAsExpr(0);
8191 QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc());
8192 if (!T.isNull())
8193 CurType = T;
8196 static bool isPermittedNeonBaseType(QualType &Ty,
8197 VectorType::VectorKind VecKind, Sema &S) {
8198 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
8199 if (!BTy)
8200 return false;
8202 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
8204 // Signed poly is mathematically wrong, but has been baked into some ABIs by
8205 // now.
8206 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
8207 Triple.getArch() == llvm::Triple::aarch64_32 ||
8208 Triple.getArch() == llvm::Triple::aarch64_be;
8209 if (VecKind == VectorType::NeonPolyVector) {
8210 if (IsPolyUnsigned) {
8211 // AArch64 polynomial vectors are unsigned.
8212 return BTy->getKind() == BuiltinType::UChar ||
8213 BTy->getKind() == BuiltinType::UShort ||
8214 BTy->getKind() == BuiltinType::ULong ||
8215 BTy->getKind() == BuiltinType::ULongLong;
8216 } else {
8217 // AArch32 polynomial vectors are signed.
8218 return BTy->getKind() == BuiltinType::SChar ||
8219 BTy->getKind() == BuiltinType::Short ||
8220 BTy->getKind() == BuiltinType::LongLong;
8224 // Non-polynomial vector types: the usual suspects are allowed, as well as
8225 // float64_t on AArch64.
8226 if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) &&
8227 BTy->getKind() == BuiltinType::Double)
8228 return true;
8230 return BTy->getKind() == BuiltinType::SChar ||
8231 BTy->getKind() == BuiltinType::UChar ||
8232 BTy->getKind() == BuiltinType::Short ||
8233 BTy->getKind() == BuiltinType::UShort ||
8234 BTy->getKind() == BuiltinType::Int ||
8235 BTy->getKind() == BuiltinType::UInt ||
8236 BTy->getKind() == BuiltinType::Long ||
8237 BTy->getKind() == BuiltinType::ULong ||
8238 BTy->getKind() == BuiltinType::LongLong ||
8239 BTy->getKind() == BuiltinType::ULongLong ||
8240 BTy->getKind() == BuiltinType::Float ||
8241 BTy->getKind() == BuiltinType::Half ||
8242 BTy->getKind() == BuiltinType::BFloat16;
8245 static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr,
8246 llvm::APSInt &Result) {
8247 const auto *AttrExpr = Attr.getArgAsExpr(0);
8248 if (!AttrExpr->isTypeDependent()) {
8249 if (std::optional<llvm::APSInt> Res =
8250 AttrExpr->getIntegerConstantExpr(S.Context)) {
8251 Result = *Res;
8252 return true;
8255 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
8256 << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange();
8257 Attr.setInvalid();
8258 return false;
8261 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
8262 /// "neon_polyvector_type" attributes are used to create vector types that
8263 /// are mangled according to ARM's ABI. Otherwise, these types are identical
8264 /// to those created with the "vector_size" attribute. Unlike "vector_size"
8265 /// the argument to these Neon attributes is the number of vector elements,
8266 /// not the vector size in bytes. The vector width and element type must
8267 /// match one of the standard Neon vector types.
8268 static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8269 Sema &S, VectorType::VectorKind VecKind) {
8270 bool IsTargetCUDAAndHostARM = false;
8271 if (S.getLangOpts().CUDAIsDevice) {
8272 const TargetInfo *AuxTI = S.getASTContext().getAuxTargetInfo();
8273 IsTargetCUDAAndHostARM =
8274 AuxTI && (AuxTI->getTriple().isAArch64() || AuxTI->getTriple().isARM());
8277 // Target must have NEON (or MVE, whose vectors are similar enough
8278 // not to need a separate attribute)
8279 if (!(S.Context.getTargetInfo().hasFeature("neon") ||
8280 S.Context.getTargetInfo().hasFeature("mve") ||
8281 IsTargetCUDAAndHostARM)) {
8282 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
8283 << Attr << "'neon' or 'mve'";
8284 Attr.setInvalid();
8285 return;
8287 // Check the attribute arguments.
8288 if (Attr.getNumArgs() != 1) {
8289 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8290 << Attr << 1;
8291 Attr.setInvalid();
8292 return;
8294 // The number of elements must be an ICE.
8295 llvm::APSInt numEltsInt(32);
8296 if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt))
8297 return;
8299 // Only certain element types are supported for Neon vectors.
8300 if (!isPermittedNeonBaseType(CurType, VecKind, S) &&
8301 !IsTargetCUDAAndHostARM) {
8302 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
8303 Attr.setInvalid();
8304 return;
8307 // The total size of the vector must be 64 or 128 bits.
8308 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
8309 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
8310 unsigned vecSize = typeSize * numElts;
8311 if (vecSize != 64 && vecSize != 128) {
8312 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
8313 Attr.setInvalid();
8314 return;
8317 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
8320 /// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is
8321 /// used to create fixed-length versions of sizeless SVE types defined by
8322 /// the ACLE, such as svint32_t and svbool_t.
8323 static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr,
8324 Sema &S) {
8325 // Target must have SVE.
8326 if (!S.Context.getTargetInfo().hasFeature("sve")) {
8327 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'";
8328 Attr.setInvalid();
8329 return;
8332 // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or
8333 // if <bits>+ syntax is used.
8334 if (!S.getLangOpts().VScaleMin ||
8335 S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) {
8336 S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported)
8337 << Attr;
8338 Attr.setInvalid();
8339 return;
8342 // Check the attribute arguments.
8343 if (Attr.getNumArgs() != 1) {
8344 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8345 << Attr << 1;
8346 Attr.setInvalid();
8347 return;
8350 // The vector size must be an integer constant expression.
8351 llvm::APSInt SveVectorSizeInBits(32);
8352 if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits))
8353 return;
8355 unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue());
8357 // The attribute vector size must match -msve-vector-bits.
8358 if (VecSize != S.getLangOpts().VScaleMin * 128) {
8359 S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size)
8360 << VecSize << S.getLangOpts().VScaleMin * 128;
8361 Attr.setInvalid();
8362 return;
8365 // Attribute can only be attached to a single SVE vector or predicate type.
8366 if (!CurType->isSveVLSBuiltinType()) {
8367 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type)
8368 << Attr << CurType;
8369 Attr.setInvalid();
8370 return;
8373 const auto *BT = CurType->castAs<BuiltinType>();
8375 QualType EltType = CurType->getSveEltType(S.Context);
8376 unsigned TypeSize = S.Context.getTypeSize(EltType);
8377 VectorType::VectorKind VecKind = VectorType::SveFixedLengthDataVector;
8378 if (BT->getKind() == BuiltinType::SveBool) {
8379 // Predicates are represented as i8.
8380 VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth();
8381 VecKind = VectorType::SveFixedLengthPredicateVector;
8382 } else
8383 VecSize /= TypeSize;
8384 CurType = S.Context.getVectorType(EltType, VecSize, VecKind);
8387 static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State,
8388 QualType &CurType,
8389 ParsedAttr &Attr) {
8390 const VectorType *VT = dyn_cast<VectorType>(CurType);
8391 if (!VT || VT->getVectorKind() != VectorType::NeonVector) {
8392 State.getSema().Diag(Attr.getLoc(),
8393 diag::err_attribute_arm_mve_polymorphism);
8394 Attr.setInvalid();
8395 return;
8398 CurType =
8399 State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>(
8400 State.getSema().Context, Attr),
8401 CurType, CurType);
8404 /// HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is
8405 /// used to create fixed-length versions of sizeless RVV types such as
8406 /// vint8m1_t_t.
8407 static void HandleRISCVRVVVectorBitsTypeAttr(QualType &CurType,
8408 ParsedAttr &Attr, Sema &S) {
8409 // Target must have vector extension.
8410 if (!S.Context.getTargetInfo().hasFeature("zve32x")) {
8411 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
8412 << Attr << "'zve32x'";
8413 Attr.setInvalid();
8414 return;
8417 auto VScale = S.Context.getTargetInfo().getVScaleRange(S.getLangOpts());
8418 if (!VScale || !VScale->first || VScale->first != VScale->second) {
8419 S.Diag(Attr.getLoc(), diag::err_attribute_riscv_rvv_bits_unsupported)
8420 << Attr;
8421 Attr.setInvalid();
8422 return;
8425 // Check the attribute arguments.
8426 if (Attr.getNumArgs() != 1) {
8427 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8428 << Attr << 1;
8429 Attr.setInvalid();
8430 return;
8433 // The vector size must be an integer constant expression.
8434 llvm::APSInt RVVVectorSizeInBits(32);
8435 if (!verifyValidIntegerConstantExpr(S, Attr, RVVVectorSizeInBits))
8436 return;
8438 // Attribute can only be attached to a single RVV vector type.
8439 if (!CurType->isRVVVLSBuiltinType()) {
8440 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_rvv_type)
8441 << Attr << CurType;
8442 Attr.setInvalid();
8443 return;
8446 unsigned VecSize = static_cast<unsigned>(RVVVectorSizeInBits.getZExtValue());
8448 ASTContext::BuiltinVectorTypeInfo Info =
8449 S.Context.getBuiltinVectorTypeInfo(CurType->castAs<BuiltinType>());
8450 unsigned EltSize = S.Context.getTypeSize(Info.ElementType);
8451 unsigned MinElts = Info.EC.getKnownMinValue();
8453 // The attribute vector size must match -mrvv-vector-bits.
8454 unsigned ExpectedSize = VScale->first * MinElts * EltSize;
8455 if (VecSize != ExpectedSize) {
8456 S.Diag(Attr.getLoc(), diag::err_attribute_bad_rvv_vector_size)
8457 << VecSize << ExpectedSize;
8458 Attr.setInvalid();
8459 return;
8462 VectorType::VectorKind VecKind = VectorType::RVVFixedLengthDataVector;
8463 VecSize /= EltSize;
8464 CurType = S.Context.getVectorType(Info.ElementType, VecSize, VecKind);
8467 /// Handle OpenCL Access Qualifier Attribute.
8468 static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
8469 Sema &S) {
8470 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
8471 if (!(CurType->isImageType() || CurType->isPipeType())) {
8472 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
8473 Attr.setInvalid();
8474 return;
8477 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
8478 QualType BaseTy = TypedefTy->desugar();
8480 std::string PrevAccessQual;
8481 if (BaseTy->isPipeType()) {
8482 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
8483 OpenCLAccessAttr *Attr =
8484 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
8485 PrevAccessQual = Attr->getSpelling();
8486 } else {
8487 PrevAccessQual = "read_only";
8489 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
8491 switch (ImgType->getKind()) {
8492 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8493 case BuiltinType::Id: \
8494 PrevAccessQual = #Access; \
8495 break;
8496 #include "clang/Basic/OpenCLImageTypes.def"
8497 default:
8498 llvm_unreachable("Unable to find corresponding image type.");
8500 } else {
8501 llvm_unreachable("unexpected type");
8503 StringRef AttrName = Attr.getAttrName()->getName();
8504 if (PrevAccessQual == AttrName.ltrim("_")) {
8505 // Duplicated qualifiers
8506 S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
8507 << AttrName << Attr.getRange();
8508 } else {
8509 // Contradicting qualifiers
8510 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
8513 S.Diag(TypedefTy->getDecl()->getBeginLoc(),
8514 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
8515 } else if (CurType->isPipeType()) {
8516 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
8517 QualType ElemType = CurType->castAs<PipeType>()->getElementType();
8518 CurType = S.Context.getWritePipeType(ElemType);
8523 /// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type
8524 static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8525 Sema &S) {
8526 if (!S.getLangOpts().MatrixTypes) {
8527 S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled);
8528 return;
8531 if (Attr.getNumArgs() != 2) {
8532 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8533 << Attr << 2;
8534 return;
8537 Expr *RowsExpr = Attr.getArgAsExpr(0);
8538 Expr *ColsExpr = Attr.getArgAsExpr(1);
8539 QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc());
8540 if (!T.isNull())
8541 CurType = T;
8544 static void HandleAnnotateTypeAttr(TypeProcessingState &State,
8545 QualType &CurType, const ParsedAttr &PA) {
8546 Sema &S = State.getSema();
8548 if (PA.getNumArgs() < 1) {
8549 S.Diag(PA.getLoc(), diag::err_attribute_too_few_arguments) << PA << 1;
8550 return;
8553 // Make sure that there is a string literal as the annotation's first
8554 // argument.
8555 StringRef Str;
8556 if (!S.checkStringLiteralArgumentAttr(PA, 0, Str))
8557 return;
8559 llvm::SmallVector<Expr *, 4> Args;
8560 Args.reserve(PA.getNumArgs() - 1);
8561 for (unsigned Idx = 1; Idx < PA.getNumArgs(); Idx++) {
8562 assert(!PA.isArgIdent(Idx));
8563 Args.push_back(PA.getArgAsExpr(Idx));
8565 if (!S.ConstantFoldAttrArgs(PA, Args))
8566 return;
8567 auto *AnnotateTypeAttr =
8568 AnnotateTypeAttr::Create(S.Context, Str, Args.data(), Args.size(), PA);
8569 CurType = State.getAttributedType(AnnotateTypeAttr, CurType, CurType);
8572 static void HandleLifetimeBoundAttr(TypeProcessingState &State,
8573 QualType &CurType,
8574 ParsedAttr &Attr) {
8575 if (State.getDeclarator().isDeclarationOfFunction()) {
8576 CurType = State.getAttributedType(
8577 createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
8578 CurType, CurType);
8582 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
8583 TypeAttrLocation TAL,
8584 const ParsedAttributesView &attrs) {
8586 state.setParsedNoDeref(false);
8587 if (attrs.empty())
8588 return;
8590 // Scan through and apply attributes to this type where it makes sense. Some
8591 // attributes (such as __address_space__, __vector_size__, etc) apply to the
8592 // type, but others can be present in the type specifiers even though they
8593 // apply to the decl. Here we apply type attributes and ignore the rest.
8595 // This loop modifies the list pretty frequently, but we still need to make
8596 // sure we visit every element once. Copy the attributes list, and iterate
8597 // over that.
8598 ParsedAttributesView AttrsCopy{attrs};
8599 for (ParsedAttr &attr : AttrsCopy) {
8601 // Skip attributes that were marked to be invalid.
8602 if (attr.isInvalid())
8603 continue;
8605 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute()) {
8606 // [[gnu::...]] attributes are treated as declaration attributes, so may
8607 // not appertain to a DeclaratorChunk. If we handle them as type
8608 // attributes, accept them in that position and diagnose the GCC
8609 // incompatibility.
8610 if (attr.isGNUScope()) {
8611 assert(attr.isStandardAttributeSyntax());
8612 bool IsTypeAttr = attr.isTypeAttr();
8613 if (TAL == TAL_DeclChunk) {
8614 state.getSema().Diag(attr.getLoc(),
8615 IsTypeAttr
8616 ? diag::warn_gcc_ignores_type_attr
8617 : diag::warn_cxx11_gnu_attribute_on_type)
8618 << attr;
8619 if (!IsTypeAttr)
8620 continue;
8622 } else if (TAL != TAL_DeclSpec && TAL != TAL_DeclChunk &&
8623 !attr.isTypeAttr()) {
8624 // Otherwise, only consider type processing for a C++11 attribute if
8625 // - it has actually been applied to a type (decl-specifier-seq or
8626 // declarator chunk), or
8627 // - it is a type attribute, irrespective of where it was applied (so
8628 // that we can support the legacy behavior of some type attributes
8629 // that can be applied to the declaration name).
8630 continue;
8634 // If this is an attribute we can handle, do so now,
8635 // otherwise, add it to the FnAttrs list for rechaining.
8636 switch (attr.getKind()) {
8637 default:
8638 // A [[]] attribute on a declarator chunk must appertain to a type.
8639 if ((attr.isStandardAttributeSyntax() ||
8640 attr.isRegularKeywordAttribute()) &&
8641 TAL == TAL_DeclChunk) {
8642 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
8643 << attr << attr.isRegularKeywordAttribute();
8644 attr.setUsedAsTypeAttr();
8646 break;
8648 case ParsedAttr::UnknownAttribute:
8649 if (attr.isStandardAttributeSyntax()) {
8650 state.getSema().Diag(attr.getLoc(),
8651 diag::warn_unknown_attribute_ignored)
8652 << attr << attr.getRange();
8653 // Mark the attribute as invalid so we don't emit the same diagnostic
8654 // multiple times.
8655 attr.setInvalid();
8657 break;
8659 case ParsedAttr::IgnoredAttribute:
8660 break;
8662 case ParsedAttr::AT_BTFTypeTag:
8663 HandleBTFTypeTagAttribute(type, attr, state);
8664 attr.setUsedAsTypeAttr();
8665 break;
8667 case ParsedAttr::AT_MayAlias:
8668 // FIXME: This attribute needs to actually be handled, but if we ignore
8669 // it it breaks large amounts of Linux software.
8670 attr.setUsedAsTypeAttr();
8671 break;
8672 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
8673 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
8674 case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace:
8675 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace:
8676 case ParsedAttr::AT_OpenCLLocalAddressSpace:
8677 case ParsedAttr::AT_OpenCLConstantAddressSpace:
8678 case ParsedAttr::AT_OpenCLGenericAddressSpace:
8679 case ParsedAttr::AT_HLSLGroupSharedAddressSpace:
8680 case ParsedAttr::AT_AddressSpace:
8681 HandleAddressSpaceTypeAttribute(type, attr, state);
8682 attr.setUsedAsTypeAttr();
8683 break;
8684 OBJC_POINTER_TYPE_ATTRS_CASELIST:
8685 if (!handleObjCPointerTypeAttr(state, attr, type))
8686 distributeObjCPointerTypeAttr(state, attr, type);
8687 attr.setUsedAsTypeAttr();
8688 break;
8689 case ParsedAttr::AT_VectorSize:
8690 HandleVectorSizeAttr(type, attr, state.getSema());
8691 attr.setUsedAsTypeAttr();
8692 break;
8693 case ParsedAttr::AT_ExtVectorType:
8694 HandleExtVectorTypeAttr(type, attr, state.getSema());
8695 attr.setUsedAsTypeAttr();
8696 break;
8697 case ParsedAttr::AT_NeonVectorType:
8698 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
8699 VectorType::NeonVector);
8700 attr.setUsedAsTypeAttr();
8701 break;
8702 case ParsedAttr::AT_NeonPolyVectorType:
8703 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
8704 VectorType::NeonPolyVector);
8705 attr.setUsedAsTypeAttr();
8706 break;
8707 case ParsedAttr::AT_ArmSveVectorBits:
8708 HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema());
8709 attr.setUsedAsTypeAttr();
8710 break;
8711 case ParsedAttr::AT_ArmMveStrictPolymorphism: {
8712 HandleArmMveStrictPolymorphismAttr(state, type, attr);
8713 attr.setUsedAsTypeAttr();
8714 break;
8716 case ParsedAttr::AT_RISCVRVVVectorBits:
8717 HandleRISCVRVVVectorBitsTypeAttr(type, attr, state.getSema());
8718 attr.setUsedAsTypeAttr();
8719 break;
8720 case ParsedAttr::AT_OpenCLAccess:
8721 HandleOpenCLAccessAttr(type, attr, state.getSema());
8722 attr.setUsedAsTypeAttr();
8723 break;
8724 case ParsedAttr::AT_LifetimeBound:
8725 if (TAL == TAL_DeclChunk)
8726 HandleLifetimeBoundAttr(state, type, attr);
8727 break;
8729 case ParsedAttr::AT_NoDeref: {
8730 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
8731 // See https://github.com/llvm/llvm-project/issues/55790 for details.
8732 // For the time being, we simply emit a warning that the attribute is
8733 // ignored.
8734 if (attr.isStandardAttributeSyntax()) {
8735 state.getSema().Diag(attr.getLoc(), diag::warn_attribute_ignored)
8736 << attr;
8737 break;
8739 ASTContext &Ctx = state.getSema().Context;
8740 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
8741 type, type);
8742 attr.setUsedAsTypeAttr();
8743 state.setParsedNoDeref(true);
8744 break;
8747 case ParsedAttr::AT_MatrixType:
8748 HandleMatrixTypeAttr(type, attr, state.getSema());
8749 attr.setUsedAsTypeAttr();
8750 break;
8752 case ParsedAttr::AT_WebAssemblyFuncref: {
8753 if (!HandleWebAssemblyFuncrefAttr(state, type, attr))
8754 attr.setUsedAsTypeAttr();
8755 break;
8758 MS_TYPE_ATTRS_CASELIST:
8759 if (!handleMSPointerTypeQualifierAttr(state, attr, type))
8760 attr.setUsedAsTypeAttr();
8761 break;
8764 NULLABILITY_TYPE_ATTRS_CASELIST:
8765 // Either add nullability here or try to distribute it. We
8766 // don't want to distribute the nullability specifier past any
8767 // dependent type, because that complicates the user model.
8768 if (type->canHaveNullability() || type->isDependentType() ||
8769 type->isArrayType() ||
8770 !distributeNullabilityTypeAttr(state, type, attr)) {
8771 unsigned endIndex;
8772 if (TAL == TAL_DeclChunk)
8773 endIndex = state.getCurrentChunkIndex();
8774 else
8775 endIndex = state.getDeclarator().getNumTypeObjects();
8776 bool allowOnArrayType =
8777 state.getDeclarator().isPrototypeContext() &&
8778 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
8779 if (checkNullabilityTypeSpecifier(
8780 state,
8781 type,
8782 attr,
8783 allowOnArrayType)) {
8784 attr.setInvalid();
8787 attr.setUsedAsTypeAttr();
8789 break;
8791 case ParsedAttr::AT_ObjCKindOf:
8792 // '__kindof' must be part of the decl-specifiers.
8793 switch (TAL) {
8794 case TAL_DeclSpec:
8795 break;
8797 case TAL_DeclChunk:
8798 case TAL_DeclName:
8799 state.getSema().Diag(attr.getLoc(),
8800 diag::err_objc_kindof_wrong_position)
8801 << FixItHint::CreateRemoval(attr.getLoc())
8802 << FixItHint::CreateInsertion(
8803 state.getDeclarator().getDeclSpec().getBeginLoc(),
8804 "__kindof ");
8805 break;
8808 // Apply it regardless.
8809 if (checkObjCKindOfType(state, type, attr))
8810 attr.setInvalid();
8811 break;
8813 case ParsedAttr::AT_NoThrow:
8814 // Exception Specifications aren't generally supported in C mode throughout
8815 // clang, so revert to attribute-based handling for C.
8816 if (!state.getSema().getLangOpts().CPlusPlus)
8817 break;
8818 [[fallthrough]];
8819 FUNCTION_TYPE_ATTRS_CASELIST:
8820 attr.setUsedAsTypeAttr();
8822 // Attributes with standard syntax have strict rules for what they
8823 // appertain to and hence should not use the "distribution" logic below.
8824 if (attr.isStandardAttributeSyntax() ||
8825 attr.isRegularKeywordAttribute()) {
8826 if (!handleFunctionTypeAttr(state, attr, type)) {
8827 diagnoseBadTypeAttribute(state.getSema(), attr, type);
8828 attr.setInvalid();
8830 break;
8833 // Never process function type attributes as part of the
8834 // declaration-specifiers.
8835 if (TAL == TAL_DeclSpec)
8836 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
8838 // Otherwise, handle the possible delays.
8839 else if (!handleFunctionTypeAttr(state, attr, type))
8840 distributeFunctionTypeAttr(state, attr, type);
8841 break;
8842 case ParsedAttr::AT_AcquireHandle: {
8843 if (!type->isFunctionType())
8844 return;
8846 if (attr.getNumArgs() != 1) {
8847 state.getSema().Diag(attr.getLoc(),
8848 diag::err_attribute_wrong_number_arguments)
8849 << attr << 1;
8850 attr.setInvalid();
8851 return;
8854 StringRef HandleType;
8855 if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType))
8856 return;
8857 type = state.getAttributedType(
8858 AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr),
8859 type, type);
8860 attr.setUsedAsTypeAttr();
8861 break;
8863 case ParsedAttr::AT_AnnotateType: {
8864 HandleAnnotateTypeAttr(state, type, attr);
8865 attr.setUsedAsTypeAttr();
8866 break;
8870 // Handle attributes that are defined in a macro. We do not want this to be
8871 // applied to ObjC builtin attributes.
8872 if (isa<AttributedType>(type) && attr.hasMacroIdentifier() &&
8873 !type.getQualifiers().hasObjCLifetime() &&
8874 !type.getQualifiers().hasObjCGCAttr() &&
8875 attr.getKind() != ParsedAttr::AT_ObjCGC &&
8876 attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
8877 const IdentifierInfo *MacroII = attr.getMacroIdentifier();
8878 type = state.getSema().Context.getMacroQualifiedType(type, MacroII);
8879 state.setExpansionLocForMacroQualifiedType(
8880 cast<MacroQualifiedType>(type.getTypePtr()),
8881 attr.getMacroExpansionLoc());
8886 void Sema::completeExprArrayBound(Expr *E) {
8887 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
8888 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
8889 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
8890 auto *Def = Var->getDefinition();
8891 if (!Def) {
8892 SourceLocation PointOfInstantiation = E->getExprLoc();
8893 runWithSufficientStackSpace(PointOfInstantiation, [&] {
8894 InstantiateVariableDefinition(PointOfInstantiation, Var);
8896 Def = Var->getDefinition();
8898 // If we don't already have a point of instantiation, and we managed
8899 // to instantiate a definition, this is the point of instantiation.
8900 // Otherwise, we don't request an end-of-TU instantiation, so this is
8901 // not a point of instantiation.
8902 // FIXME: Is this really the right behavior?
8903 if (Var->getPointOfInstantiation().isInvalid() && Def) {
8904 assert(Var->getTemplateSpecializationKind() ==
8905 TSK_ImplicitInstantiation &&
8906 "explicit instantiation with no point of instantiation");
8907 Var->setTemplateSpecializationKind(
8908 Var->getTemplateSpecializationKind(), PointOfInstantiation);
8912 // Update the type to the definition's type both here and within the
8913 // expression.
8914 if (Def) {
8915 DRE->setDecl(Def);
8916 QualType T = Def->getType();
8917 DRE->setType(T);
8918 // FIXME: Update the type on all intervening expressions.
8919 E->setType(T);
8922 // We still go on to try to complete the type independently, as it
8923 // may also require instantiations or diagnostics if it remains
8924 // incomplete.
8930 QualType Sema::getCompletedType(Expr *E) {
8931 // Incomplete array types may be completed by the initializer attached to
8932 // their definitions. For static data members of class templates and for
8933 // variable templates, we need to instantiate the definition to get this
8934 // initializer and complete the type.
8935 if (E->getType()->isIncompleteArrayType())
8936 completeExprArrayBound(E);
8938 // FIXME: Are there other cases which require instantiating something other
8939 // than the type to complete the type of an expression?
8941 return E->getType();
8944 /// Ensure that the type of the given expression is complete.
8946 /// This routine checks whether the expression \p E has a complete type. If the
8947 /// expression refers to an instantiable construct, that instantiation is
8948 /// performed as needed to complete its type. Furthermore
8949 /// Sema::RequireCompleteType is called for the expression's type (or in the
8950 /// case of a reference type, the referred-to type).
8952 /// \param E The expression whose type is required to be complete.
8953 /// \param Kind Selects which completeness rules should be applied.
8954 /// \param Diagnoser The object that will emit a diagnostic if the type is
8955 /// incomplete.
8957 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
8958 /// otherwise.
8959 bool Sema::RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
8960 TypeDiagnoser &Diagnoser) {
8961 return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind,
8962 Diagnoser);
8965 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
8966 BoundTypeDiagnoser<> Diagnoser(DiagID);
8967 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
8970 /// Ensure that the type T is a complete type.
8972 /// This routine checks whether the type @p T is complete in any
8973 /// context where a complete type is required. If @p T is a complete
8974 /// type, returns false. If @p T is a class template specialization,
8975 /// this routine then attempts to perform class template
8976 /// instantiation. If instantiation fails, or if @p T is incomplete
8977 /// and cannot be completed, issues the diagnostic @p diag (giving it
8978 /// the type @p T) and returns true.
8980 /// @param Loc The location in the source that the incomplete type
8981 /// diagnostic should refer to.
8983 /// @param T The type that this routine is examining for completeness.
8985 /// @param Kind Selects which completeness rules should be applied.
8987 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
8988 /// @c false otherwise.
8989 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
8990 CompleteTypeKind Kind,
8991 TypeDiagnoser &Diagnoser) {
8992 if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser))
8993 return true;
8994 if (const TagType *Tag = T->getAs<TagType>()) {
8995 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
8996 Tag->getDecl()->setCompleteDefinitionRequired();
8997 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
9000 return false;
9003 bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) {
9004 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
9005 if (!Suggested)
9006 return false;
9008 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
9009 // and isolate from other C++ specific checks.
9010 StructuralEquivalenceContext Ctx(
9011 D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls,
9012 StructuralEquivalenceKind::Default,
9013 false /*StrictTypeSpelling*/, true /*Complain*/,
9014 true /*ErrorOnTagTypeMismatch*/);
9015 return Ctx.IsEquivalent(D, Suggested);
9018 bool Sema::hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
9019 AcceptableKind Kind, bool OnlyNeedComplete) {
9020 // Easy case: if we don't have modules, all declarations are visible.
9021 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
9022 return true;
9024 // If this definition was instantiated from a template, map back to the
9025 // pattern from which it was instantiated.
9026 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
9027 // We're in the middle of defining it; this definition should be treated
9028 // as visible.
9029 return true;
9030 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9031 if (auto *Pattern = RD->getTemplateInstantiationPattern())
9032 RD = Pattern;
9033 D = RD->getDefinition();
9034 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
9035 if (auto *Pattern = ED->getTemplateInstantiationPattern())
9036 ED = Pattern;
9037 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) {
9038 // If the enum has a fixed underlying type, it may have been forward
9039 // declared. In -fms-compatibility, `enum Foo;` will also forward declare
9040 // the enum and assign it the underlying type of `int`. Since we're only
9041 // looking for a complete type (not a definition), any visible declaration
9042 // of it will do.
9043 *Suggested = nullptr;
9044 for (auto *Redecl : ED->redecls()) {
9045 if (isAcceptable(Redecl, Kind))
9046 return true;
9047 if (Redecl->isThisDeclarationADefinition() ||
9048 (Redecl->isCanonicalDecl() && !*Suggested))
9049 *Suggested = Redecl;
9052 return false;
9054 D = ED->getDefinition();
9055 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
9056 if (auto *Pattern = FD->getTemplateInstantiationPattern())
9057 FD = Pattern;
9058 D = FD->getDefinition();
9059 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
9060 if (auto *Pattern = VD->getTemplateInstantiationPattern())
9061 VD = Pattern;
9062 D = VD->getDefinition();
9065 assert(D && "missing definition for pattern of instantiated definition");
9067 *Suggested = D;
9069 auto DefinitionIsAcceptable = [&] {
9070 // The (primary) definition might be in a visible module.
9071 if (isAcceptable(D, Kind))
9072 return true;
9074 // A visible module might have a merged definition instead.
9075 if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D)
9076 : hasVisibleMergedDefinition(D)) {
9077 if (CodeSynthesisContexts.empty() &&
9078 !getLangOpts().ModulesLocalVisibility) {
9079 // Cache the fact that this definition is implicitly visible because
9080 // there is a visible merged definition.
9081 D->setVisibleDespiteOwningModule();
9083 return true;
9086 return false;
9089 if (DefinitionIsAcceptable())
9090 return true;
9092 // The external source may have additional definitions of this entity that are
9093 // visible, so complete the redeclaration chain now and ask again.
9094 if (auto *Source = Context.getExternalSource()) {
9095 Source->CompleteRedeclChain(D);
9096 return DefinitionIsAcceptable();
9099 return false;
9102 /// Determine whether there is any declaration of \p D that was ever a
9103 /// definition (perhaps before module merging) and is currently visible.
9104 /// \param D The definition of the entity.
9105 /// \param Suggested Filled in with the declaration that should be made visible
9106 /// in order to provide a definition of this entity.
9107 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9108 /// not defined. This only matters for enums with a fixed underlying
9109 /// type, since in all other cases, a type is complete if and only if it
9110 /// is defined.
9111 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
9112 bool OnlyNeedComplete) {
9113 return hasAcceptableDefinition(D, Suggested, Sema::AcceptableKind::Visible,
9114 OnlyNeedComplete);
9117 /// Determine whether there is any declaration of \p D that was ever a
9118 /// definition (perhaps before module merging) and is currently
9119 /// reachable.
9120 /// \param D The definition of the entity.
9121 /// \param Suggested Filled in with the declaration that should be made
9122 /// reachable
9123 /// in order to provide a definition of this entity.
9124 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9125 /// not defined. This only matters for enums with a fixed underlying
9126 /// type, since in all other cases, a type is complete if and only if it
9127 /// is defined.
9128 bool Sema::hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
9129 bool OnlyNeedComplete) {
9130 return hasAcceptableDefinition(D, Suggested, Sema::AcceptableKind::Reachable,
9131 OnlyNeedComplete);
9134 /// Locks in the inheritance model for the given class and all of its bases.
9135 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
9136 RD = RD->getMostRecentNonInjectedDecl();
9137 if (!RD->hasAttr<MSInheritanceAttr>()) {
9138 MSInheritanceModel IM;
9139 bool BestCase = false;
9140 switch (S.MSPointerToMemberRepresentationMethod) {
9141 case LangOptions::PPTMK_BestCase:
9142 BestCase = true;
9143 IM = RD->calculateInheritanceModel();
9144 break;
9145 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
9146 IM = MSInheritanceModel::Single;
9147 break;
9148 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
9149 IM = MSInheritanceModel::Multiple;
9150 break;
9151 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
9152 IM = MSInheritanceModel::Unspecified;
9153 break;
9156 SourceRange Loc = S.ImplicitMSInheritanceAttrLoc.isValid()
9157 ? S.ImplicitMSInheritanceAttrLoc
9158 : RD->getSourceRange();
9159 RD->addAttr(MSInheritanceAttr::CreateImplicit(
9160 S.getASTContext(), BestCase, Loc, MSInheritanceAttr::Spelling(IM)));
9161 S.Consumer.AssignInheritanceModel(RD);
9165 /// The implementation of RequireCompleteType
9166 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
9167 CompleteTypeKind Kind,
9168 TypeDiagnoser *Diagnoser) {
9169 // FIXME: Add this assertion to make sure we always get instantiation points.
9170 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
9171 // FIXME: Add this assertion to help us flush out problems with
9172 // checking for dependent types and type-dependent expressions.
9174 // assert(!T->isDependentType() &&
9175 // "Can't ask whether a dependent type is complete");
9177 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
9178 if (!MPTy->getClass()->isDependentType()) {
9179 if (getLangOpts().CompleteMemberPointers &&
9180 !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() &&
9181 RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), Kind,
9182 diag::err_memptr_incomplete))
9183 return true;
9185 // We lock in the inheritance model once somebody has asked us to ensure
9186 // that a pointer-to-member type is complete.
9187 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9188 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
9189 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
9194 NamedDecl *Def = nullptr;
9195 bool AcceptSizeless = (Kind == CompleteTypeKind::AcceptSizeless);
9196 bool Incomplete = (T->isIncompleteType(&Def) ||
9197 (!AcceptSizeless && T->isSizelessBuiltinType()));
9199 // Check that any necessary explicit specializations are visible. For an
9200 // enum, we just need the declaration, so don't check this.
9201 if (Def && !isa<EnumDecl>(Def))
9202 checkSpecializationReachability(Loc, Def);
9204 // If we have a complete type, we're done.
9205 if (!Incomplete) {
9206 NamedDecl *Suggested = nullptr;
9207 if (Def &&
9208 !hasReachableDefinition(Def, &Suggested, /*OnlyNeedComplete=*/true)) {
9209 // If the user is going to see an error here, recover by making the
9210 // definition visible.
9211 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
9212 if (Diagnoser && Suggested)
9213 diagnoseMissingImport(Loc, Suggested, MissingImportKind::Definition,
9214 /*Recover*/ TreatAsComplete);
9215 return !TreatAsComplete;
9216 } else if (Def && !TemplateInstCallbacks.empty()) {
9217 CodeSynthesisContext TempInst;
9218 TempInst.Kind = CodeSynthesisContext::Memoization;
9219 TempInst.Template = Def;
9220 TempInst.Entity = Def;
9221 TempInst.PointOfInstantiation = Loc;
9222 atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
9223 atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
9226 return false;
9229 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
9230 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
9232 // Give the external source a chance to provide a definition of the type.
9233 // This is kept separate from completing the redeclaration chain so that
9234 // external sources such as LLDB can avoid synthesizing a type definition
9235 // unless it's actually needed.
9236 if (Tag || IFace) {
9237 // Avoid diagnosing invalid decls as incomplete.
9238 if (Def->isInvalidDecl())
9239 return true;
9241 // Give the external AST source a chance to complete the type.
9242 if (auto *Source = Context.getExternalSource()) {
9243 if (Tag && Tag->hasExternalLexicalStorage())
9244 Source->CompleteType(Tag);
9245 if (IFace && IFace->hasExternalLexicalStorage())
9246 Source->CompleteType(IFace);
9247 // If the external source completed the type, go through the motions
9248 // again to ensure we're allowed to use the completed type.
9249 if (!T->isIncompleteType())
9250 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9254 // If we have a class template specialization or a class member of a
9255 // class template specialization, or an array with known size of such,
9256 // try to instantiate it.
9257 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
9258 bool Instantiated = false;
9259 bool Diagnosed = false;
9260 if (RD->isDependentContext()) {
9261 // Don't try to instantiate a dependent class (eg, a member template of
9262 // an instantiated class template specialization).
9263 // FIXME: Can this ever happen?
9264 } else if (auto *ClassTemplateSpec =
9265 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
9266 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
9267 runWithSufficientStackSpace(Loc, [&] {
9268 Diagnosed = InstantiateClassTemplateSpecialization(
9269 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
9270 /*Complain=*/Diagnoser);
9272 Instantiated = true;
9274 } else {
9275 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
9276 if (!RD->isBeingDefined() && Pattern) {
9277 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
9278 assert(MSI && "Missing member specialization information?");
9279 // This record was instantiated from a class within a template.
9280 if (MSI->getTemplateSpecializationKind() !=
9281 TSK_ExplicitSpecialization) {
9282 runWithSufficientStackSpace(Loc, [&] {
9283 Diagnosed = InstantiateClass(Loc, RD, Pattern,
9284 getTemplateInstantiationArgs(RD),
9285 TSK_ImplicitInstantiation,
9286 /*Complain=*/Diagnoser);
9288 Instantiated = true;
9293 if (Instantiated) {
9294 // Instantiate* might have already complained that the template is not
9295 // defined, if we asked it to.
9296 if (Diagnoser && Diagnosed)
9297 return true;
9298 // If we instantiated a definition, check that it's usable, even if
9299 // instantiation produced an error, so that repeated calls to this
9300 // function give consistent answers.
9301 if (!T->isIncompleteType())
9302 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9306 // FIXME: If we didn't instantiate a definition because of an explicit
9307 // specialization declaration, check that it's visible.
9309 if (!Diagnoser)
9310 return true;
9312 Diagnoser->diagnose(*this, Loc, T);
9314 // If the type was a forward declaration of a class/struct/union
9315 // type, produce a note.
9316 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid())
9317 Diag(Tag->getLocation(),
9318 Tag->isBeingDefined() ? diag::note_type_being_defined
9319 : diag::note_forward_declaration)
9320 << Context.getTagDeclType(Tag);
9322 // If the Objective-C class was a forward declaration, produce a note.
9323 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid())
9324 Diag(IFace->getLocation(), diag::note_forward_class);
9326 // If we have external information that we can use to suggest a fix,
9327 // produce a note.
9328 if (ExternalSource)
9329 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
9331 return true;
9334 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
9335 CompleteTypeKind Kind, unsigned DiagID) {
9336 BoundTypeDiagnoser<> Diagnoser(DiagID);
9337 return RequireCompleteType(Loc, T, Kind, Diagnoser);
9340 /// Get diagnostic %select index for tag kind for
9341 /// literal type diagnostic message.
9342 /// WARNING: Indexes apply to particular diagnostics only!
9344 /// \returns diagnostic %select index.
9345 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
9346 switch (Tag) {
9347 case TTK_Struct: return 0;
9348 case TTK_Interface: return 1;
9349 case TTK_Class: return 2;
9350 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
9354 /// Ensure that the type T is a literal type.
9356 /// This routine checks whether the type @p T is a literal type. If @p T is an
9357 /// incomplete type, an attempt is made to complete it. If @p T is a literal
9358 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
9359 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
9360 /// it the type @p T), along with notes explaining why the type is not a
9361 /// literal type, and returns true.
9363 /// @param Loc The location in the source that the non-literal type
9364 /// diagnostic should refer to.
9366 /// @param T The type that this routine is examining for literalness.
9368 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
9370 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
9371 /// @c false otherwise.
9372 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
9373 TypeDiagnoser &Diagnoser) {
9374 assert(!T->isDependentType() && "type should not be dependent");
9376 QualType ElemType = Context.getBaseElementType(T);
9377 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
9378 T->isLiteralType(Context))
9379 return false;
9381 Diagnoser.diagnose(*this, Loc, T);
9383 if (T->isVariableArrayType())
9384 return true;
9386 const RecordType *RT = ElemType->getAs<RecordType>();
9387 if (!RT)
9388 return true;
9390 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
9392 // A partially-defined class type can't be a literal type, because a literal
9393 // class type must have a trivial destructor (which can't be checked until
9394 // the class definition is complete).
9395 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
9396 return true;
9398 // [expr.prim.lambda]p3:
9399 // This class type is [not] a literal type.
9400 if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
9401 Diag(RD->getLocation(), diag::note_non_literal_lambda);
9402 return true;
9405 // If the class has virtual base classes, then it's not an aggregate, and
9406 // cannot have any constexpr constructors or a trivial default constructor,
9407 // so is non-literal. This is better to diagnose than the resulting absence
9408 // of constexpr constructors.
9409 if (RD->getNumVBases()) {
9410 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
9411 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
9412 for (const auto &I : RD->vbases())
9413 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
9414 << I.getSourceRange();
9415 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
9416 !RD->hasTrivialDefaultConstructor()) {
9417 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
9418 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
9419 for (const auto &I : RD->bases()) {
9420 if (!I.getType()->isLiteralType(Context)) {
9421 Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
9422 << RD << I.getType() << I.getSourceRange();
9423 return true;
9426 for (const auto *I : RD->fields()) {
9427 if (!I->getType()->isLiteralType(Context) ||
9428 I->getType().isVolatileQualified()) {
9429 Diag(I->getLocation(), diag::note_non_literal_field)
9430 << RD << I << I->getType()
9431 << I->getType().isVolatileQualified();
9432 return true;
9435 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor()
9436 : !RD->hasTrivialDestructor()) {
9437 // All fields and bases are of literal types, so have trivial or constexpr
9438 // destructors. If this class's destructor is non-trivial / non-constexpr,
9439 // it must be user-declared.
9440 CXXDestructorDecl *Dtor = RD->getDestructor();
9441 assert(Dtor && "class has literal fields and bases but no dtor?");
9442 if (!Dtor)
9443 return true;
9445 if (getLangOpts().CPlusPlus20) {
9446 Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor)
9447 << RD;
9448 } else {
9449 Diag(Dtor->getLocation(), Dtor->isUserProvided()
9450 ? diag::note_non_literal_user_provided_dtor
9451 : diag::note_non_literal_nontrivial_dtor)
9452 << RD;
9453 if (!Dtor->isUserProvided())
9454 SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI,
9455 /*Diagnose*/ true);
9459 return true;
9462 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
9463 BoundTypeDiagnoser<> Diagnoser(DiagID);
9464 return RequireLiteralType(Loc, T, Diagnoser);
9467 /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified
9468 /// by the nested-name-specifier contained in SS, and that is (re)declared by
9469 /// OwnedTagDecl, which is nullptr if this is not a (re)declaration.
9470 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
9471 const CXXScopeSpec &SS, QualType T,
9472 TagDecl *OwnedTagDecl) {
9473 if (T.isNull())
9474 return T;
9475 return Context.getElaboratedType(
9476 Keyword, SS.isValid() ? SS.getScopeRep() : nullptr, T, OwnedTagDecl);
9479 QualType Sema::BuildTypeofExprType(Expr *E, TypeOfKind Kind) {
9480 assert(!E->hasPlaceholderType() && "unexpected placeholder");
9482 if (!getLangOpts().CPlusPlus && E->refersToBitField())
9483 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
9484 << (Kind == TypeOfKind::Unqualified ? 3 : 2);
9486 if (!E->isTypeDependent()) {
9487 QualType T = E->getType();
9488 if (const TagType *TT = T->getAs<TagType>())
9489 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
9491 return Context.getTypeOfExprType(E, Kind);
9494 /// getDecltypeForExpr - Given an expr, will return the decltype for
9495 /// that expression, according to the rules in C++11
9496 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
9497 QualType Sema::getDecltypeForExpr(Expr *E) {
9498 if (E->isTypeDependent())
9499 return Context.DependentTy;
9501 Expr *IDExpr = E;
9502 if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E))
9503 IDExpr = ImplCastExpr->getSubExpr();
9505 // C++11 [dcl.type.simple]p4:
9506 // The type denoted by decltype(e) is defined as follows:
9508 // C++20:
9509 // - if E is an unparenthesized id-expression naming a non-type
9510 // template-parameter (13.2), decltype(E) is the type of the
9511 // template-parameter after performing any necessary type deduction
9512 // Note that this does not pick up the implicit 'const' for a template
9513 // parameter object. This rule makes no difference before C++20 so we apply
9514 // it unconditionally.
9515 if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr))
9516 return SNTTPE->getParameterType(Context);
9518 // - if e is an unparenthesized id-expression or an unparenthesized class
9519 // member access (5.2.5), decltype(e) is the type of the entity named
9520 // by e. If there is no such entity, or if e names a set of overloaded
9521 // functions, the program is ill-formed;
9523 // We apply the same rules for Objective-C ivar and property references.
9524 if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) {
9525 const ValueDecl *VD = DRE->getDecl();
9526 QualType T = VD->getType();
9527 return isa<TemplateParamObjectDecl>(VD) ? T.getUnqualifiedType() : T;
9529 if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) {
9530 if (const auto *VD = ME->getMemberDecl())
9531 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
9532 return VD->getType();
9533 } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) {
9534 return IR->getDecl()->getType();
9535 } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) {
9536 if (PR->isExplicitProperty())
9537 return PR->getExplicitProperty()->getType();
9538 } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) {
9539 return PE->getType();
9542 // C++11 [expr.lambda.prim]p18:
9543 // Every occurrence of decltype((x)) where x is a possibly
9544 // parenthesized id-expression that names an entity of automatic
9545 // storage duration is treated as if x were transformed into an
9546 // access to a corresponding data member of the closure type that
9547 // would have been declared if x were an odr-use of the denoted
9548 // entity.
9549 if (getCurLambda() && isa<ParenExpr>(IDExpr)) {
9550 if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) {
9551 if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
9552 QualType T = getCapturedDeclRefType(Var, DRE->getLocation());
9553 if (!T.isNull())
9554 return Context.getLValueReferenceType(T);
9559 return Context.getReferenceQualifiedType(E);
9562 QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) {
9563 assert(!E->hasPlaceholderType() && "unexpected placeholder");
9565 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
9566 !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) {
9567 // The expression operand for decltype is in an unevaluated expression
9568 // context, so side effects could result in unintended consequences.
9569 // Exclude instantiation-dependent expressions, because 'decltype' is often
9570 // used to build SFINAE gadgets.
9571 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
9573 return Context.getDecltypeType(E, getDecltypeForExpr(E));
9576 static QualType GetEnumUnderlyingType(Sema &S, QualType BaseType,
9577 SourceLocation Loc) {
9578 assert(BaseType->isEnumeralType());
9579 EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl();
9580 assert(ED && "EnumType has no EnumDecl");
9582 S.DiagnoseUseOfDecl(ED, Loc);
9584 QualType Underlying = ED->getIntegerType();
9585 assert(!Underlying.isNull());
9587 return Underlying;
9590 QualType Sema::BuiltinEnumUnderlyingType(QualType BaseType,
9591 SourceLocation Loc) {
9592 if (!BaseType->isEnumeralType()) {
9593 Diag(Loc, diag::err_only_enums_have_underlying_types);
9594 return QualType();
9597 // The enum could be incomplete if we're parsing its definition or
9598 // recovering from an error.
9599 NamedDecl *FwdDecl = nullptr;
9600 if (BaseType->isIncompleteType(&FwdDecl)) {
9601 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
9602 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
9603 return QualType();
9606 return GetEnumUnderlyingType(*this, BaseType, Loc);
9609 QualType Sema::BuiltinAddPointer(QualType BaseType, SourceLocation Loc) {
9610 QualType Pointer = BaseType.isReferenceable() || BaseType->isVoidType()
9611 ? BuildPointerType(BaseType.getNonReferenceType(), Loc,
9612 DeclarationName())
9613 : BaseType;
9615 return Pointer.isNull() ? QualType() : Pointer;
9618 QualType Sema::BuiltinRemovePointer(QualType BaseType, SourceLocation Loc) {
9619 // We don't want block pointers or ObjectiveC's id type.
9620 if (!BaseType->isAnyPointerType() || BaseType->isObjCIdType())
9621 return BaseType;
9623 return BaseType->getPointeeType();
9626 QualType Sema::BuiltinDecay(QualType BaseType, SourceLocation Loc) {
9627 QualType Underlying = BaseType.getNonReferenceType();
9628 if (Underlying->isArrayType())
9629 return Context.getDecayedType(Underlying);
9631 if (Underlying->isFunctionType())
9632 return BuiltinAddPointer(BaseType, Loc);
9634 SplitQualType Split = Underlying.getSplitUnqualifiedType();
9635 // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is
9636 // in the same group of qualifiers as 'const' and 'volatile', we're extending
9637 // '__decay(T)' so that it removes all qualifiers.
9638 Split.Quals.removeCVRQualifiers();
9639 return Context.getQualifiedType(Split);
9642 QualType Sema::BuiltinAddReference(QualType BaseType, UTTKind UKind,
9643 SourceLocation Loc) {
9644 assert(LangOpts.CPlusPlus);
9645 QualType Reference =
9646 BaseType.isReferenceable()
9647 ? BuildReferenceType(BaseType,
9648 UKind == UnaryTransformType::AddLvalueReference,
9649 Loc, DeclarationName())
9650 : BaseType;
9651 return Reference.isNull() ? QualType() : Reference;
9654 QualType Sema::BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
9655 SourceLocation Loc) {
9656 if (UKind == UnaryTransformType::RemoveAllExtents)
9657 return Context.getBaseElementType(BaseType);
9659 if (const auto *AT = Context.getAsArrayType(BaseType))
9660 return AT->getElementType();
9662 return BaseType;
9665 QualType Sema::BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
9666 SourceLocation Loc) {
9667 assert(LangOpts.CPlusPlus);
9668 QualType T = BaseType.getNonReferenceType();
9669 if (UKind == UTTKind::RemoveCVRef &&
9670 (T.isConstQualified() || T.isVolatileQualified())) {
9671 Qualifiers Quals;
9672 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
9673 Quals.removeConst();
9674 Quals.removeVolatile();
9675 T = Context.getQualifiedType(Unqual, Quals);
9677 return T;
9680 QualType Sema::BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
9681 SourceLocation Loc) {
9682 if ((BaseType->isReferenceType() && UKind != UTTKind::RemoveRestrict) ||
9683 BaseType->isFunctionType())
9684 return BaseType;
9686 Qualifiers Quals;
9687 QualType Unqual = Context.getUnqualifiedArrayType(BaseType, Quals);
9689 if (UKind == UTTKind::RemoveConst || UKind == UTTKind::RemoveCV)
9690 Quals.removeConst();
9691 if (UKind == UTTKind::RemoveVolatile || UKind == UTTKind::RemoveCV)
9692 Quals.removeVolatile();
9693 if (UKind == UTTKind::RemoveRestrict)
9694 Quals.removeRestrict();
9696 return Context.getQualifiedType(Unqual, Quals);
9699 static QualType ChangeIntegralSignedness(Sema &S, QualType BaseType,
9700 bool IsMakeSigned,
9701 SourceLocation Loc) {
9702 if (BaseType->isEnumeralType()) {
9703 QualType Underlying = GetEnumUnderlyingType(S, BaseType, Loc);
9704 if (auto *BitInt = dyn_cast<BitIntType>(Underlying)) {
9705 unsigned int Bits = BitInt->getNumBits();
9706 if (Bits > 1)
9707 return S.Context.getBitIntType(!IsMakeSigned, Bits);
9709 S.Diag(Loc, diag::err_make_signed_integral_only)
9710 << IsMakeSigned << /*_BitInt(1)*/ true << BaseType << 1 << Underlying;
9711 return QualType();
9713 if (Underlying->isBooleanType()) {
9714 S.Diag(Loc, diag::err_make_signed_integral_only)
9715 << IsMakeSigned << /*_BitInt(1)*/ false << BaseType << 1
9716 << Underlying;
9717 return QualType();
9721 bool Int128Unsupported = !S.Context.getTargetInfo().hasInt128Type();
9722 std::array<CanQualType *, 6> AllSignedIntegers = {
9723 &S.Context.SignedCharTy, &S.Context.ShortTy, &S.Context.IntTy,
9724 &S.Context.LongTy, &S.Context.LongLongTy, &S.Context.Int128Ty};
9725 ArrayRef<CanQualType *> AvailableSignedIntegers(
9726 AllSignedIntegers.data(), AllSignedIntegers.size() - Int128Unsupported);
9727 std::array<CanQualType *, 6> AllUnsignedIntegers = {
9728 &S.Context.UnsignedCharTy, &S.Context.UnsignedShortTy,
9729 &S.Context.UnsignedIntTy, &S.Context.UnsignedLongTy,
9730 &S.Context.UnsignedLongLongTy, &S.Context.UnsignedInt128Ty};
9731 ArrayRef<CanQualType *> AvailableUnsignedIntegers(AllUnsignedIntegers.data(),
9732 AllUnsignedIntegers.size() -
9733 Int128Unsupported);
9734 ArrayRef<CanQualType *> *Consider =
9735 IsMakeSigned ? &AvailableSignedIntegers : &AvailableUnsignedIntegers;
9737 uint64_t BaseSize = S.Context.getTypeSize(BaseType);
9738 auto *Result =
9739 llvm::find_if(*Consider, [&S, BaseSize](const CanQual<Type> *T) {
9740 return BaseSize == S.Context.getTypeSize(T->getTypePtr());
9743 assert(Result != Consider->end());
9744 return QualType((*Result)->getTypePtr(), 0);
9747 QualType Sema::BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
9748 SourceLocation Loc) {
9749 bool IsMakeSigned = UKind == UnaryTransformType::MakeSigned;
9750 if ((!BaseType->isIntegerType() && !BaseType->isEnumeralType()) ||
9751 BaseType->isBooleanType() ||
9752 (BaseType->isBitIntType() &&
9753 BaseType->getAs<BitIntType>()->getNumBits() < 2)) {
9754 Diag(Loc, diag::err_make_signed_integral_only)
9755 << IsMakeSigned << BaseType->isBitIntType() << BaseType << 0;
9756 return QualType();
9759 bool IsNonIntIntegral =
9760 BaseType->isChar16Type() || BaseType->isChar32Type() ||
9761 BaseType->isWideCharType() || BaseType->isEnumeralType();
9763 QualType Underlying =
9764 IsNonIntIntegral
9765 ? ChangeIntegralSignedness(*this, BaseType, IsMakeSigned, Loc)
9766 : IsMakeSigned ? Context.getCorrespondingSignedType(BaseType)
9767 : Context.getCorrespondingUnsignedType(BaseType);
9768 if (Underlying.isNull())
9769 return Underlying;
9770 return Context.getQualifiedType(Underlying, BaseType.getQualifiers());
9773 QualType Sema::BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
9774 SourceLocation Loc) {
9775 if (BaseType->isDependentType())
9776 return Context.getUnaryTransformType(BaseType, BaseType, UKind);
9777 QualType Result;
9778 switch (UKind) {
9779 case UnaryTransformType::EnumUnderlyingType: {
9780 Result = BuiltinEnumUnderlyingType(BaseType, Loc);
9781 break;
9783 case UnaryTransformType::AddPointer: {
9784 Result = BuiltinAddPointer(BaseType, Loc);
9785 break;
9787 case UnaryTransformType::RemovePointer: {
9788 Result = BuiltinRemovePointer(BaseType, Loc);
9789 break;
9791 case UnaryTransformType::Decay: {
9792 Result = BuiltinDecay(BaseType, Loc);
9793 break;
9795 case UnaryTransformType::AddLvalueReference:
9796 case UnaryTransformType::AddRvalueReference: {
9797 Result = BuiltinAddReference(BaseType, UKind, Loc);
9798 break;
9800 case UnaryTransformType::RemoveAllExtents:
9801 case UnaryTransformType::RemoveExtent: {
9802 Result = BuiltinRemoveExtent(BaseType, UKind, Loc);
9803 break;
9805 case UnaryTransformType::RemoveCVRef:
9806 case UnaryTransformType::RemoveReference: {
9807 Result = BuiltinRemoveReference(BaseType, UKind, Loc);
9808 break;
9810 case UnaryTransformType::RemoveConst:
9811 case UnaryTransformType::RemoveCV:
9812 case UnaryTransformType::RemoveRestrict:
9813 case UnaryTransformType::RemoveVolatile: {
9814 Result = BuiltinChangeCVRQualifiers(BaseType, UKind, Loc);
9815 break;
9817 case UnaryTransformType::MakeSigned:
9818 case UnaryTransformType::MakeUnsigned: {
9819 Result = BuiltinChangeSignedness(BaseType, UKind, Loc);
9820 break;
9824 return !Result.isNull()
9825 ? Context.getUnaryTransformType(BaseType, Result, UKind)
9826 : Result;
9829 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
9830 if (!isDependentOrGNUAutoType(T)) {
9831 // FIXME: It isn't entirely clear whether incomplete atomic types
9832 // are allowed or not; for simplicity, ban them for the moment.
9833 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
9834 return QualType();
9836 int DisallowedKind = -1;
9837 if (T->isArrayType())
9838 DisallowedKind = 1;
9839 else if (T->isFunctionType())
9840 DisallowedKind = 2;
9841 else if (T->isReferenceType())
9842 DisallowedKind = 3;
9843 else if (T->isAtomicType())
9844 DisallowedKind = 4;
9845 else if (T.hasQualifiers())
9846 DisallowedKind = 5;
9847 else if (T->isSizelessType())
9848 DisallowedKind = 6;
9849 else if (!T.isTriviallyCopyableType(Context))
9850 // Some other non-trivially-copyable type (probably a C++ class)
9851 DisallowedKind = 7;
9852 else if (T->isBitIntType())
9853 DisallowedKind = 8;
9855 if (DisallowedKind != -1) {
9856 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
9857 return QualType();
9860 // FIXME: Do we need any handling for ARC here?
9863 // Build the pointer type.
9864 return Context.getAtomicType(T);