clang 20.0.0git
SemaType.cpp
Go to the documentation of this file.
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.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclObjC.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprObjC.h"
25#include "clang/AST/Type.h"
26#include "clang/AST/TypeLoc.h"
33#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Lookup.h"
39#include "clang/Sema/SemaCUDA.h"
40#include "clang/Sema/SemaHLSL.h"
41#include "clang/Sema/SemaObjC.h"
43#include "clang/Sema/Template.h"
45#include "llvm/ADT/ArrayRef.h"
46#include "llvm/ADT/STLForwardCompat.h"
47#include "llvm/ADT/StringExtras.h"
48#include "llvm/IR/DerivedTypes.h"
49#include "llvm/Support/ErrorHandling.h"
50#include <bitset>
51#include <optional>
52
53using namespace clang;
54
59};
60
61/// isOmittedBlockReturnType - Return true if this declarator is missing a
62/// return type because this is a omitted return type on a block literal.
64 if (D.getContext() != DeclaratorContext::BlockLiteral ||
65 D.getDeclSpec().hasTypeSpecifier())
66 return false;
67
68 if (D.getNumTypeObjects() == 0)
69 return true; // ^{ ... }
70
71 if (D.getNumTypeObjects() == 1 &&
72 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
73 return true; // ^(int X, float Y) { ... }
74
75 return false;
76}
77
78/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
79/// doesn't apply to the given type.
80static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
81 QualType type) {
82 TypeDiagSelector WhichType;
83 bool useExpansionLoc = true;
84 switch (attr.getKind()) {
85 case ParsedAttr::AT_ObjCGC:
86 WhichType = TDS_Pointer;
87 break;
88 case ParsedAttr::AT_ObjCOwnership:
89 WhichType = TDS_ObjCObjOrBlock;
90 break;
91 default:
92 // Assume everything else was a function attribute.
93 WhichType = TDS_Function;
94 useExpansionLoc = false;
95 break;
96 }
97
98 SourceLocation loc = attr.getLoc();
99 StringRef name = attr.getAttrName()->getName();
100
101 // The GC attributes are usually written with macros; special-case them.
102 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
103 : nullptr;
104 if (useExpansionLoc && loc.isMacroID() && II) {
105 if (II->isStr("strong")) {
106 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
107 } else if (II->isStr("weak")) {
108 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
109 }
110 }
111
112 S.Diag(loc, attr.isRegularKeywordAttribute()
113 ? diag::err_type_attribute_wrong_type
114 : diag::warn_type_attribute_wrong_type)
115 << name << WhichType << type;
116}
117
118// objc_gc applies to Objective-C pointers or, otherwise, to the
119// smallest available pointer type (i.e. 'void*' in 'void**').
120#define OBJC_POINTER_TYPE_ATTRS_CASELIST \
121 case ParsedAttr::AT_ObjCGC: \
122 case ParsedAttr::AT_ObjCOwnership
123
124// Calling convention attributes.
125#define CALLING_CONV_ATTRS_CASELIST \
126 case ParsedAttr::AT_CDecl: \
127 case ParsedAttr::AT_FastCall: \
128 case ParsedAttr::AT_StdCall: \
129 case ParsedAttr::AT_ThisCall: \
130 case ParsedAttr::AT_RegCall: \
131 case ParsedAttr::AT_Pascal: \
132 case ParsedAttr::AT_SwiftCall: \
133 case ParsedAttr::AT_SwiftAsyncCall: \
134 case ParsedAttr::AT_VectorCall: \
135 case ParsedAttr::AT_AArch64VectorPcs: \
136 case ParsedAttr::AT_AArch64SVEPcs: \
137 case ParsedAttr::AT_AMDGPUKernelCall: \
138 case ParsedAttr::AT_MSABI: \
139 case ParsedAttr::AT_SysVABI: \
140 case ParsedAttr::AT_Pcs: \
141 case ParsedAttr::AT_IntelOclBicc: \
142 case ParsedAttr::AT_PreserveMost: \
143 case ParsedAttr::AT_PreserveAll: \
144 case ParsedAttr::AT_M68kRTD: \
145 case ParsedAttr::AT_PreserveNone: \
146 case ParsedAttr::AT_RISCVVectorCC
147
148// Function type attributes.
149#define FUNCTION_TYPE_ATTRS_CASELIST \
150 case ParsedAttr::AT_NSReturnsRetained: \
151 case ParsedAttr::AT_NoReturn: \
152 case ParsedAttr::AT_NonBlocking: \
153 case ParsedAttr::AT_NonAllocating: \
154 case ParsedAttr::AT_Blocking: \
155 case ParsedAttr::AT_Allocating: \
156 case ParsedAttr::AT_Regparm: \
157 case ParsedAttr::AT_CmseNSCall: \
158 case ParsedAttr::AT_ArmStreaming: \
159 case ParsedAttr::AT_ArmStreamingCompatible: \
160 case ParsedAttr::AT_ArmPreserves: \
161 case ParsedAttr::AT_ArmIn: \
162 case ParsedAttr::AT_ArmOut: \
163 case ParsedAttr::AT_ArmInOut: \
164 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
165 case ParsedAttr::AT_AnyX86NoCfCheck: \
166 CALLING_CONV_ATTRS_CASELIST
167
168// Microsoft-specific type qualifiers.
169#define MS_TYPE_ATTRS_CASELIST \
170 case ParsedAttr::AT_Ptr32: \
171 case ParsedAttr::AT_Ptr64: \
172 case ParsedAttr::AT_SPtr: \
173 case ParsedAttr::AT_UPtr
174
175// Nullability qualifiers.
176#define NULLABILITY_TYPE_ATTRS_CASELIST \
177 case ParsedAttr::AT_TypeNonNull: \
178 case ParsedAttr::AT_TypeNullable: \
179 case ParsedAttr::AT_TypeNullableResult: \
180 case ParsedAttr::AT_TypeNullUnspecified
181
182namespace {
183 /// An object which stores processing state for the entire
184 /// GetTypeForDeclarator process.
185 class TypeProcessingState {
186 Sema &sema;
187
188 /// The declarator being processed.
189 Declarator &declarator;
190
191 /// The index of the declarator chunk we're currently processing.
192 /// May be the total number of valid chunks, indicating the
193 /// DeclSpec.
194 unsigned chunkIndex;
195
196 /// The original set of attributes on the DeclSpec.
198
199 /// A list of attributes to diagnose the uselessness of when the
200 /// processing is complete.
201 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
202
203 /// Attributes corresponding to AttributedTypeLocs that we have not yet
204 /// populated.
205 // FIXME: The two-phase mechanism by which we construct Types and fill
206 // their TypeLocs makes it hard to correctly assign these. We keep the
207 // attributes in creation order as an attempt to make them line up
208 // properly.
209 using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
210 SmallVector<TypeAttrPair, 8> AttrsForTypes;
211 bool AttrsForTypesSorted = true;
212
213 /// MacroQualifiedTypes mapping to macro expansion locations that will be
214 /// stored in a MacroQualifiedTypeLoc.
215 llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
216
217 /// Flag to indicate we parsed a noderef attribute. This is used for
218 /// validating that noderef was used on a pointer or array.
219 bool parsedNoDeref;
220
221 // Flag to indicate that we already parsed a HLSL parameter modifier
222 // attribute. This prevents double-mutating the type.
223 bool ParsedHLSLParamMod;
224
225 public:
226 TypeProcessingState(Sema &sema, Declarator &declarator)
227 : sema(sema), declarator(declarator),
228 chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false),
229 ParsedHLSLParamMod(false) {}
230
231 Sema &getSema() const {
232 return sema;
233 }
234
235 Declarator &getDeclarator() const {
236 return declarator;
237 }
238
239 bool isProcessingDeclSpec() const {
240 return chunkIndex == declarator.getNumTypeObjects();
241 }
242
243 unsigned getCurrentChunkIndex() const {
244 return chunkIndex;
245 }
246
247 void setCurrentChunkIndex(unsigned idx) {
248 assert(idx <= declarator.getNumTypeObjects());
249 chunkIndex = idx;
250 }
251
252 ParsedAttributesView &getCurrentAttributes() const {
253 if (isProcessingDeclSpec())
254 return getMutableDeclSpec().getAttributes();
255 return declarator.getTypeObject(chunkIndex).getAttrs();
256 }
257
258 /// Save the current set of attributes on the DeclSpec.
259 void saveDeclSpecAttrs() {
260 // Don't try to save them multiple times.
261 if (!savedAttrs.empty())
262 return;
263
264 DeclSpec &spec = getMutableDeclSpec();
265 llvm::append_range(savedAttrs,
266 llvm::make_pointer_range(spec.getAttributes()));
267 }
268
269 /// Record that we had nowhere to put the given type attribute.
270 /// We will diagnose such attributes later.
271 void addIgnoredTypeAttr(ParsedAttr &attr) {
272 ignoredTypeAttrs.push_back(&attr);
273 }
274
275 /// Diagnose all the ignored type attributes, given that the
276 /// declarator worked out to the given type.
277 void diagnoseIgnoredTypeAttrs(QualType type) const {
278 for (auto *Attr : ignoredTypeAttrs)
279 diagnoseBadTypeAttribute(getSema(), *Attr, type);
280 }
281
282 /// Get an attributed type for the given attribute, and remember the Attr
283 /// object so that we can attach it to the AttributedTypeLoc.
284 QualType getAttributedType(Attr *A, QualType ModifiedType,
285 QualType EquivType) {
286 QualType T =
287 sema.Context.getAttributedType(A, ModifiedType, EquivType);
288 AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
289 AttrsForTypesSorted = false;
290 return T;
291 }
292
293 /// Get a BTFTagAttributed type for the btf_type_tag attribute.
294 QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
295 QualType WrappedType) {
296 return sema.Context.getBTFTagAttributedType(BTFAttr, WrappedType);
297 }
298
299 /// Completely replace the \c auto in \p TypeWithAuto by
300 /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
301 /// necessary.
302 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
303 QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
304 if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
305 // Attributed type still should be an attributed type after replacement.
306 auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
307 for (TypeAttrPair &A : AttrsForTypes) {
308 if (A.first == AttrTy)
309 A.first = NewAttrTy;
310 }
311 AttrsForTypesSorted = false;
312 }
313 return T;
314 }
315
316 /// Extract and remove the Attr* for a given attributed type.
317 const Attr *takeAttrForAttributedType(const AttributedType *AT) {
318 if (!AttrsForTypesSorted) {
319 llvm::stable_sort(AttrsForTypes, llvm::less_first());
320 AttrsForTypesSorted = true;
321 }
322
323 // FIXME: This is quadratic if we have lots of reuses of the same
324 // attributed type.
325 for (auto It = std::partition_point(
326 AttrsForTypes.begin(), AttrsForTypes.end(),
327 [=](const TypeAttrPair &A) { return A.first < AT; });
328 It != AttrsForTypes.end() && It->first == AT; ++It) {
329 if (It->second) {
330 const Attr *Result = It->second;
331 It->second = nullptr;
332 return Result;
333 }
334 }
335
336 llvm_unreachable("no Attr* for AttributedType*");
337 }
338
340 getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
341 auto FoundLoc = LocsForMacros.find(MQT);
342 assert(FoundLoc != LocsForMacros.end() &&
343 "Unable to find macro expansion location for MacroQualifedType");
344 return FoundLoc->second;
345 }
346
347 void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
349 LocsForMacros[MQT] = Loc;
350 }
351
352 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
353
354 bool didParseNoDeref() const { return parsedNoDeref; }
355
356 void setParsedHLSLParamMod(bool Parsed) { ParsedHLSLParamMod = Parsed; }
357
358 bool didParseHLSLParamMod() const { return ParsedHLSLParamMod; }
359
360 ~TypeProcessingState() {
361 if (savedAttrs.empty())
362 return;
363
364 getMutableDeclSpec().getAttributes().clearListOnly();
365 for (ParsedAttr *AL : savedAttrs)
366 getMutableDeclSpec().getAttributes().addAtEnd(AL);
367 }
368
369 private:
370 DeclSpec &getMutableDeclSpec() const {
371 return const_cast<DeclSpec&>(declarator.getDeclSpec());
372 }
373 };
374} // end anonymous namespace
375
377 ParsedAttributesView &fromList,
378 ParsedAttributesView &toList) {
379 fromList.remove(&attr);
380 toList.addAtEnd(&attr);
381}
382
383/// The location of a type attribute.
385 /// The attribute is in the decl-specifier-seq.
387 /// The attribute is part of a DeclaratorChunk.
389 /// The attribute is immediately after the declaration's name.
392
393static void
394processTypeAttrs(TypeProcessingState &state, QualType &type,
395 TypeAttrLocation TAL, const ParsedAttributesView &attrs,
396 CUDAFunctionTarget CFT = CUDAFunctionTarget::HostDevice);
397
398static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
400
401static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
402 ParsedAttr &attr, QualType &type);
403
404static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
405 QualType &type);
406
407static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
408 ParsedAttr &attr, QualType &type);
409
410static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
411 ParsedAttr &attr, QualType &type) {
412 if (attr.getKind() == ParsedAttr::AT_ObjCGC)
413 return handleObjCGCTypeAttr(state, attr, type);
414 assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
415 return handleObjCOwnershipTypeAttr(state, attr, type);
416}
417
418/// Given the index of a declarator chunk, check whether that chunk
419/// directly specifies the return type of a function and, if so, find
420/// an appropriate place for it.
421///
422/// \param i - a notional index which the search will start
423/// immediately inside
424///
425/// \param onlyBlockPointers Whether we should only look into block
426/// pointer types (vs. all pointer types).
428 unsigned i,
429 bool onlyBlockPointers) {
430 assert(i <= declarator.getNumTypeObjects());
431
432 DeclaratorChunk *result = nullptr;
433
434 // First, look inwards past parens for a function declarator.
435 for (; i != 0; --i) {
436 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
437 switch (fnChunk.Kind) {
439 continue;
440
441 // If we find anything except a function, bail out.
448 return result;
449
450 // If we do find a function declarator, scan inwards from that,
451 // looking for a (block-)pointer declarator.
453 for (--i; i != 0; --i) {
454 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
455 switch (ptrChunk.Kind) {
461 continue;
462
465 if (onlyBlockPointers)
466 continue;
467
468 [[fallthrough]];
469
471 result = &ptrChunk;
472 goto continue_outer;
473 }
474 llvm_unreachable("bad declarator chunk kind");
475 }
476
477 // If we run out of declarators doing that, we're done.
478 return result;
479 }
480 llvm_unreachable("bad declarator chunk kind");
481
482 // Okay, reconsider from our new point.
483 continue_outer: ;
484 }
485
486 // Ran out of chunks, bail out.
487 return result;
488}
489
490/// Given that an objc_gc attribute was written somewhere on a
491/// declaration *other* than on the declarator itself (for which, use
492/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
493/// didn't apply in whatever position it was written in, try to move
494/// it to a more appropriate position.
495static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
496 ParsedAttr &attr, QualType type) {
497 Declarator &declarator = state.getDeclarator();
498
499 // Move it to the outermost normal or block pointer declarator.
500 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
501 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
502 switch (chunk.Kind) {
505 // But don't move an ARC ownership attribute to the return type
506 // of a block.
507 DeclaratorChunk *destChunk = nullptr;
508 if (state.isProcessingDeclSpec() &&
509 attr.getKind() == ParsedAttr::AT_ObjCOwnership)
510 destChunk = maybeMovePastReturnType(declarator, i - 1,
511 /*onlyBlockPointers=*/true);
512 if (!destChunk) destChunk = &chunk;
513
514 moveAttrFromListToList(attr, state.getCurrentAttributes(),
515 destChunk->getAttrs());
516 return;
517 }
518
521 continue;
522
523 // We may be starting at the return type of a block.
525 if (state.isProcessingDeclSpec() &&
526 attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
528 declarator, i,
529 /*onlyBlockPointers=*/true)) {
530 moveAttrFromListToList(attr, state.getCurrentAttributes(),
531 dest->getAttrs());
532 return;
533 }
534 }
535 goto error;
536
537 // Don't walk through these.
541 goto error;
542 }
543 }
544 error:
545
546 diagnoseBadTypeAttribute(state.getSema(), attr, type);
547}
548
549/// Distribute an objc_gc type attribute that was written on the
550/// declarator.
552 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
553 Declarator &declarator = state.getDeclarator();
554
555 // objc_gc goes on the innermost pointer to something that's not a
556 // pointer.
557 unsigned innermost = -1U;
558 bool considerDeclSpec = true;
559 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
560 DeclaratorChunk &chunk = declarator.getTypeObject(i);
561 switch (chunk.Kind) {
564 innermost = i;
565 continue;
566
572 continue;
573
575 considerDeclSpec = false;
576 goto done;
577 }
578 }
579 done:
580
581 // That might actually be the decl spec if we weren't blocked by
582 // anything in the declarator.
583 if (considerDeclSpec) {
584 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
585 // Splice the attribute into the decl spec. Prevents the
586 // attribute from being applied multiple times and gives
587 // the source-location-filler something to work with.
588 state.saveDeclSpecAttrs();
590 declarator.getAttributes(), &attr);
591 return;
592 }
593 }
594
595 // Otherwise, if we found an appropriate chunk, splice the attribute
596 // into it.
597 if (innermost != -1U) {
599 declarator.getTypeObject(innermost).getAttrs());
600 return;
601 }
602
603 // Otherwise, diagnose when we're done building the type.
604 declarator.getAttributes().remove(&attr);
605 state.addIgnoredTypeAttr(attr);
606}
607
608/// A function type attribute was written somewhere in a declaration
609/// *other* than on the declarator itself or in the decl spec. Given
610/// that it didn't apply in whatever position it was written in, try
611/// to move it to a more appropriate position.
612static void distributeFunctionTypeAttr(TypeProcessingState &state,
613 ParsedAttr &attr, QualType type) {
614 Declarator &declarator = state.getDeclarator();
615
616 // Try to push the attribute from the return type of a function to
617 // the function itself.
618 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
619 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
620 switch (chunk.Kind) {
622 moveAttrFromListToList(attr, state.getCurrentAttributes(),
623 chunk.getAttrs());
624 return;
625
633 continue;
634 }
635 }
636
637 diagnoseBadTypeAttribute(state.getSema(), attr, type);
638}
639
640/// Try to distribute a function type attribute to the innermost
641/// function chunk or type. Returns true if the attribute was
642/// distributed, false if no location was found.
644 TypeProcessingState &state, ParsedAttr &attr,
645 ParsedAttributesView &attrList, QualType &declSpecType,
646 CUDAFunctionTarget CFT) {
647 Declarator &declarator = state.getDeclarator();
648
649 // Put it on the innermost function chunk, if there is one.
650 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
651 DeclaratorChunk &chunk = declarator.getTypeObject(i);
652 if (chunk.Kind != DeclaratorChunk::Function) continue;
653
654 moveAttrFromListToList(attr, attrList, chunk.getAttrs());
655 return true;
656 }
657
658 return handleFunctionTypeAttr(state, attr, declSpecType, CFT);
659}
660
661/// A function type attribute was written in the decl spec. Try to
662/// apply it somewhere.
663static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
664 ParsedAttr &attr,
665 QualType &declSpecType,
666 CUDAFunctionTarget CFT) {
667 state.saveDeclSpecAttrs();
668
669 // Try to distribute to the innermost.
671 state, attr, state.getCurrentAttributes(), declSpecType, CFT))
672 return;
673
674 // If that failed, diagnose the bad attribute when the declarator is
675 // fully built.
676 state.addIgnoredTypeAttr(attr);
677}
678
679/// A function type attribute was written on the declarator or declaration.
680/// Try to apply it somewhere.
681/// `Attrs` is the attribute list containing the declaration (either of the
682/// declarator or the declaration).
683static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
684 ParsedAttr &attr,
685 QualType &declSpecType,
686 CUDAFunctionTarget CFT) {
687 Declarator &declarator = state.getDeclarator();
688
689 // Try to distribute to the innermost.
691 state, attr, declarator.getAttributes(), declSpecType, CFT))
692 return;
693
694 // If that failed, diagnose the bad attribute when the declarator is
695 // fully built.
696 declarator.getAttributes().remove(&attr);
697 state.addIgnoredTypeAttr(attr);
698}
699
700/// Given that there are attributes written on the declarator or declaration
701/// itself, try to distribute any type attributes to the appropriate
702/// declarator chunk.
703///
704/// These are attributes like the following:
705/// int f ATTR;
706/// int (f ATTR)();
707/// but not necessarily this:
708/// int f() ATTR;
709///
710/// `Attrs` is the attribute list containing the declaration (either of the
711/// declarator or the declaration).
712static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
713 QualType &declSpecType,
714 CUDAFunctionTarget CFT) {
715 // The called functions in this loop actually remove things from the current
716 // list, so iterating over the existing list isn't possible. Instead, make a
717 // non-owning copy and iterate over that.
718 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
719 for (ParsedAttr &attr : AttrsCopy) {
720 // Do not distribute [[]] attributes. They have strict rules for what
721 // they appertain to.
722 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute())
723 continue;
724
725 switch (attr.getKind()) {
728 break;
729
731 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType, CFT);
732 break;
733
735 // Microsoft type attributes cannot go after the declarator-id.
736 continue;
737
739 // Nullability specifiers cannot go after the declarator-id.
740
741 // Objective-C __kindof does not get distributed.
742 case ParsedAttr::AT_ObjCKindOf:
743 continue;
744
745 default:
746 break;
747 }
748 }
749}
750
751/// Add a synthetic '()' to a block-literal declarator if it is
752/// required, given the return type.
753static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
754 QualType declSpecType) {
755 Declarator &declarator = state.getDeclarator();
756
757 // First, check whether the declarator would produce a function,
758 // i.e. whether the innermost semantic chunk is a function.
759 if (declarator.isFunctionDeclarator()) {
760 // If so, make that declarator a prototyped declarator.
761 declarator.getFunctionTypeInfo().hasPrototype = true;
762 return;
763 }
764
765 // If there are any type objects, the type as written won't name a
766 // function, regardless of the decl spec type. This is because a
767 // block signature declarator is always an abstract-declarator, and
768 // abstract-declarators can't just be parentheses chunks. Therefore
769 // we need to build a function chunk unless there are no type
770 // objects and the decl spec type is a function.
771 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
772 return;
773
774 // Note that there *are* cases with invalid declarators where
775 // declarators consist solely of parentheses. In general, these
776 // occur only in failed efforts to make function declarators, so
777 // faking up the function chunk is still the right thing to do.
778
779 // Otherwise, we need to fake up a function declarator.
780 SourceLocation loc = declarator.getBeginLoc();
781
782 // ...and *prepend* it to the declarator.
783 SourceLocation NoLoc;
785 /*HasProto=*/true,
786 /*IsAmbiguous=*/false,
787 /*LParenLoc=*/NoLoc,
788 /*ArgInfo=*/nullptr,
789 /*NumParams=*/0,
790 /*EllipsisLoc=*/NoLoc,
791 /*RParenLoc=*/NoLoc,
792 /*RefQualifierIsLvalueRef=*/true,
793 /*RefQualifierLoc=*/NoLoc,
794 /*MutableLoc=*/NoLoc, EST_None,
795 /*ESpecRange=*/SourceRange(),
796 /*Exceptions=*/nullptr,
797 /*ExceptionRanges=*/nullptr,
798 /*NumExceptions=*/0,
799 /*NoexceptExpr=*/nullptr,
800 /*ExceptionSpecTokens=*/nullptr,
801 /*DeclsInPrototype=*/{}, loc, loc, declarator));
802
803 // For consistency, make sure the state still has us as processing
804 // the decl spec.
805 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
806 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
807}
808
810 unsigned &TypeQuals,
811 QualType TypeSoFar,
812 unsigned RemoveTQs,
813 unsigned DiagID) {
814 // If this occurs outside a template instantiation, warn the user about
815 // it; they probably didn't mean to specify a redundant qualifier.
816 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
817 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
820 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
821 if (!(RemoveTQs & Qual.first))
822 continue;
823
824 if (!S.inTemplateInstantiation()) {
825 if (TypeQuals & Qual.first)
826 S.Diag(Qual.second, DiagID)
827 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
828 << FixItHint::CreateRemoval(Qual.second);
829 }
830
831 TypeQuals &= ~Qual.first;
832 }
833}
834
835/// Return true if this is omitted block return type. Also check type
836/// attributes and type qualifiers when returning true.
837static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
838 QualType Result) {
839 if (!isOmittedBlockReturnType(declarator))
840 return false;
841
842 // Warn if we see type attributes for omitted return type on a block literal.
844 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
845 if (AL.isInvalid() || !AL.isTypeAttr())
846 continue;
847 S.Diag(AL.getLoc(),
848 diag::warn_block_literal_attributes_on_omitted_return_type)
849 << AL;
850 ToBeRemoved.push_back(&AL);
851 }
852 // Remove bad attributes from the list.
853 for (ParsedAttr *AL : ToBeRemoved)
854 declarator.getMutableDeclSpec().getAttributes().remove(AL);
855
856 // Warn if we see type qualifiers for omitted return type on a block literal.
857 const DeclSpec &DS = declarator.getDeclSpec();
858 unsigned TypeQuals = DS.getTypeQualifiers();
859 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
860 diag::warn_block_literal_qualifiers_on_omitted_return_type);
862
863 return true;
864}
865
866static OpenCLAccessAttr::Spelling
868 for (const ParsedAttr &AL : Attrs)
869 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
870 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
871 return OpenCLAccessAttr::Keyword_read_only;
872}
873
876 switch (SwitchTST) {
877#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
878 case TST_##Trait: \
879 return UnaryTransformType::Enum;
880#include "clang/Basic/TransformTypeTraits.def"
881 default:
882 llvm_unreachable("attempted to parse a non-unary transform builtin");
883 }
884}
885
886/// Convert the specified declspec to the appropriate type
887/// object.
888/// \param state Specifies the declarator containing the declaration specifier
889/// to be converted, along with other associated processing state.
890/// \returns The type described by the declaration specifiers. This function
891/// never returns null.
892static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
893 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
894 // checking.
895
896 Sema &S = state.getSema();
897 Declarator &declarator = state.getDeclarator();
898 DeclSpec &DS = declarator.getMutableDeclSpec();
899 SourceLocation DeclLoc = declarator.getIdentifierLoc();
900 if (DeclLoc.isInvalid())
901 DeclLoc = DS.getBeginLoc();
902
903 ASTContext &Context = S.Context;
904
905 QualType Result;
906 switch (DS.getTypeSpecType()) {
908 Result = Context.VoidTy;
909 break;
911 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
912 Result = Context.CharTy;
913 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed)
914 Result = Context.SignedCharTy;
915 else {
916 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
917 "Unknown TSS value");
918 Result = Context.UnsignedCharTy;
919 }
920 break;
922 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
923 Result = Context.WCharTy;
924 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) {
925 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
927 Context.getPrintingPolicy());
928 Result = Context.getSignedWCharType();
929 } else {
930 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
931 "Unknown TSS value");
932 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
934 Context.getPrintingPolicy());
935 Result = Context.getUnsignedWCharType();
936 }
937 break;
939 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
940 "Unknown TSS value");
941 Result = Context.Char8Ty;
942 break;
944 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
945 "Unknown TSS value");
946 Result = Context.Char16Ty;
947 break;
949 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
950 "Unknown TSS value");
951 Result = Context.Char32Ty;
952 break;
954 // If this is a missing declspec in a block literal return context, then it
955 // is inferred from the return statements inside the block.
956 // The declspec is always missing in a lambda expr context; it is either
957 // specified with a trailing return type or inferred.
958 if (S.getLangOpts().CPlusPlus14 &&
959 declarator.getContext() == DeclaratorContext::LambdaExpr) {
960 // In C++1y, a lambda's implicit return type is 'auto'.
961 Result = Context.getAutoDeductType();
962 break;
963 } else if (declarator.getContext() == DeclaratorContext::LambdaExpr ||
964 checkOmittedBlockReturnType(S, declarator,
965 Context.DependentTy)) {
966 Result = Context.DependentTy;
967 break;
968 }
969
970 // Unspecified typespec defaults to int in C90. However, the C90 grammar
971 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
972 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
973 // Note that the one exception to this is function definitions, which are
974 // allowed to be completely missing a declspec. This is handled in the
975 // parser already though by it pretending to have seen an 'int' in this
976 // case.
978 S.Diag(DeclLoc, diag::warn_missing_type_specifier)
979 << DS.getSourceRange()
981 } else if (!DS.hasTypeSpecifier()) {
982 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
983 // "At least one type specifier shall be given in the declaration
984 // specifiers in each declaration, and in the specifier-qualifier list in
985 // each struct declaration and type name."
986 if (!S.getLangOpts().isImplicitIntAllowed() && !DS.isTypeSpecPipe()) {
987 S.Diag(DeclLoc, diag::err_missing_type_specifier)
988 << DS.getSourceRange();
989
990 // When this occurs, often something is very broken with the value
991 // being declared, poison it as invalid so we don't get chains of
992 // errors.
993 declarator.setInvalidType(true);
994 } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 &&
995 DS.isTypeSpecPipe()) {
996 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
997 << DS.getSourceRange();
998 declarator.setInvalidType(true);
999 } else {
1000 assert(S.getLangOpts().isImplicitIntAllowed() &&
1001 "implicit int is disabled?");
1002 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1003 << DS.getSourceRange()
1005 }
1006 }
1007
1008 [[fallthrough]];
1009 case DeclSpec::TST_int: {
1010 if (DS.getTypeSpecSign() != TypeSpecifierSign::Unsigned) {
1011 switch (DS.getTypeSpecWidth()) {
1012 case TypeSpecifierWidth::Unspecified:
1013 Result = Context.IntTy;
1014 break;
1015 case TypeSpecifierWidth::Short:
1016 Result = Context.ShortTy;
1017 break;
1018 case TypeSpecifierWidth::Long:
1019 Result = Context.LongTy;
1020 break;
1021 case TypeSpecifierWidth::LongLong:
1022 Result = Context.LongLongTy;
1023
1024 // 'long long' is a C99 or C++11 feature.
1025 if (!S.getLangOpts().C99) {
1026 if (S.getLangOpts().CPlusPlus)
1028 S.getLangOpts().CPlusPlus11 ?
1029 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1030 else
1031 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1032 }
1033 break;
1034 }
1035 } else {
1036 switch (DS.getTypeSpecWidth()) {
1037 case TypeSpecifierWidth::Unspecified:
1038 Result = Context.UnsignedIntTy;
1039 break;
1040 case TypeSpecifierWidth::Short:
1041 Result = Context.UnsignedShortTy;
1042 break;
1043 case TypeSpecifierWidth::Long:
1044 Result = Context.UnsignedLongTy;
1045 break;
1046 case TypeSpecifierWidth::LongLong:
1047 Result = Context.UnsignedLongLongTy;
1048
1049 // 'long long' is a C99 or C++11 feature.
1050 if (!S.getLangOpts().C99) {
1051 if (S.getLangOpts().CPlusPlus)
1053 S.getLangOpts().CPlusPlus11 ?
1054 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1055 else
1056 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1057 }
1058 break;
1059 }
1060 }
1061 break;
1062 }
1063 case DeclSpec::TST_bitint: {
1065 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_BitInt";
1066 Result =
1067 S.BuildBitIntType(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned,
1068 DS.getRepAsExpr(), DS.getBeginLoc());
1069 if (Result.isNull()) {
1070 Result = Context.IntTy;
1071 declarator.setInvalidType(true);
1072 }
1073 break;
1074 }
1075 case DeclSpec::TST_accum: {
1076 switch (DS.getTypeSpecWidth()) {
1077 case TypeSpecifierWidth::Short:
1078 Result = Context.ShortAccumTy;
1079 break;
1080 case TypeSpecifierWidth::Unspecified:
1081 Result = Context.AccumTy;
1082 break;
1083 case TypeSpecifierWidth::Long:
1084 Result = Context.LongAccumTy;
1085 break;
1086 case TypeSpecifierWidth::LongLong:
1087 llvm_unreachable("Unable to specify long long as _Accum width");
1088 }
1089
1090 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1091 Result = Context.getCorrespondingUnsignedType(Result);
1092
1093 if (DS.isTypeSpecSat())
1094 Result = Context.getCorrespondingSaturatedType(Result);
1095
1096 break;
1097 }
1098 case DeclSpec::TST_fract: {
1099 switch (DS.getTypeSpecWidth()) {
1100 case TypeSpecifierWidth::Short:
1101 Result = Context.ShortFractTy;
1102 break;
1103 case TypeSpecifierWidth::Unspecified:
1104 Result = Context.FractTy;
1105 break;
1106 case TypeSpecifierWidth::Long:
1107 Result = Context.LongFractTy;
1108 break;
1109 case TypeSpecifierWidth::LongLong:
1110 llvm_unreachable("Unable to specify long long as _Fract width");
1111 }
1112
1113 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1114 Result = Context.getCorrespondingUnsignedType(Result);
1115
1116 if (DS.isTypeSpecSat())
1117 Result = Context.getCorrespondingSaturatedType(Result);
1118
1119 break;
1120 }
1122 if (!S.Context.getTargetInfo().hasInt128Type() &&
1123 !(S.getLangOpts().SYCLIsDevice || S.getLangOpts().CUDAIsDevice ||
1124 (S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice)))
1125 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1126 << "__int128";
1127 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1128 Result = Context.UnsignedInt128Ty;
1129 else
1130 Result = Context.Int128Ty;
1131 break;
1133 // CUDA host and device may have different _Float16 support, therefore
1134 // do not diagnose _Float16 usage to avoid false alarm.
1135 // ToDo: more precise diagnostics for CUDA.
1136 if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
1137 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1138 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1139 << "_Float16";
1140 Result = Context.Float16Ty;
1141 break;
1142 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1145 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice) &&
1146 !S.getLangOpts().SYCLIsDevice)
1147 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__bf16";
1148 Result = Context.BFloat16Ty;
1149 break;
1150 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1152 if (DS.getTypeSpecWidth() == TypeSpecifierWidth::Long)
1153 Result = Context.LongDoubleTy;
1154 else
1155 Result = Context.DoubleTy;
1156 if (S.getLangOpts().OpenCL) {
1157 if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts()))
1158 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1159 << 0 << Result
1161 ? "cl_khr_fp64 and __opencl_c_fp64"
1162 : "cl_khr_fp64");
1163 else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts()))
1164 S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma);
1165 }
1166 break;
1169 !S.getLangOpts().SYCLIsDevice && !S.getLangOpts().CUDAIsDevice &&
1170 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1171 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1172 << "__float128";
1173 Result = Context.Float128Ty;
1174 break;
1176 if (!S.Context.getTargetInfo().hasIbm128Type() &&
1177 !S.getLangOpts().SYCLIsDevice &&
1178 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1179 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128";
1180 Result = Context.Ibm128Ty;
1181 break;
1182 case DeclSpec::TST_bool:
1183 Result = Context.BoolTy; // _Bool or bool
1184 break;
1185 case DeclSpec::TST_decimal32: // _Decimal32
1186 case DeclSpec::TST_decimal64: // _Decimal64
1187 case DeclSpec::TST_decimal128: // _Decimal128
1188 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1189 Result = Context.IntTy;
1190 declarator.setInvalidType(true);
1191 break;
1193 case DeclSpec::TST_enum:
1197 TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1198 if (!D) {
1199 // This can happen in C++ with ambiguous lookups.
1200 Result = Context.IntTy;
1201 declarator.setInvalidType(true);
1202 break;
1203 }
1204
1205 // If the type is deprecated or unavailable, diagnose it.
1207
1208 assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1209 DS.getTypeSpecComplex() == 0 &&
1210 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1211 "No qualifiers on tag names!");
1212
1213 // TypeQuals handled by caller.
1214 Result = Context.getTypeDeclType(D);
1215
1216 // In both C and C++, make an ElaboratedType.
1217 ElaboratedTypeKeyword Keyword
1218 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1219 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
1220 DS.isTypeSpecOwned() ? D : nullptr);
1221 break;
1222 }
1224 assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1225 DS.getTypeSpecComplex() == 0 &&
1226 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1227 "Can't handle qualifiers on typedef names yet!");
1228 Result = S.GetTypeFromParser(DS.getRepAsType());
1229 if (Result.isNull()) {
1230 declarator.setInvalidType(true);
1231 }
1232
1233 // TypeQuals handled by caller.
1234 break;
1235 }
1238 // FIXME: Preserve type source info.
1239 Result = S.GetTypeFromParser(DS.getRepAsType());
1240 assert(!Result.isNull() && "Didn't get a type for typeof?");
1241 if (!Result->isDependentType())
1242 if (const TagType *TT = Result->getAs<TagType>())
1243 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1244 // TypeQuals handled by caller.
1245 Result = Context.getTypeOfType(
1247 ? TypeOfKind::Unqualified
1248 : TypeOfKind::Qualified);
1249 break;
1252 Expr *E = DS.getRepAsExpr();
1253 assert(E && "Didn't get an expression for typeof?");
1254 // TypeQuals handled by caller.
1255 Result = S.BuildTypeofExprType(E, DS.getTypeSpecType() ==
1257 ? TypeOfKind::Unqualified
1258 : TypeOfKind::Qualified);
1259 if (Result.isNull()) {
1260 Result = Context.IntTy;
1261 declarator.setInvalidType(true);
1262 }
1263 break;
1264 }
1266 Expr *E = DS.getRepAsExpr();
1267 assert(E && "Didn't get an expression for decltype?");
1268 // TypeQuals handled by caller.
1269 Result = S.BuildDecltypeType(E);
1270 if (Result.isNull()) {
1271 Result = Context.IntTy;
1272 declarator.setInvalidType(true);
1273 }
1274 break;
1275 }
1277 Expr *E = DS.getPackIndexingExpr();
1278 assert(E && "Didn't get an expression for pack indexing");
1279 QualType Pattern = S.GetTypeFromParser(DS.getRepAsType());
1280 Result = S.BuildPackIndexingType(Pattern, E, DS.getBeginLoc(),
1281 DS.getEllipsisLoc());
1282 if (Result.isNull()) {
1283 declarator.setInvalidType(true);
1284 Result = Context.IntTy;
1285 }
1286 break;
1287 }
1288
1289#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
1290#include "clang/Basic/TransformTypeTraits.def"
1291 Result = S.GetTypeFromParser(DS.getRepAsType());
1292 assert(!Result.isNull() && "Didn't get a type for the transformation?");
1293 Result = S.BuildUnaryTransformType(
1295 DS.getTypeSpecTypeLoc());
1296 if (Result.isNull()) {
1297 Result = Context.IntTy;
1298 declarator.setInvalidType(true);
1299 }
1300 break;
1301
1302 case DeclSpec::TST_auto:
1304 auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1305 ? AutoTypeKeyword::DecltypeAuto
1306 : AutoTypeKeyword::Auto;
1307
1308 ConceptDecl *TypeConstraintConcept = nullptr;
1310 if (DS.isConstrainedAuto()) {
1311 if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1312 TypeConstraintConcept =
1313 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl());
1314 TemplateArgumentListInfo TemplateArgsInfo;
1315 TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1316 TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1317 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1318 TemplateId->NumArgs);
1319 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1320 for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1321 TemplateArgs.push_back(ArgLoc.getArgument());
1322 } else {
1323 declarator.setInvalidType(true);
1324 }
1325 }
1326 Result = S.Context.getAutoType(QualType(), AutoKW,
1327 /*IsDependent*/ false, /*IsPack=*/false,
1328 TypeConstraintConcept, TemplateArgs);
1329 break;
1330 }
1331
1333 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1334 break;
1335
1337 Result = Context.UnknownAnyTy;
1338 break;
1339
1341 Result = S.GetTypeFromParser(DS.getRepAsType());
1342 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1343 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1344 if (Result.isNull()) {
1345 Result = Context.IntTy;
1346 declarator.setInvalidType(true);
1347 }
1348 break;
1349
1350#define GENERIC_IMAGE_TYPE(ImgType, Id) \
1351 case DeclSpec::TST_##ImgType##_t: \
1352 switch (getImageAccess(DS.getAttributes())) { \
1353 case OpenCLAccessAttr::Keyword_write_only: \
1354 Result = Context.Id##WOTy; \
1355 break; \
1356 case OpenCLAccessAttr::Keyword_read_write: \
1357 Result = Context.Id##RWTy; \
1358 break; \
1359 case OpenCLAccessAttr::Keyword_read_only: \
1360 Result = Context.Id##ROTy; \
1361 break; \
1362 case OpenCLAccessAttr::SpellingNotCalculated: \
1363 llvm_unreachable("Spelling not yet calculated"); \
1364 } \
1365 break;
1366#include "clang/Basic/OpenCLImageTypes.def"
1367
1368#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1369 case DeclSpec::TST_##Name: \
1370 Result = Context.SingletonId; \
1371 break;
1372#include "clang/Basic/HLSLIntangibleTypes.def"
1373
1375 Result = Context.IntTy;
1376 declarator.setInvalidType(true);
1377 break;
1378 }
1379
1380 // FIXME: we want resulting declarations to be marked invalid, but claiming
1381 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1382 // a null type.
1383 if (Result->containsErrors())
1384 declarator.setInvalidType();
1385
1386 if (S.getLangOpts().OpenCL) {
1387 const auto &OpenCLOptions = S.getOpenCLOptions();
1388 bool IsOpenCLC30Compatible =
1390 // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1391 // support.
1392 // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1393 // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1394 // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1395 // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1396 // only when the optional feature is supported
1397 if ((Result->isImageType() || Result->isSamplerT()) &&
1398 (IsOpenCLC30Compatible &&
1399 !OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts()))) {
1400 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1401 << 0 << Result << "__opencl_c_images";
1402 declarator.setInvalidType();
1403 } else if (Result->isOCLImage3dWOType() &&
1404 !OpenCLOptions.isSupported("cl_khr_3d_image_writes",
1405 S.getLangOpts())) {
1406 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1407 << 0 << Result
1408 << (IsOpenCLC30Compatible
1409 ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes"
1410 : "cl_khr_3d_image_writes");
1411 declarator.setInvalidType();
1412 }
1413 }
1414
1415 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1417
1418 // Only fixed point types can be saturated
1419 if (DS.isTypeSpecSat() && !IsFixedPointType)
1420 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1422 Context.getPrintingPolicy());
1423
1424 // Handle complex types.
1426 if (S.getLangOpts().Freestanding)
1427 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1428 Result = Context.getComplexType(Result);
1429 } else if (DS.isTypeAltiVecVector()) {
1430 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1431 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1432 VectorKind VecKind = VectorKind::AltiVecVector;
1433 if (DS.isTypeAltiVecPixel())
1434 VecKind = VectorKind::AltiVecPixel;
1435 else if (DS.isTypeAltiVecBool())
1436 VecKind = VectorKind::AltiVecBool;
1437 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1438 }
1439
1440 // _Imaginary was a feature of C99 through C23 but was never supported in
1441 // Clang. The feature was removed in C2y, but we retain the unsupported
1442 // diagnostic for an improved user experience.
1444 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1445
1446 // Before we process any type attributes, synthesize a block literal
1447 // function declarator if necessary.
1448 if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1449 maybeSynthesizeBlockSignature(state, Result);
1450
1451 // Apply any type attributes from the decl spec. This may cause the
1452 // list of type attributes to be temporarily saved while the type
1453 // attributes are pushed around.
1454 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1455 if (!DS.isTypeSpecPipe()) {
1456 // We also apply declaration attributes that "slide" to the decl spec.
1457 // Ordering can be important for attributes. The decalaration attributes
1458 // come syntactically before the decl spec attributes, so we process them
1459 // in that order.
1460 ParsedAttributesView SlidingAttrs;
1461 for (ParsedAttr &AL : declarator.getDeclarationAttributes()) {
1462 if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
1463 SlidingAttrs.addAtEnd(&AL);
1464
1465 // For standard syntax attributes, which would normally appertain to the
1466 // declaration here, suggest moving them to the type instead. But only
1467 // do this for our own vendor attributes; moving other vendors'
1468 // attributes might hurt portability.
1469 // There's one special case that we need to deal with here: The
1470 // `MatrixType` attribute may only be used in a typedef declaration. If
1471 // it's being used anywhere else, don't output the warning as
1472 // ProcessDeclAttributes() will output an error anyway.
1473 if (AL.isStandardAttributeSyntax() && AL.isClangScope() &&
1474 !(AL.getKind() == ParsedAttr::AT_MatrixType &&
1476 S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl)
1477 << AL;
1478 }
1479 }
1480 }
1481 // During this call to processTypeAttrs(),
1482 // TypeProcessingState::getCurrentAttributes() will erroneously return a
1483 // reference to the DeclSpec attributes, rather than the declaration
1484 // attributes. However, this doesn't matter, as getCurrentAttributes()
1485 // is only called when distributing attributes from one attribute list
1486 // to another. Declaration attributes are always C++11 attributes, and these
1487 // are never distributed.
1488 processTypeAttrs(state, Result, TAL_DeclSpec, SlidingAttrs);
1489 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
1490 }
1491
1492 // Apply const/volatile/restrict qualifiers to T.
1493 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1494 // Warn about CV qualifiers on function types.
1495 // C99 6.7.3p8:
1496 // If the specification of a function type includes any type qualifiers,
1497 // the behavior is undefined.
1498 // C2y changed this behavior to be implementation-defined. Clang defines
1499 // the behavior in all cases to ignore the qualifier, as in C++.
1500 // C++11 [dcl.fct]p7:
1501 // The effect of a cv-qualifier-seq in a function declarator is not the
1502 // same as adding cv-qualification on top of the function type. In the
1503 // latter case, the cv-qualifiers are ignored.
1504 if (Result->isFunctionType()) {
1505 unsigned DiagId = diag::warn_typecheck_function_qualifiers_ignored;
1506 if (!S.getLangOpts().CPlusPlus && !S.getLangOpts().C2y)
1507 DiagId = diag::ext_typecheck_function_qualifiers_unspecified;
1509 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1510 DiagId);
1511 // No diagnostic for 'restrict' or '_Atomic' applied to a
1512 // function type; we'll diagnose those later, in BuildQualifiedType.
1513 }
1514
1515 // C++11 [dcl.ref]p1:
1516 // Cv-qualified references are ill-formed except when the
1517 // cv-qualifiers are introduced through the use of a typedef-name
1518 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1519 //
1520 // There don't appear to be any other contexts in which a cv-qualified
1521 // reference type could be formed, so the 'ill-formed' clause here appears
1522 // to never happen.
1523 if (TypeQuals && Result->isReferenceType()) {
1525 S, DS, TypeQuals, Result,
1527 diag::warn_typecheck_reference_qualifiers);
1528 }
1529
1530 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1531 // than once in the same specifier-list or qualifier-list, either directly
1532 // or via one or more typedefs."
1533 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1534 && TypeQuals & Result.getCVRQualifiers()) {
1535 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1536 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1537 << "const";
1538 }
1539
1540 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1541 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1542 << "volatile";
1543 }
1544
1545 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1546 // produce a warning in this case.
1547 }
1548
1549 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1550
1551 // If adding qualifiers fails, just use the unqualified type.
1552 if (Qualified.isNull())
1553 declarator.setInvalidType(true);
1554 else
1555 Result = Qualified;
1556 }
1557
1558 if (S.getLangOpts().HLSL)
1559 Result = S.HLSL().ProcessResourceTypeAttributes(Result);
1560
1561 assert(!Result.isNull() && "This function should not return a null type");
1562 return Result;
1563}
1564
1565static std::string getPrintableNameForEntity(DeclarationName Entity) {
1566 if (Entity)
1567 return Entity.getAsString();
1568
1569 return "type name";
1570}
1571
1573 if (T->isDependentType())
1574 return true;
1575
1576 const auto *AT = dyn_cast<AutoType>(T);
1577 return AT && AT->isGNUAutoType();
1578}
1579
1581 Qualifiers Qs, const DeclSpec *DS) {
1582 if (T.isNull())
1583 return QualType();
1584
1585 // Ignore any attempt to form a cv-qualified reference.
1586 if (T->isReferenceType()) {
1587 Qs.removeConst();
1588 Qs.removeVolatile();
1589 }
1590
1591 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1592 // object or incomplete types shall not be restrict-qualified."
1593 if (Qs.hasRestrict()) {
1594 unsigned DiagID = 0;
1595 QualType ProblemTy;
1596
1597 if (T->isAnyPointerType() || T->isReferenceType() ||
1599 QualType EltTy;
1601 EltTy = T;
1602 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1603 EltTy = PTy->getPointeeType();
1604 else
1605 EltTy = T->getPointeeType();
1606
1607 // If we have a pointer or reference, the pointee must have an object
1608 // incomplete type.
1609 if (!EltTy->isIncompleteOrObjectType()) {
1610 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1611 ProblemTy = EltTy;
1612 }
1613 } else if (!isDependentOrGNUAutoType(T)) {
1614 // For an __auto_type variable, we may not have seen the initializer yet
1615 // and so have no idea whether the underlying type is a pointer type or
1616 // not.
1617 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1618 ProblemTy = T;
1619 }
1620
1621 if (DiagID) {
1622 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1623 Qs.removeRestrict();
1624 }
1625 }
1626
1627 return Context.getQualifiedType(T, Qs);
1628}
1629
1631 unsigned CVRAU, const DeclSpec *DS) {
1632 if (T.isNull())
1633 return QualType();
1634
1635 // Ignore any attempt to form a cv-qualified reference.
1636 if (T->isReferenceType())
1637 CVRAU &=
1639
1640 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1641 // TQ_unaligned;
1642 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1643
1644 // C11 6.7.3/5:
1645 // If the same qualifier appears more than once in the same
1646 // specifier-qualifier-list, either directly or via one or more typedefs,
1647 // the behavior is the same as if it appeared only once.
1648 //
1649 // It's not specified what happens when the _Atomic qualifier is applied to
1650 // a type specified with the _Atomic specifier, but we assume that this
1651 // should be treated as if the _Atomic qualifier appeared multiple times.
1652 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1653 // C11 6.7.3/5:
1654 // If other qualifiers appear along with the _Atomic qualifier in a
1655 // specifier-qualifier-list, the resulting type is the so-qualified
1656 // atomic type.
1657 //
1658 // Don't need to worry about array types here, since _Atomic can't be
1659 // applied to such types.
1660 SplitQualType Split = T.getSplitUnqualifiedType();
1661 T = BuildAtomicType(QualType(Split.Ty, 0),
1662 DS ? DS->getAtomicSpecLoc() : Loc);
1663 if (T.isNull())
1664 return T;
1665 Split.Quals.addCVRQualifiers(CVR);
1666 return BuildQualifiedType(T, Loc, Split.Quals);
1667 }
1668
1671 return BuildQualifiedType(T, Loc, Q, DS);
1672}
1673
1675 return Context.getParenType(T);
1676}
1677
1678/// Given that we're building a pointer or reference to the given
1680 SourceLocation loc,
1681 bool isReference) {
1682 // Bail out if retention is unrequired or already specified.
1683 if (!type->isObjCLifetimeType() ||
1684 type.getObjCLifetime() != Qualifiers::OCL_None)
1685 return type;
1686
1688
1689 // If the object type is const-qualified, we can safely use
1690 // __unsafe_unretained. This is safe (because there are no read
1691 // barriers), and it'll be safe to coerce anything but __weak* to
1692 // the resulting type.
1693 if (type.isConstQualified()) {
1694 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1695
1696 // Otherwise, check whether the static type does not require
1697 // retaining. This currently only triggers for Class (possibly
1698 // protocol-qualifed, and arrays thereof).
1699 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1700 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1701
1702 // If we are in an unevaluated context, like sizeof, skip adding a
1703 // qualification.
1704 } else if (S.isUnevaluatedContext()) {
1705 return type;
1706
1707 // If that failed, give an error and recover using __strong. __strong
1708 // is the option most likely to prevent spurious second-order diagnostics,
1709 // like when binding a reference to a field.
1710 } else {
1711 // These types can show up in private ivars in system headers, so
1712 // we need this to not be an error in those cases. Instead we
1713 // want to delay.
1717 diag::err_arc_indirect_no_ownership, type, isReference));
1718 } else {
1719 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1720 }
1721 implicitLifetime = Qualifiers::OCL_Strong;
1722 }
1723 assert(implicitLifetime && "didn't infer any lifetime!");
1724
1725 Qualifiers qs;
1726 qs.addObjCLifetime(implicitLifetime);
1727 return S.Context.getQualifiedType(type, qs);
1728}
1729
1730static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1731 std::string Quals = FnTy->getMethodQuals().getAsString();
1732
1733 switch (FnTy->getRefQualifier()) {
1734 case RQ_None:
1735 break;
1736
1737 case RQ_LValue:
1738 if (!Quals.empty())
1739 Quals += ' ';
1740 Quals += '&';
1741 break;
1742
1743 case RQ_RValue:
1744 if (!Quals.empty())
1745 Quals += ' ';
1746 Quals += "&&";
1747 break;
1748 }
1749
1750 return Quals;
1751}
1752
1753namespace {
1754/// Kinds of declarator that cannot contain a qualified function type.
1755///
1756/// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1757/// a function type with a cv-qualifier or a ref-qualifier can only appear
1758/// at the topmost level of a type.
1759///
1760/// Parens and member pointers are permitted. We don't diagnose array and
1761/// function declarators, because they don't allow function types at all.
1762///
1763/// The values of this enum are used in diagnostics.
1764enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1765} // end anonymous namespace
1766
1767/// Check whether the type T is a qualified function type, and if it is,
1768/// diagnose that it cannot be contained within the given kind of declarator.
1770 QualifiedFunctionKind QFK) {
1771 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1772 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1773 if (!FPT ||
1774 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1775 return false;
1776
1777 S.Diag(Loc, diag::err_compound_qualified_function_type)
1778 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1780 return true;
1781}
1782
1784 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1785 if (!FPT ||
1786 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1787 return false;
1788
1789 Diag(Loc, diag::err_qualified_function_typeid)
1791 return true;
1792}
1793
1794// Helper to deduce addr space of a pointee type in OpenCL mode.
1796 if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
1797 !PointeeType->isSamplerT() &&
1798 !PointeeType.hasAddressSpace())
1799 PointeeType = S.getASTContext().getAddrSpaceQualType(
1801 return PointeeType;
1802}
1803
1806 if (T->isReferenceType()) {
1807 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1808 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1809 << getPrintableNameForEntity(Entity) << T;
1810 return QualType();
1811 }
1812
1813 if (T->isFunctionType() && getLangOpts().OpenCL &&
1814 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
1815 getLangOpts())) {
1816 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
1817 return QualType();
1818 }
1819
1820 if (getLangOpts().HLSL && Loc.isValid()) {
1821 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
1822 return QualType();
1823 }
1824
1825 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1826 return QualType();
1827
1828 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1829
1830 // In ARC, it is forbidden to build pointers to unqualified pointers.
1831 if (getLangOpts().ObjCAutoRefCount)
1832 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1833
1834 if (getLangOpts().OpenCL)
1836
1837 // In WebAssembly, pointers to reference types and pointers to tables are
1838 // illegal.
1839 if (getASTContext().getTargetInfo().getTriple().isWasm()) {
1840 if (T.isWebAssemblyReferenceType()) {
1841 Diag(Loc, diag::err_wasm_reference_pr) << 0;
1842 return QualType();
1843 }
1844
1845 // We need to desugar the type here in case T is a ParenType.
1847 Diag(Loc, diag::err_wasm_table_pr) << 0;
1848 return QualType();
1849 }
1850 }
1851
1852 // Build the pointer type.
1853 return Context.getPointerType(T);
1854}
1855
1858 DeclarationName Entity) {
1860 "Unresolved overloaded function type");
1861
1862 // C++0x [dcl.ref]p6:
1863 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1864 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1865 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1866 // the type "lvalue reference to T", while an attempt to create the type
1867 // "rvalue reference to cv TR" creates the type TR.
1868 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1869
1870 // C++ [dcl.ref]p4: There shall be no references to references.
1871 //
1872 // According to C++ DR 106, references to references are only
1873 // diagnosed when they are written directly (e.g., "int & &"),
1874 // but not when they happen via a typedef:
1875 //
1876 // typedef int& intref;
1877 // typedef intref& intref2;
1878 //
1879 // Parser::ParseDeclaratorInternal diagnoses the case where
1880 // references are written directly; here, we handle the
1881 // collapsing of references-to-references as described in C++0x.
1882 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1883
1884 // C++ [dcl.ref]p1:
1885 // A declarator that specifies the type "reference to cv void"
1886 // is ill-formed.
1887 if (T->isVoidType()) {
1888 Diag(Loc, diag::err_reference_to_void);
1889 return QualType();
1890 }
1891
1892 if (getLangOpts().HLSL && Loc.isValid()) {
1893 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1;
1894 return QualType();
1895 }
1896
1897 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1898 return QualType();
1899
1900 if (T->isFunctionType() && getLangOpts().OpenCL &&
1901 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
1902 getLangOpts())) {
1903 Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1;
1904 return QualType();
1905 }
1906
1907 // In ARC, it is forbidden to build references to unqualified pointers.
1908 if (getLangOpts().ObjCAutoRefCount)
1909 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1910
1911 if (getLangOpts().OpenCL)
1913
1914 // In WebAssembly, references to reference types and tables are illegal.
1915 if (getASTContext().getTargetInfo().getTriple().isWasm() &&
1916 T.isWebAssemblyReferenceType()) {
1917 Diag(Loc, diag::err_wasm_reference_pr) << 1;
1918 return QualType();
1919 }
1920 if (T->isWebAssemblyTableType()) {
1921 Diag(Loc, diag::err_wasm_table_pr) << 1;
1922 return QualType();
1923 }
1924
1925 // Handle restrict on references.
1926 if (LValueRef)
1927 return Context.getLValueReferenceType(T, SpelledAsLValue);
1929}
1930
1932 return Context.getReadPipeType(T);
1933}
1934
1936 return Context.getWritePipeType(T);
1937}
1938
1939QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth,
1941 if (BitWidth->isInstantiationDependent())
1942 return Context.getDependentBitIntType(IsUnsigned, BitWidth);
1943
1944 llvm::APSInt Bits(32);
1945 ExprResult ICE =
1946 VerifyIntegerConstantExpression(BitWidth, &Bits, /*FIXME*/ AllowFold);
1947
1948 if (ICE.isInvalid())
1949 return QualType();
1950
1951 size_t NumBits = Bits.getZExtValue();
1952 if (!IsUnsigned && NumBits < 2) {
1953 Diag(Loc, diag::err_bit_int_bad_size) << 0;
1954 return QualType();
1955 }
1956
1957 if (IsUnsigned && NumBits < 1) {
1958 Diag(Loc, diag::err_bit_int_bad_size) << 1;
1959 return QualType();
1960 }
1961
1962 const TargetInfo &TI = getASTContext().getTargetInfo();
1963 if (NumBits > TI.getMaxBitIntWidth()) {
1964 Diag(Loc, diag::err_bit_int_max_size)
1965 << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth());
1966 return QualType();
1967 }
1968
1969 return Context.getBitIntType(IsUnsigned, NumBits);
1970}
1971
1972/// Check whether the specified array bound can be evaluated using the relevant
1973/// language rules. If so, returns the possibly-converted expression and sets
1974/// SizeVal to the size. If not, but the expression might be a VLA bound,
1975/// returns ExprResult(). Otherwise, produces a diagnostic and returns
1976/// ExprError().
1977static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
1978 llvm::APSInt &SizeVal, unsigned VLADiag,
1979 bool VLAIsError) {
1980 if (S.getLangOpts().CPlusPlus14 &&
1981 (VLAIsError ||
1982 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) {
1983 // C++14 [dcl.array]p1:
1984 // The constant-expression shall be a converted constant expression of
1985 // type std::size_t.
1986 //
1987 // Don't apply this rule if we might be forming a VLA: in that case, we
1988 // allow non-constant expressions and constant-folding. We only need to use
1989 // the converted constant expression rules (to properly convert the source)
1990 // when the source expression is of class type.
1992 ArraySize, S.Context.getSizeType(), SizeVal, Sema::CCEK_ArrayBound);
1993 }
1994
1995 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1996 // (like gnu99, but not c99) accept any evaluatable value as an extension.
1997 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1998 public:
1999 unsigned VLADiag;
2000 bool VLAIsError;
2001 bool IsVLA = false;
2002
2003 VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2004 : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2005
2006 Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2007 QualType T) override {
2008 return S.Diag(Loc, diag::err_array_size_non_int) << T;
2009 }
2010
2011 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2012 SourceLocation Loc) override {
2013 IsVLA = !VLAIsError;
2014 return S.Diag(Loc, VLADiag);
2015 }
2016
2017 Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2018 SourceLocation Loc) override {
2019 return S.Diag(Loc, diag::ext_vla_folded_to_constant);
2020 }
2021 } Diagnoser(VLADiag, VLAIsError);
2022
2023 ExprResult R =
2024 S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser);
2025 if (Diagnoser.IsVLA)
2026 return ExprResult();
2027 return R;
2028}
2029
2031 EltTy = Context.getBaseElementType(EltTy);
2032 if (EltTy->isIncompleteType() || EltTy->isDependentType() ||
2033 EltTy->isUndeducedType())
2034 return true;
2035
2036 CharUnits Size = Context.getTypeSizeInChars(EltTy);
2037 CharUnits Alignment = Context.getTypeAlignInChars(EltTy);
2038
2039 if (Size.isMultipleOf(Alignment))
2040 return true;
2041
2042 Diag(Loc, diag::err_array_element_alignment)
2043 << EltTy << Size.getQuantity() << Alignment.getQuantity();
2044 return false;
2045}
2046
2048 Expr *ArraySize, unsigned Quals,
2049 SourceRange Brackets, DeclarationName Entity) {
2050
2051 SourceLocation Loc = Brackets.getBegin();
2052 if (getLangOpts().CPlusPlus) {
2053 // C++ [dcl.array]p1:
2054 // T is called the array element type; this type shall not be a reference
2055 // type, the (possibly cv-qualified) type void, a function type or an
2056 // abstract class type.
2057 //
2058 // C++ [dcl.array]p3:
2059 // When several "array of" specifications are adjacent, [...] only the
2060 // first of the constant expressions that specify the bounds of the arrays
2061 // may be omitted.
2062 //
2063 // Note: function types are handled in the common path with C.
2064 if (T->isReferenceType()) {
2065 Diag(Loc, diag::err_illegal_decl_array_of_references)
2066 << getPrintableNameForEntity(Entity) << T;
2067 return QualType();
2068 }
2069
2070 if (T->isVoidType() || T->isIncompleteArrayType()) {
2071 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2072 return QualType();
2073 }
2074
2075 if (RequireNonAbstractType(Brackets.getBegin(), T,
2076 diag::err_array_of_abstract_type))
2077 return QualType();
2078
2079 // Mentioning a member pointer type for an array type causes us to lock in
2080 // an inheritance model, even if it's inside an unused typedef.
2082 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2083 if (!MPTy->getClass()->isDependentType())
2084 (void)isCompleteType(Loc, T);
2085
2086 } else {
2087 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2088 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2089 if (!T.isWebAssemblyReferenceType() &&
2091 diag::err_array_incomplete_or_sizeless_type))
2092 return QualType();
2093 }
2094
2095 // Multi-dimensional arrays of WebAssembly references are not allowed.
2096 if (Context.getTargetInfo().getTriple().isWasm() && T->isArrayType()) {
2097 const auto *ATy = dyn_cast<ArrayType>(T);
2098 if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
2099 Diag(Loc, diag::err_wasm_reftype_multidimensional_array);
2100 return QualType();
2101 }
2102 }
2103
2104 if (T->isSizelessType() && !T.isWebAssemblyReferenceType()) {
2105 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2106 return QualType();
2107 }
2108
2109 if (T->isFunctionType()) {
2110 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2111 << getPrintableNameForEntity(Entity) << T;
2112 return QualType();
2113 }
2114
2115 if (const RecordType *EltTy = T->getAs<RecordType>()) {
2116 // If the element type is a struct or union that contains a variadic
2117 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2118 if (EltTy->getDecl()->hasFlexibleArrayMember())
2119 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2120 } else if (T->isObjCObjectType()) {
2121 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2122 return QualType();
2123 }
2124
2126 return QualType();
2127
2128 // Do placeholder conversions on the array size expression.
2129 if (ArraySize && ArraySize->hasPlaceholderType()) {
2131 if (Result.isInvalid()) return QualType();
2132 ArraySize = Result.get();
2133 }
2134
2135 // Do lvalue-to-rvalue conversions on the array size expression.
2136 if (ArraySize && !ArraySize->isPRValue()) {
2138 if (Result.isInvalid())
2139 return QualType();
2140
2141 ArraySize = Result.get();
2142 }
2143
2144 // C99 6.7.5.2p1: The size expression shall have integer type.
2145 // C++11 allows contextual conversions to such types.
2146 if (!getLangOpts().CPlusPlus11 &&
2147 ArraySize && !ArraySize->isTypeDependent() &&
2149 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2150 << ArraySize->getType() << ArraySize->getSourceRange();
2151 return QualType();
2152 }
2153
2154 auto IsStaticAssertLike = [](const Expr *ArraySize, ASTContext &Context) {
2155 if (!ArraySize)
2156 return false;
2157
2158 // If the array size expression is a conditional expression whose branches
2159 // are both integer constant expressions, one negative and one positive,
2160 // then it's assumed to be like an old-style static assertion. e.g.,
2161 // int old_style_assert[expr ? 1 : -1];
2162 // We will accept any integer constant expressions instead of assuming the
2163 // values 1 and -1 are always used.
2164 if (const auto *CondExpr = dyn_cast_if_present<ConditionalOperator>(
2165 ArraySize->IgnoreParenImpCasts())) {
2166 std::optional<llvm::APSInt> LHS =
2167 CondExpr->getLHS()->getIntegerConstantExpr(Context);
2168 std::optional<llvm::APSInt> RHS =
2169 CondExpr->getRHS()->getIntegerConstantExpr(Context);
2170 return LHS && RHS && LHS->isNegative() != RHS->isNegative();
2171 }
2172 return false;
2173 };
2174
2175 // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2176 unsigned VLADiag;
2177 bool VLAIsError;
2178 if (getLangOpts().OpenCL) {
2179 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2180 VLADiag = diag::err_opencl_vla;
2181 VLAIsError = true;
2182 } else if (getLangOpts().C99) {
2183 VLADiag = diag::warn_vla_used;
2184 VLAIsError = false;
2185 } else if (isSFINAEContext()) {
2186 VLADiag = diag::err_vla_in_sfinae;
2187 VLAIsError = true;
2188 } else if (getLangOpts().OpenMP && OpenMP().isInOpenMPTaskUntiedContext()) {
2189 VLADiag = diag::err_openmp_vla_in_task_untied;
2190 VLAIsError = true;
2191 } else if (getLangOpts().CPlusPlus) {
2192 if (getLangOpts().CPlusPlus11 && IsStaticAssertLike(ArraySize, Context))
2193 VLADiag = getLangOpts().GNUMode
2194 ? diag::ext_vla_cxx_in_gnu_mode_static_assert
2195 : diag::ext_vla_cxx_static_assert;
2196 else
2197 VLADiag = getLangOpts().GNUMode ? diag::ext_vla_cxx_in_gnu_mode
2198 : diag::ext_vla_cxx;
2199 VLAIsError = false;
2200 } else {
2201 VLADiag = diag::ext_vla;
2202 VLAIsError = false;
2203 }
2204
2205 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2206 if (!ArraySize) {
2207 if (ASM == ArraySizeModifier::Star) {
2208 Diag(Loc, VLADiag);
2209 if (VLAIsError)
2210 return QualType();
2211
2212 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2213 } else {
2214 T = Context.getIncompleteArrayType(T, ASM, Quals);
2215 }
2216 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2217 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2218 } else {
2219 ExprResult R =
2220 checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError);
2221 if (R.isInvalid())
2222 return QualType();
2223
2224 if (!R.isUsable()) {
2225 // C99: an array with a non-ICE size is a VLA. We accept any expression
2226 // that we can fold to a non-zero positive value as a non-VLA as an
2227 // extension.
2228 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2229 } else if (!T->isDependentType() && !T->isIncompleteType() &&
2230 !T->isConstantSizeType()) {
2231 // C99: an array with an element type that has a non-constant-size is a
2232 // VLA.
2233 // FIXME: Add a note to explain why this isn't a VLA.
2234 Diag(Loc, VLADiag);
2235 if (VLAIsError)
2236 return QualType();
2237 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2238 } else {
2239 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2240 // have a value greater than zero.
2241 // In C++, this follows from narrowing conversions being disallowed.
2242 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2243 if (Entity)
2244 Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2245 << getPrintableNameForEntity(Entity)
2246 << ArraySize->getSourceRange();
2247 else
2248 Diag(ArraySize->getBeginLoc(),
2249 diag::err_typecheck_negative_array_size)
2250 << ArraySize->getSourceRange();
2251 return QualType();
2252 }
2253 if (ConstVal == 0 && !T.isWebAssemblyReferenceType()) {
2254 // GCC accepts zero sized static arrays. We allow them when
2255 // we're not in a SFINAE context.
2256 Diag(ArraySize->getBeginLoc(),
2257 isSFINAEContext() ? diag::err_typecheck_zero_array_size
2258 : diag::ext_typecheck_zero_array_size)
2259 << 0 << ArraySize->getSourceRange();
2260 }
2261
2262 // Is the array too large?
2263 unsigned ActiveSizeBits =
2267 : ConstVal.getActiveBits();
2268 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2269 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2270 << toString(ConstVal, 10) << ArraySize->getSourceRange();
2271 return QualType();
2272 }
2273
2274 T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2275 }
2276 }
2277
2278 if (T->isVariableArrayType()) {
2280 // CUDA device code and some other targets don't support VLAs.
2281 bool IsCUDADevice = (getLangOpts().CUDA && getLangOpts().CUDAIsDevice);
2283 IsCUDADevice ? diag::err_cuda_vla : diag::err_vla_unsupported)
2284 << (IsCUDADevice ? llvm::to_underlying(CUDA().CurrentTarget()) : 0);
2285 } else if (sema::FunctionScopeInfo *FSI = getCurFunction()) {
2286 // VLAs are supported on this target, but we may need to do delayed
2287 // checking that the VLA is not being used within a coroutine.
2288 FSI->setHasVLA(Loc);
2289 }
2290 }
2291
2292 // If this is not C99, diagnose array size modifiers on non-VLAs.
2293 if (!getLangOpts().C99 && !T->isVariableArrayType() &&
2294 (ASM != ArraySizeModifier::Normal || Quals != 0)) {
2295 Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx
2296 : diag::ext_c99_array_usage)
2297 << llvm::to_underlying(ASM);
2298 }
2299
2300 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2301 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2302 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2303 if (getLangOpts().OpenCL) {
2304 const QualType ArrType = Context.getBaseElementType(T);
2305 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2306 ArrType->isSamplerT() || ArrType->isImageType()) {
2307 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2308 return QualType();
2309 }
2310 }
2311
2312 return T;
2313}
2314
2316 const BitIntType *BIT,
2317 bool ForMatrixType = false) {
2318 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2319 unsigned NumBits = BIT->getNumBits();
2320 if (!llvm::isPowerOf2_32(NumBits) || NumBits < 8)
2321 return S.Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2322 << ForMatrixType << (NumBits < 8);
2323 return false;
2324}
2325
2327 SourceLocation AttrLoc) {
2328 // The base type must be integer (not Boolean or enumeration) or float, and
2329 // can't already be a vector.
2330 if ((!CurType->isDependentType() &&
2331 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2332 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) &&
2333 !CurType->isBitIntType()) ||
2334 CurType->isArrayType()) {
2335 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2336 return QualType();
2337 }
2338
2339 if (const auto *BIT = CurType->getAs<BitIntType>();
2340 BIT && CheckBitIntElementType(*this, AttrLoc, BIT))
2341 return QualType();
2342
2343 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2344 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2346
2347 std::optional<llvm::APSInt> VecSize =
2349 if (!VecSize) {
2350 Diag(AttrLoc, diag::err_attribute_argument_type)
2351 << "vector_size" << AANT_ArgumentIntegerConstant
2352 << SizeExpr->getSourceRange();
2353 return QualType();
2354 }
2355
2356 if (CurType->isDependentType())
2357 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2359
2360 // vecSize is specified in bytes - convert to bits.
2361 if (!VecSize->isIntN(61)) {
2362 // Bit size will overflow uint64.
2363 Diag(AttrLoc, diag::err_attribute_size_too_large)
2364 << SizeExpr->getSourceRange() << "vector";
2365 return QualType();
2366 }
2367 uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2368 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2369
2370 if (VectorSizeBits == 0) {
2371 Diag(AttrLoc, diag::err_attribute_zero_size)
2372 << SizeExpr->getSourceRange() << "vector";
2373 return QualType();
2374 }
2375
2376 if (!TypeSize || VectorSizeBits % TypeSize) {
2377 Diag(AttrLoc, diag::err_attribute_invalid_size)
2378 << SizeExpr->getSourceRange();
2379 return QualType();
2380 }
2381
2382 if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2383 Diag(AttrLoc, diag::err_attribute_size_too_large)
2384 << SizeExpr->getSourceRange() << "vector";
2385 return QualType();
2386 }
2387
2388 return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2390}
2391
2393 SourceLocation AttrLoc) {
2394 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2395 // in conjunction with complex types (pointers, arrays, functions, etc.).
2396 //
2397 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2398 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2399 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2400 // of bool aren't allowed.
2401 //
2402 // We explicitly allow bool elements in ext_vector_type for C/C++.
2403 bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus;
2404 if ((!T->isDependentType() && !T->isIntegerType() &&
2405 !T->isRealFloatingType()) ||
2406 (IsNoBoolVecLang && T->isBooleanType())) {
2407 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2408 return QualType();
2409 }
2410
2411 if (const auto *BIT = T->getAs<BitIntType>();
2412 BIT && CheckBitIntElementType(*this, AttrLoc, BIT))
2413 return QualType();
2414
2415 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2416 std::optional<llvm::APSInt> vecSize =
2417 ArraySize->getIntegerConstantExpr(Context);
2418 if (!vecSize) {
2419 Diag(AttrLoc, diag::err_attribute_argument_type)
2420 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2421 << ArraySize->getSourceRange();
2422 return QualType();
2423 }
2424
2425 if (!vecSize->isIntN(32)) {
2426 Diag(AttrLoc, diag::err_attribute_size_too_large)
2427 << ArraySize->getSourceRange() << "vector";
2428 return QualType();
2429 }
2430 // Unlike gcc's vector_size attribute, the size is specified as the
2431 // number of elements, not the number of bytes.
2432 unsigned vectorSize = static_cast<unsigned>(vecSize->getZExtValue());
2433
2434 if (vectorSize == 0) {
2435 Diag(AttrLoc, diag::err_attribute_zero_size)
2436 << ArraySize->getSourceRange() << "vector";
2437 return QualType();
2438 }
2439
2440 return Context.getExtVectorType(T, vectorSize);
2441 }
2442
2443 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2444}
2445
2446QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2447 SourceLocation AttrLoc) {
2448 assert(Context.getLangOpts().MatrixTypes &&
2449 "Should never build a matrix type when it is disabled");
2450
2451 // Check element type, if it is not dependent.
2452 if (!ElementTy->isDependentType() &&
2453 !MatrixType::isValidElementType(ElementTy)) {
2454 Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2455 return QualType();
2456 }
2457
2458 if (const auto *BIT = ElementTy->getAs<BitIntType>();
2459 BIT &&
2460 CheckBitIntElementType(*this, AttrLoc, BIT, /*ForMatrixType=*/true))
2461 return QualType();
2462
2463 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2464 NumRows->isValueDependent() || NumCols->isValueDependent())
2465 return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2466 AttrLoc);
2467
2468 std::optional<llvm::APSInt> ValueRows =
2470 std::optional<llvm::APSInt> ValueColumns =
2472
2473 auto const RowRange = NumRows->getSourceRange();
2474 auto const ColRange = NumCols->getSourceRange();
2475
2476 // Both are row and column expressions are invalid.
2477 if (!ValueRows && !ValueColumns) {
2478 Diag(AttrLoc, diag::err_attribute_argument_type)
2479 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2480 << ColRange;
2481 return QualType();
2482 }
2483
2484 // Only the row expression is invalid.
2485 if (!ValueRows) {
2486 Diag(AttrLoc, diag::err_attribute_argument_type)
2487 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2488 return QualType();
2489 }
2490
2491 // Only the column expression is invalid.
2492 if (!ValueColumns) {
2493 Diag(AttrLoc, diag::err_attribute_argument_type)
2494 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2495 return QualType();
2496 }
2497
2498 // Check the matrix dimensions.
2499 unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2500 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2501 if (MatrixRows == 0 && MatrixColumns == 0) {
2502 Diag(AttrLoc, diag::err_attribute_zero_size)
2503 << "matrix" << RowRange << ColRange;
2504 return QualType();
2505 }
2506 if (MatrixRows == 0) {
2507 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2508 return QualType();
2509 }
2510 if (MatrixColumns == 0) {
2511 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2512 return QualType();
2513 }
2514 if (!ConstantMatrixType::isDimensionValid(MatrixRows)) {
2515 Diag(AttrLoc, diag::err_attribute_size_too_large)
2516 << RowRange << "matrix row";
2517 return QualType();
2518 }
2519 if (!ConstantMatrixType::isDimensionValid(MatrixColumns)) {
2520 Diag(AttrLoc, diag::err_attribute_size_too_large)
2521 << ColRange << "matrix column";
2522 return QualType();
2523 }
2524 return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2525}
2526
2528 if (T->isArrayType() || T->isFunctionType()) {
2529 Diag(Loc, diag::err_func_returning_array_function)
2530 << T->isFunctionType() << T;
2531 return true;
2532 }
2533
2534 // Functions cannot return half FP.
2535 if (T->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2537 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2539 return true;
2540 }
2541
2542 // Methods cannot return interface types. All ObjC objects are
2543 // passed by reference.
2544 if (T->isObjCObjectType()) {
2545 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2546 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2547 return true;
2548 }
2549
2550 if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2551 T.hasNonTrivialToPrimitiveCopyCUnion())
2554
2555 // C++2a [dcl.fct]p12:
2556 // A volatile-qualified return type is deprecated
2557 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2558 Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2559
2560 if (T.getAddressSpace() != LangAS::Default && getLangOpts().HLSL)
2561 return true;
2562 return false;
2563}
2564
2565/// Check the extended parameter information. Most of the necessary
2566/// checking should occur when applying the parameter attribute; the
2567/// only other checks required are positional restrictions.
2570 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2571 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2572
2573 bool emittedError = false;
2574 auto actualCC = EPI.ExtInfo.getCC();
2575 enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
2576 auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
2577 bool isCompatible =
2578 (required == RequiredCC::OnlySwift)
2579 ? (actualCC == CC_Swift)
2580 : (actualCC == CC_Swift || actualCC == CC_SwiftAsync);
2581 if (isCompatible || emittedError)
2582 return;
2583 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2585 << (required == RequiredCC::OnlySwift);
2586 emittedError = true;
2587 };
2588 for (size_t paramIndex = 0, numParams = paramTypes.size();
2589 paramIndex != numParams; ++paramIndex) {
2590 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2591 // Nothing interesting to check for orindary-ABI parameters.
2595 continue;
2596
2597 // swift_indirect_result parameters must be a prefix of the function
2598 // arguments.
2600 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2601 if (paramIndex != 0 &&
2602 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2604 S.Diag(getParamLoc(paramIndex),
2605 diag::err_swift_indirect_result_not_first);
2606 }
2607 continue;
2608
2610 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2611 continue;
2612
2613 // SwiftAsyncContext is not limited to swiftasynccall functions.
2615 continue;
2616
2617 // swift_error parameters must be preceded by a swift_context parameter.
2619 checkCompatible(paramIndex, RequiredCC::OnlySwift);
2620 if (paramIndex == 0 ||
2621 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2623 S.Diag(getParamLoc(paramIndex),
2624 diag::err_swift_error_result_not_after_swift_context);
2625 }
2626 continue;
2627 }
2628 llvm_unreachable("bad ABI kind");
2629 }
2630}
2631
2633 MutableArrayRef<QualType> ParamTypes,
2636 bool Invalid = false;
2637
2639
2640 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2641 // FIXME: Loc is too inprecise here, should use proper locations for args.
2642 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2643 if (ParamType->isVoidType()) {
2644 Diag(Loc, diag::err_param_with_void_type);
2645 Invalid = true;
2646 } else if (ParamType->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2648 // Disallow half FP arguments.
2649 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2651 Invalid = true;
2652 } else if (ParamType->isWebAssemblyTableType()) {
2653 Diag(Loc, diag::err_wasm_table_as_function_parameter);
2654 Invalid = true;
2655 }
2656
2657 // C++2a [dcl.fct]p4:
2658 // A parameter with volatile-qualified type is deprecated
2659 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
2660 Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
2661
2662 ParamTypes[Idx] = ParamType;
2663 }
2664
2665 if (EPI.ExtParameterInfos) {
2666 checkExtParameterInfos(*this, ParamTypes, EPI,
2667 [=](unsigned i) { return Loc; });
2668 }
2669
2670 if (EPI.ExtInfo.getProducesResult()) {
2671 // This is just a warning, so we can't fail to build if we see it.
2673 }
2674
2675 if (Invalid)
2676 return QualType();
2677
2678 return Context.getFunctionType(T, ParamTypes, EPI);
2679}
2680
2683 DeclarationName Entity) {
2684 // Verify that we're not building a pointer to pointer to function with
2685 // exception specification.
2687 Diag(Loc, diag::err_distant_exception_spec);
2688 return QualType();
2689 }
2690
2691 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2692 // with reference type, or "cv void."
2693 if (T->isReferenceType()) {
2694 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2695 << getPrintableNameForEntity(Entity) << T;
2696 return QualType();
2697 }
2698
2699 if (T->isVoidType()) {
2700 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2701 << getPrintableNameForEntity(Entity);
2702 return QualType();
2703 }
2704
2705 if (!Class->isDependentType() && !Class->isRecordType()) {
2706 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2707 return QualType();
2708 }
2709
2710 if (T->isFunctionType() && getLangOpts().OpenCL &&
2711 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2712 getLangOpts())) {
2713 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2714 return QualType();
2715 }
2716
2717 if (getLangOpts().HLSL && Loc.isValid()) {
2718 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
2719 return QualType();
2720 }
2721
2722 // Adjust the default free function calling convention to the default method
2723 // calling convention.
2724 bool IsCtorOrDtor =
2727 if (T->isFunctionType())
2728 adjustMemberFunctionCC(T, /*HasThisPointer=*/true, IsCtorOrDtor, Loc);
2729
2730 return Context.getMemberPointerType(T, Class.getTypePtr());
2731}
2732
2735 DeclarationName Entity) {
2736 if (!T->isFunctionType()) {
2737 Diag(Loc, diag::err_nonfunction_block_type);
2738 return QualType();
2739 }
2740
2741 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2742 return QualType();
2743
2744 if (getLangOpts().OpenCL)
2746
2748}
2749
2751 QualType QT = Ty.get();
2752 if (QT.isNull()) {
2753 if (TInfo) *TInfo = nullptr;
2754 return QualType();
2755 }
2756
2757 TypeSourceInfo *DI = nullptr;
2758 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2759 QT = LIT->getType();
2760 DI = LIT->getTypeSourceInfo();
2761 }
2762
2763 if (TInfo) *TInfo = DI;
2764 return QT;
2765}
2766
2767static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2768 Qualifiers::ObjCLifetime ownership,
2769 unsigned chunkIndex);
2770
2771/// Given that this is the declaration of a parameter under ARC,
2772/// attempt to infer attributes and such for pointer-to-whatever
2773/// types.
2774static void inferARCWriteback(TypeProcessingState &state,
2775 QualType &declSpecType) {
2776 Sema &S = state.getSema();
2777 Declarator &declarator = state.getDeclarator();
2778
2779 // TODO: should we care about decl qualifiers?
2780
2781 // Check whether the declarator has the expected form. We walk
2782 // from the inside out in order to make the block logic work.
2783 unsigned outermostPointerIndex = 0;
2784 bool isBlockPointer = false;
2785 unsigned numPointers = 0;
2786 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2787 unsigned chunkIndex = i;
2788 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2789 switch (chunk.Kind) {
2791 // Ignore parens.
2792 break;
2793
2796 // Count the number of pointers. Treat references
2797 // interchangeably as pointers; if they're mis-ordered, normal
2798 // type building will discover that.
2799 outermostPointerIndex = chunkIndex;
2800 numPointers++;
2801 break;
2802
2804 // If we have a pointer to block pointer, that's an acceptable
2805 // indirect reference; anything else is not an application of
2806 // the rules.
2807 if (numPointers != 1) return;
2808 numPointers++;
2809 outermostPointerIndex = chunkIndex;
2810 isBlockPointer = true;
2811
2812 // We don't care about pointer structure in return values here.
2813 goto done;
2814
2815 case DeclaratorChunk::Array: // suppress if written (id[])?
2819 return;
2820 }
2821 }
2822 done:
2823
2824 // If we have *one* pointer, then we want to throw the qualifier on
2825 // the declaration-specifiers, which means that it needs to be a
2826 // retainable object type.
2827 if (numPointers == 1) {
2828 // If it's not a retainable object type, the rule doesn't apply.
2829 if (!declSpecType->isObjCRetainableType()) return;
2830
2831 // If it already has lifetime, don't do anything.
2832 if (declSpecType.getObjCLifetime()) return;
2833
2834 // Otherwise, modify the type in-place.
2835 Qualifiers qs;
2836
2837 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2839 else
2841 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2842
2843 // If we have *two* pointers, then we want to throw the qualifier on
2844 // the outermost pointer.
2845 } else if (numPointers == 2) {
2846 // If we don't have a block pointer, we need to check whether the
2847 // declaration-specifiers gave us something that will turn into a
2848 // retainable object pointer after we slap the first pointer on it.
2849 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2850 return;
2851
2852 // Look for an explicit lifetime attribute there.
2853 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2854 if (chunk.Kind != DeclaratorChunk::Pointer &&
2856 return;
2857 for (const ParsedAttr &AL : chunk.getAttrs())
2858 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
2859 return;
2860
2862 outermostPointerIndex);
2863
2864 // Any other number of pointers/references does not trigger the rule.
2865 } else return;
2866
2867 // TODO: mark whether we did this inference?
2868}
2869
2870void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2871 SourceLocation FallbackLoc,
2872 SourceLocation ConstQualLoc,
2873 SourceLocation VolatileQualLoc,
2874 SourceLocation RestrictQualLoc,
2875 SourceLocation AtomicQualLoc,
2876 SourceLocation UnalignedQualLoc) {
2877 if (!Quals)
2878 return;
2879
2880 struct Qual {
2881 const char *Name;
2882 unsigned Mask;
2884 } const QualKinds[5] = {
2885 { "const", DeclSpec::TQ_const, ConstQualLoc },
2886 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2887 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2888 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2889 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2890 };
2891
2892 SmallString<32> QualStr;
2893 unsigned NumQuals = 0;
2895 FixItHint FixIts[5];
2896
2897 // Build a string naming the redundant qualifiers.
2898 for (auto &E : QualKinds) {
2899 if (Quals & E.Mask) {
2900 if (!QualStr.empty()) QualStr += ' ';
2901 QualStr += E.Name;
2902
2903 // If we have a location for the qualifier, offer a fixit.
2904 SourceLocation QualLoc = E.Loc;
2905 if (QualLoc.isValid()) {
2906 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2907 if (Loc.isInvalid() ||
2908 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2909 Loc = QualLoc;
2910 }
2911
2912 ++NumQuals;
2913 }
2914 }
2915
2916 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2917 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2918}
2919
2920// Diagnose pointless type qualifiers on the return type of a function.
2922 Declarator &D,
2923 unsigned FunctionChunkIndex) {
2925 D.getTypeObject(FunctionChunkIndex).Fun;
2926 if (FTI.hasTrailingReturnType()) {
2927 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2928 RetTy.getLocalCVRQualifiers(),
2930 return;
2931 }
2932
2933 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2934 End = D.getNumTypeObjects();
2935 OuterChunkIndex != End; ++OuterChunkIndex) {
2936 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2937 switch (OuterChunk.Kind) {
2939 continue;
2940
2942 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2944 diag::warn_qual_return_type,
2945 PTI.TypeQuals,
2947 PTI.ConstQualLoc,
2948 PTI.VolatileQualLoc,
2949 PTI.RestrictQualLoc,
2950 PTI.AtomicQualLoc,
2951 PTI.UnalignedQualLoc);
2952 return;
2953 }
2954
2961 // FIXME: We can't currently provide an accurate source location and a
2962 // fix-it hint for these.
2963 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2964 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2965 RetTy.getCVRQualifiers() | AtomicQual,
2966 D.getIdentifierLoc());
2967 return;
2968 }
2969
2970 llvm_unreachable("unknown declarator chunk kind");
2971 }
2972
2973 // If the qualifiers come from a conversion function type, don't diagnose
2974 // them -- they're not necessarily redundant, since such a conversion
2975 // operator can be explicitly called as "x.operator const int()".
2977 return;
2978
2979 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2980 // which are present there.
2981 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2982 D.getDeclSpec().getTypeQualifiers(),
2983 D.getIdentifierLoc(),
2984 D.getDeclSpec().getConstSpecLoc(),
2985 D.getDeclSpec().getVolatileSpecLoc(),
2986 D.getDeclSpec().getRestrictSpecLoc(),
2987 D.getDeclSpec().getAtomicSpecLoc(),
2988 D.getDeclSpec().getUnalignedSpecLoc());
2989}
2990
2991static std::pair<QualType, TypeSourceInfo *>
2992InventTemplateParameter(TypeProcessingState &state, QualType T,
2993 TypeSourceInfo *TrailingTSI, AutoType *Auto,
2995 Sema &S = state.getSema();
2996 Declarator &D = state.getDeclarator();
2997
2998 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
2999 const unsigned AutoParameterPosition = Info.TemplateParams.size();
3000 const bool IsParameterPack = D.hasEllipsis();
3001
3002 // If auto is mentioned in a lambda parameter or abbreviated function
3003 // template context, convert it to a template parameter type.
3004
3005 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3006 // template parameter type. Template parameters are temporarily added
3007 // to the TU until the associated TemplateDecl is created.
3008 TemplateTypeParmDecl *InventedTemplateParam =
3011 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3012 /*NameLoc=*/D.getIdentifierLoc(),
3013 TemplateParameterDepth, AutoParameterPosition,
3015 D.getIdentifier(), AutoParameterPosition), false,
3016 IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3017 InventedTemplateParam->setImplicit();
3018 Info.TemplateParams.push_back(InventedTemplateParam);
3019
3020 // Attach type constraints to the new parameter.
3021 if (Auto->isConstrained()) {
3022 if (TrailingTSI) {
3023 // The 'auto' appears in a trailing return type we've already built;
3024 // extract its type constraints to attach to the template parameter.
3025 AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3026 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3027 bool Invalid = false;
3028 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3029 if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3032 Invalid = true;
3033 TAL.addArgument(AutoLoc.getArgLoc(Idx));
3034 }
3035
3036 if (!Invalid) {
3038 AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3039 AutoLoc.getNamedConcept(), /*FoundDecl=*/AutoLoc.getFoundDecl(),
3040 AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3041 InventedTemplateParam,
3042 S.Context.getTypeDeclType(InventedTemplateParam),
3043 D.getEllipsisLoc());
3044 }
3045 } else {
3046 // The 'auto' appears in the decl-specifiers; we've not finished forming
3047 // TypeSourceInfo for it yet.
3048 TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId();
3049 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
3050 TemplateId->RAngleLoc);
3051 bool Invalid = false;
3052 if (TemplateId->LAngleLoc.isValid()) {
3053 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3054 TemplateId->NumArgs);
3055 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3056
3057 if (D.getEllipsisLoc().isInvalid()) {
3058 for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3061 Invalid = true;
3062 break;
3063 }
3064 }
3065 }
3066 }
3067 if (!Invalid) {
3068 UsingShadowDecl *USD =
3069 TemplateId->Template.get().getAsUsingShadowDecl();
3070 auto *CD =
3071 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl());
3073 D.getDeclSpec().getTypeSpecScope().getWithLocInContext(S.Context),
3075 TemplateId->TemplateNameLoc),
3076 CD,
3077 /*FoundDecl=*/
3078 USD ? cast<NamedDecl>(USD) : CD,
3079 TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3080 InventedTemplateParam,
3081 S.Context.getTypeDeclType(InventedTemplateParam),
3082 D.getEllipsisLoc());
3083 }
3084 }
3085 }
3086
3087 // Replace the 'auto' in the function parameter with this invented
3088 // template type parameter.
3089 // FIXME: Retain some type sugar to indicate that this was written
3090 // as 'auto'?
3091 QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3092 QualType NewT = state.ReplaceAutoType(T, Replacement);
3093 TypeSourceInfo *NewTSI =
3094 TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)
3095 : nullptr;
3096 return {NewT, NewTSI};
3097}
3098
3099static TypeSourceInfo *
3100GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3101 QualType T, TypeSourceInfo *ReturnTypeInfo);
3102
3103static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3104 TypeSourceInfo *&ReturnTypeInfo) {
3105 Sema &SemaRef = state.getSema();
3106 Declarator &D = state.getDeclarator();
3107 QualType T;
3108 ReturnTypeInfo = nullptr;
3109
3110 // The TagDecl owned by the DeclSpec.
3111 TagDecl *OwnedTagDecl = nullptr;
3112
3113 switch (D.getName().getKind()) {
3119 T = ConvertDeclSpecToType(state);
3120
3121 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3122 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3123 // Owned declaration is embedded in declarator.
3124 OwnedTagDecl->setEmbeddedInDeclarator(true);
3125 }
3126 break;
3127
3131 // Constructors and destructors don't have return types. Use
3132 // "void" instead.
3133 T = SemaRef.Context.VoidTy;
3135 D.getMutableDeclSpec().getAttributes());
3136 break;
3137
3139 // Deduction guides have a trailing return type and no type in their
3140 // decl-specifier sequence. Use a placeholder return type for now.
3141 T = SemaRef.Context.DependentTy;
3142 break;
3143
3145 // The result type of a conversion function is the type that it
3146 // converts to.
3147 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
3148 &ReturnTypeInfo);
3149 break;
3150 }
3151
3152 // Note: We don't need to distribute declaration attributes (i.e.
3153 // D.getDeclarationAttributes()) because those are always C++11 attributes,
3154 // and those don't get distributed.
3156 state, T, SemaRef.CUDA().IdentifyTarget(D.getAttributes()));
3157
3158 // Find the deduced type in this type. Look in the trailing return type if we
3159 // have one, otherwise in the DeclSpec type.
3160 // FIXME: The standard wording doesn't currently describe this.
3162 bool DeducedIsTrailingReturnType = false;
3163 if (Deduced && isa<AutoType>(Deduced) && D.hasTrailingReturnType()) {
3164 QualType T = SemaRef.GetTypeFromParser(D.getTrailingReturnType());
3165 Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3166 DeducedIsTrailingReturnType = true;
3167 }
3168
3169 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3170 if (Deduced) {
3171 AutoType *Auto = dyn_cast<AutoType>(Deduced);
3172 int Error = -1;
3173
3174 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3175 // class template argument deduction)?
3176 bool IsCXXAutoType =
3177 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3178 bool IsDeducedReturnType = false;
3179
3180 switch (D.getContext()) {
3182 // Declared return type of a lambda-declarator is implicit and is always
3183 // 'auto'.
3184 break;
3187 Error = 0;
3188 break;
3190 Error = 22;
3191 break;
3194 InventedTemplateParameterInfo *Info = nullptr;
3195 if (D.getContext() == DeclaratorContext::Prototype) {
3196 // With concepts we allow 'auto' in function parameters.
3197 if (!SemaRef.getLangOpts().CPlusPlus20 || !Auto ||
3198 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3199 Error = 0;
3200 break;
3201 } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3202 Error = 21;
3203 break;
3204 }
3205
3206 Info = &SemaRef.InventedParameterInfos.back();
3207 } else {
3208 // In C++14, generic lambdas allow 'auto' in their parameters.
3209 if (!SemaRef.getLangOpts().CPlusPlus14 && Auto &&
3210 Auto->getKeyword() == AutoTypeKeyword::Auto) {
3211 Error = 25; // auto not allowed in lambda parameter (before C++14)
3212 break;
3213 } else if (!Auto || Auto->getKeyword() != AutoTypeKeyword::Auto) {
3214 Error = 16; // __auto_type or decltype(auto) not allowed in lambda
3215 // parameter
3216 break;
3217 }
3218 Info = SemaRef.getCurLambda();
3219 assert(Info && "No LambdaScopeInfo on the stack!");
3220 }
3221
3222 // We'll deal with inventing template parameters for 'auto' in trailing
3223 // return types when we pick up the trailing return type when processing
3224 // the function chunk.
3225 if (!DeducedIsTrailingReturnType)
3226 T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3227 break;
3228 }
3230 if (D.isStaticMember() || D.isFunctionDeclarator())
3231 break;
3232 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3233 if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3234 Error = 6; // Interface member.
3235 } else {
3236 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3237 case TagTypeKind::Enum:
3238 llvm_unreachable("unhandled tag kind");
3240 Error = Cxx ? 1 : 2; /* Struct member */
3241 break;
3242 case TagTypeKind::Union:
3243 Error = Cxx ? 3 : 4; /* Union member */
3244 break;
3245 case TagTypeKind::Class:
3246 Error = 5; /* Class member */
3247 break;
3249 Error = 6; /* Interface member */
3250 break;
3251 }
3252 }
3253 if (D.getDeclSpec().isFriendSpecified())
3254 Error = 20; // Friend type
3255 break;
3256 }
3259 Error = 7; // Exception declaration
3260 break;
3262 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3263 !SemaRef.getLangOpts().CPlusPlus20)
3264 Error = 19; // Template parameter (until C++20)
3265 else if (!SemaRef.getLangOpts().CPlusPlus17)
3266 Error = 8; // Template parameter (until C++17)
3267 break;
3269 Error = 9; // Block literal
3270 break;
3272 // Within a template argument list, a deduced template specialization
3273 // type will be reinterpreted as a template template argument.
3274 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3275 !D.getNumTypeObjects() &&
3276 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier)
3277 break;
3278 [[fallthrough]];
3280 Error = 10; // Template type argument
3281 break;
3284 Error = 12; // Type alias
3285 break;
3288 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3289 Error = 13; // Function return type
3290 IsDeducedReturnType = true;
3291 break;
3293 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3294 Error = 14; // conversion-type-id
3295 IsDeducedReturnType = true;
3296 break;
3298 if (isa<DeducedTemplateSpecializationType>(Deduced))
3299 break;
3300 if (SemaRef.getLangOpts().CPlusPlus23 && IsCXXAutoType &&
3301 !Auto->isDecltypeAuto())
3302 break; // auto(x)
3303 [[fallthrough]];
3306 Error = 15; // Generic
3307 break;
3313 // FIXME: P0091R3 (erroneously) does not permit class template argument
3314 // deduction in conditions, for-init-statements, and other declarations
3315 // that are not simple-declarations.
3316 break;
3318 // FIXME: P0091R3 does not permit class template argument deduction here,
3319 // but we follow GCC and allow it anyway.
3320 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3321 Error = 17; // 'new' type
3322 break;
3324 Error = 18; // K&R function parameter
3325 break;
3326 }
3327
3328 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3329 Error = 11;
3330
3331 // In Objective-C it is an error to use 'auto' on a function declarator
3332 // (and everywhere for '__auto_type').
3333 if (D.isFunctionDeclarator() &&
3334 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3335 Error = 13;
3336
3337 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3339 AutoRange = D.getName().getSourceRange();
3340
3341 if (Error != -1) {
3342 unsigned Kind;
3343 if (Auto) {
3344 switch (Auto->getKeyword()) {
3345 case AutoTypeKeyword::Auto: Kind = 0; break;
3346 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3347 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3348 }
3349 } else {
3350 assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3351 "unknown auto type");
3352 Kind = 3;
3353 }
3354
3355 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3356 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3357
3358 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3359 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3360 << QualType(Deduced, 0) << AutoRange;
3361 if (auto *TD = TN.getAsTemplateDecl())
3362 SemaRef.NoteTemplateLocation(*TD);
3363
3364 T = SemaRef.Context.IntTy;
3365 D.setInvalidType(true);
3366 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) {
3367 // If there was a trailing return type, we already got
3368 // warn_cxx98_compat_trailing_return_type in the parser.
3369 SemaRef.Diag(AutoRange.getBegin(),
3371 ? diag::warn_cxx11_compat_generic_lambda
3372 : IsDeducedReturnType
3373 ? diag::warn_cxx11_compat_deduced_return_type
3374 : diag::warn_cxx98_compat_auto_type_specifier)
3375 << AutoRange;
3376 }
3377 }
3378
3379 if (SemaRef.getLangOpts().CPlusPlus &&
3380 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3381 // Check the contexts where C++ forbids the declaration of a new class
3382 // or enumeration in a type-specifier-seq.
3383 unsigned DiagID = 0;
3384 switch (D.getContext()) {
3387 // Class and enumeration definitions are syntactically not allowed in
3388 // trailing return types.
3389 llvm_unreachable("parser should not have allowed this");
3390 break;
3398 // C++11 [dcl.type]p3:
3399 // A type-specifier-seq shall not define a class or enumeration unless
3400 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3401 // the declaration of a template-declaration.
3403 break;
3405 DiagID = diag::err_type_defined_in_alias_template;
3406 break;
3417 DiagID = diag::err_type_defined_in_type_specifier;
3418 break;
3425 // C++ [dcl.fct]p6:
3426 // Types shall not be defined in return or parameter types.
3427 DiagID = diag::err_type_defined_in_param_type;
3428 break;
3430 // C++ 6.4p2:
3431 // The type-specifier-seq shall not contain typedef and shall not declare
3432 // a new class or enumeration.
3433 DiagID = diag::err_type_defined_in_condition;
3434 break;
3435 }
3436
3437 if (DiagID != 0) {
3438 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3439 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3440 D.setInvalidType(true);
3441 }
3442 }
3443
3444 assert(!T.isNull() && "This function should not return a null type");
3445 return T;
3446}
3447
3448/// Produce an appropriate diagnostic for an ambiguity between a function
3449/// declarator and a C++ direct-initializer.
3451 DeclaratorChunk &DeclType, QualType RT) {
3452 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3453 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3454
3455 // If the return type is void there is no ambiguity.
3456 if (RT->isVoidType())
3457 return;
3458
3459 // An initializer for a non-class type can have at most one argument.
3460 if (!RT->isRecordType() && FTI.NumParams > 1)
3461 return;
3462
3463 // An initializer for a reference must have exactly one argument.
3464 if (RT->isReferenceType() && FTI.NumParams != 1)
3465 return;
3466
3467 // Only warn if this declarator is declaring a function at block scope, and
3468 // doesn't have a storage class (such as 'extern') specified.
3469 if (!D.isFunctionDeclarator() ||
3470 D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration ||
3472 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified)
3473 return;
3474
3475 // Inside a condition, a direct initializer is not permitted. We allow one to
3476 // be parsed in order to give better diagnostics in condition parsing.
3477 if (D.getContext() == DeclaratorContext::Condition)
3478 return;
3479
3480 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3481
3482 S.Diag(DeclType.Loc,
3483 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3484 : diag::warn_empty_parens_are_function_decl)
3485 << ParenRange;
3486
3487 // If the declaration looks like:
3488 // T var1,
3489 // f();
3490 // and name lookup finds a function named 'f', then the ',' was
3491 // probably intended to be a ';'.
3492 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3493 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3494 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3495 if (Comma.getFileID() != Name.getFileID() ||
3496 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3497 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3499 if (S.LookupName(Result, S.getCurScope()))
3500 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3501 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3502 << D.getIdentifier();
3503 Result.suppressDiagnostics();
3504 }
3505 }
3506
3507 if (FTI.NumParams > 0) {
3508 // For a declaration with parameters, eg. "T var(T());", suggest adding
3509 // parens around the first parameter to turn the declaration into a
3510 // variable declaration.
3514 // FIXME: Maybe we should suggest adding braces instead of parens
3515 // in C++11 for classes that don't have an initializer_list constructor.
3516 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3519 } else {
3520 // For a declaration without parameters, eg. "T var();", suggest replacing
3521 // the parens with an initializer to turn the declaration into a variable
3522 // declaration.
3523 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3524
3525 // Empty parens mean value-initialization, and no parens mean
3526 // default initialization. These are equivalent if the default
3527 // constructor is user-provided or if zero-initialization is a
3528 // no-op.
3529 if (RD && RD->hasDefinition() &&
3531 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3532 << FixItHint::CreateRemoval(ParenRange);
3533 else {
3534 std::string Init =
3535 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3536 if (Init.empty() && S.LangOpts.CPlusPlus11)
3537 Init = "{}";
3538 if (!Init.empty())
3539 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3540 << FixItHint::CreateReplacement(ParenRange, Init);
3541 }
3542 }
3543}
3544
3545/// Produce an appropriate diagnostic for a declarator with top-level
3546/// parentheses.
3548 DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
3549 assert(Paren.Kind == DeclaratorChunk::Paren &&
3550 "do not have redundant top-level parentheses");
3551
3552 // This is a syntactic check; we're not interested in cases that arise
3553 // during template instantiation.
3555 return;
3556
3557 // Check whether this could be intended to be a construction of a temporary
3558 // object in C++ via a function-style cast.
3559 bool CouldBeTemporaryObject =
3560 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3561 !D.isInvalidType() && D.getIdentifier() &&
3562 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3563 (T->isRecordType() || T->isDependentType()) &&
3564 D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator();
3565
3566 bool StartsWithDeclaratorId = true;
3567 for (auto &C : D.type_objects()) {
3568 switch (C.Kind) {
3570 if (&C == &Paren)
3571 continue;
3572 [[fallthrough]];
3574 StartsWithDeclaratorId = false;
3575 continue;
3576
3578 if (!C.Arr.NumElts)
3579 CouldBeTemporaryObject = false;
3580 continue;
3581
3583 // FIXME: Suppress the warning here if there is no initializer; we're
3584 // going to give an error anyway.
3585 // We assume that something like 'T (&x) = y;' is highly likely to not
3586 // be intended to be a temporary object.
3587 CouldBeTemporaryObject = false;
3588 StartsWithDeclaratorId = false;
3589 continue;
3590
3592 // In a new-type-id, function chunks require parentheses.
3593 if (D.getContext() == DeclaratorContext::CXXNew)
3594 return;
3595 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3596 // redundant-parens warning, but we don't know whether the function
3597 // chunk was syntactically valid as an expression here.
3598 CouldBeTemporaryObject = false;
3599 continue;
3600
3604 // These cannot appear in expressions.
3605 CouldBeTemporaryObject = false;
3606 StartsWithDeclaratorId = false;
3607 continue;
3608 }
3609 }
3610
3611 // FIXME: If there is an initializer, assume that this is not intended to be
3612 // a construction of a temporary object.
3613
3614 // Check whether the name has already been declared; if not, this is not a
3615 // function-style cast.
3616 if (CouldBeTemporaryObject) {
3617 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3619 if (!S.LookupName(Result, S.getCurScope()))
3620 CouldBeTemporaryObject = false;
3621 Result.suppressDiagnostics();
3622 }
3623
3624 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3625
3626 if (!CouldBeTemporaryObject) {
3627 // If we have A (::B), the parentheses affect the meaning of the program.
3628 // Suppress the warning in that case. Don't bother looking at the DeclSpec
3629 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3630 // formally unambiguous.
3631 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3632 for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
3633 NNS = NNS->getPrefix()) {
3634 if (NNS->getKind() == NestedNameSpecifier::Global)
3635 return;
3636 }
3637 }
3638
3639 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3640 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3642 return;
3643 }
3644
3645 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3646 << ParenRange << D.getIdentifier();
3647 auto *RD = T->getAsCXXRecordDecl();
3648 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3649 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3650 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3651 << D.getIdentifier();
3652 // FIXME: A cast to void is probably a better suggestion in cases where it's
3653 // valid (when there is no initializer and we're not in a condition).
3654 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3657 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3660}
3661
3662/// Helper for figuring out the default CC for a function declarator type. If
3663/// this is the outermost chunk, then we can determine the CC from the
3664/// declarator context. If not, then this could be either a member function
3665/// type or normal function type.
3667 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3668 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3669 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3670
3671 // Check for an explicit CC attribute.
3672 for (const ParsedAttr &AL : AttrList) {
3673 switch (AL.getKind()) {
3675 // Ignore attributes that don't validate or can't apply to the
3676 // function type. We'll diagnose the failure to apply them in
3677 // handleFunctionTypeAttr.
3678 CallingConv CC;
3679 if (!S.CheckCallingConvAttr(AL, CC, /*FunctionDecl=*/nullptr,
3680 S.CUDA().IdentifyTarget(D.getAttributes())) &&
3681 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3682 return CC;
3683 }
3684 break;
3685 }
3686
3687 default:
3688 break;
3689 }
3690 }
3691
3692 bool IsCXXInstanceMethod = false;
3693
3694 if (S.getLangOpts().CPlusPlus) {
3695 // Look inwards through parentheses to see if this chunk will form a
3696 // member pointer type or if we're the declarator. Any type attributes
3697 // between here and there will override the CC we choose here.
3698 unsigned I = ChunkIndex;
3699 bool FoundNonParen = false;
3700 while (I && !FoundNonParen) {
3701 --I;
3702 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
3703 FoundNonParen = true;
3704 }
3705
3706 if (FoundNonParen) {
3707 // If we're not the declarator, we're a regular function type unless we're
3708 // in a member pointer.
3709 IsCXXInstanceMethod =
3710 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
3711 } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
3712 // This can only be a call operator for a lambda, which is an instance
3713 // method, unless explicitly specified as 'static'.
3714 IsCXXInstanceMethod =
3715 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static;
3716 } else {
3717 // We're the innermost decl chunk, so must be a function declarator.
3718 assert(D.isFunctionDeclarator());
3719
3720 // If we're inside a record, we're declaring a method, but it could be
3721 // explicitly or implicitly static.
3722 IsCXXInstanceMethod =
3723 D.isFirstDeclarationOfMember() &&
3724 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
3725 !D.isStaticMember();
3726 }
3727 }
3728
3730 IsCXXInstanceMethod);
3731
3732 // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3733 // and AMDGPU targets, hence it cannot be treated as a calling
3734 // convention attribute. This is the simplest place to infer
3735 // calling convention for OpenCL kernels.
3736 if (S.getLangOpts().OpenCL) {
3737 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3738 if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
3739 CC = CC_OpenCLKernel;
3740 break;
3741 }
3742 }
3743 } else if (S.getLangOpts().CUDA) {
3744 // If we're compiling CUDA/HIP code and targeting HIPSPV we need to make
3745 // sure the kernels will be marked with the right calling convention so that
3746 // they will be visible by the APIs that ingest SPIR-V. We do not do this
3747 // when targeting AMDGCNSPIRV, as it does not rely on OpenCL.
3748 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
3749 if (Triple.isSPIRV() && Triple.getVendor() != llvm::Triple::AMD) {
3750 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3751 if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) {
3752 CC = CC_OpenCLKernel;
3753 break;
3754 }
3755 }
3756 }
3757 }
3758
3759 return CC;
3760}
3761
3762namespace {
3763 /// A simple notion of pointer kinds, which matches up with the various
3764 /// pointer declarators.
3765 enum class SimplePointerKind {
3766 Pointer,
3767 BlockPointer,
3768 MemberPointer,
3769 Array,
3770 };
3771} // end anonymous namespace
3772
3774 switch (nullability) {
3776 if (!Ident__Nonnull)
3777 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3778 return Ident__Nonnull;
3779
3781 if (!Ident__Nullable)
3782 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3783 return Ident__Nullable;
3784
3786 if (!Ident__Nullable_result)
3787 Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
3788 return Ident__Nullable_result;
3789
3791 if (!Ident__Null_unspecified)
3792 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3793 return Ident__Null_unspecified;
3794 }
3795 llvm_unreachable("Unknown nullability kind.");
3796}
3797
3798/// Check whether there is a nullability attribute of any kind in the given
3799/// attribute list.
3800static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
3801 for (const ParsedAttr &AL : attrs) {
3802 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
3803 AL.getKind() == ParsedAttr::AT_TypeNullable ||
3804 AL.getKind() == ParsedAttr::AT_TypeNullableResult ||
3805 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
3806 return true;
3807 }
3808
3809 return false;
3810}
3811
3812namespace {
3813 /// Describes the kind of a pointer a declarator describes.
3814 enum class PointerDeclaratorKind {
3815 // Not a pointer.
3816 NonPointer,
3817 // Single-level pointer.
3818 SingleLevelPointer,
3819 // Multi-level pointer (of any pointer kind).
3820 MultiLevelPointer,
3821 // CFFooRef*
3822 MaybePointerToCFRef,
3823 // CFErrorRef*
3824 CFErrorRefPointer,
3825 // NSError**
3826 NSErrorPointerPointer,
3827 };
3828
3829 /// Describes a declarator chunk wrapping a pointer that marks inference as
3830 /// unexpected.
3831 // These values must be kept in sync with diagnostics.
3832 enum class PointerWrappingDeclaratorKind {
3833 /// Pointer is top-level.
3834 None = -1,
3835 /// Pointer is an array element.
3836 Array = 0,
3837 /// Pointer is the referent type of a C++ reference.
3838 Reference = 1
3839 };
3840} // end anonymous namespace
3841
3842/// Classify the given declarator, whose type-specified is \c type, based on
3843/// what kind of pointer it refers to.
3844///
3845/// This is used to determine the default nullability.
3846static PointerDeclaratorKind
3848 PointerWrappingDeclaratorKind &wrappingKind) {
3849 unsigned numNormalPointers = 0;
3850
3851 // For any dependent type, we consider it a non-pointer.
3852 if (type->isDependentType())
3853 return PointerDeclaratorKind::NonPointer;
3854
3855 // Look through the declarator chunks to identify pointers.
3856 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3857 DeclaratorChunk &chunk = declarator.getTypeObject(i);
3858 switch (chunk.Kind) {
3860 if (numNormalPointers == 0)
3861 wrappingKind = PointerWrappingDeclaratorKind::Array;
3862 break;
3863
3866 break;
3867
3870 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3871 : PointerDeclaratorKind::SingleLevelPointer;
3872
3874 break;
3875
3877 if (numNormalPointers == 0)
3878 wrappingKind = PointerWrappingDeclaratorKind::Reference;
3879 break;
3880
3882 ++numNormalPointers;
3883 if (numNormalPointers > 2)
3884 return PointerDeclaratorKind::MultiLevelPointer;
3885 break;
3886 }
3887 }
3888
3889 // Then, dig into the type specifier itself.
3890 unsigned numTypeSpecifierPointers = 0;
3891 do {
3892 // Decompose normal pointers.
3893 if (auto ptrType = type->getAs<PointerType>()) {
3894 ++numNormalPointers;
3895
3896 if (numNormalPointers > 2)
3897 return PointerDeclaratorKind::MultiLevelPointer;
3898
3899 type = ptrType->getPointeeType();
3900 ++numTypeSpecifierPointers;
3901 continue;
3902 }
3903
3904 // Decompose block pointers.
3905 if (type->getAs<BlockPointerType>()) {
3906 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3907 : PointerDeclaratorKind::SingleLevelPointer;
3908 }
3909
3910 // Decompose member pointers.
3911 if (type->getAs<MemberPointerType>()) {
3912 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3913 : PointerDeclaratorKind::SingleLevelPointer;
3914 }
3915
3916 // Look at Objective-C object pointers.
3917 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3918 ++numNormalPointers;
3919 ++numTypeSpecifierPointers;
3920
3921 // If this is NSError**, report that.
3922 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3923 if (objcClassDecl->getIdentifier() == S.ObjC().getNSErrorIdent() &&
3924 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3925 return PointerDeclaratorKind::NSErrorPointerPointer;
3926 }
3927 }
3928
3929 break;
3930 }
3931
3932 // Look at Objective-C class types.
3933 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3934 if (objcClass->getInterface()->getIdentifier() ==
3935 S.ObjC().getNSErrorIdent()) {
3936 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3937 return PointerDeclaratorKind::NSErrorPointerPointer;
3938 }
3939
3940 break;
3941 }
3942
3943 // If at this point we haven't seen a pointer, we won't see one.
3944 if (numNormalPointers == 0)
3945 return PointerDeclaratorKind::NonPointer;
3946
3947 if (auto recordType = type->getAs<RecordType>()) {
3948 RecordDecl *recordDecl = recordType->getDecl();
3949
3950 // If this is CFErrorRef*, report it as such.
3951 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 &&
3952 S.ObjC().isCFError(recordDecl)) {
3953 return PointerDeclaratorKind::CFErrorRefPointer;
3954 }
3955 break;
3956 }
3957
3958 break;
3959 } while (true);
3960
3961 switch (numNormalPointers) {
3962 case 0:
3963 return PointerDeclaratorKind::NonPointer;
3964
3965 case 1:
3966 return PointerDeclaratorKind::SingleLevelPointer;
3967
3968 case 2:
3969 return PointerDeclaratorKind::MaybePointerToCFRef;
3970
3971 default:
3972 return PointerDeclaratorKind::MultiLevelPointer;
3973 }
3974}
3975
3977 SourceLocation loc) {
3978 // If we're anywhere in a function, method, or closure context, don't perform
3979 // completeness checks.
3980 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
3981 if (ctx->isFunctionOrMethod())
3982 return FileID();
3983
3984 if (ctx->isFileContext())
3985 break;
3986 }
3987
3988 // We only care about the expansion location.
3989 loc = S.SourceMgr.getExpansionLoc(loc);
3990 FileID file = S.SourceMgr.getFileID(loc);
3991 if (file.isInvalid())
3992 return FileID();
3993
3994 // Retrieve file information.
3995 bool invalid = false;
3996 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
3997 if (invalid || !sloc.isFile())
3998 return FileID();
3999
4000 // We don't want to perform completeness checks on the main file or in
4001 // system headers.
4002 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4003 if (fileInfo.getIncludeLoc().isInvalid())
4004 return FileID();
4005 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4007 return FileID();
4008 }
4009
4010 return file;
4011}
4012
4013/// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4014/// taking into account whitespace before and after.
4015template <typename DiagBuilderT>
4016static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4017 SourceLocation PointerLoc,
4018 NullabilityKind Nullability) {
4019 assert(PointerLoc.isValid());
4020 if (PointerLoc.isMacroID())
4021 return;
4022
4023 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4024 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4025 return;
4026
4027 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4028 if (!NextChar)
4029 return;
4030
4031 SmallString<32> InsertionTextBuf{" "};
4032 InsertionTextBuf += getNullabilitySpelling(Nullability);
4033 InsertionTextBuf += " ";
4034 StringRef InsertionText = InsertionTextBuf.str();
4035
4036 if (isWhitespace(*NextChar)) {
4037 InsertionText = InsertionText.drop_back();
4038 } else if (NextChar[-1] == '[') {
4039 if (NextChar[0] == ']')
4040 InsertionText = InsertionText.drop_back().drop_front();
4041 else
4042 InsertionText = InsertionText.drop_front();
4043 } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) &&
4044 !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) {
4045 InsertionText = InsertionText.drop_back().drop_front();
4046 }
4047
4048 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4049}
4050
4052 SimplePointerKind PointerKind,
4053 SourceLocation PointerLoc,
4054 SourceLocation PointerEndLoc) {
4055 assert(PointerLoc.isValid());
4056
4057 if (PointerKind == SimplePointerKind::Array) {
4058 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4059 } else {
4060 S.Diag(PointerLoc, diag::warn_nullability_missing)
4061 << static_cast<unsigned>(PointerKind);
4062 }
4063
4064 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4065 if (FixItLoc.isMacroID())
4066 return;
4067
4068 auto addFixIt = [&](NullabilityKind Nullability) {
4069 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4070 Diag << static_cast<unsigned>(Nullability);
4071 Diag << static_cast<unsigned>(PointerKind);
4072 fixItNullability(S, Diag, FixItLoc, Nullability);
4073 };
4074 addFixIt(NullabilityKind::Nullable);
4075 addFixIt(NullabilityKind::NonNull);
4076}
4077
4078/// Complains about missing nullability if the file containing \p pointerLoc
4079/// has other uses of nullability (either the keywords or the \c assume_nonnull
4080/// pragma).
4081///
4082/// If the file has \e not seen other uses of nullability, this particular
4083/// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4084static void
4085checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4086 SourceLocation pointerLoc,
4087 SourceLocation pointerEndLoc = SourceLocation()) {
4088 // Determine which file we're performing consistency checking for.
4089 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4090 if (file.isInvalid())
4091 return;
4092
4093 // If we haven't seen any type nullability in this file, we won't warn now
4094 // about anything.
4095 FileNullability &fileNullability = S.NullabilityMap[file];
4096 if (!fileNullability.SawTypeNullability) {
4097 // If this is the first pointer declarator in the file, and the appropriate
4098 // warning is on, record it in case we need to diagnose it retroactively.
4099 diag::kind diagKind;
4100 if (pointerKind == SimplePointerKind::Array)
4101 diagKind = diag::warn_nullability_missing_array;
4102 else
4103 diagKind = diag::warn_nullability_missing;
4104
4105 if (fileNullability.PointerLoc.isInvalid() &&
4106 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
4107 fileNullability.PointerLoc = pointerLoc;
4108 fileNullability.PointerEndLoc = pointerEndLoc;
4109 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4110 }
4111
4112 return;
4113 }
4114
4115 // Complain about missing nullability.
4116 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4117}
4118
4119/// Marks that a nullability feature has been used in the file containing
4120/// \p loc.
4121///
4122/// If this file already had pointer types in it that were missing nullability,
4123/// the first such instance is retroactively diagnosed.
4124///
4125/// \sa checkNullabilityConsistency
4128 if (file.isInvalid())
4129 return;
4130
4131 FileNullability &fileNullability = S.NullabilityMap[file];
4132 if (fileNullability.SawTypeNullability)
4133 return;
4134 fileNullability.SawTypeNullability = true;
4135
4136 // If we haven't seen any type nullability before, now we have. Retroactively
4137 // diagnose the first unannotated pointer, if there was one.
4138 if (fileNullability.PointerLoc.isInvalid())
4139 return;
4140
4141 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4142 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
4143 fileNullability.PointerEndLoc);
4144}
4145
4146/// Returns true if any of the declarator chunks before \p endIndex include a
4147/// level of indirection: array, pointer, reference, or pointer-to-member.
4148///
4149/// Because declarator chunks are stored in outer-to-inner order, testing
4150/// every chunk before \p endIndex is testing all chunks that embed the current
4151/// chunk as part of their type.
4152///
4153/// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4154/// end index, in which case all chunks are tested.
4155static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4156 unsigned i = endIndex;
4157 while (i != 0) {
4158 // Walk outwards along the declarator chunks.
4159 --i;
4160 const DeclaratorChunk &DC = D.getTypeObject(i);
4161 switch (DC.Kind) {
4163 break;
4168 return true;
4172 // These are invalid anyway, so just ignore.
4173 break;
4174 }
4175 }
4176 return false;
4177}
4178
4179static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk) {
4180 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4181 Chunk.Kind == DeclaratorChunk::Array);
4182}
4183
4184template<typename AttrT>
4185static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4186 AL.setUsedAsTypeAttr();
4187 return ::new (Ctx) AttrT(Ctx, AL);
4188}
4189
4191 NullabilityKind NK) {
4192 switch (NK) {
4194 return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
4195
4197 return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
4198
4200 return createSimpleAttr<TypeNullableResultAttr>(Ctx, Attr);
4201
4203 return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
4204 }
4205 llvm_unreachable("unknown NullabilityKind");
4206}
4207
4208// Diagnose whether this is a case with the multiple addr spaces.
4209// Returns true if this is an invalid case.
4210// ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4211// by qualifiers for two or more different address spaces."
4213 LangAS ASNew,
4214 SourceLocation AttrLoc) {
4215 if (ASOld != LangAS::Default) {
4216 if (ASOld != ASNew) {
4217 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4218 return true;
4219 }
4220 // Emit a warning if they are identical; it's likely unintended.
4221 S.Diag(AttrLoc,
4222 diag::warn_attribute_address_multiple_identical_qualifiers);
4223 }
4224 return false;
4225}
4226
4227// Whether this is a type broadly expected to have nullability attached.
4228// These types are affected by `#pragma assume_nonnull`, and missing nullability
4229// will be diagnosed with -Wnullability-completeness.
4231 return T->canHaveNullability(/*ResultIfUnknown=*/false) &&
4232 // For now, do not infer/require nullability on C++ smart pointers.
4233 // It's unclear whether the pragma's behavior is useful for C++.
4234 // e.g. treating type-aliases and template-type-parameters differently
4235 // from types of declarations can be surprising.
4236 !isa<RecordType, TemplateSpecializationType>(
4238}
4239
4240static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4241 QualType declSpecType,
4242 TypeSourceInfo *TInfo) {
4243 // The TypeSourceInfo that this function returns will not be a null type.
4244 // If there is an error, this function will fill in a dummy type as fallback.
4245 QualType T = declSpecType;
4246 Declarator &D = state.getDeclarator();
4247 Sema &S = state.getSema();
4248 ASTContext &Context = S.Context;
4249 const LangOptions &LangOpts = S.getLangOpts();
4250
4251 // The name we're declaring, if any.
4252 DeclarationName Name;
4253 if (D.getIdentifier())
4254 Name = D.getIdentifier();
4255
4256 // Does this declaration declare a typedef-name?
4257 bool IsTypedefName =
4258 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
4259 D.getContext() == DeclaratorContext::AliasDecl ||
4260 D.getContext() == DeclaratorContext::AliasTemplate;
4261
4262 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4263 bool IsQualifiedFunction = T->isFunctionProtoType() &&
4264 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4265 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4266
4267 // If T is 'decltype(auto)', the only declarators we can have are parens
4268 // and at most one function declarator if this is a function declaration.
4269 // If T is a deduced class template specialization type, we can have no
4270 // declarator chunks at all.
4271 if (auto *DT = T->getAs<DeducedType>()) {
4272 const AutoType *AT = T->getAs<AutoType>();
4273 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4274 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4275 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4276 unsigned Index = E - I - 1;
4277 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4278 unsigned DiagId = IsClassTemplateDeduction
4279 ? diag::err_deduced_class_template_compound_type
4280 : diag::err_decltype_auto_compound_type;
4281 unsigned DiagKind = 0;
4282 switch (DeclChunk.Kind) {
4284 // FIXME: Rejecting this is a little silly.
4285 if (IsClassTemplateDeduction) {
4286 DiagKind = 4;
4287 break;
4288 }
4289 continue;
4291 if (IsClassTemplateDeduction) {
4292 DiagKind = 3;
4293 break;
4294 }
4295 unsigned FnIndex;
4296 if (D.isFunctionDeclarationContext() &&
4297 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4298 continue;
4299 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4300 break;
4301 }
4305 DiagKind = 0;
4306 break;
4308 DiagKind = 1;
4309 break;
4311 DiagKind = 2;
4312 break;
4314 break;
4315 }
4316
4317 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4318 D.setInvalidType(true);
4319 break;
4320 }
4321 }
4322 }
4323
4324 // Determine whether we should infer _Nonnull on pointer types.
4325 std::optional<NullabilityKind> inferNullability;
4326 bool inferNullabilityCS = false;
4327 bool inferNullabilityInnerOnly = false;
4328 bool inferNullabilityInnerOnlyComplete = false;
4329
4330 // Are we in an assume-nonnull region?
4331 bool inAssumeNonNullRegion = false;
4332 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4333 if (assumeNonNullLoc.isValid()) {
4334 inAssumeNonNullRegion = true;
4335 recordNullabilitySeen(S, assumeNonNullLoc);
4336 }
4337
4338 // Whether to complain about missing nullability specifiers or not.
4339 enum {
4340 /// Never complain.
4341 CAMN_No,
4342 /// Complain on the inner pointers (but not the outermost
4343 /// pointer).
4344 CAMN_InnerPointers,
4345 /// Complain about any pointers that don't have nullability
4346 /// specified or inferred.
4347 CAMN_Yes
4348 } complainAboutMissingNullability = CAMN_No;
4349 unsigned NumPointersRemaining = 0;
4350 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4351
4352 if (IsTypedefName) {
4353 // For typedefs, we do not infer any nullability (the default),
4354 // and we only complain about missing nullability specifiers on
4355 // inner pointers.
4356 complainAboutMissingNullability = CAMN_InnerPointers;
4357
4359 // Note that we allow but don't require nullability on dependent types.
4360 ++NumPointersRemaining;
4361 }
4362
4363 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4364 DeclaratorChunk &chunk = D.getTypeObject(i);
4365 switch (chunk.Kind) {
4369 break;
4370
4373 ++NumPointersRemaining;
4374 break;
4375
4378 continue;
4379
4381 ++NumPointersRemaining;
4382 continue;
4383 }
4384 }
4385 } else {
4386 bool isFunctionOrMethod = false;
4387 switch (auto context = state.getDeclarator().getContext()) {
4393 isFunctionOrMethod = true;
4394 [[fallthrough]];
4395
4397 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4398 complainAboutMissingNullability = CAMN_No;
4399 break;
4400 }
4401
4402 // Weak properties are inferred to be nullable.
4403 if (state.getDeclarator().isObjCWeakProperty()) {
4404 // Weak properties cannot be nonnull, and should not complain about
4405 // missing nullable attributes during completeness checks.
4406 complainAboutMissingNullability = CAMN_No;
4407 if (inAssumeNonNullRegion) {
4408 inferNullability = NullabilityKind::Nullable;
4409 }
4410 break;
4411 }
4412
4413 [[fallthrough]];
4414
4417 complainAboutMissingNullability = CAMN_Yes;
4418
4419 // Nullability inference depends on the type and declarator.
4420 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4421 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4422 case PointerDeclaratorKind::NonPointer:
4423 case PointerDeclaratorKind::MultiLevelPointer:
4424 // Cannot infer nullability.
4425 break;
4426
4427 case PointerDeclaratorKind::SingleLevelPointer:
4428 // Infer _Nonnull if we are in an assumes-nonnull region.
4429 if (inAssumeNonNullRegion) {
4430 complainAboutInferringWithinChunk = wrappingKind;
4431 inferNullability = NullabilityKind::NonNull;
4432 inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4434 }
4435 break;
4436
4437 case PointerDeclaratorKind::CFErrorRefPointer:
4438 case PointerDeclaratorKind::NSErrorPointerPointer:
4439 // Within a function or method signature, infer _Nullable at both
4440 // levels.
4441 if (isFunctionOrMethod && inAssumeNonNullRegion)
4442 inferNullability = NullabilityKind::Nullable;
4443 break;
4444
4445 case PointerDeclaratorKind::MaybePointerToCFRef:
4446 if (isFunctionOrMethod) {
4447 // On pointer-to-pointer parameters marked cf_returns_retained or
4448 // cf_returns_not_retained, if the outer pointer is explicit then
4449 // infer the inner pointer as _Nullable.
4450 auto hasCFReturnsAttr =
4451 [](const ParsedAttributesView &AttrList) -> bool {
4452 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4453 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4454 };
4455 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4456 if (hasCFReturnsAttr(D.getDeclarationAttributes()) ||
4457 hasCFReturnsAttr(D.getAttributes()) ||
4458 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4459 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4460 inferNullability = NullabilityKind::Nullable;
4461 inferNullabilityInnerOnly = true;
4462 }
4463 }
4464 }
4465 break;
4466 }
4467 break;
4468 }
4469
4471 complainAboutMissingNullability = CAMN_Yes;
4472 break;
4473
4493 // Don't infer in these contexts.
4494 break;
4495 }
4496 }
4497
4498 // Local function that returns true if its argument looks like a va_list.
4499 auto isVaList = [&S](QualType T) -> bool {
4500 auto *typedefTy = T->getAs<TypedefType>();
4501 if (!typedefTy)
4502 return false;
4503 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4504 do {
4505 if (typedefTy->getDecl() == vaListTypedef)
4506 return true;
4507 if (auto *name = typedefTy->getDecl()->getIdentifier())
4508 if (name->isStr("va_list"))
4509 return true;
4510 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4511 } while (typedefTy);
4512 return false;
4513 };
4514
4515 // Local function that checks the nullability for a given pointer declarator.
4516 // Returns true if _Nonnull was inferred.
4517 auto inferPointerNullability =
4518 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4519 SourceLocation pointerEndLoc,
4520 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4521 // We've seen a pointer.
4522 if (NumPointersRemaining > 0)
4523 --NumPointersRemaining;
4524
4525 // If a nullability attribute is present, there's nothing to do.
4526 if (hasNullabilityAttr(attrs))
4527 return nullptr;
4528
4529 // If we're supposed to infer nullability, do so now.
4530 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4531 ParsedAttr::Form form =
4532 inferNullabilityCS
4533 ? ParsedAttr::Form::ContextSensitiveKeyword()
4534 : ParsedAttr::Form::Keyword(false /*IsAlignAs*/,
4535 false /*IsRegularKeywordAttribute*/);
4536 ParsedAttr *nullabilityAttr = Pool.create(
4537 S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4538 nullptr, SourceLocation(), nullptr, 0, form);
4539
4540 attrs.addAtEnd(nullabilityAttr);
4541
4542 if (inferNullabilityCS) {
4543 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4544 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4545 }
4546
4547 if (pointerLoc.isValid() &&
4548 complainAboutInferringWithinChunk !=
4549 PointerWrappingDeclaratorKind::None) {
4550 auto Diag =
4551 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4552 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4554 }
4555
4556 if (inferNullabilityInnerOnly)
4557 inferNullabilityInnerOnlyComplete = true;
4558 return nullabilityAttr;
4559 }
4560
4561 // If we're supposed to complain about missing nullability, do so
4562 // now if it's truly missing.
4563 switch (complainAboutMissingNullability) {
4564 case CAMN_No:
4565 break;
4566
4567 case CAMN_InnerPointers:
4568 if (NumPointersRemaining == 0)
4569 break;
4570 [[fallthrough]];
4571
4572 case CAMN_Yes:
4573 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4574 }
4575 return nullptr;
4576 };
4577
4578 // If the type itself could have nullability but does not, infer pointer
4579 // nullability and perform consistency checking.
4580 if (S.CodeSynthesisContexts.empty()) {
4582 if (isVaList(T)) {
4583 // Record that we've seen a pointer, but do nothing else.
4584 if (NumPointersRemaining > 0)
4585 --NumPointersRemaining;
4586 } else {
4587 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4588 if (T->isBlockPointerType())
4589 pointerKind = SimplePointerKind::BlockPointer;
4590 else if (T->isMemberPointerType())
4591 pointerKind = SimplePointerKind::MemberPointer;
4592
4593 if (auto *attr = inferPointerNullability(
4594 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4595 D.getDeclSpec().getEndLoc(),
4596 D.getMutableDeclSpec().getAttributes(),
4597 D.getMutableDeclSpec().getAttributePool())) {
4598 T = state.getAttributedType(
4599 createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4600 }
4601 }
4602 }
4603
4604 if (complainAboutMissingNullability == CAMN_Yes && T->isArrayType() &&
4605 !T->getNullability() && !isVaList(T) && D.isPrototypeContext() &&
4606 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
4607 checkNullabilityConsistency(S, SimplePointerKind::Array,
4608 D.getDeclSpec().getTypeSpecTypeLoc());
4609 }
4610 }
4611
4612 bool ExpectNoDerefChunk =
4613 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4614
4615 // Walk the DeclTypeInfo, building the recursive type as we go.
4616 // DeclTypeInfos are ordered from the identifier out, which is
4617 // opposite of what we want :).
4618
4619 // Track if the produced type matches the structure of the declarator.
4620 // This is used later to decide if we can fill `TypeLoc` from
4621 // `DeclaratorChunk`s. E.g. it must be false if Clang recovers from
4622 // an error by replacing the type with `int`.
4623 bool AreDeclaratorChunksValid = true;
4624 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4625 unsigned chunkIndex = e - i - 1;
4626 state.setCurrentChunkIndex(chunkIndex);
4627 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4628 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4629 switch (DeclType.Kind) {
4631 if (i == 0)
4633 T = S.BuildParenType(T);
4634 break;
4636 // If blocks are disabled, emit an error.
4637 if (!LangOpts.Blocks)
4638 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4639
4640 // Handle pointer nullability.
4641 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4642 DeclType.EndLoc, DeclType.getAttrs(),
4643 state.getDeclarator().getAttributePool());
4644
4645 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4646 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4647 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4648 // qualified with const.
4649 if (LangOpts.OpenCL)
4650 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4651 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4652 }
4653 break;
4655 // Verify that we're not building a pointer to pointer to function with
4656 // exception specification.
4657 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4658 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4659 D.setInvalidType(true);
4660 // Build the type anyway.
4661 }
4662
4663 // Handle pointer nullability
4664 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4665 DeclType.EndLoc, DeclType.getAttrs(),
4666 state.getDeclarator().getAttributePool());
4667
4668 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
4669 T = Context.getObjCObjectPointerType(T);
4670 if (DeclType.Ptr.TypeQuals)
4671 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4672 break;
4673 }
4674
4675 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4676 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4677 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4678 if (LangOpts.OpenCL) {
4679 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4680 T->isBlockPointerType()) {
4681 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4682 D.setInvalidType(true);
4683 }
4684 }
4685
4686 T = S.BuildPointerType(T, DeclType.Loc, Name);
4687 if (DeclType.Ptr.TypeQuals)
4688 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4689 break;
4691 // Verify that we're not building a reference to pointer to function with
4692 // exception specification.
4693 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4694 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4695 D.setInvalidType(true);
4696 // Build the type anyway.
4697 }
4698 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4699
4700 if (DeclType.Ref.HasRestrict)
4702 break;
4703 }
4705 // Verify that we're not building an array of pointers to function with
4706 // exception specification.
4707 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4708 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4709 D.setInvalidType(true);
4710 // Build the type anyway.
4711 }
4712 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4713 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4715
4716 // Microsoft property fields can have multiple sizeless array chunks
4717 // (i.e. int x[][][]). Skip all of these except one to avoid creating
4718 // bad incomplete array types.
4719 if (chunkIndex != 0 && !ArraySize &&
4720 D.getDeclSpec().getAttributes().hasMSPropertyAttr()) {
4721 // This is a sizeless chunk. If the next is also, skip this one.
4722 DeclaratorChunk &NextDeclType = D.getTypeObject(chunkIndex - 1);
4723 if (NextDeclType.Kind == DeclaratorChunk::Array &&
4724 !NextDeclType.Arr.NumElts)
4725 break;
4726 }
4727
4728 if (ATI.isStar)
4730 else if (ATI.hasStatic)
4732 else
4734 if (ASM == ArraySizeModifier::Star && !D.isPrototypeContext()) {
4735 // FIXME: This check isn't quite right: it allows star in prototypes
4736 // for function definitions, and disallows some edge cases detailed
4737 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4738 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4740 D.setInvalidType(true);
4741 }
4742
4743 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4744 // shall appear only in a declaration of a function parameter with an
4745 // array type, ...
4746 if (ASM == ArraySizeModifier::Static || ATI.TypeQuals) {
4747 if (!(D.isPrototypeContext() ||
4748 D.getContext() == DeclaratorContext::KNRTypeList)) {
4749 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype)
4750 << (ASM == ArraySizeModifier::Static ? "'static'"
4751 : "type qualifier");
4752 // Remove the 'static' and the type qualifiers.
4753 if (ASM == ArraySizeModifier::Static)
4755 ATI.TypeQuals = 0;
4756 D.setInvalidType(true);
4757 }
4758
4759 // C99 6.7.5.2p1: ... and then only in the outermost array type
4760 // derivation.
4761 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4762 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost)
4763 << (ASM == ArraySizeModifier::Static ? "'static'"
4764 : "type qualifier");
4765 if (ASM == ArraySizeModifier::Static)
4767 ATI.TypeQuals = 0;
4768 D.setInvalidType(true);
4769 }
4770 }
4771
4772 // Array parameters can be marked nullable as well, although it's not
4773 // necessary if they're marked 'static'.
4774 if (complainAboutMissingNullability == CAMN_Yes &&
4775 !hasNullabilityAttr(DeclType.getAttrs()) &&
4776 ASM != ArraySizeModifier::Static && D.isPrototypeContext() &&
4777 !hasOuterPointerLikeChunk(D, chunkIndex)) {
4778 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4779 }
4780
4781 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4782 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4783 break;
4784 }
4786 // If the function declarator has a prototype (i.e. it is not () and
4787 // does not have a K&R-style identifier list), then the arguments are part
4788 // of the type, otherwise the argument list is ().
4789 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4790 IsQualifiedFunction =
4792
4793 // Check for auto functions and trailing return type and adjust the
4794 // return type accordingly.
4795 if (!D.isInvalidType()) {
4796 auto IsClassType = [&](CXXScopeSpec &SS) {
4797 // If there already was an problem with the scope, don’t issue another
4798 // error about the explicit object parameter.
4799 return SS.isInvalid() ||
4800 isa_and_present<CXXRecordDecl>(S.computeDeclContext(SS));
4801 };
4802
4803 // C++23 [dcl.fct]p6:
4804 //
4805 // An explicit-object-parameter-declaration is a parameter-declaration
4806 // with a this specifier. An explicit-object-parameter-declaration shall
4807 // appear only as the first parameter-declaration of a
4808 // parameter-declaration-list of one of:
4809 //
4810 // - a declaration of a member function or member function template
4811 // ([class.mem]), or
4812 //
4813 // - an explicit instantiation ([temp.explicit]) or explicit
4814 // specialization ([temp.expl.spec]) of a templated member function,
4815 // or
4816 //
4817 // - a lambda-declarator [expr.prim.lambda].
4818 DeclaratorContext C = D.getContext();
4820 FTI.NumParams
4821 ? dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param)
4822 : nullptr;
4823
4824 bool IsFunctionDecl = D.getInnermostNonParenChunk() == &DeclType;
4825 if (First && First->isExplicitObjectParameter() &&
4827
4828 // Either not a member or nested declarator in a member.
4829 //
4830 // Note that e.g. 'static' or 'friend' declarations are accepted
4831 // here; we diagnose them later when we build the member function
4832 // because it's easier that way.
4833 (C != DeclaratorContext::Member || !IsFunctionDecl) &&
4834
4835 // Allow out-of-line definitions of member functions.
4836 !IsClassType(D.getCXXScopeSpec())) {
4837 if (IsFunctionDecl)
4838 S.Diag(First->getBeginLoc(),
4839 diag::err_explicit_object_parameter_nonmember)
4840 << /*non-member*/ 2 << /*function*/ 0
4841 << First->getSourceRange();
4842 else
4843 S.Diag(First->getBeginLoc(),
4844 diag::err_explicit_object_parameter_invalid)
4845 << First->getSourceRange();
4846
4847 D.setInvalidType();
4848 AreDeclaratorChunksValid = false;
4849 }