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