[Flang] remove whole-archive option for AIX linker (#76039)
[llvm-project.git] / clang / lib / Sema / SemaType.cpp
bloba376f20fa4f4e08540b3a86ac5a9ac1e96f88b6d
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/Decl.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/Type.h"
24 #include "clang/AST/TypeLoc.h"
25 #include "clang/AST/TypeLocVisitor.h"
26 #include "clang/Basic/PartialDiagnostic.h"
27 #include "clang/Basic/SourceLocation.h"
28 #include "clang/Basic/Specifiers.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/DeclSpec.h"
32 #include "clang/Sema/DelayedDiagnostic.h"
33 #include "clang/Sema/Lookup.h"
34 #include "clang/Sema/ParsedTemplate.h"
35 #include "clang/Sema/ScopeInfo.h"
36 #include "clang/Sema/SemaInternal.h"
37 #include "clang/Sema/Template.h"
38 #include "clang/Sema/TemplateInstCallback.h"
39 #include "llvm/ADT/ArrayRef.h"
40 #include "llvm/ADT/SmallPtrSet.h"
41 #include "llvm/ADT/SmallString.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include "llvm/IR/DerivedTypes.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include <bitset>
47 #include <optional>
49 using namespace clang;
51 enum TypeDiagSelector {
52 TDS_Function,
53 TDS_Pointer,
54 TDS_ObjCObjOrBlock
57 /// isOmittedBlockReturnType - Return true if this declarator is missing a
58 /// return type because this is a omitted return type on a block literal.
59 static bool isOmittedBlockReturnType(const Declarator &D) {
60 if (D.getContext() != DeclaratorContext::BlockLiteral ||
61 D.getDeclSpec().hasTypeSpecifier())
62 return false;
64 if (D.getNumTypeObjects() == 0)
65 return true; // ^{ ... }
67 if (D.getNumTypeObjects() == 1 &&
68 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
69 return true; // ^(int X, float Y) { ... }
71 return false;
74 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
75 /// doesn't apply to the given type.
76 static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
77 QualType type) {
78 TypeDiagSelector WhichType;
79 bool useExpansionLoc = true;
80 switch (attr.getKind()) {
81 case ParsedAttr::AT_ObjCGC:
82 WhichType = TDS_Pointer;
83 break;
84 case ParsedAttr::AT_ObjCOwnership:
85 WhichType = TDS_ObjCObjOrBlock;
86 break;
87 default:
88 // Assume everything else was a function attribute.
89 WhichType = TDS_Function;
90 useExpansionLoc = false;
91 break;
94 SourceLocation loc = attr.getLoc();
95 StringRef name = attr.getAttrName()->getName();
97 // The GC attributes are usually written with macros; special-case them.
98 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
99 : nullptr;
100 if (useExpansionLoc && loc.isMacroID() && II) {
101 if (II->isStr("strong")) {
102 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
103 } else if (II->isStr("weak")) {
104 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
108 S.Diag(loc, attr.isRegularKeywordAttribute()
109 ? diag::err_type_attribute_wrong_type
110 : diag::warn_type_attribute_wrong_type)
111 << name << WhichType << type;
114 // objc_gc applies to Objective-C pointers or, otherwise, to the
115 // smallest available pointer type (i.e. 'void*' in 'void**').
116 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
117 case ParsedAttr::AT_ObjCGC: \
118 case ParsedAttr::AT_ObjCOwnership
120 // Calling convention attributes.
121 #define CALLING_CONV_ATTRS_CASELIST \
122 case ParsedAttr::AT_CDecl: \
123 case ParsedAttr::AT_FastCall: \
124 case ParsedAttr::AT_StdCall: \
125 case ParsedAttr::AT_ThisCall: \
126 case ParsedAttr::AT_RegCall: \
127 case ParsedAttr::AT_Pascal: \
128 case ParsedAttr::AT_SwiftCall: \
129 case ParsedAttr::AT_SwiftAsyncCall: \
130 case ParsedAttr::AT_VectorCall: \
131 case ParsedAttr::AT_AArch64VectorPcs: \
132 case ParsedAttr::AT_AArch64SVEPcs: \
133 case ParsedAttr::AT_AMDGPUKernelCall: \
134 case ParsedAttr::AT_MSABI: \
135 case ParsedAttr::AT_SysVABI: \
136 case ParsedAttr::AT_Pcs: \
137 case ParsedAttr::AT_IntelOclBicc: \
138 case ParsedAttr::AT_PreserveMost: \
139 case ParsedAttr::AT_PreserveAll: \
140 case ParsedAttr::AT_M68kRTD
142 // Function type attributes.
143 #define FUNCTION_TYPE_ATTRS_CASELIST \
144 case ParsedAttr::AT_NSReturnsRetained: \
145 case ParsedAttr::AT_NoReturn: \
146 case ParsedAttr::AT_Regparm: \
147 case ParsedAttr::AT_CmseNSCall: \
148 case ParsedAttr::AT_ArmStreaming: \
149 case ParsedAttr::AT_ArmStreamingCompatible: \
150 case ParsedAttr::AT_ArmSharedZA: \
151 case ParsedAttr::AT_ArmPreservesZA: \
152 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
153 case ParsedAttr::AT_AnyX86NoCfCheck: \
154 CALLING_CONV_ATTRS_CASELIST
156 // Microsoft-specific type qualifiers.
157 #define MS_TYPE_ATTRS_CASELIST \
158 case ParsedAttr::AT_Ptr32: \
159 case ParsedAttr::AT_Ptr64: \
160 case ParsedAttr::AT_SPtr: \
161 case ParsedAttr::AT_UPtr
163 // Nullability qualifiers.
164 #define NULLABILITY_TYPE_ATTRS_CASELIST \
165 case ParsedAttr::AT_TypeNonNull: \
166 case ParsedAttr::AT_TypeNullable: \
167 case ParsedAttr::AT_TypeNullableResult: \
168 case ParsedAttr::AT_TypeNullUnspecified
170 namespace {
171 /// An object which stores processing state for the entire
172 /// GetTypeForDeclarator process.
173 class TypeProcessingState {
174 Sema &sema;
176 /// The declarator being processed.
177 Declarator &declarator;
179 /// The index of the declarator chunk we're currently processing.
180 /// May be the total number of valid chunks, indicating the
181 /// DeclSpec.
182 unsigned chunkIndex;
184 /// The original set of attributes on the DeclSpec.
185 SmallVector<ParsedAttr *, 2> savedAttrs;
187 /// A list of attributes to diagnose the uselessness of when the
188 /// processing is complete.
189 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
191 /// Attributes corresponding to AttributedTypeLocs that we have not yet
192 /// populated.
193 // FIXME: The two-phase mechanism by which we construct Types and fill
194 // their TypeLocs makes it hard to correctly assign these. We keep the
195 // attributes in creation order as an attempt to make them line up
196 // properly.
197 using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
198 SmallVector<TypeAttrPair, 8> AttrsForTypes;
199 bool AttrsForTypesSorted = true;
201 /// MacroQualifiedTypes mapping to macro expansion locations that will be
202 /// stored in a MacroQualifiedTypeLoc.
203 llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
205 /// Flag to indicate we parsed a noderef attribute. This is used for
206 /// validating that noderef was used on a pointer or array.
207 bool parsedNoDeref;
209 public:
210 TypeProcessingState(Sema &sema, Declarator &declarator)
211 : sema(sema), declarator(declarator),
212 chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false) {}
214 Sema &getSema() const {
215 return sema;
218 Declarator &getDeclarator() const {
219 return declarator;
222 bool isProcessingDeclSpec() const {
223 return chunkIndex == declarator.getNumTypeObjects();
226 unsigned getCurrentChunkIndex() const {
227 return chunkIndex;
230 void setCurrentChunkIndex(unsigned idx) {
231 assert(idx <= declarator.getNumTypeObjects());
232 chunkIndex = idx;
235 ParsedAttributesView &getCurrentAttributes() const {
236 if (isProcessingDeclSpec())
237 return getMutableDeclSpec().getAttributes();
238 return declarator.getTypeObject(chunkIndex).getAttrs();
241 /// Save the current set of attributes on the DeclSpec.
242 void saveDeclSpecAttrs() {
243 // Don't try to save them multiple times.
244 if (!savedAttrs.empty())
245 return;
247 DeclSpec &spec = getMutableDeclSpec();
248 llvm::append_range(savedAttrs,
249 llvm::make_pointer_range(spec.getAttributes()));
252 /// Record that we had nowhere to put the given type attribute.
253 /// We will diagnose such attributes later.
254 void addIgnoredTypeAttr(ParsedAttr &attr) {
255 ignoredTypeAttrs.push_back(&attr);
258 /// Diagnose all the ignored type attributes, given that the
259 /// declarator worked out to the given type.
260 void diagnoseIgnoredTypeAttrs(QualType type) const {
261 for (auto *Attr : ignoredTypeAttrs)
262 diagnoseBadTypeAttribute(getSema(), *Attr, type);
265 /// Get an attributed type for the given attribute, and remember the Attr
266 /// object so that we can attach it to the AttributedTypeLoc.
267 QualType getAttributedType(Attr *A, QualType ModifiedType,
268 QualType EquivType) {
269 QualType T =
270 sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType);
271 AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
272 AttrsForTypesSorted = false;
273 return T;
276 /// Get a BTFTagAttributed type for the btf_type_tag attribute.
277 QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
278 QualType WrappedType) {
279 return sema.Context.getBTFTagAttributedType(BTFAttr, WrappedType);
282 /// Completely replace the \c auto in \p TypeWithAuto by
283 /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
284 /// necessary.
285 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
286 QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
287 if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
288 // Attributed type still should be an attributed type after replacement.
289 auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
290 for (TypeAttrPair &A : AttrsForTypes) {
291 if (A.first == AttrTy)
292 A.first = NewAttrTy;
294 AttrsForTypesSorted = false;
296 return T;
299 /// Extract and remove the Attr* for a given attributed type.
300 const Attr *takeAttrForAttributedType(const AttributedType *AT) {
301 if (!AttrsForTypesSorted) {
302 llvm::stable_sort(AttrsForTypes, llvm::less_first());
303 AttrsForTypesSorted = true;
306 // FIXME: This is quadratic if we have lots of reuses of the same
307 // attributed type.
308 for (auto It = std::partition_point(
309 AttrsForTypes.begin(), AttrsForTypes.end(),
310 [=](const TypeAttrPair &A) { return A.first < AT; });
311 It != AttrsForTypes.end() && It->first == AT; ++It) {
312 if (It->second) {
313 const Attr *Result = It->second;
314 It->second = nullptr;
315 return Result;
319 llvm_unreachable("no Attr* for AttributedType*");
322 SourceLocation
323 getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
324 auto FoundLoc = LocsForMacros.find(MQT);
325 assert(FoundLoc != LocsForMacros.end() &&
326 "Unable to find macro expansion location for MacroQualifedType");
327 return FoundLoc->second;
330 void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
331 SourceLocation Loc) {
332 LocsForMacros[MQT] = Loc;
335 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
337 bool didParseNoDeref() const { return parsedNoDeref; }
339 ~TypeProcessingState() {
340 if (savedAttrs.empty())
341 return;
343 getMutableDeclSpec().getAttributes().clearListOnly();
344 for (ParsedAttr *AL : savedAttrs)
345 getMutableDeclSpec().getAttributes().addAtEnd(AL);
348 private:
349 DeclSpec &getMutableDeclSpec() const {
350 return const_cast<DeclSpec&>(declarator.getDeclSpec());
353 } // end anonymous namespace
355 static void moveAttrFromListToList(ParsedAttr &attr,
356 ParsedAttributesView &fromList,
357 ParsedAttributesView &toList) {
358 fromList.remove(&attr);
359 toList.addAtEnd(&attr);
362 /// The location of a type attribute.
363 enum TypeAttrLocation {
364 /// The attribute is in the decl-specifier-seq.
365 TAL_DeclSpec,
366 /// The attribute is part of a DeclaratorChunk.
367 TAL_DeclChunk,
368 /// The attribute is immediately after the declaration's name.
369 TAL_DeclName
372 static void
373 processTypeAttrs(TypeProcessingState &state, QualType &type,
374 TypeAttrLocation TAL, const ParsedAttributesView &attrs,
375 Sema::CUDAFunctionTarget CFT = Sema::CFT_HostDevice);
377 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
378 QualType &type,
379 Sema::CUDAFunctionTarget CFT);
381 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
382 ParsedAttr &attr, QualType &type);
384 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
385 QualType &type);
387 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
388 ParsedAttr &attr, QualType &type);
390 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
391 ParsedAttr &attr, QualType &type) {
392 if (attr.getKind() == ParsedAttr::AT_ObjCGC)
393 return handleObjCGCTypeAttr(state, attr, type);
394 assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
395 return handleObjCOwnershipTypeAttr(state, attr, type);
398 /// Given the index of a declarator chunk, check whether that chunk
399 /// directly specifies the return type of a function and, if so, find
400 /// an appropriate place for it.
402 /// \param i - a notional index which the search will start
403 /// immediately inside
405 /// \param onlyBlockPointers Whether we should only look into block
406 /// pointer types (vs. all pointer types).
407 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
408 unsigned i,
409 bool onlyBlockPointers) {
410 assert(i <= declarator.getNumTypeObjects());
412 DeclaratorChunk *result = nullptr;
414 // First, look inwards past parens for a function declarator.
415 for (; i != 0; --i) {
416 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
417 switch (fnChunk.Kind) {
418 case DeclaratorChunk::Paren:
419 continue;
421 // If we find anything except a function, bail out.
422 case DeclaratorChunk::Pointer:
423 case DeclaratorChunk::BlockPointer:
424 case DeclaratorChunk::Array:
425 case DeclaratorChunk::Reference:
426 case DeclaratorChunk::MemberPointer:
427 case DeclaratorChunk::Pipe:
428 return result;
430 // If we do find a function declarator, scan inwards from that,
431 // looking for a (block-)pointer declarator.
432 case DeclaratorChunk::Function:
433 for (--i; i != 0; --i) {
434 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
435 switch (ptrChunk.Kind) {
436 case DeclaratorChunk::Paren:
437 case DeclaratorChunk::Array:
438 case DeclaratorChunk::Function:
439 case DeclaratorChunk::Reference:
440 case DeclaratorChunk::Pipe:
441 continue;
443 case DeclaratorChunk::MemberPointer:
444 case DeclaratorChunk::Pointer:
445 if (onlyBlockPointers)
446 continue;
448 [[fallthrough]];
450 case DeclaratorChunk::BlockPointer:
451 result = &ptrChunk;
452 goto continue_outer;
454 llvm_unreachable("bad declarator chunk kind");
457 // If we run out of declarators doing that, we're done.
458 return result;
460 llvm_unreachable("bad declarator chunk kind");
462 // Okay, reconsider from our new point.
463 continue_outer: ;
466 // Ran out of chunks, bail out.
467 return result;
470 /// Given that an objc_gc attribute was written somewhere on a
471 /// declaration *other* than on the declarator itself (for which, use
472 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
473 /// didn't apply in whatever position it was written in, try to move
474 /// it to a more appropriate position.
475 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
476 ParsedAttr &attr, QualType type) {
477 Declarator &declarator = state.getDeclarator();
479 // Move it to the outermost normal or block pointer declarator.
480 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
481 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
482 switch (chunk.Kind) {
483 case DeclaratorChunk::Pointer:
484 case DeclaratorChunk::BlockPointer: {
485 // But don't move an ARC ownership attribute to the return type
486 // of a block.
487 DeclaratorChunk *destChunk = nullptr;
488 if (state.isProcessingDeclSpec() &&
489 attr.getKind() == ParsedAttr::AT_ObjCOwnership)
490 destChunk = maybeMovePastReturnType(declarator, i - 1,
491 /*onlyBlockPointers=*/true);
492 if (!destChunk) destChunk = &chunk;
494 moveAttrFromListToList(attr, state.getCurrentAttributes(),
495 destChunk->getAttrs());
496 return;
499 case DeclaratorChunk::Paren:
500 case DeclaratorChunk::Array:
501 continue;
503 // We may be starting at the return type of a block.
504 case DeclaratorChunk::Function:
505 if (state.isProcessingDeclSpec() &&
506 attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
507 if (DeclaratorChunk *dest = maybeMovePastReturnType(
508 declarator, i,
509 /*onlyBlockPointers=*/true)) {
510 moveAttrFromListToList(attr, state.getCurrentAttributes(),
511 dest->getAttrs());
512 return;
515 goto error;
517 // Don't walk through these.
518 case DeclaratorChunk::Reference:
519 case DeclaratorChunk::MemberPointer:
520 case DeclaratorChunk::Pipe:
521 goto error;
524 error:
526 diagnoseBadTypeAttribute(state.getSema(), attr, type);
529 /// Distribute an objc_gc type attribute that was written on the
530 /// declarator.
531 static void distributeObjCPointerTypeAttrFromDeclarator(
532 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
533 Declarator &declarator = state.getDeclarator();
535 // objc_gc goes on the innermost pointer to something that's not a
536 // pointer.
537 unsigned innermost = -1U;
538 bool considerDeclSpec = true;
539 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
540 DeclaratorChunk &chunk = declarator.getTypeObject(i);
541 switch (chunk.Kind) {
542 case DeclaratorChunk::Pointer:
543 case DeclaratorChunk::BlockPointer:
544 innermost = i;
545 continue;
547 case DeclaratorChunk::Reference:
548 case DeclaratorChunk::MemberPointer:
549 case DeclaratorChunk::Paren:
550 case DeclaratorChunk::Array:
551 case DeclaratorChunk::Pipe:
552 continue;
554 case DeclaratorChunk::Function:
555 considerDeclSpec = false;
556 goto done;
559 done:
561 // That might actually be the decl spec if we weren't blocked by
562 // anything in the declarator.
563 if (considerDeclSpec) {
564 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
565 // Splice the attribute into the decl spec. Prevents the
566 // attribute from being applied multiple times and gives
567 // the source-location-filler something to work with.
568 state.saveDeclSpecAttrs();
569 declarator.getMutableDeclSpec().getAttributes().takeOneFrom(
570 declarator.getAttributes(), &attr);
571 return;
575 // Otherwise, if we found an appropriate chunk, splice the attribute
576 // into it.
577 if (innermost != -1U) {
578 moveAttrFromListToList(attr, declarator.getAttributes(),
579 declarator.getTypeObject(innermost).getAttrs());
580 return;
583 // Otherwise, diagnose when we're done building the type.
584 declarator.getAttributes().remove(&attr);
585 state.addIgnoredTypeAttr(attr);
588 /// A function type attribute was written somewhere in a declaration
589 /// *other* than on the declarator itself or in the decl spec. Given
590 /// that it didn't apply in whatever position it was written in, try
591 /// to move it to a more appropriate position.
592 static void distributeFunctionTypeAttr(TypeProcessingState &state,
593 ParsedAttr &attr, QualType type) {
594 Declarator &declarator = state.getDeclarator();
596 // Try to push the attribute from the return type of a function to
597 // the function itself.
598 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
599 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
600 switch (chunk.Kind) {
601 case DeclaratorChunk::Function:
602 moveAttrFromListToList(attr, state.getCurrentAttributes(),
603 chunk.getAttrs());
604 return;
606 case DeclaratorChunk::Paren:
607 case DeclaratorChunk::Pointer:
608 case DeclaratorChunk::BlockPointer:
609 case DeclaratorChunk::Array:
610 case DeclaratorChunk::Reference:
611 case DeclaratorChunk::MemberPointer:
612 case DeclaratorChunk::Pipe:
613 continue;
617 diagnoseBadTypeAttribute(state.getSema(), attr, type);
620 /// Try to distribute a function type attribute to the innermost
621 /// function chunk or type. Returns true if the attribute was
622 /// distributed, false if no location was found.
623 static bool distributeFunctionTypeAttrToInnermost(
624 TypeProcessingState &state, ParsedAttr &attr,
625 ParsedAttributesView &attrList, QualType &declSpecType,
626 Sema::CUDAFunctionTarget CFT) {
627 Declarator &declarator = state.getDeclarator();
629 // Put it on the innermost function chunk, if there is one.
630 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
631 DeclaratorChunk &chunk = declarator.getTypeObject(i);
632 if (chunk.Kind != DeclaratorChunk::Function) continue;
634 moveAttrFromListToList(attr, attrList, chunk.getAttrs());
635 return true;
638 return handleFunctionTypeAttr(state, attr, declSpecType, CFT);
641 /// A function type attribute was written in the decl spec. Try to
642 /// apply it somewhere.
643 static void
644 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
645 ParsedAttr &attr, QualType &declSpecType,
646 Sema::CUDAFunctionTarget CFT) {
647 state.saveDeclSpecAttrs();
649 // Try to distribute to the innermost.
650 if (distributeFunctionTypeAttrToInnermost(
651 state, attr, state.getCurrentAttributes(), declSpecType, CFT))
652 return;
654 // If that failed, diagnose the bad attribute when the declarator is
655 // fully built.
656 state.addIgnoredTypeAttr(attr);
659 /// A function type attribute was written on the declarator or declaration.
660 /// Try to apply it somewhere.
661 /// `Attrs` is the attribute list containing the declaration (either of the
662 /// declarator or the declaration).
663 static void distributeFunctionTypeAttrFromDeclarator(
664 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType,
665 Sema::CUDAFunctionTarget CFT) {
666 Declarator &declarator = state.getDeclarator();
668 // Try to distribute to the innermost.
669 if (distributeFunctionTypeAttrToInnermost(
670 state, attr, declarator.getAttributes(), declSpecType, CFT))
671 return;
673 // If that failed, diagnose the bad attribute when the declarator is
674 // fully built.
675 declarator.getAttributes().remove(&attr);
676 state.addIgnoredTypeAttr(attr);
679 /// Given that there are attributes written on the declarator or declaration
680 /// itself, try to distribute any type attributes to the appropriate
681 /// declarator chunk.
683 /// These are attributes like the following:
684 /// int f ATTR;
685 /// int (f ATTR)();
686 /// but not necessarily this:
687 /// int f() ATTR;
689 /// `Attrs` is the attribute list containing the declaration (either of the
690 /// declarator or the declaration).
691 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
692 QualType &declSpecType,
693 Sema::CUDAFunctionTarget CFT) {
694 // The called functions in this loop actually remove things from the current
695 // list, so iterating over the existing list isn't possible. Instead, make a
696 // non-owning copy and iterate over that.
697 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
698 for (ParsedAttr &attr : AttrsCopy) {
699 // Do not distribute [[]] attributes. They have strict rules for what
700 // they appertain to.
701 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute())
702 continue;
704 switch (attr.getKind()) {
705 OBJC_POINTER_TYPE_ATTRS_CASELIST:
706 distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType);
707 break;
709 FUNCTION_TYPE_ATTRS_CASELIST:
710 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType, CFT);
711 break;
713 MS_TYPE_ATTRS_CASELIST:
714 // Microsoft type attributes cannot go after the declarator-id.
715 continue;
717 NULLABILITY_TYPE_ATTRS_CASELIST:
718 // Nullability specifiers cannot go after the declarator-id.
720 // Objective-C __kindof does not get distributed.
721 case ParsedAttr::AT_ObjCKindOf:
722 continue;
724 default:
725 break;
730 /// Add a synthetic '()' to a block-literal declarator if it is
731 /// required, given the return type.
732 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
733 QualType declSpecType) {
734 Declarator &declarator = state.getDeclarator();
736 // First, check whether the declarator would produce a function,
737 // i.e. whether the innermost semantic chunk is a function.
738 if (declarator.isFunctionDeclarator()) {
739 // If so, make that declarator a prototyped declarator.
740 declarator.getFunctionTypeInfo().hasPrototype = true;
741 return;
744 // If there are any type objects, the type as written won't name a
745 // function, regardless of the decl spec type. This is because a
746 // block signature declarator is always an abstract-declarator, and
747 // abstract-declarators can't just be parentheses chunks. Therefore
748 // we need to build a function chunk unless there are no type
749 // objects and the decl spec type is a function.
750 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
751 return;
753 // Note that there *are* cases with invalid declarators where
754 // declarators consist solely of parentheses. In general, these
755 // occur only in failed efforts to make function declarators, so
756 // faking up the function chunk is still the right thing to do.
758 // Otherwise, we need to fake up a function declarator.
759 SourceLocation loc = declarator.getBeginLoc();
761 // ...and *prepend* it to the declarator.
762 SourceLocation NoLoc;
763 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
764 /*HasProto=*/true,
765 /*IsAmbiguous=*/false,
766 /*LParenLoc=*/NoLoc,
767 /*ArgInfo=*/nullptr,
768 /*NumParams=*/0,
769 /*EllipsisLoc=*/NoLoc,
770 /*RParenLoc=*/NoLoc,
771 /*RefQualifierIsLvalueRef=*/true,
772 /*RefQualifierLoc=*/NoLoc,
773 /*MutableLoc=*/NoLoc, EST_None,
774 /*ESpecRange=*/SourceRange(),
775 /*Exceptions=*/nullptr,
776 /*ExceptionRanges=*/nullptr,
777 /*NumExceptions=*/0,
778 /*NoexceptExpr=*/nullptr,
779 /*ExceptionSpecTokens=*/nullptr,
780 /*DeclsInPrototype=*/std::nullopt, loc, loc, declarator));
782 // For consistency, make sure the state still has us as processing
783 // the decl spec.
784 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
785 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
788 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
789 unsigned &TypeQuals,
790 QualType TypeSoFar,
791 unsigned RemoveTQs,
792 unsigned DiagID) {
793 // If this occurs outside a template instantiation, warn the user about
794 // it; they probably didn't mean to specify a redundant qualifier.
795 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
796 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
797 QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
798 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
799 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
800 if (!(RemoveTQs & Qual.first))
801 continue;
803 if (!S.inTemplateInstantiation()) {
804 if (TypeQuals & Qual.first)
805 S.Diag(Qual.second, DiagID)
806 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
807 << FixItHint::CreateRemoval(Qual.second);
810 TypeQuals &= ~Qual.first;
814 /// Return true if this is omitted block return type. Also check type
815 /// attributes and type qualifiers when returning true.
816 static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
817 QualType Result) {
818 if (!isOmittedBlockReturnType(declarator))
819 return false;
821 // Warn if we see type attributes for omitted return type on a block literal.
822 SmallVector<ParsedAttr *, 2> ToBeRemoved;
823 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
824 if (AL.isInvalid() || !AL.isTypeAttr())
825 continue;
826 S.Diag(AL.getLoc(),
827 diag::warn_block_literal_attributes_on_omitted_return_type)
828 << AL;
829 ToBeRemoved.push_back(&AL);
831 // Remove bad attributes from the list.
832 for (ParsedAttr *AL : ToBeRemoved)
833 declarator.getMutableDeclSpec().getAttributes().remove(AL);
835 // Warn if we see type qualifiers for omitted return type on a block literal.
836 const DeclSpec &DS = declarator.getDeclSpec();
837 unsigned TypeQuals = DS.getTypeQualifiers();
838 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
839 diag::warn_block_literal_qualifiers_on_omitted_return_type);
840 declarator.getMutableDeclSpec().ClearTypeQualifiers();
842 return true;
845 /// Apply Objective-C type arguments to the given type.
846 static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
847 ArrayRef<TypeSourceInfo *> typeArgs,
848 SourceRange typeArgsRange, bool failOnError,
849 bool rebuilding) {
850 // We can only apply type arguments to an Objective-C class type.
851 const auto *objcObjectType = type->getAs<ObjCObjectType>();
852 if (!objcObjectType || !objcObjectType->getInterface()) {
853 S.Diag(loc, diag::err_objc_type_args_non_class)
854 << type
855 << typeArgsRange;
857 if (failOnError)
858 return QualType();
859 return type;
862 // The class type must be parameterized.
863 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
864 ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
865 if (!typeParams) {
866 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
867 << objcClass->getDeclName()
868 << FixItHint::CreateRemoval(typeArgsRange);
870 if (failOnError)
871 return QualType();
873 return type;
876 // The type must not already be specialized.
877 if (objcObjectType->isSpecialized()) {
878 S.Diag(loc, diag::err_objc_type_args_specialized_class)
879 << type
880 << FixItHint::CreateRemoval(typeArgsRange);
882 if (failOnError)
883 return QualType();
885 return type;
888 // Check the type arguments.
889 SmallVector<QualType, 4> finalTypeArgs;
890 unsigned numTypeParams = typeParams->size();
891 bool anyPackExpansions = false;
892 for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
893 TypeSourceInfo *typeArgInfo = typeArgs[i];
894 QualType typeArg = typeArgInfo->getType();
896 // Type arguments cannot have explicit qualifiers or nullability.
897 // We ignore indirect sources of these, e.g. behind typedefs or
898 // template arguments.
899 if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
900 bool diagnosed = false;
901 SourceRange rangeToRemove;
902 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
903 rangeToRemove = attr.getLocalSourceRange();
904 if (attr.getTypePtr()->getImmediateNullability()) {
905 typeArg = attr.getTypePtr()->getModifiedType();
906 S.Diag(attr.getBeginLoc(),
907 diag::err_objc_type_arg_explicit_nullability)
908 << typeArg << FixItHint::CreateRemoval(rangeToRemove);
909 diagnosed = true;
913 // When rebuilding, qualifiers might have gotten here through a
914 // final substitution.
915 if (!rebuilding && !diagnosed) {
916 S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified)
917 << typeArg << typeArg.getQualifiers().getAsString()
918 << FixItHint::CreateRemoval(rangeToRemove);
922 // Remove qualifiers even if they're non-local.
923 typeArg = typeArg.getUnqualifiedType();
925 finalTypeArgs.push_back(typeArg);
927 if (typeArg->getAs<PackExpansionType>())
928 anyPackExpansions = true;
930 // Find the corresponding type parameter, if there is one.
931 ObjCTypeParamDecl *typeParam = nullptr;
932 if (!anyPackExpansions) {
933 if (i < numTypeParams) {
934 typeParam = typeParams->begin()[i];
935 } else {
936 // Too many arguments.
937 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
938 << false
939 << objcClass->getDeclName()
940 << (unsigned)typeArgs.size()
941 << numTypeParams;
942 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
943 << objcClass;
945 if (failOnError)
946 return QualType();
948 return type;
952 // Objective-C object pointer types must be substitutable for the bounds.
953 if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
954 // If we don't have a type parameter to match against, assume
955 // everything is fine. There was a prior pack expansion that
956 // means we won't be able to match anything.
957 if (!typeParam) {
958 assert(anyPackExpansions && "Too many arguments?");
959 continue;
962 // Retrieve the bound.
963 QualType bound = typeParam->getUnderlyingType();
964 const auto *boundObjC = bound->castAs<ObjCObjectPointerType>();
966 // Determine whether the type argument is substitutable for the bound.
967 if (typeArgObjC->isObjCIdType()) {
968 // When the type argument is 'id', the only acceptable type
969 // parameter bound is 'id'.
970 if (boundObjC->isObjCIdType())
971 continue;
972 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
973 // Otherwise, we follow the assignability rules.
974 continue;
977 // Diagnose the mismatch.
978 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
979 diag::err_objc_type_arg_does_not_match_bound)
980 << typeArg << bound << typeParam->getDeclName();
981 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
982 << typeParam->getDeclName();
984 if (failOnError)
985 return QualType();
987 return type;
990 // Block pointer types are permitted for unqualified 'id' bounds.
991 if (typeArg->isBlockPointerType()) {
992 // If we don't have a type parameter to match against, assume
993 // everything is fine. There was a prior pack expansion that
994 // means we won't be able to match anything.
995 if (!typeParam) {
996 assert(anyPackExpansions && "Too many arguments?");
997 continue;
1000 // Retrieve the bound.
1001 QualType bound = typeParam->getUnderlyingType();
1002 if (bound->isBlockCompatibleObjCPointerType(S.Context))
1003 continue;
1005 // Diagnose the mismatch.
1006 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
1007 diag::err_objc_type_arg_does_not_match_bound)
1008 << typeArg << bound << typeParam->getDeclName();
1009 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
1010 << typeParam->getDeclName();
1012 if (failOnError)
1013 return QualType();
1015 return type;
1018 // Dependent types will be checked at instantiation time.
1019 if (typeArg->isDependentType()) {
1020 continue;
1023 // Diagnose non-id-compatible type arguments.
1024 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
1025 diag::err_objc_type_arg_not_id_compatible)
1026 << typeArg << typeArgInfo->getTypeLoc().getSourceRange();
1028 if (failOnError)
1029 return QualType();
1031 return type;
1034 // Make sure we didn't have the wrong number of arguments.
1035 if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
1036 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
1037 << (typeArgs.size() < typeParams->size())
1038 << objcClass->getDeclName()
1039 << (unsigned)finalTypeArgs.size()
1040 << (unsigned)numTypeParams;
1041 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
1042 << objcClass;
1044 if (failOnError)
1045 return QualType();
1047 return type;
1050 // Success. Form the specialized type.
1051 return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1054 QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1055 SourceLocation ProtocolLAngleLoc,
1056 ArrayRef<ObjCProtocolDecl *> Protocols,
1057 ArrayRef<SourceLocation> ProtocolLocs,
1058 SourceLocation ProtocolRAngleLoc,
1059 bool FailOnError) {
1060 QualType Result = QualType(Decl->getTypeForDecl(), 0);
1061 if (!Protocols.empty()) {
1062 bool HasError;
1063 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1064 HasError);
1065 if (HasError) {
1066 Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1067 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1068 if (FailOnError) Result = QualType();
1070 if (FailOnError && Result.isNull())
1071 return QualType();
1074 return Result;
1077 QualType Sema::BuildObjCObjectType(
1078 QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc,
1079 ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc,
1080 SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols,
1081 ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc,
1082 bool FailOnError, bool Rebuilding) {
1083 QualType Result = BaseType;
1084 if (!TypeArgs.empty()) {
1085 Result =
1086 applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1087 SourceRange(TypeArgsLAngleLoc, TypeArgsRAngleLoc),
1088 FailOnError, Rebuilding);
1089 if (FailOnError && Result.isNull())
1090 return QualType();
1093 if (!Protocols.empty()) {
1094 bool HasError;
1095 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1096 HasError);
1097 if (HasError) {
1098 Diag(Loc, diag::err_invalid_protocol_qualifiers)
1099 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1100 if (FailOnError) Result = QualType();
1102 if (FailOnError && Result.isNull())
1103 return QualType();
1106 return Result;
1109 TypeResult Sema::actOnObjCProtocolQualifierType(
1110 SourceLocation lAngleLoc,
1111 ArrayRef<Decl *> protocols,
1112 ArrayRef<SourceLocation> protocolLocs,
1113 SourceLocation rAngleLoc) {
1114 // Form id<protocol-list>.
1115 QualType Result = Context.getObjCObjectType(
1116 Context.ObjCBuiltinIdTy, {},
1117 llvm::ArrayRef((ObjCProtocolDecl *const *)protocols.data(),
1118 protocols.size()),
1119 false);
1120 Result = Context.getObjCObjectPointerType(Result);
1122 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1123 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1125 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1126 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1128 auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1129 .castAs<ObjCObjectTypeLoc>();
1130 ObjCObjectTL.setHasBaseTypeAsWritten(false);
1131 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1133 // No type arguments.
1134 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1135 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1137 // Fill in protocol qualifiers.
1138 ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1139 ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1140 for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1141 ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1143 // We're done. Return the completed type to the parser.
1144 return CreateParsedType(Result, ResultTInfo);
1147 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1148 Scope *S,
1149 SourceLocation Loc,
1150 ParsedType BaseType,
1151 SourceLocation TypeArgsLAngleLoc,
1152 ArrayRef<ParsedType> TypeArgs,
1153 SourceLocation TypeArgsRAngleLoc,
1154 SourceLocation ProtocolLAngleLoc,
1155 ArrayRef<Decl *> Protocols,
1156 ArrayRef<SourceLocation> ProtocolLocs,
1157 SourceLocation ProtocolRAngleLoc) {
1158 TypeSourceInfo *BaseTypeInfo = nullptr;
1159 QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1160 if (T.isNull())
1161 return true;
1163 // Handle missing type-source info.
1164 if (!BaseTypeInfo)
1165 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1167 // Extract type arguments.
1168 SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1169 for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1170 TypeSourceInfo *TypeArgInfo = nullptr;
1171 QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1172 if (TypeArg.isNull()) {
1173 ActualTypeArgInfos.clear();
1174 break;
1177 assert(TypeArgInfo && "No type source info?");
1178 ActualTypeArgInfos.push_back(TypeArgInfo);
1181 // Build the object type.
1182 QualType Result = BuildObjCObjectType(
1183 T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1184 TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1185 ProtocolLAngleLoc,
1186 llvm::ArrayRef((ObjCProtocolDecl *const *)Protocols.data(),
1187 Protocols.size()),
1188 ProtocolLocs, ProtocolRAngleLoc,
1189 /*FailOnError=*/false,
1190 /*Rebuilding=*/false);
1192 if (Result == T)
1193 return BaseType;
1195 // Create source information for this type.
1196 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1197 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1199 // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1200 // object pointer type. Fill in source information for it.
1201 if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1202 // The '*' is implicit.
1203 ObjCObjectPointerTL.setStarLoc(SourceLocation());
1204 ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1207 if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1208 // Protocol qualifier information.
1209 if (OTPTL.getNumProtocols() > 0) {
1210 assert(OTPTL.getNumProtocols() == Protocols.size());
1211 OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1212 OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1213 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1214 OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1217 // We're done. Return the completed type to the parser.
1218 return CreateParsedType(Result, ResultTInfo);
1221 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1223 // Type argument information.
1224 if (ObjCObjectTL.getNumTypeArgs() > 0) {
1225 assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1226 ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1227 ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1228 for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1229 ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1230 } else {
1231 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1232 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1235 // Protocol qualifier information.
1236 if (ObjCObjectTL.getNumProtocols() > 0) {
1237 assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1238 ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1239 ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1240 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1241 ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1242 } else {
1243 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1244 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1247 // Base type.
1248 ObjCObjectTL.setHasBaseTypeAsWritten(true);
1249 if (ObjCObjectTL.getType() == T)
1250 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1251 else
1252 ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1254 // We're done. Return the completed type to the parser.
1255 return CreateParsedType(Result, ResultTInfo);
1258 static OpenCLAccessAttr::Spelling
1259 getImageAccess(const ParsedAttributesView &Attrs) {
1260 for (const ParsedAttr &AL : Attrs)
1261 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
1262 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
1263 return OpenCLAccessAttr::Keyword_read_only;
1266 static UnaryTransformType::UTTKind
1267 TSTToUnaryTransformType(DeclSpec::TST SwitchTST) {
1268 switch (SwitchTST) {
1269 #define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
1270 case TST_##Trait: \
1271 return UnaryTransformType::Enum;
1272 #include "clang/Basic/TransformTypeTraits.def"
1273 default:
1274 llvm_unreachable("attempted to parse a non-unary transform builtin");
1278 /// Convert the specified declspec to the appropriate type
1279 /// object.
1280 /// \param state Specifies the declarator containing the declaration specifier
1281 /// to be converted, along with other associated processing state.
1282 /// \returns The type described by the declaration specifiers. This function
1283 /// never returns null.
1284 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1285 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1286 // checking.
1288 Sema &S = state.getSema();
1289 Declarator &declarator = state.getDeclarator();
1290 DeclSpec &DS = declarator.getMutableDeclSpec();
1291 SourceLocation DeclLoc = declarator.getIdentifierLoc();
1292 if (DeclLoc.isInvalid())
1293 DeclLoc = DS.getBeginLoc();
1295 ASTContext &Context = S.Context;
1297 QualType Result;
1298 switch (DS.getTypeSpecType()) {
1299 case DeclSpec::TST_void:
1300 Result = Context.VoidTy;
1301 break;
1302 case DeclSpec::TST_char:
1303 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1304 Result = Context.CharTy;
1305 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed)
1306 Result = Context.SignedCharTy;
1307 else {
1308 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
1309 "Unknown TSS value");
1310 Result = Context.UnsignedCharTy;
1312 break;
1313 case DeclSpec::TST_wchar:
1314 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1315 Result = Context.WCharTy;
1316 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) {
1317 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1318 << DS.getSpecifierName(DS.getTypeSpecType(),
1319 Context.getPrintingPolicy());
1320 Result = Context.getSignedWCharType();
1321 } else {
1322 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
1323 "Unknown TSS value");
1324 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1325 << DS.getSpecifierName(DS.getTypeSpecType(),
1326 Context.getPrintingPolicy());
1327 Result = Context.getUnsignedWCharType();
1329 break;
1330 case DeclSpec::TST_char8:
1331 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1332 "Unknown TSS value");
1333 Result = Context.Char8Ty;
1334 break;
1335 case DeclSpec::TST_char16:
1336 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1337 "Unknown TSS value");
1338 Result = Context.Char16Ty;
1339 break;
1340 case DeclSpec::TST_char32:
1341 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1342 "Unknown TSS value");
1343 Result = Context.Char32Ty;
1344 break;
1345 case DeclSpec::TST_unspecified:
1346 // If this is a missing declspec in a block literal return context, then it
1347 // is inferred from the return statements inside the block.
1348 // The declspec is always missing in a lambda expr context; it is either
1349 // specified with a trailing return type or inferred.
1350 if (S.getLangOpts().CPlusPlus14 &&
1351 declarator.getContext() == DeclaratorContext::LambdaExpr) {
1352 // In C++1y, a lambda's implicit return type is 'auto'.
1353 Result = Context.getAutoDeductType();
1354 break;
1355 } else if (declarator.getContext() == DeclaratorContext::LambdaExpr ||
1356 checkOmittedBlockReturnType(S, declarator,
1357 Context.DependentTy)) {
1358 Result = Context.DependentTy;
1359 break;
1362 // Unspecified typespec defaults to int in C90. However, the C90 grammar
1363 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1364 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
1365 // Note that the one exception to this is function definitions, which are
1366 // allowed to be completely missing a declspec. This is handled in the
1367 // parser already though by it pretending to have seen an 'int' in this
1368 // case.
1369 if (S.getLangOpts().isImplicitIntRequired()) {
1370 S.Diag(DeclLoc, diag::warn_missing_type_specifier)
1371 << DS.getSourceRange()
1372 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1373 } else if (!DS.hasTypeSpecifier()) {
1374 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1375 // "At least one type specifier shall be given in the declaration
1376 // specifiers in each declaration, and in the specifier-qualifier list in
1377 // each struct declaration and type name."
1378 if (!S.getLangOpts().isImplicitIntAllowed() && !DS.isTypeSpecPipe()) {
1379 S.Diag(DeclLoc, diag::err_missing_type_specifier)
1380 << DS.getSourceRange();
1382 // When this occurs, often something is very broken with the value
1383 // being declared, poison it as invalid so we don't get chains of
1384 // errors.
1385 declarator.setInvalidType(true);
1386 } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 &&
1387 DS.isTypeSpecPipe()) {
1388 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1389 << DS.getSourceRange();
1390 declarator.setInvalidType(true);
1391 } else {
1392 assert(S.getLangOpts().isImplicitIntAllowed() &&
1393 "implicit int is disabled?");
1394 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1395 << DS.getSourceRange()
1396 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1400 [[fallthrough]];
1401 case DeclSpec::TST_int: {
1402 if (DS.getTypeSpecSign() != TypeSpecifierSign::Unsigned) {
1403 switch (DS.getTypeSpecWidth()) {
1404 case TypeSpecifierWidth::Unspecified:
1405 Result = Context.IntTy;
1406 break;
1407 case TypeSpecifierWidth::Short:
1408 Result = Context.ShortTy;
1409 break;
1410 case TypeSpecifierWidth::Long:
1411 Result = Context.LongTy;
1412 break;
1413 case TypeSpecifierWidth::LongLong:
1414 Result = Context.LongLongTy;
1416 // 'long long' is a C99 or C++11 feature.
1417 if (!S.getLangOpts().C99) {
1418 if (S.getLangOpts().CPlusPlus)
1419 S.Diag(DS.getTypeSpecWidthLoc(),
1420 S.getLangOpts().CPlusPlus11 ?
1421 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1422 else
1423 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1425 break;
1427 } else {
1428 switch (DS.getTypeSpecWidth()) {
1429 case TypeSpecifierWidth::Unspecified:
1430 Result = Context.UnsignedIntTy;
1431 break;
1432 case TypeSpecifierWidth::Short:
1433 Result = Context.UnsignedShortTy;
1434 break;
1435 case TypeSpecifierWidth::Long:
1436 Result = Context.UnsignedLongTy;
1437 break;
1438 case TypeSpecifierWidth::LongLong:
1439 Result = Context.UnsignedLongLongTy;
1441 // 'long long' is a C99 or C++11 feature.
1442 if (!S.getLangOpts().C99) {
1443 if (S.getLangOpts().CPlusPlus)
1444 S.Diag(DS.getTypeSpecWidthLoc(),
1445 S.getLangOpts().CPlusPlus11 ?
1446 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1447 else
1448 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1450 break;
1453 break;
1455 case DeclSpec::TST_bitint: {
1456 if (!S.Context.getTargetInfo().hasBitIntType())
1457 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_BitInt";
1458 Result =
1459 S.BuildBitIntType(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned,
1460 DS.getRepAsExpr(), DS.getBeginLoc());
1461 if (Result.isNull()) {
1462 Result = Context.IntTy;
1463 declarator.setInvalidType(true);
1465 break;
1467 case DeclSpec::TST_accum: {
1468 switch (DS.getTypeSpecWidth()) {
1469 case TypeSpecifierWidth::Short:
1470 Result = Context.ShortAccumTy;
1471 break;
1472 case TypeSpecifierWidth::Unspecified:
1473 Result = Context.AccumTy;
1474 break;
1475 case TypeSpecifierWidth::Long:
1476 Result = Context.LongAccumTy;
1477 break;
1478 case TypeSpecifierWidth::LongLong:
1479 llvm_unreachable("Unable to specify long long as _Accum width");
1482 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1483 Result = Context.getCorrespondingUnsignedType(Result);
1485 if (DS.isTypeSpecSat())
1486 Result = Context.getCorrespondingSaturatedType(Result);
1488 break;
1490 case DeclSpec::TST_fract: {
1491 switch (DS.getTypeSpecWidth()) {
1492 case TypeSpecifierWidth::Short:
1493 Result = Context.ShortFractTy;
1494 break;
1495 case TypeSpecifierWidth::Unspecified:
1496 Result = Context.FractTy;
1497 break;
1498 case TypeSpecifierWidth::Long:
1499 Result = Context.LongFractTy;
1500 break;
1501 case TypeSpecifierWidth::LongLong:
1502 llvm_unreachable("Unable to specify long long as _Fract width");
1505 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1506 Result = Context.getCorrespondingUnsignedType(Result);
1508 if (DS.isTypeSpecSat())
1509 Result = Context.getCorrespondingSaturatedType(Result);
1511 break;
1513 case DeclSpec::TST_int128:
1514 if (!S.Context.getTargetInfo().hasInt128Type() &&
1515 !(S.getLangOpts().SYCLIsDevice || S.getLangOpts().CUDAIsDevice ||
1516 (S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice)))
1517 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1518 << "__int128";
1519 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1520 Result = Context.UnsignedInt128Ty;
1521 else
1522 Result = Context.Int128Ty;
1523 break;
1524 case DeclSpec::TST_float16:
1525 // CUDA host and device may have different _Float16 support, therefore
1526 // do not diagnose _Float16 usage to avoid false alarm.
1527 // ToDo: more precise diagnostics for CUDA.
1528 if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
1529 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1530 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1531 << "_Float16";
1532 Result = Context.Float16Ty;
1533 break;
1534 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1535 case DeclSpec::TST_BFloat16:
1536 if (!S.Context.getTargetInfo().hasBFloat16Type() &&
1537 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice) &&
1538 !S.getLangOpts().SYCLIsDevice)
1539 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__bf16";
1540 Result = Context.BFloat16Ty;
1541 break;
1542 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1543 case DeclSpec::TST_double:
1544 if (DS.getTypeSpecWidth() == TypeSpecifierWidth::Long)
1545 Result = Context.LongDoubleTy;
1546 else
1547 Result = Context.DoubleTy;
1548 if (S.getLangOpts().OpenCL) {
1549 if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts()))
1550 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1551 << 0 << Result
1552 << (S.getLangOpts().getOpenCLCompatibleVersion() == 300
1553 ? "cl_khr_fp64 and __opencl_c_fp64"
1554 : "cl_khr_fp64");
1555 else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts()))
1556 S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma);
1558 break;
1559 case DeclSpec::TST_float128:
1560 if (!S.Context.getTargetInfo().hasFloat128Type() &&
1561 !S.getLangOpts().SYCLIsDevice &&
1562 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1563 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1564 << "__float128";
1565 Result = Context.Float128Ty;
1566 break;
1567 case DeclSpec::TST_ibm128:
1568 if (!S.Context.getTargetInfo().hasIbm128Type() &&
1569 !S.getLangOpts().SYCLIsDevice &&
1570 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1571 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128";
1572 Result = Context.Ibm128Ty;
1573 break;
1574 case DeclSpec::TST_bool:
1575 Result = Context.BoolTy; // _Bool or bool
1576 break;
1577 case DeclSpec::TST_decimal32: // _Decimal32
1578 case DeclSpec::TST_decimal64: // _Decimal64
1579 case DeclSpec::TST_decimal128: // _Decimal128
1580 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1581 Result = Context.IntTy;
1582 declarator.setInvalidType(true);
1583 break;
1584 case DeclSpec::TST_class:
1585 case DeclSpec::TST_enum:
1586 case DeclSpec::TST_union:
1587 case DeclSpec::TST_struct:
1588 case DeclSpec::TST_interface: {
1589 TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1590 if (!D) {
1591 // This can happen in C++ with ambiguous lookups.
1592 Result = Context.IntTy;
1593 declarator.setInvalidType(true);
1594 break;
1597 // If the type is deprecated or unavailable, diagnose it.
1598 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1600 assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1601 DS.getTypeSpecComplex() == 0 &&
1602 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1603 "No qualifiers on tag names!");
1605 // TypeQuals handled by caller.
1606 Result = Context.getTypeDeclType(D);
1608 // In both C and C++, make an ElaboratedType.
1609 ElaboratedTypeKeyword Keyword
1610 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1611 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
1612 DS.isTypeSpecOwned() ? D : nullptr);
1613 break;
1615 case DeclSpec::TST_typename: {
1616 assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1617 DS.getTypeSpecComplex() == 0 &&
1618 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1619 "Can't handle qualifiers on typedef names yet!");
1620 Result = S.GetTypeFromParser(DS.getRepAsType());
1621 if (Result.isNull()) {
1622 declarator.setInvalidType(true);
1625 // TypeQuals handled by caller.
1626 break;
1628 case DeclSpec::TST_typeof_unqualType:
1629 case DeclSpec::TST_typeofType:
1630 // FIXME: Preserve type source info.
1631 Result = S.GetTypeFromParser(DS.getRepAsType());
1632 assert(!Result.isNull() && "Didn't get a type for typeof?");
1633 if (!Result->isDependentType())
1634 if (const TagType *TT = Result->getAs<TagType>())
1635 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1636 // TypeQuals handled by caller.
1637 Result = Context.getTypeOfType(
1638 Result, DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType
1639 ? TypeOfKind::Unqualified
1640 : TypeOfKind::Qualified);
1641 break;
1642 case DeclSpec::TST_typeof_unqualExpr:
1643 case DeclSpec::TST_typeofExpr: {
1644 Expr *E = DS.getRepAsExpr();
1645 assert(E && "Didn't get an expression for typeof?");
1646 // TypeQuals handled by caller.
1647 Result = S.BuildTypeofExprType(E, DS.getTypeSpecType() ==
1648 DeclSpec::TST_typeof_unqualExpr
1649 ? TypeOfKind::Unqualified
1650 : TypeOfKind::Qualified);
1651 if (Result.isNull()) {
1652 Result = Context.IntTy;
1653 declarator.setInvalidType(true);
1655 break;
1657 case DeclSpec::TST_decltype: {
1658 Expr *E = DS.getRepAsExpr();
1659 assert(E && "Didn't get an expression for decltype?");
1660 // TypeQuals handled by caller.
1661 Result = S.BuildDecltypeType(E);
1662 if (Result.isNull()) {
1663 Result = Context.IntTy;
1664 declarator.setInvalidType(true);
1666 break;
1668 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
1669 #include "clang/Basic/TransformTypeTraits.def"
1670 Result = S.GetTypeFromParser(DS.getRepAsType());
1671 assert(!Result.isNull() && "Didn't get a type for the transformation?");
1672 Result = S.BuildUnaryTransformType(
1673 Result, TSTToUnaryTransformType(DS.getTypeSpecType()),
1674 DS.getTypeSpecTypeLoc());
1675 if (Result.isNull()) {
1676 Result = Context.IntTy;
1677 declarator.setInvalidType(true);
1679 break;
1681 case DeclSpec::TST_auto:
1682 case DeclSpec::TST_decltype_auto: {
1683 auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1684 ? AutoTypeKeyword::DecltypeAuto
1685 : AutoTypeKeyword::Auto;
1687 ConceptDecl *TypeConstraintConcept = nullptr;
1688 llvm::SmallVector<TemplateArgument, 8> TemplateArgs;
1689 if (DS.isConstrainedAuto()) {
1690 if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1691 TypeConstraintConcept =
1692 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl());
1693 TemplateArgumentListInfo TemplateArgsInfo;
1694 TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1695 TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1696 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1697 TemplateId->NumArgs);
1698 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1699 for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1700 TemplateArgs.push_back(ArgLoc.getArgument());
1701 } else {
1702 declarator.setInvalidType(true);
1705 Result = S.Context.getAutoType(QualType(), AutoKW,
1706 /*IsDependent*/ false, /*IsPack=*/false,
1707 TypeConstraintConcept, TemplateArgs);
1708 break;
1711 case DeclSpec::TST_auto_type:
1712 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1713 break;
1715 case DeclSpec::TST_unknown_anytype:
1716 Result = Context.UnknownAnyTy;
1717 break;
1719 case DeclSpec::TST_atomic:
1720 Result = S.GetTypeFromParser(DS.getRepAsType());
1721 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1722 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1723 if (Result.isNull()) {
1724 Result = Context.IntTy;
1725 declarator.setInvalidType(true);
1727 break;
1729 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
1730 case DeclSpec::TST_##ImgType##_t: \
1731 switch (getImageAccess(DS.getAttributes())) { \
1732 case OpenCLAccessAttr::Keyword_write_only: \
1733 Result = Context.Id##WOTy; \
1734 break; \
1735 case OpenCLAccessAttr::Keyword_read_write: \
1736 Result = Context.Id##RWTy; \
1737 break; \
1738 case OpenCLAccessAttr::Keyword_read_only: \
1739 Result = Context.Id##ROTy; \
1740 break; \
1741 case OpenCLAccessAttr::SpellingNotCalculated: \
1742 llvm_unreachable("Spelling not yet calculated"); \
1744 break;
1745 #include "clang/Basic/OpenCLImageTypes.def"
1747 case DeclSpec::TST_error:
1748 Result = Context.IntTy;
1749 declarator.setInvalidType(true);
1750 break;
1753 // FIXME: we want resulting declarations to be marked invalid, but claiming
1754 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1755 // a null type.
1756 if (Result->containsErrors())
1757 declarator.setInvalidType();
1759 if (S.getLangOpts().OpenCL) {
1760 const auto &OpenCLOptions = S.getOpenCLOptions();
1761 bool IsOpenCLC30Compatible =
1762 S.getLangOpts().getOpenCLCompatibleVersion() == 300;
1763 // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1764 // support.
1765 // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1766 // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1767 // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1768 // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1769 // only when the optional feature is supported
1770 if ((Result->isImageType() || Result->isSamplerT()) &&
1771 (IsOpenCLC30Compatible &&
1772 !OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts()))) {
1773 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1774 << 0 << Result << "__opencl_c_images";
1775 declarator.setInvalidType();
1776 } else if (Result->isOCLImage3dWOType() &&
1777 !OpenCLOptions.isSupported("cl_khr_3d_image_writes",
1778 S.getLangOpts())) {
1779 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1780 << 0 << Result
1781 << (IsOpenCLC30Compatible
1782 ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes"
1783 : "cl_khr_3d_image_writes");
1784 declarator.setInvalidType();
1788 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1789 DS.getTypeSpecType() == DeclSpec::TST_fract;
1791 // Only fixed point types can be saturated
1792 if (DS.isTypeSpecSat() && !IsFixedPointType)
1793 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1794 << DS.getSpecifierName(DS.getTypeSpecType(),
1795 Context.getPrintingPolicy());
1797 // Handle complex types.
1798 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1799 if (S.getLangOpts().Freestanding)
1800 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1801 Result = Context.getComplexType(Result);
1802 } else if (DS.isTypeAltiVecVector()) {
1803 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1804 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1805 VectorKind VecKind = VectorKind::AltiVecVector;
1806 if (DS.isTypeAltiVecPixel())
1807 VecKind = VectorKind::AltiVecPixel;
1808 else if (DS.isTypeAltiVecBool())
1809 VecKind = VectorKind::AltiVecBool;
1810 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1813 // FIXME: Imaginary.
1814 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1815 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1817 // Before we process any type attributes, synthesize a block literal
1818 // function declarator if necessary.
1819 if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1820 maybeSynthesizeBlockSignature(state, Result);
1822 // Apply any type attributes from the decl spec. This may cause the
1823 // list of type attributes to be temporarily saved while the type
1824 // attributes are pushed around.
1825 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1826 if (!DS.isTypeSpecPipe()) {
1827 // We also apply declaration attributes that "slide" to the decl spec.
1828 // Ordering can be important for attributes. The decalaration attributes
1829 // come syntactically before the decl spec attributes, so we process them
1830 // in that order.
1831 ParsedAttributesView SlidingAttrs;
1832 for (ParsedAttr &AL : declarator.getDeclarationAttributes()) {
1833 if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
1834 SlidingAttrs.addAtEnd(&AL);
1836 // For standard syntax attributes, which would normally appertain to the
1837 // declaration here, suggest moving them to the type instead. But only
1838 // do this for our own vendor attributes; moving other vendors'
1839 // attributes might hurt portability.
1840 // There's one special case that we need to deal with here: The
1841 // `MatrixType` attribute may only be used in a typedef declaration. If
1842 // it's being used anywhere else, don't output the warning as
1843 // ProcessDeclAttributes() will output an error anyway.
1844 if (AL.isStandardAttributeSyntax() && AL.isClangScope() &&
1845 !(AL.getKind() == ParsedAttr::AT_MatrixType &&
1846 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)) {
1847 S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl)
1848 << AL;
1852 // During this call to processTypeAttrs(),
1853 // TypeProcessingState::getCurrentAttributes() will erroneously return a
1854 // reference to the DeclSpec attributes, rather than the declaration
1855 // attributes. However, this doesn't matter, as getCurrentAttributes()
1856 // is only called when distributing attributes from one attribute list
1857 // to another. Declaration attributes are always C++11 attributes, and these
1858 // are never distributed.
1859 processTypeAttrs(state, Result, TAL_DeclSpec, SlidingAttrs);
1860 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
1863 // Apply const/volatile/restrict qualifiers to T.
1864 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1865 // Warn about CV qualifiers on function types.
1866 // C99 6.7.3p8:
1867 // If the specification of a function type includes any type qualifiers,
1868 // the behavior is undefined.
1869 // C++11 [dcl.fct]p7:
1870 // The effect of a cv-qualifier-seq in a function declarator is not the
1871 // same as adding cv-qualification on top of the function type. In the
1872 // latter case, the cv-qualifiers are ignored.
1873 if (Result->isFunctionType()) {
1874 diagnoseAndRemoveTypeQualifiers(
1875 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1876 S.getLangOpts().CPlusPlus
1877 ? diag::warn_typecheck_function_qualifiers_ignored
1878 : diag::warn_typecheck_function_qualifiers_unspecified);
1879 // No diagnostic for 'restrict' or '_Atomic' applied to a
1880 // function type; we'll diagnose those later, in BuildQualifiedType.
1883 // C++11 [dcl.ref]p1:
1884 // Cv-qualified references are ill-formed except when the
1885 // cv-qualifiers are introduced through the use of a typedef-name
1886 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1888 // There don't appear to be any other contexts in which a cv-qualified
1889 // reference type could be formed, so the 'ill-formed' clause here appears
1890 // to never happen.
1891 if (TypeQuals && Result->isReferenceType()) {
1892 diagnoseAndRemoveTypeQualifiers(
1893 S, DS, TypeQuals, Result,
1894 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1895 diag::warn_typecheck_reference_qualifiers);
1898 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1899 // than once in the same specifier-list or qualifier-list, either directly
1900 // or via one or more typedefs."
1901 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1902 && TypeQuals & Result.getCVRQualifiers()) {
1903 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1904 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1905 << "const";
1908 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1909 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1910 << "volatile";
1913 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1914 // produce a warning in this case.
1917 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1919 // If adding qualifiers fails, just use the unqualified type.
1920 if (Qualified.isNull())
1921 declarator.setInvalidType(true);
1922 else
1923 Result = Qualified;
1926 assert(!Result.isNull() && "This function should not return a null type");
1927 return Result;
1930 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1931 if (Entity)
1932 return Entity.getAsString();
1934 return "type name";
1937 static bool isDependentOrGNUAutoType(QualType T) {
1938 if (T->isDependentType())
1939 return true;
1941 const auto *AT = dyn_cast<AutoType>(T);
1942 return AT && AT->isGNUAutoType();
1945 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1946 Qualifiers Qs, const DeclSpec *DS) {
1947 if (T.isNull())
1948 return QualType();
1950 // Ignore any attempt to form a cv-qualified reference.
1951 if (T->isReferenceType()) {
1952 Qs.removeConst();
1953 Qs.removeVolatile();
1956 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1957 // object or incomplete types shall not be restrict-qualified."
1958 if (Qs.hasRestrict()) {
1959 unsigned DiagID = 0;
1960 QualType ProblemTy;
1962 if (T->isAnyPointerType() || T->isReferenceType() ||
1963 T->isMemberPointerType()) {
1964 QualType EltTy;
1965 if (T->isObjCObjectPointerType())
1966 EltTy = T;
1967 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1968 EltTy = PTy->getPointeeType();
1969 else
1970 EltTy = T->getPointeeType();
1972 // If we have a pointer or reference, the pointee must have an object
1973 // incomplete type.
1974 if (!EltTy->isIncompleteOrObjectType()) {
1975 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1976 ProblemTy = EltTy;
1978 } else if (!isDependentOrGNUAutoType(T)) {
1979 // For an __auto_type variable, we may not have seen the initializer yet
1980 // and so have no idea whether the underlying type is a pointer type or
1981 // not.
1982 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1983 ProblemTy = T;
1986 if (DiagID) {
1987 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1988 Qs.removeRestrict();
1992 return Context.getQualifiedType(T, Qs);
1995 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1996 unsigned CVRAU, const DeclSpec *DS) {
1997 if (T.isNull())
1998 return QualType();
2000 // Ignore any attempt to form a cv-qualified reference.
2001 if (T->isReferenceType())
2002 CVRAU &=
2003 ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
2005 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
2006 // TQ_unaligned;
2007 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
2009 // C11 6.7.3/5:
2010 // If the same qualifier appears more than once in the same
2011 // specifier-qualifier-list, either directly or via one or more typedefs,
2012 // the behavior is the same as if it appeared only once.
2014 // It's not specified what happens when the _Atomic qualifier is applied to
2015 // a type specified with the _Atomic specifier, but we assume that this
2016 // should be treated as if the _Atomic qualifier appeared multiple times.
2017 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
2018 // C11 6.7.3/5:
2019 // If other qualifiers appear along with the _Atomic qualifier in a
2020 // specifier-qualifier-list, the resulting type is the so-qualified
2021 // atomic type.
2023 // Don't need to worry about array types here, since _Atomic can't be
2024 // applied to such types.
2025 SplitQualType Split = T.getSplitUnqualifiedType();
2026 T = BuildAtomicType(QualType(Split.Ty, 0),
2027 DS ? DS->getAtomicSpecLoc() : Loc);
2028 if (T.isNull())
2029 return T;
2030 Split.Quals.addCVRQualifiers(CVR);
2031 return BuildQualifiedType(T, Loc, Split.Quals);
2034 Qualifiers Q = Qualifiers::fromCVRMask(CVR);
2035 Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
2036 return BuildQualifiedType(T, Loc, Q, DS);
2039 /// Build a paren type including \p T.
2040 QualType Sema::BuildParenType(QualType T) {
2041 return Context.getParenType(T);
2044 /// Given that we're building a pointer or reference to the given
2045 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
2046 SourceLocation loc,
2047 bool isReference) {
2048 // Bail out if retention is unrequired or already specified.
2049 if (!type->isObjCLifetimeType() ||
2050 type.getObjCLifetime() != Qualifiers::OCL_None)
2051 return type;
2053 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
2055 // If the object type is const-qualified, we can safely use
2056 // __unsafe_unretained. This is safe (because there are no read
2057 // barriers), and it'll be safe to coerce anything but __weak* to
2058 // the resulting type.
2059 if (type.isConstQualified()) {
2060 implicitLifetime = Qualifiers::OCL_ExplicitNone;
2062 // Otherwise, check whether the static type does not require
2063 // retaining. This currently only triggers for Class (possibly
2064 // protocol-qualifed, and arrays thereof).
2065 } else if (type->isObjCARCImplicitlyUnretainedType()) {
2066 implicitLifetime = Qualifiers::OCL_ExplicitNone;
2068 // If we are in an unevaluated context, like sizeof, skip adding a
2069 // qualification.
2070 } else if (S.isUnevaluatedContext()) {
2071 return type;
2073 // If that failed, give an error and recover using __strong. __strong
2074 // is the option most likely to prevent spurious second-order diagnostics,
2075 // like when binding a reference to a field.
2076 } else {
2077 // These types can show up in private ivars in system headers, so
2078 // we need this to not be an error in those cases. Instead we
2079 // want to delay.
2080 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
2081 S.DelayedDiagnostics.add(
2082 sema::DelayedDiagnostic::makeForbiddenType(loc,
2083 diag::err_arc_indirect_no_ownership, type, isReference));
2084 } else {
2085 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
2087 implicitLifetime = Qualifiers::OCL_Strong;
2089 assert(implicitLifetime && "didn't infer any lifetime!");
2091 Qualifiers qs;
2092 qs.addObjCLifetime(implicitLifetime);
2093 return S.Context.getQualifiedType(type, qs);
2096 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
2097 std::string Quals = FnTy->getMethodQuals().getAsString();
2099 switch (FnTy->getRefQualifier()) {
2100 case RQ_None:
2101 break;
2103 case RQ_LValue:
2104 if (!Quals.empty())
2105 Quals += ' ';
2106 Quals += '&';
2107 break;
2109 case RQ_RValue:
2110 if (!Quals.empty())
2111 Quals += ' ';
2112 Quals += "&&";
2113 break;
2116 return Quals;
2119 namespace {
2120 /// Kinds of declarator that cannot contain a qualified function type.
2122 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
2123 /// a function type with a cv-qualifier or a ref-qualifier can only appear
2124 /// at the topmost level of a type.
2126 /// Parens and member pointers are permitted. We don't diagnose array and
2127 /// function declarators, because they don't allow function types at all.
2129 /// The values of this enum are used in diagnostics.
2130 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
2131 } // end anonymous namespace
2133 /// Check whether the type T is a qualified function type, and if it is,
2134 /// diagnose that it cannot be contained within the given kind of declarator.
2135 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
2136 QualifiedFunctionKind QFK) {
2137 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2138 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2139 if (!FPT ||
2140 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2141 return false;
2143 S.Diag(Loc, diag::err_compound_qualified_function_type)
2144 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
2145 << getFunctionQualifiersAsString(FPT);
2146 return true;
2149 bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) {
2150 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2151 if (!FPT ||
2152 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2153 return false;
2155 Diag(Loc, diag::err_qualified_function_typeid)
2156 << T << getFunctionQualifiersAsString(FPT);
2157 return true;
2160 // Helper to deduce addr space of a pointee type in OpenCL mode.
2161 static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType) {
2162 if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
2163 !PointeeType->isSamplerT() &&
2164 !PointeeType.hasAddressSpace())
2165 PointeeType = S.getASTContext().getAddrSpaceQualType(
2166 PointeeType, S.getASTContext().getDefaultOpenCLPointeeAddrSpace());
2167 return PointeeType;
2170 /// Build a pointer type.
2172 /// \param T The type to which we'll be building a pointer.
2174 /// \param Loc The location of the entity whose type involves this
2175 /// pointer type or, if there is no such entity, the location of the
2176 /// type that will have pointer type.
2178 /// \param Entity The name of the entity that involves the pointer
2179 /// type, if known.
2181 /// \returns A suitable pointer type, if there are no
2182 /// errors. Otherwise, returns a NULL type.
2183 QualType Sema::BuildPointerType(QualType T,
2184 SourceLocation Loc, DeclarationName Entity) {
2185 if (T->isReferenceType()) {
2186 // C++ 8.3.2p4: There shall be no ... pointers to references ...
2187 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
2188 << getPrintableNameForEntity(Entity) << T;
2189 return QualType();
2192 if (T->isFunctionType() && getLangOpts().OpenCL &&
2193 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2194 getLangOpts())) {
2195 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2196 return QualType();
2199 if (getLangOpts().HLSL && Loc.isValid()) {
2200 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
2201 return QualType();
2204 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
2205 return QualType();
2207 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
2209 // In ARC, it is forbidden to build pointers to unqualified pointers.
2210 if (getLangOpts().ObjCAutoRefCount)
2211 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
2213 if (getLangOpts().OpenCL)
2214 T = deduceOpenCLPointeeAddrSpace(*this, T);
2216 // In WebAssembly, pointers to reference types and pointers to tables are
2217 // illegal.
2218 if (getASTContext().getTargetInfo().getTriple().isWasm()) {
2219 if (T.isWebAssemblyReferenceType()) {
2220 Diag(Loc, diag::err_wasm_reference_pr) << 0;
2221 return QualType();
2224 // We need to desugar the type here in case T is a ParenType.
2225 if (T->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
2226 Diag(Loc, diag::err_wasm_table_pr) << 0;
2227 return QualType();
2231 // Build the pointer type.
2232 return Context.getPointerType(T);
2235 /// Build a reference type.
2237 /// \param T The type to which we'll be building a reference.
2239 /// \param Loc The location of the entity whose type involves this
2240 /// reference type or, if there is no such entity, the location of the
2241 /// type that will have reference type.
2243 /// \param Entity The name of the entity that involves the reference
2244 /// type, if known.
2246 /// \returns A suitable reference type, if there are no
2247 /// errors. Otherwise, returns a NULL type.
2248 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
2249 SourceLocation Loc,
2250 DeclarationName Entity) {
2251 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
2252 "Unresolved overloaded function type");
2254 // C++0x [dcl.ref]p6:
2255 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
2256 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
2257 // type T, an attempt to create the type "lvalue reference to cv TR" creates
2258 // the type "lvalue reference to T", while an attempt to create the type
2259 // "rvalue reference to cv TR" creates the type TR.
2260 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
2262 // C++ [dcl.ref]p4: There shall be no references to references.
2264 // According to C++ DR 106, references to references are only
2265 // diagnosed when they are written directly (e.g., "int & &"),
2266 // but not when they happen via a typedef:
2268 // typedef int& intref;
2269 // typedef intref& intref2;
2271 // Parser::ParseDeclaratorInternal diagnoses the case where
2272 // references are written directly; here, we handle the
2273 // collapsing of references-to-references as described in C++0x.
2274 // DR 106 and 540 introduce reference-collapsing into C++98/03.
2276 // C++ [dcl.ref]p1:
2277 // A declarator that specifies the type "reference to cv void"
2278 // is ill-formed.
2279 if (T->isVoidType()) {
2280 Diag(Loc, diag::err_reference_to_void);
2281 return QualType();
2284 if (getLangOpts().HLSL && Loc.isValid()) {
2285 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1;
2286 return QualType();
2289 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2290 return QualType();
2292 if (T->isFunctionType() && getLangOpts().OpenCL &&
2293 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2294 getLangOpts())) {
2295 Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1;
2296 return QualType();
2299 // In ARC, it is forbidden to build references to unqualified pointers.
2300 if (getLangOpts().ObjCAutoRefCount)
2301 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2303 if (getLangOpts().OpenCL)
2304 T = deduceOpenCLPointeeAddrSpace(*this, T);
2306 // In WebAssembly, references to reference types and tables are illegal.
2307 if (getASTContext().getTargetInfo().getTriple().isWasm() &&
2308 T.isWebAssemblyReferenceType()) {
2309 Diag(Loc, diag::err_wasm_reference_pr) << 1;
2310 return QualType();
2312 if (T->isWebAssemblyTableType()) {
2313 Diag(Loc, diag::err_wasm_table_pr) << 1;
2314 return QualType();
2317 // Handle restrict on references.
2318 if (LValueRef)
2319 return Context.getLValueReferenceType(T, SpelledAsLValue);
2320 return Context.getRValueReferenceType(T);
2323 /// Build a Read-only Pipe type.
2325 /// \param T The type to which we'll be building a Pipe.
2327 /// \param Loc We do not use it for now.
2329 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2330 /// NULL type.
2331 QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
2332 return Context.getReadPipeType(T);
2335 /// Build a Write-only Pipe type.
2337 /// \param T The type to which we'll be building a Pipe.
2339 /// \param Loc We do not use it for now.
2341 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2342 /// NULL type.
2343 QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
2344 return Context.getWritePipeType(T);
2347 /// Build a bit-precise integer type.
2349 /// \param IsUnsigned Boolean representing the signedness of the type.
2351 /// \param BitWidth Size of this int type in bits, or an expression representing
2352 /// that.
2354 /// \param Loc Location of the keyword.
2355 QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth,
2356 SourceLocation Loc) {
2357 if (BitWidth->isInstantiationDependent())
2358 return Context.getDependentBitIntType(IsUnsigned, BitWidth);
2360 llvm::APSInt Bits(32);
2361 ExprResult ICE =
2362 VerifyIntegerConstantExpression(BitWidth, &Bits, /*FIXME*/ AllowFold);
2364 if (ICE.isInvalid())
2365 return QualType();
2367 size_t NumBits = Bits.getZExtValue();
2368 if (!IsUnsigned && NumBits < 2) {
2369 Diag(Loc, diag::err_bit_int_bad_size) << 0;
2370 return QualType();
2373 if (IsUnsigned && NumBits < 1) {
2374 Diag(Loc, diag::err_bit_int_bad_size) << 1;
2375 return QualType();
2378 const TargetInfo &TI = getASTContext().getTargetInfo();
2379 if (NumBits > TI.getMaxBitIntWidth()) {
2380 Diag(Loc, diag::err_bit_int_max_size)
2381 << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth());
2382 return QualType();
2385 return Context.getBitIntType(IsUnsigned, NumBits);
2388 /// Check whether the specified array bound can be evaluated using the relevant
2389 /// language rules. If so, returns the possibly-converted expression and sets
2390 /// SizeVal to the size. If not, but the expression might be a VLA bound,
2391 /// returns ExprResult(). Otherwise, produces a diagnostic and returns
2392 /// ExprError().
2393 static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
2394 llvm::APSInt &SizeVal, unsigned VLADiag,
2395 bool VLAIsError) {
2396 if (S.getLangOpts().CPlusPlus14 &&
2397 (VLAIsError ||
2398 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) {
2399 // C++14 [dcl.array]p1:
2400 // The constant-expression shall be a converted constant expression of
2401 // type std::size_t.
2403 // Don't apply this rule if we might be forming a VLA: in that case, we
2404 // allow non-constant expressions and constant-folding. We only need to use
2405 // the converted constant expression rules (to properly convert the source)
2406 // when the source expression is of class type.
2407 return S.CheckConvertedConstantExpression(
2408 ArraySize, S.Context.getSizeType(), SizeVal, Sema::CCEK_ArrayBound);
2411 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2412 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2413 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2414 public:
2415 unsigned VLADiag;
2416 bool VLAIsError;
2417 bool IsVLA = false;
2419 VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2420 : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2422 Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2423 QualType T) override {
2424 return S.Diag(Loc, diag::err_array_size_non_int) << T;
2427 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2428 SourceLocation Loc) override {
2429 IsVLA = !VLAIsError;
2430 return S.Diag(Loc, VLADiag);
2433 Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2434 SourceLocation Loc) override {
2435 return S.Diag(Loc, diag::ext_vla_folded_to_constant);
2437 } Diagnoser(VLADiag, VLAIsError);
2439 ExprResult R =
2440 S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser);
2441 if (Diagnoser.IsVLA)
2442 return ExprResult();
2443 return R;
2446 bool Sema::checkArrayElementAlignment(QualType EltTy, SourceLocation Loc) {
2447 EltTy = Context.getBaseElementType(EltTy);
2448 if (EltTy->isIncompleteType() || EltTy->isDependentType() ||
2449 EltTy->isUndeducedType())
2450 return true;
2452 CharUnits Size = Context.getTypeSizeInChars(EltTy);
2453 CharUnits Alignment = Context.getTypeAlignInChars(EltTy);
2455 if (Size.isMultipleOf(Alignment))
2456 return true;
2458 Diag(Loc, diag::err_array_element_alignment)
2459 << EltTy << Size.getQuantity() << Alignment.getQuantity();
2460 return false;
2463 /// Build an array type.
2465 /// \param T The type of each element in the array.
2467 /// \param ASM C99 array size modifier (e.g., '*', 'static').
2469 /// \param ArraySize Expression describing the size of the array.
2471 /// \param Brackets The range from the opening '[' to the closing ']'.
2473 /// \param Entity The name of the entity that involves the array
2474 /// type, if known.
2476 /// \returns A suitable array type, if there are no errors. Otherwise,
2477 /// returns a NULL type.
2478 QualType Sema::BuildArrayType(QualType T, ArraySizeModifier ASM,
2479 Expr *ArraySize, unsigned Quals,
2480 SourceRange Brackets, DeclarationName Entity) {
2482 SourceLocation Loc = Brackets.getBegin();
2483 if (getLangOpts().CPlusPlus) {
2484 // C++ [dcl.array]p1:
2485 // T is called the array element type; this type shall not be a reference
2486 // type, the (possibly cv-qualified) type void, a function type or an
2487 // abstract class type.
2489 // C++ [dcl.array]p3:
2490 // When several "array of" specifications are adjacent, [...] only the
2491 // first of the constant expressions that specify the bounds of the arrays
2492 // may be omitted.
2494 // Note: function types are handled in the common path with C.
2495 if (T->isReferenceType()) {
2496 Diag(Loc, diag::err_illegal_decl_array_of_references)
2497 << getPrintableNameForEntity(Entity) << T;
2498 return QualType();
2501 if (T->isVoidType() || T->isIncompleteArrayType()) {
2502 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2503 return QualType();
2506 if (RequireNonAbstractType(Brackets.getBegin(), T,
2507 diag::err_array_of_abstract_type))
2508 return QualType();
2510 // Mentioning a member pointer type for an array type causes us to lock in
2511 // an inheritance model, even if it's inside an unused typedef.
2512 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2513 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2514 if (!MPTy->getClass()->isDependentType())
2515 (void)isCompleteType(Loc, T);
2517 } else {
2518 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2519 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2520 if (!T.isWebAssemblyReferenceType() &&
2521 RequireCompleteSizedType(Loc, T,
2522 diag::err_array_incomplete_or_sizeless_type))
2523 return QualType();
2526 // Multi-dimensional arrays of WebAssembly references are not allowed.
2527 if (Context.getTargetInfo().getTriple().isWasm() && T->isArrayType()) {
2528 const auto *ATy = dyn_cast<ArrayType>(T);
2529 if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
2530 Diag(Loc, diag::err_wasm_reftype_multidimensional_array);
2531 return QualType();
2535 if (T->isSizelessType() && !T.isWebAssemblyReferenceType()) {
2536 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2537 return QualType();
2540 if (T->isFunctionType()) {
2541 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2542 << getPrintableNameForEntity(Entity) << T;
2543 return QualType();
2546 if (const RecordType *EltTy = T->getAs<RecordType>()) {
2547 // If the element type is a struct or union that contains a variadic
2548 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2549 if (EltTy->getDecl()->hasFlexibleArrayMember())
2550 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2551 } else if (T->isObjCObjectType()) {
2552 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2553 return QualType();
2556 if (!checkArrayElementAlignment(T, Loc))
2557 return QualType();
2559 // Do placeholder conversions on the array size expression.
2560 if (ArraySize && ArraySize->hasPlaceholderType()) {
2561 ExprResult Result = CheckPlaceholderExpr(ArraySize);
2562 if (Result.isInvalid()) return QualType();
2563 ArraySize = Result.get();
2566 // Do lvalue-to-rvalue conversions on the array size expression.
2567 if (ArraySize && !ArraySize->isPRValue()) {
2568 ExprResult Result = DefaultLvalueConversion(ArraySize);
2569 if (Result.isInvalid())
2570 return QualType();
2572 ArraySize = Result.get();
2575 // C99 6.7.5.2p1: The size expression shall have integer type.
2576 // C++11 allows contextual conversions to such types.
2577 if (!getLangOpts().CPlusPlus11 &&
2578 ArraySize && !ArraySize->isTypeDependent() &&
2579 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2580 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2581 << ArraySize->getType() << ArraySize->getSourceRange();
2582 return QualType();
2585 auto IsStaticAssertLike = [](const Expr *ArraySize, ASTContext &Context) {
2586 if (!ArraySize)
2587 return false;
2589 // If the array size expression is a conditional expression whose branches
2590 // are both integer constant expressions, one negative and one positive,
2591 // then it's assumed to be like an old-style static assertion. e.g.,
2592 // int old_style_assert[expr ? 1 : -1];
2593 // We will accept any integer constant expressions instead of assuming the
2594 // values 1 and -1 are always used.
2595 if (const auto *CondExpr = dyn_cast_if_present<ConditionalOperator>(
2596 ArraySize->IgnoreParenImpCasts())) {
2597 std::optional<llvm::APSInt> LHS =
2598 CondExpr->getLHS()->getIntegerConstantExpr(Context);
2599 std::optional<llvm::APSInt> RHS =
2600 CondExpr->getRHS()->getIntegerConstantExpr(Context);
2601 return LHS && RHS && LHS->isNegative() != RHS->isNegative();
2603 return false;
2606 // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2607 unsigned VLADiag;
2608 bool VLAIsError;
2609 if (getLangOpts().OpenCL) {
2610 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2611 VLADiag = diag::err_opencl_vla;
2612 VLAIsError = true;
2613 } else if (getLangOpts().C99) {
2614 VLADiag = diag::warn_vla_used;
2615 VLAIsError = false;
2616 } else if (isSFINAEContext()) {
2617 VLADiag = diag::err_vla_in_sfinae;
2618 VLAIsError = true;
2619 } else if (getLangOpts().OpenMP && isInOpenMPTaskUntiedContext()) {
2620 VLADiag = diag::err_openmp_vla_in_task_untied;
2621 VLAIsError = true;
2622 } else if (getLangOpts().CPlusPlus) {
2623 if (getLangOpts().CPlusPlus11 && IsStaticAssertLike(ArraySize, Context))
2624 VLADiag = getLangOpts().GNUMode
2625 ? diag::ext_vla_cxx_in_gnu_mode_static_assert
2626 : diag::ext_vla_cxx_static_assert;
2627 else
2628 VLADiag = getLangOpts().GNUMode ? diag::ext_vla_cxx_in_gnu_mode
2629 : diag::ext_vla_cxx;
2630 VLAIsError = false;
2631 } else {
2632 VLADiag = diag::ext_vla;
2633 VLAIsError = false;
2636 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2637 if (!ArraySize) {
2638 if (ASM == ArraySizeModifier::Star) {
2639 Diag(Loc, VLADiag);
2640 if (VLAIsError)
2641 return QualType();
2643 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2644 } else {
2645 T = Context.getIncompleteArrayType(T, ASM, Quals);
2647 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2648 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2649 } else {
2650 ExprResult R =
2651 checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError);
2652 if (R.isInvalid())
2653 return QualType();
2655 if (!R.isUsable()) {
2656 // C99: an array with a non-ICE size is a VLA. We accept any expression
2657 // that we can fold to a non-zero positive value as a non-VLA as an
2658 // extension.
2659 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2660 } else if (!T->isDependentType() && !T->isIncompleteType() &&
2661 !T->isConstantSizeType()) {
2662 // C99: an array with an element type that has a non-constant-size is a
2663 // VLA.
2664 // FIXME: Add a note to explain why this isn't a VLA.
2665 Diag(Loc, VLADiag);
2666 if (VLAIsError)
2667 return QualType();
2668 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2669 } else {
2670 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2671 // have a value greater than zero.
2672 // In C++, this follows from narrowing conversions being disallowed.
2673 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2674 if (Entity)
2675 Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2676 << getPrintableNameForEntity(Entity)
2677 << ArraySize->getSourceRange();
2678 else
2679 Diag(ArraySize->getBeginLoc(),
2680 diag::err_typecheck_negative_array_size)
2681 << ArraySize->getSourceRange();
2682 return QualType();
2684 if (ConstVal == 0 && !T.isWebAssemblyReferenceType()) {
2685 // GCC accepts zero sized static arrays. We allow them when
2686 // we're not in a SFINAE context.
2687 Diag(ArraySize->getBeginLoc(),
2688 isSFINAEContext() ? diag::err_typecheck_zero_array_size
2689 : diag::ext_typecheck_zero_array_size)
2690 << 0 << ArraySize->getSourceRange();
2693 // Is the array too large?
2694 unsigned ActiveSizeBits =
2695 (!T->isDependentType() && !T->isVariablyModifiedType() &&
2696 !T->isIncompleteType() && !T->isUndeducedType())
2697 ? ConstantArrayType::getNumAddressingBits(Context, T, ConstVal)
2698 : ConstVal.getActiveBits();
2699 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2700 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2701 << toString(ConstVal, 10) << ArraySize->getSourceRange();
2702 return QualType();
2705 T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2709 if (T->isVariableArrayType()) {
2710 if (!Context.getTargetInfo().isVLASupported()) {
2711 // CUDA device code and some other targets don't support VLAs.
2712 bool IsCUDADevice = (getLangOpts().CUDA && getLangOpts().CUDAIsDevice);
2713 targetDiag(Loc,
2714 IsCUDADevice ? diag::err_cuda_vla : diag::err_vla_unsupported)
2715 << (IsCUDADevice ? CurrentCUDATarget() : 0);
2716 } else if (sema::FunctionScopeInfo *FSI = getCurFunction()) {
2717 // VLAs are supported on this target, but we may need to do delayed
2718 // checking that the VLA is not being used within a coroutine.
2719 FSI->setHasVLA(Loc);
2723 // If this is not C99, diagnose array size modifiers on non-VLAs.
2724 if (!getLangOpts().C99 && !T->isVariableArrayType() &&
2725 (ASM != ArraySizeModifier::Normal || Quals != 0)) {
2726 Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx
2727 : diag::ext_c99_array_usage)
2728 << llvm::to_underlying(ASM);
2731 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2732 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2733 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2734 if (getLangOpts().OpenCL) {
2735 const QualType ArrType = Context.getBaseElementType(T);
2736 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2737 ArrType->isSamplerT() || ArrType->isImageType()) {
2738 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2739 return QualType();
2743 return T;
2746 QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
2747 SourceLocation AttrLoc) {
2748 // The base type must be integer (not Boolean or enumeration) or float, and
2749 // can't already be a vector.
2750 if ((!CurType->isDependentType() &&
2751 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2752 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) &&
2753 !CurType->isBitIntType()) ||
2754 CurType->isArrayType()) {
2755 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2756 return QualType();
2758 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2759 if (const auto *BIT = CurType->getAs<BitIntType>()) {
2760 unsigned NumBits = BIT->getNumBits();
2761 if (!llvm::isPowerOf2_32(NumBits) || NumBits < 8) {
2762 Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2763 << (NumBits < 8);
2764 return QualType();
2768 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2769 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2770 VectorKind::Generic);
2772 std::optional<llvm::APSInt> VecSize =
2773 SizeExpr->getIntegerConstantExpr(Context);
2774 if (!VecSize) {
2775 Diag(AttrLoc, diag::err_attribute_argument_type)
2776 << "vector_size" << AANT_ArgumentIntegerConstant
2777 << SizeExpr->getSourceRange();
2778 return QualType();
2781 if (CurType->isDependentType())
2782 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2783 VectorKind::Generic);
2785 // vecSize is specified in bytes - convert to bits.
2786 if (!VecSize->isIntN(61)) {
2787 // Bit size will overflow uint64.
2788 Diag(AttrLoc, diag::err_attribute_size_too_large)
2789 << SizeExpr->getSourceRange() << "vector";
2790 return QualType();
2792 uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2793 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2795 if (VectorSizeBits == 0) {
2796 Diag(AttrLoc, diag::err_attribute_zero_size)
2797 << SizeExpr->getSourceRange() << "vector";
2798 return QualType();
2801 if (!TypeSize || VectorSizeBits % TypeSize) {
2802 Diag(AttrLoc, diag::err_attribute_invalid_size)
2803 << SizeExpr->getSourceRange();
2804 return QualType();
2807 if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2808 Diag(AttrLoc, diag::err_attribute_size_too_large)
2809 << SizeExpr->getSourceRange() << "vector";
2810 return QualType();
2813 return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2814 VectorKind::Generic);
2817 /// Build an ext-vector type.
2819 /// Run the required checks for the extended vector type.
2820 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2821 SourceLocation AttrLoc) {
2822 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2823 // in conjunction with complex types (pointers, arrays, functions, etc.).
2825 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2826 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2827 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2828 // of bool aren't allowed.
2830 // We explictly allow bool elements in ext_vector_type for C/C++.
2831 bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus;
2832 if ((!T->isDependentType() && !T->isIntegerType() &&
2833 !T->isRealFloatingType()) ||
2834 (IsNoBoolVecLang && T->isBooleanType())) {
2835 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2836 return QualType();
2839 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2840 if (T->isBitIntType()) {
2841 unsigned NumBits = T->castAs<BitIntType>()->getNumBits();
2842 if (!llvm::isPowerOf2_32(NumBits) || NumBits < 8) {
2843 Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2844 << (NumBits < 8);
2845 return QualType();
2849 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2850 std::optional<llvm::APSInt> vecSize =
2851 ArraySize->getIntegerConstantExpr(Context);
2852 if (!vecSize) {
2853 Diag(AttrLoc, diag::err_attribute_argument_type)
2854 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2855 << ArraySize->getSourceRange();
2856 return QualType();
2859 if (!vecSize->isIntN(32)) {
2860 Diag(AttrLoc, diag::err_attribute_size_too_large)
2861 << ArraySize->getSourceRange() << "vector";
2862 return QualType();
2864 // Unlike gcc's vector_size attribute, the size is specified as the
2865 // number of elements, not the number of bytes.
2866 unsigned vectorSize = static_cast<unsigned>(vecSize->getZExtValue());
2868 if (vectorSize == 0) {
2869 Diag(AttrLoc, diag::err_attribute_zero_size)
2870 << ArraySize->getSourceRange() << "vector";
2871 return QualType();
2874 return Context.getExtVectorType(T, vectorSize);
2877 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2880 QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2881 SourceLocation AttrLoc) {
2882 assert(Context.getLangOpts().MatrixTypes &&
2883 "Should never build a matrix type when it is disabled");
2885 // Check element type, if it is not dependent.
2886 if (!ElementTy->isDependentType() &&
2887 !MatrixType::isValidElementType(ElementTy)) {
2888 Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2889 return QualType();
2892 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2893 NumRows->isValueDependent() || NumCols->isValueDependent())
2894 return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2895 AttrLoc);
2897 std::optional<llvm::APSInt> ValueRows =
2898 NumRows->getIntegerConstantExpr(Context);
2899 std::optional<llvm::APSInt> ValueColumns =
2900 NumCols->getIntegerConstantExpr(Context);
2902 auto const RowRange = NumRows->getSourceRange();
2903 auto const ColRange = NumCols->getSourceRange();
2905 // Both are row and column expressions are invalid.
2906 if (!ValueRows && !ValueColumns) {
2907 Diag(AttrLoc, diag::err_attribute_argument_type)
2908 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2909 << ColRange;
2910 return QualType();
2913 // Only the row expression is invalid.
2914 if (!ValueRows) {
2915 Diag(AttrLoc, diag::err_attribute_argument_type)
2916 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2917 return QualType();
2920 // Only the column expression is invalid.
2921 if (!ValueColumns) {
2922 Diag(AttrLoc, diag::err_attribute_argument_type)
2923 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2924 return QualType();
2927 // Check the matrix dimensions.
2928 unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2929 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2930 if (MatrixRows == 0 && MatrixColumns == 0) {
2931 Diag(AttrLoc, diag::err_attribute_zero_size)
2932 << "matrix" << RowRange << ColRange;
2933 return QualType();
2935 if (MatrixRows == 0) {
2936 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2937 return QualType();
2939 if (MatrixColumns == 0) {
2940 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2941 return QualType();
2943 if (!ConstantMatrixType::isDimensionValid(MatrixRows)) {
2944 Diag(AttrLoc, diag::err_attribute_size_too_large)
2945 << RowRange << "matrix row";
2946 return QualType();
2948 if (!ConstantMatrixType::isDimensionValid(MatrixColumns)) {
2949 Diag(AttrLoc, diag::err_attribute_size_too_large)
2950 << ColRange << "matrix column";
2951 return QualType();
2953 return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2956 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2957 if (T->isArrayType() || T->isFunctionType()) {
2958 Diag(Loc, diag::err_func_returning_array_function)
2959 << T->isFunctionType() << T;
2960 return true;
2963 // Functions cannot return half FP.
2964 if (T->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2965 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2966 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2967 FixItHint::CreateInsertion(Loc, "*");
2968 return true;
2971 // Methods cannot return interface types. All ObjC objects are
2972 // passed by reference.
2973 if (T->isObjCObjectType()) {
2974 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2975 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2976 return true;
2979 if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2980 T.hasNonTrivialToPrimitiveCopyCUnion())
2981 checkNonTrivialCUnion(T, Loc, NTCUC_FunctionReturn,
2982 NTCUK_Destruct|NTCUK_Copy);
2984 // C++2a [dcl.fct]p12:
2985 // A volatile-qualified return type is deprecated
2986 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2987 Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2989 if (T.getAddressSpace() != LangAS::Default && getLangOpts().HLSL)
2990 return true;
2991 return false;
2994 /// Check the extended parameter information. Most of the necessary
2995 /// checking should occur when applying the parameter attribute; the
2996 /// only other checks required are positional restrictions.
2997 static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2998 const FunctionProtoType::ExtProtoInfo &EPI,
2999 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
3000 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
3002 bool emittedError = false;
3003 auto actualCC = EPI.ExtInfo.getCC();
3004 enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
3005 auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
3006 bool isCompatible =
3007 (required == RequiredCC::OnlySwift)
3008 ? (actualCC == CC_Swift)
3009 : (actualCC == CC_Swift || actualCC == CC_SwiftAsync);
3010 if (isCompatible || emittedError)
3011 return;
3012 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
3013 << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI())
3014 << (required == RequiredCC::OnlySwift);
3015 emittedError = true;
3017 for (size_t paramIndex = 0, numParams = paramTypes.size();
3018 paramIndex != numParams; ++paramIndex) {
3019 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
3020 // Nothing interesting to check for orindary-ABI parameters.
3021 case ParameterABI::Ordinary:
3022 continue;
3024 // swift_indirect_result parameters must be a prefix of the function
3025 // arguments.
3026 case ParameterABI::SwiftIndirectResult:
3027 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
3028 if (paramIndex != 0 &&
3029 EPI.ExtParameterInfos[paramIndex - 1].getABI()
3030 != ParameterABI::SwiftIndirectResult) {
3031 S.Diag(getParamLoc(paramIndex),
3032 diag::err_swift_indirect_result_not_first);
3034 continue;
3036 case ParameterABI::SwiftContext:
3037 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
3038 continue;
3040 // SwiftAsyncContext is not limited to swiftasynccall functions.
3041 case ParameterABI::SwiftAsyncContext:
3042 continue;
3044 // swift_error parameters must be preceded by a swift_context parameter.
3045 case ParameterABI::SwiftErrorResult:
3046 checkCompatible(paramIndex, RequiredCC::OnlySwift);
3047 if (paramIndex == 0 ||
3048 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
3049 ParameterABI::SwiftContext) {
3050 S.Diag(getParamLoc(paramIndex),
3051 diag::err_swift_error_result_not_after_swift_context);
3053 continue;
3055 llvm_unreachable("bad ABI kind");
3059 QualType Sema::BuildFunctionType(QualType T,
3060 MutableArrayRef<QualType> ParamTypes,
3061 SourceLocation Loc, DeclarationName Entity,
3062 const FunctionProtoType::ExtProtoInfo &EPI) {
3063 bool Invalid = false;
3065 Invalid |= CheckFunctionReturnType(T, Loc);
3067 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
3068 // FIXME: Loc is too inprecise here, should use proper locations for args.
3069 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
3070 if (ParamType->isVoidType()) {
3071 Diag(Loc, diag::err_param_with_void_type);
3072 Invalid = true;
3073 } else if (ParamType->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
3074 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
3075 // Disallow half FP arguments.
3076 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
3077 FixItHint::CreateInsertion(Loc, "*");
3078 Invalid = true;
3079 } else if (ParamType->isWebAssemblyTableType()) {
3080 Diag(Loc, diag::err_wasm_table_as_function_parameter);
3081 Invalid = true;
3084 // C++2a [dcl.fct]p4:
3085 // A parameter with volatile-qualified type is deprecated
3086 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
3087 Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
3089 ParamTypes[Idx] = ParamType;
3092 if (EPI.ExtParameterInfos) {
3093 checkExtParameterInfos(*this, ParamTypes, EPI,
3094 [=](unsigned i) { return Loc; });
3097 if (EPI.ExtInfo.getProducesResult()) {
3098 // This is just a warning, so we can't fail to build if we see it.
3099 checkNSReturnsRetainedReturnType(Loc, T);
3102 if (Invalid)
3103 return QualType();
3105 return Context.getFunctionType(T, ParamTypes, EPI);
3108 /// Build a member pointer type \c T Class::*.
3110 /// \param T the type to which the member pointer refers.
3111 /// \param Class the class type into which the member pointer points.
3112 /// \param Loc the location where this type begins
3113 /// \param Entity the name of the entity that will have this member pointer type
3115 /// \returns a member pointer type, if successful, or a NULL type if there was
3116 /// an error.
3117 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
3118 SourceLocation Loc,
3119 DeclarationName Entity) {
3120 // Verify that we're not building a pointer to pointer to function with
3121 // exception specification.
3122 if (CheckDistantExceptionSpec(T)) {
3123 Diag(Loc, diag::err_distant_exception_spec);
3124 return QualType();
3127 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
3128 // with reference type, or "cv void."
3129 if (T->isReferenceType()) {
3130 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
3131 << getPrintableNameForEntity(Entity) << T;
3132 return QualType();
3135 if (T->isVoidType()) {
3136 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
3137 << getPrintableNameForEntity(Entity);
3138 return QualType();
3141 if (!Class->isDependentType() && !Class->isRecordType()) {
3142 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
3143 return QualType();
3146 if (T->isFunctionType() && getLangOpts().OpenCL &&
3147 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
3148 getLangOpts())) {
3149 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
3150 return QualType();
3153 if (getLangOpts().HLSL && Loc.isValid()) {
3154 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
3155 return QualType();
3158 // Adjust the default free function calling convention to the default method
3159 // calling convention.
3160 bool IsCtorOrDtor =
3161 (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
3162 (Entity.getNameKind() == DeclarationName::CXXDestructorName);
3163 if (T->isFunctionType())
3164 adjustMemberFunctionCC(T, /*HasThisPointer=*/true, IsCtorOrDtor, Loc);
3166 return Context.getMemberPointerType(T, Class.getTypePtr());
3169 /// Build a block pointer type.
3171 /// \param T The type to which we'll be building a block pointer.
3173 /// \param Loc The source location, used for diagnostics.
3175 /// \param Entity The name of the entity that involves the block pointer
3176 /// type, if known.
3178 /// \returns A suitable block pointer type, if there are no
3179 /// errors. Otherwise, returns a NULL type.
3180 QualType Sema::BuildBlockPointerType(QualType T,
3181 SourceLocation Loc,
3182 DeclarationName Entity) {
3183 if (!T->isFunctionType()) {
3184 Diag(Loc, diag::err_nonfunction_block_type);
3185 return QualType();
3188 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
3189 return QualType();
3191 if (getLangOpts().OpenCL)
3192 T = deduceOpenCLPointeeAddrSpace(*this, T);
3194 return Context.getBlockPointerType(T);
3197 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
3198 QualType QT = Ty.get();
3199 if (QT.isNull()) {
3200 if (TInfo) *TInfo = nullptr;
3201 return QualType();
3204 TypeSourceInfo *DI = nullptr;
3205 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
3206 QT = LIT->getType();
3207 DI = LIT->getTypeSourceInfo();
3210 if (TInfo) *TInfo = DI;
3211 return QT;
3214 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
3215 Qualifiers::ObjCLifetime ownership,
3216 unsigned chunkIndex);
3218 /// Given that this is the declaration of a parameter under ARC,
3219 /// attempt to infer attributes and such for pointer-to-whatever
3220 /// types.
3221 static void inferARCWriteback(TypeProcessingState &state,
3222 QualType &declSpecType) {
3223 Sema &S = state.getSema();
3224 Declarator &declarator = state.getDeclarator();
3226 // TODO: should we care about decl qualifiers?
3228 // Check whether the declarator has the expected form. We walk
3229 // from the inside out in order to make the block logic work.
3230 unsigned outermostPointerIndex = 0;
3231 bool isBlockPointer = false;
3232 unsigned numPointers = 0;
3233 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
3234 unsigned chunkIndex = i;
3235 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
3236 switch (chunk.Kind) {
3237 case DeclaratorChunk::Paren:
3238 // Ignore parens.
3239 break;
3241 case DeclaratorChunk::Reference:
3242 case DeclaratorChunk::Pointer:
3243 // Count the number of pointers. Treat references
3244 // interchangeably as pointers; if they're mis-ordered, normal
3245 // type building will discover that.
3246 outermostPointerIndex = chunkIndex;
3247 numPointers++;
3248 break;
3250 case DeclaratorChunk::BlockPointer:
3251 // If we have a pointer to block pointer, that's an acceptable
3252 // indirect reference; anything else is not an application of
3253 // the rules.
3254 if (numPointers != 1) return;
3255 numPointers++;
3256 outermostPointerIndex = chunkIndex;
3257 isBlockPointer = true;
3259 // We don't care about pointer structure in return values here.
3260 goto done;
3262 case DeclaratorChunk::Array: // suppress if written (id[])?
3263 case DeclaratorChunk::Function:
3264 case DeclaratorChunk::MemberPointer:
3265 case DeclaratorChunk::Pipe:
3266 return;
3269 done:
3271 // If we have *one* pointer, then we want to throw the qualifier on
3272 // the declaration-specifiers, which means that it needs to be a
3273 // retainable object type.
3274 if (numPointers == 1) {
3275 // If it's not a retainable object type, the rule doesn't apply.
3276 if (!declSpecType->isObjCRetainableType()) return;
3278 // If it already has lifetime, don't do anything.
3279 if (declSpecType.getObjCLifetime()) return;
3281 // Otherwise, modify the type in-place.
3282 Qualifiers qs;
3284 if (declSpecType->isObjCARCImplicitlyUnretainedType())
3285 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
3286 else
3287 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
3288 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
3290 // If we have *two* pointers, then we want to throw the qualifier on
3291 // the outermost pointer.
3292 } else if (numPointers == 2) {
3293 // If we don't have a block pointer, we need to check whether the
3294 // declaration-specifiers gave us something that will turn into a
3295 // retainable object pointer after we slap the first pointer on it.
3296 if (!isBlockPointer && !declSpecType->isObjCObjectType())
3297 return;
3299 // Look for an explicit lifetime attribute there.
3300 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
3301 if (chunk.Kind != DeclaratorChunk::Pointer &&
3302 chunk.Kind != DeclaratorChunk::BlockPointer)
3303 return;
3304 for (const ParsedAttr &AL : chunk.getAttrs())
3305 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
3306 return;
3308 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
3309 outermostPointerIndex);
3311 // Any other number of pointers/references does not trigger the rule.
3312 } else return;
3314 // TODO: mark whether we did this inference?
3317 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
3318 SourceLocation FallbackLoc,
3319 SourceLocation ConstQualLoc,
3320 SourceLocation VolatileQualLoc,
3321 SourceLocation RestrictQualLoc,
3322 SourceLocation AtomicQualLoc,
3323 SourceLocation UnalignedQualLoc) {
3324 if (!Quals)
3325 return;
3327 struct Qual {
3328 const char *Name;
3329 unsigned Mask;
3330 SourceLocation Loc;
3331 } const QualKinds[5] = {
3332 { "const", DeclSpec::TQ_const, ConstQualLoc },
3333 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
3334 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
3335 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
3336 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
3339 SmallString<32> QualStr;
3340 unsigned NumQuals = 0;
3341 SourceLocation Loc;
3342 FixItHint FixIts[5];
3344 // Build a string naming the redundant qualifiers.
3345 for (auto &E : QualKinds) {
3346 if (Quals & E.Mask) {
3347 if (!QualStr.empty()) QualStr += ' ';
3348 QualStr += E.Name;
3350 // If we have a location for the qualifier, offer a fixit.
3351 SourceLocation QualLoc = E.Loc;
3352 if (QualLoc.isValid()) {
3353 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
3354 if (Loc.isInvalid() ||
3355 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
3356 Loc = QualLoc;
3359 ++NumQuals;
3363 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
3364 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
3367 // Diagnose pointless type qualifiers on the return type of a function.
3368 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
3369 Declarator &D,
3370 unsigned FunctionChunkIndex) {
3371 const DeclaratorChunk::FunctionTypeInfo &FTI =
3372 D.getTypeObject(FunctionChunkIndex).Fun;
3373 if (FTI.hasTrailingReturnType()) {
3374 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3375 RetTy.getLocalCVRQualifiers(),
3376 FTI.getTrailingReturnTypeLoc());
3377 return;
3380 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3381 End = D.getNumTypeObjects();
3382 OuterChunkIndex != End; ++OuterChunkIndex) {
3383 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
3384 switch (OuterChunk.Kind) {
3385 case DeclaratorChunk::Paren:
3386 continue;
3388 case DeclaratorChunk::Pointer: {
3389 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3390 S.diagnoseIgnoredQualifiers(
3391 diag::warn_qual_return_type,
3392 PTI.TypeQuals,
3393 SourceLocation(),
3394 PTI.ConstQualLoc,
3395 PTI.VolatileQualLoc,
3396 PTI.RestrictQualLoc,
3397 PTI.AtomicQualLoc,
3398 PTI.UnalignedQualLoc);
3399 return;
3402 case DeclaratorChunk::Function:
3403 case DeclaratorChunk::BlockPointer:
3404 case DeclaratorChunk::Reference:
3405 case DeclaratorChunk::Array:
3406 case DeclaratorChunk::MemberPointer:
3407 case DeclaratorChunk::Pipe:
3408 // FIXME: We can't currently provide an accurate source location and a
3409 // fix-it hint for these.
3410 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
3411 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3412 RetTy.getCVRQualifiers() | AtomicQual,
3413 D.getIdentifierLoc());
3414 return;
3417 llvm_unreachable("unknown declarator chunk kind");
3420 // If the qualifiers come from a conversion function type, don't diagnose
3421 // them -- they're not necessarily redundant, since such a conversion
3422 // operator can be explicitly called as "x.operator const int()".
3423 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3424 return;
3426 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3427 // which are present there.
3428 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3429 D.getDeclSpec().getTypeQualifiers(),
3430 D.getIdentifierLoc(),
3431 D.getDeclSpec().getConstSpecLoc(),
3432 D.getDeclSpec().getVolatileSpecLoc(),
3433 D.getDeclSpec().getRestrictSpecLoc(),
3434 D.getDeclSpec().getAtomicSpecLoc(),
3435 D.getDeclSpec().getUnalignedSpecLoc());
3438 static std::pair<QualType, TypeSourceInfo *>
3439 InventTemplateParameter(TypeProcessingState &state, QualType T,
3440 TypeSourceInfo *TrailingTSI, AutoType *Auto,
3441 InventedTemplateParameterInfo &Info) {
3442 Sema &S = state.getSema();
3443 Declarator &D = state.getDeclarator();
3445 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3446 const unsigned AutoParameterPosition = Info.TemplateParams.size();
3447 const bool IsParameterPack = D.hasEllipsis();
3449 // If auto is mentioned in a lambda parameter or abbreviated function
3450 // template context, convert it to a template parameter type.
3452 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3453 // template parameter type. Template parameters are temporarily added
3454 // to the TU until the associated TemplateDecl is created.
3455 TemplateTypeParmDecl *InventedTemplateParam =
3456 TemplateTypeParmDecl::Create(
3457 S.Context, S.Context.getTranslationUnitDecl(),
3458 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3459 /*NameLoc=*/D.getIdentifierLoc(),
3460 TemplateParameterDepth, AutoParameterPosition,
3461 S.InventAbbreviatedTemplateParameterTypeName(
3462 D.getIdentifier(), AutoParameterPosition), false,
3463 IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3464 InventedTemplateParam->setImplicit();
3465 Info.TemplateParams.push_back(InventedTemplateParam);
3467 // Attach type constraints to the new parameter.
3468 if (Auto->isConstrained()) {
3469 if (TrailingTSI) {
3470 // The 'auto' appears in a trailing return type we've already built;
3471 // extract its type constraints to attach to the template parameter.
3472 AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3473 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3474 bool Invalid = false;
3475 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3476 if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3477 S.DiagnoseUnexpandedParameterPack(AutoLoc.getArgLoc(Idx),
3478 Sema::UPPC_TypeConstraint))
3479 Invalid = true;
3480 TAL.addArgument(AutoLoc.getArgLoc(Idx));
3483 if (!Invalid) {
3484 S.AttachTypeConstraint(
3485 AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3486 AutoLoc.getNamedConcept(),
3487 AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3488 InventedTemplateParam, D.getEllipsisLoc());
3490 } else {
3491 // The 'auto' appears in the decl-specifiers; we've not finished forming
3492 // TypeSourceInfo for it yet.
3493 TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId();
3494 TemplateArgumentListInfo TemplateArgsInfo;
3495 bool Invalid = false;
3496 if (TemplateId->LAngleLoc.isValid()) {
3497 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3498 TemplateId->NumArgs);
3499 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3501 if (D.getEllipsisLoc().isInvalid()) {
3502 for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3503 if (S.DiagnoseUnexpandedParameterPack(Arg,
3504 Sema::UPPC_TypeConstraint)) {
3505 Invalid = true;
3506 break;
3511 if (!Invalid) {
3512 S.AttachTypeConstraint(
3513 D.getDeclSpec().getTypeSpecScope().getWithLocInContext(S.Context),
3514 DeclarationNameInfo(DeclarationName(TemplateId->Name),
3515 TemplateId->TemplateNameLoc),
3516 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl()),
3517 TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3518 InventedTemplateParam, D.getEllipsisLoc());
3523 // Replace the 'auto' in the function parameter with this invented
3524 // template type parameter.
3525 // FIXME: Retain some type sugar to indicate that this was written
3526 // as 'auto'?
3527 QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3528 QualType NewT = state.ReplaceAutoType(T, Replacement);
3529 TypeSourceInfo *NewTSI =
3530 TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)
3531 : nullptr;
3532 return {NewT, NewTSI};
3535 static TypeSourceInfo *
3536 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3537 QualType T, TypeSourceInfo *ReturnTypeInfo);
3539 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3540 TypeSourceInfo *&ReturnTypeInfo) {
3541 Sema &SemaRef = state.getSema();
3542 Declarator &D = state.getDeclarator();
3543 QualType T;
3544 ReturnTypeInfo = nullptr;
3546 // The TagDecl owned by the DeclSpec.
3547 TagDecl *OwnedTagDecl = nullptr;
3549 switch (D.getName().getKind()) {
3550 case UnqualifiedIdKind::IK_ImplicitSelfParam:
3551 case UnqualifiedIdKind::IK_OperatorFunctionId:
3552 case UnqualifiedIdKind::IK_Identifier:
3553 case UnqualifiedIdKind::IK_LiteralOperatorId:
3554 case UnqualifiedIdKind::IK_TemplateId:
3555 T = ConvertDeclSpecToType(state);
3557 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3558 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3559 // Owned declaration is embedded in declarator.
3560 OwnedTagDecl->setEmbeddedInDeclarator(true);
3562 break;
3564 case UnqualifiedIdKind::IK_ConstructorName:
3565 case UnqualifiedIdKind::IK_ConstructorTemplateId:
3566 case UnqualifiedIdKind::IK_DestructorName:
3567 // Constructors and destructors don't have return types. Use
3568 // "void" instead.
3569 T = SemaRef.Context.VoidTy;
3570 processTypeAttrs(state, T, TAL_DeclSpec,
3571 D.getMutableDeclSpec().getAttributes());
3572 break;
3574 case UnqualifiedIdKind::IK_DeductionGuideName:
3575 // Deduction guides have a trailing return type and no type in their
3576 // decl-specifier sequence. Use a placeholder return type for now.
3577 T = SemaRef.Context.DependentTy;
3578 break;
3580 case UnqualifiedIdKind::IK_ConversionFunctionId:
3581 // The result type of a conversion function is the type that it
3582 // converts to.
3583 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
3584 &ReturnTypeInfo);
3585 break;
3588 // Note: We don't need to distribute declaration attributes (i.e.
3589 // D.getDeclarationAttributes()) because those are always C++11 attributes,
3590 // and those don't get distributed.
3591 distributeTypeAttrsFromDeclarator(
3592 state, T, SemaRef.IdentifyCUDATarget(D.getAttributes()));
3594 // Find the deduced type in this type. Look in the trailing return type if we
3595 // have one, otherwise in the DeclSpec type.
3596 // FIXME: The standard wording doesn't currently describe this.
3597 DeducedType *Deduced = T->getContainedDeducedType();
3598 bool DeducedIsTrailingReturnType = false;
3599 if (Deduced && isa<AutoType>(Deduced) && D.hasTrailingReturnType()) {
3600 QualType T = SemaRef.GetTypeFromParser(D.getTrailingReturnType());
3601 Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3602 DeducedIsTrailingReturnType = true;
3605 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3606 if (Deduced) {
3607 AutoType *Auto = dyn_cast<AutoType>(Deduced);
3608 int Error = -1;
3610 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3611 // class template argument deduction)?
3612 bool IsCXXAutoType =
3613 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3614 bool IsDeducedReturnType = false;
3616 switch (D.getContext()) {
3617 case DeclaratorContext::LambdaExpr:
3618 // Declared return type of a lambda-declarator is implicit and is always
3619 // 'auto'.
3620 break;
3621 case DeclaratorContext::ObjCParameter:
3622 case DeclaratorContext::ObjCResult:
3623 Error = 0;
3624 break;
3625 case DeclaratorContext::RequiresExpr:
3626 Error = 22;
3627 break;
3628 case DeclaratorContext::Prototype:
3629 case DeclaratorContext::LambdaExprParameter: {
3630 InventedTemplateParameterInfo *Info = nullptr;
3631 if (D.getContext() == DeclaratorContext::Prototype) {
3632 // With concepts we allow 'auto' in function parameters.
3633 if (!SemaRef.getLangOpts().CPlusPlus20 || !Auto ||
3634 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3635 Error = 0;
3636 break;
3637 } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3638 Error = 21;
3639 break;
3642 Info = &SemaRef.InventedParameterInfos.back();
3643 } else {
3644 // In C++14, generic lambdas allow 'auto' in their parameters.
3645 if (!SemaRef.getLangOpts().CPlusPlus14 || !Auto ||
3646 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3647 Error = 16;
3648 break;
3650 Info = SemaRef.getCurLambda();
3651 assert(Info && "No LambdaScopeInfo on the stack!");
3654 // We'll deal with inventing template parameters for 'auto' in trailing
3655 // return types when we pick up the trailing return type when processing
3656 // the function chunk.
3657 if (!DeducedIsTrailingReturnType)
3658 T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3659 break;
3661 case DeclaratorContext::Member: {
3662 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
3663 D.isFunctionDeclarator())
3664 break;
3665 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3666 if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3667 Error = 6; // Interface member.
3668 } else {
3669 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3670 case TagTypeKind::Enum:
3671 llvm_unreachable("unhandled tag kind");
3672 case TagTypeKind::Struct:
3673 Error = Cxx ? 1 : 2; /* Struct member */
3674 break;
3675 case TagTypeKind::Union:
3676 Error = Cxx ? 3 : 4; /* Union member */
3677 break;
3678 case TagTypeKind::Class:
3679 Error = 5; /* Class member */
3680 break;
3681 case TagTypeKind::Interface:
3682 Error = 6; /* Interface member */
3683 break;
3686 if (D.getDeclSpec().isFriendSpecified())
3687 Error = 20; // Friend type
3688 break;
3690 case DeclaratorContext::CXXCatch:
3691 case DeclaratorContext::ObjCCatch:
3692 Error = 7; // Exception declaration
3693 break;
3694 case DeclaratorContext::TemplateParam:
3695 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3696 !SemaRef.getLangOpts().CPlusPlus20)
3697 Error = 19; // Template parameter (until C++20)
3698 else if (!SemaRef.getLangOpts().CPlusPlus17)
3699 Error = 8; // Template parameter (until C++17)
3700 break;
3701 case DeclaratorContext::BlockLiteral:
3702 Error = 9; // Block literal
3703 break;
3704 case DeclaratorContext::TemplateArg:
3705 // Within a template argument list, a deduced template specialization
3706 // type will be reinterpreted as a template template argument.
3707 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3708 !D.getNumTypeObjects() &&
3709 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier)
3710 break;
3711 [[fallthrough]];
3712 case DeclaratorContext::TemplateTypeArg:
3713 Error = 10; // Template type argument
3714 break;
3715 case DeclaratorContext::AliasDecl:
3716 case DeclaratorContext::AliasTemplate:
3717 Error = 12; // Type alias
3718 break;
3719 case DeclaratorContext::TrailingReturn:
3720 case DeclaratorContext::TrailingReturnVar:
3721 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3722 Error = 13; // Function return type
3723 IsDeducedReturnType = true;
3724 break;
3725 case DeclaratorContext::ConversionId:
3726 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3727 Error = 14; // conversion-type-id
3728 IsDeducedReturnType = true;
3729 break;
3730 case DeclaratorContext::FunctionalCast:
3731 if (isa<DeducedTemplateSpecializationType>(Deduced))
3732 break;
3733 if (SemaRef.getLangOpts().CPlusPlus23 && IsCXXAutoType &&
3734 !Auto->isDecltypeAuto())
3735 break; // auto(x)
3736 [[fallthrough]];
3737 case DeclaratorContext::TypeName:
3738 case DeclaratorContext::Association:
3739 Error = 15; // Generic
3740 break;
3741 case DeclaratorContext::File:
3742 case DeclaratorContext::Block:
3743 case DeclaratorContext::ForInit:
3744 case DeclaratorContext::SelectionInit:
3745 case DeclaratorContext::Condition:
3746 // FIXME: P0091R3 (erroneously) does not permit class template argument
3747 // deduction in conditions, for-init-statements, and other declarations
3748 // that are not simple-declarations.
3749 break;
3750 case DeclaratorContext::CXXNew:
3751 // FIXME: P0091R3 does not permit class template argument deduction here,
3752 // but we follow GCC and allow it anyway.
3753 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3754 Error = 17; // 'new' type
3755 break;
3756 case DeclaratorContext::KNRTypeList:
3757 Error = 18; // K&R function parameter
3758 break;
3761 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3762 Error = 11;
3764 // In Objective-C it is an error to use 'auto' on a function declarator
3765 // (and everywhere for '__auto_type').
3766 if (D.isFunctionDeclarator() &&
3767 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3768 Error = 13;
3770 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3771 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3772 AutoRange = D.getName().getSourceRange();
3774 if (Error != -1) {
3775 unsigned Kind;
3776 if (Auto) {
3777 switch (Auto->getKeyword()) {
3778 case AutoTypeKeyword::Auto: Kind = 0; break;
3779 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3780 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3782 } else {
3783 assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3784 "unknown auto type");
3785 Kind = 3;
3788 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3789 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3791 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3792 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3793 << QualType(Deduced, 0) << AutoRange;
3794 if (auto *TD = TN.getAsTemplateDecl())
3795 SemaRef.NoteTemplateLocation(*TD);
3797 T = SemaRef.Context.IntTy;
3798 D.setInvalidType(true);
3799 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) {
3800 // If there was a trailing return type, we already got
3801 // warn_cxx98_compat_trailing_return_type in the parser.
3802 SemaRef.Diag(AutoRange.getBegin(),
3803 D.getContext() == DeclaratorContext::LambdaExprParameter
3804 ? diag::warn_cxx11_compat_generic_lambda
3805 : IsDeducedReturnType
3806 ? diag::warn_cxx11_compat_deduced_return_type
3807 : diag::warn_cxx98_compat_auto_type_specifier)
3808 << AutoRange;
3812 if (SemaRef.getLangOpts().CPlusPlus &&
3813 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3814 // Check the contexts where C++ forbids the declaration of a new class
3815 // or enumeration in a type-specifier-seq.
3816 unsigned DiagID = 0;
3817 switch (D.getContext()) {
3818 case DeclaratorContext::TrailingReturn:
3819 case DeclaratorContext::TrailingReturnVar:
3820 // Class and enumeration definitions are syntactically not allowed in
3821 // trailing return types.
3822 llvm_unreachable("parser should not have allowed this");
3823 break;
3824 case DeclaratorContext::File:
3825 case DeclaratorContext::Member:
3826 case DeclaratorContext::Block:
3827 case DeclaratorContext::ForInit:
3828 case DeclaratorContext::SelectionInit:
3829 case DeclaratorContext::BlockLiteral:
3830 case DeclaratorContext::LambdaExpr:
3831 // C++11 [dcl.type]p3:
3832 // A type-specifier-seq shall not define a class or enumeration unless
3833 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3834 // the declaration of a template-declaration.
3835 case DeclaratorContext::AliasDecl:
3836 break;
3837 case DeclaratorContext::AliasTemplate:
3838 DiagID = diag::err_type_defined_in_alias_template;
3839 break;
3840 case DeclaratorContext::TypeName:
3841 case DeclaratorContext::FunctionalCast:
3842 case DeclaratorContext::ConversionId:
3843 case DeclaratorContext::TemplateParam:
3844 case DeclaratorContext::CXXNew:
3845 case DeclaratorContext::CXXCatch:
3846 case DeclaratorContext::ObjCCatch:
3847 case DeclaratorContext::TemplateArg:
3848 case DeclaratorContext::TemplateTypeArg:
3849 case DeclaratorContext::Association:
3850 DiagID = diag::err_type_defined_in_type_specifier;
3851 break;
3852 case DeclaratorContext::Prototype:
3853 case DeclaratorContext::LambdaExprParameter:
3854 case DeclaratorContext::ObjCParameter:
3855 case DeclaratorContext::ObjCResult:
3856 case DeclaratorContext::KNRTypeList:
3857 case DeclaratorContext::RequiresExpr:
3858 // C++ [dcl.fct]p6:
3859 // Types shall not be defined in return or parameter types.
3860 DiagID = diag::err_type_defined_in_param_type;
3861 break;
3862 case DeclaratorContext::Condition:
3863 // C++ 6.4p2:
3864 // The type-specifier-seq shall not contain typedef and shall not declare
3865 // a new class or enumeration.
3866 DiagID = diag::err_type_defined_in_condition;
3867 break;
3870 if (DiagID != 0) {
3871 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3872 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3873 D.setInvalidType(true);
3877 assert(!T.isNull() && "This function should not return a null type");
3878 return T;
3881 /// Produce an appropriate diagnostic for an ambiguity between a function
3882 /// declarator and a C++ direct-initializer.
3883 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3884 DeclaratorChunk &DeclType, QualType RT) {
3885 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3886 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3888 // If the return type is void there is no ambiguity.
3889 if (RT->isVoidType())
3890 return;
3892 // An initializer for a non-class type can have at most one argument.
3893 if (!RT->isRecordType() && FTI.NumParams > 1)
3894 return;
3896 // An initializer for a reference must have exactly one argument.
3897 if (RT->isReferenceType() && FTI.NumParams != 1)
3898 return;
3900 // Only warn if this declarator is declaring a function at block scope, and
3901 // doesn't have a storage class (such as 'extern') specified.
3902 if (!D.isFunctionDeclarator() ||
3903 D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration ||
3904 !S.CurContext->isFunctionOrMethod() ||
3905 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified)
3906 return;
3908 // Inside a condition, a direct initializer is not permitted. We allow one to
3909 // be parsed in order to give better diagnostics in condition parsing.
3910 if (D.getContext() == DeclaratorContext::Condition)
3911 return;
3913 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3915 S.Diag(DeclType.Loc,
3916 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3917 : diag::warn_empty_parens_are_function_decl)
3918 << ParenRange;
3920 // If the declaration looks like:
3921 // T var1,
3922 // f();
3923 // and name lookup finds a function named 'f', then the ',' was
3924 // probably intended to be a ';'.
3925 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3926 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3927 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3928 if (Comma.getFileID() != Name.getFileID() ||
3929 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3930 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3931 Sema::LookupOrdinaryName);
3932 if (S.LookupName(Result, S.getCurScope()))
3933 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3934 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3935 << D.getIdentifier();
3936 Result.suppressDiagnostics();
3940 if (FTI.NumParams > 0) {
3941 // For a declaration with parameters, eg. "T var(T());", suggest adding
3942 // parens around the first parameter to turn the declaration into a
3943 // variable declaration.
3944 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3945 SourceLocation B = Range.getBegin();
3946 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3947 // FIXME: Maybe we should suggest adding braces instead of parens
3948 // in C++11 for classes that don't have an initializer_list constructor.
3949 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3950 << FixItHint::CreateInsertion(B, "(")
3951 << FixItHint::CreateInsertion(E, ")");
3952 } else {
3953 // For a declaration without parameters, eg. "T var();", suggest replacing
3954 // the parens with an initializer to turn the declaration into a variable
3955 // declaration.
3956 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3958 // Empty parens mean value-initialization, and no parens mean
3959 // default initialization. These are equivalent if the default
3960 // constructor is user-provided or if zero-initialization is a
3961 // no-op.
3962 if (RD && RD->hasDefinition() &&
3963 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3964 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3965 << FixItHint::CreateRemoval(ParenRange);
3966 else {
3967 std::string Init =
3968 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3969 if (Init.empty() && S.LangOpts.CPlusPlus11)
3970 Init = "{}";
3971 if (!Init.empty())
3972 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3973 << FixItHint::CreateReplacement(ParenRange, Init);
3978 /// Produce an appropriate diagnostic for a declarator with top-level
3979 /// parentheses.
3980 static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
3981 DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
3982 assert(Paren.Kind == DeclaratorChunk::Paren &&
3983 "do not have redundant top-level parentheses");
3985 // This is a syntactic check; we're not interested in cases that arise
3986 // during template instantiation.
3987 if (S.inTemplateInstantiation())
3988 return;
3990 // Check whether this could be intended to be a construction of a temporary
3991 // object in C++ via a function-style cast.
3992 bool CouldBeTemporaryObject =
3993 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3994 !D.isInvalidType() && D.getIdentifier() &&
3995 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3996 (T->isRecordType() || T->isDependentType()) &&
3997 D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator();
3999 bool StartsWithDeclaratorId = true;
4000 for (auto &C : D.type_objects()) {
4001 switch (C.Kind) {
4002 case DeclaratorChunk::Paren:
4003 if (&C == &Paren)
4004 continue;
4005 [[fallthrough]];
4006 case DeclaratorChunk::Pointer:
4007 StartsWithDeclaratorId = false;
4008 continue;
4010 case DeclaratorChunk::Array:
4011 if (!C.Arr.NumElts)
4012 CouldBeTemporaryObject = false;
4013 continue;
4015 case DeclaratorChunk::Reference:
4016 // FIXME: Suppress the warning here if there is no initializer; we're
4017 // going to give an error anyway.
4018 // We assume that something like 'T (&x) = y;' is highly likely to not
4019 // be intended to be a temporary object.
4020 CouldBeTemporaryObject = false;
4021 StartsWithDeclaratorId = false;
4022 continue;
4024 case DeclaratorChunk::Function:
4025 // In a new-type-id, function chunks require parentheses.
4026 if (D.getContext() == DeclaratorContext::CXXNew)
4027 return;
4028 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
4029 // redundant-parens warning, but we don't know whether the function
4030 // chunk was syntactically valid as an expression here.
4031 CouldBeTemporaryObject = false;
4032 continue;
4034 case DeclaratorChunk::BlockPointer:
4035 case DeclaratorChunk::MemberPointer:
4036 case DeclaratorChunk::Pipe:
4037 // These cannot appear in expressions.
4038 CouldBeTemporaryObject = false;
4039 StartsWithDeclaratorId = false;
4040 continue;
4044 // FIXME: If there is an initializer, assume that this is not intended to be
4045 // a construction of a temporary object.
4047 // Check whether the name has already been declared; if not, this is not a
4048 // function-style cast.
4049 if (CouldBeTemporaryObject) {
4050 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
4051 Sema::LookupOrdinaryName);
4052 if (!S.LookupName(Result, S.getCurScope()))
4053 CouldBeTemporaryObject = false;
4054 Result.suppressDiagnostics();
4057 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
4059 if (!CouldBeTemporaryObject) {
4060 // If we have A (::B), the parentheses affect the meaning of the program.
4061 // Suppress the warning in that case. Don't bother looking at the DeclSpec
4062 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
4063 // formally unambiguous.
4064 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
4065 for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
4066 NNS = NNS->getPrefix()) {
4067 if (NNS->getKind() == NestedNameSpecifier::Global)
4068 return;
4072 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
4073 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
4074 << FixItHint::CreateRemoval(Paren.EndLoc);
4075 return;
4078 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
4079 << ParenRange << D.getIdentifier();
4080 auto *RD = T->getAsCXXRecordDecl();
4081 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
4082 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
4083 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
4084 << D.getIdentifier();
4085 // FIXME: A cast to void is probably a better suggestion in cases where it's
4086 // valid (when there is no initializer and we're not in a condition).
4087 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
4088 << FixItHint::CreateInsertion(D.getBeginLoc(), "(")
4089 << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")");
4090 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
4091 << FixItHint::CreateRemoval(Paren.Loc)
4092 << FixItHint::CreateRemoval(Paren.EndLoc);
4095 /// Helper for figuring out the default CC for a function declarator type. If
4096 /// this is the outermost chunk, then we can determine the CC from the
4097 /// declarator context. If not, then this could be either a member function
4098 /// type or normal function type.
4099 static CallingConv getCCForDeclaratorChunk(
4100 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
4101 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
4102 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
4104 // Check for an explicit CC attribute.
4105 for (const ParsedAttr &AL : AttrList) {
4106 switch (AL.getKind()) {
4107 CALLING_CONV_ATTRS_CASELIST : {
4108 // Ignore attributes that don't validate or can't apply to the
4109 // function type. We'll diagnose the failure to apply them in
4110 // handleFunctionTypeAttr.
4111 CallingConv CC;
4112 if (!S.CheckCallingConvAttr(AL, CC, /*FunctionDecl=*/nullptr,
4113 S.IdentifyCUDATarget(D.getAttributes())) &&
4114 (!FTI.isVariadic || supportsVariadicCall(CC))) {
4115 return CC;
4117 break;
4120 default:
4121 break;
4125 bool IsCXXInstanceMethod = false;
4127 if (S.getLangOpts().CPlusPlus) {
4128 // Look inwards through parentheses to see if this chunk will form a
4129 // member pointer type or if we're the declarator. Any type attributes
4130 // between here and there will override the CC we choose here.
4131 unsigned I = ChunkIndex;
4132 bool FoundNonParen = false;
4133 while (I && !FoundNonParen) {
4134 --I;
4135 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
4136 FoundNonParen = true;
4139 if (FoundNonParen) {
4140 // If we're not the declarator, we're a regular function type unless we're
4141 // in a member pointer.
4142 IsCXXInstanceMethod =
4143 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
4144 } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
4145 // This can only be a call operator for a lambda, which is an instance
4146 // method, unless explicitly specified as 'static'.
4147 IsCXXInstanceMethod =
4148 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static;
4149 } else {
4150 // We're the innermost decl chunk, so must be a function declarator.
4151 assert(D.isFunctionDeclarator());
4153 // If we're inside a record, we're declaring a method, but it could be
4154 // explicitly or implicitly static.
4155 IsCXXInstanceMethod =
4156 D.isFirstDeclarationOfMember() &&
4157 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
4158 !D.isStaticMember();
4162 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
4163 IsCXXInstanceMethod);
4165 // Attribute AT_OpenCLKernel affects the calling convention for SPIR
4166 // and AMDGPU targets, hence it cannot be treated as a calling
4167 // convention attribute. This is the simplest place to infer
4168 // calling convention for OpenCL kernels.
4169 if (S.getLangOpts().OpenCL) {
4170 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4171 if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
4172 CC = CC_OpenCLKernel;
4173 break;
4176 } else if (S.getLangOpts().CUDA) {
4177 // If we're compiling CUDA/HIP code and targeting SPIR-V we need to make
4178 // sure the kernels will be marked with the right calling convention so that
4179 // they will be visible by the APIs that ingest SPIR-V.
4180 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
4181 if (Triple.getArch() == llvm::Triple::spirv32 ||
4182 Triple.getArch() == llvm::Triple::spirv64) {
4183 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4184 if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) {
4185 CC = CC_OpenCLKernel;
4186 break;
4192 return CC;
4195 namespace {
4196 /// A simple notion of pointer kinds, which matches up with the various
4197 /// pointer declarators.
4198 enum class SimplePointerKind {
4199 Pointer,
4200 BlockPointer,
4201 MemberPointer,
4202 Array,
4204 } // end anonymous namespace
4206 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
4207 switch (nullability) {
4208 case NullabilityKind::NonNull:
4209 if (!Ident__Nonnull)
4210 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
4211 return Ident__Nonnull;
4213 case NullabilityKind::Nullable:
4214 if (!Ident__Nullable)
4215 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
4216 return Ident__Nullable;
4218 case NullabilityKind::NullableResult:
4219 if (!Ident__Nullable_result)
4220 Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
4221 return Ident__Nullable_result;
4223 case NullabilityKind::Unspecified:
4224 if (!Ident__Null_unspecified)
4225 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
4226 return Ident__Null_unspecified;
4228 llvm_unreachable("Unknown nullability kind.");
4231 /// Retrieve the identifier "NSError".
4232 IdentifierInfo *Sema::getNSErrorIdent() {
4233 if (!Ident_NSError)
4234 Ident_NSError = PP.getIdentifierInfo("NSError");
4236 return Ident_NSError;
4239 /// Check whether there is a nullability attribute of any kind in the given
4240 /// attribute list.
4241 static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
4242 for (const ParsedAttr &AL : attrs) {
4243 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
4244 AL.getKind() == ParsedAttr::AT_TypeNullable ||
4245 AL.getKind() == ParsedAttr::AT_TypeNullableResult ||
4246 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
4247 return true;
4250 return false;
4253 namespace {
4254 /// Describes the kind of a pointer a declarator describes.
4255 enum class PointerDeclaratorKind {
4256 // Not a pointer.
4257 NonPointer,
4258 // Single-level pointer.
4259 SingleLevelPointer,
4260 // Multi-level pointer (of any pointer kind).
4261 MultiLevelPointer,
4262 // CFFooRef*
4263 MaybePointerToCFRef,
4264 // CFErrorRef*
4265 CFErrorRefPointer,
4266 // NSError**
4267 NSErrorPointerPointer,
4270 /// Describes a declarator chunk wrapping a pointer that marks inference as
4271 /// unexpected.
4272 // These values must be kept in sync with diagnostics.
4273 enum class PointerWrappingDeclaratorKind {
4274 /// Pointer is top-level.
4275 None = -1,
4276 /// Pointer is an array element.
4277 Array = 0,
4278 /// Pointer is the referent type of a C++ reference.
4279 Reference = 1
4281 } // end anonymous namespace
4283 /// Classify the given declarator, whose type-specified is \c type, based on
4284 /// what kind of pointer it refers to.
4286 /// This is used to determine the default nullability.
4287 static PointerDeclaratorKind
4288 classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
4289 PointerWrappingDeclaratorKind &wrappingKind) {
4290 unsigned numNormalPointers = 0;
4292 // For any dependent type, we consider it a non-pointer.
4293 if (type->isDependentType())
4294 return PointerDeclaratorKind::NonPointer;
4296 // Look through the declarator chunks to identify pointers.
4297 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
4298 DeclaratorChunk &chunk = declarator.getTypeObject(i);
4299 switch (chunk.Kind) {
4300 case DeclaratorChunk::Array:
4301 if (numNormalPointers == 0)
4302 wrappingKind = PointerWrappingDeclaratorKind::Array;
4303 break;
4305 case DeclaratorChunk::Function:
4306 case DeclaratorChunk::Pipe:
4307 break;
4309 case DeclaratorChunk::BlockPointer:
4310 case DeclaratorChunk::MemberPointer:
4311 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4312 : PointerDeclaratorKind::SingleLevelPointer;
4314 case DeclaratorChunk::Paren:
4315 break;
4317 case DeclaratorChunk::Reference:
4318 if (numNormalPointers == 0)
4319 wrappingKind = PointerWrappingDeclaratorKind::Reference;
4320 break;
4322 case DeclaratorChunk::Pointer:
4323 ++numNormalPointers;
4324 if (numNormalPointers > 2)
4325 return PointerDeclaratorKind::MultiLevelPointer;
4326 break;
4330 // Then, dig into the type specifier itself.
4331 unsigned numTypeSpecifierPointers = 0;
4332 do {
4333 // Decompose normal pointers.
4334 if (auto ptrType = type->getAs<PointerType>()) {
4335 ++numNormalPointers;
4337 if (numNormalPointers > 2)
4338 return PointerDeclaratorKind::MultiLevelPointer;
4340 type = ptrType->getPointeeType();
4341 ++numTypeSpecifierPointers;
4342 continue;
4345 // Decompose block pointers.
4346 if (type->getAs<BlockPointerType>()) {
4347 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4348 : PointerDeclaratorKind::SingleLevelPointer;
4351 // Decompose member pointers.
4352 if (type->getAs<MemberPointerType>()) {
4353 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4354 : PointerDeclaratorKind::SingleLevelPointer;
4357 // Look at Objective-C object pointers.
4358 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
4359 ++numNormalPointers;
4360 ++numTypeSpecifierPointers;
4362 // If this is NSError**, report that.
4363 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
4364 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
4365 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
4366 return PointerDeclaratorKind::NSErrorPointerPointer;
4370 break;
4373 // Look at Objective-C class types.
4374 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
4375 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
4376 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
4377 return PointerDeclaratorKind::NSErrorPointerPointer;
4380 break;
4383 // If at this point we haven't seen a pointer, we won't see one.
4384 if (numNormalPointers == 0)
4385 return PointerDeclaratorKind::NonPointer;
4387 if (auto recordType = type->getAs<RecordType>()) {
4388 RecordDecl *recordDecl = recordType->getDecl();
4390 // If this is CFErrorRef*, report it as such.
4391 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 &&
4392 S.isCFError(recordDecl)) {
4393 return PointerDeclaratorKind::CFErrorRefPointer;
4395 break;
4398 break;
4399 } while (true);
4401 switch (numNormalPointers) {
4402 case 0:
4403 return PointerDeclaratorKind::NonPointer;
4405 case 1:
4406 return PointerDeclaratorKind::SingleLevelPointer;
4408 case 2:
4409 return PointerDeclaratorKind::MaybePointerToCFRef;
4411 default:
4412 return PointerDeclaratorKind::MultiLevelPointer;
4416 bool Sema::isCFError(RecordDecl *RD) {
4417 // If we already know about CFError, test it directly.
4418 if (CFError)
4419 return CFError == RD;
4421 // Check whether this is CFError, which we identify based on its bridge to
4422 // NSError. CFErrorRef used to be declared with "objc_bridge" but is now
4423 // declared with "objc_bridge_mutable", so look for either one of the two
4424 // attributes.
4425 if (RD->getTagKind() == TagTypeKind::Struct) {
4426 IdentifierInfo *bridgedType = nullptr;
4427 if (auto bridgeAttr = RD->getAttr<ObjCBridgeAttr>())
4428 bridgedType = bridgeAttr->getBridgedType();
4429 else if (auto bridgeAttr = RD->getAttr<ObjCBridgeMutableAttr>())
4430 bridgedType = bridgeAttr->getBridgedType();
4432 if (bridgedType == getNSErrorIdent()) {
4433 CFError = RD;
4434 return true;
4438 return false;
4441 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
4442 SourceLocation loc) {
4443 // If we're anywhere in a function, method, or closure context, don't perform
4444 // completeness checks.
4445 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
4446 if (ctx->isFunctionOrMethod())
4447 return FileID();
4449 if (ctx->isFileContext())
4450 break;
4453 // We only care about the expansion location.
4454 loc = S.SourceMgr.getExpansionLoc(loc);
4455 FileID file = S.SourceMgr.getFileID(loc);
4456 if (file.isInvalid())
4457 return FileID();
4459 // Retrieve file information.
4460 bool invalid = false;
4461 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4462 if (invalid || !sloc.isFile())
4463 return FileID();
4465 // We don't want to perform completeness checks on the main file or in
4466 // system headers.
4467 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4468 if (fileInfo.getIncludeLoc().isInvalid())
4469 return FileID();
4470 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4471 S.Diags.getSuppressSystemWarnings()) {
4472 return FileID();
4475 return file;
4478 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4479 /// taking into account whitespace before and after.
4480 template <typename DiagBuilderT>
4481 static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4482 SourceLocation PointerLoc,
4483 NullabilityKind Nullability) {
4484 assert(PointerLoc.isValid());
4485 if (PointerLoc.isMacroID())
4486 return;
4488 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4489 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4490 return;
4492 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4493 if (!NextChar)
4494 return;
4496 SmallString<32> InsertionTextBuf{" "};
4497 InsertionTextBuf += getNullabilitySpelling(Nullability);
4498 InsertionTextBuf += " ";
4499 StringRef InsertionText = InsertionTextBuf.str();
4501 if (isWhitespace(*NextChar)) {
4502 InsertionText = InsertionText.drop_back();
4503 } else if (NextChar[-1] == '[') {
4504 if (NextChar[0] == ']')
4505 InsertionText = InsertionText.drop_back().drop_front();
4506 else
4507 InsertionText = InsertionText.drop_front();
4508 } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) &&
4509 !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) {
4510 InsertionText = InsertionText.drop_back().drop_front();
4513 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4516 static void emitNullabilityConsistencyWarning(Sema &S,
4517 SimplePointerKind PointerKind,
4518 SourceLocation PointerLoc,
4519 SourceLocation PointerEndLoc) {
4520 assert(PointerLoc.isValid());
4522 if (PointerKind == SimplePointerKind::Array) {
4523 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4524 } else {
4525 S.Diag(PointerLoc, diag::warn_nullability_missing)
4526 << static_cast<unsigned>(PointerKind);
4529 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4530 if (FixItLoc.isMacroID())
4531 return;
4533 auto addFixIt = [&](NullabilityKind Nullability) {
4534 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4535 Diag << static_cast<unsigned>(Nullability);
4536 Diag << static_cast<unsigned>(PointerKind);
4537 fixItNullability(S, Diag, FixItLoc, Nullability);
4539 addFixIt(NullabilityKind::Nullable);
4540 addFixIt(NullabilityKind::NonNull);
4543 /// Complains about missing nullability if the file containing \p pointerLoc
4544 /// has other uses of nullability (either the keywords or the \c assume_nonnull
4545 /// pragma).
4547 /// If the file has \e not seen other uses of nullability, this particular
4548 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4549 static void
4550 checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4551 SourceLocation pointerLoc,
4552 SourceLocation pointerEndLoc = SourceLocation()) {
4553 // Determine which file we're performing consistency checking for.
4554 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4555 if (file.isInvalid())
4556 return;
4558 // If we haven't seen any type nullability in this file, we won't warn now
4559 // about anything.
4560 FileNullability &fileNullability = S.NullabilityMap[file];
4561 if (!fileNullability.SawTypeNullability) {
4562 // If this is the first pointer declarator in the file, and the appropriate
4563 // warning is on, record it in case we need to diagnose it retroactively.
4564 diag::kind diagKind;
4565 if (pointerKind == SimplePointerKind::Array)
4566 diagKind = diag::warn_nullability_missing_array;
4567 else
4568 diagKind = diag::warn_nullability_missing;
4570 if (fileNullability.PointerLoc.isInvalid() &&
4571 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
4572 fileNullability.PointerLoc = pointerLoc;
4573 fileNullability.PointerEndLoc = pointerEndLoc;
4574 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4577 return;
4580 // Complain about missing nullability.
4581 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4584 /// Marks that a nullability feature has been used in the file containing
4585 /// \p loc.
4587 /// If this file already had pointer types in it that were missing nullability,
4588 /// the first such instance is retroactively diagnosed.
4590 /// \sa checkNullabilityConsistency
4591 static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
4592 FileID file = getNullabilityCompletenessCheckFileID(S, loc);
4593 if (file.isInvalid())
4594 return;
4596 FileNullability &fileNullability = S.NullabilityMap[file];
4597 if (fileNullability.SawTypeNullability)
4598 return;
4599 fileNullability.SawTypeNullability = true;
4601 // If we haven't seen any type nullability before, now we have. Retroactively
4602 // diagnose the first unannotated pointer, if there was one.
4603 if (fileNullability.PointerLoc.isInvalid())
4604 return;
4606 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4607 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
4608 fileNullability.PointerEndLoc);
4611 /// Returns true if any of the declarator chunks before \p endIndex include a
4612 /// level of indirection: array, pointer, reference, or pointer-to-member.
4614 /// Because declarator chunks are stored in outer-to-inner order, testing
4615 /// every chunk before \p endIndex is testing all chunks that embed the current
4616 /// chunk as part of their type.
4618 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4619 /// end index, in which case all chunks are tested.
4620 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4621 unsigned i = endIndex;
4622 while (i != 0) {
4623 // Walk outwards along the declarator chunks.
4624 --i;
4625 const DeclaratorChunk &DC = D.getTypeObject(i);
4626 switch (DC.Kind) {
4627 case DeclaratorChunk::Paren:
4628 break;
4629 case DeclaratorChunk::Array:
4630 case DeclaratorChunk::Pointer:
4631 case DeclaratorChunk::Reference:
4632 case DeclaratorChunk::MemberPointer:
4633 return true;
4634 case DeclaratorChunk::Function:
4635 case DeclaratorChunk::BlockPointer:
4636 case DeclaratorChunk::Pipe:
4637 // These are invalid anyway, so just ignore.
4638 break;
4641 return false;
4644 static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk) {
4645 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4646 Chunk.Kind == DeclaratorChunk::Array);
4649 template<typename AttrT>
4650 static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4651 AL.setUsedAsTypeAttr();
4652 return ::new (Ctx) AttrT(Ctx, AL);
4655 static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr,
4656 NullabilityKind NK) {
4657 switch (NK) {
4658 case NullabilityKind::NonNull:
4659 return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
4661 case NullabilityKind::Nullable:
4662 return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
4664 case NullabilityKind::NullableResult:
4665 return createSimpleAttr<TypeNullableResultAttr>(Ctx, Attr);
4667 case NullabilityKind::Unspecified:
4668 return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
4670 llvm_unreachable("unknown NullabilityKind");
4673 // Diagnose whether this is a case with the multiple addr spaces.
4674 // Returns true if this is an invalid case.
4675 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4676 // by qualifiers for two or more different address spaces."
4677 static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld,
4678 LangAS ASNew,
4679 SourceLocation AttrLoc) {
4680 if (ASOld != LangAS::Default) {
4681 if (ASOld != ASNew) {
4682 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4683 return true;
4685 // Emit a warning if they are identical; it's likely unintended.
4686 S.Diag(AttrLoc,
4687 diag::warn_attribute_address_multiple_identical_qualifiers);
4689 return false;
4692 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4693 QualType declSpecType,
4694 TypeSourceInfo *TInfo) {
4695 // The TypeSourceInfo that this function returns will not be a null type.
4696 // If there is an error, this function will fill in a dummy type as fallback.
4697 QualType T = declSpecType;
4698 Declarator &D = state.getDeclarator();
4699 Sema &S = state.getSema();
4700 ASTContext &Context = S.Context;
4701 const LangOptions &LangOpts = S.getLangOpts();
4703 // The name we're declaring, if any.
4704 DeclarationName Name;
4705 if (D.getIdentifier())
4706 Name = D.getIdentifier();
4708 // Does this declaration declare a typedef-name?
4709 bool IsTypedefName =
4710 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
4711 D.getContext() == DeclaratorContext::AliasDecl ||
4712 D.getContext() == DeclaratorContext::AliasTemplate;
4714 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4715 bool IsQualifiedFunction = T->isFunctionProtoType() &&
4716 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4717 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4719 // If T is 'decltype(auto)', the only declarators we can have are parens
4720 // and at most one function declarator if this is a function declaration.
4721 // If T is a deduced class template specialization type, we can have no
4722 // declarator chunks at all.
4723 if (auto *DT = T->getAs<DeducedType>()) {
4724 const AutoType *AT = T->getAs<AutoType>();
4725 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4726 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4727 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4728 unsigned Index = E - I - 1;
4729 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4730 unsigned DiagId = IsClassTemplateDeduction
4731 ? diag::err_deduced_class_template_compound_type
4732 : diag::err_decltype_auto_compound_type;
4733 unsigned DiagKind = 0;
4734 switch (DeclChunk.Kind) {
4735 case DeclaratorChunk::Paren:
4736 // FIXME: Rejecting this is a little silly.
4737 if (IsClassTemplateDeduction) {
4738 DiagKind = 4;
4739 break;
4741 continue;
4742 case DeclaratorChunk::Function: {
4743 if (IsClassTemplateDeduction) {
4744 DiagKind = 3;
4745 break;
4747 unsigned FnIndex;
4748 if (D.isFunctionDeclarationContext() &&
4749 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4750 continue;
4751 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4752 break;
4754 case DeclaratorChunk::Pointer:
4755 case DeclaratorChunk::BlockPointer:
4756 case DeclaratorChunk::MemberPointer:
4757 DiagKind = 0;
4758 break;
4759 case DeclaratorChunk::Reference:
4760 DiagKind = 1;
4761 break;
4762 case DeclaratorChunk::Array:
4763 DiagKind = 2;
4764 break;
4765 case DeclaratorChunk::Pipe:
4766 break;
4769 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4770 D.setInvalidType(true);
4771 break;
4776 // Determine whether we should infer _Nonnull on pointer types.
4777 std::optional<NullabilityKind> inferNullability;
4778 bool inferNullabilityCS = false;
4779 bool inferNullabilityInnerOnly = false;
4780 bool inferNullabilityInnerOnlyComplete = false;
4782 // Are we in an assume-nonnull region?
4783 bool inAssumeNonNullRegion = false;
4784 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4785 if (assumeNonNullLoc.isValid()) {
4786 inAssumeNonNullRegion = true;
4787 recordNullabilitySeen(S, assumeNonNullLoc);
4790 // Whether to complain about missing nullability specifiers or not.
4791 enum {
4792 /// Never complain.
4793 CAMN_No,
4794 /// Complain on the inner pointers (but not the outermost
4795 /// pointer).
4796 CAMN_InnerPointers,
4797 /// Complain about any pointers that don't have nullability
4798 /// specified or inferred.
4799 CAMN_Yes
4800 } complainAboutMissingNullability = CAMN_No;
4801 unsigned NumPointersRemaining = 0;
4802 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4804 if (IsTypedefName) {
4805 // For typedefs, we do not infer any nullability (the default),
4806 // and we only complain about missing nullability specifiers on
4807 // inner pointers.
4808 complainAboutMissingNullability = CAMN_InnerPointers;
4810 if (T->canHaveNullability(/*ResultIfUnknown*/ false) &&
4811 !T->getNullability()) {
4812 // Note that we allow but don't require nullability on dependent types.
4813 ++NumPointersRemaining;
4816 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4817 DeclaratorChunk &chunk = D.getTypeObject(i);
4818 switch (chunk.Kind) {
4819 case DeclaratorChunk::Array:
4820 case DeclaratorChunk::Function:
4821 case DeclaratorChunk::Pipe:
4822 break;
4824 case DeclaratorChunk::BlockPointer:
4825 case DeclaratorChunk::MemberPointer:
4826 ++NumPointersRemaining;
4827 break;
4829 case DeclaratorChunk::Paren:
4830 case DeclaratorChunk::Reference:
4831 continue;
4833 case DeclaratorChunk::Pointer:
4834 ++NumPointersRemaining;
4835 continue;
4838 } else {
4839 bool isFunctionOrMethod = false;
4840 switch (auto context = state.getDeclarator().getContext()) {
4841 case DeclaratorContext::ObjCParameter:
4842 case DeclaratorContext::ObjCResult:
4843 case DeclaratorContext::Prototype:
4844 case DeclaratorContext::TrailingReturn:
4845 case DeclaratorContext::TrailingReturnVar:
4846 isFunctionOrMethod = true;
4847 [[fallthrough]];
4849 case DeclaratorContext::Member:
4850 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4851 complainAboutMissingNullability = CAMN_No;
4852 break;
4855 // Weak properties are inferred to be nullable.
4856 if (state.getDeclarator().isObjCWeakProperty()) {
4857 // Weak properties cannot be nonnull, and should not complain about
4858 // missing nullable attributes during completeness checks.
4859 complainAboutMissingNullability = CAMN_No;
4860 if (inAssumeNonNullRegion) {
4861 inferNullability = NullabilityKind::Nullable;
4863 break;
4866 [[fallthrough]];
4868 case DeclaratorContext::File:
4869 case DeclaratorContext::KNRTypeList: {
4870 complainAboutMissingNullability = CAMN_Yes;
4872 // Nullability inference depends on the type and declarator.
4873 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4874 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4875 case PointerDeclaratorKind::NonPointer:
4876 case PointerDeclaratorKind::MultiLevelPointer:
4877 // Cannot infer nullability.
4878 break;
4880 case PointerDeclaratorKind::SingleLevelPointer:
4881 // Infer _Nonnull if we are in an assumes-nonnull region.
4882 if (inAssumeNonNullRegion) {
4883 complainAboutInferringWithinChunk = wrappingKind;
4884 inferNullability = NullabilityKind::NonNull;
4885 inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4886 context == DeclaratorContext::ObjCResult);
4888 break;
4890 case PointerDeclaratorKind::CFErrorRefPointer:
4891 case PointerDeclaratorKind::NSErrorPointerPointer:
4892 // Within a function or method signature, infer _Nullable at both
4893 // levels.
4894 if (isFunctionOrMethod && inAssumeNonNullRegion)
4895 inferNullability = NullabilityKind::Nullable;
4896 break;
4898 case PointerDeclaratorKind::MaybePointerToCFRef:
4899 if (isFunctionOrMethod) {
4900 // On pointer-to-pointer parameters marked cf_returns_retained or
4901 // cf_returns_not_retained, if the outer pointer is explicit then
4902 // infer the inner pointer as _Nullable.
4903 auto hasCFReturnsAttr =
4904 [](const ParsedAttributesView &AttrList) -> bool {
4905 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4906 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4908 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4909 if (hasCFReturnsAttr(D.getDeclarationAttributes()) ||
4910 hasCFReturnsAttr(D.getAttributes()) ||
4911 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4912 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4913 inferNullability = NullabilityKind::Nullable;
4914 inferNullabilityInnerOnly = true;
4918 break;
4920 break;
4923 case DeclaratorContext::ConversionId:
4924 complainAboutMissingNullability = CAMN_Yes;
4925 break;
4927 case DeclaratorContext::AliasDecl:
4928 case DeclaratorContext::AliasTemplate:
4929 case DeclaratorContext::Block:
4930 case DeclaratorContext::BlockLiteral:
4931 case DeclaratorContext::Condition:
4932 case DeclaratorContext::CXXCatch:
4933 case DeclaratorContext::CXXNew:
4934 case DeclaratorContext::ForInit:
4935 case DeclaratorContext::SelectionInit:
4936 case DeclaratorContext::LambdaExpr:
4937 case DeclaratorContext::LambdaExprParameter:
4938 case DeclaratorContext::ObjCCatch:
4939 case DeclaratorContext::TemplateParam:
4940 case DeclaratorContext::TemplateArg:
4941 case DeclaratorContext::TemplateTypeArg:
4942 case DeclaratorContext::TypeName:
4943 case DeclaratorContext::FunctionalCast:
4944 case DeclaratorContext::RequiresExpr:
4945 case DeclaratorContext::Association:
4946 // Don't infer in these contexts.
4947 break;
4951 // Local function that returns true if its argument looks like a va_list.
4952 auto isVaList = [&S](QualType T) -> bool {
4953 auto *typedefTy = T->getAs<TypedefType>();
4954 if (!typedefTy)
4955 return false;
4956 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4957 do {
4958 if (typedefTy->getDecl() == vaListTypedef)
4959 return true;
4960 if (auto *name = typedefTy->getDecl()->getIdentifier())
4961 if (name->isStr("va_list"))
4962 return true;
4963 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4964 } while (typedefTy);
4965 return false;
4968 // Local function that checks the nullability for a given pointer declarator.
4969 // Returns true if _Nonnull was inferred.
4970 auto inferPointerNullability =
4971 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4972 SourceLocation pointerEndLoc,
4973 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4974 // We've seen a pointer.
4975 if (NumPointersRemaining > 0)
4976 --NumPointersRemaining;
4978 // If a nullability attribute is present, there's nothing to do.
4979 if (hasNullabilityAttr(attrs))
4980 return nullptr;
4982 // If we're supposed to infer nullability, do so now.
4983 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4984 ParsedAttr::Form form =
4985 inferNullabilityCS
4986 ? ParsedAttr::Form::ContextSensitiveKeyword()
4987 : ParsedAttr::Form::Keyword(false /*IsAlignAs*/,
4988 false /*IsRegularKeywordAttribute*/);
4989 ParsedAttr *nullabilityAttr = Pool.create(
4990 S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4991 nullptr, SourceLocation(), nullptr, 0, form);
4993 attrs.addAtEnd(nullabilityAttr);
4995 if (inferNullabilityCS) {
4996 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4997 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
5000 if (pointerLoc.isValid() &&
5001 complainAboutInferringWithinChunk !=
5002 PointerWrappingDeclaratorKind::None) {
5003 auto Diag =
5004 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
5005 Diag << static_cast<int>(complainAboutInferringWithinChunk);
5006 fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
5009 if (inferNullabilityInnerOnly)
5010 inferNullabilityInnerOnlyComplete = true;
5011 return nullabilityAttr;
5014 // If we're supposed to complain about missing nullability, do so
5015 // now if it's truly missing.
5016 switch (complainAboutMissingNullability) {
5017 case CAMN_No:
5018 break;
5020 case CAMN_InnerPointers:
5021 if (NumPointersRemaining == 0)
5022 break;
5023 [[fallthrough]];
5025 case CAMN_Yes:
5026 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
5028 return nullptr;
5031 // If the type itself could have nullability but does not, infer pointer
5032 // nullability and perform consistency checking.
5033 if (S.CodeSynthesisContexts.empty()) {
5034 if (T->canHaveNullability(/*ResultIfUnknown*/ false) &&
5035 !T->getNullability()) {
5036 if (isVaList(T)) {
5037 // Record that we've seen a pointer, but do nothing else.
5038 if (NumPointersRemaining > 0)
5039 --NumPointersRemaining;
5040 } else {
5041 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
5042 if (T->isBlockPointerType())
5043 pointerKind = SimplePointerKind::BlockPointer;
5044 else if (T->isMemberPointerType())
5045 pointerKind = SimplePointerKind::MemberPointer;
5047 if (auto *attr = inferPointerNullability(
5048 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
5049 D.getDeclSpec().getEndLoc(),
5050 D.getMutableDeclSpec().getAttributes(),
5051 D.getMutableDeclSpec().getAttributePool())) {
5052 T = state.getAttributedType(
5053 createNullabilityAttr(Context, *attr, *inferNullability), T, T);
5058 if (complainAboutMissingNullability == CAMN_Yes && T->isArrayType() &&
5059 !T->getNullability() && !isVaList(T) && D.isPrototypeContext() &&
5060 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
5061 checkNullabilityConsistency(S, SimplePointerKind::Array,
5062 D.getDeclSpec().getTypeSpecTypeLoc());
5066 bool ExpectNoDerefChunk =
5067 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
5069 // Walk the DeclTypeInfo, building the recursive type as we go.
5070 // DeclTypeInfos are ordered from the identifier out, which is
5071 // opposite of what we want :).
5073 // Track if the produced type matches the structure of the declarator.
5074 // This is used later to decide if we can fill `TypeLoc` from
5075 // `DeclaratorChunk`s. E.g. it must be false if Clang recovers from
5076 // an error by replacing the type with `int`.
5077 bool AreDeclaratorChunksValid = true;
5078 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5079 unsigned chunkIndex = e - i - 1;
5080 state.setCurrentChunkIndex(chunkIndex);
5081 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
5082 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
5083 switch (DeclType.Kind) {
5084 case DeclaratorChunk::Paren:
5085 if (i == 0)
5086 warnAboutRedundantParens(S, D, T);
5087 T = S.BuildParenType(T);
5088 break;
5089 case DeclaratorChunk::BlockPointer:
5090 // If blocks are disabled, emit an error.
5091 if (!LangOpts.Blocks)
5092 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
5094 // Handle pointer nullability.
5095 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
5096 DeclType.EndLoc, DeclType.getAttrs(),
5097 state.getDeclarator().getAttributePool());
5099 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
5100 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
5101 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
5102 // qualified with const.
5103 if (LangOpts.OpenCL)
5104 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
5105 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
5107 break;
5108 case DeclaratorChunk::Pointer:
5109 // Verify that we're not building a pointer to pointer to function with
5110 // exception specification.
5111 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
5112 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
5113 D.setInvalidType(true);
5114 // Build the type anyway.
5117 // Handle pointer nullability
5118 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
5119 DeclType.EndLoc, DeclType.getAttrs(),
5120 state.getDeclarator().getAttributePool());
5122 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
5123 T = Context.getObjCObjectPointerType(T);
5124 if (DeclType.Ptr.TypeQuals)
5125 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
5126 break;
5129 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
5130 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
5131 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
5132 if (LangOpts.OpenCL) {
5133 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
5134 T->isBlockPointerType()) {
5135 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
5136 D.setInvalidType(true);
5140 T = S.BuildPointerType(T, DeclType.Loc, Name);
5141 if (DeclType.Ptr.TypeQuals)
5142 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
5143 break;
5144 case DeclaratorChunk::Reference: {
5145 // Verify that we're not building a reference to pointer to function with
5146 // exception specification.
5147 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
5148 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
5149 D.setInvalidType(true);
5150 // Build the type anyway.
5152 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
5154 if (DeclType.Ref.HasRestrict)
5155 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
5156 break;
5158 case DeclaratorChunk::Array: {
5159 // Verify that we're not building an array of pointers to function with
5160 // exception specification.
5161 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
5162 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
5163 D.setInvalidType(true);
5164 // Build the type anyway.
5166 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
5167 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
5168 ArraySizeModifier ASM;
5170 // Microsoft property fields can have multiple sizeless array chunks
5171 // (i.e. int x[][][]). Skip all of these except one to avoid creating
5172 // bad incomplete array types.
5173 if (chunkIndex != 0 && !ArraySize &&
5174 D.getDeclSpec().getAttributes().hasMSPropertyAttr()) {
5175 // This is a sizeless chunk. If the next is also, skip this one.
5176 DeclaratorChunk &NextDeclType = D.getTypeObject(chunkIndex - 1);
5177 if (NextDeclType.Kind == DeclaratorChunk::Array &&
5178 !NextDeclType.Arr.NumElts)
5179 break;
5182 if (ATI.isStar)
5183 ASM = ArraySizeModifier::Star;
5184 else if (ATI.hasStatic)
5185 ASM = ArraySizeModifier::Static;
5186 else
5187 ASM = ArraySizeModifier::Normal;
5188 if (ASM == ArraySizeModifier::Star && !D.isPrototypeContext()) {
5189 // FIXME: This check isn't quite right: it allows star in prototypes
5190 // for function definitions, and disallows some edge cases detailed
5191 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
5192 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
5193 ASM = ArraySizeModifier::Normal;
5194 D.setInvalidType(true);
5197 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
5198 // shall appear only in a declaration of a function parameter with an
5199 // array type, ...
5200 if (ASM == ArraySizeModifier::Static || ATI.TypeQuals) {
5201 if (!(D.isPrototypeContext() ||
5202 D.getContext() == DeclaratorContext::KNRTypeList)) {
5203 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype)
5204 << (ASM == ArraySizeModifier::Static ? "'static'"
5205 : "type qualifier");
5206 // Remove the 'static' and the type qualifiers.
5207 if (ASM == ArraySizeModifier::Static)
5208 ASM = ArraySizeModifier::Normal;
5209 ATI.TypeQuals = 0;
5210 D.setInvalidType(true);
5213 // C99 6.7.5.2p1: ... and then only in the outermost array type
5214 // derivation.
5215 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
5216 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost)
5217 << (ASM == ArraySizeModifier::Static ? "'static'"
5218 : "type qualifier");
5219 if (ASM == ArraySizeModifier::Static)
5220 ASM = ArraySizeModifier::Normal;
5221 ATI.TypeQuals = 0;
5222 D.setInvalidType(true);
5226 // Array parameters can be marked nullable as well, although it's not
5227 // necessary if they're marked 'static'.
5228 if (complainAboutMissingNullability == CAMN_Yes &&
5229 !hasNullabilityAttr(DeclType.getAttrs()) &&
5230 ASM != ArraySizeModifier::Static && D.isPrototypeContext() &&
5231 !hasOuterPointerLikeChunk(D, chunkIndex)) {
5232 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
5235 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
5236 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
5237 break;
5239 case DeclaratorChunk::Function: {
5240 // If the function declarator has a prototype (i.e. it is not () and
5241 // does not have a K&R-style identifier list), then the arguments are part
5242 // of the type, otherwise the argument list is ().
5243 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5244 IsQualifiedFunction =
5245 FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier();
5247 // Check for auto functions and trailing return type and adjust the
5248 // return type accordingly.
5249 if (!D.isInvalidType()) {
5250 // trailing-return-type is only required if we're declaring a function,
5251 // and not, for instance, a pointer to a function.
5252 if (D.getDeclSpec().hasAutoTypeSpec() &&
5253 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
5254 if (!S.getLangOpts().CPlusPlus14) {
5255 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5256 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
5257 ? diag::err_auto_missing_trailing_return
5258 : diag::err_deduced_return_type);
5259 T = Context.IntTy;
5260 D.setInvalidType(true);
5261 AreDeclaratorChunksValid = false;
5262 } else {
5263 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5264 diag::warn_cxx11_compat_deduced_return_type);
5266 } else if (FTI.hasTrailingReturnType()) {
5267 // T must be exactly 'auto' at this point. See CWG issue 681.
5268 if (isa<ParenType>(T)) {
5269 S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
5270 << T << D.getSourceRange();
5271 D.setInvalidType(true);
5272 // FIXME: recover and fill decls in `TypeLoc`s.
5273 AreDeclaratorChunksValid = false;
5274 } else if (D.getName().getKind() ==
5275 UnqualifiedIdKind::IK_DeductionGuideName) {
5276 if (T != Context.DependentTy) {
5277 S.Diag(D.getDeclSpec().getBeginLoc(),
5278 diag::err_deduction_guide_with_complex_decl)
5279 << D.getSourceRange();
5280 D.setInvalidType(true);
5281 // FIXME: recover and fill decls in `TypeLoc`s.
5282 AreDeclaratorChunksValid = false;
5284 } else if (D.getContext() != DeclaratorContext::LambdaExpr &&
5285 (T.hasQualifiers() || !isa<AutoType>(T) ||
5286 cast<AutoType>(T)->getKeyword() !=
5287 AutoTypeKeyword::Auto ||
5288 cast<AutoType>(T)->isConstrained())) {
5289 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5290 diag::err_trailing_return_without_auto)
5291 << T << D.getDeclSpec().getSourceRange();
5292 D.setInvalidType(true);
5293 // FIXME: recover and fill decls in `TypeLoc`s.
5294 AreDeclaratorChunksValid = false;
5296 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
5297 if (T.isNull()) {
5298 // An error occurred parsing the trailing return type.
5299 T = Context.IntTy;
5300 D.setInvalidType(true);
5301 } else if (AutoType *Auto = T->getContainedAutoType()) {
5302 // If the trailing return type contains an `auto`, we may need to
5303 // invent a template parameter for it, for cases like
5304 // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
5305 InventedTemplateParameterInfo *InventedParamInfo = nullptr;
5306 if (D.getContext() == DeclaratorContext::Prototype)
5307 InventedParamInfo = &S.InventedParameterInfos.back();
5308 else if (D.getContext() == DeclaratorContext::LambdaExprParameter)
5309 InventedParamInfo = S.getCurLambda();
5310 if (InventedParamInfo) {
5311 std::tie(T, TInfo) = InventTemplateParameter(
5312 state, T, TInfo, Auto, *InventedParamInfo);
5315 } else {
5316 // This function type is not the type of the entity being declared,
5317 // so checking the 'auto' is not the responsibility of this chunk.
5321 // C99 6.7.5.3p1: The return type may not be a function or array type.
5322 // For conversion functions, we'll diagnose this particular error later.
5323 if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
5324 (D.getName().getKind() !=
5325 UnqualifiedIdKind::IK_ConversionFunctionId)) {
5326 unsigned diagID = diag::err_func_returning_array_function;
5327 // Last processing chunk in block context means this function chunk
5328 // represents the block.
5329 if (chunkIndex == 0 &&
5330 D.getContext() == DeclaratorContext::BlockLiteral)
5331 diagID = diag::err_block_returning_array_function;
5332 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
5333 T = Context.IntTy;
5334 D.setInvalidType(true);
5335 AreDeclaratorChunksValid = false;
5338 // Do not allow returning half FP value.
5339 // FIXME: This really should be in BuildFunctionType.
5340 if (T->isHalfType()) {
5341 if (S.getLangOpts().OpenCL) {
5342 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5343 S.getLangOpts())) {
5344 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5345 << T << 0 /*pointer hint*/;
5346 D.setInvalidType(true);
5348 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5349 !S.Context.getTargetInfo().allowHalfArgsAndReturns()) {
5350 S.Diag(D.getIdentifierLoc(),
5351 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
5352 D.setInvalidType(true);
5356 if (LangOpts.OpenCL) {
5357 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
5358 // function.
5359 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
5360 T->isPipeType()) {
5361 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5362 << T << 1 /*hint off*/;
5363 D.setInvalidType(true);
5365 // OpenCL doesn't support variadic functions and blocks
5366 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
5367 // We also allow here any toolchain reserved identifiers.
5368 if (FTI.isVariadic &&
5369 !S.getOpenCLOptions().isAvailableOption(
5370 "__cl_clang_variadic_functions", S.getLangOpts()) &&
5371 !(D.getIdentifier() &&
5372 ((D.getIdentifier()->getName() == "printf" &&
5373 LangOpts.getOpenCLCompatibleVersion() >= 120) ||
5374 D.getIdentifier()->getName().starts_with("__")))) {
5375 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
5376 D.setInvalidType(true);
5380 // Methods cannot return interface types. All ObjC objects are
5381 // passed by reference.
5382 if (T->isObjCObjectType()) {
5383 SourceLocation DiagLoc, FixitLoc;
5384 if (TInfo) {
5385 DiagLoc = TInfo->getTypeLoc().getBeginLoc();
5386 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
5387 } else {
5388 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5389 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
5391 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
5392 << 0 << T
5393 << FixItHint::CreateInsertion(FixitLoc, "*");
5395 T = Context.getObjCObjectPointerType(T);
5396 if (TInfo) {
5397 TypeLocBuilder TLB;
5398 TLB.pushFullCopy(TInfo->getTypeLoc());
5399 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
5400 TLoc.setStarLoc(FixitLoc);
5401 TInfo = TLB.getTypeSourceInfo(Context, T);
5402 } else {
5403 AreDeclaratorChunksValid = false;
5406 D.setInvalidType(true);
5409 // cv-qualifiers on return types are pointless except when the type is a
5410 // class type in C++.
5411 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
5412 !(S.getLangOpts().CPlusPlus &&
5413 (T->isDependentType() || T->isRecordType()))) {
5414 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
5415 D.getFunctionDefinitionKind() ==
5416 FunctionDefinitionKind::Definition) {
5417 // [6.9.1/3] qualified void return is invalid on a C
5418 // function definition. Apparently ok on declarations and
5419 // in C++ though (!)
5420 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
5421 } else
5422 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
5424 // C++2a [dcl.fct]p12:
5425 // A volatile-qualified return type is deprecated
5426 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20)
5427 S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T;
5430 // Objective-C ARC ownership qualifiers are ignored on the function
5431 // return type (by type canonicalization). Complain if this attribute
5432 // was written here.
5433 if (T.getQualifiers().hasObjCLifetime()) {
5434 SourceLocation AttrLoc;
5435 if (chunkIndex + 1 < D.getNumTypeObjects()) {
5436 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
5437 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5438 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5439 AttrLoc = AL.getLoc();
5440 break;
5444 if (AttrLoc.isInvalid()) {
5445 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5446 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5447 AttrLoc = AL.getLoc();
5448 break;
5453 if (AttrLoc.isValid()) {
5454 // The ownership attributes are almost always written via
5455 // the predefined
5456 // __strong/__weak/__autoreleasing/__unsafe_unretained.
5457 if (AttrLoc.isMacroID())
5458 AttrLoc =
5459 S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin();
5461 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
5462 << T.getQualifiers().getObjCLifetime();
5466 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
5467 // C++ [dcl.fct]p6:
5468 // Types shall not be defined in return or parameter types.
5469 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
5470 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
5471 << Context.getTypeDeclType(Tag);
5474 // Exception specs are not allowed in typedefs. Complain, but add it
5475 // anyway.
5476 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
5477 S.Diag(FTI.getExceptionSpecLocBeg(),
5478 diag::err_exception_spec_in_typedef)
5479 << (D.getContext() == DeclaratorContext::AliasDecl ||
5480 D.getContext() == DeclaratorContext::AliasTemplate);
5482 // If we see "T var();" or "T var(T());" at block scope, it is probably
5483 // an attempt to initialize a variable, not a function declaration.
5484 if (FTI.isAmbiguous)
5485 warnAboutAmbiguousFunction(S, D, DeclType, T);
5487 FunctionType::ExtInfo EI(
5488 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
5490 // OpenCL disallows functions without a prototype, but it doesn't enforce
5491 // strict prototypes as in C23 because it allows a function definition to
5492 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
5493 if (!FTI.NumParams && !FTI.isVariadic &&
5494 !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) {
5495 // Simple void foo(), where the incoming T is the result type.
5496 T = Context.getFunctionNoProtoType(T, EI);
5497 } else {
5498 // We allow a zero-parameter variadic function in C if the
5499 // function is marked with the "overloadable" attribute. Scan
5500 // for this attribute now. We also allow it in C23 per WG14 N2975.
5501 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
5502 if (LangOpts.C23)
5503 S.Diag(FTI.getEllipsisLoc(),
5504 diag::warn_c17_compat_ellipsis_only_parameter);
5505 else if (!D.getDeclarationAttributes().hasAttribute(
5506 ParsedAttr::AT_Overloadable) &&
5507 !D.getAttributes().hasAttribute(
5508 ParsedAttr::AT_Overloadable) &&
5509 !D.getDeclSpec().getAttributes().hasAttribute(
5510 ParsedAttr::AT_Overloadable))
5511 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
5514 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
5515 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5516 // definition.
5517 S.Diag(FTI.Params[0].IdentLoc,
5518 diag::err_ident_list_in_fn_declaration);
5519 D.setInvalidType(true);
5520 // Recover by creating a K&R-style function type, if possible.
5521 T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL)
5522 ? Context.getFunctionNoProtoType(T, EI)
5523 : Context.IntTy;
5524 AreDeclaratorChunksValid = false;
5525 break;
5528 FunctionProtoType::ExtProtoInfo EPI;
5529 EPI.ExtInfo = EI;
5530 EPI.Variadic = FTI.isVariadic;
5531 EPI.EllipsisLoc = FTI.getEllipsisLoc();
5532 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
5533 EPI.TypeQuals.addCVRUQualifiers(
5534 FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers()
5535 : 0);
5536 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
5537 : FTI.RefQualifierIsLValueRef? RQ_LValue
5538 : RQ_RValue;
5540 // Otherwise, we have a function with a parameter list that is
5541 // potentially variadic.
5542 SmallVector<QualType, 16> ParamTys;
5543 ParamTys.reserve(FTI.NumParams);
5545 SmallVector<FunctionProtoType::ExtParameterInfo, 16>
5546 ExtParameterInfos(FTI.NumParams);
5547 bool HasAnyInterestingExtParameterInfos = false;
5549 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
5550 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5551 QualType ParamTy = Param->getType();
5552 assert(!ParamTy.isNull() && "Couldn't parse type?");
5554 // Look for 'void'. void is allowed only as a single parameter to a
5555 // function with no other parameters (C99 6.7.5.3p10). We record
5556 // int(void) as a FunctionProtoType with an empty parameter list.
5557 if (ParamTy->isVoidType()) {
5558 // If this is something like 'float(int, void)', reject it. 'void'
5559 // is an incomplete type (C99 6.2.5p19) and function decls cannot
5560 // have parameters of incomplete type.
5561 if (FTI.NumParams != 1 || FTI.isVariadic) {
5562 S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param);
5563 ParamTy = Context.IntTy;
5564 Param->setType(ParamTy);
5565 } else if (FTI.Params[i].Ident) {
5566 // Reject, but continue to parse 'int(void abc)'.
5567 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
5568 ParamTy = Context.IntTy;
5569 Param->setType(ParamTy);
5570 } else {
5571 // Reject, but continue to parse 'float(const void)'.
5572 if (ParamTy.hasQualifiers())
5573 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
5575 // Do not add 'void' to the list.
5576 break;
5578 } else if (ParamTy->isHalfType()) {
5579 // Disallow half FP parameters.
5580 // FIXME: This really should be in BuildFunctionType.
5581 if (S.getLangOpts().OpenCL) {
5582 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5583 S.getLangOpts())) {
5584 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5585 << ParamTy << 0;
5586 D.setInvalidType();
5587 Param->setInvalidDecl();
5589 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5590 !S.Context.getTargetInfo().allowHalfArgsAndReturns()) {
5591 S.Diag(Param->getLocation(),
5592 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5593 D.setInvalidType();
5595 } else if (!FTI.hasPrototype) {
5596 if (Context.isPromotableIntegerType(ParamTy)) {
5597 ParamTy = Context.getPromotedIntegerType(ParamTy);
5598 Param->setKNRPromoted(true);
5599 } else if (const BuiltinType *BTy = ParamTy->getAs<BuiltinType>()) {
5600 if (BTy->getKind() == BuiltinType::Float) {
5601 ParamTy = Context.DoubleTy;
5602 Param->setKNRPromoted(true);
5605 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) {
5606 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5607 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5608 << ParamTy << 1 /*hint off*/;
5609 D.setInvalidType();
5612 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
5613 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
5614 HasAnyInterestingExtParameterInfos = true;
5617 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5618 ExtParameterInfos[i] =
5619 ExtParameterInfos[i].withABI(attr->getABI());
5620 HasAnyInterestingExtParameterInfos = true;
5623 if (Param->hasAttr<PassObjectSizeAttr>()) {
5624 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5625 HasAnyInterestingExtParameterInfos = true;
5628 if (Param->hasAttr<NoEscapeAttr>()) {
5629 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
5630 HasAnyInterestingExtParameterInfos = true;
5633 ParamTys.push_back(ParamTy);
5636 if (HasAnyInterestingExtParameterInfos) {
5637 EPI.ExtParameterInfos = ExtParameterInfos.data();
5638 checkExtParameterInfos(S, ParamTys, EPI,
5639 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
5642 SmallVector<QualType, 4> Exceptions;
5643 SmallVector<ParsedType, 2> DynamicExceptions;
5644 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5645 Expr *NoexceptExpr = nullptr;
5647 if (FTI.getExceptionSpecType() == EST_Dynamic) {
5648 // FIXME: It's rather inefficient to have to split into two vectors
5649 // here.
5650 unsigned N = FTI.getNumExceptions();
5651 DynamicExceptions.reserve(N);
5652 DynamicExceptionRanges.reserve(N);
5653 for (unsigned I = 0; I != N; ++I) {
5654 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
5655 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
5657 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
5658 NoexceptExpr = FTI.NoexceptExpr;
5661 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
5662 FTI.getExceptionSpecType(),
5663 DynamicExceptions,
5664 DynamicExceptionRanges,
5665 NoexceptExpr,
5666 Exceptions,
5667 EPI.ExceptionSpec);
5669 // FIXME: Set address space from attrs for C++ mode here.
5670 // OpenCLCPlusPlus: A class member function has an address space.
5671 auto IsClassMember = [&]() {
5672 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5673 state.getDeclarator()
5674 .getCXXScopeSpec()
5675 .getScopeRep()
5676 ->getKind() == NestedNameSpecifier::TypeSpec) ||
5677 state.getDeclarator().getContext() ==
5678 DeclaratorContext::Member ||
5679 state.getDeclarator().getContext() ==
5680 DeclaratorContext::LambdaExpr;
5683 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
5684 LangAS ASIdx = LangAS::Default;
5685 // Take address space attr if any and mark as invalid to avoid adding
5686 // them later while creating QualType.
5687 if (FTI.MethodQualifiers)
5688 for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) {
5689 LangAS ASIdxNew = attr.asOpenCLLangAS();
5690 if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
5691 attr.getLoc()))
5692 D.setInvalidType(true);
5693 else
5694 ASIdx = ASIdxNew;
5696 // If a class member function's address space is not set, set it to
5697 // __generic.
5698 LangAS AS =
5699 (ASIdx == LangAS::Default ? S.getDefaultCXXMethodAddrSpace()
5700 : ASIdx);
5701 EPI.TypeQuals.addAddressSpace(AS);
5703 T = Context.getFunctionType(T, ParamTys, EPI);
5705 break;
5707 case DeclaratorChunk::MemberPointer: {
5708 // The scope spec must refer to a class, or be dependent.
5709 CXXScopeSpec &SS = DeclType.Mem.Scope();
5710 QualType ClsType;
5712 // Handle pointer nullability.
5713 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5714 DeclType.EndLoc, DeclType.getAttrs(),
5715 state.getDeclarator().getAttributePool());
5717 if (SS.isInvalid()) {
5718 // Avoid emitting extra errors if we already errored on the scope.
5719 D.setInvalidType(true);
5720 } else if (S.isDependentScopeSpecifier(SS) ||
5721 isa_and_nonnull<CXXRecordDecl>(S.computeDeclContext(SS))) {
5722 NestedNameSpecifier *NNS = SS.getScopeRep();
5723 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
5724 switch (NNS->getKind()) {
5725 case NestedNameSpecifier::Identifier:
5726 ClsType = Context.getDependentNameType(
5727 ElaboratedTypeKeyword::None, NNSPrefix, NNS->getAsIdentifier());
5728 break;
5730 case NestedNameSpecifier::Namespace:
5731 case NestedNameSpecifier::NamespaceAlias:
5732 case NestedNameSpecifier::Global:
5733 case NestedNameSpecifier::Super:
5734 llvm_unreachable("Nested-name-specifier must name a type");
5736 case NestedNameSpecifier::TypeSpec:
5737 case NestedNameSpecifier::TypeSpecWithTemplate:
5738 ClsType = QualType(NNS->getAsType(), 0);
5739 // Note: if the NNS has a prefix and ClsType is a nondependent
5740 // TemplateSpecializationType, then the NNS prefix is NOT included
5741 // in ClsType; hence we wrap ClsType into an ElaboratedType.
5742 // NOTE: in particular, no wrap occurs if ClsType already is an
5743 // Elaborated, DependentName, or DependentTemplateSpecialization.
5744 if (isa<TemplateSpecializationType>(NNS->getAsType()))
5745 ClsType = Context.getElaboratedType(ElaboratedTypeKeyword::None,
5746 NNSPrefix, ClsType);
5747 break;
5749 } else {
5750 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
5751 diag::err_illegal_decl_mempointer_in_nonclass)
5752 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
5753 << DeclType.Mem.Scope().getRange();
5754 D.setInvalidType(true);
5757 if (!ClsType.isNull())
5758 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
5759 D.getIdentifier());
5760 else
5761 AreDeclaratorChunksValid = false;
5763 if (T.isNull()) {
5764 T = Context.IntTy;
5765 D.setInvalidType(true);
5766 AreDeclaratorChunksValid = false;
5767 } else if (DeclType.Mem.TypeQuals) {
5768 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
5770 break;
5773 case DeclaratorChunk::Pipe: {
5774 T = S.BuildReadPipeType(T, DeclType.Loc);
5775 processTypeAttrs(state, T, TAL_DeclSpec,
5776 D.getMutableDeclSpec().getAttributes());
5777 break;
5781 if (T.isNull()) {
5782 D.setInvalidType(true);
5783 T = Context.IntTy;
5784 AreDeclaratorChunksValid = false;
5787 // See if there are any attributes on this declarator chunk.
5788 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs(),
5789 S.IdentifyCUDATarget(D.getAttributes()));
5791 if (DeclType.Kind != DeclaratorChunk::Paren) {
5792 if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
5793 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5795 ExpectNoDerefChunk = state.didParseNoDeref();
5799 if (ExpectNoDerefChunk)
5800 S.Diag(state.getDeclarator().getBeginLoc(),
5801 diag::warn_noderef_on_non_pointer_or_array);
5803 // GNU warning -Wstrict-prototypes
5804 // Warn if a function declaration or definition is without a prototype.
5805 // This warning is issued for all kinds of unprototyped function
5806 // declarations (i.e. function type typedef, function pointer etc.)
5807 // C99 6.7.5.3p14:
5808 // The empty list in a function declarator that is not part of a definition
5809 // of that function specifies that no information about the number or types
5810 // of the parameters is supplied.
5811 // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of
5812 // function declarations whose behavior changes in C23.
5813 if (!LangOpts.requiresStrictPrototypes()) {
5814 bool IsBlock = false;
5815 for (const DeclaratorChunk &DeclType : D.type_objects()) {
5816 switch (DeclType.Kind) {
5817 case DeclaratorChunk::BlockPointer:
5818 IsBlock = true;
5819 break;
5820 case DeclaratorChunk::Function: {
5821 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5822 // We suppress the warning when there's no LParen location, as this
5823 // indicates the declaration was an implicit declaration, which gets
5824 // warned about separately via -Wimplicit-function-declaration. We also
5825 // suppress the warning when we know the function has a prototype.
5826 if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic &&
5827 FTI.getLParenLoc().isValid())
5828 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5829 << IsBlock
5830 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5831 IsBlock = false;
5832 break;
5834 default:
5835 break;
5840 assert(!T.isNull() && "T must not be null after this point");
5842 if (LangOpts.CPlusPlus && T->isFunctionType()) {
5843 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5844 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
5846 // C++ 8.3.5p4:
5847 // A cv-qualifier-seq shall only be part of the function type
5848 // for a nonstatic member function, the function type to which a pointer
5849 // to member refers, or the top-level function type of a function typedef
5850 // declaration.
5852 // Core issue 547 also allows cv-qualifiers on function types that are
5853 // top-level template type arguments.
5854 enum {
5855 NonMember,
5856 Member,
5857 ExplicitObjectMember,
5858 DeductionGuide
5859 } Kind = NonMember;
5860 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
5861 Kind = DeductionGuide;
5862 else if (!D.getCXXScopeSpec().isSet()) {
5863 if ((D.getContext() == DeclaratorContext::Member ||
5864 D.getContext() == DeclaratorContext::LambdaExpr) &&
5865 !D.getDeclSpec().isFriendSpecified())
5866 Kind = Member;
5867 } else {
5868 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
5869 if (!DC || DC->isRecord())
5870 Kind = Member;
5873 if (Kind == Member) {
5874 unsigned I;
5875 if (D.isFunctionDeclarator(I)) {
5876 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5877 if (Chunk.Fun.NumParams) {
5878 auto *P = dyn_cast_or_null<ParmVarDecl>(Chunk.Fun.Params->Param);
5879 if (P && P->isExplicitObjectParameter())
5880 Kind = ExplicitObjectMember;
5885 // C++11 [dcl.fct]p6 (w/DR1417):
5886 // An attempt to specify a function type with a cv-qualifier-seq or a
5887 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5888 // - the function type for a non-static member function,
5889 // - the function type to which a pointer to member refers,
5890 // - the top-level function type of a function typedef declaration or
5891 // alias-declaration,
5892 // - the type-id in the default argument of a type-parameter, or
5893 // - the type-id of a template-argument for a type-parameter
5895 // FIXME: Checking this here is insufficient. We accept-invalid on:
5897 // template<typename T> struct S { void f(T); };
5898 // S<int() const> s;
5900 // ... for instance.
5901 if (IsQualifiedFunction &&
5902 !(Kind == Member && !D.isExplicitObjectMemberFunction() &&
5903 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
5904 !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg &&
5905 D.getContext() != DeclaratorContext::TemplateTypeArg) {
5906 SourceLocation Loc = D.getBeginLoc();
5907 SourceRange RemovalRange;
5908 unsigned I;
5909 if (D.isFunctionDeclarator(I)) {
5910 SmallVector<SourceLocation, 4> RemovalLocs;
5911 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5912 assert(Chunk.Kind == DeclaratorChunk::Function);
5914 if (Chunk.Fun.hasRefQualifier())
5915 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5917 if (Chunk.Fun.hasMethodTypeQualifiers())
5918 Chunk.Fun.MethodQualifiers->forEachQualifier(
5919 [&](DeclSpec::TQ TypeQual, StringRef QualName,
5920 SourceLocation SL) { RemovalLocs.push_back(SL); });
5922 if (!RemovalLocs.empty()) {
5923 llvm::sort(RemovalLocs,
5924 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
5925 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5926 Loc = RemovalLocs.front();
5930 S.Diag(Loc, diag::err_invalid_qualified_function_type)
5931 << Kind << D.isFunctionDeclarator() << T
5932 << getFunctionQualifiersAsString(FnTy)
5933 << FixItHint::CreateRemoval(RemovalRange);
5935 // Strip the cv-qualifiers and ref-qualifiers from the type.
5936 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
5937 EPI.TypeQuals.removeCVRQualifiers();
5938 EPI.RefQualifier = RQ_None;
5940 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5941 EPI);
5942 // Rebuild any parens around the identifier in the function type.
5943 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5944 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
5945 break;
5946 T = S.BuildParenType(T);
5951 // Apply any undistributed attributes from the declaration or declarator.
5952 ParsedAttributesView NonSlidingAttrs;
5953 for (ParsedAttr &AL : D.getDeclarationAttributes()) {
5954 if (!AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
5955 NonSlidingAttrs.addAtEnd(&AL);
5958 processTypeAttrs(state, T, TAL_DeclName, NonSlidingAttrs);
5959 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
5961 // Diagnose any ignored type attributes.
5962 state.diagnoseIgnoredTypeAttrs(T);
5964 // C++0x [dcl.constexpr]p9:
5965 // A constexpr specifier used in an object declaration declares the object
5966 // as const.
5967 if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr &&
5968 T->isObjectType())
5969 T.addConst();
5971 // C++2a [dcl.fct]p4:
5972 // A parameter with volatile-qualified type is deprecated
5973 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 &&
5974 (D.getContext() == DeclaratorContext::Prototype ||
5975 D.getContext() == DeclaratorContext::LambdaExprParameter))
5976 S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T;
5978 // If there was an ellipsis in the declarator, the declaration declares a
5979 // parameter pack whose type may be a pack expansion type.
5980 if (D.hasEllipsis()) {
5981 // C++0x [dcl.fct]p13:
5982 // A declarator-id or abstract-declarator containing an ellipsis shall
5983 // only be used in a parameter-declaration. Such a parameter-declaration
5984 // is a parameter pack (14.5.3). [...]
5985 switch (D.getContext()) {
5986 case DeclaratorContext::Prototype:
5987 case DeclaratorContext::LambdaExprParameter:
5988 case DeclaratorContext::RequiresExpr:
5989 // C++0x [dcl.fct]p13:
5990 // [...] When it is part of a parameter-declaration-clause, the
5991 // parameter pack is a function parameter pack (14.5.3). The type T
5992 // of the declarator-id of the function parameter pack shall contain
5993 // a template parameter pack; each template parameter pack in T is
5994 // expanded by the function parameter pack.
5996 // We represent function parameter packs as function parameters whose
5997 // type is a pack expansion.
5998 if (!T->containsUnexpandedParameterPack() &&
5999 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) {
6000 S.Diag(D.getEllipsisLoc(),
6001 diag::err_function_parameter_pack_without_parameter_packs)
6002 << T << D.getSourceRange();
6003 D.setEllipsisLoc(SourceLocation());
6004 } else {
6005 T = Context.getPackExpansionType(T, std::nullopt,
6006 /*ExpectPackInType=*/false);
6008 break;
6009 case DeclaratorContext::TemplateParam:
6010 // C++0x [temp.param]p15:
6011 // If a template-parameter is a [...] is a parameter-declaration that
6012 // declares a parameter pack (8.3.5), then the template-parameter is a
6013 // template parameter pack (14.5.3).
6015 // Note: core issue 778 clarifies that, if there are any unexpanded
6016 // parameter packs in the type of the non-type template parameter, then
6017 // it expands those parameter packs.
6018 if (T->containsUnexpandedParameterPack())
6019 T = Context.getPackExpansionType(T, std::nullopt);
6020 else
6021 S.Diag(D.getEllipsisLoc(),
6022 LangOpts.CPlusPlus11
6023 ? diag::warn_cxx98_compat_variadic_templates
6024 : diag::ext_variadic_templates);
6025 break;
6027 case DeclaratorContext::File:
6028 case DeclaratorContext::KNRTypeList:
6029 case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here?
6030 case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here?
6031 case DeclaratorContext::TypeName:
6032 case DeclaratorContext::FunctionalCast:
6033 case DeclaratorContext::CXXNew:
6034 case DeclaratorContext::AliasDecl:
6035 case DeclaratorContext::AliasTemplate:
6036 case DeclaratorContext::Member:
6037 case DeclaratorContext::Block:
6038 case DeclaratorContext::ForInit:
6039 case DeclaratorContext::SelectionInit:
6040 case DeclaratorContext::Condition:
6041 case DeclaratorContext::CXXCatch:
6042 case DeclaratorContext::ObjCCatch:
6043 case DeclaratorContext::BlockLiteral:
6044 case DeclaratorContext::LambdaExpr:
6045 case DeclaratorContext::ConversionId:
6046 case DeclaratorContext::TrailingReturn:
6047 case DeclaratorContext::TrailingReturnVar:
6048 case DeclaratorContext::TemplateArg:
6049 case DeclaratorContext::TemplateTypeArg:
6050 case DeclaratorContext::Association:
6051 // FIXME: We may want to allow parameter packs in block-literal contexts
6052 // in the future.
6053 S.Diag(D.getEllipsisLoc(),
6054 diag::err_ellipsis_in_declarator_not_parameter);
6055 D.setEllipsisLoc(SourceLocation());
6056 break;
6060 assert(!T.isNull() && "T must not be null at the end of this function");
6061 if (!AreDeclaratorChunksValid)
6062 return Context.getTrivialTypeSourceInfo(T);
6063 return GetTypeSourceInfoForDeclarator(state, T, TInfo);
6066 /// GetTypeForDeclarator - Convert the type for the specified
6067 /// declarator to Type instances.
6069 /// The result of this call will never be null, but the associated
6070 /// type may be a null type if there's an unrecoverable error.
6071 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
6072 // Determine the type of the declarator. Not all forms of declarator
6073 // have a type.
6075 TypeProcessingState state(*this, D);
6077 TypeSourceInfo *ReturnTypeInfo = nullptr;
6078 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
6079 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
6080 inferARCWriteback(state, T);
6082 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
6085 static void transferARCOwnershipToDeclSpec(Sema &S,
6086 QualType &declSpecTy,
6087 Qualifiers::ObjCLifetime ownership) {
6088 if (declSpecTy->isObjCRetainableType() &&
6089 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
6090 Qualifiers qs;
6091 qs.addObjCLifetime(ownership);
6092 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
6096 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
6097 Qualifiers::ObjCLifetime ownership,
6098 unsigned chunkIndex) {
6099 Sema &S = state.getSema();
6100 Declarator &D = state.getDeclarator();
6102 // Look for an explicit lifetime attribute.
6103 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
6104 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
6105 return;
6107 const char *attrStr = nullptr;
6108 switch (ownership) {
6109 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
6110 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
6111 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
6112 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
6113 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
6116 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
6117 Arg->Ident = &S.Context.Idents.get(attrStr);
6118 Arg->Loc = SourceLocation();
6120 ArgsUnion Args(Arg);
6122 // If there wasn't one, add one (with an invalid source location
6123 // so that we don't make an AttributedType for it).
6124 ParsedAttr *attr = D.getAttributePool().create(
6125 &S.Context.Idents.get("objc_ownership"), SourceLocation(),
6126 /*scope*/ nullptr, SourceLocation(),
6127 /*args*/ &Args, 1, ParsedAttr::Form::GNU());
6128 chunk.getAttrs().addAtEnd(attr);
6129 // TODO: mark whether we did this inference?
6132 /// Used for transferring ownership in casts resulting in l-values.
6133 static void transferARCOwnership(TypeProcessingState &state,
6134 QualType &declSpecTy,
6135 Qualifiers::ObjCLifetime ownership) {
6136 Sema &S = state.getSema();
6137 Declarator &D = state.getDeclarator();
6139 int inner = -1;
6140 bool hasIndirection = false;
6141 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6142 DeclaratorChunk &chunk = D.getTypeObject(i);
6143 switch (chunk.Kind) {
6144 case DeclaratorChunk::Paren:
6145 // Ignore parens.
6146 break;
6148 case DeclaratorChunk::Array:
6149 case DeclaratorChunk::Reference:
6150 case DeclaratorChunk::Pointer:
6151 if (inner != -1)
6152 hasIndirection = true;
6153 inner = i;
6154 break;
6156 case DeclaratorChunk::BlockPointer:
6157 if (inner != -1)
6158 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
6159 return;
6161 case DeclaratorChunk::Function:
6162 case DeclaratorChunk::MemberPointer:
6163 case DeclaratorChunk::Pipe:
6164 return;
6168 if (inner == -1)
6169 return;
6171 DeclaratorChunk &chunk = D.getTypeObject(inner);
6172 if (chunk.Kind == DeclaratorChunk::Pointer) {
6173 if (declSpecTy->isObjCRetainableType())
6174 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
6175 if (declSpecTy->isObjCObjectType() && hasIndirection)
6176 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
6177 } else {
6178 assert(chunk.Kind == DeclaratorChunk::Array ||
6179 chunk.Kind == DeclaratorChunk::Reference);
6180 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
6184 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
6185 TypeProcessingState state(*this, D);
6187 TypeSourceInfo *ReturnTypeInfo = nullptr;
6188 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
6190 if (getLangOpts().ObjC) {
6191 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
6192 if (ownership != Qualifiers::OCL_None)
6193 transferARCOwnership(state, declSpecTy, ownership);
6196 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
6199 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
6200 TypeProcessingState &State) {
6201 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
6204 static void fillMatrixTypeLoc(MatrixTypeLoc MTL,
6205 const ParsedAttributesView &Attrs) {
6206 for (const ParsedAttr &AL : Attrs) {
6207 if (AL.getKind() == ParsedAttr::AT_MatrixType) {
6208 MTL.setAttrNameLoc(AL.getLoc());
6209 MTL.setAttrRowOperand(AL.getArgAsExpr(0));
6210 MTL.setAttrColumnOperand(AL.getArgAsExpr(1));
6211 MTL.setAttrOperandParensRange(SourceRange());
6212 return;
6216 llvm_unreachable("no matrix_type attribute found at the expected location!");
6219 namespace {
6220 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
6221 Sema &SemaRef;
6222 ASTContext &Context;
6223 TypeProcessingState &State;
6224 const DeclSpec &DS;
6226 public:
6227 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
6228 const DeclSpec &DS)
6229 : SemaRef(S), Context(Context), State(State), DS(DS) {}
6231 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6232 Visit(TL.getModifiedLoc());
6233 fillAttributedTypeLoc(TL, State);
6235 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6236 Visit(TL.getWrappedLoc());
6238 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6239 Visit(TL.getInnerLoc());
6240 TL.setExpansionLoc(
6241 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6243 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6244 Visit(TL.getUnqualifiedLoc());
6246 // Allow to fill pointee's type locations, e.g.,
6247 // int __attr * __attr * __attr *p;
6248 void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); }
6249 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6250 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6252 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6253 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6254 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
6255 // addition field. What we have is good enough for display of location
6256 // of 'fixit' on interface name.
6257 TL.setNameEndLoc(DS.getEndLoc());
6259 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6260 TypeSourceInfo *RepTInfo = nullptr;
6261 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6262 TL.copy(RepTInfo->getTypeLoc());
6264 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6265 TypeSourceInfo *RepTInfo = nullptr;
6266 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6267 TL.copy(RepTInfo->getTypeLoc());
6269 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
6270 TypeSourceInfo *TInfo = nullptr;
6271 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6273 // If we got no declarator info from previous Sema routines,
6274 // just fill with the typespec loc.
6275 if (!TInfo) {
6276 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
6277 return;
6280 TypeLoc OldTL = TInfo->getTypeLoc();
6281 if (TInfo->getType()->getAs<ElaboratedType>()) {
6282 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
6283 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
6284 .castAs<TemplateSpecializationTypeLoc>();
6285 TL.copy(NamedTL);
6286 } else {
6287 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
6288 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
6292 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6293 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
6294 DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualExpr);
6295 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
6296 TL.setParensRange(DS.getTypeofParensRange());
6298 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6299 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
6300 DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType);
6301 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
6302 TL.setParensRange(DS.getTypeofParensRange());
6303 assert(DS.getRepAsType());
6304 TypeSourceInfo *TInfo = nullptr;
6305 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6306 TL.setUnmodifiedTInfo(TInfo);
6308 void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6309 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
6310 TL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
6311 TL.setRParenLoc(DS.getTypeofParensRange().getEnd());
6313 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6314 assert(DS.isTransformTypeTrait(DS.getTypeSpecType()));
6315 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6316 TL.setParensRange(DS.getTypeofParensRange());
6317 assert(DS.getRepAsType());
6318 TypeSourceInfo *TInfo = nullptr;
6319 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6320 TL.setUnderlyingTInfo(TInfo);
6322 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6323 // By default, use the source location of the type specifier.
6324 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
6325 if (TL.needsExtraLocalData()) {
6326 // Set info for the written builtin specifiers.
6327 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
6328 // Try to have a meaningful source location.
6329 if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified)
6330 TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
6331 if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified)
6332 TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
6335 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6336 if (DS.getTypeSpecType() == TST_typename) {
6337 TypeSourceInfo *TInfo = nullptr;
6338 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6339 if (TInfo)
6340 if (auto ETL = TInfo->getTypeLoc().getAs<ElaboratedTypeLoc>()) {
6341 TL.copy(ETL);
6342 return;
6345 const ElaboratedType *T = TL.getTypePtr();
6346 TL.setElaboratedKeywordLoc(T->getKeyword() != ElaboratedTypeKeyword::None
6347 ? DS.getTypeSpecTypeLoc()
6348 : SourceLocation());
6349 const CXXScopeSpec& SS = DS.getTypeSpecScope();
6350 TL.setQualifierLoc(SS.getWithLocInContext(Context));
6351 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
6353 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6354 assert(DS.getTypeSpecType() == TST_typename);
6355 TypeSourceInfo *TInfo = nullptr;
6356 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6357 assert(TInfo);
6358 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
6360 void VisitDependentTemplateSpecializationTypeLoc(
6361 DependentTemplateSpecializationTypeLoc TL) {
6362 assert(DS.getTypeSpecType() == TST_typename);
6363 TypeSourceInfo *TInfo = nullptr;
6364 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6365 assert(TInfo);
6366 TL.copy(
6367 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
6369 void VisitAutoTypeLoc(AutoTypeLoc TL) {
6370 assert(DS.getTypeSpecType() == TST_auto ||
6371 DS.getTypeSpecType() == TST_decltype_auto ||
6372 DS.getTypeSpecType() == TST_auto_type ||
6373 DS.getTypeSpecType() == TST_unspecified);
6374 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6375 if (DS.getTypeSpecType() == TST_decltype_auto)
6376 TL.setRParenLoc(DS.getTypeofParensRange().getEnd());
6377 if (!DS.isConstrainedAuto())
6378 return;
6379 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
6380 if (!TemplateId)
6381 return;
6383 NestedNameSpecifierLoc NNS =
6384 (DS.getTypeSpecScope().isNotEmpty()
6385 ? DS.getTypeSpecScope().getWithLocInContext(Context)
6386 : NestedNameSpecifierLoc());
6387 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
6388 TemplateId->RAngleLoc);
6389 if (TemplateId->NumArgs > 0) {
6390 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6391 TemplateId->NumArgs);
6392 SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
6394 DeclarationNameInfo DNI = DeclarationNameInfo(
6395 TL.getTypePtr()->getTypeConstraintConcept()->getDeclName(),
6396 TemplateId->TemplateNameLoc);
6397 auto *CR = ConceptReference::Create(
6398 Context, NNS, TemplateId->TemplateKWLoc, DNI,
6399 /*FoundDecl=*/nullptr,
6400 /*NamedDecl=*/TL.getTypePtr()->getTypeConstraintConcept(),
6401 ASTTemplateArgumentListInfo::Create(Context, TemplateArgsInfo));
6402 TL.setConceptReference(CR);
6404 void VisitTagTypeLoc(TagTypeLoc TL) {
6405 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
6407 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6408 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
6409 // or an _Atomic qualifier.
6410 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
6411 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6412 TL.setParensRange(DS.getTypeofParensRange());
6414 TypeSourceInfo *TInfo = nullptr;
6415 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6416 assert(TInfo);
6417 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
6418 } else {
6419 TL.setKWLoc(DS.getAtomicSpecLoc());
6420 // No parens, to indicate this was spelled as an _Atomic qualifier.
6421 TL.setParensRange(SourceRange());
6422 Visit(TL.getValueLoc());
6426 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6427 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6429 TypeSourceInfo *TInfo = nullptr;
6430 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6431 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
6434 void VisitExtIntTypeLoc(BitIntTypeLoc TL) {
6435 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6438 void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) {
6439 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6442 void VisitTypeLoc(TypeLoc TL) {
6443 // FIXME: add other typespec types and change this to an assert.
6444 TL.initialize(Context, DS.getTypeSpecTypeLoc());
6448 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
6449 ASTContext &Context;
6450 TypeProcessingState &State;
6451 const DeclaratorChunk &Chunk;
6453 public:
6454 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
6455 const DeclaratorChunk &Chunk)
6456 : Context(Context), State(State), Chunk(Chunk) {}
6458 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6459 llvm_unreachable("qualified type locs not expected here!");
6461 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6462 llvm_unreachable("decayed type locs not expected here!");
6465 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6466 fillAttributedTypeLoc(TL, State);
6468 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6469 // nothing
6471 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6472 // nothing
6474 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6475 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
6476 TL.setCaretLoc(Chunk.Loc);
6478 void VisitPointerTypeLoc(PointerTypeLoc TL) {
6479 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6480 TL.setStarLoc(Chunk.Loc);
6482 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6483 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6484 TL.setStarLoc(Chunk.Loc);
6486 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6487 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
6488 const CXXScopeSpec& SS = Chunk.Mem.Scope();
6489 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
6491 const Type* ClsTy = TL.getClass();
6492 QualType ClsQT = QualType(ClsTy, 0);
6493 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
6494 // Now copy source location info into the type loc component.
6495 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
6496 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
6497 case NestedNameSpecifier::Identifier:
6498 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
6500 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
6501 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
6502 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
6503 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
6505 break;
6507 case NestedNameSpecifier::TypeSpec:
6508 case NestedNameSpecifier::TypeSpecWithTemplate:
6509 if (isa<ElaboratedType>(ClsTy)) {
6510 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
6511 ETLoc.setElaboratedKeywordLoc(SourceLocation());
6512 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
6513 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
6514 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
6515 } else {
6516 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
6518 break;
6520 case NestedNameSpecifier::Namespace:
6521 case NestedNameSpecifier::NamespaceAlias:
6522 case NestedNameSpecifier::Global:
6523 case NestedNameSpecifier::Super:
6524 llvm_unreachable("Nested-name-specifier must name a type");
6527 // Finally fill in MemberPointerLocInfo fields.
6528 TL.setStarLoc(Chunk.Mem.StarLoc);
6529 TL.setClassTInfo(ClsTInfo);
6531 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6532 assert(Chunk.Kind == DeclaratorChunk::Reference);
6533 // 'Amp' is misleading: this might have been originally
6534 /// spelled with AmpAmp.
6535 TL.setAmpLoc(Chunk.Loc);
6537 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6538 assert(Chunk.Kind == DeclaratorChunk::Reference);
6539 assert(!Chunk.Ref.LValueRef);
6540 TL.setAmpAmpLoc(Chunk.Loc);
6542 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
6543 assert(Chunk.Kind == DeclaratorChunk::Array);
6544 TL.setLBracketLoc(Chunk.Loc);
6545 TL.setRBracketLoc(Chunk.EndLoc);
6546 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
6548 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6549 assert(Chunk.Kind == DeclaratorChunk::Function);
6550 TL.setLocalRangeBegin(Chunk.Loc);
6551 TL.setLocalRangeEnd(Chunk.EndLoc);
6553 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
6554 TL.setLParenLoc(FTI.getLParenLoc());
6555 TL.setRParenLoc(FTI.getRParenLoc());
6556 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
6557 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
6558 TL.setParam(tpi++, Param);
6560 TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
6562 void VisitParenTypeLoc(ParenTypeLoc TL) {
6563 assert(Chunk.Kind == DeclaratorChunk::Paren);
6564 TL.setLParenLoc(Chunk.Loc);
6565 TL.setRParenLoc(Chunk.EndLoc);
6567 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6568 assert(Chunk.Kind == DeclaratorChunk::Pipe);
6569 TL.setKWLoc(Chunk.Loc);
6571 void VisitBitIntTypeLoc(BitIntTypeLoc TL) {
6572 TL.setNameLoc(Chunk.Loc);
6574 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6575 TL.setExpansionLoc(Chunk.Loc);
6577 void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); }
6578 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) {
6579 TL.setNameLoc(Chunk.Loc);
6581 void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6582 TL.setNameLoc(Chunk.Loc);
6584 void
6585 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) {
6586 TL.setNameLoc(Chunk.Loc);
6588 void VisitMatrixTypeLoc(MatrixTypeLoc TL) {
6589 fillMatrixTypeLoc(TL, Chunk.getAttrs());
6592 void VisitTypeLoc(TypeLoc TL) {
6593 llvm_unreachable("unsupported TypeLoc kind in declarator!");
6596 } // end anonymous namespace
6598 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
6599 SourceLocation Loc;
6600 switch (Chunk.Kind) {
6601 case DeclaratorChunk::Function:
6602 case DeclaratorChunk::Array:
6603 case DeclaratorChunk::Paren:
6604 case DeclaratorChunk::Pipe:
6605 llvm_unreachable("cannot be _Atomic qualified");
6607 case DeclaratorChunk::Pointer:
6608 Loc = Chunk.Ptr.AtomicQualLoc;
6609 break;
6611 case DeclaratorChunk::BlockPointer:
6612 case DeclaratorChunk::Reference:
6613 case DeclaratorChunk::MemberPointer:
6614 // FIXME: Provide a source location for the _Atomic keyword.
6615 break;
6618 ATL.setKWLoc(Loc);
6619 ATL.setParensRange(SourceRange());
6622 static void
6623 fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL,
6624 const ParsedAttributesView &Attrs) {
6625 for (const ParsedAttr &AL : Attrs) {
6626 if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
6627 DASTL.setAttrNameLoc(AL.getLoc());
6628 DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
6629 DASTL.setAttrOperandParensRange(SourceRange());
6630 return;
6634 llvm_unreachable(
6635 "no address_space attribute found at the expected location!");
6638 /// Create and instantiate a TypeSourceInfo with type source information.
6640 /// \param T QualType referring to the type as written in source code.
6642 /// \param ReturnTypeInfo For declarators whose return type does not show
6643 /// up in the normal place in the declaration specifiers (such as a C++
6644 /// conversion function), this pointer will refer to a type source information
6645 /// for that return type.
6646 static TypeSourceInfo *
6647 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
6648 QualType T, TypeSourceInfo *ReturnTypeInfo) {
6649 Sema &S = State.getSema();
6650 Declarator &D = State.getDeclarator();
6652 TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T);
6653 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
6655 // Handle parameter packs whose type is a pack expansion.
6656 if (isa<PackExpansionType>(T)) {
6657 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
6658 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6661 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6662 // Microsoft property fields can have multiple sizeless array chunks
6663 // (i.e. int x[][][]). Don't create more than one level of incomplete array.
6664 if (CurrTL.getTypeLocClass() == TypeLoc::IncompleteArray && e != 1 &&
6665 D.getDeclSpec().getAttributes().hasMSPropertyAttr())
6666 continue;
6668 // An AtomicTypeLoc might be produced by an atomic qualifier in this
6669 // declarator chunk.
6670 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
6671 fillAtomicQualLoc(ATL, D.getTypeObject(i));
6672 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
6675 bool HasDesugaredTypeLoc = true;
6676 while (HasDesugaredTypeLoc) {
6677 switch (CurrTL.getTypeLocClass()) {
6678 case TypeLoc::MacroQualified: {
6679 auto TL = CurrTL.castAs<MacroQualifiedTypeLoc>();
6680 TL.setExpansionLoc(
6681 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6682 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6683 break;
6686 case TypeLoc::Attributed: {
6687 auto TL = CurrTL.castAs<AttributedTypeLoc>();
6688 fillAttributedTypeLoc(TL, State);
6689 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6690 break;
6693 case TypeLoc::Adjusted:
6694 case TypeLoc::BTFTagAttributed: {
6695 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6696 break;
6699 case TypeLoc::DependentAddressSpace: {
6700 auto TL = CurrTL.castAs<DependentAddressSpaceTypeLoc>();
6701 fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs());
6702 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
6703 break;
6706 default:
6707 HasDesugaredTypeLoc = false;
6708 break;
6712 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
6713 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6716 // If we have different source information for the return type, use
6717 // that. This really only applies to C++ conversion functions.
6718 if (ReturnTypeInfo) {
6719 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
6720 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
6721 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
6722 } else {
6723 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL);
6726 return TInfo;
6729 /// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
6730 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
6731 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6732 // and Sema during declaration parsing. Try deallocating/caching them when
6733 // it's appropriate, instead of allocating them and keeping them around.
6734 LocInfoType *LocT = (LocInfoType *)BumpAlloc.Allocate(sizeof(LocInfoType),
6735 alignof(LocInfoType));
6736 new (LocT) LocInfoType(T, TInfo);
6737 assert(LocT->getTypeClass() != T->getTypeClass() &&
6738 "LocInfoType's TypeClass conflicts with an existing Type class");
6739 return ParsedType::make(QualType(LocT, 0));
6742 void LocInfoType::getAsStringInternal(std::string &Str,
6743 const PrintingPolicy &Policy) const {
6744 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6745 " was used directly instead of getting the QualType through"
6746 " GetTypeFromParser");
6749 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
6750 // C99 6.7.6: Type names have no identifier. This is already validated by
6751 // the parser.
6752 assert(D.getIdentifier() == nullptr &&
6753 "Type name should have no identifier!");
6755 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6756 QualType T = TInfo->getType();
6757 if (D.isInvalidType())
6758 return true;
6760 // Make sure there are no unused decl attributes on the declarator.
6761 // We don't want to do this for ObjC parameters because we're going
6762 // to apply them to the actual parameter declaration.
6763 // Likewise, we don't want to do this for alias declarations, because
6764 // we are actually going to build a declaration from this eventually.
6765 if (D.getContext() != DeclaratorContext::ObjCParameter &&
6766 D.getContext() != DeclaratorContext::AliasDecl &&
6767 D.getContext() != DeclaratorContext::AliasTemplate)
6768 checkUnusedDeclAttributes(D);
6770 if (getLangOpts().CPlusPlus) {
6771 // Check that there are no default arguments (C++ only).
6772 CheckExtraCXXDefaultArguments(D);
6775 return CreateParsedType(T, TInfo);
6778 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
6779 QualType T = Context.getObjCInstanceType();
6780 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
6781 return CreateParsedType(T, TInfo);
6784 //===----------------------------------------------------------------------===//
6785 // Type Attribute Processing
6786 //===----------------------------------------------------------------------===//
6788 /// Build an AddressSpace index from a constant expression and diagnose any
6789 /// errors related to invalid address_spaces. Returns true on successfully
6790 /// building an AddressSpace index.
6791 static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
6792 const Expr *AddrSpace,
6793 SourceLocation AttrLoc) {
6794 if (!AddrSpace->isValueDependent()) {
6795 std::optional<llvm::APSInt> OptAddrSpace =
6796 AddrSpace->getIntegerConstantExpr(S.Context);
6797 if (!OptAddrSpace) {
6798 S.Diag(AttrLoc, diag::err_attribute_argument_type)
6799 << "'address_space'" << AANT_ArgumentIntegerConstant
6800 << AddrSpace->getSourceRange();
6801 return false;
6803 llvm::APSInt &addrSpace = *OptAddrSpace;
6805 // Bounds checking.
6806 if (addrSpace.isSigned()) {
6807 if (addrSpace.isNegative()) {
6808 S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
6809 << AddrSpace->getSourceRange();
6810 return false;
6812 addrSpace.setIsSigned(false);
6815 llvm::APSInt max(addrSpace.getBitWidth());
6816 max =
6817 Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace;
6819 if (addrSpace > max) {
6820 S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
6821 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
6822 return false;
6825 ASIdx =
6826 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
6827 return true;
6830 // Default value for DependentAddressSpaceTypes
6831 ASIdx = LangAS::Default;
6832 return true;
6835 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression
6836 /// is uninstantiated. If instantiated it will apply the appropriate address
6837 /// space to the type. This function allows dependent template variables to be
6838 /// used in conjunction with the address_space attribute
6839 QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
6840 SourceLocation AttrLoc) {
6841 if (!AddrSpace->isValueDependent()) {
6842 if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
6843 AttrLoc))
6844 return QualType();
6846 return Context.getAddrSpaceQualType(T, ASIdx);
6849 // A check with similar intentions as checking if a type already has an
6850 // address space except for on a dependent types, basically if the
6851 // current type is already a DependentAddressSpaceType then its already
6852 // lined up to have another address space on it and we can't have
6853 // multiple address spaces on the one pointer indirection
6854 if (T->getAs<DependentAddressSpaceType>()) {
6855 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
6856 return QualType();
6859 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
6862 QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
6863 SourceLocation AttrLoc) {
6864 LangAS ASIdx;
6865 if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
6866 return QualType();
6867 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
6870 static void HandleBTFTypeTagAttribute(QualType &Type, const ParsedAttr &Attr,
6871 TypeProcessingState &State) {
6872 Sema &S = State.getSema();
6874 // Check the number of attribute arguments.
6875 if (Attr.getNumArgs() != 1) {
6876 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6877 << Attr << 1;
6878 Attr.setInvalid();
6879 return;
6882 // Ensure the argument is a string.
6883 auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6884 if (!StrLiteral) {
6885 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6886 << Attr << AANT_ArgumentString;
6887 Attr.setInvalid();
6888 return;
6891 ASTContext &Ctx = S.Context;
6892 StringRef BTFTypeTag = StrLiteral->getString();
6893 Type = State.getBTFTagAttributedType(
6894 ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type);
6897 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6898 /// specified type. The attribute contains 1 argument, the id of the address
6899 /// space for the type.
6900 static void HandleAddressSpaceTypeAttribute(QualType &Type,
6901 const ParsedAttr &Attr,
6902 TypeProcessingState &State) {
6903 Sema &S = State.getSema();
6905 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6906 // qualified by an address-space qualifier."
6907 if (Type->isFunctionType()) {
6908 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
6909 Attr.setInvalid();
6910 return;
6913 LangAS ASIdx;
6914 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
6916 // Check the attribute arguments.
6917 if (Attr.getNumArgs() != 1) {
6918 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
6919 << 1;
6920 Attr.setInvalid();
6921 return;
6924 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6925 LangAS ASIdx;
6926 if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
6927 Attr.setInvalid();
6928 return;
6931 ASTContext &Ctx = S.Context;
6932 auto *ASAttr =
6933 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
6935 // If the expression is not value dependent (not templated), then we can
6936 // apply the address space qualifiers just to the equivalent type.
6937 // Otherwise, we make an AttributedType with the modified and equivalent
6938 // type the same, and wrap it in a DependentAddressSpaceType. When this
6939 // dependent type is resolved, the qualifier is added to the equivalent type
6940 // later.
6941 QualType T;
6942 if (!ASArgExpr->isValueDependent()) {
6943 QualType EquivType =
6944 S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
6945 if (EquivType.isNull()) {
6946 Attr.setInvalid();
6947 return;
6949 T = State.getAttributedType(ASAttr, Type, EquivType);
6950 } else {
6951 T = State.getAttributedType(ASAttr, Type, Type);
6952 T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
6955 if (!T.isNull())
6956 Type = T;
6957 else
6958 Attr.setInvalid();
6959 } else {
6960 // The keyword-based type attributes imply which address space to use.
6961 ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS()
6962 : Attr.asOpenCLLangAS();
6963 if (S.getLangOpts().HLSL)
6964 ASIdx = Attr.asHLSLLangAS();
6966 if (ASIdx == LangAS::Default)
6967 llvm_unreachable("Invalid address space");
6969 if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
6970 Attr.getLoc())) {
6971 Attr.setInvalid();
6972 return;
6975 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
6979 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
6980 /// attribute on the specified type.
6982 /// Returns 'true' if the attribute was handled.
6983 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6984 ParsedAttr &attr, QualType &type) {
6985 bool NonObjCPointer = false;
6987 if (!type->isDependentType() && !type->isUndeducedType()) {
6988 if (const PointerType *ptr = type->getAs<PointerType>()) {
6989 QualType pointee = ptr->getPointeeType();
6990 if (pointee->isObjCRetainableType() || pointee->isPointerType())
6991 return false;
6992 // It is important not to lose the source info that there was an attribute
6993 // applied to non-objc pointer. We will create an attributed type but
6994 // its type will be the same as the original type.
6995 NonObjCPointer = true;
6996 } else if (!type->isObjCRetainableType()) {
6997 return false;
7000 // Don't accept an ownership attribute in the declspec if it would
7001 // just be the return type of a block pointer.
7002 if (state.isProcessingDeclSpec()) {
7003 Declarator &D = state.getDeclarator();
7004 if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
7005 /*onlyBlockPointers=*/true))
7006 return false;
7010 Sema &S = state.getSema();
7011 SourceLocation AttrLoc = attr.getLoc();
7012 if (AttrLoc.isMacroID())
7013 AttrLoc =
7014 S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin();
7016 if (!attr.isArgIdent(0)) {
7017 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
7018 << AANT_ArgumentString;
7019 attr.setInvalid();
7020 return true;
7023 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
7024 Qualifiers::ObjCLifetime lifetime;
7025 if (II->isStr("none"))
7026 lifetime = Qualifiers::OCL_ExplicitNone;
7027 else if (II->isStr("strong"))
7028 lifetime = Qualifiers::OCL_Strong;
7029 else if (II->isStr("weak"))
7030 lifetime = Qualifiers::OCL_Weak;
7031 else if (II->isStr("autoreleasing"))
7032 lifetime = Qualifiers::OCL_Autoreleasing;
7033 else {
7034 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II;
7035 attr.setInvalid();
7036 return true;
7039 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
7040 // outside of ARC mode.
7041 if (!S.getLangOpts().ObjCAutoRefCount &&
7042 lifetime != Qualifiers::OCL_Weak &&
7043 lifetime != Qualifiers::OCL_ExplicitNone) {
7044 return true;
7047 SplitQualType underlyingType = type.split();
7049 // Check for redundant/conflicting ownership qualifiers.
7050 if (Qualifiers::ObjCLifetime previousLifetime
7051 = type.getQualifiers().getObjCLifetime()) {
7052 // If it's written directly, that's an error.
7053 if (S.Context.hasDirectOwnershipQualifier(type)) {
7054 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
7055 << type;
7056 return true;
7059 // Otherwise, if the qualifiers actually conflict, pull sugar off
7060 // and remove the ObjCLifetime qualifiers.
7061 if (previousLifetime != lifetime) {
7062 // It's possible to have multiple local ObjCLifetime qualifiers. We
7063 // can't stop after we reach a type that is directly qualified.
7064 const Type *prevTy = nullptr;
7065 while (!prevTy || prevTy != underlyingType.Ty) {
7066 prevTy = underlyingType.Ty;
7067 underlyingType = underlyingType.getSingleStepDesugaredType();
7069 underlyingType.Quals.removeObjCLifetime();
7073 underlyingType.Quals.addObjCLifetime(lifetime);
7075 if (NonObjCPointer) {
7076 StringRef name = attr.getAttrName()->getName();
7077 switch (lifetime) {
7078 case Qualifiers::OCL_None:
7079 case Qualifiers::OCL_ExplicitNone:
7080 break;
7081 case Qualifiers::OCL_Strong: name = "__strong"; break;
7082 case Qualifiers::OCL_Weak: name = "__weak"; break;
7083 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
7085 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
7086 << TDS_ObjCObjOrBlock << type;
7089 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
7090 // because having both 'T' and '__unsafe_unretained T' exist in the type
7091 // system causes unfortunate widespread consistency problems. (For example,
7092 // they're not considered compatible types, and we mangle them identicially
7093 // as template arguments.) These problems are all individually fixable,
7094 // but it's easier to just not add the qualifier and instead sniff it out
7095 // in specific places using isObjCInertUnsafeUnretainedType().
7097 // Doing this does means we miss some trivial consistency checks that
7098 // would've triggered in ARC, but that's better than trying to solve all
7099 // the coexistence problems with __unsafe_unretained.
7100 if (!S.getLangOpts().ObjCAutoRefCount &&
7101 lifetime == Qualifiers::OCL_ExplicitNone) {
7102 type = state.getAttributedType(
7103 createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr),
7104 type, type);
7105 return true;
7108 QualType origType = type;
7109 if (!NonObjCPointer)
7110 type = S.Context.getQualifiedType(underlyingType);
7112 // If we have a valid source location for the attribute, use an
7113 // AttributedType instead.
7114 if (AttrLoc.isValid()) {
7115 type = state.getAttributedType(::new (S.Context)
7116 ObjCOwnershipAttr(S.Context, attr, II),
7117 origType, type);
7120 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
7121 unsigned diagnostic, QualType type) {
7122 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
7123 S.DelayedDiagnostics.add(
7124 sema::DelayedDiagnostic::makeForbiddenType(
7125 S.getSourceManager().getExpansionLoc(loc),
7126 diagnostic, type, /*ignored*/ 0));
7127 } else {
7128 S.Diag(loc, diagnostic);
7132 // Sometimes, __weak isn't allowed.
7133 if (lifetime == Qualifiers::OCL_Weak &&
7134 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
7136 // Use a specialized diagnostic if the runtime just doesn't support them.
7137 unsigned diagnostic =
7138 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
7139 : diag::err_arc_weak_no_runtime);
7141 // In any case, delay the diagnostic until we know what we're parsing.
7142 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
7144 attr.setInvalid();
7145 return true;
7148 // Forbid __weak for class objects marked as
7149 // objc_arc_weak_reference_unavailable
7150 if (lifetime == Qualifiers::OCL_Weak) {
7151 if (const ObjCObjectPointerType *ObjT =
7152 type->getAs<ObjCObjectPointerType>()) {
7153 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
7154 if (Class->isArcWeakrefUnavailable()) {
7155 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
7156 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
7157 diag::note_class_declared);
7163 return true;
7166 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
7167 /// attribute on the specified type. Returns true to indicate that
7168 /// the attribute was handled, false to indicate that the type does
7169 /// not permit the attribute.
7170 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7171 QualType &type) {
7172 Sema &S = state.getSema();
7174 // Delay if this isn't some kind of pointer.
7175 if (!type->isPointerType() &&
7176 !type->isObjCObjectPointerType() &&
7177 !type->isBlockPointerType())
7178 return false;
7180 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
7181 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
7182 attr.setInvalid();
7183 return true;
7186 // Check the attribute arguments.
7187 if (!attr.isArgIdent(0)) {
7188 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
7189 << attr << AANT_ArgumentString;
7190 attr.setInvalid();
7191 return true;
7193 Qualifiers::GC GCAttr;
7194 if (attr.getNumArgs() > 1) {
7195 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
7196 << 1;
7197 attr.setInvalid();
7198 return true;
7201 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
7202 if (II->isStr("weak"))
7203 GCAttr = Qualifiers::Weak;
7204 else if (II->isStr("strong"))
7205 GCAttr = Qualifiers::Strong;
7206 else {
7207 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
7208 << attr << II;
7209 attr.setInvalid();
7210 return true;
7213 QualType origType = type;
7214 type = S.Context.getObjCGCQualType(origType, GCAttr);
7216 // Make an attributed type to preserve the source information.
7217 if (attr.getLoc().isValid())
7218 type = state.getAttributedType(
7219 ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type);
7221 return true;
7224 namespace {
7225 /// A helper class to unwrap a type down to a function for the
7226 /// purposes of applying attributes there.
7228 /// Use:
7229 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
7230 /// if (unwrapped.isFunctionType()) {
7231 /// const FunctionType *fn = unwrapped.get();
7232 /// // change fn somehow
7233 /// T = unwrapped.wrap(fn);
7234 /// }
7235 struct FunctionTypeUnwrapper {
7236 enum WrapKind {
7237 Desugar,
7238 Attributed,
7239 Parens,
7240 Array,
7241 Pointer,
7242 BlockPointer,
7243 Reference,
7244 MemberPointer,
7245 MacroQualified,
7248 QualType Original;
7249 const FunctionType *Fn;
7250 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
7252 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
7253 while (true) {
7254 const Type *Ty = T.getTypePtr();
7255 if (isa<FunctionType>(Ty)) {
7256 Fn = cast<FunctionType>(Ty);
7257 return;
7258 } else if (isa<ParenType>(Ty)) {
7259 T = cast<ParenType>(Ty)->getInnerType();
7260 Stack.push_back(Parens);
7261 } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) ||
7262 isa<IncompleteArrayType>(Ty)) {
7263 T = cast<ArrayType>(Ty)->getElementType();
7264 Stack.push_back(Array);
7265 } else if (isa<PointerType>(Ty)) {
7266 T = cast<PointerType>(Ty)->getPointeeType();
7267 Stack.push_back(Pointer);
7268 } else if (isa<BlockPointerType>(Ty)) {
7269 T = cast<BlockPointerType>(Ty)->getPointeeType();
7270 Stack.push_back(BlockPointer);
7271 } else if (isa<MemberPointerType>(Ty)) {
7272 T = cast<MemberPointerType>(Ty)->getPointeeType();
7273 Stack.push_back(MemberPointer);
7274 } else if (isa<ReferenceType>(Ty)) {
7275 T = cast<ReferenceType>(Ty)->getPointeeType();
7276 Stack.push_back(Reference);
7277 } else if (isa<AttributedType>(Ty)) {
7278 T = cast<AttributedType>(Ty)->getEquivalentType();
7279 Stack.push_back(Attributed);
7280 } else if (isa<MacroQualifiedType>(Ty)) {
7281 T = cast<MacroQualifiedType>(Ty)->getUnderlyingType();
7282 Stack.push_back(MacroQualified);
7283 } else {
7284 const Type *DTy = Ty->getUnqualifiedDesugaredType();
7285 if (Ty == DTy) {
7286 Fn = nullptr;
7287 return;
7290 T = QualType(DTy, 0);
7291 Stack.push_back(Desugar);
7296 bool isFunctionType() const { return (Fn != nullptr); }
7297 const FunctionType *get() const { return Fn; }
7299 QualType wrap(Sema &S, const FunctionType *New) {
7300 // If T wasn't modified from the unwrapped type, do nothing.
7301 if (New == get()) return Original;
7303 Fn = New;
7304 return wrap(S.Context, Original, 0);
7307 private:
7308 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
7309 if (I == Stack.size())
7310 return C.getQualifiedType(Fn, Old.getQualifiers());
7312 // Build up the inner type, applying the qualifiers from the old
7313 // type to the new type.
7314 SplitQualType SplitOld = Old.split();
7316 // As a special case, tail-recurse if there are no qualifiers.
7317 if (SplitOld.Quals.empty())
7318 return wrap(C, SplitOld.Ty, I);
7319 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
7322 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
7323 if (I == Stack.size()) return QualType(Fn, 0);
7325 switch (static_cast<WrapKind>(Stack[I++])) {
7326 case Desugar:
7327 // This is the point at which we potentially lose source
7328 // information.
7329 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
7331 case Attributed:
7332 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
7334 case Parens: {
7335 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
7336 return C.getParenType(New);
7339 case MacroQualified:
7340 return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I);
7342 case Array: {
7343 if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) {
7344 QualType New = wrap(C, CAT->getElementType(), I);
7345 return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(),
7346 CAT->getSizeModifier(),
7347 CAT->getIndexTypeCVRQualifiers());
7350 if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) {
7351 QualType New = wrap(C, VAT->getElementType(), I);
7352 return C.getVariableArrayType(
7353 New, VAT->getSizeExpr(), VAT->getSizeModifier(),
7354 VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange());
7357 const auto *IAT = cast<IncompleteArrayType>(Old);
7358 QualType New = wrap(C, IAT->getElementType(), I);
7359 return C.getIncompleteArrayType(New, IAT->getSizeModifier(),
7360 IAT->getIndexTypeCVRQualifiers());
7363 case Pointer: {
7364 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
7365 return C.getPointerType(New);
7368 case BlockPointer: {
7369 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
7370 return C.getBlockPointerType(New);
7373 case MemberPointer: {
7374 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
7375 QualType New = wrap(C, OldMPT->getPointeeType(), I);
7376 return C.getMemberPointerType(New, OldMPT->getClass());
7379 case Reference: {
7380 const ReferenceType *OldRef = cast<ReferenceType>(Old);
7381 QualType New = wrap(C, OldRef->getPointeeType(), I);
7382 if (isa<LValueReferenceType>(OldRef))
7383 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
7384 else
7385 return C.getRValueReferenceType(New);
7389 llvm_unreachable("unknown wrapping kind");
7392 } // end anonymous namespace
7394 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
7395 ParsedAttr &PAttr, QualType &Type) {
7396 Sema &S = State.getSema();
7398 Attr *A;
7399 switch (PAttr.getKind()) {
7400 default: llvm_unreachable("Unknown attribute kind");
7401 case ParsedAttr::AT_Ptr32:
7402 A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr);
7403 break;
7404 case ParsedAttr::AT_Ptr64:
7405 A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr);
7406 break;
7407 case ParsedAttr::AT_SPtr:
7408 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
7409 break;
7410 case ParsedAttr::AT_UPtr:
7411 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
7412 break;
7415 std::bitset<attr::LastAttr> Attrs;
7416 QualType Desugared = Type;
7417 for (;;) {
7418 if (const TypedefType *TT = dyn_cast<TypedefType>(Desugared)) {
7419 Desugared = TT->desugar();
7420 continue;
7421 } else if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(Desugared)) {
7422 Desugared = ET->desugar();
7423 continue;
7425 const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
7426 if (!AT)
7427 break;
7428 Attrs[AT->getAttrKind()] = true;
7429 Desugared = AT->getModifiedType();
7432 // You cannot specify duplicate type attributes, so if the attribute has
7433 // already been applied, flag it.
7434 attr::Kind NewAttrKind = A->getKind();
7435 if (Attrs[NewAttrKind]) {
7436 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7437 return true;
7439 Attrs[NewAttrKind] = true;
7441 // You cannot have both __sptr and __uptr on the same type, nor can you
7442 // have __ptr32 and __ptr64.
7443 if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) {
7444 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7445 << "'__ptr32'"
7446 << "'__ptr64'" << /*isRegularKeyword=*/0;
7447 return true;
7448 } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) {
7449 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7450 << "'__sptr'"
7451 << "'__uptr'" << /*isRegularKeyword=*/0;
7452 return true;
7455 // Check the raw (i.e., desugared) Canonical type to see if it
7456 // is a pointer type.
7457 if (!isa<PointerType>(Desugared)) {
7458 // Pointer type qualifiers can only operate on pointer types, but not
7459 // pointer-to-member types.
7460 if (Type->isMemberPointerType())
7461 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
7462 else
7463 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
7464 return true;
7467 // Add address space to type based on its attributes.
7468 LangAS ASIdx = LangAS::Default;
7469 uint64_t PtrWidth =
7470 S.Context.getTargetInfo().getPointerWidth(LangAS::Default);
7471 if (PtrWidth == 32) {
7472 if (Attrs[attr::Ptr64])
7473 ASIdx = LangAS::ptr64;
7474 else if (Attrs[attr::UPtr])
7475 ASIdx = LangAS::ptr32_uptr;
7476 } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) {
7477 if (Attrs[attr::UPtr])
7478 ASIdx = LangAS::ptr32_uptr;
7479 else
7480 ASIdx = LangAS::ptr32_sptr;
7483 QualType Pointee = Type->getPointeeType();
7484 if (ASIdx != LangAS::Default)
7485 Pointee = S.Context.getAddrSpaceQualType(
7486 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7487 Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee));
7488 return false;
7491 static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State,
7492 QualType &QT, ParsedAttr &PAttr) {
7493 assert(PAttr.getKind() == ParsedAttr::AT_WebAssemblyFuncref);
7495 Sema &S = State.getSema();
7496 Attr *A = createSimpleAttr<WebAssemblyFuncrefAttr>(S.Context, PAttr);
7498 std::bitset<attr::LastAttr> Attrs;
7499 attr::Kind NewAttrKind = A->getKind();
7500 const auto *AT = dyn_cast<AttributedType>(QT);
7501 while (AT) {
7502 Attrs[AT->getAttrKind()] = true;
7503 AT = dyn_cast<AttributedType>(AT->getModifiedType());
7506 // You cannot specify duplicate type attributes, so if the attribute has
7507 // already been applied, flag it.
7508 if (Attrs[NewAttrKind]) {
7509 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7510 return true;
7513 // Add address space to type based on its attributes.
7514 LangAS ASIdx = LangAS::wasm_funcref;
7515 QualType Pointee = QT->getPointeeType();
7516 Pointee = S.Context.getAddrSpaceQualType(
7517 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7518 QT = State.getAttributedType(A, QT, S.Context.getPointerType(Pointee));
7519 return false;
7522 /// Map a nullability attribute kind to a nullability kind.
7523 static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) {
7524 switch (kind) {
7525 case ParsedAttr::AT_TypeNonNull:
7526 return NullabilityKind::NonNull;
7528 case ParsedAttr::AT_TypeNullable:
7529 return NullabilityKind::Nullable;
7531 case ParsedAttr::AT_TypeNullableResult:
7532 return NullabilityKind::NullableResult;
7534 case ParsedAttr::AT_TypeNullUnspecified:
7535 return NullabilityKind::Unspecified;
7537 default:
7538 llvm_unreachable("not a nullability attribute kind");
7542 /// Applies a nullability type specifier to the given type, if possible.
7544 /// \param state The type processing state.
7546 /// \param type The type to which the nullability specifier will be
7547 /// added. On success, this type will be updated appropriately.
7549 /// \param attr The attribute as written on the type.
7551 /// \param allowOnArrayType Whether to accept nullability specifiers on an
7552 /// array type (e.g., because it will decay to a pointer).
7554 /// \returns true if a problem has been diagnosed, false on success.
7555 static bool checkNullabilityTypeSpecifier(TypeProcessingState &state,
7556 QualType &type,
7557 ParsedAttr &attr,
7558 bool allowOnArrayType) {
7559 Sema &S = state.getSema();
7561 NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind());
7562 SourceLocation nullabilityLoc = attr.getLoc();
7563 bool isContextSensitive = attr.isContextSensitiveKeywordAttribute();
7565 recordNullabilitySeen(S, nullabilityLoc);
7567 // Check for existing nullability attributes on the type.
7568 QualType desugared = type;
7569 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
7570 // Check whether there is already a null
7571 if (auto existingNullability = attributed->getImmediateNullability()) {
7572 // Duplicated nullability.
7573 if (nullability == *existingNullability) {
7574 S.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
7575 << DiagNullabilityKind(nullability, isContextSensitive)
7576 << FixItHint::CreateRemoval(nullabilityLoc);
7578 break;
7581 // Conflicting nullability.
7582 S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
7583 << DiagNullabilityKind(nullability, isContextSensitive)
7584 << DiagNullabilityKind(*existingNullability, false);
7585 return true;
7588 desugared = attributed->getModifiedType();
7591 // If there is already a different nullability specifier, complain.
7592 // This (unlike the code above) looks through typedefs that might
7593 // have nullability specifiers on them, which means we cannot
7594 // provide a useful Fix-It.
7595 if (auto existingNullability = desugared->getNullability()) {
7596 if (nullability != *existingNullability) {
7597 S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
7598 << DiagNullabilityKind(nullability, isContextSensitive)
7599 << DiagNullabilityKind(*existingNullability, false);
7601 // Try to find the typedef with the existing nullability specifier.
7602 if (auto typedefType = desugared->getAs<TypedefType>()) {
7603 TypedefNameDecl *typedefDecl = typedefType->getDecl();
7604 QualType underlyingType = typedefDecl->getUnderlyingType();
7605 if (auto typedefNullability
7606 = AttributedType::stripOuterNullability(underlyingType)) {
7607 if (*typedefNullability == *existingNullability) {
7608 S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
7609 << DiagNullabilityKind(*existingNullability, false);
7614 return true;
7618 // If this definitely isn't a pointer type, reject the specifier.
7619 if (!desugared->canHaveNullability() &&
7620 !(allowOnArrayType && desugared->isArrayType())) {
7621 S.Diag(nullabilityLoc, diag::err_nullability_nonpointer)
7622 << DiagNullabilityKind(nullability, isContextSensitive) << type;
7623 return true;
7626 // For the context-sensitive keywords/Objective-C property
7627 // attributes, require that the type be a single-level pointer.
7628 if (isContextSensitive) {
7629 // Make sure that the pointee isn't itself a pointer type.
7630 const Type *pointeeType = nullptr;
7631 if (desugared->isArrayType())
7632 pointeeType = desugared->getArrayElementTypeNoTypeQual();
7633 else if (desugared->isAnyPointerType())
7634 pointeeType = desugared->getPointeeType().getTypePtr();
7636 if (pointeeType && (pointeeType->isAnyPointerType() ||
7637 pointeeType->isObjCObjectPointerType() ||
7638 pointeeType->isMemberPointerType())) {
7639 S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
7640 << DiagNullabilityKind(nullability, true)
7641 << type;
7642 S.Diag(nullabilityLoc, diag::note_nullability_type_specifier)
7643 << DiagNullabilityKind(nullability, false)
7644 << type
7645 << FixItHint::CreateReplacement(nullabilityLoc,
7646 getNullabilitySpelling(nullability));
7647 return true;
7651 // Form the attributed type.
7652 type = state.getAttributedType(
7653 createNullabilityAttr(S.Context, attr, nullability), type, type);
7654 return false;
7657 /// Check the application of the Objective-C '__kindof' qualifier to
7658 /// the given type.
7659 static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
7660 ParsedAttr &attr) {
7661 Sema &S = state.getSema();
7663 if (isa<ObjCTypeParamType>(type)) {
7664 // Build the attributed type to record where __kindof occurred.
7665 type = state.getAttributedType(
7666 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type);
7667 return false;
7670 // Find out if it's an Objective-C object or object pointer type;
7671 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
7672 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
7673 : type->getAs<ObjCObjectType>();
7675 // If not, we can't apply __kindof.
7676 if (!objType) {
7677 // FIXME: Handle dependent types that aren't yet object types.
7678 S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
7679 << type;
7680 return true;
7683 // Rebuild the "equivalent" type, which pushes __kindof down into
7684 // the object type.
7685 // There is no need to apply kindof on an unqualified id type.
7686 QualType equivType = S.Context.getObjCObjectType(
7687 objType->getBaseType(), objType->getTypeArgsAsWritten(),
7688 objType->getProtocols(),
7689 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
7691 // If we started with an object pointer type, rebuild it.
7692 if (ptrType) {
7693 equivType = S.Context.getObjCObjectPointerType(equivType);
7694 if (auto nullability = type->getNullability()) {
7695 // We create a nullability attribute from the __kindof attribute.
7696 // Make sure that will make sense.
7697 assert(attr.getAttributeSpellingListIndex() == 0 &&
7698 "multiple spellings for __kindof?");
7699 Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
7700 A->setImplicit(true);
7701 equivType = state.getAttributedType(A, equivType, equivType);
7705 // Build the attributed type to record where __kindof occurred.
7706 type = state.getAttributedType(
7707 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType);
7708 return false;
7711 /// Distribute a nullability type attribute that cannot be applied to
7712 /// the type specifier to a pointer, block pointer, or member pointer
7713 /// declarator, complaining if necessary.
7715 /// \returns true if the nullability annotation was distributed, false
7716 /// otherwise.
7717 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
7718 QualType type, ParsedAttr &attr) {
7719 Declarator &declarator = state.getDeclarator();
7721 /// Attempt to move the attribute to the specified chunk.
7722 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
7723 // If there is already a nullability attribute there, don't add
7724 // one.
7725 if (hasNullabilityAttr(chunk.getAttrs()))
7726 return false;
7728 // Complain about the nullability qualifier being in the wrong
7729 // place.
7730 enum {
7731 PK_Pointer,
7732 PK_BlockPointer,
7733 PK_MemberPointer,
7734 PK_FunctionPointer,
7735 PK_MemberFunctionPointer,
7736 } pointerKind
7737 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
7738 : PK_Pointer)
7739 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
7740 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
7742 auto diag = state.getSema().Diag(attr.getLoc(),
7743 diag::warn_nullability_declspec)
7744 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
7745 attr.isContextSensitiveKeywordAttribute())
7746 << type
7747 << static_cast<unsigned>(pointerKind);
7749 // FIXME: MemberPointer chunks don't carry the location of the *.
7750 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
7751 diag << FixItHint::CreateRemoval(attr.getLoc())
7752 << FixItHint::CreateInsertion(
7753 state.getSema().getPreprocessor().getLocForEndOfToken(
7754 chunk.Loc),
7755 " " + attr.getAttrName()->getName().str() + " ");
7758 moveAttrFromListToList(attr, state.getCurrentAttributes(),
7759 chunk.getAttrs());
7760 return true;
7763 // Move it to the outermost pointer, member pointer, or block
7764 // pointer declarator.
7765 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
7766 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
7767 switch (chunk.Kind) {
7768 case DeclaratorChunk::Pointer:
7769 case DeclaratorChunk::BlockPointer:
7770 case DeclaratorChunk::MemberPointer:
7771 return moveToChunk(chunk, false);
7773 case DeclaratorChunk::Paren:
7774 case DeclaratorChunk::Array:
7775 continue;
7777 case DeclaratorChunk::Function:
7778 // Try to move past the return type to a function/block/member
7779 // function pointer.
7780 if (DeclaratorChunk *dest = maybeMovePastReturnType(
7781 declarator, i,
7782 /*onlyBlockPointers=*/false)) {
7783 return moveToChunk(*dest, true);
7786 return false;
7788 // Don't walk through these.
7789 case DeclaratorChunk::Reference:
7790 case DeclaratorChunk::Pipe:
7791 return false;
7795 return false;
7798 static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) {
7799 assert(!Attr.isInvalid());
7800 switch (Attr.getKind()) {
7801 default:
7802 llvm_unreachable("not a calling convention attribute");
7803 case ParsedAttr::AT_CDecl:
7804 return createSimpleAttr<CDeclAttr>(Ctx, Attr);
7805 case ParsedAttr::AT_FastCall:
7806 return createSimpleAttr<FastCallAttr>(Ctx, Attr);
7807 case ParsedAttr::AT_StdCall:
7808 return createSimpleAttr<StdCallAttr>(Ctx, Attr);
7809 case ParsedAttr::AT_ThisCall:
7810 return createSimpleAttr<ThisCallAttr>(Ctx, Attr);
7811 case ParsedAttr::AT_RegCall:
7812 return createSimpleAttr<RegCallAttr>(Ctx, Attr);
7813 case ParsedAttr::AT_Pascal:
7814 return createSimpleAttr<PascalAttr>(Ctx, Attr);
7815 case ParsedAttr::AT_SwiftCall:
7816 return createSimpleAttr<SwiftCallAttr>(Ctx, Attr);
7817 case ParsedAttr::AT_SwiftAsyncCall:
7818 return createSimpleAttr<SwiftAsyncCallAttr>(Ctx, Attr);
7819 case ParsedAttr::AT_VectorCall:
7820 return createSimpleAttr<VectorCallAttr>(Ctx, Attr);
7821 case ParsedAttr::AT_AArch64VectorPcs:
7822 return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr);
7823 case ParsedAttr::AT_AArch64SVEPcs:
7824 return createSimpleAttr<AArch64SVEPcsAttr>(Ctx, Attr);
7825 case ParsedAttr::AT_ArmStreaming:
7826 return createSimpleAttr<ArmStreamingAttr>(Ctx, Attr);
7827 case ParsedAttr::AT_AMDGPUKernelCall:
7828 return createSimpleAttr<AMDGPUKernelCallAttr>(Ctx, Attr);
7829 case ParsedAttr::AT_Pcs: {
7830 // The attribute may have had a fixit applied where we treated an
7831 // identifier as a string literal. The contents of the string are valid,
7832 // but the form may not be.
7833 StringRef Str;
7834 if (Attr.isArgExpr(0))
7835 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
7836 else
7837 Str = Attr.getArgAsIdent(0)->Ident->getName();
7838 PcsAttr::PCSType Type;
7839 if (!PcsAttr::ConvertStrToPCSType(Str, Type))
7840 llvm_unreachable("already validated the attribute");
7841 return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
7843 case ParsedAttr::AT_IntelOclBicc:
7844 return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr);
7845 case ParsedAttr::AT_MSABI:
7846 return createSimpleAttr<MSABIAttr>(Ctx, Attr);
7847 case ParsedAttr::AT_SysVABI:
7848 return createSimpleAttr<SysVABIAttr>(Ctx, Attr);
7849 case ParsedAttr::AT_PreserveMost:
7850 return createSimpleAttr<PreserveMostAttr>(Ctx, Attr);
7851 case ParsedAttr::AT_PreserveAll:
7852 return createSimpleAttr<PreserveAllAttr>(Ctx, Attr);
7853 case ParsedAttr::AT_M68kRTD:
7854 return createSimpleAttr<M68kRTDAttr>(Ctx, Attr);
7856 llvm_unreachable("unexpected attribute kind!");
7859 static bool checkMutualExclusion(TypeProcessingState &state,
7860 const FunctionProtoType::ExtProtoInfo &EPI,
7861 ParsedAttr &Attr,
7862 AttributeCommonInfo::Kind OtherKind) {
7863 auto OtherAttr = std::find_if(
7864 state.getCurrentAttributes().begin(), state.getCurrentAttributes().end(),
7865 [OtherKind](const ParsedAttr &A) { return A.getKind() == OtherKind; });
7866 if (OtherAttr == state.getCurrentAttributes().end() || OtherAttr->isInvalid())
7867 return false;
7869 Sema &S = state.getSema();
7870 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
7871 << *OtherAttr << Attr
7872 << (OtherAttr->isRegularKeywordAttribute() ||
7873 Attr.isRegularKeywordAttribute());
7874 S.Diag(OtherAttr->getLoc(), diag::note_conflicting_attribute);
7875 Attr.setInvalid();
7876 return true;
7879 /// Process an individual function attribute. Returns true to
7880 /// indicate that the attribute was handled, false if it wasn't.
7881 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7882 QualType &type,
7883 Sema::CUDAFunctionTarget CFT) {
7884 Sema &S = state.getSema();
7886 FunctionTypeUnwrapper unwrapped(S, type);
7888 if (attr.getKind() == ParsedAttr::AT_NoReturn) {
7889 if (S.CheckAttrNoArgs(attr))
7890 return true;
7892 // Delay if this is not a function type.
7893 if (!unwrapped.isFunctionType())
7894 return false;
7896 // Otherwise we can process right away.
7897 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
7898 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7899 return true;
7902 if (attr.getKind() == ParsedAttr::AT_CmseNSCall) {
7903 // Delay if this is not a function type.
7904 if (!unwrapped.isFunctionType())
7905 return false;
7907 // Ignore if we don't have CMSE enabled.
7908 if (!S.getLangOpts().Cmse) {
7909 S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr;
7910 attr.setInvalid();
7911 return true;
7914 // Otherwise we can process right away.
7915 FunctionType::ExtInfo EI =
7916 unwrapped.get()->getExtInfo().withCmseNSCall(true);
7917 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7918 return true;
7921 // ns_returns_retained is not always a type attribute, but if we got
7922 // here, we're treating it as one right now.
7923 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
7924 if (attr.getNumArgs()) return true;
7926 // Delay if this is not a function type.
7927 if (!unwrapped.isFunctionType())
7928 return false;
7930 // Check whether the return type is reasonable.
7931 if (S.checkNSReturnsRetainedReturnType(attr.getLoc(),
7932 unwrapped.get()->getReturnType()))
7933 return true;
7935 // Only actually change the underlying type in ARC builds.
7936 QualType origType = type;
7937 if (state.getSema().getLangOpts().ObjCAutoRefCount) {
7938 FunctionType::ExtInfo EI
7939 = unwrapped.get()->getExtInfo().withProducesResult(true);
7940 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7942 type = state.getAttributedType(
7943 createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr),
7944 origType, type);
7945 return true;
7948 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
7949 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
7950 return true;
7952 // Delay if this is not a function type.
7953 if (!unwrapped.isFunctionType())
7954 return false;
7956 FunctionType::ExtInfo EI =
7957 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
7958 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7959 return true;
7962 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
7963 if (!S.getLangOpts().CFProtectionBranch) {
7964 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
7965 attr.setInvalid();
7966 return true;
7969 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
7970 return true;
7972 // If this is not a function type, warning will be asserted by subject
7973 // check.
7974 if (!unwrapped.isFunctionType())
7975 return true;
7977 FunctionType::ExtInfo EI =
7978 unwrapped.get()->getExtInfo().withNoCfCheck(true);
7979 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7980 return true;
7983 if (attr.getKind() == ParsedAttr::AT_Regparm) {
7984 unsigned value;
7985 if (S.CheckRegparmAttr(attr, value))
7986 return true;
7988 // Delay if this is not a function type.
7989 if (!unwrapped.isFunctionType())
7990 return false;
7992 // Diagnose regparm with fastcall.
7993 const FunctionType *fn = unwrapped.get();
7994 CallingConv CC = fn->getCallConv();
7995 if (CC == CC_X86FastCall) {
7996 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7997 << FunctionType::getNameForCallConv(CC) << "regparm"
7998 << attr.isRegularKeywordAttribute();
7999 attr.setInvalid();
8000 return true;
8003 FunctionType::ExtInfo EI =
8004 unwrapped.get()->getExtInfo().withRegParm(value);
8005 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8006 return true;
8009 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8010 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible ||
8011 attr.getKind() == ParsedAttr::AT_ArmSharedZA ||
8012 attr.getKind() == ParsedAttr::AT_ArmPreservesZA){
8013 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
8014 return true;
8016 if (!unwrapped.isFunctionType())
8017 return false;
8019 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8020 if (!FnTy) {
8021 // SME ACLE attributes are not supported on K&R-style unprototyped C
8022 // functions.
8023 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type) <<
8024 attr << attr.isRegularKeywordAttribute() << ExpectedFunctionWithProtoType;
8025 attr.setInvalid();
8026 return false;
8029 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8030 switch (attr.getKind()) {
8031 case ParsedAttr::AT_ArmStreaming:
8032 if (checkMutualExclusion(state, EPI, attr,
8033 ParsedAttr::AT_ArmStreamingCompatible))
8034 return true;
8035 EPI.setArmSMEAttribute(FunctionType::SME_PStateSMEnabledMask);
8036 break;
8037 case ParsedAttr::AT_ArmStreamingCompatible:
8038 if (checkMutualExclusion(state, EPI, attr, ParsedAttr::AT_ArmStreaming))
8039 return true;
8040 EPI.setArmSMEAttribute(FunctionType::SME_PStateSMCompatibleMask);
8041 break;
8042 case ParsedAttr::AT_ArmSharedZA:
8043 EPI.setArmSMEAttribute(FunctionType::SME_PStateZASharedMask);
8044 break;
8045 case ParsedAttr::AT_ArmPreservesZA:
8046 EPI.setArmSMEAttribute(FunctionType::SME_PStateZAPreservedMask);
8047 break;
8048 default:
8049 llvm_unreachable("Unsupported attribute");
8052 QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(),
8053 FnTy->getParamTypes(), EPI);
8054 type = unwrapped.wrap(S, newtype->getAs<FunctionType>());
8055 return true;
8058 if (attr.getKind() == ParsedAttr::AT_NoThrow) {
8059 // Delay if this is not a function type.
8060 if (!unwrapped.isFunctionType())
8061 return false;
8063 if (S.CheckAttrNoArgs(attr)) {
8064 attr.setInvalid();
8065 return true;
8068 // Otherwise we can process right away.
8069 auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
8071 // MSVC ignores nothrow if it is in conflict with an explicit exception
8072 // specification.
8073 if (Proto->hasExceptionSpec()) {
8074 switch (Proto->getExceptionSpecType()) {
8075 case EST_None:
8076 llvm_unreachable("This doesn't have an exception spec!");
8078 case EST_DynamicNone:
8079 case EST_BasicNoexcept:
8080 case EST_NoexceptTrue:
8081 case EST_NoThrow:
8082 // Exception spec doesn't conflict with nothrow, so don't warn.
8083 [[fallthrough]];
8084 case EST_Unparsed:
8085 case EST_Uninstantiated:
8086 case EST_DependentNoexcept:
8087 case EST_Unevaluated:
8088 // We don't have enough information to properly determine if there is a
8089 // conflict, so suppress the warning.
8090 break;
8091 case EST_Dynamic:
8092 case EST_MSAny:
8093 case EST_NoexceptFalse:
8094 S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored);
8095 break;
8097 return true;
8100 type = unwrapped.wrap(
8101 S, S.Context
8102 .getFunctionTypeWithExceptionSpec(
8103 QualType{Proto, 0},
8104 FunctionProtoType::ExceptionSpecInfo{EST_NoThrow})
8105 ->getAs<FunctionType>());
8106 return true;
8109 // Delay if the type didn't work out to a function.
8110 if (!unwrapped.isFunctionType()) return false;
8112 // Otherwise, a calling convention.
8113 CallingConv CC;
8114 if (S.CheckCallingConvAttr(attr, CC, /*FunctionDecl=*/nullptr, CFT))
8115 return true;
8117 const FunctionType *fn = unwrapped.get();
8118 CallingConv CCOld = fn->getCallConv();
8119 Attr *CCAttr = getCCTypeAttr(S.Context, attr);
8121 if (CCOld != CC) {
8122 // Error out on when there's already an attribute on the type
8123 // and the CCs don't match.
8124 if (S.getCallingConvAttributedType(type)) {
8125 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8126 << FunctionType::getNameForCallConv(CC)
8127 << FunctionType::getNameForCallConv(CCOld)
8128 << attr.isRegularKeywordAttribute();
8129 attr.setInvalid();
8130 return true;
8134 // Diagnose use of variadic functions with calling conventions that
8135 // don't support them (e.g. because they're callee-cleanup).
8136 // We delay warning about this on unprototyped function declarations
8137 // until after redeclaration checking, just in case we pick up a
8138 // prototype that way. And apparently we also "delay" warning about
8139 // unprototyped function types in general, despite not necessarily having
8140 // much ability to diagnose it later.
8141 if (!supportsVariadicCall(CC)) {
8142 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
8143 if (FnP && FnP->isVariadic()) {
8144 // stdcall and fastcall are ignored with a warning for GCC and MS
8145 // compatibility.
8146 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
8147 return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported)
8148 << FunctionType::getNameForCallConv(CC)
8149 << (int)Sema::CallingConventionIgnoredReason::VariadicFunction;
8151 attr.setInvalid();
8152 return S.Diag(attr.getLoc(), diag::err_cconv_varargs)
8153 << FunctionType::getNameForCallConv(CC);
8157 // Also diagnose fastcall with regparm.
8158 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
8159 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8160 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall)
8161 << attr.isRegularKeywordAttribute();
8162 attr.setInvalid();
8163 return true;
8166 // Modify the CC from the wrapped function type, wrap it all back, and then
8167 // wrap the whole thing in an AttributedType as written. The modified type
8168 // might have a different CC if we ignored the attribute.
8169 QualType Equivalent;
8170 if (CCOld == CC) {
8171 Equivalent = type;
8172 } else {
8173 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
8174 Equivalent =
8175 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8177 type = state.getAttributedType(CCAttr, type, Equivalent);
8178 return true;
8181 bool Sema::hasExplicitCallingConv(QualType T) {
8182 const AttributedType *AT;
8184 // Stop if we'd be stripping off a typedef sugar node to reach the
8185 // AttributedType.
8186 while ((AT = T->getAs<AttributedType>()) &&
8187 AT->getAs<TypedefType>() == T->getAs<TypedefType>()) {
8188 if (AT->isCallingConv())
8189 return true;
8190 T = AT->getModifiedType();
8192 return false;
8195 void Sema::adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
8196 bool IsCtorOrDtor, SourceLocation Loc) {
8197 FunctionTypeUnwrapper Unwrapped(*this, T);
8198 const FunctionType *FT = Unwrapped.get();
8199 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
8200 cast<FunctionProtoType>(FT)->isVariadic());
8201 CallingConv CurCC = FT->getCallConv();
8202 CallingConv ToCC =
8203 Context.getDefaultCallingConvention(IsVariadic, HasThisPointer);
8205 if (CurCC == ToCC)
8206 return;
8208 // MS compiler ignores explicit calling convention attributes on structors. We
8209 // should do the same.
8210 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
8211 // Issue a warning on ignored calling convention -- except of __stdcall.
8212 // Again, this is what MS compiler does.
8213 if (CurCC != CC_X86StdCall)
8214 Diag(Loc, diag::warn_cconv_unsupported)
8215 << FunctionType::getNameForCallConv(CurCC)
8216 << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor;
8217 // Default adjustment.
8218 } else {
8219 // Only adjust types with the default convention. For example, on Windows
8220 // we should adjust a __cdecl type to __thiscall for instance methods, and a
8221 // __thiscall type to __cdecl for static methods.
8222 CallingConv DefaultCC =
8223 Context.getDefaultCallingConvention(IsVariadic, !HasThisPointer);
8225 if (CurCC != DefaultCC)
8226 return;
8228 if (hasExplicitCallingConv(T))
8229 return;
8232 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
8233 QualType Wrapped = Unwrapped.wrap(*this, FT);
8234 T = Context.getAdjustedType(T, Wrapped);
8237 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
8238 /// and float scalars, although arrays, pointers, and function return values are
8239 /// allowed in conjunction with this construct. Aggregates with this attribute
8240 /// are invalid, even if they are of the same size as a corresponding scalar.
8241 /// The raw attribute should contain precisely 1 argument, the vector size for
8242 /// the variable, measured in bytes. If curType and rawAttr are well formed,
8243 /// this routine will return a new vector type.
8244 static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
8245 Sema &S) {
8246 // Check the attribute arguments.
8247 if (Attr.getNumArgs() != 1) {
8248 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8249 << 1;
8250 Attr.setInvalid();
8251 return;
8254 Expr *SizeExpr = Attr.getArgAsExpr(0);
8255 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
8256 if (!T.isNull())
8257 CurType = T;
8258 else
8259 Attr.setInvalid();
8262 /// Process the OpenCL-like ext_vector_type attribute when it occurs on
8263 /// a type.
8264 static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8265 Sema &S) {
8266 // check the attribute arguments.
8267 if (Attr.getNumArgs() != 1) {
8268 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8269 << 1;
8270 return;
8273 Expr *SizeExpr = Attr.getArgAsExpr(0);
8274 QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc());
8275 if (!T.isNull())
8276 CurType = T;
8279 static bool isPermittedNeonBaseType(QualType &Ty, VectorKind VecKind, Sema &S) {
8280 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
8281 if (!BTy)
8282 return false;
8284 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
8286 // Signed poly is mathematically wrong, but has been baked into some ABIs by
8287 // now.
8288 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
8289 Triple.getArch() == llvm::Triple::aarch64_32 ||
8290 Triple.getArch() == llvm::Triple::aarch64_be;
8291 if (VecKind == VectorKind::NeonPoly) {
8292 if (IsPolyUnsigned) {
8293 // AArch64 polynomial vectors are unsigned.
8294 return BTy->getKind() == BuiltinType::UChar ||
8295 BTy->getKind() == BuiltinType::UShort ||
8296 BTy->getKind() == BuiltinType::ULong ||
8297 BTy->getKind() == BuiltinType::ULongLong;
8298 } else {
8299 // AArch32 polynomial vectors are signed.
8300 return BTy->getKind() == BuiltinType::SChar ||
8301 BTy->getKind() == BuiltinType::Short ||
8302 BTy->getKind() == BuiltinType::LongLong;
8306 // Non-polynomial vector types: the usual suspects are allowed, as well as
8307 // float64_t on AArch64.
8308 if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) &&
8309 BTy->getKind() == BuiltinType::Double)
8310 return true;
8312 return BTy->getKind() == BuiltinType::SChar ||
8313 BTy->getKind() == BuiltinType::UChar ||
8314 BTy->getKind() == BuiltinType::Short ||
8315 BTy->getKind() == BuiltinType::UShort ||
8316 BTy->getKind() == BuiltinType::Int ||
8317 BTy->getKind() == BuiltinType::UInt ||
8318 BTy->getKind() == BuiltinType::Long ||
8319 BTy->getKind() == BuiltinType::ULong ||
8320 BTy->getKind() == BuiltinType::LongLong ||
8321 BTy->getKind() == BuiltinType::ULongLong ||
8322 BTy->getKind() == BuiltinType::Float ||
8323 BTy->getKind() == BuiltinType::Half ||
8324 BTy->getKind() == BuiltinType::BFloat16;
8327 static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr,
8328 llvm::APSInt &Result) {
8329 const auto *AttrExpr = Attr.getArgAsExpr(0);
8330 if (!AttrExpr->isTypeDependent()) {
8331 if (std::optional<llvm::APSInt> Res =
8332 AttrExpr->getIntegerConstantExpr(S.Context)) {
8333 Result = *Res;
8334 return true;
8337 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
8338 << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange();
8339 Attr.setInvalid();
8340 return false;
8343 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
8344 /// "neon_polyvector_type" attributes are used to create vector types that
8345 /// are mangled according to ARM's ABI. Otherwise, these types are identical
8346 /// to those created with the "vector_size" attribute. Unlike "vector_size"
8347 /// the argument to these Neon attributes is the number of vector elements,
8348 /// not the vector size in bytes. The vector width and element type must
8349 /// match one of the standard Neon vector types.
8350 static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8351 Sema &S, VectorKind VecKind) {
8352 bool IsTargetCUDAAndHostARM = false;
8353 if (S.getLangOpts().CUDAIsDevice) {
8354 const TargetInfo *AuxTI = S.getASTContext().getAuxTargetInfo();
8355 IsTargetCUDAAndHostARM =
8356 AuxTI && (AuxTI->getTriple().isAArch64() || AuxTI->getTriple().isARM());
8359 // Target must have NEON (or MVE, whose vectors are similar enough
8360 // not to need a separate attribute)
8361 if (!(S.Context.getTargetInfo().hasFeature("neon") ||
8362 S.Context.getTargetInfo().hasFeature("mve") ||
8363 S.Context.getTargetInfo().hasFeature("sve") ||
8364 S.Context.getTargetInfo().hasFeature("sme") ||
8365 IsTargetCUDAAndHostARM) &&
8366 VecKind == VectorKind::Neon) {
8367 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
8368 << Attr << "'neon', 'mve', 'sve' or 'sme'";
8369 Attr.setInvalid();
8370 return;
8372 if (!(S.Context.getTargetInfo().hasFeature("neon") ||
8373 S.Context.getTargetInfo().hasFeature("mve") ||
8374 IsTargetCUDAAndHostARM) &&
8375 VecKind == VectorKind::NeonPoly) {
8376 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
8377 << Attr << "'neon' or 'mve'";
8378 Attr.setInvalid();
8379 return;
8382 // Check the attribute arguments.
8383 if (Attr.getNumArgs() != 1) {
8384 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8385 << Attr << 1;
8386 Attr.setInvalid();
8387 return;
8389 // The number of elements must be an ICE.
8390 llvm::APSInt numEltsInt(32);
8391 if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt))
8392 return;
8394 // Only certain element types are supported for Neon vectors.
8395 if (!isPermittedNeonBaseType(CurType, VecKind, S) &&
8396 !IsTargetCUDAAndHostARM) {
8397 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
8398 Attr.setInvalid();
8399 return;
8402 // The total size of the vector must be 64 or 128 bits.
8403 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
8404 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
8405 unsigned vecSize = typeSize * numElts;
8406 if (vecSize != 64 && vecSize != 128) {
8407 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
8408 Attr.setInvalid();
8409 return;
8412 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
8415 /// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is
8416 /// used to create fixed-length versions of sizeless SVE types defined by
8417 /// the ACLE, such as svint32_t and svbool_t.
8418 static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr,
8419 Sema &S) {
8420 // Target must have SVE.
8421 if (!S.Context.getTargetInfo().hasFeature("sve")) {
8422 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'";
8423 Attr.setInvalid();
8424 return;
8427 // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or
8428 // if <bits>+ syntax is used.
8429 if (!S.getLangOpts().VScaleMin ||
8430 S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) {
8431 S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported)
8432 << Attr;
8433 Attr.setInvalid();
8434 return;
8437 // Check the attribute arguments.
8438 if (Attr.getNumArgs() != 1) {
8439 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8440 << Attr << 1;
8441 Attr.setInvalid();
8442 return;
8445 // The vector size must be an integer constant expression.
8446 llvm::APSInt SveVectorSizeInBits(32);
8447 if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits))
8448 return;
8450 unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue());
8452 // The attribute vector size must match -msve-vector-bits.
8453 if (VecSize != S.getLangOpts().VScaleMin * 128) {
8454 S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size)
8455 << VecSize << S.getLangOpts().VScaleMin * 128;
8456 Attr.setInvalid();
8457 return;
8460 // Attribute can only be attached to a single SVE vector or predicate type.
8461 if (!CurType->isSveVLSBuiltinType()) {
8462 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type)
8463 << Attr << CurType;
8464 Attr.setInvalid();
8465 return;
8468 const auto *BT = CurType->castAs<BuiltinType>();
8470 QualType EltType = CurType->getSveEltType(S.Context);
8471 unsigned TypeSize = S.Context.getTypeSize(EltType);
8472 VectorKind VecKind = VectorKind::SveFixedLengthData;
8473 if (BT->getKind() == BuiltinType::SveBool) {
8474 // Predicates are represented as i8.
8475 VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth();
8476 VecKind = VectorKind::SveFixedLengthPredicate;
8477 } else
8478 VecSize /= TypeSize;
8479 CurType = S.Context.getVectorType(EltType, VecSize, VecKind);
8482 static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State,
8483 QualType &CurType,
8484 ParsedAttr &Attr) {
8485 const VectorType *VT = dyn_cast<VectorType>(CurType);
8486 if (!VT || VT->getVectorKind() != VectorKind::Neon) {
8487 State.getSema().Diag(Attr.getLoc(),
8488 diag::err_attribute_arm_mve_polymorphism);
8489 Attr.setInvalid();
8490 return;
8493 CurType =
8494 State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>(
8495 State.getSema().Context, Attr),
8496 CurType, CurType);
8499 /// HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is
8500 /// used to create fixed-length versions of sizeless RVV types such as
8501 /// vint8m1_t_t.
8502 static void HandleRISCVRVVVectorBitsTypeAttr(QualType &CurType,
8503 ParsedAttr &Attr, Sema &S) {
8504 // Target must have vector extension.
8505 if (!S.Context.getTargetInfo().hasFeature("zve32x")) {
8506 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
8507 << Attr << "'zve32x'";
8508 Attr.setInvalid();
8509 return;
8512 auto VScale = S.Context.getTargetInfo().getVScaleRange(S.getLangOpts());
8513 if (!VScale || !VScale->first || VScale->first != VScale->second) {
8514 S.Diag(Attr.getLoc(), diag::err_attribute_riscv_rvv_bits_unsupported)
8515 << Attr;
8516 Attr.setInvalid();
8517 return;
8520 // Check the attribute arguments.
8521 if (Attr.getNumArgs() != 1) {
8522 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8523 << Attr << 1;
8524 Attr.setInvalid();
8525 return;
8528 // The vector size must be an integer constant expression.
8529 llvm::APSInt RVVVectorSizeInBits(32);
8530 if (!verifyValidIntegerConstantExpr(S, Attr, RVVVectorSizeInBits))
8531 return;
8533 // Attribute can only be attached to a single RVV vector type.
8534 if (!CurType->isRVVVLSBuiltinType()) {
8535 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_rvv_type)
8536 << Attr << CurType;
8537 Attr.setInvalid();
8538 return;
8541 unsigned VecSize = static_cast<unsigned>(RVVVectorSizeInBits.getZExtValue());
8543 ASTContext::BuiltinVectorTypeInfo Info =
8544 S.Context.getBuiltinVectorTypeInfo(CurType->castAs<BuiltinType>());
8545 unsigned EltSize = S.Context.getTypeSize(Info.ElementType);
8546 unsigned MinElts = Info.EC.getKnownMinValue();
8548 // The attribute vector size must match -mrvv-vector-bits.
8549 unsigned ExpectedSize = VScale->first * MinElts * EltSize;
8550 if (VecSize != ExpectedSize) {
8551 S.Diag(Attr.getLoc(), diag::err_attribute_bad_rvv_vector_size)
8552 << VecSize << ExpectedSize;
8553 Attr.setInvalid();
8554 return;
8557 VectorKind VecKind = VectorKind::RVVFixedLengthData;
8558 VecSize /= EltSize;
8559 CurType = S.Context.getVectorType(Info.ElementType, VecSize, VecKind);
8562 /// Handle OpenCL Access Qualifier Attribute.
8563 static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
8564 Sema &S) {
8565 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
8566 if (!(CurType->isImageType() || CurType->isPipeType())) {
8567 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
8568 Attr.setInvalid();
8569 return;
8572 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
8573 QualType BaseTy = TypedefTy->desugar();
8575 std::string PrevAccessQual;
8576 if (BaseTy->isPipeType()) {
8577 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
8578 OpenCLAccessAttr *Attr =
8579 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
8580 PrevAccessQual = Attr->getSpelling();
8581 } else {
8582 PrevAccessQual = "read_only";
8584 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
8586 switch (ImgType->getKind()) {
8587 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8588 case BuiltinType::Id: \
8589 PrevAccessQual = #Access; \
8590 break;
8591 #include "clang/Basic/OpenCLImageTypes.def"
8592 default:
8593 llvm_unreachable("Unable to find corresponding image type.");
8595 } else {
8596 llvm_unreachable("unexpected type");
8598 StringRef AttrName = Attr.getAttrName()->getName();
8599 if (PrevAccessQual == AttrName.ltrim("_")) {
8600 // Duplicated qualifiers
8601 S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
8602 << AttrName << Attr.getRange();
8603 } else {
8604 // Contradicting qualifiers
8605 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
8608 S.Diag(TypedefTy->getDecl()->getBeginLoc(),
8609 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
8610 } else if (CurType->isPipeType()) {
8611 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
8612 QualType ElemType = CurType->castAs<PipeType>()->getElementType();
8613 CurType = S.Context.getWritePipeType(ElemType);
8618 /// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type
8619 static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8620 Sema &S) {
8621 if (!S.getLangOpts().MatrixTypes) {
8622 S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled);
8623 return;
8626 if (Attr.getNumArgs() != 2) {
8627 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8628 << Attr << 2;
8629 return;
8632 Expr *RowsExpr = Attr.getArgAsExpr(0);
8633 Expr *ColsExpr = Attr.getArgAsExpr(1);
8634 QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc());
8635 if (!T.isNull())
8636 CurType = T;
8639 static void HandleAnnotateTypeAttr(TypeProcessingState &State,
8640 QualType &CurType, const ParsedAttr &PA) {
8641 Sema &S = State.getSema();
8643 if (PA.getNumArgs() < 1) {
8644 S.Diag(PA.getLoc(), diag::err_attribute_too_few_arguments) << PA << 1;
8645 return;
8648 // Make sure that there is a string literal as the annotation's first
8649 // argument.
8650 StringRef Str;
8651 if (!S.checkStringLiteralArgumentAttr(PA, 0, Str))
8652 return;
8654 llvm::SmallVector<Expr *, 4> Args;
8655 Args.reserve(PA.getNumArgs() - 1);
8656 for (unsigned Idx = 1; Idx < PA.getNumArgs(); Idx++) {
8657 assert(!PA.isArgIdent(Idx));
8658 Args.push_back(PA.getArgAsExpr(Idx));
8660 if (!S.ConstantFoldAttrArgs(PA, Args))
8661 return;
8662 auto *AnnotateTypeAttr =
8663 AnnotateTypeAttr::Create(S.Context, Str, Args.data(), Args.size(), PA);
8664 CurType = State.getAttributedType(AnnotateTypeAttr, CurType, CurType);
8667 static void HandleLifetimeBoundAttr(TypeProcessingState &State,
8668 QualType &CurType,
8669 ParsedAttr &Attr) {
8670 if (State.getDeclarator().isDeclarationOfFunction()) {
8671 CurType = State.getAttributedType(
8672 createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
8673 CurType, CurType);
8677 static void HandleHLSLParamModifierAttr(QualType &CurType,
8678 const ParsedAttr &Attr, Sema &S) {
8679 // Don't apply this attribute to template dependent types. It is applied on
8680 // substitution during template instantiation.
8681 if (CurType->isDependentType())
8682 return;
8683 if (Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_inout ||
8684 Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_out)
8685 CurType = S.getASTContext().getLValueReferenceType(CurType);
8688 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
8689 TypeAttrLocation TAL,
8690 const ParsedAttributesView &attrs,
8691 Sema::CUDAFunctionTarget CFT) {
8693 state.setParsedNoDeref(false);
8694 if (attrs.empty())
8695 return;
8697 // Scan through and apply attributes to this type where it makes sense. Some
8698 // attributes (such as __address_space__, __vector_size__, etc) apply to the
8699 // type, but others can be present in the type specifiers even though they
8700 // apply to the decl. Here we apply type attributes and ignore the rest.
8702 // This loop modifies the list pretty frequently, but we still need to make
8703 // sure we visit every element once. Copy the attributes list, and iterate
8704 // over that.
8705 ParsedAttributesView AttrsCopy{attrs};
8706 for (ParsedAttr &attr : AttrsCopy) {
8708 // Skip attributes that were marked to be invalid.
8709 if (attr.isInvalid())
8710 continue;
8712 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute()) {
8713 // [[gnu::...]] attributes are treated as declaration attributes, so may
8714 // not appertain to a DeclaratorChunk. If we handle them as type
8715 // attributes, accept them in that position and diagnose the GCC
8716 // incompatibility.
8717 if (attr.isGNUScope()) {
8718 assert(attr.isStandardAttributeSyntax());
8719 bool IsTypeAttr = attr.isTypeAttr();
8720 if (TAL == TAL_DeclChunk) {
8721 state.getSema().Diag(attr.getLoc(),
8722 IsTypeAttr
8723 ? diag::warn_gcc_ignores_type_attr
8724 : diag::warn_cxx11_gnu_attribute_on_type)
8725 << attr;
8726 if (!IsTypeAttr)
8727 continue;
8729 } else if (TAL != TAL_DeclSpec && TAL != TAL_DeclChunk &&
8730 !attr.isTypeAttr()) {
8731 // Otherwise, only consider type processing for a C++11 attribute if
8732 // - it has actually been applied to a type (decl-specifier-seq or
8733 // declarator chunk), or
8734 // - it is a type attribute, irrespective of where it was applied (so
8735 // that we can support the legacy behavior of some type attributes
8736 // that can be applied to the declaration name).
8737 continue;
8741 // If this is an attribute we can handle, do so now,
8742 // otherwise, add it to the FnAttrs list for rechaining.
8743 switch (attr.getKind()) {
8744 default:
8745 // A [[]] attribute on a declarator chunk must appertain to a type.
8746 if ((attr.isStandardAttributeSyntax() ||
8747 attr.isRegularKeywordAttribute()) &&
8748 TAL == TAL_DeclChunk) {
8749 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
8750 << attr << attr.isRegularKeywordAttribute();
8751 attr.setUsedAsTypeAttr();
8753 break;
8755 case ParsedAttr::UnknownAttribute:
8756 if (attr.isStandardAttributeSyntax()) {
8757 state.getSema().Diag(attr.getLoc(),
8758 diag::warn_unknown_attribute_ignored)
8759 << attr << attr.getRange();
8760 // Mark the attribute as invalid so we don't emit the same diagnostic
8761 // multiple times.
8762 attr.setInvalid();
8764 break;
8766 case ParsedAttr::IgnoredAttribute:
8767 break;
8769 case ParsedAttr::AT_BTFTypeTag:
8770 HandleBTFTypeTagAttribute(type, attr, state);
8771 attr.setUsedAsTypeAttr();
8772 break;
8774 case ParsedAttr::AT_MayAlias:
8775 // FIXME: This attribute needs to actually be handled, but if we ignore
8776 // it it breaks large amounts of Linux software.
8777 attr.setUsedAsTypeAttr();
8778 break;
8779 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
8780 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
8781 case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace:
8782 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace:
8783 case ParsedAttr::AT_OpenCLLocalAddressSpace:
8784 case ParsedAttr::AT_OpenCLConstantAddressSpace:
8785 case ParsedAttr::AT_OpenCLGenericAddressSpace:
8786 case ParsedAttr::AT_HLSLGroupSharedAddressSpace:
8787 case ParsedAttr::AT_AddressSpace:
8788 HandleAddressSpaceTypeAttribute(type, attr, state);
8789 attr.setUsedAsTypeAttr();
8790 break;
8791 OBJC_POINTER_TYPE_ATTRS_CASELIST:
8792 if (!handleObjCPointerTypeAttr(state, attr, type))
8793 distributeObjCPointerTypeAttr(state, attr, type);
8794 attr.setUsedAsTypeAttr();
8795 break;
8796 case ParsedAttr::AT_VectorSize:
8797 HandleVectorSizeAttr(type, attr, state.getSema());
8798 attr.setUsedAsTypeAttr();
8799 break;
8800 case ParsedAttr::AT_ExtVectorType:
8801 HandleExtVectorTypeAttr(type, attr, state.getSema());
8802 attr.setUsedAsTypeAttr();
8803 break;
8804 case ParsedAttr::AT_NeonVectorType:
8805 HandleNeonVectorTypeAttr(type, attr, state.getSema(), VectorKind::Neon);
8806 attr.setUsedAsTypeAttr();
8807 break;
8808 case ParsedAttr::AT_NeonPolyVectorType:
8809 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
8810 VectorKind::NeonPoly);
8811 attr.setUsedAsTypeAttr();
8812 break;
8813 case ParsedAttr::AT_ArmSveVectorBits:
8814 HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema());
8815 attr.setUsedAsTypeAttr();
8816 break;
8817 case ParsedAttr::AT_ArmMveStrictPolymorphism: {
8818 HandleArmMveStrictPolymorphismAttr(state, type, attr);
8819 attr.setUsedAsTypeAttr();
8820 break;
8822 case ParsedAttr::AT_RISCVRVVVectorBits:
8823 HandleRISCVRVVVectorBitsTypeAttr(type, attr, state.getSema());
8824 attr.setUsedAsTypeAttr();
8825 break;
8826 case ParsedAttr::AT_OpenCLAccess:
8827 HandleOpenCLAccessAttr(type, attr, state.getSema());
8828 attr.setUsedAsTypeAttr();
8829 break;
8830 case ParsedAttr::AT_LifetimeBound:
8831 if (TAL == TAL_DeclChunk)
8832 HandleLifetimeBoundAttr(state, type, attr);
8833 break;
8835 case ParsedAttr::AT_NoDeref: {
8836 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
8837 // See https://github.com/llvm/llvm-project/issues/55790 for details.
8838 // For the time being, we simply emit a warning that the attribute is
8839 // ignored.
8840 if (attr.isStandardAttributeSyntax()) {
8841 state.getSema().Diag(attr.getLoc(), diag::warn_attribute_ignored)
8842 << attr;
8843 break;
8845 ASTContext &Ctx = state.getSema().Context;
8846 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
8847 type, type);
8848 attr.setUsedAsTypeAttr();
8849 state.setParsedNoDeref(true);
8850 break;
8853 case ParsedAttr::AT_MatrixType:
8854 HandleMatrixTypeAttr(type, attr, state.getSema());
8855 attr.setUsedAsTypeAttr();
8856 break;
8858 case ParsedAttr::AT_WebAssemblyFuncref: {
8859 if (!HandleWebAssemblyFuncrefAttr(state, type, attr))
8860 attr.setUsedAsTypeAttr();
8861 break;
8864 case ParsedAttr::AT_HLSLParamModifier: {
8865 HandleHLSLParamModifierAttr(type, attr, state.getSema());
8866 attr.setUsedAsTypeAttr();
8867 break;
8870 MS_TYPE_ATTRS_CASELIST:
8871 if (!handleMSPointerTypeQualifierAttr(state, attr, type))
8872 attr.setUsedAsTypeAttr();
8873 break;
8876 NULLABILITY_TYPE_ATTRS_CASELIST:
8877 // Either add nullability here or try to distribute it. We
8878 // don't want to distribute the nullability specifier past any
8879 // dependent type, because that complicates the user model.
8880 if (type->canHaveNullability() || type->isDependentType() ||
8881 type->isArrayType() ||
8882 !distributeNullabilityTypeAttr(state, type, attr)) {
8883 unsigned endIndex;
8884 if (TAL == TAL_DeclChunk)
8885 endIndex = state.getCurrentChunkIndex();
8886 else
8887 endIndex = state.getDeclarator().getNumTypeObjects();
8888 bool allowOnArrayType =
8889 state.getDeclarator().isPrototypeContext() &&
8890 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
8891 if (checkNullabilityTypeSpecifier(
8892 state,
8893 type,
8894 attr,
8895 allowOnArrayType)) {
8896 attr.setInvalid();
8899 attr.setUsedAsTypeAttr();
8901 break;
8903 case ParsedAttr::AT_ObjCKindOf:
8904 // '__kindof' must be part of the decl-specifiers.
8905 switch (TAL) {
8906 case TAL_DeclSpec:
8907 break;
8909 case TAL_DeclChunk:
8910 case TAL_DeclName:
8911 state.getSema().Diag(attr.getLoc(),
8912 diag::err_objc_kindof_wrong_position)
8913 << FixItHint::CreateRemoval(attr.getLoc())
8914 << FixItHint::CreateInsertion(
8915 state.getDeclarator().getDeclSpec().getBeginLoc(),
8916 "__kindof ");
8917 break;
8920 // Apply it regardless.
8921 if (checkObjCKindOfType(state, type, attr))
8922 attr.setInvalid();
8923 break;
8925 case ParsedAttr::AT_NoThrow:
8926 // Exception Specifications aren't generally supported in C mode throughout
8927 // clang, so revert to attribute-based handling for C.
8928 if (!state.getSema().getLangOpts().CPlusPlus)
8929 break;
8930 [[fallthrough]];
8931 FUNCTION_TYPE_ATTRS_CASELIST:
8932 attr.setUsedAsTypeAttr();
8934 // Attributes with standard syntax have strict rules for what they
8935 // appertain to and hence should not use the "distribution" logic below.
8936 if (attr.isStandardAttributeSyntax() ||
8937 attr.isRegularKeywordAttribute()) {
8938 if (!handleFunctionTypeAttr(state, attr, type, CFT)) {
8939 diagnoseBadTypeAttribute(state.getSema(), attr, type);
8940 attr.setInvalid();
8942 break;
8945 // Never process function type attributes as part of the
8946 // declaration-specifiers.
8947 if (TAL == TAL_DeclSpec)
8948 distributeFunctionTypeAttrFromDeclSpec(state, attr, type, CFT);
8950 // Otherwise, handle the possible delays.
8951 else if (!handleFunctionTypeAttr(state, attr, type, CFT))
8952 distributeFunctionTypeAttr(state, attr, type);
8953 break;
8954 case ParsedAttr::AT_AcquireHandle: {
8955 if (!type->isFunctionType())
8956 return;
8958 if (attr.getNumArgs() != 1) {
8959 state.getSema().Diag(attr.getLoc(),
8960 diag::err_attribute_wrong_number_arguments)
8961 << attr << 1;
8962 attr.setInvalid();
8963 return;
8966 StringRef HandleType;
8967 if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType))
8968 return;
8969 type = state.getAttributedType(
8970 AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr),
8971 type, type);
8972 attr.setUsedAsTypeAttr();
8973 break;
8975 case ParsedAttr::AT_AnnotateType: {
8976 HandleAnnotateTypeAttr(state, type, attr);
8977 attr.setUsedAsTypeAttr();
8978 break;
8982 // Handle attributes that are defined in a macro. We do not want this to be
8983 // applied to ObjC builtin attributes.
8984 if (isa<AttributedType>(type) && attr.hasMacroIdentifier() &&
8985 !type.getQualifiers().hasObjCLifetime() &&
8986 !type.getQualifiers().hasObjCGCAttr() &&
8987 attr.getKind() != ParsedAttr::AT_ObjCGC &&
8988 attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
8989 const IdentifierInfo *MacroII = attr.getMacroIdentifier();
8990 type = state.getSema().Context.getMacroQualifiedType(type, MacroII);
8991 state.setExpansionLocForMacroQualifiedType(
8992 cast<MacroQualifiedType>(type.getTypePtr()),
8993 attr.getMacroExpansionLoc());
8998 void Sema::completeExprArrayBound(Expr *E) {
8999 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
9000 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
9001 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
9002 auto *Def = Var->getDefinition();
9003 if (!Def) {
9004 SourceLocation PointOfInstantiation = E->getExprLoc();
9005 runWithSufficientStackSpace(PointOfInstantiation, [&] {
9006 InstantiateVariableDefinition(PointOfInstantiation, Var);
9008 Def = Var->getDefinition();
9010 // If we don't already have a point of instantiation, and we managed
9011 // to instantiate a definition, this is the point of instantiation.
9012 // Otherwise, we don't request an end-of-TU instantiation, so this is
9013 // not a point of instantiation.
9014 // FIXME: Is this really the right behavior?
9015 if (Var->getPointOfInstantiation().isInvalid() && Def) {
9016 assert(Var->getTemplateSpecializationKind() ==
9017 TSK_ImplicitInstantiation &&
9018 "explicit instantiation with no point of instantiation");
9019 Var->setTemplateSpecializationKind(
9020 Var->getTemplateSpecializationKind(), PointOfInstantiation);
9024 // Update the type to the definition's type both here and within the
9025 // expression.
9026 if (Def) {
9027 DRE->setDecl(Def);
9028 QualType T = Def->getType();
9029 DRE->setType(T);
9030 // FIXME: Update the type on all intervening expressions.
9031 E->setType(T);
9034 // We still go on to try to complete the type independently, as it
9035 // may also require instantiations or diagnostics if it remains
9036 // incomplete.
9042 QualType Sema::getCompletedType(Expr *E) {
9043 // Incomplete array types may be completed by the initializer attached to
9044 // their definitions. For static data members of class templates and for
9045 // variable templates, we need to instantiate the definition to get this
9046 // initializer and complete the type.
9047 if (E->getType()->isIncompleteArrayType())
9048 completeExprArrayBound(E);
9050 // FIXME: Are there other cases which require instantiating something other
9051 // than the type to complete the type of an expression?
9053 return E->getType();
9056 /// Ensure that the type of the given expression is complete.
9058 /// This routine checks whether the expression \p E has a complete type. If the
9059 /// expression refers to an instantiable construct, that instantiation is
9060 /// performed as needed to complete its type. Furthermore
9061 /// Sema::RequireCompleteType is called for the expression's type (or in the
9062 /// case of a reference type, the referred-to type).
9064 /// \param E The expression whose type is required to be complete.
9065 /// \param Kind Selects which completeness rules should be applied.
9066 /// \param Diagnoser The object that will emit a diagnostic if the type is
9067 /// incomplete.
9069 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
9070 /// otherwise.
9071 bool Sema::RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
9072 TypeDiagnoser &Diagnoser) {
9073 return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind,
9074 Diagnoser);
9077 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
9078 BoundTypeDiagnoser<> Diagnoser(DiagID);
9079 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
9082 /// Ensure that the type T is a complete type.
9084 /// This routine checks whether the type @p T is complete in any
9085 /// context where a complete type is required. If @p T is a complete
9086 /// type, returns false. If @p T is a class template specialization,
9087 /// this routine then attempts to perform class template
9088 /// instantiation. If instantiation fails, or if @p T is incomplete
9089 /// and cannot be completed, issues the diagnostic @p diag (giving it
9090 /// the type @p T) and returns true.
9092 /// @param Loc The location in the source that the incomplete type
9093 /// diagnostic should refer to.
9095 /// @param T The type that this routine is examining for completeness.
9097 /// @param Kind Selects which completeness rules should be applied.
9099 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
9100 /// @c false otherwise.
9101 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
9102 CompleteTypeKind Kind,
9103 TypeDiagnoser &Diagnoser) {
9104 if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser))
9105 return true;
9106 if (const TagType *Tag = T->getAs<TagType>()) {
9107 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
9108 Tag->getDecl()->setCompleteDefinitionRequired();
9109 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
9112 return false;
9115 bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) {
9116 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
9117 if (!Suggested)
9118 return false;
9120 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
9121 // and isolate from other C++ specific checks.
9122 StructuralEquivalenceContext Ctx(
9123 D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls,
9124 StructuralEquivalenceKind::Default,
9125 false /*StrictTypeSpelling*/, true /*Complain*/,
9126 true /*ErrorOnTagTypeMismatch*/);
9127 return Ctx.IsEquivalent(D, Suggested);
9130 bool Sema::hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
9131 AcceptableKind Kind, bool OnlyNeedComplete) {
9132 // Easy case: if we don't have modules, all declarations are visible.
9133 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
9134 return true;
9136 // If this definition was instantiated from a template, map back to the
9137 // pattern from which it was instantiated.
9138 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
9139 // We're in the middle of defining it; this definition should be treated
9140 // as visible.
9141 return true;
9142 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9143 if (auto *Pattern = RD->getTemplateInstantiationPattern())
9144 RD = Pattern;
9145 D = RD->getDefinition();
9146 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
9147 if (auto *Pattern = ED->getTemplateInstantiationPattern())
9148 ED = Pattern;
9149 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) {
9150 // If the enum has a fixed underlying type, it may have been forward
9151 // declared. In -fms-compatibility, `enum Foo;` will also forward declare
9152 // the enum and assign it the underlying type of `int`. Since we're only
9153 // looking for a complete type (not a definition), any visible declaration
9154 // of it will do.
9155 *Suggested = nullptr;
9156 for (auto *Redecl : ED->redecls()) {
9157 if (isAcceptable(Redecl, Kind))
9158 return true;
9159 if (Redecl->isThisDeclarationADefinition() ||
9160 (Redecl->isCanonicalDecl() && !*Suggested))
9161 *Suggested = Redecl;
9164 return false;
9166 D = ED->getDefinition();
9167 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
9168 if (auto *Pattern = FD->getTemplateInstantiationPattern())
9169 FD = Pattern;
9170 D = FD->getDefinition();
9171 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
9172 if (auto *Pattern = VD->getTemplateInstantiationPattern())
9173 VD = Pattern;
9174 D = VD->getDefinition();
9177 assert(D && "missing definition for pattern of instantiated definition");
9179 *Suggested = D;
9181 auto DefinitionIsAcceptable = [&] {
9182 // The (primary) definition might be in a visible module.
9183 if (isAcceptable(D, Kind))
9184 return true;
9186 // A visible module might have a merged definition instead.
9187 if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D)
9188 : hasVisibleMergedDefinition(D)) {
9189 if (CodeSynthesisContexts.empty() &&
9190 !getLangOpts().ModulesLocalVisibility) {
9191 // Cache the fact that this definition is implicitly visible because
9192 // there is a visible merged definition.
9193 D->setVisibleDespiteOwningModule();
9195 return true;
9198 return false;
9201 if (DefinitionIsAcceptable())
9202 return true;
9204 // The external source may have additional definitions of this entity that are
9205 // visible, so complete the redeclaration chain now and ask again.
9206 if (auto *Source = Context.getExternalSource()) {
9207 Source->CompleteRedeclChain(D);
9208 return DefinitionIsAcceptable();
9211 return false;
9214 /// Determine whether there is any declaration of \p D that was ever a
9215 /// definition (perhaps before module merging) and is currently visible.
9216 /// \param D The definition of the entity.
9217 /// \param Suggested Filled in with the declaration that should be made visible
9218 /// in order to provide a definition of this entity.
9219 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9220 /// not defined. This only matters for enums with a fixed underlying
9221 /// type, since in all other cases, a type is complete if and only if it
9222 /// is defined.
9223 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
9224 bool OnlyNeedComplete) {
9225 return hasAcceptableDefinition(D, Suggested, Sema::AcceptableKind::Visible,
9226 OnlyNeedComplete);
9229 /// Determine whether there is any declaration of \p D that was ever a
9230 /// definition (perhaps before module merging) and is currently
9231 /// reachable.
9232 /// \param D The definition of the entity.
9233 /// \param Suggested Filled in with the declaration that should be made
9234 /// reachable
9235 /// in order to provide a definition of this entity.
9236 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9237 /// not defined. This only matters for enums with a fixed underlying
9238 /// type, since in all other cases, a type is complete if and only if it
9239 /// is defined.
9240 bool Sema::hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
9241 bool OnlyNeedComplete) {
9242 return hasAcceptableDefinition(D, Suggested, Sema::AcceptableKind::Reachable,
9243 OnlyNeedComplete);
9246 /// Locks in the inheritance model for the given class and all of its bases.
9247 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
9248 RD = RD->getMostRecentNonInjectedDecl();
9249 if (!RD->hasAttr<MSInheritanceAttr>()) {
9250 MSInheritanceModel IM;
9251 bool BestCase = false;
9252 switch (S.MSPointerToMemberRepresentationMethod) {
9253 case LangOptions::PPTMK_BestCase:
9254 BestCase = true;
9255 IM = RD->calculateInheritanceModel();
9256 break;
9257 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
9258 IM = MSInheritanceModel::Single;
9259 break;
9260 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
9261 IM = MSInheritanceModel::Multiple;
9262 break;
9263 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
9264 IM = MSInheritanceModel::Unspecified;
9265 break;
9268 SourceRange Loc = S.ImplicitMSInheritanceAttrLoc.isValid()
9269 ? S.ImplicitMSInheritanceAttrLoc
9270 : RD->getSourceRange();
9271 RD->addAttr(MSInheritanceAttr::CreateImplicit(
9272 S.getASTContext(), BestCase, Loc, MSInheritanceAttr::Spelling(IM)));
9273 S.Consumer.AssignInheritanceModel(RD);
9277 /// The implementation of RequireCompleteType
9278 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
9279 CompleteTypeKind Kind,
9280 TypeDiagnoser *Diagnoser) {
9281 // FIXME: Add this assertion to make sure we always get instantiation points.
9282 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
9283 // FIXME: Add this assertion to help us flush out problems with
9284 // checking for dependent types and type-dependent expressions.
9286 // assert(!T->isDependentType() &&
9287 // "Can't ask whether a dependent type is complete");
9289 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
9290 if (!MPTy->getClass()->isDependentType()) {
9291 if (getLangOpts().CompleteMemberPointers &&
9292 !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() &&
9293 RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), Kind,
9294 diag::err_memptr_incomplete))
9295 return true;
9297 // We lock in the inheritance model once somebody has asked us to ensure
9298 // that a pointer-to-member type is complete.
9299 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9300 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
9301 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
9306 NamedDecl *Def = nullptr;
9307 bool AcceptSizeless = (Kind == CompleteTypeKind::AcceptSizeless);
9308 bool Incomplete = (T->isIncompleteType(&Def) ||
9309 (!AcceptSizeless && T->isSizelessBuiltinType()));
9311 // Check that any necessary explicit specializations are visible. For an
9312 // enum, we just need the declaration, so don't check this.
9313 if (Def && !isa<EnumDecl>(Def))
9314 checkSpecializationReachability(Loc, Def);
9316 // If we have a complete type, we're done.
9317 if (!Incomplete) {
9318 NamedDecl *Suggested = nullptr;
9319 if (Def &&
9320 !hasReachableDefinition(Def, &Suggested, /*OnlyNeedComplete=*/true)) {
9321 // If the user is going to see an error here, recover by making the
9322 // definition visible.
9323 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
9324 if (Diagnoser && Suggested)
9325 diagnoseMissingImport(Loc, Suggested, MissingImportKind::Definition,
9326 /*Recover*/ TreatAsComplete);
9327 return !TreatAsComplete;
9328 } else if (Def && !TemplateInstCallbacks.empty()) {
9329 CodeSynthesisContext TempInst;
9330 TempInst.Kind = CodeSynthesisContext::Memoization;
9331 TempInst.Template = Def;
9332 TempInst.Entity = Def;
9333 TempInst.PointOfInstantiation = Loc;
9334 atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
9335 atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
9338 return false;
9341 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
9342 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
9344 // Give the external source a chance to provide a definition of the type.
9345 // This is kept separate from completing the redeclaration chain so that
9346 // external sources such as LLDB can avoid synthesizing a type definition
9347 // unless it's actually needed.
9348 if (Tag || IFace) {
9349 // Avoid diagnosing invalid decls as incomplete.
9350 if (Def->isInvalidDecl())
9351 return true;
9353 // Give the external AST source a chance to complete the type.
9354 if (auto *Source = Context.getExternalSource()) {
9355 if (Tag && Tag->hasExternalLexicalStorage())
9356 Source->CompleteType(Tag);
9357 if (IFace && IFace->hasExternalLexicalStorage())
9358 Source->CompleteType(IFace);
9359 // If the external source completed the type, go through the motions
9360 // again to ensure we're allowed to use the completed type.
9361 if (!T->isIncompleteType())
9362 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9366 // If we have a class template specialization or a class member of a
9367 // class template specialization, or an array with known size of such,
9368 // try to instantiate it.
9369 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
9370 bool Instantiated = false;
9371 bool Diagnosed = false;
9372 if (RD->isDependentContext()) {
9373 // Don't try to instantiate a dependent class (eg, a member template of
9374 // an instantiated class template specialization).
9375 // FIXME: Can this ever happen?
9376 } else if (auto *ClassTemplateSpec =
9377 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
9378 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
9379 runWithSufficientStackSpace(Loc, [&] {
9380 Diagnosed = InstantiateClassTemplateSpecialization(
9381 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
9382 /*Complain=*/Diagnoser);
9384 Instantiated = true;
9386 } else {
9387 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
9388 if (!RD->isBeingDefined() && Pattern) {
9389 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
9390 assert(MSI && "Missing member specialization information?");
9391 // This record was instantiated from a class within a template.
9392 if (MSI->getTemplateSpecializationKind() !=
9393 TSK_ExplicitSpecialization) {
9394 runWithSufficientStackSpace(Loc, [&] {
9395 Diagnosed = InstantiateClass(Loc, RD, Pattern,
9396 getTemplateInstantiationArgs(RD),
9397 TSK_ImplicitInstantiation,
9398 /*Complain=*/Diagnoser);
9400 Instantiated = true;
9405 if (Instantiated) {
9406 // Instantiate* might have already complained that the template is not
9407 // defined, if we asked it to.
9408 if (Diagnoser && Diagnosed)
9409 return true;
9410 // If we instantiated a definition, check that it's usable, even if
9411 // instantiation produced an error, so that repeated calls to this
9412 // function give consistent answers.
9413 if (!T->isIncompleteType())
9414 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9418 // FIXME: If we didn't instantiate a definition because of an explicit
9419 // specialization declaration, check that it's visible.
9421 if (!Diagnoser)
9422 return true;
9424 Diagnoser->diagnose(*this, Loc, T);
9426 // If the type was a forward declaration of a class/struct/union
9427 // type, produce a note.
9428 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid())
9429 Diag(Tag->getLocation(),
9430 Tag->isBeingDefined() ? diag::note_type_being_defined
9431 : diag::note_forward_declaration)
9432 << Context.getTagDeclType(Tag);
9434 // If the Objective-C class was a forward declaration, produce a note.
9435 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid())
9436 Diag(IFace->getLocation(), diag::note_forward_class);
9438 // If we have external information that we can use to suggest a fix,
9439 // produce a note.
9440 if (ExternalSource)
9441 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
9443 return true;
9446 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
9447 CompleteTypeKind Kind, unsigned DiagID) {
9448 BoundTypeDiagnoser<> Diagnoser(DiagID);
9449 return RequireCompleteType(Loc, T, Kind, Diagnoser);
9452 /// Get diagnostic %select index for tag kind for
9453 /// literal type diagnostic message.
9454 /// WARNING: Indexes apply to particular diagnostics only!
9456 /// \returns diagnostic %select index.
9457 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
9458 switch (Tag) {
9459 case TagTypeKind::Struct:
9460 return 0;
9461 case TagTypeKind::Interface:
9462 return 1;
9463 case TagTypeKind::Class:
9464 return 2;
9465 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
9469 /// Ensure that the type T is a literal type.
9471 /// This routine checks whether the type @p T is a literal type. If @p T is an
9472 /// incomplete type, an attempt is made to complete it. If @p T is a literal
9473 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
9474 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
9475 /// it the type @p T), along with notes explaining why the type is not a
9476 /// literal type, and returns true.
9478 /// @param Loc The location in the source that the non-literal type
9479 /// diagnostic should refer to.
9481 /// @param T The type that this routine is examining for literalness.
9483 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
9485 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
9486 /// @c false otherwise.
9487 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
9488 TypeDiagnoser &Diagnoser) {
9489 assert(!T->isDependentType() && "type should not be dependent");
9491 QualType ElemType = Context.getBaseElementType(T);
9492 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
9493 T->isLiteralType(Context))
9494 return false;
9496 Diagnoser.diagnose(*this, Loc, T);
9498 if (T->isVariableArrayType())
9499 return true;
9501 const RecordType *RT = ElemType->getAs<RecordType>();
9502 if (!RT)
9503 return true;
9505 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
9507 // A partially-defined class type can't be a literal type, because a literal
9508 // class type must have a trivial destructor (which can't be checked until
9509 // the class definition is complete).
9510 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
9511 return true;
9513 // [expr.prim.lambda]p3:
9514 // This class type is [not] a literal type.
9515 if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
9516 Diag(RD->getLocation(), diag::note_non_literal_lambda);
9517 return true;
9520 // If the class has virtual base classes, then it's not an aggregate, and
9521 // cannot have any constexpr constructors or a trivial default constructor,
9522 // so is non-literal. This is better to diagnose than the resulting absence
9523 // of constexpr constructors.
9524 if (RD->getNumVBases()) {
9525 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
9526 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
9527 for (const auto &I : RD->vbases())
9528 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
9529 << I.getSourceRange();
9530 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
9531 !RD->hasTrivialDefaultConstructor()) {
9532 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
9533 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
9534 for (const auto &I : RD->bases()) {
9535 if (!I.getType()->isLiteralType(Context)) {
9536 Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
9537 << RD << I.getType() << I.getSourceRange();
9538 return true;
9541 for (const auto *I : RD->fields()) {
9542 if (!I->getType()->isLiteralType(Context) ||
9543 I->getType().isVolatileQualified()) {
9544 Diag(I->getLocation(), diag::note_non_literal_field)
9545 << RD << I << I->getType()
9546 << I->getType().isVolatileQualified();
9547 return true;
9550 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor()
9551 : !RD->hasTrivialDestructor()) {
9552 // All fields and bases are of literal types, so have trivial or constexpr
9553 // destructors. If this class's destructor is non-trivial / non-constexpr,
9554 // it must be user-declared.
9555 CXXDestructorDecl *Dtor = RD->getDestructor();
9556 assert(Dtor && "class has literal fields and bases but no dtor?");
9557 if (!Dtor)
9558 return true;
9560 if (getLangOpts().CPlusPlus20) {
9561 Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor)
9562 << RD;
9563 } else {
9564 Diag(Dtor->getLocation(), Dtor->isUserProvided()
9565 ? diag::note_non_literal_user_provided_dtor
9566 : diag::note_non_literal_nontrivial_dtor)
9567 << RD;
9568 if (!Dtor->isUserProvided())
9569 SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI,
9570 /*Diagnose*/ true);
9574 return true;
9577 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
9578 BoundTypeDiagnoser<> Diagnoser(DiagID);
9579 return RequireLiteralType(Loc, T, Diagnoser);
9582 /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified
9583 /// by the nested-name-specifier contained in SS, and that is (re)declared by
9584 /// OwnedTagDecl, which is nullptr if this is not a (re)declaration.
9585 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
9586 const CXXScopeSpec &SS, QualType T,
9587 TagDecl *OwnedTagDecl) {
9588 if (T.isNull())
9589 return T;
9590 return Context.getElaboratedType(
9591 Keyword, SS.isValid() ? SS.getScopeRep() : nullptr, T, OwnedTagDecl);
9594 QualType Sema::BuildTypeofExprType(Expr *E, TypeOfKind Kind) {
9595 assert(!E->hasPlaceholderType() && "unexpected placeholder");
9597 if (!getLangOpts().CPlusPlus && E->refersToBitField())
9598 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
9599 << (Kind == TypeOfKind::Unqualified ? 3 : 2);
9601 if (!E->isTypeDependent()) {
9602 QualType T = E->getType();
9603 if (const TagType *TT = T->getAs<TagType>())
9604 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
9606 return Context.getTypeOfExprType(E, Kind);
9609 /// getDecltypeForExpr - Given an expr, will return the decltype for
9610 /// that expression, according to the rules in C++11
9611 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
9612 QualType Sema::getDecltypeForExpr(Expr *E) {
9613 if (E->isTypeDependent())
9614 return Context.DependentTy;
9616 Expr *IDExpr = E;
9617 if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E))
9618 IDExpr = ImplCastExpr->getSubExpr();
9620 // C++11 [dcl.type.simple]p4:
9621 // The type denoted by decltype(e) is defined as follows:
9623 // C++20:
9624 // - if E is an unparenthesized id-expression naming a non-type
9625 // template-parameter (13.2), decltype(E) is the type of the
9626 // template-parameter after performing any necessary type deduction
9627 // Note that this does not pick up the implicit 'const' for a template
9628 // parameter object. This rule makes no difference before C++20 so we apply
9629 // it unconditionally.
9630 if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr))
9631 return SNTTPE->getParameterType(Context);
9633 // - if e is an unparenthesized id-expression or an unparenthesized class
9634 // member access (5.2.5), decltype(e) is the type of the entity named
9635 // by e. If there is no such entity, or if e names a set of overloaded
9636 // functions, the program is ill-formed;
9638 // We apply the same rules for Objective-C ivar and property references.
9639 if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) {
9640 const ValueDecl *VD = DRE->getDecl();
9641 QualType T = VD->getType();
9642 return isa<TemplateParamObjectDecl>(VD) ? T.getUnqualifiedType() : T;
9644 if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) {
9645 if (const auto *VD = ME->getMemberDecl())
9646 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
9647 return VD->getType();
9648 } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) {
9649 return IR->getDecl()->getType();
9650 } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) {
9651 if (PR->isExplicitProperty())
9652 return PR->getExplicitProperty()->getType();
9653 } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) {
9654 return PE->getType();
9657 // C++11 [expr.lambda.prim]p18:
9658 // Every occurrence of decltype((x)) where x is a possibly
9659 // parenthesized id-expression that names an entity of automatic
9660 // storage duration is treated as if x were transformed into an
9661 // access to a corresponding data member of the closure type that
9662 // would have been declared if x were an odr-use of the denoted
9663 // entity.
9664 if (getCurLambda() && isa<ParenExpr>(IDExpr)) {
9665 if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) {
9666 if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
9667 QualType T = getCapturedDeclRefType(Var, DRE->getLocation());
9668 if (!T.isNull())
9669 return Context.getLValueReferenceType(T);
9674 return Context.getReferenceQualifiedType(E);
9677 QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) {
9678 assert(!E->hasPlaceholderType() && "unexpected placeholder");
9680 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
9681 !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) {
9682 // The expression operand for decltype is in an unevaluated expression
9683 // context, so side effects could result in unintended consequences.
9684 // Exclude instantiation-dependent expressions, because 'decltype' is often
9685 // used to build SFINAE gadgets.
9686 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
9688 return Context.getDecltypeType(E, getDecltypeForExpr(E));
9691 static QualType GetEnumUnderlyingType(Sema &S, QualType BaseType,
9692 SourceLocation Loc) {
9693 assert(BaseType->isEnumeralType());
9694 EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl();
9695 assert(ED && "EnumType has no EnumDecl");
9697 S.DiagnoseUseOfDecl(ED, Loc);
9699 QualType Underlying = ED->getIntegerType();
9700 assert(!Underlying.isNull());
9702 return Underlying;
9705 QualType Sema::BuiltinEnumUnderlyingType(QualType BaseType,
9706 SourceLocation Loc) {
9707 if (!BaseType->isEnumeralType()) {
9708 Diag(Loc, diag::err_only_enums_have_underlying_types);
9709 return QualType();
9712 // The enum could be incomplete if we're parsing its definition or
9713 // recovering from an error.
9714 NamedDecl *FwdDecl = nullptr;
9715 if (BaseType->isIncompleteType(&FwdDecl)) {
9716 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
9717 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
9718 return QualType();
9721 return GetEnumUnderlyingType(*this, BaseType, Loc);
9724 QualType Sema::BuiltinAddPointer(QualType BaseType, SourceLocation Loc) {
9725 QualType Pointer = BaseType.isReferenceable() || BaseType->isVoidType()
9726 ? BuildPointerType(BaseType.getNonReferenceType(), Loc,
9727 DeclarationName())
9728 : BaseType;
9730 return Pointer.isNull() ? QualType() : Pointer;
9733 QualType Sema::BuiltinRemovePointer(QualType BaseType, SourceLocation Loc) {
9734 // We don't want block pointers or ObjectiveC's id type.
9735 if (!BaseType->isAnyPointerType() || BaseType->isObjCIdType())
9736 return BaseType;
9738 return BaseType->getPointeeType();
9741 QualType Sema::BuiltinDecay(QualType BaseType, SourceLocation Loc) {
9742 QualType Underlying = BaseType.getNonReferenceType();
9743 if (Underlying->isArrayType())
9744 return Context.getDecayedType(Underlying);
9746 if (Underlying->isFunctionType())
9747 return BuiltinAddPointer(BaseType, Loc);
9749 SplitQualType Split = Underlying.getSplitUnqualifiedType();
9750 // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is
9751 // in the same group of qualifiers as 'const' and 'volatile', we're extending
9752 // '__decay(T)' so that it removes all qualifiers.
9753 Split.Quals.removeCVRQualifiers();
9754 return Context.getQualifiedType(Split);
9757 QualType Sema::BuiltinAddReference(QualType BaseType, UTTKind UKind,
9758 SourceLocation Loc) {
9759 assert(LangOpts.CPlusPlus);
9760 QualType Reference =
9761 BaseType.isReferenceable()
9762 ? BuildReferenceType(BaseType,
9763 UKind == UnaryTransformType::AddLvalueReference,
9764 Loc, DeclarationName())
9765 : BaseType;
9766 return Reference.isNull() ? QualType() : Reference;
9769 QualType Sema::BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
9770 SourceLocation Loc) {
9771 if (UKind == UnaryTransformType::RemoveAllExtents)
9772 return Context.getBaseElementType(BaseType);
9774 if (const auto *AT = Context.getAsArrayType(BaseType))
9775 return AT->getElementType();
9777 return BaseType;
9780 QualType Sema::BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
9781 SourceLocation Loc) {
9782 assert(LangOpts.CPlusPlus);
9783 QualType T = BaseType.getNonReferenceType();
9784 if (UKind == UTTKind::RemoveCVRef &&
9785 (T.isConstQualified() || T.isVolatileQualified())) {
9786 Qualifiers Quals;
9787 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
9788 Quals.removeConst();
9789 Quals.removeVolatile();
9790 T = Context.getQualifiedType(Unqual, Quals);
9792 return T;
9795 QualType Sema::BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
9796 SourceLocation Loc) {
9797 if ((BaseType->isReferenceType() && UKind != UTTKind::RemoveRestrict) ||
9798 BaseType->isFunctionType())
9799 return BaseType;
9801 Qualifiers Quals;
9802 QualType Unqual = Context.getUnqualifiedArrayType(BaseType, Quals);
9804 if (UKind == UTTKind::RemoveConst || UKind == UTTKind::RemoveCV)
9805 Quals.removeConst();
9806 if (UKind == UTTKind::RemoveVolatile || UKind == UTTKind::RemoveCV)
9807 Quals.removeVolatile();
9808 if (UKind == UTTKind::RemoveRestrict)
9809 Quals.removeRestrict();
9811 return Context.getQualifiedType(Unqual, Quals);
9814 static QualType ChangeIntegralSignedness(Sema &S, QualType BaseType,
9815 bool IsMakeSigned,
9816 SourceLocation Loc) {
9817 if (BaseType->isEnumeralType()) {
9818 QualType Underlying = GetEnumUnderlyingType(S, BaseType, Loc);
9819 if (auto *BitInt = dyn_cast<BitIntType>(Underlying)) {
9820 unsigned int Bits = BitInt->getNumBits();
9821 if (Bits > 1)
9822 return S.Context.getBitIntType(!IsMakeSigned, Bits);
9824 S.Diag(Loc, diag::err_make_signed_integral_only)
9825 << IsMakeSigned << /*_BitInt(1)*/ true << BaseType << 1 << Underlying;
9826 return QualType();
9828 if (Underlying->isBooleanType()) {
9829 S.Diag(Loc, diag::err_make_signed_integral_only)
9830 << IsMakeSigned << /*_BitInt(1)*/ false << BaseType << 1
9831 << Underlying;
9832 return QualType();
9836 bool Int128Unsupported = !S.Context.getTargetInfo().hasInt128Type();
9837 std::array<CanQualType *, 6> AllSignedIntegers = {
9838 &S.Context.SignedCharTy, &S.Context.ShortTy, &S.Context.IntTy,
9839 &S.Context.LongTy, &S.Context.LongLongTy, &S.Context.Int128Ty};
9840 ArrayRef<CanQualType *> AvailableSignedIntegers(
9841 AllSignedIntegers.data(), AllSignedIntegers.size() - Int128Unsupported);
9842 std::array<CanQualType *, 6> AllUnsignedIntegers = {
9843 &S.Context.UnsignedCharTy, &S.Context.UnsignedShortTy,
9844 &S.Context.UnsignedIntTy, &S.Context.UnsignedLongTy,
9845 &S.Context.UnsignedLongLongTy, &S.Context.UnsignedInt128Ty};
9846 ArrayRef<CanQualType *> AvailableUnsignedIntegers(AllUnsignedIntegers.data(),
9847 AllUnsignedIntegers.size() -
9848 Int128Unsupported);
9849 ArrayRef<CanQualType *> *Consider =
9850 IsMakeSigned ? &AvailableSignedIntegers : &AvailableUnsignedIntegers;
9852 uint64_t BaseSize = S.Context.getTypeSize(BaseType);
9853 auto *Result =
9854 llvm::find_if(*Consider, [&S, BaseSize](const CanQual<Type> *T) {
9855 return BaseSize == S.Context.getTypeSize(T->getTypePtr());
9858 assert(Result != Consider->end());
9859 return QualType((*Result)->getTypePtr(), 0);
9862 QualType Sema::BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
9863 SourceLocation Loc) {
9864 bool IsMakeSigned = UKind == UnaryTransformType::MakeSigned;
9865 if ((!BaseType->isIntegerType() && !BaseType->isEnumeralType()) ||
9866 BaseType->isBooleanType() ||
9867 (BaseType->isBitIntType() &&
9868 BaseType->getAs<BitIntType>()->getNumBits() < 2)) {
9869 Diag(Loc, diag::err_make_signed_integral_only)
9870 << IsMakeSigned << BaseType->isBitIntType() << BaseType << 0;
9871 return QualType();
9874 bool IsNonIntIntegral =
9875 BaseType->isChar16Type() || BaseType->isChar32Type() ||
9876 BaseType->isWideCharType() || BaseType->isEnumeralType();
9878 QualType Underlying =
9879 IsNonIntIntegral
9880 ? ChangeIntegralSignedness(*this, BaseType, IsMakeSigned, Loc)
9881 : IsMakeSigned ? Context.getCorrespondingSignedType(BaseType)
9882 : Context.getCorrespondingUnsignedType(BaseType);
9883 if (Underlying.isNull())
9884 return Underlying;
9885 return Context.getQualifiedType(Underlying, BaseType.getQualifiers());
9888 QualType Sema::BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
9889 SourceLocation Loc) {
9890 if (BaseType->isDependentType())
9891 return Context.getUnaryTransformType(BaseType, BaseType, UKind);
9892 QualType Result;
9893 switch (UKind) {
9894 case UnaryTransformType::EnumUnderlyingType: {
9895 Result = BuiltinEnumUnderlyingType(BaseType, Loc);
9896 break;
9898 case UnaryTransformType::AddPointer: {
9899 Result = BuiltinAddPointer(BaseType, Loc);
9900 break;
9902 case UnaryTransformType::RemovePointer: {
9903 Result = BuiltinRemovePointer(BaseType, Loc);
9904 break;
9906 case UnaryTransformType::Decay: {
9907 Result = BuiltinDecay(BaseType, Loc);
9908 break;
9910 case UnaryTransformType::AddLvalueReference:
9911 case UnaryTransformType::AddRvalueReference: {
9912 Result = BuiltinAddReference(BaseType, UKind, Loc);
9913 break;
9915 case UnaryTransformType::RemoveAllExtents:
9916 case UnaryTransformType::RemoveExtent: {
9917 Result = BuiltinRemoveExtent(BaseType, UKind, Loc);
9918 break;
9920 case UnaryTransformType::RemoveCVRef:
9921 case UnaryTransformType::RemoveReference: {
9922 Result = BuiltinRemoveReference(BaseType, UKind, Loc);
9923 break;
9925 case UnaryTransformType::RemoveConst:
9926 case UnaryTransformType::RemoveCV:
9927 case UnaryTransformType::RemoveRestrict:
9928 case UnaryTransformType::RemoveVolatile: {
9929 Result = BuiltinChangeCVRQualifiers(BaseType, UKind, Loc);
9930 break;
9932 case UnaryTransformType::MakeSigned:
9933 case UnaryTransformType::MakeUnsigned: {
9934 Result = BuiltinChangeSignedness(BaseType, UKind, Loc);
9935 break;
9939 return !Result.isNull()
9940 ? Context.getUnaryTransformType(BaseType, Result, UKind)
9941 : Result;
9944 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
9945 if (!isDependentOrGNUAutoType(T)) {
9946 // FIXME: It isn't entirely clear whether incomplete atomic types
9947 // are allowed or not; for simplicity, ban them for the moment.
9948 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
9949 return QualType();
9951 int DisallowedKind = -1;
9952 if (T->isArrayType())
9953 DisallowedKind = 1;
9954 else if (T->isFunctionType())
9955 DisallowedKind = 2;
9956 else if (T->isReferenceType())
9957 DisallowedKind = 3;
9958 else if (T->isAtomicType())
9959 DisallowedKind = 4;
9960 else if (T.hasQualifiers())
9961 DisallowedKind = 5;
9962 else if (T->isSizelessType())
9963 DisallowedKind = 6;
9964 else if (!T.isTriviallyCopyableType(Context) && getLangOpts().CPlusPlus)
9965 // Some other non-trivially-copyable type (probably a C++ class)
9966 DisallowedKind = 7;
9967 else if (T->isBitIntType())
9968 DisallowedKind = 8;
9969 else if (getLangOpts().C23 && T->isUndeducedAutoType())
9970 // _Atomic auto is prohibited in C23
9971 DisallowedKind = 9;
9973 if (DisallowedKind != -1) {
9974 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
9975 return QualType();
9978 // FIXME: Do we need any handling for ARC here?
9981 // Build the pointer type.
9982 return Context.getAtomicType(T);