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