clang 23.0.0git
SemaType.cpp
Go to the documentation of this file.
1//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements type-related semantic analysis.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclObjC.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprObjC.h"
25#include "clang/AST/Type.h"
26#include "clang/AST/TypeLoc.h"
33#include "clang/Sema/DeclSpec.h"
35#include "clang/Sema/Lookup.h"
39#include "clang/Sema/SemaCUDA.h"
40#include "clang/Sema/SemaHLSL.h"
41#include "clang/Sema/SemaObjC.h"
43#include "clang/Sema/Template.h"
45#include "llvm/ADT/ArrayRef.h"
46#include "llvm/ADT/STLForwardCompat.h"
47#include "llvm/ADT/StringExtras.h"
48#include "llvm/IR/DerivedTypes.h"
49#include "llvm/Support/ErrorHandling.h"
50#include <bitset>
51#include <optional>
52
53using namespace clang;
54
60
61/// isOmittedBlockReturnType - Return true if this declarator is missing a
62/// return type because this is a omitted return type on a block literal.
63static bool isOmittedBlockReturnType(const Declarator &D) {
66 return false;
67
68 if (D.getNumTypeObjects() == 0)
69 return true; // ^{ ... }
70
71 if (D.getNumTypeObjects() == 1 &&
73 return true; // ^(int X, float Y) { ... }
74
75 return false;
76}
77
78/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
79/// doesn't apply to the given type.
81 QualType type) {
82 TypeDiagSelector WhichType;
83 bool useExpansionLoc = true;
84 switch (attr.getKind()) {
85 case ParsedAttr::AT_ObjCGC:
86 WhichType = TDS_Pointer;
87 break;
88 case ParsedAttr::AT_ObjCOwnership:
89 WhichType = TDS_ObjCObjOrBlock;
90 break;
91 default:
92 // Assume everything else was a function attribute.
93 WhichType = TDS_Function;
94 useExpansionLoc = false;
95 break;
96 }
97
98 SourceLocation loc = attr.getLoc();
99 StringRef name = attr.getAttrName()->getName();
100
101 // The GC attributes are usually written with macros; special-case them.
102 IdentifierInfo *II =
103 attr.isArgIdent(0) ? attr.getArgAsIdent(0)->getIdentifierInfo() : nullptr;
104 if (useExpansionLoc && loc.isMacroID() && II) {
105 if (II->isStr("strong")) {
106 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
107 } else if (II->isStr("weak")) {
108 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
109 }
110 }
111
112 S.Diag(loc, attr.isRegularKeywordAttribute()
113 ? diag::err_type_attribute_wrong_type
114 : diag::warn_type_attribute_wrong_type)
115 << name << WhichType << type;
116}
117
118// objc_gc applies to Objective-C pointers or, otherwise, to the
119// smallest available pointer type (i.e. 'void*' in 'void**').
120#define OBJC_POINTER_TYPE_ATTRS_CASELIST \
121 case ParsedAttr::AT_ObjCGC: \
122 case ParsedAttr::AT_ObjCOwnership
123
124// Calling convention attributes.
125#define CALLING_CONV_ATTRS_CASELIST \
126 case ParsedAttr::AT_CDecl: \
127 case ParsedAttr::AT_FastCall: \
128 case ParsedAttr::AT_StdCall: \
129 case ParsedAttr::AT_ThisCall: \
130 case ParsedAttr::AT_RegCall: \
131 case ParsedAttr::AT_Pascal: \
132 case ParsedAttr::AT_SwiftCall: \
133 case ParsedAttr::AT_SwiftAsyncCall: \
134 case ParsedAttr::AT_VectorCall: \
135 case ParsedAttr::AT_AArch64VectorPcs: \
136 case ParsedAttr::AT_AArch64SVEPcs: \
137 case ParsedAttr::AT_MSABI: \
138 case ParsedAttr::AT_SysVABI: \
139 case ParsedAttr::AT_Pcs: \
140 case ParsedAttr::AT_IntelOclBicc: \
141 case ParsedAttr::AT_PreserveMost: \
142 case ParsedAttr::AT_PreserveAll: \
143 case ParsedAttr::AT_M68kRTD: \
144 case ParsedAttr::AT_PreserveNone: \
145 case ParsedAttr::AT_RISCVVectorCC: \
146 case ParsedAttr::AT_RISCVVLSCC
147
148// Function type attributes.
149#define FUNCTION_TYPE_ATTRS_CASELIST \
150 case ParsedAttr::AT_NSReturnsRetained: \
151 case ParsedAttr::AT_NoReturn: \
152 case ParsedAttr::AT_NonBlocking: \
153 case ParsedAttr::AT_NonAllocating: \
154 case ParsedAttr::AT_Blocking: \
155 case ParsedAttr::AT_Allocating: \
156 case ParsedAttr::AT_Regparm: \
157 case ParsedAttr::AT_CFIUncheckedCallee: \
158 case ParsedAttr::AT_CFISalt: \
159 case ParsedAttr::AT_CmseNSCall: \
160 case ParsedAttr::AT_ArmStreaming: \
161 case ParsedAttr::AT_ArmStreamingCompatible: \
162 case ParsedAttr::AT_ArmPreserves: \
163 case ParsedAttr::AT_ArmIn: \
164 case ParsedAttr::AT_ArmOut: \
165 case ParsedAttr::AT_ArmInOut: \
166 case ParsedAttr::AT_ArmAgnostic: \
167 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
168 case ParsedAttr::AT_AnyX86NoCfCheck: \
169 CALLING_CONV_ATTRS_CASELIST
170
171// Microsoft-specific type qualifiers.
172#define MS_TYPE_ATTRS_CASELIST \
173 case ParsedAttr::AT_Ptr32: \
174 case ParsedAttr::AT_Ptr64: \
175 case ParsedAttr::AT_SPtr: \
176 case ParsedAttr::AT_UPtr
177
178// Nullability qualifiers.
179#define NULLABILITY_TYPE_ATTRS_CASELIST \
180 case ParsedAttr::AT_TypeNonNull: \
181 case ParsedAttr::AT_TypeNullable: \
182 case ParsedAttr::AT_TypeNullableResult: \
183 case ParsedAttr::AT_TypeNullUnspecified
184
185namespace {
186 /// An object which stores processing state for the entire
187 /// GetTypeForDeclarator process.
188 class TypeProcessingState {
189 Sema &sema;
190
191 /// The declarator being processed.
192 Declarator &declarator;
193
194 /// The index of the declarator chunk we're currently processing.
195 /// May be the total number of valid chunks, indicating the
196 /// DeclSpec.
197 unsigned chunkIndex;
198
199 /// The original set of attributes on the DeclSpec.
201
202 /// A list of attributes to diagnose the uselessness of when the
203 /// processing is complete.
204 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
205
206 /// Attributes corresponding to AttributedTypeLocs that we have not yet
207 /// populated.
208 // FIXME: The two-phase mechanism by which we construct Types and fill
209 // their TypeLocs makes it hard to correctly assign these. We keep the
210 // attributes in creation order as an attempt to make them line up
211 // properly.
212 using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
213 SmallVector<TypeAttrPair, 8> AttrsForTypes;
214 bool AttrsForTypesSorted = true;
215
216 /// MacroQualifiedTypes mapping to macro expansion locations that will be
217 /// stored in a MacroQualifiedTypeLoc.
218 llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
219
220 /// Flag to indicate we parsed a noderef attribute. This is used for
221 /// validating that noderef was used on a pointer or array.
222 bool parsedNoDeref;
223
224 // Flag to indicate that we already parsed a HLSL parameter modifier
225 // attribute. This prevents double-mutating the type.
226 bool ParsedHLSLParamMod;
227
228 public:
229 TypeProcessingState(Sema &sema, Declarator &declarator)
230 : sema(sema), declarator(declarator),
231 chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false),
232 ParsedHLSLParamMod(false) {}
233
234 Sema &getSema() const {
235 return sema;
236 }
237
238 Declarator &getDeclarator() const {
239 return declarator;
240 }
241
242 bool isProcessingDeclSpec() const {
243 return chunkIndex == declarator.getNumTypeObjects();
244 }
245
246 unsigned getCurrentChunkIndex() const {
247 return chunkIndex;
248 }
249
250 void setCurrentChunkIndex(unsigned idx) {
251 assert(idx <= declarator.getNumTypeObjects());
252 chunkIndex = idx;
253 }
254
255 ParsedAttributesView &getCurrentAttributes() const {
256 if (isProcessingDeclSpec())
257 return getMutableDeclSpec().getAttributes();
258 return declarator.getTypeObject(chunkIndex).getAttrs();
259 }
260
261 /// Save the current set of attributes on the DeclSpec.
262 void saveDeclSpecAttrs() {
263 // Don't try to save them multiple times.
264 if (!savedAttrs.empty())
265 return;
266
267 DeclSpec &spec = getMutableDeclSpec();
268 llvm::append_range(savedAttrs,
269 llvm::make_pointer_range(spec.getAttributes()));
270 }
271
272 /// Record that we had nowhere to put the given type attribute.
273 /// We will diagnose such attributes later.
274 void addIgnoredTypeAttr(ParsedAttr &attr) {
275 ignoredTypeAttrs.push_back(&attr);
276 }
277
278 /// Diagnose all the ignored type attributes, given that the
279 /// declarator worked out to the given type.
280 void diagnoseIgnoredTypeAttrs(QualType type) const {
281 for (auto *Attr : ignoredTypeAttrs)
282 diagnoseBadTypeAttribute(getSema(), *Attr, type);
283 }
284
285 /// Get an attributed type for the given attribute, and remember the Attr
286 /// object so that we can attach it to the AttributedTypeLoc.
287 QualType getAttributedType(Attr *A, QualType ModifiedType,
288 QualType EquivType) {
289 QualType T =
290 sema.Context.getAttributedType(A, ModifiedType, EquivType);
291 AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
292 AttrsForTypesSorted = false;
293 return T;
294 }
295
296 /// Get a BTFTagAttributed type for the btf_type_tag attribute.
297 QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
298 QualType WrappedType) {
299 return sema.Context.getBTFTagAttributedType(BTFAttr, WrappedType);
300 }
301
302 /// Get a OverflowBehaviorType type for the overflow_behavior type
303 /// attribute.
305 getOverflowBehaviorType(OverflowBehaviorType::OverflowBehaviorKind Kind,
306 QualType UnderlyingType) {
307 return sema.Context.getOverflowBehaviorType(Kind, UnderlyingType);
308 }
309
310 /// Completely replace the \c auto in \p TypeWithAuto by
311 /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
312 /// necessary.
313 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
314 QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
315 if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
316 // Attributed type still should be an attributed type after replacement.
317 auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
318 for (TypeAttrPair &A : AttrsForTypes) {
319 if (A.first == AttrTy)
320 A.first = NewAttrTy;
321 }
322 AttrsForTypesSorted = false;
323 }
324 return T;
325 }
326
327 /// Extract and remove the Attr* for a given attributed type.
328 const Attr *takeAttrForAttributedType(const AttributedType *AT) {
329 if (!AttrsForTypesSorted) {
330 llvm::stable_sort(AttrsForTypes, llvm::less_first());
331 AttrsForTypesSorted = true;
332 }
333
334 // FIXME: This is quadratic if we have lots of reuses of the same
335 // attributed type.
336 for (auto It = llvm::partition_point(
337 AttrsForTypes,
338 [=](const TypeAttrPair &A) { return A.first < AT; });
339 It != AttrsForTypes.end() && It->first == AT; ++It) {
340 if (It->second) {
341 const Attr *Result = It->second;
342 It->second = nullptr;
343 return Result;
344 }
345 }
346
347 llvm_unreachable("no Attr* for AttributedType*");
348 }
349
351 getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
352 auto FoundLoc = LocsForMacros.find(MQT);
353 assert(FoundLoc != LocsForMacros.end() &&
354 "Unable to find macro expansion location for MacroQualifedType");
355 return FoundLoc->second;
356 }
357
358 void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
359 SourceLocation Loc) {
360 LocsForMacros[MQT] = Loc;
361 }
362
363 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
364
365 bool didParseNoDeref() const { return parsedNoDeref; }
366
367 void setParsedHLSLParamMod(bool Parsed) { ParsedHLSLParamMod = Parsed; }
368
369 bool didParseHLSLParamMod() const { return ParsedHLSLParamMod; }
370
371 ~TypeProcessingState() {
372 if (savedAttrs.empty())
373 return;
374
375 getMutableDeclSpec().getAttributes().clearListOnly();
376 for (ParsedAttr *AL : savedAttrs)
377 getMutableDeclSpec().getAttributes().addAtEnd(AL);
378 }
379
380 private:
381 DeclSpec &getMutableDeclSpec() const {
382 return const_cast<DeclSpec&>(declarator.getDeclSpec());
383 }
384 };
385} // end anonymous namespace
386
388 ParsedAttributesView &fromList,
389 ParsedAttributesView &toList) {
390 fromList.remove(&attr);
391 toList.addAtEnd(&attr);
392}
393
394/// The location of a type attribute.
396 /// The attribute is in the decl-specifier-seq.
398 /// The attribute is part of a DeclaratorChunk.
400 /// The attribute is immediately after the declaration's name.
402};
403
404static void
405processTypeAttrs(TypeProcessingState &state, QualType &type,
406 TypeAttrLocation TAL, const ParsedAttributesView &attrs,
408
409static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
411
412static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
414
415static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
416 QualType &type);
417
418static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
420
421static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
423 if (attr.getKind() == ParsedAttr::AT_ObjCGC)
424 return handleObjCGCTypeAttr(state, attr, type);
425 assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
426 return handleObjCOwnershipTypeAttr(state, attr, type);
427}
428
429/// Given the index of a declarator chunk, check whether that chunk
430/// directly specifies the return type of a function and, if so, find
431/// an appropriate place for it.
432///
433/// \param i - a notional index which the search will start
434/// immediately inside
435///
436/// \param onlyBlockPointers Whether we should only look into block
437/// pointer types (vs. all pointer types).
439 unsigned i,
440 bool onlyBlockPointers) {
441 assert(i <= declarator.getNumTypeObjects());
442
443 DeclaratorChunk *result = nullptr;
444
445 // First, look inwards past parens for a function declarator.
446 for (; i != 0; --i) {
447 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
448 switch (fnChunk.Kind) {
450 continue;
451
452 // If we find anything except a function, bail out.
459 return result;
460
461 // If we do find a function declarator, scan inwards from that,
462 // looking for a (block-)pointer declarator.
464 for (--i; i != 0; --i) {
465 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
466 switch (ptrChunk.Kind) {
472 continue;
473
476 if (onlyBlockPointers)
477 continue;
478
479 [[fallthrough]];
480
482 result = &ptrChunk;
483 goto continue_outer;
484 }
485 llvm_unreachable("bad declarator chunk kind");
486 }
487
488 // If we run out of declarators doing that, we're done.
489 return result;
490 }
491 llvm_unreachable("bad declarator chunk kind");
492
493 // Okay, reconsider from our new point.
494 continue_outer: ;
495 }
496
497 // Ran out of chunks, bail out.
498 return result;
499}
500
501/// Given that an objc_gc attribute was written somewhere on a
502/// declaration *other* than on the declarator itself (for which, use
503/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
504/// didn't apply in whatever position it was written in, try to move
505/// it to a more appropriate position.
506static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
508 Declarator &declarator = state.getDeclarator();
509
510 // Move it to the outermost normal or block pointer declarator.
511 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
512 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
513 switch (chunk.Kind) {
516 // But don't move an ARC ownership attribute to the return type
517 // of a block.
518 DeclaratorChunk *destChunk = nullptr;
519 if (state.isProcessingDeclSpec() &&
520 attr.getKind() == ParsedAttr::AT_ObjCOwnership)
521 destChunk = maybeMovePastReturnType(declarator, i - 1,
522 /*onlyBlockPointers=*/true);
523 if (!destChunk) destChunk = &chunk;
524
525 moveAttrFromListToList(attr, state.getCurrentAttributes(),
526 destChunk->getAttrs());
527 return;
528 }
529
532 continue;
533
534 // We may be starting at the return type of a block.
536 if (state.isProcessingDeclSpec() &&
537 attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
539 declarator, i,
540 /*onlyBlockPointers=*/true)) {
541 moveAttrFromListToList(attr, state.getCurrentAttributes(),
542 dest->getAttrs());
543 return;
544 }
545 }
546 goto error;
547
548 // Don't walk through these.
552 goto error;
553 }
554 }
555 error:
556
557 diagnoseBadTypeAttribute(state.getSema(), attr, type);
558}
559
560/// Distribute an objc_gc type attribute that was written on the
561/// declarator.
563 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
564 Declarator &declarator = state.getDeclarator();
565
566 // objc_gc goes on the innermost pointer to something that's not a
567 // pointer.
568 unsigned innermost = -1U;
569 bool considerDeclSpec = true;
570 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
571 DeclaratorChunk &chunk = declarator.getTypeObject(i);
572 switch (chunk.Kind) {
575 innermost = i;
576 continue;
577
583 continue;
584
586 considerDeclSpec = false;
587 goto done;
588 }
589 }
590 done:
591
592 // That might actually be the decl spec if we weren't blocked by
593 // anything in the declarator.
594 if (considerDeclSpec) {
595 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
596 // Splice the attribute into the decl spec. Prevents the
597 // attribute from being applied multiple times and gives
598 // the source-location-filler something to work with.
599 state.saveDeclSpecAttrs();
601 declarator.getAttributes(), &attr);
602 return;
603 }
604 }
605
606 // Otherwise, if we found an appropriate chunk, splice the attribute
607 // into it.
608 if (innermost != -1U) {
610 declarator.getTypeObject(innermost).getAttrs());
611 return;
612 }
613
614 // Otherwise, diagnose when we're done building the type.
615 declarator.getAttributes().remove(&attr);
616 state.addIgnoredTypeAttr(attr);
617}
618
619/// A function type attribute was written somewhere in a declaration
620/// *other* than on the declarator itself or in the decl spec. Given
621/// that it didn't apply in whatever position it was written in, try
622/// to move it to a more appropriate position.
623static void distributeFunctionTypeAttr(TypeProcessingState &state,
625 Declarator &declarator = state.getDeclarator();
626
627 // Try to push the attribute from the return type of a function to
628 // the function itself.
629 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
630 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
631 switch (chunk.Kind) {
633 moveAttrFromListToList(attr, state.getCurrentAttributes(),
634 chunk.getAttrs());
635 return;
636
644 continue;
645 }
646 }
647
648 diagnoseBadTypeAttribute(state.getSema(), attr, type);
649}
650
651/// Try to distribute a function type attribute to the innermost
652/// function chunk or type. Returns true if the attribute was
653/// distributed, false if no location was found.
655 TypeProcessingState &state, ParsedAttr &attr,
656 ParsedAttributesView &attrList, QualType &declSpecType,
657 CUDAFunctionTarget CFT) {
658 Declarator &declarator = state.getDeclarator();
659
660 // Put it on the innermost function chunk, if there is one.
661 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
662 DeclaratorChunk &chunk = declarator.getTypeObject(i);
663 if (chunk.Kind != DeclaratorChunk::Function) continue;
664
665 moveAttrFromListToList(attr, attrList, chunk.getAttrs());
666 return true;
667 }
668
669 return handleFunctionTypeAttr(state, attr, declSpecType, CFT);
670}
671
672/// A function type attribute was written in the decl spec. Try to
673/// apply it somewhere.
674static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
676 QualType &declSpecType,
677 CUDAFunctionTarget CFT) {
678 state.saveDeclSpecAttrs();
679
680 // Try to distribute to the innermost.
682 state, attr, state.getCurrentAttributes(), declSpecType, CFT))
683 return;
684
685 // If that failed, diagnose the bad attribute when the declarator is
686 // fully built.
687 state.addIgnoredTypeAttr(attr);
688}
689
690/// A function type attribute was written on the declarator or declaration.
691/// Try to apply it somewhere.
692/// `Attrs` is the attribute list containing the declaration (either of the
693/// declarator or the declaration).
694static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
696 QualType &declSpecType,
697 CUDAFunctionTarget CFT) {
698 Declarator &declarator = state.getDeclarator();
699
700 // Try to distribute to the innermost.
702 state, attr, declarator.getAttributes(), declSpecType, CFT))
703 return;
704
705 // If that failed, diagnose the bad attribute when the declarator is
706 // fully built.
707 declarator.getAttributes().remove(&attr);
708 state.addIgnoredTypeAttr(attr);
709}
710
711/// Given that there are attributes written on the declarator or declaration
712/// itself, try to distribute any type attributes to the appropriate
713/// declarator chunk.
714///
715/// These are attributes like the following:
716/// int f ATTR;
717/// int (f ATTR)();
718/// but not necessarily this:
719/// int f() ATTR;
720///
721/// `Attrs` is the attribute list containing the declaration (either of the
722/// declarator or the declaration).
723static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
724 QualType &declSpecType,
725 CUDAFunctionTarget CFT) {
726 // The called functions in this loop actually remove things from the current
727 // list, so iterating over the existing list isn't possible. Instead, make a
728 // non-owning copy and iterate over that.
729 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
730 for (ParsedAttr &attr : AttrsCopy) {
731 // Do not distribute [[]] attributes. They have strict rules for what
732 // they appertain to.
733 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute())
734 continue;
735
736 switch (attr.getKind()) {
739 break;
740
742 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType, CFT);
743 break;
744
746 // Microsoft type attributes cannot go after the declarator-id.
747 continue;
748
750 // Nullability specifiers cannot go after the declarator-id.
751
752 // Objective-C __kindof does not get distributed.
753 case ParsedAttr::AT_ObjCKindOf:
754 continue;
755
756 default:
757 break;
758 }
759 }
760}
761
762/// Add a synthetic '()' to a block-literal declarator if it is
763/// required, given the return type.
764static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
765 QualType declSpecType) {
766 Declarator &declarator = state.getDeclarator();
767
768 // First, check whether the declarator would produce a function,
769 // i.e. whether the innermost semantic chunk is a function.
770 if (declarator.isFunctionDeclarator()) {
771 // If so, make that declarator a prototyped declarator.
772 declarator.getFunctionTypeInfo().hasPrototype = true;
773 return;
774 }
775
776 // If there are any type objects, the type as written won't name a
777 // function, regardless of the decl spec type. This is because a
778 // block signature declarator is always an abstract-declarator, and
779 // abstract-declarators can't just be parentheses chunks. Therefore
780 // we need to build a function chunk unless there are no type
781 // objects and the decl spec type is a function.
782 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
783 return;
784
785 // Note that there *are* cases with invalid declarators where
786 // declarators consist solely of parentheses. In general, these
787 // occur only in failed efforts to make function declarators, so
788 // faking up the function chunk is still the right thing to do.
789
790 // Otherwise, we need to fake up a function declarator.
791 SourceLocation loc = declarator.getBeginLoc();
792
793 // ...and *prepend* it to the declarator.
794 SourceLocation NoLoc;
796 /*HasProto=*/true,
797 /*IsAmbiguous=*/false,
798 /*LParenLoc=*/NoLoc,
799 /*ArgInfo=*/nullptr,
800 /*NumParams=*/0,
801 /*EllipsisLoc=*/NoLoc,
802 /*RParenLoc=*/NoLoc,
803 /*RefQualifierIsLvalueRef=*/true,
804 /*RefQualifierLoc=*/NoLoc,
805 /*MutableLoc=*/NoLoc, EST_None,
806 /*ESpecRange=*/SourceRange(),
807 /*Exceptions=*/nullptr,
808 /*ExceptionRanges=*/nullptr,
809 /*NumExceptions=*/0,
810 /*NoexceptExpr=*/nullptr,
811 /*ExceptionSpecTokens=*/nullptr,
812 /*DeclsInPrototype=*/{}, loc, loc, declarator));
813
814 // For consistency, make sure the state still has us as processing
815 // the decl spec.
816 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
817 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
818}
819
821 unsigned &TypeQuals,
822 QualType TypeSoFar,
823 unsigned RemoveTQs,
824 unsigned DiagID) {
825 // If this occurs outside a template instantiation, warn the user about
826 // it; they probably didn't mean to specify a redundant qualifier.
827 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
828 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
831 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
832 if (!(RemoveTQs & Qual.first))
833 continue;
834
835 if (!S.inTemplateInstantiation()) {
836 if (TypeQuals & Qual.first)
837 S.Diag(Qual.second, DiagID)
838 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
839 << FixItHint::CreateRemoval(Qual.second);
840 }
841
842 TypeQuals &= ~Qual.first;
843 }
844}
845
846/// Return true if this is omitted block return type. Also check type
847/// attributes and type qualifiers when returning true.
848static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
850 if (!isOmittedBlockReturnType(declarator))
851 return false;
852
853 // Warn if we see type attributes for omitted return type on a block literal.
855 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
856 if (AL.isInvalid() || !AL.isTypeAttr())
857 continue;
858 S.Diag(AL.getLoc(),
859 diag::warn_block_literal_attributes_on_omitted_return_type)
860 << AL;
861 ToBeRemoved.push_back(&AL);
862 }
863 // Remove bad attributes from the list.
864 for (ParsedAttr *AL : ToBeRemoved)
865 declarator.getMutableDeclSpec().getAttributes().remove(AL);
866
867 // Warn if we see type qualifiers for omitted return type on a block literal.
868 const DeclSpec &DS = declarator.getDeclSpec();
869 unsigned TypeQuals = DS.getTypeQualifiers();
870 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
871 diag::warn_block_literal_qualifiers_on_omitted_return_type);
873
874 return true;
875}
876
877static OpenCLAccessAttr::Spelling
879 for (const ParsedAttr &AL : Attrs)
880 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
881 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
882 return OpenCLAccessAttr::Keyword_read_only;
883}
884
885static UnaryTransformType::UTTKind
887 switch (SwitchTST) {
888#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
889 case TST_##Trait: \
890 return UnaryTransformType::Enum;
891#include "clang/Basic/TransformTypeTraits.def"
892 default:
893 llvm_unreachable("attempted to parse a non-unary transform builtin");
894 }
895}
896
897/// Convert the specified declspec to the appropriate type
898/// object.
899/// \param state Specifies the declarator containing the declaration specifier
900/// to be converted, along with other associated processing state.
901/// \returns The type described by the declaration specifiers. This function
902/// never returns null.
903static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
904 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
905 // checking.
906
907 Sema &S = state.getSema();
908 Declarator &declarator = state.getDeclarator();
909 DeclSpec &DS = declarator.getMutableDeclSpec();
910 SourceLocation DeclLoc = declarator.getIdentifierLoc();
911 if (DeclLoc.isInvalid())
912 DeclLoc = DS.getBeginLoc();
913
914 ASTContext &Context = S.Context;
915
917 switch (DS.getTypeSpecType()) {
919 Result = Context.VoidTy;
920 break;
923 Result = Context.CharTy;
925 Result = Context.SignedCharTy;
926 else {
928 "Unknown TSS value");
929 Result = Context.UnsignedCharTy;
930 }
931 break;
934 Result = Context.WCharTy;
936 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
938 Context.getPrintingPolicy());
939 Result = Context.getSignedWCharType();
940 } else {
942 "Unknown TSS value");
943 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
945 Context.getPrintingPolicy());
946 Result = Context.getUnsignedWCharType();
947 }
948 break;
951 "Unknown TSS value");
952 Result = Context.Char8Ty;
953 break;
956 "Unknown TSS value");
957 Result = Context.Char16Ty;
958 break;
961 "Unknown TSS value");
962 Result = Context.Char32Ty;
963 break;
965 // If this is a missing declspec in a block literal return context, then it
966 // is inferred from the return statements inside the block.
967 // The declspec is always missing in a lambda expr context; it is either
968 // specified with a trailing return type or inferred.
969 if (S.getLangOpts().CPlusPlus14 &&
971 // In C++1y, a lambda's implicit return type is 'auto'.
972 Result = Context.getAutoDeductType();
973 break;
974 } else if (declarator.getContext() == DeclaratorContext::LambdaExpr ||
975 checkOmittedBlockReturnType(S, declarator,
976 Context.DependentTy)) {
977 Result = Context.DependentTy;
978 break;
979 }
980
981 // Unspecified typespec defaults to int in C90. However, the C90 grammar
982 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
983 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
984 // Note that the one exception to this is function definitions, which are
985 // allowed to be completely missing a declspec. This is handled in the
986 // parser already though by it pretending to have seen an 'int' in this
987 // case.
989 // Only emit the diagnostic for the first declarator in a DeclGroup, as
990 // the warning is always implied for all subsequent declarators, and the
991 // fix must only be applied exactly once as well.
992 if (declarator.isFirstDeclarator()) {
993 S.Diag(DeclLoc, diag::warn_missing_type_specifier)
994 << DS.getSourceRange()
996 }
997 } else if (!DS.hasTypeSpecifier()) {
998 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
999 // "At least one type specifier shall be given in the declaration
1000 // specifiers in each declaration, and in the specifier-qualifier list
1001 // in each struct declaration and type name."
1002 if (!S.getLangOpts().isImplicitIntAllowed() && !DS.isTypeSpecPipe()) {
1003 if (declarator.isFirstDeclarator()) {
1004 S.Diag(DeclLoc, diag::err_missing_type_specifier)
1005 << DS.getSourceRange();
1006 }
1007
1008 // When this occurs, often something is very broken with the value
1009 // being declared, poison it as invalid so we don't get chains of
1010 // errors.
1011 declarator.setInvalidType(true);
1012 } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 &&
1013 DS.isTypeSpecPipe()) {
1014 if (declarator.isFirstDeclarator()) {
1015 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1016 << DS.getSourceRange();
1017 }
1018 declarator.setInvalidType(true);
1019 } else if (declarator.isFirstDeclarator()) {
1020 assert(S.getLangOpts().isImplicitIntAllowed() &&
1021 "implicit int is disabled?");
1022 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1023 << DS.getSourceRange()
1024 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int ");
1025 }
1026 }
1027
1028 [[fallthrough]];
1029 case DeclSpec::TST_int: {
1031 switch (DS.getTypeSpecWidth()) {
1033 Result = Context.IntTy;
1034 break;
1036 Result = Context.ShortTy;
1037 break;
1039 Result = Context.LongTy;
1040 break;
1042 Result = Context.LongLongTy;
1043
1044 if (S.getLangOpts().OpenCL) {
1045 // OpenCL v3.0 s6.3.4: 'long long' is a reserved data type.
1046 S.Diag(DS.getTypeSpecWidthLoc(), diag::warn_opencl_longlong);
1047 } else if (!S.getLangOpts().C99) {
1048 // 'long long' is a C99 or C++11 feature.
1049 if (S.getLangOpts().CPlusPlus)
1051 S.getLangOpts().CPlusPlus11 ?
1052 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1053 else
1054 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1055 }
1056 break;
1057 }
1058 } else {
1059 switch (DS.getTypeSpecWidth()) {
1061 Result = Context.UnsignedIntTy;
1062 break;
1064 Result = Context.UnsignedShortTy;
1065 break;
1067 Result = Context.UnsignedLongTy;
1068 break;
1070 Result = Context.UnsignedLongLongTy;
1071
1072 if (S.getLangOpts().OpenCL) {
1073 // OpenCL v3.0 s6.3.4: 'long long' is a reserved data type.
1074 S.Diag(DS.getTypeSpecWidthLoc(), diag::warn_opencl_longlong);
1075 } else if (!S.getLangOpts().C99) {
1076 // 'long long' is a C99 or C++11 feature.
1077 if (S.getLangOpts().CPlusPlus)
1079 S.getLangOpts().CPlusPlus11 ?
1080 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1081 else
1082 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1083 }
1084 break;
1085 }
1086 }
1087 break;
1088 }
1089 case DeclSpec::TST_bitint: {
1091 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_BitInt";
1092 Result =
1094 DS.getRepAsExpr(), DS.getBeginLoc());
1095 if (Result.isNull()) {
1096 Result = Context.IntTy;
1097 declarator.setInvalidType(true);
1098 }
1099 break;
1100 }
1101 case DeclSpec::TST_accum: {
1102 switch (DS.getTypeSpecWidth()) {
1104 Result = Context.ShortAccumTy;
1105 break;
1107 Result = Context.AccumTy;
1108 break;
1110 Result = Context.LongAccumTy;
1111 break;
1113 llvm_unreachable("Unable to specify long long as _Accum width");
1114 }
1115
1117 Result = Context.getCorrespondingUnsignedType(Result);
1118
1119 if (DS.isTypeSpecSat())
1120 Result = Context.getCorrespondingSaturatedType(Result);
1121
1122 break;
1123 }
1124 case DeclSpec::TST_fract: {
1125 switch (DS.getTypeSpecWidth()) {
1127 Result = Context.ShortFractTy;
1128 break;
1130 Result = Context.FractTy;
1131 break;
1133 Result = Context.LongFractTy;
1134 break;
1136 llvm_unreachable("Unable to specify long long as _Fract width");
1137 }
1138
1140 Result = Context.getCorrespondingUnsignedType(Result);
1141
1142 if (DS.isTypeSpecSat())
1143 Result = Context.getCorrespondingSaturatedType(Result);
1144
1145 break;
1146 }
1148 if (!S.Context.getTargetInfo().hasInt128Type() &&
1149 !(S.getLangOpts().isTargetDevice()))
1150 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1151 << "__int128";
1153 Result = Context.UnsignedInt128Ty;
1154 else
1155 Result = Context.Int128Ty;
1156 break;
1158 // CUDA host and device may have different _Float16 support, therefore
1159 // do not diagnose _Float16 usage to avoid false alarm.
1160 // ToDo: more precise diagnostics for CUDA.
1161 if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
1162 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1163 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1164 << "_Float16";
1165 Result = Context.Float16Ty;
1166 break;
1167 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1170 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice) &&
1171 !S.getLangOpts().SYCLIsDevice)
1172 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__bf16";
1173 Result = Context.BFloat16Ty;
1174 break;
1175 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1178 Result = Context.LongDoubleTy;
1179 else
1180 Result = Context.DoubleTy;
1181 if (S.getLangOpts().OpenCL) {
1182 if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts()))
1183 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1184 << 0 << Result
1185 << (S.getLangOpts().getOpenCLCompatibleVersion() == 300
1186 ? "cl_khr_fp64 and __opencl_c_fp64"
1187 : "cl_khr_fp64");
1188 else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts()))
1189 S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma);
1190 }
1191 break;
1195 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1196 << "__float128";
1197 Result = Context.Float128Ty;
1198 break;
1200 if (!S.Context.getTargetInfo().hasIbm128Type() &&
1201 !S.getLangOpts().SYCLIsDevice &&
1202 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1203 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128";
1204 Result = Context.Ibm128Ty;
1205 break;
1206 case DeclSpec::TST_bool:
1207 Result = Context.BoolTy; // _Bool or bool
1208 break;
1209 case DeclSpec::TST_decimal32: // _Decimal32
1210 case DeclSpec::TST_decimal64: // _Decimal64
1211 case DeclSpec::TST_decimal128: // _Decimal128
1212 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1213 Result = Context.IntTy;
1214 declarator.setInvalidType(true);
1215 break;
1217 case DeclSpec::TST_enum:
1221 TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1222 if (!D) {
1223 // This can happen in C++ with ambiguous lookups.
1224 Result = Context.IntTy;
1225 declarator.setInvalidType(true);
1226 break;
1227 }
1228
1229 // If the type is deprecated or unavailable, diagnose it.
1231
1233 DS.getTypeSpecComplex() == 0 &&
1235 "No qualifiers on tag names!");
1236
1239 // TypeQuals handled by caller.
1240 Result = Context.getTagType(Keyword, DS.getTypeSpecScope().getScopeRep(), D,
1241 DS.isTypeSpecOwned());
1242 break;
1243 }
1246 DS.getTypeSpecComplex() == 0 &&
1248 "Can't handle qualifiers on typedef names yet!");
1250 if (Result.isNull()) {
1251 declarator.setInvalidType(true);
1252 }
1253
1254 // TypeQuals handled by caller.
1255 break;
1256 }
1259 // FIXME: Preserve type source info.
1261 assert(!Result.isNull() && "Didn't get a type for typeof?");
1262 if (!Result->isDependentType())
1263 if (const auto *TT = Result->getAs<TagType>())
1264 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1265 // TypeQuals handled by caller.
1266 Result = Context.getTypeOfType(
1270 break;
1273 Expr *E = DS.getRepAsExpr();
1274 assert(E && "Didn't get an expression for typeof?");
1275 // TypeQuals handled by caller.
1280 if (Result.isNull()) {
1281 Result = Context.IntTy;
1282 declarator.setInvalidType(true);
1283 }
1284 break;
1285 }
1287 Expr *E = DS.getRepAsExpr();
1288 assert(E && "Didn't get an expression for decltype?");
1289 // TypeQuals handled by caller.
1291 if (Result.isNull()) {
1292 Result = Context.IntTy;
1293 declarator.setInvalidType(true);
1294 }
1295 break;
1296 }
1298 Expr *E = DS.getPackIndexingExpr();
1299 assert(E && "Didn't get an expression for pack indexing");
1300 QualType Pattern = S.GetTypeFromParser(DS.getRepAsType());
1301 Result = S.BuildPackIndexingType(Pattern, E, DS.getBeginLoc(),
1302 DS.getEllipsisLoc());
1303 if (Result.isNull()) {
1304 declarator.setInvalidType(true);
1305 Result = Context.IntTy;
1306 }
1307 break;
1308 }
1309
1310#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
1311#include "clang/Basic/TransformTypeTraits.def"
1313 assert(!Result.isNull() && "Didn't get a type for the transformation?");
1316 DS.getTypeSpecTypeLoc());
1317 if (Result.isNull()) {
1318 Result = Context.IntTy;
1319 declarator.setInvalidType(true);
1320 }
1321 break;
1322
1323 case DeclSpec::TST_auto:
1325 auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1328
1329 TemplateDecl *TypeConstraintConcept = nullptr;
1331 if (DS.isConstrainedAuto()) {
1332 if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1333 TypeConstraintConcept =
1334 cast<TemplateDecl>(TemplateId->Template.get().getAsTemplateDecl());
1335 TemplateArgumentListInfo TemplateArgsInfo;
1336 TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1337 TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1338 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1339 TemplateId->NumArgs);
1340 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1341 for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1342 TemplateArgs.push_back(ArgLoc.getArgument());
1343 } else {
1344 declarator.setInvalidType(true);
1345 }
1346 }
1348 TypeConstraintConcept, TemplateArgs);
1349 break;
1350 }
1351
1353 Result = Context.getAutoType(DeducedKind::Undeduced, QualType(),
1355 break;
1356
1358 Result = Context.UnknownAnyTy;
1359 break;
1360
1363 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1365 if (Result.isNull()) {
1366 Result = Context.IntTy;
1367 declarator.setInvalidType(true);
1368 }
1369 break;
1370
1371#define GENERIC_IMAGE_TYPE(ImgType, Id) \
1372 case DeclSpec::TST_##ImgType##_t: \
1373 switch (getImageAccess(DS.getAttributes())) { \
1374 case OpenCLAccessAttr::Keyword_write_only: \
1375 Result = Context.Id##WOTy; \
1376 break; \
1377 case OpenCLAccessAttr::Keyword_read_write: \
1378 Result = Context.Id##RWTy; \
1379 break; \
1380 case OpenCLAccessAttr::Keyword_read_only: \
1381 Result = Context.Id##ROTy; \
1382 break; \
1383 case OpenCLAccessAttr::SpellingNotCalculated: \
1384 llvm_unreachable("Spelling not yet calculated"); \
1385 } \
1386 break;
1387#include "clang/Basic/OpenCLImageTypes.def"
1388
1389#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1390 case DeclSpec::TST_##Name: \
1391 Result = Context.SingletonId; \
1392 break;
1393#include "clang/Basic/HLSLIntangibleTypes.def"
1394
1396 Result = Context.IntTy;
1397 declarator.setInvalidType(true);
1398 break;
1399 }
1400
1401 // FIXME: we want resulting declarations to be marked invalid, but claiming
1402 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1403 // a null type.
1404 if (Result->containsErrors())
1405 declarator.setInvalidType();
1406
1407 if (S.getLangOpts().OpenCL) {
1408 const auto &OpenCLOptions = S.getOpenCLOptions();
1409 bool IsOpenCLC30Compatible =
1411 // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1412 // support.
1413 // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1414 // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1415 // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1416 // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1417 // only when the optional feature is supported
1418 if ((Result->isImageType() || Result->isSamplerT()) &&
1419 (IsOpenCLC30Compatible &&
1420 !OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts()))) {
1421 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1422 << 0 << Result << "__opencl_c_images";
1423 declarator.setInvalidType();
1424 } else if (Result->isOCLImage3dWOType() &&
1425 !OpenCLOptions.isSupported("cl_khr_3d_image_writes",
1426 S.getLangOpts())) {
1427 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1428 << 0 << Result
1429 << (IsOpenCLC30Compatible
1430 ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes"
1431 : "cl_khr_3d_image_writes");
1432 declarator.setInvalidType();
1433 }
1434 }
1435
1436 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1438
1439 // Only fixed point types can be saturated
1440 if (DS.isTypeSpecSat() && !IsFixedPointType)
1441 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1443 Context.getPrintingPolicy());
1444
1445 // Handle complex types.
1447 if (S.getLangOpts().Freestanding)
1448 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1449 Result = Context.getComplexType(Result);
1450 } else if (DS.isTypeAltiVecVector()) {
1451 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1452 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1454 if (DS.isTypeAltiVecPixel())
1455 VecKind = VectorKind::AltiVecPixel;
1456 else if (DS.isTypeAltiVecBool())
1457 VecKind = VectorKind::AltiVecBool;
1458 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1459 }
1460
1461 // _Imaginary was a feature of C99 through C23 but was never supported in
1462 // Clang. The feature was removed in C2y, but we retain the unsupported
1463 // diagnostic for an improved user experience.
1465 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1466
1467 // Before we process any type attributes, synthesize a block literal
1468 // function declarator if necessary.
1469 if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1471
1472 // Apply any type attributes from the decl spec. This may cause the
1473 // list of type attributes to be temporarily saved while the type
1474 // attributes are pushed around.
1475 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1476 if (!DS.isTypeSpecPipe()) {
1477 // We also apply declaration attributes that "slide" to the decl spec.
1478 // Ordering can be important for attributes. The decalaration attributes
1479 // come syntactically before the decl spec attributes, so we process them
1480 // in that order.
1481 ParsedAttributesView SlidingAttrs;
1482 for (ParsedAttr &AL : declarator.getDeclarationAttributes()) {
1483 if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
1484 SlidingAttrs.addAtEnd(&AL);
1485
1486 // For standard syntax attributes, which would normally appertain to the
1487 // declaration here, suggest moving them to the type instead. But only
1488 // do this for our own vendor attributes; moving other vendors'
1489 // attributes might hurt portability.
1490 // There's one special case that we need to deal with here: The
1491 // `MatrixType` attribute may only be used in a typedef declaration. If
1492 // it's being used anywhere else, don't output the warning as
1493 // ProcessDeclAttributes() will output an error anyway.
1494 if (AL.isStandardAttributeSyntax() && AL.isClangScope() &&
1495 !(AL.getKind() == ParsedAttr::AT_MatrixType &&
1497 S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl)
1498 << AL;
1499 }
1500 }
1501 }
1502 // During this call to processTypeAttrs(),
1503 // TypeProcessingState::getCurrentAttributes() will erroneously return a
1504 // reference to the DeclSpec attributes, rather than the declaration
1505 // attributes. However, this doesn't matter, as getCurrentAttributes()
1506 // is only called when distributing attributes from one attribute list
1507 // to another. Declaration attributes are always C++11 attributes, and these
1508 // are never distributed.
1509 processTypeAttrs(state, Result, TAL_DeclSpec, SlidingAttrs);
1511 }
1512
1513 // Apply const/volatile/restrict qualifiers to T.
1514 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1515 // Warn about CV qualifiers on function types.
1516 // C99 6.7.3p8:
1517 // If the specification of a function type includes any type qualifiers,
1518 // the behavior is undefined.
1519 // C2y changed this behavior to be implementation-defined. Clang defines
1520 // the behavior in all cases to ignore the qualifier, as in C++.
1521 // C++11 [dcl.fct]p7:
1522 // The effect of a cv-qualifier-seq in a function declarator is not the
1523 // same as adding cv-qualification on top of the function type. In the
1524 // latter case, the cv-qualifiers are ignored.
1525 if (Result->isFunctionType()) {
1526 unsigned DiagId = diag::warn_typecheck_function_qualifiers_ignored;
1527 if (!S.getLangOpts().CPlusPlus && !S.getLangOpts().C2y)
1528 DiagId = diag::ext_typecheck_function_qualifiers_unspecified;
1530 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1531 DiagId);
1532 // No diagnostic for 'restrict' or '_Atomic' applied to a
1533 // function type; we'll diagnose those later, in BuildQualifiedType.
1534 }
1535
1536 // C++11 [dcl.ref]p1:
1537 // Cv-qualified references are ill-formed except when the
1538 // cv-qualifiers are introduced through the use of a typedef-name
1539 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1540 //
1541 // There don't appear to be any other contexts in which a cv-qualified
1542 // reference type could be formed, so the 'ill-formed' clause here appears
1543 // to never happen.
1544 if (TypeQuals && Result->isReferenceType()) {
1546 S, DS, TypeQuals, Result,
1548 diag::warn_typecheck_reference_qualifiers);
1549 }
1550
1551 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1552 // than once in the same specifier-list or qualifier-list, either directly
1553 // or via one or more typedefs."
1554 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1555 && TypeQuals & Result.getCVRQualifiers()) {
1556 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1557 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1558 << "const";
1559 }
1560
1561 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1562 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1563 << "volatile";
1564 }
1565
1566 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1567 // produce a warning in this case.
1568 }
1569
1570 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1571
1572 // If adding qualifiers fails, just use the unqualified type.
1573 if (Qualified.isNull())
1574 declarator.setInvalidType(true);
1575 else
1576 Result = Qualified;
1577 }
1578
1579 // Check for __ob_wrap and __ob_trap
1580 if (DS.isOverflowBehaviorSpecified() &&
1581 S.getLangOpts().OverflowBehaviorTypes) {
1582 if (!Result->isIntegerType()) {
1584 StringRef SpecifierName =
1586 S.Diag(Loc, diag::err_overflow_behavior_non_integer_type)
1587 << SpecifierName << Result.getAsString() << 1;
1588 } else {
1589 OverflowBehaviorType::OverflowBehaviorKind Kind =
1590 DS.isWrapSpecified()
1591 ? OverflowBehaviorType::OverflowBehaviorKind::Wrap
1592 : OverflowBehaviorType::OverflowBehaviorKind::Trap;
1593 Result = state.getOverflowBehaviorType(Kind, Result);
1594 }
1595 }
1596
1597 if (S.getLangOpts().HLSL)
1599
1600 assert(!Result.isNull() && "This function should not return a null type");
1601 return Result;
1602}
1603
1604static std::string getPrintableNameForEntity(DeclarationName Entity) {
1605 if (Entity)
1606 return Entity.getAsString();
1607
1608 return "type name";
1609}
1610
1612 Qualifiers Qs, const DeclSpec *DS) {
1613 if (T.isNull())
1614 return QualType();
1615
1616 // Ignore any attempt to form a cv-qualified reference.
1617 if (T->isReferenceType()) {
1618 Qs.removeConst();
1619 Qs.removeVolatile();
1620 }
1621
1622 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1623 // object or incomplete types shall not be restrict-qualified."
1624 if (Qs.hasRestrict()) {
1625 unsigned DiagID = 0;
1626 QualType EltTy = Context.getBaseElementType(T);
1627
1628 if (EltTy->isAnyPointerType() || EltTy->isReferenceType() ||
1629 EltTy->isMemberPointerType()) {
1630
1631 if (const auto *PTy = EltTy->getAs<MemberPointerType>())
1632 EltTy = PTy->getPointeeType();
1633 else
1634 EltTy = EltTy->getPointeeType();
1635
1636 // If we have a pointer or reference, the pointee must have an object
1637 // incomplete type.
1638 if (!EltTy->isIncompleteOrObjectType())
1639 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1640
1641 } else if (!T->isDependentType() && !isa<AutoType>(T)) {
1642 // For an inferred type, we may not have seen the initializer yet and so
1643 // have no idea whether the underlying type is a pointer type or not.
1644 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1645 EltTy = T;
1646 }
1647
1648 Loc = DS ? DS->getRestrictSpecLoc() : Loc;
1649 if (DiagID) {
1650 Diag(Loc, DiagID) << EltTy;
1651 Qs.removeRestrict();
1652 } else {
1653 if (T->isArrayType())
1654 Diag(Loc, getLangOpts().C23
1655 ? diag::warn_c23_compat_restrict_on_array_of_pointers
1656 : diag::ext_restrict_on_array_of_pointers_c23);
1657 }
1658 }
1659
1660 return Context.getQualifiedType(T, Qs);
1661}
1662
1664 unsigned CVRAU, const DeclSpec *DS) {
1665 if (T.isNull())
1666 return QualType();
1667
1668 // Ignore any attempt to form a cv-qualified reference.
1669 if (T->isReferenceType())
1670 CVRAU &=
1672
1673 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1674 // TQ_unaligned;
1675 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1676
1677 // C11 6.7.3/5:
1678 // If the same qualifier appears more than once in the same
1679 // specifier-qualifier-list, either directly or via one or more typedefs,
1680 // the behavior is the same as if it appeared only once.
1681 //
1682 // It's not specified what happens when the _Atomic qualifier is applied to
1683 // a type specified with the _Atomic specifier, but we assume that this
1684 // should be treated as if the _Atomic qualifier appeared multiple times.
1685 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1686 // C11 6.7.3/5:
1687 // If other qualifiers appear along with the _Atomic qualifier in a
1688 // specifier-qualifier-list, the resulting type is the so-qualified
1689 // atomic type.
1690 //
1691 // Don't need to worry about array types here, since _Atomic can't be
1692 // applied to such types.
1693 SplitQualType Split = T.getSplitUnqualifiedType();
1694 T = BuildAtomicType(QualType(Split.Ty, 0),
1695 DS ? DS->getAtomicSpecLoc() : Loc);
1696 if (T.isNull())
1697 return T;
1698 Split.Quals.addCVRQualifiers(CVR);
1699 return BuildQualifiedType(T, Loc, Split.Quals);
1700 }
1701
1704 return BuildQualifiedType(T, Loc, Q, DS);
1705}
1706
1708 return Context.getParenType(T);
1709}
1710
1711/// Given that we're building a pointer or reference to the given
1713 SourceLocation loc,
1714 bool isReference) {
1715 // Bail out if retention is unrequired or already specified.
1716 if (!type->isObjCLifetimeType() ||
1717 type.getObjCLifetime() != Qualifiers::OCL_None)
1718 return type;
1719
1721
1722 // If the object type is const-qualified, we can safely use
1723 // __unsafe_unretained. This is safe (because there are no read
1724 // barriers), and it'll be safe to coerce anything but __weak* to
1725 // the resulting type.
1726 if (type.isConstQualified()) {
1727 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1728
1729 // Otherwise, check whether the static type does not require
1730 // retaining. This currently only triggers for Class (possibly
1731 // protocol-qualifed, and arrays thereof).
1732 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1733 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1734
1735 // If we are in an unevaluated context, like sizeof, skip adding a
1736 // qualification.
1737 } else if (S.isUnevaluatedContext()) {
1738 return type;
1739
1740 // If that failed, give an error and recover using __strong. __strong
1741 // is the option most likely to prevent spurious second-order diagnostics,
1742 // like when binding a reference to a field.
1743 } else {
1744 // These types can show up in private ivars in system headers, so
1745 // we need this to not be an error in those cases. Instead we
1746 // want to delay.
1750 diag::err_arc_indirect_no_ownership, type, isReference));
1751 } else {
1752 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1753 }
1754 implicitLifetime = Qualifiers::OCL_Strong;
1755 }
1756 assert(implicitLifetime && "didn't infer any lifetime!");
1757
1758 Qualifiers qs;
1759 qs.addObjCLifetime(implicitLifetime);
1760 return S.Context.getQualifiedType(type, qs);
1761}
1762
1763static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1764 std::string Quals = FnTy->getMethodQuals().getAsString();
1765
1766 switch (FnTy->getRefQualifier()) {
1767 case RQ_None:
1768 break;
1769
1770 case RQ_LValue:
1771 if (!Quals.empty())
1772 Quals += ' ';
1773 Quals += '&';
1774 break;
1775
1776 case RQ_RValue:
1777 if (!Quals.empty())
1778 Quals += ' ';
1779 Quals += "&&";
1780 break;
1781 }
1782
1783 return Quals;
1784}
1785
1786namespace {
1787/// Kinds of declarator that cannot contain a qualified function type.
1788///
1789/// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1790/// a function type with a cv-qualifier or a ref-qualifier can only appear
1791/// at the topmost level of a type.
1792///
1793/// Parens and member pointers are permitted. We don't diagnose array and
1794/// function declarators, because they don't allow function types at all.
1795///
1796/// The values of this enum are used in diagnostics.
1797enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1798} // end anonymous namespace
1799
1800/// Check whether the type T is a qualified function type, and if it is,
1801/// diagnose that it cannot be contained within the given kind of declarator.
1803 QualifiedFunctionKind QFK) {
1804 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1805 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1806 if (!FPT ||
1807 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1808 return false;
1809
1810 S.Diag(Loc, diag::err_compound_qualified_function_type)
1811 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1813 return true;
1814}
1815
1817 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1818 if (!FPT ||
1819 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1820 return false;
1821
1822 Diag(Loc, diag::err_qualified_function_typeid)
1823 << T << getFunctionQualifiersAsString(FPT);
1824 return true;
1825}
1826
1827// Helper to deduce addr space of a pointee type in OpenCL mode.
1829 if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
1830 !PointeeType->isSamplerT() &&
1831 !PointeeType.hasAddressSpace())
1832 PointeeType = S.getASTContext().getAddrSpaceQualType(
1834 return PointeeType;
1835}
1836
1838 SourceLocation Loc, DeclarationName Entity) {
1839 if (T->isReferenceType()) {
1840 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1841 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1842 << getPrintableNameForEntity(Entity) << T;
1843 return QualType();
1844 }
1845
1846 if (T->isFunctionType() && getLangOpts().OpenCL &&
1847 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
1848 getLangOpts())) {
1849 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
1850 return QualType();
1851 }
1852
1853 if (getLangOpts().HLSL && Loc.isValid()) {
1854 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
1855 return QualType();
1856 }
1857
1858 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1859 return QualType();
1860
1861 if (T->isObjCObjectType())
1862 return Context.getObjCObjectPointerType(T);
1863
1864 // In ARC, it is forbidden to build pointers to unqualified pointers.
1865 if (getLangOpts().ObjCAutoRefCount)
1866 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1867
1868 if (getLangOpts().OpenCL)
1869 T = deduceOpenCLPointeeAddrSpace(*this, T);
1870
1871 // In WebAssembly, pointers to reference types and pointers to tables are
1872 // illegal.
1873 if (getASTContext().getTargetInfo().getTriple().isWasm()) {
1874 if (T.isWebAssemblyReferenceType()) {
1875 Diag(Loc, diag::err_wasm_reference_pr) << 0;
1876 return QualType();
1877 }
1878
1879 // We need to desugar the type here in case T is a ParenType.
1880 if (T->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
1881 Diag(Loc, diag::err_wasm_table_pr) << 0;
1882 return QualType();
1883 }
1884 }
1885
1886 // Build the pointer type.
1887 return Context.getPointerType(T);
1888}
1889
1891 SourceLocation Loc,
1892 DeclarationName Entity) {
1893 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1894 "Unresolved overloaded function type");
1895
1896 // C++0x [dcl.ref]p6:
1897 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1898 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1899 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1900 // the type "lvalue reference to T", while an attempt to create the type
1901 // "rvalue reference to cv TR" creates the type TR.
1902 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1903
1904 // C++ [dcl.ref]p4: There shall be no references to references.
1905 //
1906 // According to C++ DR 106, references to references are only
1907 // diagnosed when they are written directly (e.g., "int & &"),
1908 // but not when they happen via a typedef:
1909 //
1910 // typedef int& intref;
1911 // typedef intref& intref2;
1912 //
1913 // Parser::ParseDeclaratorInternal diagnoses the case where
1914 // references are written directly; here, we handle the
1915 // collapsing of references-to-references as described in C++0x.
1916 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1917
1918 // C++ [dcl.ref]p1:
1919 // A declarator that specifies the type "reference to cv void"
1920 // is ill-formed.
1921 if (T->isVoidType()) {
1922 Diag(Loc, diag::err_reference_to_void);
1923 return QualType();
1924 }
1925
1926 if (getLangOpts().HLSL && Loc.isValid()) {
1927 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1;
1928 return QualType();
1929 }
1930
1931 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1932 return QualType();
1933
1934 if (T->isFunctionType() && getLangOpts().OpenCL &&
1935 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
1936 getLangOpts())) {
1937 Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1;
1938 return QualType();
1939 }
1940
1941 // In ARC, it is forbidden to build references to unqualified pointers.
1942 if (getLangOpts().ObjCAutoRefCount)
1943 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1944
1945 if (getLangOpts().OpenCL)
1946 T = deduceOpenCLPointeeAddrSpace(*this, T);
1947
1948 // In WebAssembly, references to reference types and tables are illegal.
1949 if (getASTContext().getTargetInfo().getTriple().isWasm() &&
1950 T.isWebAssemblyReferenceType()) {
1951 Diag(Loc, diag::err_wasm_reference_pr) << 1;
1952 return QualType();
1953 }
1954 if (T->isWebAssemblyTableType()) {
1955 Diag(Loc, diag::err_wasm_table_pr) << 1;
1956 return QualType();
1957 }
1958
1959 // Handle restrict on references.
1960 if (LValueRef)
1961 return Context.getLValueReferenceType(T, SpelledAsLValue);
1962 return Context.getRValueReferenceType(T);
1963}
1964
1966 return Context.getReadPipeType(T);
1967}
1968
1970 return Context.getWritePipeType(T);
1971}
1972
1973QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth,
1974 SourceLocation Loc) {
1975 if (BitWidth->isInstantiationDependent())
1976 return Context.getDependentBitIntType(IsUnsigned, BitWidth);
1977
1978 llvm::APSInt Bits(32);
1980 BitWidth, &Bits, /*FIXME*/ AllowFoldKind::Allow);
1981
1982 if (ICE.isInvalid())
1983 return QualType();
1984
1985 size_t NumBits = Bits.getZExtValue();
1986 if (!IsUnsigned && NumBits < 2) {
1987 Diag(Loc, diag::err_bit_int_bad_size) << 0;
1988 return QualType();
1989 }
1990
1991 if (IsUnsigned && NumBits < 1) {
1992 Diag(Loc, diag::err_bit_int_bad_size) << 1;
1993 return QualType();
1994 }
1995
1996 const TargetInfo &TI = getASTContext().getTargetInfo();
1997 if (NumBits > TI.getMaxBitIntWidth()) {
1998 Diag(Loc, diag::err_bit_int_max_size)
1999 << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth());
2000 return QualType();
2001 }
2002
2003 return Context.getBitIntType(IsUnsigned, NumBits);
2004}
2005
2006/// Check whether the specified array bound can be evaluated using the relevant
2007/// language rules. If so, returns the possibly-converted expression and sets
2008/// SizeVal to the size. If not, but the expression might be a VLA bound,
2009/// returns ExprResult(). Otherwise, produces a diagnostic and returns
2010/// ExprError().
2011static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
2012 llvm::APSInt &SizeVal, unsigned VLADiag,
2013 bool VLAIsError) {
2014 if (S.getLangOpts().CPlusPlus14 &&
2015 (VLAIsError ||
2016 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) {
2017 // C++14 [dcl.array]p1:
2018 // The constant-expression shall be a converted constant expression of
2019 // type std::size_t.
2020 //
2021 // Don't apply this rule if we might be forming a VLA: in that case, we
2022 // allow non-constant expressions and constant-folding. We only need to use
2023 // the converted constant expression rules (to properly convert the source)
2024 // when the source expression is of class type.
2026 ArraySize, S.Context.getSizeType(), SizeVal, CCEKind::ArrayBound);
2027 }
2028
2029 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2030 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2031 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2032 public:
2033 unsigned VLADiag;
2034 bool VLAIsError;
2035 bool IsVLA = false;
2036
2037 VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2038 : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2039
2040 Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2041 QualType T) override {
2042 return S.Diag(Loc, diag::err_array_size_non_int) << T;
2043 }
2044
2045 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2046 SourceLocation Loc) override {
2047 IsVLA = !VLAIsError;
2048 return S.Diag(Loc, VLADiag);
2049 }
2050
2051 Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2052 SourceLocation Loc) override {
2053 return S.Diag(Loc, diag::ext_vla_folded_to_constant);
2054 }
2055 } Diagnoser(VLADiag, VLAIsError);
2056
2057 ExprResult R =
2058 S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser);
2059 if (Diagnoser.IsVLA)
2060 return ExprResult();
2061 return R;
2062}
2063
2065 EltTy = Context.getBaseElementType(EltTy);
2066 if (EltTy->isIncompleteType() || EltTy->isDependentType() ||
2067 EltTy->isUndeducedType())
2068 return true;
2069
2070 CharUnits Size = Context.getTypeSizeInChars(EltTy);
2071 CharUnits Alignment = Context.getTypeAlignInChars(EltTy);
2072
2073 if (Size.isMultipleOf(Alignment))
2074 return true;
2075
2076 Diag(Loc, diag::err_array_element_alignment)
2077 << EltTy << Size.getQuantity() << Alignment.getQuantity();
2078 return false;
2079}
2080
2082 Expr *ArraySize, unsigned Quals,
2083 SourceRange Brackets, DeclarationName Entity) {
2084
2085 SourceLocation Loc = Brackets.getBegin();
2086 if (getLangOpts().CPlusPlus) {
2087 // C++ [dcl.array]p1:
2088 // T is called the array element type; this type shall not be a reference
2089 // type, the (possibly cv-qualified) type void, a function type or an
2090 // abstract class type.
2091 //
2092 // C++ [dcl.array]p3:
2093 // When several "array of" specifications are adjacent, [...] only the
2094 // first of the constant expressions that specify the bounds of the arrays
2095 // may be omitted.
2096 //
2097 // Note: function types are handled in the common path with C.
2098 if (T->isReferenceType()) {
2099 Diag(Loc, diag::err_illegal_decl_array_of_references)
2100 << getPrintableNameForEntity(Entity) << T;
2101 return QualType();
2102 }
2103
2104 if (T->isVoidType() || T->isIncompleteArrayType()) {
2105 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2106 return QualType();
2107 }
2108
2109 if (RequireNonAbstractType(Brackets.getBegin(), T,
2110 diag::err_array_of_abstract_type))
2111 return QualType();
2112
2113 // Mentioning a member pointer type for an array type causes us to lock in
2114 // an inheritance model, even if it's inside an unused typedef.
2115 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2116 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2117 if (!MPTy->getQualifier().isDependent())
2118 (void)isCompleteType(Loc, T);
2119
2120 } else {
2121 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2122 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2123 if (!T.isWebAssemblyReferenceType() &&
2125 diag::err_array_incomplete_or_sizeless_type))
2126 return QualType();
2127 }
2128
2129 // Multi-dimensional arrays of WebAssembly references are not allowed.
2130 if (Context.getTargetInfo().getTriple().isWasm() && T->isArrayType()) {
2131 const auto *ATy = dyn_cast<ArrayType>(T);
2132 if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
2133 Diag(Loc, diag::err_wasm_reftype_multidimensional_array);
2134 return QualType();
2135 }
2136 }
2137
2138 if (T->isSizelessType() && !T.isWebAssemblyReferenceType()) {
2139 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2140 return QualType();
2141 }
2142
2143 if (T->isFunctionType()) {
2144 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2145 << getPrintableNameForEntity(Entity) << T;
2146 return QualType();
2147 }
2148
2149 if (const auto *RD = T->getAsRecordDecl()) {
2150 // If the element type is a struct or union that contains a variadic
2151 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2152 if (RD->hasFlexibleArrayMember())
2153 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2154 } else if (T->isObjCObjectType()) {
2155 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2156 return QualType();
2157 }
2158
2159 if (!checkArrayElementAlignment(T, Loc))
2160 return QualType();
2161
2162 // Do placeholder conversions on the array size expression.
2163 if (ArraySize && ArraySize->hasPlaceholderType()) {
2165 if (Result.isInvalid()) return QualType();
2166 ArraySize = Result.get();
2167 }
2168
2169 // Do lvalue-to-rvalue conversions on the array size expression.
2170 if (ArraySize && !ArraySize->isPRValue()) {
2172 if (Result.isInvalid())
2173 return QualType();
2174
2175 ArraySize = Result.get();
2176 }
2177
2178 // C99 6.7.5.2p1: The size expression shall have integer type.
2179 // C++11 allows contextual conversions to such types.
2180 if (!getLangOpts().CPlusPlus11 &&
2181 ArraySize && !ArraySize->isTypeDependent() &&
2183 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2184 << ArraySize->getType() << ArraySize->getSourceRange();
2185 return QualType();
2186 }
2187
2188 auto IsStaticAssertLike = [](const Expr *ArraySize, ASTContext &Context) {
2189 if (!ArraySize)
2190 return false;
2191
2192 // If the array size expression is a conditional expression whose branches
2193 // are both integer constant expressions, one negative and one positive,
2194 // then it's assumed to be like an old-style static assertion. e.g.,
2195 // int old_style_assert[expr ? 1 : -1];
2196 // We will accept any integer constant expressions instead of assuming the
2197 // values 1 and -1 are always used.
2198 if (const auto *CondExpr = dyn_cast_if_present<ConditionalOperator>(
2199 ArraySize->IgnoreParenImpCasts())) {
2200 std::optional<llvm::APSInt> LHS =
2201 CondExpr->getLHS()->getIntegerConstantExpr(Context);
2202 std::optional<llvm::APSInt> RHS =
2203 CondExpr->getRHS()->getIntegerConstantExpr(Context);
2204 return LHS && RHS && LHS->isNegative() != RHS->isNegative();
2205 }
2206 return false;
2207 };
2208
2209 // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2210 unsigned VLADiag;
2211 bool VLAIsError;
2212 if (getLangOpts().OpenCL) {
2213 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2214 VLADiag = diag::err_opencl_vla;
2215 VLAIsError = true;
2216 } else if (getLangOpts().C99) {
2217 VLADiag = diag::warn_vla_used;
2218 VLAIsError = false;
2219 } else if (isSFINAEContext()) {
2220 VLADiag = diag::err_vla_in_sfinae;
2221 VLAIsError = true;
2222 } else if (getLangOpts().OpenMP && OpenMP().isInOpenMPTaskUntiedContext()) {
2223 VLADiag = diag::err_openmp_vla_in_task_untied;
2224 VLAIsError = true;
2225 } else if (getLangOpts().CPlusPlus) {
2226 if (getLangOpts().CPlusPlus11 && IsStaticAssertLike(ArraySize, Context))
2227 VLADiag = getLangOpts().GNUMode
2228 ? diag::ext_vla_cxx_in_gnu_mode_static_assert
2229 : diag::ext_vla_cxx_static_assert;
2230 else
2231 VLADiag = getLangOpts().GNUMode ? diag::ext_vla_cxx_in_gnu_mode
2232 : diag::ext_vla_cxx;
2233 VLAIsError = false;
2234 } else {
2235 VLADiag = diag::ext_vla;
2236 VLAIsError = false;
2237 }
2238
2239 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2240 if (!ArraySize) {
2241 if (ASM == ArraySizeModifier::Star) {
2242 Diag(Loc, VLADiag);
2243 if (VLAIsError)
2244 return QualType();
2245
2246 T = Context.getVariableArrayType(T, nullptr, ASM, Quals);
2247 } else {
2248 T = Context.getIncompleteArrayType(T, ASM, Quals);
2249 }
2250 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2251 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals);
2252 } else {
2253 ExprResult R =
2254 checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError);
2255 if (R.isInvalid())
2256 return QualType();
2257
2258 if (!R.isUsable()) {
2259 // C99: an array with a non-ICE size is a VLA. We accept any expression
2260 // that we can fold to a non-zero positive value as a non-VLA as an
2261 // extension.
2262 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals);
2263 } else if (!T->isDependentType() && !T->isIncompleteType() &&
2264 !T->isConstantSizeType()) {
2265 // C99: an array with an element type that has a non-constant-size is a
2266 // VLA.
2267 // FIXME: Add a note to explain why this isn't a VLA.
2268 Diag(Loc, VLADiag);
2269 if (VLAIsError)
2270 return QualType();
2271 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals);
2272 } else {
2273 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2274 // have a value greater than zero.
2275 // In C++, this follows from narrowing conversions being disallowed.
2276 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2277 if (Entity)
2278 Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2279 << getPrintableNameForEntity(Entity)
2280 << ArraySize->getSourceRange();
2281 else
2282 Diag(ArraySize->getBeginLoc(),
2283 diag::err_typecheck_negative_array_size)
2284 << ArraySize->getSourceRange();
2285 return QualType();
2286 }
2287 if (ConstVal == 0 && !T.isWebAssemblyReferenceType()) {
2288 if (getLangOpts().OpenCL) {
2289 Diag(ArraySize->getBeginLoc(), diag::err_typecheck_zero_array_size)
2290 << 3 << ArraySize->getSourceRange();
2291 return QualType();
2292 }
2293
2294 // GCC accepts zero sized static arrays. We allow them when
2295 // we're not in a SFINAE context.
2296 Diag(ArraySize->getBeginLoc(),
2297 isSFINAEContext() ? diag::err_typecheck_zero_array_size
2298 : diag::ext_typecheck_zero_array_size)
2299 << 0 << ArraySize->getSourceRange();
2300 if (isSFINAEContext())
2301 return QualType();
2302 }
2303
2304 // Is the array too large?
2305 unsigned ActiveSizeBits =
2306 (!T->isDependentType() && !T->isVariablyModifiedType() &&
2307 !T->isIncompleteType() && !T->isUndeducedType())
2309 : ConstVal.getActiveBits();
2310 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2311 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2312 << toString(ConstVal, 10, ConstVal.isSigned(),
2313 /*formatAsCLiteral=*/false, /*UpperCase=*/false,
2314 /*InsertSeparators=*/true)
2315 << ArraySize->getSourceRange();
2316 return QualType();
2317 }
2318
2319 T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2320 }
2321 }
2322
2323 if (T->isVariableArrayType()) {
2324 if (!Context.getTargetInfo().isVLASupported()) {
2325 // CUDA device code and some other targets don't support VLAs.
2326 bool IsCUDADevice = (getLangOpts().CUDA && getLangOpts().CUDAIsDevice);
2327 targetDiag(Loc,
2328 IsCUDADevice ? diag::err_cuda_vla : diag::err_vla_unsupported)
2329 << (IsCUDADevice ? llvm::to_underlying(CUDA().CurrentTarget()) : 0);
2330 } else if (sema::FunctionScopeInfo *FSI = getCurFunction()) {
2331 // VLAs are supported on this target, but we may need to do delayed
2332 // checking that the VLA is not being used within a coroutine.
2333 FSI->setHasVLA(Loc);
2334 }
2335 }
2336
2337 // If this is not C99, diagnose array size modifiers on non-VLAs.
2338 if (!getLangOpts().C99 && !T->isVariableArrayType() &&
2339 (ASM != ArraySizeModifier::Normal || Quals != 0)) {
2340 Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx
2341 : diag::ext_c99_array_usage)
2342 << ASM;
2343 }
2344
2345 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2346 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2347 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2348 if (getLangOpts().OpenCL) {
2349 const QualType ArrType = Context.getBaseElementType(T);
2350 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2351 ArrType->isSamplerT() || ArrType->isImageType()) {
2352 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2353 return QualType();
2354 }
2355 }
2356
2357 return T;
2358}
2359
2361 const BitIntType *BIT,
2362 bool ForMatrixType = false) {
2363 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2364 unsigned NumBits = BIT->getNumBits();
2365 if (!llvm::isPowerOf2_32(NumBits))
2366 return S.Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2367 << ForMatrixType;
2368 return false;
2369}
2370
2372 SourceLocation AttrLoc) {
2373 // The base type must be integer (not Boolean or enumeration) or float, and
2374 // can't already be a vector.
2375 if ((!CurType->isDependentType() &&
2376 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2377 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) &&
2378 !CurType->isBitIntType()) ||
2379 CurType->isArrayType()) {
2380 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2381 return QualType();
2382 }
2383
2384 if (const auto *BIT = CurType->getAs<BitIntType>();
2385 BIT && CheckBitIntElementType(*this, AttrLoc, BIT))
2386 return QualType();
2387
2388 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2389 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2391
2392 std::optional<llvm::APSInt> VecSize =
2394 if (!VecSize) {
2395 Diag(AttrLoc, diag::err_attribute_argument_type)
2396 << "vector_size" << AANT_ArgumentIntegerConstant
2397 << SizeExpr->getSourceRange();
2398 return QualType();
2399 }
2400
2401 if (VecSize->isNegative()) {
2402 Diag(SizeExpr->getExprLoc(), diag::err_attribute_vec_negative_size);
2403 return QualType();
2404 }
2405
2406 if (CurType->isDependentType())
2407 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2409
2410 // vecSize is specified in bytes - convert to bits.
2411 if (!VecSize->isIntN(61)) {
2412 // Bit size will overflow uint64.
2413 Diag(AttrLoc, diag::err_attribute_size_too_large)
2414 << SizeExpr->getSourceRange() << "vector";
2415 return QualType();
2416 }
2417 uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2418 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2419
2420 if (VectorSizeBits == 0) {
2421 Diag(AttrLoc, diag::err_attribute_zero_size)
2422 << SizeExpr->getSourceRange() << "vector";
2423 return QualType();
2424 }
2425
2426 if (!TypeSize || VectorSizeBits % TypeSize) {
2427 Diag(AttrLoc, diag::err_attribute_invalid_size)
2428 << SizeExpr->getSourceRange();
2429 return QualType();
2430 }
2431
2432 if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2433 Diag(AttrLoc, diag::err_attribute_size_too_large)
2434 << SizeExpr->getSourceRange() << "vector";
2435 return QualType();
2436 }
2437
2438 return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2440}
2441
2443 SourceLocation AttrLoc) {
2444 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2445 // in conjunction with complex types (pointers, arrays, functions, etc.).
2446 //
2447 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2448 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2449 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2450 // of bool aren't allowed.
2451 //
2452 // We explicitly allow bool elements in ext_vector_type for C/C++.
2453 bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus;
2454 if ((!T->isDependentType() && !T->isIntegerType() &&
2455 !T->isRealFloatingType()) ||
2456 (IsNoBoolVecLang && T->isBooleanType())) {
2457 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2458 return QualType();
2459 }
2460
2461 if (const auto *BIT = T->getAs<BitIntType>();
2462 BIT && CheckBitIntElementType(*this, AttrLoc, BIT))
2463 return QualType();
2464
2465 if (!SizeExpr->isTypeDependent() && !SizeExpr->isValueDependent()) {
2466 std::optional<llvm::APSInt> VecSize =
2468 if (!VecSize) {
2469 Diag(AttrLoc, diag::err_attribute_argument_type)
2470 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2471 << SizeExpr->getSourceRange();
2472 return QualType();
2473 }
2474
2475 if (VecSize->isNegative()) {
2476 Diag(SizeExpr->getExprLoc(), diag::err_attribute_vec_negative_size);
2477 return QualType();
2478 }
2479
2480 if (!VecSize->isIntN(32)) {
2481 Diag(AttrLoc, diag::err_attribute_size_too_large)
2482 << SizeExpr->getSourceRange() << "vector";
2483 return QualType();
2484 }
2485 // Unlike gcc's vector_size attribute, the size is specified as the
2486 // number of elements, not the number of bytes.
2487 unsigned VectorSize = static_cast<unsigned>(VecSize->getZExtValue());
2488
2489 if (VectorSize == 0) {
2490 Diag(AttrLoc, diag::err_attribute_zero_size)
2491 << SizeExpr->getSourceRange() << "vector";
2492 return QualType();
2493 }
2494
2495 return Context.getExtVectorType(T, VectorSize);
2496 }
2497
2498 return Context.getDependentSizedExtVectorType(T, SizeExpr, AttrLoc);
2499}
2500
2501QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2502 SourceLocation AttrLoc) {
2503 assert(Context.getLangOpts().MatrixTypes &&
2504 "Should never build a matrix type when it is disabled");
2505
2506 // Check element type, if it is not dependent.
2507 if (!ElementTy->isDependentType() &&
2509 Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2510 return QualType();
2511 }
2512
2513 if (const auto *BIT = ElementTy->getAs<BitIntType>();
2514 BIT &&
2515 CheckBitIntElementType(*this, AttrLoc, BIT, /*ForMatrixType=*/true))
2516 return QualType();
2517
2518 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2519 NumRows->isValueDependent() || NumCols->isValueDependent())
2520 return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2521 AttrLoc);
2522
2523 std::optional<llvm::APSInt> ValueRows =
2525 std::optional<llvm::APSInt> ValueColumns =
2527
2528 auto const RowRange = NumRows->getSourceRange();
2529 auto const ColRange = NumCols->getSourceRange();
2530
2531 // Both are row and column expressions are invalid.
2532 if (!ValueRows && !ValueColumns) {
2533 Diag(AttrLoc, diag::err_attribute_argument_type)
2534 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2535 << ColRange;
2536 return QualType();
2537 }
2538
2539 // Only the row expression is invalid.
2540 if (!ValueRows) {
2541 Diag(AttrLoc, diag::err_attribute_argument_type)
2542 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2543 return QualType();
2544 }
2545
2546 // Only the column expression is invalid.
2547 if (!ValueColumns) {
2548 Diag(AttrLoc, diag::err_attribute_argument_type)
2549 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2550 return QualType();
2551 }
2552
2553 // Check the matrix dimensions.
2554 unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2555 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2556 if (MatrixRows == 0 && MatrixColumns == 0) {
2557 Diag(AttrLoc, diag::err_attribute_zero_size)
2558 << "matrix" << RowRange << ColRange;
2559 return QualType();
2560 }
2561 if (MatrixRows == 0) {
2562 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2563 return QualType();
2564 }
2565 if (MatrixColumns == 0) {
2566 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2567 return QualType();
2568 }
2569 if (MatrixRows > Context.getLangOpts().MaxMatrixDimension &&
2570 MatrixColumns > Context.getLangOpts().MaxMatrixDimension) {
2571 Diag(AttrLoc, diag::err_attribute_size_too_large)
2572 << RowRange << ColRange << "matrix row and column";
2573 return QualType();
2574 }
2575 if (MatrixRows > Context.getLangOpts().MaxMatrixDimension) {
2576 Diag(AttrLoc, diag::err_attribute_size_too_large)
2577 << RowRange << "matrix row";
2578 return QualType();
2579 }
2580 if (MatrixColumns > Context.getLangOpts().MaxMatrixDimension) {
2581 Diag(AttrLoc, diag::err_attribute_size_too_large)
2582 << ColRange << "matrix column";
2583 return QualType();
2584 }
2585 return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2586}
2587
2589 if ((T->isArrayType() && !getLangOpts().allowArrayReturnTypes()) ||
2590 T->isFunctionType()) {
2591 Diag(Loc, diag::err_func_returning_array_function)
2592 << T->isFunctionType() << T;
2593 return true;
2594 }
2595
2596 // Functions cannot return half FP.
2597 if (T->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2598 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2599 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2601 return true;
2602 }
2603
2604 // Methods cannot return interface types. All ObjC objects are
2605 // passed by reference.
2606 if (T->isObjCObjectType()) {
2607 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2608 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2609 return true;
2610 }
2611
2612 // __ptrauth is illegal on a function return type.
2613 if (T.getPointerAuth()) {
2614 Diag(Loc, diag::err_ptrauth_qualifier_invalid) << T << 0;
2615 return true;
2616 }
2617
2618 if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2619 T.hasNonTrivialToPrimitiveCopyCUnion())
2622
2623 // C++2a [dcl.fct]p12:
2624 // A volatile-qualified return type is deprecated
2625 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2626 Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2627
2628 if (T.getAddressSpace() != LangAS::Default && getLangOpts().HLSL)
2629 return true;
2630 return false;
2631}
2632
2633/// Check the extended parameter information. Most of the necessary
2634/// checking should occur when applying the parameter attribute; the
2635/// only other checks required are positional restrictions.
2638 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2639 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2640
2641 bool emittedError = false;
2642 auto actualCC = EPI.ExtInfo.getCC();
2643 enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
2644 auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
2645 bool isCompatible =
2646 (required == RequiredCC::OnlySwift)
2647 ? (actualCC == CC_Swift)
2648 : (actualCC == CC_Swift || actualCC == CC_SwiftAsync);
2649 if (isCompatible || emittedError)
2650 return;
2651 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2653 << (required == RequiredCC::OnlySwift);
2654 emittedError = true;
2655 };
2656 for (size_t paramIndex = 0, numParams = paramTypes.size();
2657 paramIndex != numParams; ++paramIndex) {
2658 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2659 // Nothing interesting to check for orindary-ABI parameters.
2663 continue;
2664
2665 // swift_indirect_result parameters must be a prefix of the function
2666 // arguments.
2668 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2669 if (paramIndex != 0 &&
2670 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2672 S.Diag(getParamLoc(paramIndex),
2673 diag::err_swift_indirect_result_not_first);
2674 }
2675 continue;
2676
2678 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2679 continue;
2680
2681 // SwiftAsyncContext is not limited to swiftasynccall functions.
2683 continue;
2684
2685 // swift_error parameters must be preceded by a swift_context parameter.
2687 checkCompatible(paramIndex, RequiredCC::OnlySwift);
2688 if (paramIndex == 0 ||
2689 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2691 S.Diag(getParamLoc(paramIndex),
2692 diag::err_swift_error_result_not_after_swift_context);
2693 }
2694 continue;
2695 }
2696 llvm_unreachable("bad ABI kind");
2697 }
2698}
2699
2701 MutableArrayRef<QualType> ParamTypes,
2702 SourceLocation Loc, DeclarationName Entity,
2704 bool Invalid = false;
2705
2707
2708 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2709 // FIXME: Loc is too inprecise here, should use proper locations for args.
2710 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2711 if (ParamType->isVoidType()) {
2712 Diag(Loc, diag::err_param_with_void_type);
2713 Invalid = true;
2714 } else if (ParamType->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2715 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2716 // Disallow half FP arguments.
2717 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2719 Invalid = true;
2720 } else if (ParamType->isWebAssemblyTableType()) {
2721 Diag(Loc, diag::err_wasm_table_as_function_parameter);
2722 Invalid = true;
2723 } else if (ParamType.getPointerAuth()) {
2724 // __ptrauth is illegal on a function return type.
2725 Diag(Loc, diag::err_ptrauth_qualifier_invalid) << T << 1;
2726 Invalid = true;
2727 }
2728
2729 // C++2a [dcl.fct]p4:
2730 // A parameter with volatile-qualified type is deprecated
2731 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
2732 Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
2733
2734 ParamTypes[Idx] = ParamType;
2735 }
2736
2737 if (EPI.ExtParameterInfos) {
2738 checkExtParameterInfos(*this, ParamTypes, EPI,
2739 [=](unsigned i) { return Loc; });
2740 }
2741
2742 if (EPI.ExtInfo.getProducesResult()) {
2743 // This is just a warning, so we can't fail to build if we see it.
2745 }
2746
2747 if (Invalid)
2748 return QualType();
2749
2750 return Context.getFunctionType(T, ParamTypes, EPI);
2751}
2752
2754 CXXRecordDecl *Cls, SourceLocation Loc,
2755 DeclarationName Entity) {
2756 if (!Cls && !isDependentScopeSpecifier(SS)) {
2757 Cls = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS));
2758 if (!Cls) {
2759 auto D =
2760 Diag(SS.getBeginLoc(), diag::err_illegal_decl_mempointer_in_nonclass)
2761 << SS.getRange();
2762 if (const IdentifierInfo *II = Entity.getAsIdentifierInfo())
2763 D << II;
2764 else
2765 D << "member pointer";
2766 return QualType();
2767 }
2768 }
2769
2770 // Verify that we're not building a pointer to pointer to function with
2771 // exception specification.
2773 Diag(Loc, diag::err_distant_exception_spec);
2774 return QualType();
2775 }
2776
2777 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2778 // with reference type, or "cv void."
2779 if (T->isReferenceType()) {
2780 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2781 << getPrintableNameForEntity(Entity) << T;
2782 return QualType();
2783 }
2784
2785 if (T->isVoidType()) {
2786 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2787 << getPrintableNameForEntity(Entity);
2788 return QualType();
2789 }
2790
2791 if (T->isFunctionType() && getLangOpts().OpenCL &&
2792 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2793 getLangOpts())) {
2794 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2795 return QualType();
2796 }
2797
2798 if (getLangOpts().HLSL && Loc.isValid()) {
2799 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
2800 return QualType();
2801 }
2802
2803 // Adjust the default free function calling convention to the default method
2804 // calling convention.
2805 bool IsCtorOrDtor =
2808 if (T->isFunctionType())
2809 adjustMemberFunctionCC(T, /*HasThisPointer=*/true, IsCtorOrDtor, Loc);
2810
2811 return Context.getMemberPointerType(T, SS.getScopeRep(), Cls);
2812}
2813
2815 SourceLocation Loc,
2816 DeclarationName Entity) {
2817 if (!T->isFunctionType()) {
2818 Diag(Loc, diag::err_nonfunction_block_type);
2819 return QualType();
2820 }
2821
2822 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2823 return QualType();
2824
2825 if (getLangOpts().OpenCL)
2826 T = deduceOpenCLPointeeAddrSpace(*this, T);
2827
2828 return Context.getBlockPointerType(T);
2829}
2830
2832 QualType QT = Ty.get();
2833 if (QT.isNull()) {
2834 if (TInfo) *TInfo = nullptr;
2835 return QualType();
2836 }
2837
2838 TypeSourceInfo *TSI = nullptr;
2839 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2840 QT = LIT->getType();
2841 TSI = LIT->getTypeSourceInfo();
2842 }
2843
2844 if (TInfo)
2845 *TInfo = TSI;
2846 return QT;
2847}
2848
2849static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2850 Qualifiers::ObjCLifetime ownership,
2851 unsigned chunkIndex);
2852
2853/// Given that this is the declaration of a parameter under ARC,
2854/// attempt to infer attributes and such for pointer-to-whatever
2855/// types.
2856static void inferARCWriteback(TypeProcessingState &state,
2857 QualType &declSpecType) {
2858 Sema &S = state.getSema();
2859 Declarator &declarator = state.getDeclarator();
2860
2861 // TODO: should we care about decl qualifiers?
2862
2863 // Check whether the declarator has the expected form. We walk
2864 // from the inside out in order to make the block logic work.
2865 unsigned outermostPointerIndex = 0;
2866 bool isBlockPointer = false;
2867 unsigned numPointers = 0;
2868 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2869 unsigned chunkIndex = i;
2870 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2871 switch (chunk.Kind) {
2873 // Ignore parens.
2874 break;
2875
2878 // Count the number of pointers. Treat references
2879 // interchangeably as pointers; if they're mis-ordered, normal
2880 // type building will discover that.
2881 outermostPointerIndex = chunkIndex;
2882 numPointers++;
2883 break;
2884
2886 // If we have a pointer to block pointer, that's an acceptable
2887 // indirect reference; anything else is not an application of
2888 // the rules.
2889 if (numPointers != 1) return;
2890 numPointers++;
2891 outermostPointerIndex = chunkIndex;
2892 isBlockPointer = true;
2893
2894 // We don't care about pointer structure in return values here.
2895 goto done;
2896
2897 case DeclaratorChunk::Array: // suppress if written (id[])?
2901 return;
2902 }
2903 }
2904 done:
2905
2906 // If we have *one* pointer, then we want to throw the qualifier on
2907 // the declaration-specifiers, which means that it needs to be a
2908 // retainable object type.
2909 if (numPointers == 1) {
2910 // If it's not a retainable object type, the rule doesn't apply.
2911 if (!declSpecType->isObjCRetainableType()) return;
2912
2913 // If it already has lifetime, don't do anything.
2914 if (declSpecType.getObjCLifetime()) return;
2915
2916 // Otherwise, modify the type in-place.
2917 Qualifiers qs;
2918
2919 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2921 else
2923 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2924
2925 // If we have *two* pointers, then we want to throw the qualifier on
2926 // the outermost pointer.
2927 } else if (numPointers == 2) {
2928 // If we don't have a block pointer, we need to check whether the
2929 // declaration-specifiers gave us something that will turn into a
2930 // retainable object pointer after we slap the first pointer on it.
2931 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2932 return;
2933
2934 // Look for an explicit lifetime attribute there.
2935 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2936 if (chunk.Kind != DeclaratorChunk::Pointer &&
2938 return;
2939 for (const ParsedAttr &AL : chunk.getAttrs())
2940 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
2941 return;
2942
2944 outermostPointerIndex);
2945
2946 // Any other number of pointers/references does not trigger the rule.
2947 } else return;
2948
2949 // TODO: mark whether we did this inference?
2950}
2951
2952void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2953 SourceLocation FallbackLoc,
2954 SourceLocation ConstQualLoc,
2955 SourceLocation VolatileQualLoc,
2956 SourceLocation RestrictQualLoc,
2957 SourceLocation AtomicQualLoc,
2958 SourceLocation UnalignedQualLoc) {
2959 if (!Quals)
2960 return;
2961
2962 struct Qual {
2963 const char *Name;
2964 unsigned Mask;
2965 SourceLocation Loc;
2966 } const QualKinds[5] = {
2967 { "const", DeclSpec::TQ_const, ConstQualLoc },
2968 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2969 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2970 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2971 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2972 };
2973
2974 SmallString<32> QualStr;
2975 unsigned NumQuals = 0;
2976 SourceLocation Loc;
2977 FixItHint FixIts[5];
2978
2979 // Build a string naming the redundant qualifiers.
2980 for (auto &E : QualKinds) {
2981 if (Quals & E.Mask) {
2982 if (!QualStr.empty()) QualStr += ' ';
2983 QualStr += E.Name;
2984
2985 // If we have a location for the qualifier, offer a fixit.
2986 SourceLocation QualLoc = E.Loc;
2987 if (QualLoc.isValid()) {
2988 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2989 if (Loc.isInvalid() ||
2990 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2991 Loc = QualLoc;
2992 }
2993
2994 ++NumQuals;
2995 }
2996 }
2997
2998 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2999 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
3000}
3001
3002// Diagnose pointless type qualifiers on the return type of a function.
3004 Declarator &D,
3005 unsigned FunctionChunkIndex) {
3007 D.getTypeObject(FunctionChunkIndex).Fun;
3008 if (FTI.hasTrailingReturnType()) {
3009 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3010 RetTy.getLocalCVRQualifiers(),
3012 return;
3013 }
3014
3015 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3016 End = D.getNumTypeObjects();
3017 OuterChunkIndex != End; ++OuterChunkIndex) {
3018 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
3019 switch (OuterChunk.Kind) {
3021 continue;
3022
3024 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3026 diag::warn_qual_return_type,
3027 PTI.TypeQuals,
3029 PTI.ConstQualLoc,
3030 PTI.VolatileQualLoc,
3031 PTI.RestrictQualLoc,
3032 PTI.AtomicQualLoc,
3033 PTI.UnalignedQualLoc);
3034 return;
3035 }
3036
3043 // FIXME: We can't currently provide an accurate source location and a
3044 // fix-it hint for these.
3045 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
3046 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3047 RetTy.getCVRQualifiers() | AtomicQual,
3048 D.getIdentifierLoc());
3049 return;
3050 }
3051
3052 llvm_unreachable("unknown declarator chunk kind");
3053 }
3054
3055 // If the qualifiers come from a conversion function type, don't diagnose
3056 // them -- they're not necessarily redundant, since such a conversion
3057 // operator can be explicitly called as "x.operator const int()".
3059 return;
3060
3061 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3062 // which are present there.
3063 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3065 D.getIdentifierLoc(),
3071}
3072
3073static std::pair<QualType, TypeSourceInfo *>
3074InventTemplateParameter(TypeProcessingState &state, QualType T,
3075 TypeSourceInfo *TrailingTSI, AutoType *Auto,
3077 Sema &S = state.getSema();
3078 Declarator &D = state.getDeclarator();
3079
3080 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3081 const unsigned AutoParameterPosition = Info.TemplateParams.size();
3082 const bool IsParameterPack = D.hasEllipsis();
3083
3084 // If auto is mentioned in a lambda parameter or abbreviated function
3085 // template context, convert it to a template parameter type.
3086
3087 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3088 // template parameter type. Template parameters are temporarily added
3089 // to the TU until the associated TemplateDecl is created.
3090 TemplateTypeParmDecl *InventedTemplateParam =
3093 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3094 /*NameLoc=*/D.getIdentifierLoc(),
3095 TemplateParameterDepth, AutoParameterPosition,
3097 D.getIdentifier(), AutoParameterPosition), false,
3098 IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3099 InventedTemplateParam->setImplicit();
3100 Info.TemplateParams.push_back(InventedTemplateParam);
3101
3102 // Attach type constraints to the new parameter.
3103 if (Auto->isConstrained()) {
3104 if (TrailingTSI) {
3105 // The 'auto' appears in a trailing return type we've already built;
3106 // extract its type constraints to attach to the template parameter.
3107 AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3108 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3109 bool Invalid = false;
3110 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3111 if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3114 Invalid = true;
3115 TAL.addArgument(AutoLoc.getArgLoc(Idx));
3116 }
3117
3118 if (!Invalid) {
3120 AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3121 AutoLoc.getNamedConcept(), /*FoundDecl=*/AutoLoc.getFoundDecl(),
3122 AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3123 InventedTemplateParam, D.getEllipsisLoc());
3124 }
3125 } else {
3126 // The 'auto' appears in the decl-specifiers; we've not finished forming
3127 // TypeSourceInfo for it yet.
3129 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
3130 TemplateId->RAngleLoc);
3131 bool Invalid = false;
3132 if (TemplateId->LAngleLoc.isValid()) {
3133 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3134 TemplateId->NumArgs);
3135 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3136
3137 if (D.getEllipsisLoc().isInvalid()) {
3138 for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3141 Invalid = true;
3142 break;
3143 }
3144 }
3145 }
3146 }
3147 if (!Invalid) {
3148 UsingShadowDecl *USD =
3149 TemplateId->Template.get().getAsUsingShadowDecl();
3150 TemplateDecl *CD = TemplateId->Template.get().getAsTemplateDecl();
3154 TemplateId->TemplateNameLoc),
3155 CD,
3156 /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
3157 TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3158 InventedTemplateParam, D.getEllipsisLoc());
3159 }
3160 }
3161 }
3162
3163 // Replace the 'auto' in the function parameter with this invented
3164 // template type parameter.
3165 // FIXME: Retain some type sugar to indicate that this was written
3166 // as 'auto'?
3167 QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3168 QualType NewT = state.ReplaceAutoType(T, Replacement);
3169 TypeSourceInfo *NewTSI =
3170 TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)
3171 : nullptr;
3172 return {NewT, NewTSI};
3173}
3174
3175static TypeSourceInfo *
3176GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3177 QualType T, TypeSourceInfo *ReturnTypeInfo);
3178
3179static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3180 TypeSourceInfo *&ReturnTypeInfo) {
3181 Sema &SemaRef = state.getSema();
3182 Declarator &D = state.getDeclarator();
3183 QualType T;
3184 ReturnTypeInfo = nullptr;
3185
3186 // The TagDecl owned by the DeclSpec.
3187 TagDecl *OwnedTagDecl = nullptr;
3188
3189 switch (D.getName().getKind()) {
3195 T = ConvertDeclSpecToType(state);
3196
3197 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3198 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3199 // Owned declaration is embedded in declarator.
3200 OwnedTagDecl->setEmbeddedInDeclarator(true);
3201 }
3202 break;
3203
3207 // Constructors and destructors don't have return types. Use
3208 // "void" instead.
3209 T = SemaRef.Context.VoidTy;
3212 break;
3213
3215 // Deduction guides have a trailing return type and no type in their
3216 // decl-specifier sequence. Use a placeholder return type for now.
3217 T = SemaRef.Context.DependentTy;
3218 break;
3219
3221 // The result type of a conversion function is the type that it
3222 // converts to.
3224 &ReturnTypeInfo);
3225 break;
3226 }
3227
3228 // Note: We don't need to distribute declaration attributes (i.e.
3229 // D.getDeclarationAttributes()) because those are always C++11 attributes,
3230 // and those don't get distributed.
3232 state, T, SemaRef.CUDA().IdentifyTarget(D.getAttributes()));
3233
3234 // Find the deduced type in this type. Look in the trailing return type if we
3235 // have one, otherwise in the DeclSpec type.
3236 // FIXME: The standard wording doesn't currently describe this.
3237 DeducedType *Deduced = T->getContainedDeducedType();
3238 bool DeducedIsTrailingReturnType = false;
3241 Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3242 DeducedIsTrailingReturnType = true;
3243 }
3244
3245 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3246 if (Deduced) {
3247 AutoType *Auto = dyn_cast<AutoType>(Deduced);
3248 int Error = -1;
3249
3250 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3251 // class template argument deduction)?
3252 bool IsCXXAutoType =
3253 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3254 bool IsDeducedReturnType = false;
3255
3256 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3258 AutoRange = D.getName().getSourceRange();
3259
3260 switch (D.getContext()) {
3262 // Declared return type of a lambda-declarator is implicit and is always
3263 // 'auto'.
3264 break;
3267 Error = 0;
3268 break;
3270 Error = 22;
3271 break;
3274 InventedTemplateParameterInfo *Info = nullptr;
3276 // With concepts we allow 'auto' in function parameters.
3277 if (!SemaRef.getLangOpts().CPlusPlus || !Auto ||
3278 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3279 Error = 0;
3280 break;
3281 }
3282
3283 if (!SemaRef.getLangOpts().CPlusPlus20)
3284 SemaRef.DiagCompat(AutoRange.getBegin(), diag_compat::auto_param);
3285
3286 if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3287 Error = 21;
3288 break;
3289 }
3290
3291 Info = &SemaRef.InventedParameterInfos.back();
3292 } else {
3293 // In C++14, generic lambdas allow 'auto' in their parameters.
3294 if (!SemaRef.getLangOpts().CPlusPlus14 && Auto &&
3295 Auto->getKeyword() == AutoTypeKeyword::Auto) {
3296 Error = 25; // auto not allowed in lambda parameter (before C++14)
3297 break;
3298 } else if (!Auto || Auto->getKeyword() != AutoTypeKeyword::Auto) {
3299 Error = 16; // __auto_type or decltype(auto) not allowed in lambda
3300 // parameter
3301 break;
3302 }
3303 Info = SemaRef.getCurLambda();
3304 assert(Info && "No LambdaScopeInfo on the stack!");
3305 }
3306
3307 // We'll deal with inventing template parameters for 'auto' in trailing
3308 // return types when we pick up the trailing return type when processing
3309 // the function chunk.
3310 if (!DeducedIsTrailingReturnType)
3311 T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3312 break;
3313 }
3315 if (D.isStaticMember() || D.isFunctionDeclarator())
3316 break;
3317 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3318 if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3319 Error = 6; // Interface member.
3320 } else {
3321 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3322 case TagTypeKind::Enum:
3323 llvm_unreachable("unhandled tag kind");
3325 Error = Cxx ? 1 : 2; /* Struct member */
3326 break;
3327 case TagTypeKind::Union:
3328 Error = Cxx ? 3 : 4; /* Union member */
3329 break;
3330 case TagTypeKind::Class:
3331 Error = 5; /* Class member */
3332 break;
3334 Error = 6; /* Interface member */
3335 break;
3336 }
3337 }
3339 Error = 20; // Friend type
3340 break;
3341 }
3344 Error = 7; // Exception declaration
3345 break;
3348 !SemaRef.getLangOpts().CPlusPlus20)
3349 Error = 19; // Template parameter (until C++20)
3350 else if (!SemaRef.getLangOpts().CPlusPlus17)
3351 Error = 8; // Template parameter (until C++17)
3352 break;
3354 Error = 9; // Block literal
3355 break;
3357 // Within a template argument list, a deduced template specialization
3358 // type will be reinterpreted as a template template argument.
3360 !D.getNumTypeObjects() &&
3362 break;
3363 [[fallthrough]];
3365 Error = 10; // Template type argument
3366 break;
3369 Error = 12; // Type alias
3370 break;
3373 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3374 Error = 13; // Function return type
3375 IsDeducedReturnType = true;
3376 break;
3378 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3379 Error = 14; // conversion-type-id
3380 IsDeducedReturnType = true;
3381 break;
3384 break;
3385 if (SemaRef.getLangOpts().CPlusPlus23 && IsCXXAutoType &&
3386 !Auto->isDecltypeAuto())
3387 break; // auto(x)
3388 [[fallthrough]];
3391 Error = 15; // Generic
3392 break;
3398 // FIXME: P0091R3 (erroneously) does not permit class template argument
3399 // deduction in conditions, for-init-statements, and other declarations
3400 // that are not simple-declarations.
3401 break;
3403 // FIXME: P0091R3 does not permit class template argument deduction here,
3404 // but we follow GCC and allow it anyway.
3405 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3406 Error = 17; // 'new' type
3407 break;
3409 Error = 18; // K&R function parameter
3410 break;
3411 }
3412
3414 Error = 11;
3415
3416 // In Objective-C it is an error to use 'auto' on a function declarator
3417 // (and everywhere for '__auto_type').
3418 if (D.isFunctionDeclarator() &&
3419 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3420 Error = 13;
3421
3422 if (Error != -1) {
3423 unsigned Kind;
3424 if (Auto) {
3425 switch (Auto->getKeyword()) {
3426 case AutoTypeKeyword::Auto: Kind = 0; break;
3427 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3428 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3429 }
3430 } else {
3432 "unknown auto type");
3433 Kind = 3;
3434 }
3435
3436 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3437 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3438
3439 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3440 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3441 << QualType(Deduced, 0) << AutoRange;
3442 if (auto *TD = TN.getAsTemplateDecl())
3443 SemaRef.NoteTemplateLocation(*TD);
3444
3445 T = SemaRef.Context.IntTy;
3446 D.setInvalidType(true);
3447 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) {
3448 // If there was a trailing return type, we already got
3449 // warn_cxx98_compat_trailing_return_type in the parser.
3450 // If there was a decltype(auto), we already got
3451 // warn_cxx11_compat_decltype_auto_type_specifier.
3452 unsigned DiagId = 0;
3454 DiagId = diag::warn_cxx11_compat_generic_lambda;
3455 else if (IsDeducedReturnType)
3456 DiagId = diag::warn_cxx11_compat_deduced_return_type;
3457 else if (Auto->getKeyword() == AutoTypeKeyword::Auto)
3458 DiagId = diag::warn_cxx98_compat_auto_type_specifier;
3459
3460 if (DiagId)
3461 SemaRef.Diag(AutoRange.getBegin(), DiagId) << AutoRange;
3462 }
3463 }
3464
3465 if (SemaRef.getLangOpts().CPlusPlus &&
3466 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3467 // Check the contexts where C++ forbids the declaration of a new class
3468 // or enumeration in a type-specifier-seq.
3469 unsigned DiagID = 0;
3470 switch (D.getContext()) {
3473 // Class and enumeration definitions are syntactically not allowed in
3474 // trailing return types.
3475 llvm_unreachable("parser should not have allowed this");
3476 break;
3484 // C++11 [dcl.type]p3:
3485 // A type-specifier-seq shall not define a class or enumeration unless
3486 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3487 // the declaration of a template-declaration.
3489 break;
3491 DiagID = diag::err_type_defined_in_alias_template;
3492 break;
3503 DiagID = diag::err_type_defined_in_type_specifier;
3504 break;
3511 // C++ [dcl.fct]p6:
3512 // Types shall not be defined in return or parameter types.
3513 DiagID = diag::err_type_defined_in_param_type;
3514 break;
3516 // C++ 6.4p2:
3517 // The type-specifier-seq shall not contain typedef and shall not declare
3518 // a new class or enumeration.
3519 DiagID = diag::err_type_defined_in_condition;
3520 break;
3521 }
3522
3523 if (DiagID != 0) {
3524 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3525 << SemaRef.Context.getCanonicalTagType(OwnedTagDecl);
3526 D.setInvalidType(true);
3527 }
3528 }
3529
3530 assert(!T.isNull() && "This function should not return a null type");
3531 return T;
3532}
3533
3534/// Produce an appropriate diagnostic for an ambiguity between a function
3535/// declarator and a C++ direct-initializer.
3537 DeclaratorChunk &DeclType, QualType RT) {
3538 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3539 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3540
3541 // If the return type is void there is no ambiguity.
3542 if (RT->isVoidType())
3543 return;
3544
3545 // An initializer for a non-class type can have at most one argument.
3546 if (!RT->isRecordType() && FTI.NumParams > 1)
3547 return;
3548
3549 // An initializer for a reference must have exactly one argument.
3550 if (RT->isReferenceType() && FTI.NumParams != 1)
3551 return;
3552
3553 // Only warn if this declarator is declaring a function at block scope, and
3554 // doesn't have a storage class (such as 'extern') specified.
3555 if (!D.isFunctionDeclarator() ||
3559 return;
3560
3561 // Inside a condition, a direct initializer is not permitted. We allow one to
3562 // be parsed in order to give better diagnostics in condition parsing.
3564 return;
3565
3566 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3567
3568 S.Diag(DeclType.Loc,
3569 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3570 : diag::warn_empty_parens_are_function_decl)
3571 << ParenRange;
3572
3573 // If the declaration looks like:
3574 // T var1,
3575 // f();
3576 // and name lookup finds a function named 'f', then the ',' was
3577 // probably intended to be a ';'.
3578 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3579 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3581 if (Comma.getFileID() != Name.getFileID() ||
3582 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3585 if (S.LookupName(Result, S.getCurScope()))
3586 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3588 << D.getIdentifier();
3589 Result.suppressDiagnostics();
3590 }
3591 }
3592
3593 if (FTI.NumParams > 0) {
3594 // For a declaration with parameters, eg. "T var(T());", suggest adding
3595 // parens around the first parameter to turn the declaration into a
3596 // variable declaration.
3597 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3598 SourceLocation B = Range.getBegin();
3599 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3600 // FIXME: Maybe we should suggest adding braces instead of parens
3601 // in C++11 for classes that don't have an initializer_list constructor.
3602 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3604 << FixItHint::CreateInsertion(E, ")");
3605 } else {
3606 // For a declaration without parameters, eg. "T var();", suggest replacing
3607 // the parens with an initializer to turn the declaration into a variable
3608 // declaration.
3609 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3610
3611 // Empty parens mean value-initialization, and no parens mean
3612 // default initialization. These are equivalent if the default
3613 // constructor is user-provided or if zero-initialization is a
3614 // no-op.
3615 if (RD && RD->hasDefinition() &&
3617 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3618 << FixItHint::CreateRemoval(ParenRange);
3619 else {
3620 std::string Init =
3621 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3622 if (Init.empty() && S.LangOpts.CPlusPlus11)
3623 Init = "{}";
3624 if (!Init.empty())
3625 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3626 << FixItHint::CreateReplacement(ParenRange, Init);
3627 }
3628 }
3629}
3630
3631/// Produce an appropriate diagnostic for a declarator with top-level
3632/// parentheses.
3635 assert(Paren.Kind == DeclaratorChunk::Paren &&
3636 "do not have redundant top-level parentheses");
3637
3638 // This is a syntactic check; we're not interested in cases that arise
3639 // during template instantiation.
3641 return;
3642
3643 // Check whether this could be intended to be a construction of a temporary
3644 // object in C++ via a function-style cast.
3645 bool CouldBeTemporaryObject =
3646 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3647 !D.isInvalidType() && D.getIdentifier() &&
3649 (T->isRecordType() || T->isDependentType()) &&
3651
3652 bool StartsWithDeclaratorId = true;
3653 for (auto &C : D.type_objects()) {
3654 switch (C.Kind) {
3656 if (&C == &Paren)
3657 continue;
3658 [[fallthrough]];
3660 StartsWithDeclaratorId = false;
3661 continue;
3662
3664 if (!C.Arr.NumElts)
3665 CouldBeTemporaryObject = false;
3666 continue;
3667
3669 // FIXME: Suppress the warning here if there is no initializer; we're
3670 // going to give an error anyway.
3671 // We assume that something like 'T (&x) = y;' is highly likely to not
3672 // be intended to be a temporary object.
3673 CouldBeTemporaryObject = false;
3674 StartsWithDeclaratorId = false;
3675 continue;
3676
3678 // In a new-type-id, function chunks require parentheses.
3680 return;
3681 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3682 // redundant-parens warning, but we don't know whether the function
3683 // chunk was syntactically valid as an expression here.
3684 CouldBeTemporaryObject = false;
3685 continue;
3686
3690 // These cannot appear in expressions.
3691 CouldBeTemporaryObject = false;
3692 StartsWithDeclaratorId = false;
3693 continue;
3694 }
3695 }
3696
3697 // FIXME: If there is an initializer, assume that this is not intended to be
3698 // a construction of a temporary object.
3699
3700 // Check whether the name has already been declared; if not, this is not a
3701 // function-style cast.
3702 if (CouldBeTemporaryObject) {
3705 if (!S.LookupName(Result, S.getCurScope()))
3706 CouldBeTemporaryObject = false;
3707 Result.suppressDiagnostics();
3708 }
3709
3710 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3711
3712 if (!CouldBeTemporaryObject) {
3713 // If we have A (::B), the parentheses affect the meaning of the program.
3714 // Suppress the warning in that case. Don't bother looking at the DeclSpec
3715 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3716 // formally unambiguous.
3717 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3719 for (;;) {
3720 switch (NNS.getKind()) {
3722 return;
3724 NNS = NNS.getAsType()->getPrefix();
3725 continue;
3727 NNS = NNS.getAsNamespaceAndPrefix().Prefix;
3728 continue;
3729 default:
3730 goto out;
3731 }
3732 }
3733 out:;
3734 }
3735
3736 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3737 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3739 return;
3740 }
3741
3742 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3743 << ParenRange << D.getIdentifier();
3744 auto *RD = T->getAsCXXRecordDecl();
3745 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3746 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3747 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3748 << D.getIdentifier();
3749 // FIXME: A cast to void is probably a better suggestion in cases where it's
3750 // valid (when there is no initializer and we're not in a condition).
3751 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3754 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3757}
3758
3759/// Helper for figuring out the default CC for a function declarator type. If
3760/// this is the outermost chunk, then we can determine the CC from the
3761/// declarator context. If not, then this could be either a member function
3762/// type or normal function type.
3764 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3765 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3766 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3767
3768 // Check for an explicit CC attribute.
3769 for (const ParsedAttr &AL : AttrList) {
3770 switch (AL.getKind()) {
3772 // Ignore attributes that don't validate or can't apply to the
3773 // function type. We'll diagnose the failure to apply them in
3774 // handleFunctionTypeAttr.
3775 CallingConv CC;
3776 if (!S.CheckCallingConvAttr(AL, CC, /*FunctionDecl=*/nullptr,
3777 S.CUDA().IdentifyTarget(D.getAttributes())) &&
3778 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3779 return CC;
3780 }
3781 break;
3782 }
3783
3784 default:
3785 break;
3786 }
3787 }
3788
3789 bool IsCXXInstanceMethod = false;
3790
3791 if (S.getLangOpts().CPlusPlus) {
3792 // Look inwards through parentheses to see if this chunk will form a
3793 // member pointer type or if we're the declarator. Any type attributes
3794 // between here and there will override the CC we choose here.
3795 unsigned I = ChunkIndex;
3796 bool FoundNonParen = false;
3797 while (I && !FoundNonParen) {
3798 --I;
3800 FoundNonParen = true;
3801 }
3802
3803 if (FoundNonParen) {
3804 // If we're not the declarator, we're a regular function type unless we're
3805 // in a member pointer.
3806 IsCXXInstanceMethod =
3808 } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
3809 // This can only be a call operator for a lambda, which is an instance
3810 // method, unless explicitly specified as 'static'.
3811 IsCXXInstanceMethod =
3813 } else {
3814 // We're the innermost decl chunk, so must be a function declarator.
3815 assert(D.isFunctionDeclarator());
3816
3817 // If we're inside a record, we're declaring a method, but it could be
3818 // explicitly or implicitly static.
3819 IsCXXInstanceMethod =
3822 !D.isStaticMember();
3823 }
3824 }
3825
3827 IsCXXInstanceMethod);
3828
3829 if (S.getLangOpts().CUDA) {
3830 // If we're compiling CUDA/HIP code and targeting HIPSPV we need to make
3831 // sure the kernels will be marked with the right calling convention so that
3832 // they will be visible by the APIs that ingest SPIR-V. We do not do this
3833 // when targeting AMDGCNSPIRV, as it does not rely on OpenCL.
3834 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
3835 if (Triple.isSPIRV() && Triple.getVendor() != llvm::Triple::AMD) {
3836 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3837 if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) {
3838 CC = CC_DeviceKernel;
3839 break;
3840 }
3841 }
3842 }
3843 }
3844
3845 for (const ParsedAttr &AL : llvm::concat<ParsedAttr>(
3848 if (AL.getKind() == ParsedAttr::AT_DeviceKernel) {
3849 CC = CC_DeviceKernel;
3850 break;
3851 }
3852 }
3853 return CC;
3854}
3855
3856namespace {
3857 /// A simple notion of pointer kinds, which matches up with the various
3858 /// pointer declarators.
3859 enum class SimplePointerKind {
3860 Pointer,
3861 BlockPointer,
3862 MemberPointer,
3863 Array,
3864 };
3865} // end anonymous namespace
3866
3868 switch (nullability) {
3870 if (!Ident__Nonnull)
3871 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3872 return Ident__Nonnull;
3873
3875 if (!Ident__Nullable)
3876 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3877 return Ident__Nullable;
3878
3880 if (!Ident__Nullable_result)
3881 Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
3882 return Ident__Nullable_result;
3883
3885 if (!Ident__Null_unspecified)
3886 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3887 return Ident__Null_unspecified;
3888 }
3889 llvm_unreachable("Unknown nullability kind.");
3890}
3891
3892/// Check whether there is a nullability attribute of any kind in the given
3893/// attribute list.
3894static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
3895 for (const ParsedAttr &AL : attrs) {
3896 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
3897 AL.getKind() == ParsedAttr::AT_TypeNullable ||
3898 AL.getKind() == ParsedAttr::AT_TypeNullableResult ||
3899 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
3900 return true;
3901 }
3902
3903 return false;
3904}
3905
3906namespace {
3907 /// Describes the kind of a pointer a declarator describes.
3908 enum class PointerDeclaratorKind {
3909 // Not a pointer.
3910 NonPointer,
3911 // Single-level pointer.
3912 SingleLevelPointer,
3913 // Multi-level pointer (of any pointer kind).
3914 MultiLevelPointer,
3915 // CFFooRef*
3916 MaybePointerToCFRef,
3917 // CFErrorRef*
3918 CFErrorRefPointer,
3919 // NSError**
3920 NSErrorPointerPointer,
3921 };
3922
3923 /// Describes a declarator chunk wrapping a pointer that marks inference as
3924 /// unexpected.
3925 // These values must be kept in sync with diagnostics.
3926 enum class PointerWrappingDeclaratorKind {
3927 /// Pointer is top-level.
3928 None = -1,
3929 /// Pointer is an array element.
3930 Array = 0,
3931 /// Pointer is the referent type of a C++ reference.
3932 Reference = 1
3933 };
3934} // end anonymous namespace
3935
3936/// Classify the given declarator, whose type-specified is \c type, based on
3937/// what kind of pointer it refers to.
3938///
3939/// This is used to determine the default nullability.
3940static PointerDeclaratorKind
3942 PointerWrappingDeclaratorKind &wrappingKind) {
3943 unsigned numNormalPointers = 0;
3944
3945 // For any dependent type, we consider it a non-pointer.
3946 if (type->isDependentType())
3947 return PointerDeclaratorKind::NonPointer;
3948
3949 // Look through the declarator chunks to identify pointers.
3950 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3951 DeclaratorChunk &chunk = declarator.getTypeObject(i);
3952 switch (chunk.Kind) {
3954 if (numNormalPointers == 0)
3955 wrappingKind = PointerWrappingDeclaratorKind::Array;
3956 break;
3957
3960 break;
3961
3964 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3965 : PointerDeclaratorKind::SingleLevelPointer;
3966
3968 break;
3969
3971 if (numNormalPointers == 0)
3972 wrappingKind = PointerWrappingDeclaratorKind::Reference;
3973 break;
3974
3976 ++numNormalPointers;
3977 if (numNormalPointers > 2)
3978 return PointerDeclaratorKind::MultiLevelPointer;
3979 break;
3980 }
3981 }
3982
3983 // Then, dig into the type specifier itself.
3984 unsigned numTypeSpecifierPointers = 0;
3985 do {
3986 // Decompose normal pointers.
3987 if (auto ptrType = type->getAs<PointerType>()) {
3988 ++numNormalPointers;
3989
3990 if (numNormalPointers > 2)
3991 return PointerDeclaratorKind::MultiLevelPointer;
3992
3993 type = ptrType->getPointeeType();
3994 ++numTypeSpecifierPointers;
3995 continue;
3996 }
3997
3998 // Decompose block pointers.
3999 if (type->getAs<BlockPointerType>()) {
4000 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4001 : PointerDeclaratorKind::SingleLevelPointer;
4002 }
4003
4004 // Decompose member pointers.
4005 if (type->getAs<MemberPointerType>()) {
4006 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4007 : PointerDeclaratorKind::SingleLevelPointer;
4008 }
4009
4010 // Look at Objective-C object pointers.
4011 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
4012 ++numNormalPointers;
4013 ++numTypeSpecifierPointers;
4014
4015 // If this is NSError**, report that.
4016 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
4017 if (objcClassDecl->getIdentifier() == S.ObjC().getNSErrorIdent() &&
4018 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
4019 return PointerDeclaratorKind::NSErrorPointerPointer;
4020 }
4021 }
4022
4023 break;
4024 }
4025
4026 // Look at Objective-C class types.
4027 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
4028 if (objcClass->getInterface()->getIdentifier() ==
4029 S.ObjC().getNSErrorIdent()) {
4030 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
4031 return PointerDeclaratorKind::NSErrorPointerPointer;
4032 }
4033
4034 break;
4035 }
4036
4037 // If at this point we haven't seen a pointer, we won't see one.
4038 if (numNormalPointers == 0)
4039 return PointerDeclaratorKind::NonPointer;
4040
4041 if (auto *recordDecl = type->getAsRecordDecl()) {
4042 // If this is CFErrorRef*, report it as such.
4043 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 &&
4044 S.ObjC().isCFError(recordDecl)) {
4045 return PointerDeclaratorKind::CFErrorRefPointer;
4046 }
4047 break;
4048 }
4049
4050 break;
4051 } while (true);
4052
4053 switch (numNormalPointers) {
4054 case 0:
4055 return PointerDeclaratorKind::NonPointer;
4056
4057 case 1:
4058 return PointerDeclaratorKind::SingleLevelPointer;
4059
4060 case 2:
4061 return PointerDeclaratorKind::MaybePointerToCFRef;
4062
4063 default:
4064 return PointerDeclaratorKind::MultiLevelPointer;
4065 }
4066}
4067
4069 SourceLocation loc) {
4070 // If we're anywhere in a function, method, or closure context, don't perform
4071 // completeness checks.
4072 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
4073 if (ctx->isFunctionOrMethod())
4074 return FileID();
4075
4076 if (ctx->isFileContext())
4077 break;
4078 }
4079
4080 // We only care about the expansion location.
4081 loc = S.SourceMgr.getExpansionLoc(loc);
4082 FileID file = S.SourceMgr.getFileID(loc);
4083 if (file.isInvalid())
4084 return FileID();
4085
4086 // Retrieve file information.
4087 bool invalid = false;
4088 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4089 if (invalid || !sloc.isFile())
4090 return FileID();
4091
4092 // We don't want to perform completeness checks on the main file or in
4093 // system headers.
4094 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4095 if (fileInfo.getIncludeLoc().isInvalid())
4096 return FileID();
4097 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4099 return FileID();
4100 }
4101
4102 return file;
4103}
4104
4105/// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4106/// taking into account whitespace before and after.
4107template <typename DiagBuilderT>
4108static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4109 SourceLocation PointerLoc,
4110 NullabilityKind Nullability) {
4111 assert(PointerLoc.isValid());
4112 if (PointerLoc.isMacroID())
4113 return;
4114
4115 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4116 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4117 return;
4118
4119 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4120 if (!NextChar)
4121 return;
4122
4123 SmallString<32> InsertionTextBuf{" "};
4124 InsertionTextBuf += getNullabilitySpelling(Nullability);
4125 InsertionTextBuf += " ";
4126 StringRef InsertionText = InsertionTextBuf.str();
4127
4128 if (isWhitespace(*NextChar)) {
4129 InsertionText = InsertionText.drop_back();
4130 } else if (NextChar[-1] == '[') {
4131 if (NextChar[0] == ']')
4132 InsertionText = InsertionText.drop_back().drop_front();
4133 else
4134 InsertionText = InsertionText.drop_front();
4135 } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) &&
4136 !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) {
4137 InsertionText = InsertionText.drop_back().drop_front();
4138 }
4139
4140 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4141}
4142
4144 SimplePointerKind PointerKind,
4145 SourceLocation PointerLoc,
4146 SourceLocation PointerEndLoc) {
4147 assert(PointerLoc.isValid());
4148
4149 if (PointerKind == SimplePointerKind::Array) {
4150 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4151 } else {
4152 S.Diag(PointerLoc, diag::warn_nullability_missing)
4153 << static_cast<unsigned>(PointerKind);
4154 }
4155
4156 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4157 if (FixItLoc.isMacroID())
4158 return;
4159
4160 auto addFixIt = [&](NullabilityKind Nullability) {
4161 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4162 Diag << static_cast<unsigned>(Nullability);
4163 Diag << static_cast<unsigned>(PointerKind);
4164 fixItNullability(S, Diag, FixItLoc, Nullability);
4165 };
4166 addFixIt(NullabilityKind::Nullable);
4167 addFixIt(NullabilityKind::NonNull);
4168}
4169
4170/// Complains about missing nullability if the file containing \p pointerLoc
4171/// has other uses of nullability (either the keywords or the \c assume_nonnull
4172/// pragma).
4173///
4174/// If the file has \e not seen other uses of nullability, this particular
4175/// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4176static void
4177checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4178 SourceLocation pointerLoc,
4179 SourceLocation pointerEndLoc = SourceLocation()) {
4180 // Determine which file we're performing consistency checking for.
4181 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4182 if (file.isInvalid())
4183 return;
4184
4185 // If we haven't seen any type nullability in this file, we won't warn now
4186 // about anything.
4187 FileNullability &fileNullability = S.NullabilityMap[file];
4188 if (!fileNullability.SawTypeNullability) {
4189 // If this is the first pointer declarator in the file, and the appropriate
4190 // warning is on, record it in case we need to diagnose it retroactively.
4191 diag::kind diagKind;
4192 if (pointerKind == SimplePointerKind::Array)
4193 diagKind = diag::warn_nullability_missing_array;
4194 else
4195 diagKind = diag::warn_nullability_missing;
4196
4197 if (fileNullability.PointerLoc.isInvalid() &&
4198 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
4199 fileNullability.PointerLoc = pointerLoc;
4200 fileNullability.PointerEndLoc = pointerEndLoc;
4201 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4202 }
4203
4204 return;
4205 }
4206
4207 // Complain about missing nullability.
4208 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4209}
4210
4211/// Marks that a nullability feature has been used in the file containing
4212/// \p loc.
4213///
4214/// If this file already had pointer types in it that were missing nullability,
4215/// the first such instance is retroactively diagnosed.
4216///
4217/// \sa checkNullabilityConsistency
4220 if (file.isInvalid())
4221 return;
4222
4223 FileNullability &fileNullability = S.NullabilityMap[file];
4224 if (fileNullability.SawTypeNullability)
4225 return;
4226 fileNullability.SawTypeNullability = true;
4227
4228 // If we haven't seen any type nullability before, now we have. Retroactively
4229 // diagnose the first unannotated pointer, if there was one.
4230 if (fileNullability.PointerLoc.isInvalid())
4231 return;
4232
4233 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4235 fileNullability.PointerEndLoc);
4236}
4237
4238/// Returns true if any of the declarator chunks before \p endIndex include a
4239/// level of indirection: array, pointer, reference, or pointer-to-member.
4240///
4241/// Because declarator chunks are stored in outer-to-inner order, testing
4242/// every chunk before \p endIndex is testing all chunks that embed the current
4243/// chunk as part of their type.
4244///
4245/// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4246/// end index, in which case all chunks are tested.
4247static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4248 unsigned i = endIndex;
4249 while (i != 0) {
4250 // Walk outwards along the declarator chunks.
4251 --i;
4252 const DeclaratorChunk &DC = D.getTypeObject(i);
4253 switch (DC.Kind) {
4255 break;
4260 return true;
4264 // These are invalid anyway, so just ignore.
4265 break;
4266 }
4267 }
4268 return false;
4269}
4270
4271static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk) {
4272 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4273 Chunk.Kind == DeclaratorChunk::Array);
4274}
4275
4276template<typename AttrT>
4277static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4278 AL.setUsedAsTypeAttr();
4279 return ::new (Ctx) AttrT(Ctx, AL);
4280}
4281
4283 NullabilityKind NK) {
4284 switch (NK) {
4287
4290
4293
4296 }
4297 llvm_unreachable("unknown NullabilityKind");
4298}
4299
4300// Diagnose whether this is a case with the multiple addr spaces.
4301// Returns true if this is an invalid case.
4302// ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4303// by qualifiers for two or more different address spaces."
4305 LangAS ASNew,
4306 SourceLocation AttrLoc) {
4307 if (ASOld != LangAS::Default) {
4308 if (ASOld != ASNew) {
4309 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4310 return true;
4311 }
4312 // Emit a warning if they are identical; it's likely unintended.
4313 S.Diag(AttrLoc,
4314 diag::warn_attribute_address_multiple_identical_qualifiers);
4315 }
4316 return false;
4317}
4318
4319// Whether this is a type broadly expected to have nullability attached.
4320// These types are affected by `#pragma assume_nonnull`, and missing nullability
4321// will be diagnosed with -Wnullability-completeness.
4323 return T->canHaveNullability(/*ResultIfUnknown=*/false) &&
4324 // For now, do not infer/require nullability on C++ smart pointers.
4325 // It's unclear whether the pragma's behavior is useful for C++.
4326 // e.g. treating type-aliases and template-type-parameters differently
4327 // from types of declarations can be surprising.
4329 T->getCanonicalTypeInternal());
4330}
4331
4332static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4333 QualType declSpecType,
4334 TypeSourceInfo *TInfo) {
4335 // The TypeSourceInfo that this function returns will not be a null type.
4336 // If there is an error, this function will fill in a dummy type as fallback.
4337 QualType T = declSpecType;
4338 Declarator &D = state.getDeclarator();
4339 Sema &S = state.getSema();
4340 ASTContext &Context = S.Context;
4341 const LangOptions &LangOpts = S.getLangOpts();
4342
4343 // The name we're declaring, if any.
4344 DeclarationName Name;
4345 if (D.getIdentifier())
4346 Name = D.getIdentifier();
4347
4348 // Does this declaration declare a typedef-name?
4349 bool IsTypedefName =
4353
4354 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4355 bool IsQualifiedFunction = T->isFunctionProtoType() &&
4356 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4357 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4358
4359 // If T is 'decltype(auto)', the only declarators we can have are parens
4360 // and at most one function declarator if this is a function declaration.
4361 // If T is a deduced class template specialization type, only parentheses
4362 // are allowed.
4363 if (auto *DT = T->getAs<DeducedType>()) {
4364 const AutoType *AT = T->getAs<AutoType>();
4365 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4366 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4367 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4368 unsigned Index = E - I - 1;
4369 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4370 unsigned DiagId = IsClassTemplateDeduction
4371 ? diag::err_deduced_class_template_compound_type
4372 : diag::err_decltype_auto_compound_type;
4373 unsigned DiagKind = 0;
4374 switch (DeclChunk.Kind) {
4376 continue;
4378 if (IsClassTemplateDeduction) {
4379 DiagKind = 3;
4380 break;
4381 }
4382 unsigned FnIndex;
4384 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4385 continue;
4386 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4387 break;
4388 }
4392 DiagKind = 0;
4393 break;
4395 DiagKind = 1;
4396 break;
4398 DiagKind = 2;
4399 break;
4401 break;
4402 }
4403
4404 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4405 D.setInvalidType(true);
4406 break;
4407 }
4408 }
4409 }
4410
4411 // Determine whether we should infer _Nonnull on pointer types.
4412 NullabilityKindOrNone inferNullability = std::nullopt;
4413 bool inferNullabilityCS = false;
4414 bool inferNullabilityInnerOnly = false;
4415 bool inferNullabilityInnerOnlyComplete = false;
4416
4417 // Are we in an assume-nonnull region?
4418 bool inAssumeNonNullRegion = false;
4419 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4420 if (assumeNonNullLoc.isValid()) {
4421 inAssumeNonNullRegion = true;
4422 recordNullabilitySeen(S, assumeNonNullLoc);
4423 }
4424
4425 // Whether to complain about missing nullability specifiers or not.
4426 enum {
4427 /// Never complain.
4428 CAMN_No,
4429 /// Complain on the inner pointers (but not the outermost
4430 /// pointer).
4431 CAMN_InnerPointers,
4432 /// Complain about any pointers that don't have nullability
4433 /// specified or inferred.
4434 CAMN_Yes
4435 } complainAboutMissingNullability = CAMN_No;
4436 unsigned NumPointersRemaining = 0;
4437 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4438
4439 if (IsTypedefName) {
4440 // For typedefs, we do not infer any nullability (the default),
4441 // and we only complain about missing nullability specifiers on
4442 // inner pointers.
4443 complainAboutMissingNullability = CAMN_InnerPointers;
4444
4445 if (shouldHaveNullability(T) && !T->getNullability()) {
4446 // Note that we allow but don't require nullability on dependent types.
4447 ++NumPointersRemaining;
4448 }
4449
4450 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4451 DeclaratorChunk &chunk = D.getTypeObject(i);
4452 switch (chunk.Kind) {
4456 break;
4457
4460 ++NumPointersRemaining;
4461 break;
4462
4465 continue;
4466
4468 ++NumPointersRemaining;
4469 continue;
4470 }
4471 }
4472 } else {
4473 bool isFunctionOrMethod = false;
4474 switch (auto context = state.getDeclarator().getContext()) {
4480 isFunctionOrMethod = true;
4481 [[fallthrough]];
4482
4484 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4485 complainAboutMissingNullability = CAMN_No;
4486 break;
4487 }
4488
4489 // Weak properties are inferred to be nullable.
4490 if (state.getDeclarator().isObjCWeakProperty()) {
4491 // Weak properties cannot be nonnull, and should not complain about
4492 // missing nullable attributes during completeness checks.
4493 complainAboutMissingNullability = CAMN_No;
4494 if (inAssumeNonNullRegion) {
4495 inferNullability = NullabilityKind::Nullable;
4496 }
4497 break;
4498 }
4499
4500 [[fallthrough]];
4501
4504 complainAboutMissingNullability = CAMN_Yes;
4505
4506 // Nullability inference depends on the type and declarator.
4507 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4508 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4509 case PointerDeclaratorKind::NonPointer:
4510 case PointerDeclaratorKind::MultiLevelPointer:
4511 // Cannot infer nullability.
4512 break;
4513
4514 case PointerDeclaratorKind::SingleLevelPointer:
4515 // Infer _Nonnull if we are in an assumes-nonnull region.
4516 if (inAssumeNonNullRegion) {
4517 complainAboutInferringWithinChunk = wrappingKind;
4518 inferNullability = NullabilityKind::NonNull;
4519 inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4521 }
4522 break;
4523
4524 case PointerDeclaratorKind::CFErrorRefPointer:
4525 case PointerDeclaratorKind::NSErrorPointerPointer:
4526 // Within a function or method signature, infer _Nullable at both
4527 // levels.
4528 if (isFunctionOrMethod && inAssumeNonNullRegion)
4529 inferNullability = NullabilityKind::Nullable;
4530 break;
4531
4532 case PointerDeclaratorKind::MaybePointerToCFRef:
4533 if (isFunctionOrMethod) {
4534 // On pointer-to-pointer parameters marked cf_returns_retained or
4535 // cf_returns_not_retained, if the outer pointer is explicit then
4536 // infer the inner pointer as _Nullable.
4537 auto hasCFReturnsAttr =
4538 [](const ParsedAttributesView &AttrList) -> bool {
4539 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4540 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4541 };
4542 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4543 if (hasCFReturnsAttr(D.getDeclarationAttributes()) ||
4544 hasCFReturnsAttr(D.getAttributes()) ||
4545 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4546 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4547 inferNullability = NullabilityKind::Nullable;
4548 inferNullabilityInnerOnly = true;
4549 }
4550 }
4551 }
4552 break;
4553 }
4554 break;
4555 }
4556
4558 complainAboutMissingNullability = CAMN_Yes;
4559 break;
4560
4580 // Don't infer in these contexts.
4581 break;
4582 }
4583 }
4584
4585 // Local function that returns true if its argument looks like a va_list.
4586 auto isVaList = [&S](QualType T) -> bool {
4587 auto *typedefTy = T->getAs<TypedefType>();
4588 if (!typedefTy)
4589 return false;
4590 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4591 do {
4592 if (typedefTy->getDecl() == vaListTypedef)
4593 return true;
4594 if (auto *name = typedefTy->getDecl()->getIdentifier())
4595 if (name->isStr("va_list"))
4596 return true;
4597 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4598 } while (typedefTy);
4599 return false;
4600 };
4601
4602 // Local function that checks the nullability for a given pointer declarator.
4603 // Returns true if _Nonnull was inferred.
4604 auto inferPointerNullability =
4605 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4606 SourceLocation pointerEndLoc,
4607 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4608 // We've seen a pointer.
4609 if (NumPointersRemaining > 0)
4610 --NumPointersRemaining;
4611
4612 // If a nullability attribute is present, there's nothing to do.
4613 if (hasNullabilityAttr(attrs))
4614 return nullptr;
4615
4616 // If we're supposed to infer nullability, do so now.
4617 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4618 ParsedAttr::Form form =
4619 inferNullabilityCS
4620 ? ParsedAttr::Form::ContextSensitiveKeyword()
4621 : ParsedAttr::Form::Keyword(false /*IsAlignAs*/,
4622 false /*IsRegularKeywordAttribute*/);
4623 ParsedAttr *nullabilityAttr = Pool.create(
4624 S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4625 AttributeScopeInfo(), nullptr, 0, form);
4626
4627 attrs.addAtEnd(nullabilityAttr);
4628
4629 if (inferNullabilityCS) {
4630 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4631 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4632 }
4633
4634 if (pointerLoc.isValid() &&
4635 complainAboutInferringWithinChunk !=
4636 PointerWrappingDeclaratorKind::None) {
4637 auto Diag =
4638 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4639 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4641 }
4642
4643 if (inferNullabilityInnerOnly)
4644 inferNullabilityInnerOnlyComplete = true;
4645 return nullabilityAttr;
4646 }
4647
4648 // If we're supposed to complain about missing nullability, do so
4649 // now if it's truly missing.
4650 switch (complainAboutMissingNullability) {
4651 case CAMN_No:
4652 break;
4653
4654 case CAMN_InnerPointers:
4655 if (NumPointersRemaining == 0)
4656 break;
4657 [[fallthrough]];
4658
4659 case CAMN_Yes:
4660 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4661 }
4662 return nullptr;
4663 };
4664
4665 // If the type itself could have nullability but does not, infer pointer
4666 // nullability and perform consistency checking.
4667 if (S.CodeSynthesisContexts.empty()) {
4668 if (shouldHaveNullability(T) && !T->getNullability()) {
4669 if (isVaList(T)) {
4670 // Record that we've seen a pointer, but do nothing else.
4671 if (NumPointersRemaining > 0)
4672 --NumPointersRemaining;
4673 } else {
4674 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4675 if (T->isBlockPointerType())
4676 pointerKind = SimplePointerKind::BlockPointer;
4677 else if (T->isMemberPointerType())
4678 pointerKind = SimplePointerKind::MemberPointer;
4679
4680 if (auto *attr = inferPointerNullability(
4681 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4682 D.getDeclSpec().getEndLoc(),
4685 T = state.getAttributedType(
4686 createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4687 }
4688 }
4689 }
4690
4691 if (complainAboutMissingNullability == CAMN_Yes && T->isArrayType() &&
4692 !T->getNullability() && !isVaList(T) && D.isPrototypeContext() &&
4694 checkNullabilityConsistency(S, SimplePointerKind::Array,
4696 }
4697 }
4698
4699 bool ExpectNoDerefChunk =
4700 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4701
4702 // Walk the DeclTypeInfo, building the recursive type as we go.
4703 // DeclTypeInfos are ordered from the identifier out, which is
4704 // opposite of what we want :).
4705
4706 // Track if the produced type matches the structure of the declarator.
4707 // This is used later to decide if we can fill `TypeLoc` from
4708 // `DeclaratorChunk`s. E.g. it must be false if Clang recovers from
4709 // an error by replacing the type with `int`.
4710 bool AreDeclaratorChunksValid = true;
4711 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4712 unsigned chunkIndex = e - i - 1;
4713 state.setCurrentChunkIndex(chunkIndex);
4714 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4715 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4716 switch (DeclType.Kind) {
4718 if (i == 0)
4719 warnAboutRedundantParens(S, D, T);
4720 T = S.BuildParenType(T);
4721 break;
4723 // If blocks are disabled, emit an error.
4724 if (!LangOpts.Blocks)
4725 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4726
4727 // Handle pointer nullability.
4728 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4729 DeclType.EndLoc, DeclType.getAttrs(),
4730 state.getDeclarator().getAttributePool());
4731
4732 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4733 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4734 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4735 // qualified with const.
4736 if (LangOpts.OpenCL)
4737 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4738 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4739 }
4740 break;
4742 // Verify that we're not building a pointer to pointer to function with
4743 // exception specification.
4744 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4745 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4746 D.setInvalidType(true);
4747 // Build the type anyway.
4748 }
4749
4750 // Handle pointer nullability
4751 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4752 DeclType.EndLoc, DeclType.getAttrs(),
4753 state.getDeclarator().getAttributePool());
4754
4755 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
4756 T = Context.getObjCObjectPointerType(T);
4757 if (DeclType.Ptr.TypeQuals)
4758 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4759 break;
4760 }
4761
4762 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4763 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4764 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4765 if (LangOpts.OpenCL) {
4766 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4767 T->isBlockPointerType()) {
4768 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4769 D.setInvalidType(true);
4770 }
4771 }
4772
4773 T = S.BuildPointerType(T, DeclType.Loc, Name);
4774 if (DeclType.Ptr.TypeQuals)
4775 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4776 if (DeclType.Ptr.OverflowBehaviorLoc.isValid()) {
4777 auto OBState = DeclType.Ptr.OverflowBehaviorIsWrap
4780 S.Diag(DeclType.Ptr.OverflowBehaviorLoc,
4781 diag::err_overflow_behavior_non_integer_type)
4782 << DeclSpec::getSpecifierName(OBState) << T.getAsString() << 1;
4783 D.setInvalidType(true);
4784 }
4785 break;
4787 // Verify that we're not building a reference to pointer to function with
4788 // exception specification.
4789 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4790 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4791 D.setInvalidType(true);
4792 // Build the type anyway.
4793 }
4794 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4795
4796 if (DeclType.Ref.HasRestrict)
4797 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4798 break;
4799 }
4801 // Verify that we're not building an array of pointers to function with
4802 // exception specification.
4803 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4804 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4805 D.setInvalidType(true);
4806 // Build the type anyway.
4807 }
4808 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4809 Expr *ArraySize = ATI.NumElts;
4811
4812 // Microsoft property fields can have multiple sizeless array chunks
4813 // (i.e. int x[][][]). Skip all of these except one to avoid creating
4814 // bad incomplete array types.
4815 if (chunkIndex != 0 && !ArraySize &&
4817 // This is a sizeless chunk. If the next is also, skip this one.
4818 DeclaratorChunk &NextDeclType = D.getTypeObject(chunkIndex - 1);
4819 if (NextDeclType.Kind == DeclaratorChunk::Array &&
4820 !NextDeclType.Arr.NumElts)
4821 break;
4822 }
4823
4824 if (ATI.isStar)
4826 else if (ATI.hasStatic)
4828 else
4830 if (ASM == ArraySizeModifier::Star && !D.isPrototypeContext()) {
4831 // FIXME: This check isn't quite right: it allows star in prototypes
4832 // for function definitions, and disallows some edge cases detailed
4833 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4834 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4836 D.setInvalidType(true);
4837 }
4838
4839 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4840 // shall appear only in a declaration of a function parameter with an
4841 // array type, ...
4842 if (ASM == ArraySizeModifier::Static || ATI.TypeQuals) {
4843 if (!(D.isPrototypeContext() ||
4845 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype)
4846 << (ASM == ArraySizeModifier::Static ? "'static'"
4847 : "type qualifier");
4848 // Remove the 'static' and the type qualifiers.
4849 if (ASM == ArraySizeModifier::Static)
4851 ATI.TypeQuals = 0;
4852 D.setInvalidType(true);
4853 }
4854
4855 // C99 6.7.5.2p1: ... and then only in the outermost array type
4856 // derivation.
4857 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4858 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost)
4859 << (ASM == ArraySizeModifier::Static ? "'static'"
4860 : "type qualifier");
4861 if (ASM == ArraySizeModifier::Static)
4863 ATI.TypeQuals = 0;
4864 D.setInvalidType(true);
4865 }
4866 }
4867
4868 // Array parameters can be marked nullable as well, although it's not
4869 // necessary if they're marked 'static'.
4870 if (complainAboutMissingNullability == CAMN_Yes &&
4871 !hasNullabilityAttr(DeclType.getAttrs()) &&
4873 !hasOuterPointerLikeChunk(D, chunkIndex)) {
4874 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4875 }
4876
4877 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4878 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4879 break;
4880 }
4882 // If the function declarator has a prototype (i.e. it is not () and
4883 // does not have a K&R-style identifier list), then the arguments are part
4884 // of the type, otherwise the argument list is ().
4885 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4886 IsQualifiedFunction =
4888
4889 auto IsClassType = [&](CXXScopeSpec &SS) {
4890 // If there already was an problem with the scope, don’t issue another
4891 // error about the explicit object parameter.
4892 return SS.isInvalid() ||
4893 isa_and_present<CXXRecordDecl>(S.computeDeclContext(SS));
4894 };
4895
4896 // C++23 [dcl.fct]p6:
4897 //
4898 // An explicit-object-parameter-declaration is a parameter-declaration
4899 // with a this specifier. An explicit-object-parameter-declaration shall
4900 // appear only as the first parameter-declaration of a
4901 // parameter-declaration-list of one of:
4902 //
4903 // - a declaration of a member function or member function template
4904 // ([class.mem]), or
4905 //
4906 // - an explicit instantiation ([temp.explicit]) or explicit
4907 // specialization ([temp.expl.spec]) of a templated member function,
4908 // or
4909 //
4910 // - a lambda-declarator [expr.prim.lambda].
4913 FTI.NumParams ? dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param)
4914 : nullptr;
4915
4916 bool IsFunctionDecl = D.getInnermostNonParenChunk() == &DeclType;
4917 if (First && First->isExplicitObjectParameter() &&
4919
4920 // Either not a member or nested declarator in a member.
4921 //
4922 // Note that e.g. 'static' or 'friend' declarations are accepted
4923 // here; we diagnose them later when we build the member function
4924 // because it's easier that way.
4925 (C != DeclaratorContext::Member || !IsFunctionDecl) &&
4926
4927 // Allow out-of-line definitions of member functions.
4928 !IsClassType(D.getCXXScopeSpec())) {
4929 if (IsFunctionDecl)
4930 S.Diag(First->getBeginLoc(),
4931 diag::err_explicit_object_parameter_nonmember)
4932 << /*non-member*/ 2 << /*function*/ 0 << First->getSourceRange();
4933 else
4934 S.Diag(First->getBeginLoc(),
4935 diag::err_explicit_object_parameter_invalid)
4936 << First->getSourceRange();
4937
4938 // Do let non-member function have explicit parameters
4939 // to not break assumptions elsewhere in the code.
4940 First->setExplicitObjectParameterLoc(SourceLocation());
4941 D.setInvalidType();
4942 AreDeclaratorChunksValid = false;
4943 }
4944
4945 // Check for auto functions and trailing return type and adjust the
4946 // return type accordingly.
4947 if (!D.isInvalidType()) {
4948 // trailing-return-type is only required if we're declaring a function,
4949 // and not, for instance, a pointer to a function.
4950 if (D.getDeclSpec().hasAutoTypeSpec() &&
4951 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
4952 if (!S.getLangOpts().CPlusPlus14) {
4955 ? diag::err_auto_missing_trailing_return
4956 : diag::err_deduced_return_type);
4957 T = Context.IntTy;
4958 D.setInvalidType(true);
4959 AreDeclaratorChunksValid = false;
4960 } else {
4962 diag::warn_cxx11_compat_deduced_return_type);
4963 }
4964 } else if (FTI.hasTrailingReturnType()) {
4965 // T must be exactly 'auto' at this point. See CWG issue 681.
4966 if (isa<ParenType>(T)) {
4967 S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
4968 << T << D.getSourceRange();
4969 D.setInvalidType(true);
4970 // FIXME: recover and fill decls in `TypeLoc`s.
4971 AreDeclaratorChunksValid = false;
4972 } else if (D.getName().getKind() ==
4974 if (T != Context.DependentTy) {
4976 diag::err_deduction_guide_with_complex_decl)
4977 << D.getSourceRange();
4978 D.setInvalidType(true);
4979 // FIXME: recover and fill decls in `TypeLoc`s.
4980 AreDeclaratorChunksValid = false;
4981 }
4982 } else if (D.getContext() != DeclaratorContext::LambdaExpr &&
4983 (T.hasQualifiers() || !isa<AutoType>(T) ||
4984 cast<AutoType>(T)->getKeyword() !=
4986 cast<AutoType>(T)->isConstrained())) {
4987 // Attach a valid source location for diagnostics on functions with
4988 // trailing return types missing 'auto'. Attempt to get the location
4989 // from the declared type; if invalid, fall back to the trailing
4990 // return type's location.
4993 if (Loc.isInvalid()) {
4994 Loc = FTI.getTrailingReturnTypeLoc();
4995 SR = D.getSourceRange();
4996 }
4997 S.Diag(Loc, diag::err_trailing_return_without_auto) << T << SR;
4998 D.setInvalidType(true);
4999 // FIXME: recover and fill decls in `TypeLoc`s.
5000 AreDeclaratorChunksValid = false;
5001 }
5002 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
5003 if (T.isNull()) {
5004 // An error occurred parsing the trailing return type.
5005 T = Context.IntTy;
5006 D.setInvalidType(true);
5007 } else if (AutoType *Auto = T->getContainedAutoType()) {
5008 // If the trailing return type contains an `auto`, we may need to
5009 // invent a template parameter for it, for cases like
5010 // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
5011 InventedTemplateParameterInfo *InventedParamInfo = nullptr;
5013 InventedParamInfo = &S.InventedParameterInfos.back();
5015 InventedParamInfo = S.getCurLambda();
5016 if (InventedParamInfo) {
5017 std::tie(T, TInfo) = InventTemplateParameter(
5018 state, T, TInfo, Auto, *InventedParamInfo);
5019 }
5020 }
5021 } else {
5022 // This function type is not the type of the entity being declared,
5023 // so checking the 'auto' is not the responsibility of this chunk.
5024 }
5025 }
5026
5027 // C99 6.7.5.3p1: The return type may not be a function or array type.
5028 // For conversion functions, we'll diagnose this particular error later.
5029 if (!D.isInvalidType() &&
5030 ((T->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
5031 T->isFunctionType()) &&
5032 (D.getName().getKind() !=
5034 unsigned diagID = diag::err_func_returning_array_function;
5035 // Last processing chunk in block context means this function chunk
5036 // represents the block.
5037 if (chunkIndex == 0 &&
5039 diagID = diag::err_block_returning_array_function;
5040 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
5041 T = Context.IntTy;
5042 D.setInvalidType(true);
5043 AreDeclaratorChunksValid = false;
5044 }
5045
5046 // Do not allow returning half FP value.
5047 // FIXME: This really should be in BuildFunctionType.
5048 if (T->isHalfType()) {
5049 if (S.getLangOpts().OpenCL) {
5050 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5051 S.getLangOpts())) {
5052 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5053 << T << 0 /*pointer hint*/;
5054 D.setInvalidType(true);
5055 }
5056 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5058 S.Diag(D.getIdentifierLoc(),
5059 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
5060 D.setInvalidType(true);
5061 }
5062 }
5063
5064 // __ptrauth is illegal on a function return type.
5065 if (T.getPointerAuth()) {
5066 S.Diag(DeclType.Loc, diag::err_ptrauth_qualifier_invalid) << T << 0;
5067 }
5068
5069 if (LangOpts.OpenCL) {
5070 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
5071 // function.
5072 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
5073 T->isPipeType()) {
5074 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5075 << T << 1 /*hint off*/;
5076 D.setInvalidType(true);
5077 }
5078 // OpenCL doesn't support variadic functions and blocks
5079 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
5080 // We also allow here any toolchain reserved identifiers.
5081 if (FTI.isVariadic &&
5083 "__cl_clang_variadic_functions", S.getLangOpts()) &&
5084 !(D.getIdentifier() &&
5085 ((D.getIdentifier()->getName() == "printf" &&
5086 LangOpts.getOpenCLCompatibleVersion() >= 120) ||
5087 D.getIdentifier()->getName().starts_with("__")))) {
5088 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
5089 D.setInvalidType(true);
5090 }
5091 }
5092
5093 // Methods cannot return interface types. All ObjC objects are
5094 // passed by reference.
5095 if (T->isObjCObjectType()) {
5096 SourceLocation DiagLoc, FixitLoc;
5097 if (TInfo) {
5098 DiagLoc = TInfo->getTypeLoc().getBeginLoc();
5099 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
5100 } else {
5101 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5102 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
5103 }
5104 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
5105 << 0 << T
5106 << FixItHint::CreateInsertion(FixitLoc, "*");
5107
5108 T = Context.getObjCObjectPointerType(T);
5109 if (TInfo) {
5110 TypeLocBuilder TLB;
5111 TLB.pushFullCopy(TInfo->getTypeLoc());
5113 TLoc.setStarLoc(FixitLoc);
5114 TInfo = TLB.getTypeSourceInfo(Context, T);
5115 } else {
5116 AreDeclaratorChunksValid = false;
5117 }
5118
5119 D.setInvalidType(true);
5120 }
5121
5122 // cv-qualifiers on return types are pointless except when the type is a
5123 // class type in C++.
5124 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
5125 // A dependent type or an undeduced type might later become a class
5126 // type.
5127 !(S.getLangOpts().CPlusPlus &&
5128 (T->isRecordType() || T->isDependentType() ||
5129 T->isUndeducedAutoType()))) {
5130 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
5133 // [6.9.1/3] qualified void return is invalid on a C
5134 // function definition. Apparently ok on declarations and
5135 // in C++ though (!)
5136 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
5137 } else
5138 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
5139 }
5140
5141 // C++2a [dcl.fct]p12:
5142 // A volatile-qualified return type is deprecated
5143 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20)
5144 S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T;
5145
5146 // Objective-C ARC ownership qualifiers are ignored on the function
5147 // return type (by type canonicalization). Complain if this attribute
5148 // was written here.
5149 if (T.getQualifiers().hasObjCLifetime()) {
5150 SourceLocation AttrLoc;
5151 if (chunkIndex + 1 < D.getNumTypeObjects()) {
5152 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
5153 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5154 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5155 AttrLoc = AL.getLoc();
5156 break;
5157 }
5158 }
5159 }
5160 if (AttrLoc.isInvalid()) {
5161 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5162 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5163 AttrLoc = AL.getLoc();
5164 break;
5165 }
5166 }
5167 }
5168
5169 if (AttrLoc.isValid()) {
5170 // The ownership attributes are almost always written via
5171 // the predefined
5172 // __strong/__weak/__autoreleasing/__unsafe_unretained.
5173 if (AttrLoc.isMacroID())
5174 AttrLoc =
5176
5177 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
5178 << T.getQualifiers().getObjCLifetime();
5179 }
5180 }
5181
5182 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
5183 // C++ [dcl.fct]p6:
5184 // Types shall not be defined in return or parameter types.
5186 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
5187 << Context.getCanonicalTagType(Tag);
5188 }
5189
5190 // Exception specs are not allowed in typedefs. Complain, but add it
5191 // anyway.
5192 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
5194 diag::err_exception_spec_in_typedef)
5197
5198 // If we see "T var();" or "T var(T());" at block scope, it is probably
5199 // an attempt to initialize a variable, not a function declaration.
5200 if (FTI.isAmbiguous)
5201 warnAboutAmbiguousFunction(S, D, DeclType, T);
5202
5204 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
5205
5206 // OpenCL disallows functions without a prototype, but it doesn't enforce
5207 // strict prototypes as in C23 because it allows a function definition to
5208 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
5209 if (!FTI.NumParams && !FTI.isVariadic &&
5210 !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) {
5211 // Simple void foo(), where the incoming T is the result type.
5212 T = Context.getFunctionNoProtoType(T, EI);
5213 } else {
5214 // We allow a zero-parameter variadic function in C if the
5215 // function is marked with the "overloadable" attribute. Scan
5216 // for this attribute now. We also allow it in C23 per WG14 N2975.
5217 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
5218 if (LangOpts.C23)
5219 S.Diag(FTI.getEllipsisLoc(),
5220 diag::warn_c17_compat_ellipsis_only_parameter);
5222 ParsedAttr::AT_Overloadable) &&
5224 ParsedAttr::AT_Overloadable) &&
5226 ParsedAttr::AT_Overloadable))
5227 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
5228 }
5229
5230 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
5231 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5232 // definition.
5233 S.Diag(FTI.Params[0].IdentLoc,
5234 diag::err_ident_list_in_fn_declaration);
5235 D.setInvalidType(true);
5236 // Recover by creating a K&R-style function type, if possible.
5237 T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL)
5238 ? Context.getFunctionNoProtoType(T, EI)
5239 : Context.IntTy;
5240 AreDeclaratorChunksValid = false;
5241 break;
5242 }
5243
5245 EPI.ExtInfo = EI;
5246 EPI.Variadic = FTI.isVariadic;
5247 EPI.EllipsisLoc = FTI.getEllipsisLoc();
5251 : 0);
5254 : RQ_RValue;
5255
5256 // Otherwise, we have a function with a parameter list that is
5257 // potentially variadic.
5259 ParamTys.reserve(FTI.NumParams);
5260
5262 ExtParameterInfos(FTI.NumParams);
5263 bool HasAnyInterestingExtParameterInfos = false;
5264
5265 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
5266 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5267 QualType ParamTy = Param->getType();
5268 assert(!ParamTy.isNull() && "Couldn't parse type?");
5269
5270 // Look for 'void'. void is allowed only as a single parameter to a
5271 // function with no other parameters (C99 6.7.5.3p10). We record
5272 // int(void) as a FunctionProtoType with an empty parameter list.
5273 if (ParamTy->isVoidType()) {
5274 // If this is something like 'float(int, void)', reject it. 'void'
5275 // is an incomplete type (C99 6.2.5p19) and function decls cannot
5276 // have parameters of incomplete type.
5277 if (FTI.NumParams != 1 || FTI.isVariadic) {
5278 S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param);
5279 ParamTy = Context.IntTy;
5280 Param->setType(ParamTy);
5281 } else if (FTI.Params[i].Ident) {
5282 // Reject, but continue to parse 'int(void abc)'.
5283 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
5284 ParamTy = Context.IntTy;
5285 Param->setType(ParamTy);
5286 } else {
5287 // Reject, but continue to parse 'float(const void)'.
5288 if (ParamTy.hasQualifiers())
5289 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
5290
5291 for (const auto *A : Param->attrs()) {
5292 S.Diag(A->getLoc(), diag::warn_attribute_on_void_param)
5293 << A << A->getRange();
5294 }
5295
5296 // Reject, but continue to parse 'float(this void)' as
5297 // 'float(void)'.
5298 if (Param->isExplicitObjectParameter()) {
5299 S.Diag(Param->getLocation(),
5300 diag::err_void_explicit_object_param);
5301 Param->setExplicitObjectParameterLoc(SourceLocation());
5302 }
5303
5304 // Do not add 'void' to the list.
5305 break;
5306 }
5307 } else if (ParamTy->isHalfType()) {
5308 // Disallow half FP parameters.
5309 // FIXME: This really should be in BuildFunctionType.
5310 if (S.getLangOpts().OpenCL) {
5311 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5312 S.getLangOpts())) {
5313 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5314 << ParamTy << 0;
5315 D.setInvalidType();
5316 Param->setInvalidDecl();
5317 }
5318 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5320 S.Diag(Param->getLocation(),
5321 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5322 D.setInvalidType();
5323 }
5324 } else if (!FTI.hasPrototype) {
5325 if (Context.isPromotableIntegerType(ParamTy)) {
5326 ParamTy = Context.getPromotedIntegerType(ParamTy);
5327 Param->setKNRPromoted(true);
5328 } else if (const BuiltinType *BTy = ParamTy->getAs<BuiltinType>()) {
5329 if (BTy->getKind() == BuiltinType::Float) {
5330 ParamTy = Context.DoubleTy;
5331 Param->setKNRPromoted(true);
5332 }
5333 }
5334 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) {
5335 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5336 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5337 << ParamTy << 1 /*hint off*/;
5338 D.setInvalidType();
5339 }
5340
5341 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
5342 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
5343 HasAnyInterestingExtParameterInfos = true;
5344 }
5345
5346 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5347 ExtParameterInfos[i] =
5348 ExtParameterInfos[i].withABI(attr->getABI());
5349 HasAnyInterestingExtParameterInfos = true;
5350 }
5351
5352 if (Param->hasAttr<PassObjectSizeAttr>()) {
5353 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5354 HasAnyInterestingExtParameterInfos = true;
5355 }
5356
5357 if (Param->hasAttr<NoEscapeAttr>()) {
5358 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
5359 HasAnyInterestingExtParameterInfos = true;
5360 }
5361
5362 ParamTys.push_back(ParamTy);
5363 }
5364
5365 if (HasAnyInterestingExtParameterInfos) {
5366 EPI.ExtParameterInfos = ExtParameterInfos.data();
5367 checkExtParameterInfos(S, ParamTys, EPI,
5368 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
5369 }
5370
5371 SmallVector<QualType, 4> Exceptions;
5372 SmallVector<ParsedType, 2> DynamicExceptions;
5373 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5374 Expr *NoexceptExpr = nullptr;
5375
5376 if (FTI.getExceptionSpecType() == EST_Dynamic) {
5377 // FIXME: It's rather inefficient to have to split into two vectors
5378 // here.
5379 unsigned N = FTI.getNumExceptions();
5380 DynamicExceptions.reserve(N);
5381 DynamicExceptionRanges.reserve(N);
5382 for (unsigned I = 0; I != N; ++I) {
5383 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
5384 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
5385 }
5386 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
5387 NoexceptExpr = FTI.NoexceptExpr;
5388 }
5389
5392 DynamicExceptions,
5393 DynamicExceptionRanges,
5394 NoexceptExpr,
5395 Exceptions,
5396 EPI.ExceptionSpec);
5397
5398 // FIXME: Set address space from attrs for C++ mode here.
5399 // OpenCLCPlusPlus: A class member function has an address space.
5400 auto IsClassMember = [&]() {
5401 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5402 state.getDeclarator()
5403 .getCXXScopeSpec()
5404 .getScopeRep()
5405 .getKind() == NestedNameSpecifier::Kind::Type) ||
5406 state.getDeclarator().getContext() ==
5408 state.getDeclarator().getContext() ==
5410 };
5411
5412 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
5413 LangAS ASIdx = LangAS::Default;
5414 // Take address space attr if any and mark as invalid to avoid adding
5415 // them later while creating QualType.
5416 if (FTI.MethodQualifiers)
5418 LangAS ASIdxNew = attr.asOpenCLLangAS();
5419 if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
5420 attr.getLoc()))
5421 D.setInvalidType(true);
5422 else
5423 ASIdx = ASIdxNew;
5424 }
5425 // If a class member function's address space is not set, set it to
5426 // __generic.
5427 LangAS AS =
5429 : ASIdx);
5430 EPI.TypeQuals.addAddressSpace(AS);
5431 }
5432 T = Context.getFunctionType(T, ParamTys, EPI);
5433 }
5434 break;
5435 }
5437 // The scope spec must refer to a class, or be dependent.
5438 CXXScopeSpec &SS = DeclType.Mem.Scope();
5439
5440 // Handle pointer nullability.
5441 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5442 DeclType.EndLoc, DeclType.getAttrs(),
5443 state.getDeclarator().getAttributePool());
5444
5445 if (SS.isInvalid()) {
5446 // Avoid emitting extra errors if we already errored on the scope.
5447 D.setInvalidType(true);
5448 AreDeclaratorChunksValid = false;
5449 } else {
5450 T = S.BuildMemberPointerType(T, SS, /*Cls=*/nullptr, DeclType.Loc,
5451 D.getIdentifier());
5452 }
5453
5454 if (T.isNull()) {
5455 T = Context.IntTy;
5456 D.setInvalidType(true);
5457 AreDeclaratorChunksValid = false;
5458 } else if (DeclType.Mem.TypeQuals) {
5459 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
5460 }
5461 break;
5462 }
5463
5464 case DeclaratorChunk::Pipe: {
5465 T = S.BuildReadPipeType(T, DeclType.Loc);
5468 break;
5469 }
5470 }
5471
5472 if (T.isNull()) {
5473 D.setInvalidType(true);
5474 T = Context.IntTy;
5475 AreDeclaratorChunksValid = false;
5476 }
5477
5478 // See if there are any attributes on this declarator chunk.
5479 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs(),
5481
5482 if (DeclType.Kind != DeclaratorChunk::Paren) {
5483 if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
5484 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5485
5486 ExpectNoDerefChunk = state.didParseNoDeref();
5487 }
5488 }
5489
5490 if (ExpectNoDerefChunk)
5491 S.Diag(state.getDeclarator().getBeginLoc(),
5492 diag::warn_noderef_on_non_pointer_or_array);
5493
5494 // GNU warning -Wstrict-prototypes
5495 // Warn if a function declaration or definition is without a prototype.
5496 // This warning is issued for all kinds of unprototyped function
5497 // declarations (i.e. function type typedef, function pointer etc.)
5498 // C99 6.7.5.3p14:
5499 // The empty list in a function declarator that is not part of a definition
5500 // of that function specifies that no information about the number or types
5501 // of the parameters is supplied.
5502 // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of
5503 // function declarations whose behavior changes in C23.
5504 if (!LangOpts.requiresStrictPrototypes()) {
5505 bool IsBlock = false;
5506 for (const DeclaratorChunk &DeclType : D.type_objects()) {
5507 switch (DeclType.Kind) {
5509 IsBlock = true;
5510 break;
5512 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5513 // We suppress the warning when there's no LParen location, as this
5514 // indicates the declaration was an implicit declaration, which gets
5515 // warned about separately via -Wimplicit-function-declaration. We also
5516 // suppress the warning when we know the function has a prototype.
5517 if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic &&
5518 FTI.getLParenLoc().isValid())
5519 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5520 << IsBlock
5521 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5522 IsBlock = false;
5523 break;
5524 }
5525 default:
5526 break;
5527 }
5528 }
5529 }
5530
5531 assert(!T.isNull() && "T must not be null after this point");
5532
5533 if (LangOpts.CPlusPlus && T->isFunctionType()) {
5534 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5535 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
5536
5537 // C++ 8.3.5p4:
5538 // A cv-qualifier-seq shall only be part of the function type
5539 // for a nonstatic member function, the function type to which a pointer
5540 // to member refers, or the top-level function type of a function typedef
5541 // declaration.
5542 //
5543 // Core issue 547 also allows cv-qualifiers on function types that are
5544 // top-level template type arguments.
5545 enum {
5546 NonMember,
5547 Member,
5548 ExplicitObjectMember,
5549 DeductionGuide
5550 } Kind = NonMember;
5552 Kind = DeductionGuide;
5553 else if (!D.getCXXScopeSpec().isSet()) {
5557 Kind = Member;
5558 } else {
5560 if (!DC || DC->isRecord())
5561 Kind = Member;
5562 }
5563
5564 if (Kind == Member) {
5565 unsigned I;
5566 if (D.isFunctionDeclarator(I)) {
5567 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5568 if (Chunk.Fun.NumParams) {
5569 auto *P = dyn_cast_or_null<ParmVarDecl>(Chunk.Fun.Params->Param);
5570 if (P && P->isExplicitObjectParameter())
5571 Kind = ExplicitObjectMember;
5572 }
5573 }
5574 }
5575
5576 // C++11 [dcl.fct]p6 (w/DR1417):
5577 // An attempt to specify a function type with a cv-qualifier-seq or a
5578 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5579 // - the function type for a non-static member function,
5580 // - the function type to which a pointer to member refers,
5581 // - the top-level function type of a function typedef declaration or
5582 // alias-declaration,
5583 // - the type-id in the default argument of a type-parameter, or
5584 // - the type-id of a template-argument for a type-parameter
5585 //
5586 // C++23 [dcl.fct]p6 (P0847R7)
5587 // ... A member-declarator with an explicit-object-parameter-declaration
5588 // shall not include a ref-qualifier or a cv-qualifier-seq and shall not be
5589 // declared static or virtual ...
5590 //
5591 // FIXME: Checking this here is insufficient. We accept-invalid on:
5592 //
5593 // template<typename T> struct S { void f(T); };
5594 // S<int() const> s;
5595 //
5596 // ... for instance.
5597 if (IsQualifiedFunction &&
5598 // Check for non-static member function and not and
5599 // explicit-object-parameter-declaration
5600 (Kind != Member || D.isExplicitObjectMemberFunction() ||
5603 D.isStaticMember())) &&
5604 !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg &&
5606 SourceLocation Loc = D.getBeginLoc();
5607 SourceRange RemovalRange;
5608 unsigned I;
5609 if (D.isFunctionDeclarator(I)) {
5611 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5612 assert(Chunk.Kind == DeclaratorChunk::Function);
5613
5614 if (Chunk.Fun.hasRefQualifier())
5615 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5616
5617 if (Chunk.Fun.hasMethodTypeQualifiers())
5619 [&](DeclSpec::TQ TypeQual, StringRef QualName,
5620 SourceLocation SL) { RemovalLocs.push_back(SL); });
5621
5622 if (!RemovalLocs.empty()) {
5623 llvm::sort(RemovalLocs,
5625 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5626 Loc = RemovalLocs.front();
5627 }
5628 }
5629
5630 S.Diag(Loc, diag::err_invalid_qualified_function_type)
5631 << Kind << D.isFunctionDeclarator() << T
5633 << FixItHint::CreateRemoval(RemovalRange);
5634
5635 // Strip the cv-qualifiers and ref-qualifiers from the type.
5638 EPI.RefQualifier = RQ_None;
5639
5640 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5641 EPI);
5642 // Rebuild any parens around the identifier in the function type.
5643 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5645 break;
5646 T = S.BuildParenType(T);
5647 }
5648 }
5649 }
5650
5651 // Apply any undistributed attributes from the declaration or declarator.
5652 ParsedAttributesView NonSlidingAttrs;
5653 for (ParsedAttr &AL : D.getDeclarationAttributes()) {
5654 if (!AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
5655 NonSlidingAttrs.addAtEnd(&AL);
5656 }
5657 }
5658 processTypeAttrs(state, T, TAL_DeclName, NonSlidingAttrs);
5660
5661 // Diagnose any ignored type attributes.
5662 state.diagnoseIgnoredTypeAttrs(T);
5663
5664 // C++0x [dcl.constexpr]p9:
5665 // A constexpr specifier used in an object declaration declares the object
5666 // as const.
5668 T->isObjectType())
5669 T.addConst();
5670
5671 // C++2a [dcl.fct]p4:
5672 // A parameter with volatile-qualified type is deprecated
5673 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 &&
5676 S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T;
5677
5678 // If there was an ellipsis in the declarator, the declaration declares a
5679 // parameter pack whose type may be a pack expansion type.
5680 if (D.hasEllipsis()) {
5681 // C++0x [dcl.fct]p13:
5682 // A declarator-id or abstract-declarator containing an ellipsis shall
5683 // only be used in a parameter-declaration. Such a parameter-declaration
5684 // is a parameter pack (14.5.3). [...]
5685 switch (D.getContext()) {
5689 // C++0x [dcl.fct]p13:
5690 // [...] When it is part of a parameter-declaration-clause, the
5691 // parameter pack is a function parameter pack (14.5.3). The type T
5692 // of the declarator-id of the function parameter pack shall contain
5693 // a template parameter pack; each template parameter pack in T is
5694 // expanded by the function parameter pack.
5695 //
5696 // We represent function parameter packs as function parameters whose
5697 // type is a pack expansion.
5698 if (!T->containsUnexpandedParameterPack() &&
5699 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) {
5700 S.Diag(D.getEllipsisLoc(),
5701 diag::err_function_parameter_pack_without_parameter_packs)
5702 << T << D.getSourceRange();
5704 } else {
5705 T = Context.getPackExpansionType(T, std::nullopt,
5706 /*ExpectPackInType=*/false);
5707 }
5708 break;
5710 // C++0x [temp.param]p15:
5711 // If a template-parameter is a [...] is a parameter-declaration that
5712 // declares a parameter pack (8.3.5), then the template-parameter is a
5713 // template parameter pack (14.5.3).
5714 //
5715 // Note: core issue 778 clarifies that, if there are any unexpanded
5716 // parameter packs in the type of the non-type template parameter, then
5717 // it expands those parameter packs.
5718 if (T->containsUnexpandedParameterPack())
5719 T = Context.getPackExpansionType(T, std::nullopt);
5720 else
5721 S.Diag(D.getEllipsisLoc(),
5722 LangOpts.CPlusPlus11
5723 ? diag::warn_cxx98_compat_variadic_templates
5724 : diag::ext_variadic_templates);
5725 break;
5726
5729 case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here?
5730 case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here?
5751 // FIXME: We may want to allow parameter packs in block-literal contexts
5752 // in the future.
5753 S.Diag(D.getEllipsisLoc(),
5754 diag::err_ellipsis_in_declarator_not_parameter);
5756 break;
5757 }
5758 }
5759
5760 assert(!T.isNull() && "T must not be null at the end of this function");
5761 if (!AreDeclaratorChunksValid)
5762 return Context.getTrivialTypeSourceInfo(T);
5763
5764 if (state.didParseHLSLParamMod() && !T->isConstantArrayType())
5765 T = S.HLSL().getInoutParameterType(T);
5766 return GetTypeSourceInfoForDeclarator(state, T, TInfo);
5767}
5768
5770 // Determine the type of the declarator. Not all forms of declarator
5771 // have a type.
5772
5773 TypeProcessingState state(*this, D);
5774
5775 TypeSourceInfo *ReturnTypeInfo = nullptr;
5776 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5777 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5778 inferARCWriteback(state, T);
5779
5780 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5781}
5782
5784 QualType &declSpecTy,
5785 Qualifiers::ObjCLifetime ownership) {
5786 if (declSpecTy->isObjCRetainableType() &&
5787 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5788 Qualifiers qs;
5789 qs.addObjCLifetime(ownership);
5790 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5791 }
5792}
5793
5794static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5795 Qualifiers::ObjCLifetime ownership,
5796 unsigned chunkIndex) {
5797 Sema &S = state.getSema();
5798 Declarator &D = state.getDeclarator();
5799
5800 // Look for an explicit lifetime attribute.
5801 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5802 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
5803 return;
5804
5805 const char *attrStr = nullptr;
5806 switch (ownership) {
5807 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5808 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5809 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5810 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5811 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5812 }
5813
5814 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5815 Arg->setIdentifierInfo(&S.Context.Idents.get(attrStr));
5816
5817 ArgsUnion Args(Arg);
5818
5819 // If there wasn't one, add one (with an invalid source location
5820 // so that we don't make an AttributedType for it).
5821 ParsedAttr *attr =
5822 D.getAttributePool().create(&S.Context.Idents.get("objc_ownership"),
5824 /*args*/ &Args, 1, ParsedAttr::Form::GNU());
5825 chunk.getAttrs().addAtEnd(attr);
5826 // TODO: mark whether we did this inference?
5827}
5828
5829/// Used for transferring ownership in casts resulting in l-values.
5830static void transferARCOwnership(TypeProcessingState &state,
5831 QualType &declSpecTy,
5832 Qualifiers::ObjCLifetime ownership) {
5833 Sema &S = state.getSema();
5834 Declarator &D = state.getDeclarator();
5835
5836 int inner = -1;
5837 bool hasIndirection = false;
5838 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5839 DeclaratorChunk &chunk = D.getTypeObject(i);
5840 switch (chunk.Kind) {
5842 // Ignore parens.
5843 break;
5844
5848 if (inner != -1)
5849 hasIndirection = true;
5850 inner = i;
5851 break;
5852
5854 if (inner != -1)
5855 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5856 return;
5857
5861 return;
5862 }
5863 }
5864
5865 if (inner == -1)
5866 return;
5867
5868 DeclaratorChunk &chunk = D.getTypeObject(inner);
5869 if (chunk.Kind == DeclaratorChunk::Pointer) {
5870 if (declSpecTy->isObjCRetainableType())
5871 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5872 if (declSpecTy->isObjCObjectType() && hasIndirection)
5873 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5874 } else {
5875 assert(chunk.Kind == DeclaratorChunk::Array ||
5877 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5878 }
5879}
5880
5882 TypeProcessingState state(*this, D);
5883
5884 TypeSourceInfo *ReturnTypeInfo = nullptr;
5885 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5886
5887 if (getLangOpts().ObjC) {
5888 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
5889 if (ownership != Qualifiers::OCL_None)
5890 transferARCOwnership(state, declSpecTy, ownership);
5891 }
5892
5893 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
5894}
5895
5897 TypeProcessingState &State) {
5898 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
5899}
5900
5902 TypeProcessingState &State) {
5904 State.getSema().HLSL().TakeLocForHLSLAttribute(TL.getTypePtr());
5905 TL.setSourceRange(LocInfo.Range);
5907}
5908
5910 const ParsedAttributesView &Attrs) {
5911 for (const ParsedAttr &AL : Attrs) {
5912 if (AL.getKind() == ParsedAttr::AT_MatrixType) {
5913 MTL.setAttrNameLoc(AL.getLoc());
5914 MTL.setAttrRowOperand(AL.getArgAsExpr(0));
5915 MTL.setAttrColumnOperand(AL.getArgAsExpr(1));
5917 return;
5918 }
5919 }
5920
5921 llvm_unreachable("no matrix_type attribute found at the expected location!");
5922}
5923
5924static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5925 SourceLocation Loc;
5926 switch (Chunk.Kind) {
5931 llvm_unreachable("cannot be _Atomic qualified");
5932
5934 Loc = Chunk.Ptr.AtomicQualLoc;
5935 break;
5936
5940 // FIXME: Provide a source location for the _Atomic keyword.
5941 break;
5942 }
5943
5944 ATL.setKWLoc(Loc);
5946}
5947
5948namespace {
5949 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5950 Sema &SemaRef;
5951 ASTContext &Context;
5952 TypeProcessingState &State;
5953 const DeclSpec &DS;
5954
5955 public:
5956 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
5957 const DeclSpec &DS)
5958 : SemaRef(S), Context(Context), State(State), DS(DS) {}
5959
5960 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5961 Visit(TL.getModifiedLoc());
5962 fillAttributedTypeLoc(TL, State);
5963 }
5964 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
5965 Visit(TL.getWrappedLoc());
5966 }
5967 void VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
5968 Visit(TL.getWrappedLoc());
5969 }
5970 void VisitHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL) {
5971 Visit(TL.getWrappedLoc());
5973 }
5974 void VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {}
5975 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
5976 Visit(TL.getInnerLoc());
5977 TL.setExpansionLoc(
5978 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
5979 }
5980 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5981 Visit(TL.getUnqualifiedLoc());
5982 }
5983 // Allow to fill pointee's type locations, e.g.,
5984 // int __attr * __attr * __attr *p;
5985 void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); }
5986 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5987 if (DS.getTypeSpecType() == TST_typename) {
5988 TypeSourceInfo *TInfo = nullptr;
5990 if (TInfo) {
5991 TL.copy(TInfo->getTypeLoc().castAs<TypedefTypeLoc>());
5992 return;
5993 }
5994 }
5995 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
5996 ? DS.getTypeSpecTypeLoc()
5997 : SourceLocation(),
6000 }
6001 void VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6002 if (DS.getTypeSpecType() == TST_typename) {
6003 TypeSourceInfo *TInfo = nullptr;
6005 if (TInfo) {
6006 TL.copy(TInfo->getTypeLoc().castAs<UnresolvedUsingTypeLoc>());
6007 return;
6008 }
6009 }
6010 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6011 ? DS.getTypeSpecTypeLoc()
6012 : SourceLocation(),
6015 }
6016 void VisitUsingTypeLoc(UsingTypeLoc TL) {
6017 if (DS.getTypeSpecType() == TST_typename) {
6018 TypeSourceInfo *TInfo = nullptr;
6020 if (TInfo) {
6021 TL.copy(TInfo->getTypeLoc().castAs<UsingTypeLoc>());
6022 return;
6023 }
6024 }
6025 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6026 ? DS.getTypeSpecTypeLoc()
6027 : SourceLocation(),
6030 }
6031 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6033 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
6034 // addition field. What we have is good enough for display of location
6035 // of 'fixit' on interface name.
6036 TL.setNameEndLoc(DS.getEndLoc());
6037 }
6038 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6039 TypeSourceInfo *RepTInfo = nullptr;
6040 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6041 TL.copy(RepTInfo->getTypeLoc());
6042 }
6043 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6044 TypeSourceInfo *RepTInfo = nullptr;
6045 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6046 TL.copy(RepTInfo->getTypeLoc());
6047 }
6048 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
6049 TypeSourceInfo *TInfo = nullptr;
6051
6052 // If we got no declarator info from previous Sema routines,
6053 // just fill with the typespec loc.
6054 if (!TInfo) {
6055 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
6056 return;
6057 }
6058
6059 TypeLoc OldTL = TInfo->getTypeLoc();
6060 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
6061 assert(TL.getRAngleLoc() ==
6062 OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
6063 }
6064 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6069 }
6070 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6075 assert(DS.getRepAsType());
6076 TypeSourceInfo *TInfo = nullptr;
6078 TL.setUnmodifiedTInfo(TInfo);
6079 }
6080 void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6084 }
6085 void VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
6088 }
6089 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6090 assert(DS.isTransformTypeTrait(DS.getTypeSpecType()));
6093 assert(DS.getRepAsType());
6094 TypeSourceInfo *TInfo = nullptr;
6096 TL.setUnderlyingTInfo(TInfo);
6097 }
6098 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6099 // By default, use the source location of the type specifier.
6101 if (TL.needsExtraLocalData()) {
6102 // Set info for the written builtin specifiers.
6104 // Try to have a meaningful source location.
6105 if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified)
6107 if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified)
6109 }
6110 }
6111 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6112 assert(DS.getTypeSpecType() == TST_typename);
6113 TypeSourceInfo *TInfo = nullptr;
6115 assert(TInfo);
6116 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
6117 }
6118 void VisitAutoTypeLoc(AutoTypeLoc TL) {
6119 assert(DS.getTypeSpecType() == TST_auto ||
6126 if (!DS.isConstrainedAuto())
6127 return;
6128 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
6129 if (!TemplateId)
6130 return;
6131
6132 NestedNameSpecifierLoc NNS =
6133 (DS.getTypeSpecScope().isNotEmpty()
6135 : NestedNameSpecifierLoc());
6136 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
6137 TemplateId->RAngleLoc);
6138 if (TemplateId->NumArgs > 0) {
6139 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6140 TemplateId->NumArgs);
6141 SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
6142 }
6143 DeclarationNameInfo DNI = DeclarationNameInfo(
6144 TL.getTypePtr()->getTypeConstraintConcept()->getDeclName(),
6145 TemplateId->TemplateNameLoc);
6146
6147 NamedDecl *FoundDecl;
6148 if (auto TN = TemplateId->Template.get();
6149 UsingShadowDecl *USD = TN.getAsUsingShadowDecl())
6150 FoundDecl = cast<NamedDecl>(USD);
6151 else
6152 FoundDecl = cast_if_present<NamedDecl>(TN.getAsTemplateDecl());
6153
6154 auto *CR = ConceptReference::Create(
6155 Context, NNS, TemplateId->TemplateKWLoc, DNI, FoundDecl,
6156 /*NamedDecl=*/TL.getTypePtr()->getTypeConstraintConcept(),
6157 ASTTemplateArgumentListInfo::Create(Context, TemplateArgsInfo));
6158 TL.setConceptReference(CR);
6159 }
6160 void VisitDeducedTemplateSpecializationTypeLoc(
6161 DeducedTemplateSpecializationTypeLoc TL) {
6162 assert(DS.getTypeSpecType() == TST_typename);
6163 TypeSourceInfo *TInfo = nullptr;
6165 assert(TInfo);
6166 TL.copy(
6167 TInfo->getTypeLoc().castAs<DeducedTemplateSpecializationTypeLoc>());
6168 }
6169 void VisitTagTypeLoc(TagTypeLoc TL) {
6170 if (DS.getTypeSpecType() == TST_typename) {
6171 TypeSourceInfo *TInfo = nullptr;
6173 if (TInfo) {
6174 TL.copy(TInfo->getTypeLoc().castAs<TagTypeLoc>());
6175 return;
6176 }
6177 }
6178 TL.setElaboratedKeywordLoc(TL.getTypePtr()->getKeyword() !=
6179 ElaboratedTypeKeyword::None
6180 ? DS.getTypeSpecTypeLoc()
6181 : SourceLocation());
6184 }
6185 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6186 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
6187 // or an _Atomic qualifier.
6191
6192 TypeSourceInfo *TInfo = nullptr;
6194 assert(TInfo);
6196 } else {
6197 TL.setKWLoc(DS.getAtomicSpecLoc());
6198 // No parens, to indicate this was spelled as an _Atomic qualifier.
6199 TL.setParensRange(SourceRange());
6200 Visit(TL.getValueLoc());
6201 }
6202 }
6203
6204 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6206
6207 TypeSourceInfo *TInfo = nullptr;
6210 }
6211
6212 void VisitExtIntTypeLoc(BitIntTypeLoc TL) {
6214 }
6215
6216 void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) {
6218 }
6219
6220 void VisitTypeLoc(TypeLoc TL) {
6221 // FIXME: add other typespec types and change this to an assert.
6222 TL.initialize(Context, DS.getTypeSpecTypeLoc());
6223 }
6224 };
6225
6226 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
6227 ASTContext &Context;
6228 TypeProcessingState &State;
6229 const DeclaratorChunk &Chunk;
6230
6231 public:
6232 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
6233 const DeclaratorChunk &Chunk)
6234 : Context(Context), State(State), Chunk(Chunk) {}
6235
6236 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6237 llvm_unreachable("qualified type locs not expected here!");
6238 }
6239 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6240 llvm_unreachable("decayed type locs not expected here!");
6241 }
6242 void VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
6243 llvm_unreachable("array parameter type locs not expected here!");
6244 }
6245
6246 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6247 fillAttributedTypeLoc(TL, State);
6248 }
6249 void VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
6250 // nothing
6251 }
6252 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6253 // nothing
6254 }
6255 void VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
6256 // nothing
6257 }
6258 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6259 // nothing
6260 }
6261 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6262 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
6263 TL.setCaretLoc(Chunk.Loc);
6264 }
6265 void VisitPointerTypeLoc(PointerTypeLoc TL) {
6266 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6267 TL.setStarLoc(Chunk.Loc);
6268 }
6269 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6270 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6271 TL.setStarLoc(Chunk.Loc);
6272 }
6273 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6274 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
6275 TL.setStarLoc(Chunk.Mem.StarLoc);
6276 TL.setQualifierLoc(Chunk.Mem.Scope().getWithLocInContext(Context));
6277 }
6278 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6279 assert(Chunk.Kind == DeclaratorChunk::Reference);
6280 // 'Amp' is misleading: this might have been originally
6281 /// spelled with AmpAmp.
6282 TL.setAmpLoc(Chunk.Loc);
6283 }
6284 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6285 assert(Chunk.Kind == DeclaratorChunk::Reference);
6286 assert(!Chunk.Ref.LValueRef);
6287 TL.setAmpAmpLoc(Chunk.Loc);
6288 }
6289 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
6290 assert(Chunk.Kind == DeclaratorChunk::Array);
6291 TL.setLBracketLoc(Chunk.Loc);
6292 TL.setRBracketLoc(Chunk.EndLoc);
6293 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
6294 }
6295 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6296 assert(Chunk.Kind == DeclaratorChunk::Function);
6297 TL.setLocalRangeBegin(Chunk.Loc);
6298 TL.setLocalRangeEnd(Chunk.EndLoc);
6299
6300 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
6301 TL.setLParenLoc(FTI.getLParenLoc());
6302 TL.setRParenLoc(FTI.getRParenLoc());
6303 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
6304 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
6305 TL.setParam(tpi++, Param);
6306 }
6308 }
6309 void VisitParenTypeLoc(ParenTypeLoc TL) {
6310 assert(Chunk.Kind == DeclaratorChunk::Paren);
6311 TL.setLParenLoc(Chunk.Loc);
6312 TL.setRParenLoc(Chunk.EndLoc);
6313 }
6314 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6315 assert(Chunk.Kind == DeclaratorChunk::Pipe);
6316 TL.setKWLoc(Chunk.Loc);
6317 }
6318 void VisitBitIntTypeLoc(BitIntTypeLoc TL) {
6319 TL.setNameLoc(Chunk.Loc);
6320 }
6321 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6322 TL.setExpansionLoc(Chunk.Loc);
6323 }
6324 void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); }
6325 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) {
6326 TL.setNameLoc(Chunk.Loc);
6327 }
6328 void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6329 TL.setNameLoc(Chunk.Loc);
6330 }
6331 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6332 fillAtomicQualLoc(TL, Chunk);
6333 }
6334 void
6335 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) {
6336 TL.setNameLoc(Chunk.Loc);
6337 }
6338 void VisitMatrixTypeLoc(MatrixTypeLoc TL) {
6339 fillMatrixTypeLoc(TL, Chunk.getAttrs());
6340 }
6341
6342 void VisitTypeLoc(TypeLoc TL) {
6343 llvm_unreachable("unsupported TypeLoc kind in declarator!");
6344 }
6345 };
6346} // end anonymous namespace
6347
6348static void
6350 const ParsedAttributesView &Attrs) {
6351 for (const ParsedAttr &AL : Attrs) {
6352 if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
6353 DASTL.setAttrNameLoc(AL.getLoc());
6354 DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
6356 return;
6357 }
6358 }
6359
6360 llvm_unreachable(
6361 "no address_space attribute found at the expected location!");
6362}
6363
6364/// Create and instantiate a TypeSourceInfo with type source information.
6365///
6366/// \param T QualType referring to the type as written in source code.
6367///
6368/// \param ReturnTypeInfo For declarators whose return type does not show
6369/// up in the normal place in the declaration specifiers (such as a C++
6370/// conversion function), this pointer will refer to a type source information
6371/// for that return type.
6372static TypeSourceInfo *
6373GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
6374 QualType T, TypeSourceInfo *ReturnTypeInfo) {
6375 Sema &S = State.getSema();
6376 Declarator &D = State.getDeclarator();
6377
6379 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
6380
6381 // Handle parameter packs whose type is a pack expansion.
6382 if (isa<PackExpansionType>(T)) {
6383 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
6384 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6385 }
6386
6387 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6388 // Microsoft property fields can have multiple sizeless array chunks
6389 // (i.e. int x[][][]). Don't create more than one level of incomplete array.
6390 if (CurrTL.getTypeLocClass() == TypeLoc::IncompleteArray && e != 1 &&
6392 continue;
6393
6394 // An AtomicTypeLoc might be produced by an atomic qualifier in this
6395 // declarator chunk.
6396 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
6398 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
6399 }
6400
6401 bool HasDesugaredTypeLoc = true;
6402 while (HasDesugaredTypeLoc) {
6403 switch (CurrTL.getTypeLocClass()) {
6404 case TypeLoc::MacroQualified: {
6405 auto TL = CurrTL.castAs<MacroQualifiedTypeLoc>();
6406 TL.setExpansionLoc(
6407 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6408 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6409 break;
6410 }
6411
6412 case TypeLoc::Attributed: {
6413 auto TL = CurrTL.castAs<AttributedTypeLoc>();
6414 fillAttributedTypeLoc(TL, State);
6415 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6416 break;
6417 }
6418
6419 case TypeLoc::Adjusted:
6420 case TypeLoc::BTFTagAttributed: {
6421 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6422 break;
6423 }
6424
6425 case TypeLoc::DependentAddressSpace: {
6426 auto TL = CurrTL.castAs<DependentAddressSpaceTypeLoc>();
6428 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
6429 break;
6430 }
6431
6432 default:
6433 HasDesugaredTypeLoc = false;
6434 break;
6435 }
6436 }
6437
6438 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
6439 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6440 }
6441
6442 // If we have different source information for the return type, use
6443 // that. This really only applies to C++ conversion functions.
6444 if (ReturnTypeInfo) {
6445 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
6446 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
6447 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
6448 } else {
6449 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL);
6450 }
6451
6452 return TInfo;
6453}
6454
6455/// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
6457 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6458 // and Sema during declaration parsing. Try deallocating/caching them when
6459 // it's appropriate, instead of allocating them and keeping them around.
6460 LocInfoType *LocT = (LocInfoType *)BumpAlloc.Allocate(sizeof(LocInfoType),
6461 alignof(LocInfoType));
6462 new (LocT) LocInfoType(T, TInfo);
6463 assert(LocT->getTypeClass() != T->getTypeClass() &&
6464 "LocInfoType's TypeClass conflicts with an existing Type class");
6465 return ParsedType::make(QualType(LocT, 0));
6466}
6467
6469 const PrintingPolicy &Policy) const {
6470 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6471 " was used directly instead of getting the QualType through"
6472 " GetTypeFromParser");
6473}
6474
6476 // C99 6.7.6: Type names have no identifier. This is already validated by
6477 // the parser.
6478 assert(D.getIdentifier() == nullptr &&
6479 "Type name should have no identifier!");
6480
6482 QualType T = TInfo->getType();
6483 if (D.isInvalidType())
6484 return true;
6485
6486 // Make sure there are no unused decl attributes on the declarator.
6487 // We don't want to do this for ObjC parameters because we're going
6488 // to apply them to the actual parameter declaration.
6489 // Likewise, we don't want to do this for alias declarations, because
6490 // we are actually going to build a declaration from this eventually.
6495
6496 if (getLangOpts().CPlusPlus) {
6497 // Check that there are no default arguments (C++ only).
6499 }
6500
6501 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
6502 const AutoType *AT = TL.getTypePtr();
6503 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
6504 }
6505 return CreateParsedType(T, TInfo);
6506}
6507
6508//===----------------------------------------------------------------------===//
6509// Type Attribute Processing
6510//===----------------------------------------------------------------------===//
6511
6512/// Build an AddressSpace index from a constant expression and diagnose any
6513/// errors related to invalid address_spaces. Returns true on successfully
6514/// building an AddressSpace index.
6515static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
6516 const Expr *AddrSpace,
6517 SourceLocation AttrLoc) {
6518 if (!AddrSpace->isValueDependent()) {
6519 std::optional<llvm::APSInt> OptAddrSpace =
6520 AddrSpace->getIntegerConstantExpr(S.Context);
6521 if (!OptAddrSpace) {
6522 S.Diag(AttrLoc, diag::err_attribute_argument_type)
6523 << "'address_space'" << AANT_ArgumentIntegerConstant
6524 << AddrSpace->getSourceRange();
6525 return false;
6526 }
6527 llvm::APSInt &addrSpace = *OptAddrSpace;
6528
6529 // Bounds checking.
6530 if (addrSpace.isSigned()) {
6531 if (addrSpace.isNegative()) {
6532 S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
6533 << AddrSpace->getSourceRange();
6534 return false;
6535 }
6536 addrSpace.setIsSigned(false);
6537 }
6538
6539 llvm::APSInt max(addrSpace.getBitWidth());
6540 max =
6542
6543 if (addrSpace > max) {
6544 S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
6545 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
6546 return false;
6547 }
6548
6549 ASIdx =
6550 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
6551 return true;
6552 }
6553
6554 // Default value for DependentAddressSpaceTypes
6555 ASIdx = LangAS::Default;
6556 return true;
6557}
6558
6560 SourceLocation AttrLoc) {
6561 if (!AddrSpace->isValueDependent()) {
6562 if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
6563 AttrLoc))
6564 return QualType();
6565
6566 return Context.getAddrSpaceQualType(T, ASIdx);
6567 }
6568
6569 // A check with similar intentions as checking if a type already has an
6570 // address space except for on a dependent types, basically if the
6571 // current type is already a DependentAddressSpaceType then its already
6572 // lined up to have another address space on it and we can't have
6573 // multiple address spaces on the one pointer indirection
6574 if (T->getAs<DependentAddressSpaceType>()) {
6575 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
6576 return QualType();
6577 }
6578
6579 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
6580}
6581
6583 SourceLocation AttrLoc) {
6584 LangAS ASIdx;
6585 if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
6586 return QualType();
6587 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
6588}
6589
6591 TypeProcessingState &State) {
6592 Sema &S = State.getSema();
6593
6594 // This attribute is only supported in C.
6595 // FIXME: we should implement checkCommonAttributeFeatures() in SemaAttr.cpp
6596 // such that it handles type attributes, and then call that from
6597 // processTypeAttrs() instead of one-off checks like this.
6598 if (!Attr.diagnoseLangOpts(S)) {
6599 Attr.setInvalid();
6600 return;
6601 }
6602
6603 // Check the number of attribute arguments.
6604 if (Attr.getNumArgs() != 1) {
6605 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6606 << Attr << 1;
6607 Attr.setInvalid();
6608 return;
6609 }
6610
6611 // Ensure the argument is a string.
6612 auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6613 if (!StrLiteral) {
6614 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6616 Attr.setInvalid();
6617 return;
6618 }
6619
6620 ASTContext &Ctx = S.Context;
6621 StringRef BTFTypeTag = StrLiteral->getString();
6622 Type = State.getBTFTagAttributedType(
6623 ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type);
6624}
6625
6626/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6627/// specified type. The attribute contains 1 argument, the id of the address
6628/// space for the type.
6630 const ParsedAttr &Attr,
6631 TypeProcessingState &State) {
6632 Sema &S = State.getSema();
6633
6634 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6635 // qualified by an address-space qualifier."
6636 if (Type->isFunctionType()) {
6637 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
6638 Attr.setInvalid();
6639 return;
6640 }
6641
6642 LangAS ASIdx;
6643 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
6644
6645 // Check the attribute arguments.
6646 if (Attr.getNumArgs() != 1) {
6647 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
6648 << 1;
6649 Attr.setInvalid();
6650 return;
6651 }
6652
6653 Expr *ASArgExpr = Attr.getArgAsExpr(0);
6654 LangAS ASIdx;
6655 if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
6656 Attr.setInvalid();
6657 return;
6658 }
6659
6660 ASTContext &Ctx = S.Context;
6661 auto *ASAttr =
6662 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
6663
6664 // If the expression is not value dependent (not templated), then we can
6665 // apply the address space qualifiers just to the equivalent type.
6666 // Otherwise, we make an AttributedType with the modified and equivalent
6667 // type the same, and wrap it in a DependentAddressSpaceType. When this
6668 // dependent type is resolved, the qualifier is added to the equivalent type
6669 // later.
6670 QualType T;
6671 if (!ASArgExpr->isValueDependent()) {
6672 QualType EquivType =
6673 S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
6674 if (EquivType.isNull()) {
6675 Attr.setInvalid();
6676 return;
6677 }
6678 T = State.getAttributedType(ASAttr, Type, EquivType);
6679 } else {
6680 T = State.getAttributedType(ASAttr, Type, Type);
6681 T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
6682 }
6683
6684 if (!T.isNull())
6685 Type = T;
6686 else
6687 Attr.setInvalid();
6688 } else {
6689 // The keyword-based type attributes imply which address space to use.
6690 ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS()
6691 : Attr.asOpenCLLangAS();
6692 if (S.getLangOpts().HLSL)
6693 ASIdx = Attr.asHLSLLangAS();
6694
6695 if (ASIdx == LangAS::Default)
6696 llvm_unreachable("Invalid address space");
6697
6698 if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
6699 Attr.getLoc())) {
6700 Attr.setInvalid();
6701 return;
6702 }
6703
6705 }
6706}
6707
6709 TypeProcessingState &State) {
6710 Sema &S = State.getSema();
6711
6712 // Check for -fexperimental-overflow-behavior-types
6713 if (!S.getLangOpts().OverflowBehaviorTypes) {
6714 S.Diag(Attr.getLoc(), diag::warn_overflow_behavior_attribute_disabled)
6715 << Attr << 1;
6716 Attr.setInvalid();
6717 return;
6718 }
6719
6720 // Check the number of attribute arguments.
6721 if (Attr.getNumArgs() != 1) {
6722 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6723 << Attr << 1;
6724 Attr.setInvalid();
6725 return;
6726 }
6727
6728 // Check that the underlying type is an integer type
6729 if (!Type->isIntegerType()) {
6730 S.Diag(Attr.getLoc(), diag::err_overflow_behavior_non_integer_type)
6731 << Attr << Type.getAsString() << 0; // 0 for attribute
6732 Attr.setInvalid();
6733 return;
6734 }
6735
6736 StringRef KindName = "";
6737 IdentifierInfo *Ident = nullptr;
6738
6739 if (Attr.isArgIdent(0)) {
6740 Ident = Attr.getArgAsIdent(0)->getIdentifierInfo();
6741 KindName = Ident->getName();
6742 }
6743
6744 // Support identifier or string argument types. Failure to provide one of
6745 // these two types results in a diagnostic that hints towards using string
6746 // arguments (either "wrap" or "trap") as this is the most common use
6747 // pattern.
6748 if (!Ident) {
6749 auto *Str = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6750 if (Str)
6751 KindName = Str->getString();
6752 else {
6753 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6755 Attr.setInvalid();
6756 return;
6757 }
6758 }
6759
6760 OverflowBehaviorType::OverflowBehaviorKind Kind;
6761 if (KindName == "wrap") {
6762 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
6763 } else if (KindName == "trap") {
6764 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
6765 } else {
6766 S.Diag(Attr.getLoc(), diag::err_overflow_behavior_unknown_ident)
6767 << KindName << Attr;
6768 Attr.setInvalid();
6769 return;
6770 }
6771
6772 // Check for mixed specifier/attribute usage
6773 const DeclSpec &DS = State.getDeclarator().getDeclSpec();
6774 if (DS.isWrapSpecified() || DS.isTrapSpecified()) {
6775 // We have both specifier and attribute on the same type. If
6776 // OverflowBehaviorKinds are the same we can just warn.
6777 OverflowBehaviorType::OverflowBehaviorKind SpecifierKind =
6778 DS.isWrapSpecified() ? OverflowBehaviorType::OverflowBehaviorKind::Wrap
6779 : OverflowBehaviorType::OverflowBehaviorKind::Trap;
6780
6781 if (SpecifierKind != Kind) {
6782 StringRef SpecifierName = DS.isWrapSpecified() ? "wrap" : "trap";
6783 S.Diag(Attr.getLoc(), diag::err_conflicting_overflow_behaviors)
6784 << 1 << SpecifierName << KindName;
6785 Attr.setInvalid();
6786 return;
6787 }
6788 S.Diag(Attr.getLoc(), diag::warn_redundant_overflow_behaviors_mixed)
6789 << KindName;
6790 Attr.setInvalid();
6791 return;
6792 }
6793
6794 // Check for conflicting overflow behavior attributes
6795 if (const auto *ExistingOBT = Type->getAs<OverflowBehaviorType>()) {
6796 OverflowBehaviorType::OverflowBehaviorKind ExistingKind =
6797 ExistingOBT->getBehaviorKind();
6798 if (ExistingKind != Kind) {
6799 S.Diag(Attr.getLoc(), diag::err_conflicting_overflow_behaviors) << 0;
6800 if (Kind == OverflowBehaviorType::OverflowBehaviorKind::Trap) {
6801 Type = State.getOverflowBehaviorType(Kind,
6802 ExistingOBT->getUnderlyingType());
6803 }
6804 return;
6805 }
6806 } else {
6807 Type = State.getOverflowBehaviorType(Kind, Type);
6808 }
6809}
6810
6811/// handleObjCOwnershipTypeAttr - Process an objc_ownership
6812/// attribute on the specified type.
6813///
6814/// Returns 'true' if the attribute was handled.
6815static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6817 bool NonObjCPointer = false;
6818
6819 if (!type->isDependentType() && !type->isUndeducedType()) {
6820 if (const PointerType *ptr = type->getAs<PointerType>()) {
6821 QualType pointee = ptr->getPointeeType();
6822 if (pointee->isObjCRetainableType() || pointee->isPointerType())
6823 return false;
6824 // It is important not to lose the source info that there was an attribute
6825 // applied to non-objc pointer. We will create an attributed type but
6826 // its type will be the same as the original type.
6827 NonObjCPointer = true;
6828 } else if (!type->isObjCRetainableType()) {
6829 return false;
6830 }
6831
6832 // Don't accept an ownership attribute in the declspec if it would
6833 // just be the return type of a block pointer.
6834 if (state.isProcessingDeclSpec()) {
6835 Declarator &D = state.getDeclarator();
6837 /*onlyBlockPointers=*/true))
6838 return false;
6839 }
6840 }
6841
6842 Sema &S = state.getSema();
6843 SourceLocation AttrLoc = attr.getLoc();
6844 if (AttrLoc.isMacroID())
6845 AttrLoc =
6847
6848 if (!attr.isArgIdent(0)) {
6849 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
6851 attr.setInvalid();
6852 return true;
6853 }
6854
6855 IdentifierInfo *II = attr.getArgAsIdent(0)->getIdentifierInfo();
6856 Qualifiers::ObjCLifetime lifetime;
6857 if (II->isStr("none"))
6859 else if (II->isStr("strong"))
6860 lifetime = Qualifiers::OCL_Strong;
6861 else if (II->isStr("weak"))
6862 lifetime = Qualifiers::OCL_Weak;
6863 else if (II->isStr("autoreleasing"))
6865 else {
6866 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II;
6867 attr.setInvalid();
6868 return true;
6869 }
6870
6871 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6872 // outside of ARC mode.
6873 if (!S.getLangOpts().ObjCAutoRefCount &&
6874 lifetime != Qualifiers::OCL_Weak &&
6875 lifetime != Qualifiers::OCL_ExplicitNone) {
6876 return true;
6877 }
6878
6879 SplitQualType underlyingType = type.split();
6880
6881 // Check for redundant/conflicting ownership qualifiers.
6882 if (Qualifiers::ObjCLifetime previousLifetime
6883 = type.getQualifiers().getObjCLifetime()) {
6884 // If it's written directly, that's an error.
6886 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
6887 << type;
6888 return true;
6889 }
6890
6891 // Otherwise, if the qualifiers actually conflict, pull sugar off
6892 // and remove the ObjCLifetime qualifiers.
6893 if (previousLifetime != lifetime) {
6894 // It's possible to have multiple local ObjCLifetime qualifiers. We
6895 // can't stop after we reach a type that is directly qualified.
6896 const Type *prevTy = nullptr;
6897 while (!prevTy || prevTy != underlyingType.Ty) {
6898 prevTy = underlyingType.Ty;
6899 underlyingType = underlyingType.getSingleStepDesugaredType();
6900 }
6901 underlyingType.Quals.removeObjCLifetime();
6902 }
6903 }
6904
6905 underlyingType.Quals.addObjCLifetime(lifetime);
6906
6907 if (NonObjCPointer) {
6908 StringRef name = attr.getAttrName()->getName();
6909 switch (lifetime) {
6912 break;
6913 case Qualifiers::OCL_Strong: name = "__strong"; break;
6914 case Qualifiers::OCL_Weak: name = "__weak"; break;
6915 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
6916 }
6917 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
6919 }
6920
6921 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
6922 // because having both 'T' and '__unsafe_unretained T' exist in the type
6923 // system causes unfortunate widespread consistency problems. (For example,
6924 // they're not considered compatible types, and we mangle them identicially
6925 // as template arguments.) These problems are all individually fixable,
6926 // but it's easier to just not add the qualifier and instead sniff it out
6927 // in specific places using isObjCInertUnsafeUnretainedType().
6928 //
6929 // Doing this does means we miss some trivial consistency checks that
6930 // would've triggered in ARC, but that's better than trying to solve all
6931 // the coexistence problems with __unsafe_unretained.
6932 if (!S.getLangOpts().ObjCAutoRefCount &&
6933 lifetime == Qualifiers::OCL_ExplicitNone) {
6934 type = state.getAttributedType(
6936 type, type);
6937 return true;
6938 }
6939
6940 QualType origType = type;
6941 if (!NonObjCPointer)
6942 type = S.Context.getQualifiedType(underlyingType);
6943
6944 // If we have a valid source location for the attribute, use an
6945 // AttributedType instead.
6946 if (AttrLoc.isValid()) {
6947 type = state.getAttributedType(::new (S.Context)
6948 ObjCOwnershipAttr(S.Context, attr, II),
6949 origType, type);
6950 }
6951
6952 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
6953 unsigned diagnostic, QualType type) {
6958 diagnostic, type, /*ignored*/ 0));
6959 } else {
6960 S.Diag(loc, diagnostic);
6961 }
6962 };
6963
6964 // Sometimes, __weak isn't allowed.
6965 if (lifetime == Qualifiers::OCL_Weak &&
6966 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
6967
6968 // Use a specialized diagnostic if the runtime just doesn't support them.
6969 unsigned diagnostic =
6970 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
6971 : diag::err_arc_weak_no_runtime);
6972
6973 // In any case, delay the diagnostic until we know what we're parsing.
6974 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
6975
6976 attr.setInvalid();
6977 return true;
6978 }
6979
6980 // Forbid __weak for class objects marked as
6981 // objc_arc_weak_reference_unavailable
6982 if (lifetime == Qualifiers::OCL_Weak) {
6983 if (const ObjCObjectPointerType *ObjT =
6984 type->getAs<ObjCObjectPointerType>()) {
6985 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
6986 if (Class->isArcWeakrefUnavailable()) {
6987 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
6988 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
6989 diag::note_class_declared);
6990 }
6991 }
6992 }
6993 }
6994
6995 return true;
6996}
6997
6998/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
6999/// attribute on the specified type. Returns true to indicate that
7000/// the attribute was handled, false to indicate that the type does
7001/// not permit the attribute.
7002static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7003 QualType &type) {
7004 Sema &S = state.getSema();
7005
7006 // Delay if this isn't some kind of pointer.
7007 if (!type->isPointerType() &&
7008 !type->isObjCObjectPointerType() &&
7009 !type->isBlockPointerType())
7010 return false;
7011
7012 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
7013 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
7014 attr.setInvalid();
7015 return true;
7016 }
7017
7018 // Check the attribute arguments.
7019 if (!attr.isArgIdent(0)) {
7020 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
7022 attr.setInvalid();
7023 return true;
7024 }
7025 Qualifiers::GC GCAttr;
7026 if (attr.getNumArgs() > 1) {
7027 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
7028 << 1;
7029 attr.setInvalid();
7030 return true;
7031 }
7032
7033 IdentifierInfo *II = attr.getArgAsIdent(0)->getIdentifierInfo();
7034 if (II->isStr("weak"))
7035 GCAttr = Qualifiers::Weak;
7036 else if (II->isStr("strong"))
7037 GCAttr = Qualifiers::Strong;
7038 else {
7039 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
7040 << attr << II;
7041 attr.setInvalid();
7042 return true;
7043 }
7044
7045 QualType origType = type;
7046 type = S.Context.getObjCGCQualType(origType, GCAttr);
7047
7048 // Make an attributed type to preserve the source information.
7049 if (attr.getLoc().isValid())
7050 type = state.getAttributedType(
7051 ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type);
7052
7053 return true;
7054}
7055
7056namespace {
7057 /// A helper class to unwrap a type down to a function for the
7058 /// purposes of applying attributes there.
7059 ///
7060 /// Use:
7061 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
7062 /// if (unwrapped.isFunctionType()) {
7063 /// const FunctionType *fn = unwrapped.get();
7064 /// // change fn somehow
7065 /// T = unwrapped.wrap(fn);
7066 /// }
7067 struct FunctionTypeUnwrapper {
7068 enum WrapKind {
7069 Desugar,
7070 Attributed,
7071 Parens,
7072 Array,
7073 Pointer,
7074 BlockPointer,
7075 Reference,
7076 MemberPointer,
7077 MacroQualified,
7078 };
7079
7080 QualType Original;
7081 const FunctionType *Fn;
7082 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
7083
7084 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
7085 while (true) {
7086 const Type *Ty = T.getTypePtr();
7087 if (isa<FunctionType>(Ty)) {
7088 Fn = cast<FunctionType>(Ty);
7089 return;
7090 } else if (isa<ParenType>(Ty)) {
7091 T = cast<ParenType>(Ty)->getInnerType();
7092 Stack.push_back(Parens);
7093 } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) ||
7095 T = cast<ArrayType>(Ty)->getElementType();
7096 Stack.push_back(Array);
7097 } else if (isa<PointerType>(Ty)) {
7098 T = cast<PointerType>(Ty)->getPointeeType();
7099 Stack.push_back(Pointer);
7100 } else if (isa<BlockPointerType>(Ty)) {
7101 T = cast<BlockPointerType>(Ty)->getPointeeType();
7102 Stack.push_back(BlockPointer);
7103 } else if (isa<MemberPointerType>(Ty)) {
7104 T = cast<MemberPointerType>(Ty)->getPointeeType();
7105 Stack.push_back(MemberPointer);
7106 } else if (isa<ReferenceType>(Ty)) {
7107 T = cast<ReferenceType>(Ty)->getPointeeType();
7108 Stack.push_back(Reference);
7109 } else if (isa<AttributedType>(Ty)) {
7110 T = cast<AttributedType>(Ty)->getEquivalentType();
7111 Stack.push_back(Attributed);
7112 } else if (isa<MacroQualifiedType>(Ty)) {
7113 T = cast<MacroQualifiedType>(Ty)->getUnderlyingType();
7114 Stack.push_back(MacroQualified);
7115 } else {
7116 const Type *DTy = Ty->getUnqualifiedDesugaredType();
7117 if (Ty == DTy) {
7118 Fn = nullptr;
7119 return;
7120 }
7121
7122 T = QualType(DTy, 0);
7123 Stack.push_back(Desugar);
7124 }
7125 }
7126 }
7127
7128 bool isFunctionType() const { return (Fn != nullptr); }
7129 const FunctionType *get() const { return Fn; }
7130
7131 QualType wrap(Sema &S, const FunctionType *New) {
7132 // If T wasn't modified from the unwrapped type, do nothing.
7133 if (New == get()) return Original;
7134
7135 Fn = New;
7136 return wrap(S.Context, Original, 0);
7137 }
7138
7139 private:
7140 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
7141 if (I == Stack.size())
7142 return C.getQualifiedType(Fn, Old.getQualifiers());
7143
7144 // Build up the inner type, applying the qualifiers from the old
7145 // type to the new type.
7146 SplitQualType SplitOld = Old.split();
7147
7148 // As a special case, tail-recurse if there are no qualifiers.
7149 if (SplitOld.Quals.empty())
7150 return wrap(C, SplitOld.Ty, I);
7151 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
7152 }
7153
7154 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
7155 if (I == Stack.size()) return QualType(Fn, 0);
7156
7157 switch (static_cast<WrapKind>(Stack[I++])) {
7158 case Desugar:
7159 // This is the point at which we potentially lose source
7160 // information.
7161 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
7162
7163 case Attributed:
7164 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
7165
7166 case Parens: {
7167 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
7168 return C.getParenType(New);
7169 }
7170
7171 case MacroQualified:
7172 return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I);
7173
7174 case Array: {
7175 if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) {
7176 QualType New = wrap(C, CAT->getElementType(), I);
7177 return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(),
7178 CAT->getSizeModifier(),
7179 CAT->getIndexTypeCVRQualifiers());
7180 }
7181
7182 if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) {
7183 QualType New = wrap(C, VAT->getElementType(), I);
7184 return C.getVariableArrayType(New, VAT->getSizeExpr(),
7185 VAT->getSizeModifier(),
7186 VAT->getIndexTypeCVRQualifiers());
7187 }
7188
7189 const auto *IAT = cast<IncompleteArrayType>(Old);
7190 QualType New = wrap(C, IAT->getElementType(), I);
7191 return C.getIncompleteArrayType(New, IAT->getSizeModifier(),
7192 IAT->getIndexTypeCVRQualifiers());
7193 }
7194
7195 case Pointer: {
7196 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
7197 return C.getPointerType(New);
7198 }
7199
7200 case BlockPointer: {
7201 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
7202 return C.getBlockPointerType(New);
7203 }
7204
7205 case MemberPointer: {
7206 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
7207 QualType New = wrap(C, OldMPT->getPointeeType(), I);
7208 return C.getMemberPointerType(New, OldMPT->getQualifier(),
7209 OldMPT->getMostRecentCXXRecordDecl());
7210 }
7211
7212 case Reference: {
7213 const ReferenceType *OldRef = cast<ReferenceType>(Old);
7214 QualType New = wrap(C, OldRef->getPointeeType(), I);
7215 if (isa<LValueReferenceType>(OldRef))
7216 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
7217 else
7218 return C.getRValueReferenceType(New);
7219 }
7220 }
7221
7222 llvm_unreachable("unknown wrapping kind");
7223 }
7224 };
7225} // end anonymous namespace
7226
7227static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
7228 ParsedAttr &PAttr, QualType &Type) {
7229 Sema &S = State.getSema();
7230
7231 Attr *A;
7232 switch (PAttr.getKind()) {
7233 default: llvm_unreachable("Unknown attribute kind");
7234 case ParsedAttr::AT_Ptr32:
7236 break;
7237 case ParsedAttr::AT_Ptr64:
7239 break;
7240 case ParsedAttr::AT_SPtr:
7241 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
7242 break;
7243 case ParsedAttr::AT_UPtr:
7244 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
7245 break;
7246 }
7247
7248 std::bitset<attr::LastAttr> Attrs;
7249 QualType Desugared = Type;
7250 for (;;) {
7251 if (const TypedefType *TT = dyn_cast<TypedefType>(Desugared)) {
7252 Desugared = TT->desugar();
7253 continue;
7254 }
7255 const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
7256 if (!AT)
7257 break;
7258 Attrs[AT->getAttrKind()] = true;
7259 Desugared = AT->getModifiedType();
7260 }
7261
7262 // You cannot specify duplicate type attributes, so if the attribute has
7263 // already been applied, flag it.
7264 attr::Kind NewAttrKind = A->getKind();
7265 if (Attrs[NewAttrKind]) {
7266 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7267 return true;
7268 }
7269 Attrs[NewAttrKind] = true;
7270
7271 // You cannot have both __sptr and __uptr on the same type, nor can you
7272 // have __ptr32 and __ptr64.
7273 if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) {
7274 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7275 << "'__ptr32'"
7276 << "'__ptr64'" << /*isRegularKeyword=*/0;
7277 return true;
7278 } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) {
7279 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7280 << "'__sptr'"
7281 << "'__uptr'" << /*isRegularKeyword=*/0;
7282 return true;
7283 }
7284
7285 // Check the raw (i.e., desugared) Canonical type to see if it
7286 // is a pointer type.
7287 if (!isa<PointerType>(Desugared)) {
7288 // Pointer type qualifiers can only operate on pointer types, but not
7289 // pointer-to-member types.
7291 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
7292 else
7293 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
7294 return true;
7295 }
7296
7297 // Add address space to type based on its attributes.
7298 LangAS ASIdx = LangAS::Default;
7299 uint64_t PtrWidth =
7301 if (PtrWidth == 32) {
7302 if (Attrs[attr::Ptr64])
7303 ASIdx = LangAS::ptr64;
7304 else if (Attrs[attr::UPtr])
7305 ASIdx = LangAS::ptr32_uptr;
7306 } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) {
7307 if (S.Context.getTargetInfo().getTriple().isOSzOS() || Attrs[attr::UPtr])
7308 ASIdx = LangAS::ptr32_uptr;
7309 else
7310 ASIdx = LangAS::ptr32_sptr;
7311 }
7312
7313 QualType Pointee = Type->getPointeeType();
7314 if (ASIdx != LangAS::Default)
7315 Pointee = S.Context.getAddrSpaceQualType(
7316 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7317 Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee));
7318 return false;
7319}
7320
7321static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State,
7322 QualType &QT, ParsedAttr &PAttr) {
7323 assert(PAttr.getKind() == ParsedAttr::AT_WebAssemblyFuncref);
7324
7325 Sema &S = State.getSema();
7327
7328 std::bitset<attr::LastAttr> Attrs;
7329 attr::Kind NewAttrKind = A->getKind();
7330 const auto *AT = dyn_cast<AttributedType>(QT);
7331 while (AT) {
7332 Attrs[AT->getAttrKind()] = true;
7333 AT = dyn_cast<AttributedType>(AT->getModifiedType());
7334 }
7335
7336 // You cannot specify duplicate type attributes, so if the attribute has
7337 // already been applied, flag it.
7338 if (Attrs[NewAttrKind]) {
7339 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7340 return true;
7341 }
7342
7343 // Check that the type is a function pointer type.
7344 QualType Desugared = QT.getDesugaredType(S.Context);
7345 const auto *Ptr = dyn_cast<PointerType>(Desugared);
7346 if (!Ptr || !Ptr->getPointeeType()->isFunctionType()) {
7347 S.Diag(PAttr.getLoc(), diag::err_attribute_webassembly_funcref);
7348 return true;
7349 }
7350
7351 // Add address space to type based on its attributes.
7353 QualType Pointee = QT->getPointeeType();
7354 Pointee = S.Context.getAddrSpaceQualType(
7355 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7356 QT = State.getAttributedType(A, QT, S.Context.getPointerType(Pointee));
7357 return false;
7358}
7359
7360static void HandleSwiftAttr(TypeProcessingState &State, TypeAttrLocation TAL,
7361 QualType &QT, ParsedAttr &PAttr) {
7362 if (TAL == TAL_DeclName)
7363 return;
7364
7365 Sema &S = State.getSema();
7366 auto &D = State.getDeclarator();
7367
7368 // If the attribute appears in declaration specifiers
7369 // it should be handled as a declaration attribute,
7370 // unless it's associated with a type or a function
7371 // prototype (i.e. appears on a parameter or result type).
7372 if (State.isProcessingDeclSpec()) {
7373 if (!(D.isPrototypeContext() ||
7374 D.getContext() == DeclaratorContext::TypeName))
7375 return;
7376
7377 if (auto *chunk = D.getInnermostNonParenChunk()) {
7378 moveAttrFromListToList(PAttr, State.getCurrentAttributes(),
7379 const_cast<DeclaratorChunk *>(chunk)->getAttrs());
7380 return;
7381 }
7382 }
7383
7384 StringRef Str;
7385 if (!S.checkStringLiteralArgumentAttr(PAttr, 0, Str)) {
7386 PAttr.setInvalid();
7387 return;
7388 }
7389
7390 // If the attribute as attached to a paren move it closer to
7391 // the declarator. This can happen in block declarations when
7392 // an attribute is placed before `^` i.e. `(__attribute__((...)) ^)`.
7393 //
7394 // Note that it's actually invalid to use GNU style attributes
7395 // in a block but such cases are currently handled gracefully
7396 // but the parser and behavior should be consistent between
7397 // cases when attribute appears before/after block's result
7398 // type and inside (^).
7399 if (TAL == TAL_DeclChunk) {
7400 auto chunkIdx = State.getCurrentChunkIndex();
7401 if (chunkIdx >= 1 &&
7402 D.getTypeObject(chunkIdx).Kind == DeclaratorChunk::Paren) {
7403 moveAttrFromListToList(PAttr, State.getCurrentAttributes(),
7404 D.getTypeObject(chunkIdx - 1).getAttrs());
7405 return;
7406 }
7407 }
7408
7409 auto *A = ::new (S.Context) SwiftAttrAttr(S.Context, PAttr, Str);
7410 QT = State.getAttributedType(A, QT, QT);
7411 PAttr.setUsedAsTypeAttr();
7412}
7413
7414/// Rebuild an attributed type without the nullability attribute on it.
7416 QualType Type) {
7417 auto Attributed = dyn_cast<AttributedType>(Type.getTypePtr());
7418 if (!Attributed)
7419 return Type;
7420
7421 // Skip the nullability attribute; we're done.
7422 if (Attributed->getImmediateNullability())
7423 return Attributed->getModifiedType();
7424
7425 // Build the modified type.
7427 Ctx, Attributed->getModifiedType());
7428 assert(Modified.getTypePtr() != Attributed->getModifiedType().getTypePtr());
7429 return Ctx.getAttributedType(Attributed->getAttrKind(), Modified,
7430 Attributed->getEquivalentType(),
7431 Attributed->getAttr());
7432}
7433
7434/// Map a nullability attribute kind to a nullability kind.
7436 switch (kind) {
7437 case ParsedAttr::AT_TypeNonNull:
7439
7440 case ParsedAttr::AT_TypeNullable:
7442
7443 case ParsedAttr::AT_TypeNullableResult:
7445
7446 case ParsedAttr::AT_TypeNullUnspecified:
7448
7449 default:
7450 llvm_unreachable("not a nullability attribute kind");
7451 }
7452}
7453
7455 Sema &S, TypeProcessingState *State, ParsedAttr *PAttr, QualType &QT,
7456 NullabilityKind Nullability, SourceLocation NullabilityLoc,
7457 bool IsContextSensitive, bool AllowOnArrayType, bool OverrideExisting) {
7458 bool Implicit = (State == nullptr);
7459 if (!Implicit)
7460 recordNullabilitySeen(S, NullabilityLoc);
7461
7462 // Check for existing nullability attributes on the type.
7463 QualType Desugared = QT;
7464 while (auto *Attributed = dyn_cast<AttributedType>(Desugared.getTypePtr())) {
7465 // Check whether there is already a null
7466 if (auto ExistingNullability = Attributed->getImmediateNullability()) {
7467 // Duplicated nullability.
7468 if (Nullability == *ExistingNullability) {
7469 if (Implicit)
7470 break;
7471
7472 S.Diag(NullabilityLoc, diag::warn_nullability_duplicate)
7473 << DiagNullabilityKind(Nullability, IsContextSensitive)
7474 << FixItHint::CreateRemoval(NullabilityLoc);
7475
7476 break;
7477 }
7478
7479 if (!OverrideExisting) {
7480 // Conflicting nullability.
7481 S.Diag(NullabilityLoc, diag::err_nullability_conflicting)
7482 << DiagNullabilityKind(Nullability, IsContextSensitive)
7483 << DiagNullabilityKind(*ExistingNullability, false);
7484 return true;
7485 }
7486
7487 // Rebuild the attributed type, dropping the existing nullability.
7489 }
7490
7491 Desugared = Attributed->getModifiedType();
7492 }
7493
7494 // If there is already a different nullability specifier, complain.
7495 // This (unlike the code above) looks through typedefs that might
7496 // have nullability specifiers on them, which means we cannot
7497 // provide a useful Fix-It.
7498 if (auto ExistingNullability = Desugared->getNullability()) {
7499 if (Nullability != *ExistingNullability && !Implicit) {
7500 S.Diag(NullabilityLoc, diag::err_nullability_conflicting)
7501 << DiagNullabilityKind(Nullability, IsContextSensitive)
7502 << DiagNullabilityKind(*ExistingNullability, false);
7503
7504 // Try to find the typedef with the existing nullability specifier.
7505 if (auto TT = Desugared->getAs<TypedefType>()) {
7506 TypedefNameDecl *typedefDecl = TT->getDecl();
7507 QualType underlyingType = typedefDecl->getUnderlyingType();
7508 if (auto typedefNullability =
7509 AttributedType::stripOuterNullability(underlyingType)) {
7510 if (*typedefNullability == *ExistingNullability) {
7511 S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
7512 << DiagNullabilityKind(*ExistingNullability, false);
7513 }
7514 }
7515 }
7516
7517 return true;
7518 }
7519 }
7520
7521 // If this definitely isn't a pointer type, reject the specifier.
7522 if (!Desugared->canHaveNullability() &&
7523 !(AllowOnArrayType && Desugared->isArrayType())) {
7524 if (!Implicit)
7525 S.Diag(NullabilityLoc, diag::err_nullability_nonpointer)
7526 << DiagNullabilityKind(Nullability, IsContextSensitive) << QT;
7527
7528 return true;
7529 }
7530
7531 // For the context-sensitive keywords/Objective-C property
7532 // attributes, require that the type be a single-level pointer.
7533 if (IsContextSensitive) {
7534 // Make sure that the pointee isn't itself a pointer type.
7535 const Type *pointeeType = nullptr;
7536 if (Desugared->isArrayType())
7537 pointeeType = Desugared->getArrayElementTypeNoTypeQual();
7538 else if (Desugared->isAnyPointerType())
7539 pointeeType = Desugared->getPointeeType().getTypePtr();
7540
7541 if (pointeeType && (pointeeType->isAnyPointerType() ||
7542 pointeeType->isObjCObjectPointerType() ||
7543 pointeeType->isMemberPointerType())) {
7544 S.Diag(NullabilityLoc, diag::err_nullability_cs_multilevel)
7545 << DiagNullabilityKind(Nullability, true) << QT;
7546 S.Diag(NullabilityLoc, diag::note_nullability_type_specifier)
7547 << DiagNullabilityKind(Nullability, false) << QT
7548 << FixItHint::CreateReplacement(NullabilityLoc,
7549 getNullabilitySpelling(Nullability));
7550 return true;
7551 }
7552 }
7553
7554 // Form the attributed type.
7555 if (State) {
7556 assert(PAttr);
7557 Attr *A = createNullabilityAttr(S.Context, *PAttr, Nullability);
7558 QT = State->getAttributedType(A, QT, QT);
7559 } else {
7560 QT = S.Context.getAttributedType(Nullability, QT, QT);
7561 }
7562 return false;
7563}
7564
7565static bool CheckNullabilityTypeSpecifier(TypeProcessingState &State,
7567 bool AllowOnArrayType) {
7569 SourceLocation NullabilityLoc = Attr.getLoc();
7570 bool IsContextSensitive = Attr.isContextSensitiveKeywordAttribute();
7571
7572 return CheckNullabilityTypeSpecifier(State.getSema(), &State, &Attr, Type,
7573 Nullability, NullabilityLoc,
7574 IsContextSensitive, AllowOnArrayType,
7575 /*overrideExisting*/ false);
7576}
7577
7579 NullabilityKind Nullability,
7580 SourceLocation DiagLoc,
7581 bool AllowArrayTypes,
7582 bool OverrideExisting) {
7584 *this, nullptr, nullptr, Type, Nullability, DiagLoc,
7585 /*isContextSensitive*/ false, AllowArrayTypes, OverrideExisting);
7586}
7587
7589 QualType T = VD->getType();
7590
7591 // Check that the variable's type can fit in the specified address space. This
7592 // is determined by how far a pointer in that address space can reach.
7593 llvm::APInt MaxSizeForAddrSpace =
7594 llvm::APInt::getMaxValue(Context.getTargetInfo().getPointerWidth(AS));
7595 std::optional<CharUnits> TSizeInChars = Context.getTypeSizeInCharsIfKnown(T);
7596 if (TSizeInChars && static_cast<uint64_t>(TSizeInChars->getQuantity()) >
7597 MaxSizeForAddrSpace.getZExtValue()) {
7598 Diag(VD->getLocation(), diag::err_type_too_large_for_address_space)
7599 << T << MaxSizeForAddrSpace;
7600 return false;
7601 }
7602
7603 return true;
7604}
7605
7606/// Check the application of the Objective-C '__kindof' qualifier to
7607/// the given type.
7608static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
7609 ParsedAttr &attr) {
7610 Sema &S = state.getSema();
7611
7613 // Build the attributed type to record where __kindof occurred.
7614 type = state.getAttributedType(
7616 return false;
7617 }
7618
7619 // Find out if it's an Objective-C object or object pointer type;
7620 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
7621 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
7622 : type->getAs<ObjCObjectType>();
7623
7624 // If not, we can't apply __kindof.
7625 if (!objType) {
7626 // FIXME: Handle dependent types that aren't yet object types.
7627 S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
7628 << type;
7629 return true;
7630 }
7631
7632 // Rebuild the "equivalent" type, which pushes __kindof down into
7633 // the object type.
7634 // There is no need to apply kindof on an unqualified id type.
7635 QualType equivType = S.Context.getObjCObjectType(
7636 objType->getBaseType(), objType->getTypeArgsAsWritten(),
7637 objType->getProtocols(),
7638 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
7639
7640 // If we started with an object pointer type, rebuild it.
7641 if (ptrType) {
7642 equivType = S.Context.getObjCObjectPointerType(equivType);
7643 if (auto nullability = type->getNullability()) {
7644 // We create a nullability attribute from the __kindof attribute.
7645 // Make sure that will make sense.
7646 assert(attr.getAttributeSpellingListIndex() == 0 &&
7647 "multiple spellings for __kindof?");
7648 Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
7649 A->setImplicit(true);
7650 equivType = state.getAttributedType(A, equivType, equivType);
7651 }
7652 }
7653
7654 // Build the attributed type to record where __kindof occurred.
7655 type = state.getAttributedType(
7657 return false;
7658}
7659
7660/// Distribute a nullability type attribute that cannot be applied to
7661/// the type specifier to a pointer, block pointer, or member pointer
7662/// declarator, complaining if necessary.
7663///
7664/// \returns true if the nullability annotation was distributed, false
7665/// otherwise.
7666static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
7668 Declarator &declarator = state.getDeclarator();
7669
7670 /// Attempt to move the attribute to the specified chunk.
7671 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
7672 // If there is already a nullability attribute there, don't add
7673 // one.
7674 if (hasNullabilityAttr(chunk.getAttrs()))
7675 return false;
7676
7677 // Complain about the nullability qualifier being in the wrong
7678 // place.
7679 enum {
7680 PK_Pointer,
7681 PK_BlockPointer,
7682 PK_MemberPointer,
7683 PK_FunctionPointer,
7684 PK_MemberFunctionPointer,
7685 } pointerKind
7686 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
7687 : PK_Pointer)
7688 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
7689 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
7690
7691 auto diag = state.getSema().Diag(attr.getLoc(),
7692 diag::warn_nullability_declspec)
7694 attr.isContextSensitiveKeywordAttribute())
7695 << type
7696 << static_cast<unsigned>(pointerKind);
7697
7698 // FIXME: MemberPointer chunks don't carry the location of the *.
7699 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
7702 state.getSema().getPreprocessor().getLocForEndOfToken(
7703 chunk.Loc),
7704 " " + attr.getAttrName()->getName().str() + " ");
7705 }
7706
7707 moveAttrFromListToList(attr, state.getCurrentAttributes(),
7708 chunk.getAttrs());
7709 return true;
7710 };
7711
7712 // Move it to the outermost pointer, member pointer, or block
7713 // pointer declarator.
7714 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
7715 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
7716 switch (chunk.Kind) {
7720 return moveToChunk(chunk, false);
7721
7724 continue;
7725
7727 // Try to move past the return type to a function/block/member
7728 // function pointer.
7730 declarator, i,
7731 /*onlyBlockPointers=*/false)) {
7732 return moveToChunk(*dest, true);
7733 }
7734
7735 return false;
7736
7737 // Don't walk through these.
7740 return false;
7741 }
7742 }
7743
7744 return false;
7745}
7746
7748 assert(!Attr.isInvalid());
7749 switch (Attr.getKind()) {
7750 default:
7751 llvm_unreachable("not a calling convention attribute");
7752 case ParsedAttr::AT_CDecl:
7753 return createSimpleAttr<CDeclAttr>(Ctx, Attr);
7754 case ParsedAttr::AT_FastCall:
7756 case ParsedAttr::AT_StdCall:
7758 case ParsedAttr::AT_ThisCall:
7760 case ParsedAttr::AT_RegCall:
7762 case ParsedAttr::AT_Pascal:
7764 case ParsedAttr::AT_SwiftCall:
7766 case ParsedAttr::AT_SwiftAsyncCall:
7768 case ParsedAttr::AT_VectorCall:
7770 case ParsedAttr::AT_AArch64VectorPcs:
7772 case ParsedAttr::AT_AArch64SVEPcs:
7774 case ParsedAttr::AT_ArmStreaming:
7776 case ParsedAttr::AT_Pcs: {
7777 // The attribute may have had a fixit applied where we treated an
7778 // identifier as a string literal. The contents of the string are valid,
7779 // but the form may not be.
7780 StringRef Str;
7781 if (Attr.isArgExpr(0))
7782 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
7783 else
7784 Str = Attr.getArgAsIdent(0)->getIdentifierInfo()->getName();
7785 PcsAttr::PCSType Type;
7786 if (!PcsAttr::ConvertStrToPCSType(Str, Type))
7787 llvm_unreachable("already validated the attribute");
7788 return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
7789 }
7790 case ParsedAttr::AT_IntelOclBicc:
7792 case ParsedAttr::AT_MSABI:
7793 return createSimpleAttr<MSABIAttr>(Ctx, Attr);
7794 case ParsedAttr::AT_SysVABI:
7796 case ParsedAttr::AT_PreserveMost:
7798 case ParsedAttr::AT_PreserveAll:
7800 case ParsedAttr::AT_M68kRTD:
7802 case ParsedAttr::AT_PreserveNone:
7804 case ParsedAttr::AT_RISCVVectorCC:
7806 case ParsedAttr::AT_RISCVVLSCC: {
7807 // If the riscv_abi_vlen doesn't have any argument, we set set it to default
7808 // value 128.
7809 unsigned ABIVLen = 128;
7810 if (Attr.getNumArgs()) {
7811 std::optional<llvm::APSInt> MaybeABIVLen =
7812 Attr.getArgAsExpr(0)->getIntegerConstantExpr(Ctx);
7813 if (!MaybeABIVLen)
7814 llvm_unreachable("Invalid RISC-V ABI VLEN");
7815 ABIVLen = MaybeABIVLen->getZExtValue();
7816 }
7817
7818 return ::new (Ctx) RISCVVLSCCAttr(Ctx, Attr, ABIVLen);
7819 }
7820 }
7821 llvm_unreachable("unexpected attribute kind!");
7822}
7823
7824std::optional<FunctionEffectMode>
7825Sema::ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName) {
7826 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent())
7828
7829 std::optional<llvm::APSInt> ConditionValue =
7831 if (!ConditionValue) {
7832 // FIXME: err_attribute_argument_type doesn't quote the attribute
7833 // name but needs to; users are inconsistent.
7834 Diag(CondExpr->getExprLoc(), diag::err_attribute_argument_type)
7835 << AttributeName << AANT_ArgumentIntegerConstant
7836 << CondExpr->getSourceRange();
7837 return std::nullopt;
7838 }
7839 return !ConditionValue->isZero() ? FunctionEffectMode::True
7841}
7842
7843static bool
7844handleNonBlockingNonAllocatingTypeAttr(TypeProcessingState &TPState,
7845 ParsedAttr &PAttr, QualType &QT,
7846 FunctionTypeUnwrapper &Unwrapped) {
7847 // Delay if this is not a function type.
7848 if (!Unwrapped.isFunctionType())
7849 return false;
7850
7851 Sema &S = TPState.getSema();
7852
7853 // Require FunctionProtoType.
7854 auto *FPT = Unwrapped.get()->getAs<FunctionProtoType>();
7855 if (FPT == nullptr) {
7856 S.Diag(PAttr.getLoc(), diag::err_func_with_effects_no_prototype)
7857 << PAttr.getAttrName()->getName();
7858 return true;
7859 }
7860
7861 // Parse the new attribute.
7862 // non/blocking or non/allocating? Or conditional (computed)?
7863 bool IsNonBlocking = PAttr.getKind() == ParsedAttr::AT_NonBlocking ||
7864 PAttr.getKind() == ParsedAttr::AT_Blocking;
7865
7867 Expr *CondExpr = nullptr; // only valid if dependent
7868
7869 if (PAttr.getKind() == ParsedAttr::AT_NonBlocking ||
7870 PAttr.getKind() == ParsedAttr::AT_NonAllocating) {
7871 if (!PAttr.checkAtMostNumArgs(S, 1)) {
7872 PAttr.setInvalid();
7873 return true;
7874 }
7875
7876 // Parse the condition, if any.
7877 if (PAttr.getNumArgs() == 1) {
7878 CondExpr = PAttr.getArgAsExpr(0);
7879 std::optional<FunctionEffectMode> MaybeMode =
7880 S.ActOnEffectExpression(CondExpr, PAttr.getAttrName()->getName());
7881 if (!MaybeMode) {
7882 PAttr.setInvalid();
7883 return true;
7884 }
7885 NewMode = *MaybeMode;
7886 if (NewMode != FunctionEffectMode::Dependent)
7887 CondExpr = nullptr;
7888 } else {
7889 NewMode = FunctionEffectMode::True;
7890 }
7891 } else {
7892 // This is the `blocking` or `allocating` attribute.
7893 if (S.CheckAttrNoArgs(PAttr)) {
7894 // The attribute has been marked invalid.
7895 return true;
7896 }
7897 NewMode = FunctionEffectMode::False;
7898 }
7899
7900 const FunctionEffect::Kind FEKind =
7901 (NewMode == FunctionEffectMode::False)
7902 ? (IsNonBlocking ? FunctionEffect::Kind::Blocking
7904 : (IsNonBlocking ? FunctionEffect::Kind::NonBlocking
7906 const FunctionEffectWithCondition NewEC{FunctionEffect(FEKind),
7907 EffectConditionExpr(CondExpr)};
7908
7909 if (S.diagnoseConflictingFunctionEffect(FPT->getFunctionEffects(), NewEC,
7910 PAttr.getLoc())) {
7911 PAttr.setInvalid();
7912 return true;
7913 }
7914
7915 // Add the effect to the FunctionProtoType.
7916 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7919 [[maybe_unused]] bool Success = FX.insert(NewEC, Errs);
7920 assert(Success && "effect conflicts should have been diagnosed above");
7922
7923 QualType NewType = S.Context.getFunctionType(FPT->getReturnType(),
7924 FPT->getParamTypes(), EPI);
7925 QT = Unwrapped.wrap(S, NewType->getAs<FunctionType>());
7926 return true;
7927}
7928
7929static bool checkMutualExclusion(TypeProcessingState &state,
7932 AttributeCommonInfo::Kind OtherKind) {
7933 auto OtherAttr = llvm::find_if(
7934 state.getCurrentAttributes(),
7935 [OtherKind](const ParsedAttr &A) { return A.getKind() == OtherKind; });
7936 if (OtherAttr == state.getCurrentAttributes().end() || OtherAttr->isInvalid())
7937 return false;
7938
7939 Sema &S = state.getSema();
7940 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
7941 << *OtherAttr << Attr
7942 << (OtherAttr->isRegularKeywordAttribute() ||
7944 S.Diag(OtherAttr->getLoc(), diag::note_conflicting_attribute);
7945 Attr.setInvalid();
7946 return true;
7947}
7948
7951 ParsedAttr &Attr) {
7952 if (!Attr.getNumArgs()) {
7953 S.Diag(Attr.getLoc(), diag::err_missing_arm_state) << Attr;
7954 Attr.setInvalid();
7955 return true;
7956 }
7957
7958 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
7959 StringRef StateName;
7960 SourceLocation LiteralLoc;
7961 if (!S.checkStringLiteralArgumentAttr(Attr, I, StateName, &LiteralLoc))
7962 return true;
7963
7964 if (StateName != "sme_za_state") {
7965 S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName;
7966 Attr.setInvalid();
7967 return true;
7968 }
7969
7970 if (EPI.AArch64SMEAttributes &
7972 S.Diag(Attr.getLoc(), diag::err_conflicting_attributes_arm_agnostic);
7973 Attr.setInvalid();
7974 return true;
7975 }
7976
7978 }
7979
7980 return false;
7981}
7982
7987 if (!Attr.getNumArgs()) {
7988 S.Diag(Attr.getLoc(), diag::err_missing_arm_state) << Attr;
7989 Attr.setInvalid();
7990 return true;
7991 }
7992
7993 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
7994 StringRef StateName;
7995 SourceLocation LiteralLoc;
7996 if (!S.checkStringLiteralArgumentAttr(Attr, I, StateName, &LiteralLoc))
7997 return true;
7998
7999 unsigned Shift;
8000 FunctionType::ArmStateValue ExistingState;
8001 if (StateName == "za") {
8004 } else if (StateName == "zt0") {
8007 } else {
8008 S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName;
8009 Attr.setInvalid();
8010 return true;
8011 }
8012
8014 S.Diag(LiteralLoc, diag::err_conflicting_attributes_arm_agnostic);
8015 Attr.setInvalid();
8016 return true;
8017 }
8018
8019 // __arm_in(S), __arm_out(S), __arm_inout(S) and __arm_preserves(S)
8020 // are all mutually exclusive for the same S, so check if there are
8021 // conflicting attributes.
8022 if (ExistingState != FunctionType::ARM_None && ExistingState != State) {
8023 S.Diag(LiteralLoc, diag::err_conflicting_attributes_arm_state)
8024 << StateName;
8025 Attr.setInvalid();
8026 return true;
8027 }
8028
8030 (FunctionType::AArch64SMETypeAttributes)((State << Shift)));
8031 }
8032 return false;
8033}
8034
8035/// Process an individual function attribute. Returns true to
8036/// indicate that the attribute was handled, false if it wasn't.
8037static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
8039 Sema &S = state.getSema();
8040
8041 FunctionTypeUnwrapper unwrapped(S, type);
8042
8043 if (attr.getKind() == ParsedAttr::AT_NoReturn) {
8044 if (S.CheckAttrNoArgs(attr))
8045 return true;
8046
8047 // Delay if this is not a function type.
8048 if (!unwrapped.isFunctionType())
8049 return false;
8050
8051 // Otherwise we can process right away.
8052 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
8053 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8054 return true;
8055 }
8056
8057 if (attr.getKind() == ParsedAttr::AT_CFIUncheckedCallee) {
8058 // Delay if this is not a prototyped function type.
8059 if (!unwrapped.isFunctionType())
8060 return false;
8061
8062 if (!unwrapped.get()->isFunctionProtoType()) {
8063 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
8064 << attr << attr.isRegularKeywordAttribute()
8066 attr.setInvalid();
8067 return true;
8068 }
8069
8070 const auto *FPT = unwrapped.get()->getAs<FunctionProtoType>();
8072 FPT->getReturnType(), FPT->getParamTypes(),
8073 FPT->getExtProtoInfo().withCFIUncheckedCallee(true));
8074 type = unwrapped.wrap(S, cast<FunctionType>(type.getTypePtr()));
8075 return true;
8076 }
8077
8078 if (attr.getKind() == ParsedAttr::AT_CmseNSCall) {
8079 // Delay if this is not a function type.
8080 if (!unwrapped.isFunctionType())
8081 return false;
8082
8083 // Ignore if we don't have CMSE enabled.
8084 if (!S.getLangOpts().Cmse) {
8085 S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr;
8086 attr.setInvalid();
8087 return true;
8088 }
8089
8090 // Otherwise we can process right away.
8092 unwrapped.get()->getExtInfo().withCmseNSCall(true);
8093 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8094 return true;
8095 }
8096
8097 // ns_returns_retained is not always a type attribute, but if we got
8098 // here, we're treating it as one right now.
8099 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
8100 if (attr.getNumArgs()) return true;
8101
8102 // Delay if this is not a function type.
8103 if (!unwrapped.isFunctionType())
8104 return false;
8105
8106 // Check whether the return type is reasonable.
8108 attr.getLoc(), unwrapped.get()->getReturnType()))
8109 return true;
8110
8111 // Only actually change the underlying type in ARC builds.
8112 QualType origType = type;
8113 if (state.getSema().getLangOpts().ObjCAutoRefCount) {
8115 = unwrapped.get()->getExtInfo().withProducesResult(true);
8116 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8117 }
8118 type = state.getAttributedType(
8120 origType, type);
8121 return true;
8122 }
8123
8124 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
8126 return true;
8127
8128 // Delay if this is not a function type.
8129 if (!unwrapped.isFunctionType())
8130 return false;
8131
8133 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
8134 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8135 return true;
8136 }
8137
8138 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
8139 if (!S.getLangOpts().CFProtectionBranch) {
8140 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
8141 attr.setInvalid();
8142 return true;
8143 }
8144
8146 return true;
8147
8148 // If this is not a function type, warning will be asserted by subject
8149 // check.
8150 if (!unwrapped.isFunctionType())
8151 return true;
8152
8154 unwrapped.get()->getExtInfo().withNoCfCheck(true);
8155 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8156 return true;
8157 }
8158
8159 if (attr.getKind() == ParsedAttr::AT_Regparm) {
8160 unsigned value;
8161 if (S.CheckRegparmAttr(attr, value))
8162 return true;
8163
8164 // Delay if this is not a function type.
8165 if (!unwrapped.isFunctionType())
8166 return false;
8167
8168 // Diagnose regparm with fastcall.
8169 const FunctionType *fn = unwrapped.get();
8170 CallingConv CC = fn->getCallConv();
8171 if (CC == CC_X86FastCall) {
8172 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8173 << FunctionType::getNameForCallConv(CC) << "regparm"
8174 << attr.isRegularKeywordAttribute();
8175 attr.setInvalid();
8176 return true;
8177 }
8178
8180 unwrapped.get()->getExtInfo().withRegParm(value);
8181 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8182 return true;
8183 }
8184
8185 if (attr.getKind() == ParsedAttr::AT_CFISalt) {
8186 if (attr.getNumArgs() != 1)
8187 return true;
8188
8189 StringRef Argument;
8190 if (!S.checkStringLiteralArgumentAttr(attr, 0, Argument))
8191 return true;
8192
8193 // Delay if this is not a function type.
8194 if (!unwrapped.isFunctionType())
8195 return false;
8196
8197 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8198 if (!FnTy) {
8199 S.Diag(attr.getLoc(), diag::err_attribute_wrong_decl_type)
8200 << attr << attr.isRegularKeywordAttribute()
8202 attr.setInvalid();
8203 return true;
8204 }
8205
8206 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8207 EPI.ExtraAttributeInfo.CFISalt = Argument;
8208
8209 QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(),
8210 FnTy->getParamTypes(), EPI);
8211 type = unwrapped.wrap(S, newtype->getAs<FunctionType>());
8212 return true;
8213 }
8214
8215 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8216 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible ||
8217 attr.getKind() == ParsedAttr::AT_ArmPreserves ||
8218 attr.getKind() == ParsedAttr::AT_ArmIn ||
8219 attr.getKind() == ParsedAttr::AT_ArmOut ||
8220 attr.getKind() == ParsedAttr::AT_ArmInOut ||
8221 attr.getKind() == ParsedAttr::AT_ArmAgnostic) {
8222 if (S.CheckAttrTarget(attr))
8223 return true;
8224
8225 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8226 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible)
8227 if (S.CheckAttrNoArgs(attr))
8228 return true;
8229
8230 if (!unwrapped.isFunctionType())
8231 return false;
8232
8233 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8234 if (!FnTy) {
8235 // SME ACLE attributes are not supported on K&R-style unprototyped C
8236 // functions.
8237 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
8238 << attr << attr.isRegularKeywordAttribute()
8240 attr.setInvalid();
8241 return false;
8242 }
8243
8244 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8245 switch (attr.getKind()) {
8246 case ParsedAttr::AT_ArmStreaming:
8247 if (checkMutualExclusion(state, EPI, attr,
8248 ParsedAttr::AT_ArmStreamingCompatible))
8249 return true;
8251 break;
8252 case ParsedAttr::AT_ArmStreamingCompatible:
8253 if (checkMutualExclusion(state, EPI, attr, ParsedAttr::AT_ArmStreaming))
8254 return true;
8256 break;
8257 case ParsedAttr::AT_ArmPreserves:
8259 return true;
8260 break;
8261 case ParsedAttr::AT_ArmIn:
8263 return true;
8264 break;
8265 case ParsedAttr::AT_ArmOut:
8267 return true;
8268 break;
8269 case ParsedAttr::AT_ArmInOut:
8271 return true;
8272 break;
8273 case ParsedAttr::AT_ArmAgnostic:
8274 if (handleArmAgnosticAttribute(S, EPI, attr))
8275 return true;
8276 break;
8277 default:
8278 llvm_unreachable("Unsupported attribute");
8279 }
8280
8281 QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(),
8282 FnTy->getParamTypes(), EPI);
8283 type = unwrapped.wrap(S, newtype->getAs<FunctionType>());
8284 return true;
8285 }
8286
8287 if (attr.getKind() == ParsedAttr::AT_NoThrow) {
8288 // Delay if this is not a function type.
8289 if (!unwrapped.isFunctionType())
8290 return false;
8291
8292 if (S.CheckAttrNoArgs(attr)) {
8293 attr.setInvalid();
8294 return true;
8295 }
8296
8297 // Otherwise we can process right away.
8298 auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
8299
8300 // MSVC ignores nothrow if it is in conflict with an explicit exception
8301 // specification.
8302 if (Proto->hasExceptionSpec()) {
8303 switch (Proto->getExceptionSpecType()) {
8304 case EST_None:
8305 llvm_unreachable("This doesn't have an exception spec!");
8306
8307 case EST_DynamicNone:
8308 case EST_BasicNoexcept:
8309 case EST_NoexceptTrue:
8310 case EST_NoThrow:
8311 // Exception spec doesn't conflict with nothrow, so don't warn.
8312 [[fallthrough]];
8313 case EST_Unparsed:
8314 case EST_Uninstantiated:
8316 case EST_Unevaluated:
8317 // We don't have enough information to properly determine if there is a
8318 // conflict, so suppress the warning.
8319 break;
8320 case EST_Dynamic:
8321 case EST_MSAny:
8322 case EST_NoexceptFalse:
8323 S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored);
8324 break;
8325 }
8326 return true;
8327 }
8328
8329 type = unwrapped.wrap(
8330 S, S.Context
8332 QualType{Proto, 0},
8334 ->getAs<FunctionType>());
8335 return true;
8336 }
8337
8338 if (attr.getKind() == ParsedAttr::AT_NonBlocking ||
8339 attr.getKind() == ParsedAttr::AT_NonAllocating ||
8340 attr.getKind() == ParsedAttr::AT_Blocking ||
8341 attr.getKind() == ParsedAttr::AT_Allocating) {
8342 return handleNonBlockingNonAllocatingTypeAttr(state, attr, type, unwrapped);
8343 }
8344
8345 // Delay if the type didn't work out to a function.
8346 if (!unwrapped.isFunctionType()) return false;
8347
8348 // Otherwise, a calling convention.
8349 CallingConv CC;
8350 if (S.CheckCallingConvAttr(attr, CC, /*FunctionDecl=*/nullptr, CFT))
8351 return true;
8352
8353 const FunctionType *fn = unwrapped.get();
8354 CallingConv CCOld = fn->getCallConv();
8355 Attr *CCAttr = getCCTypeAttr(S.Context, attr);
8356
8357 if (CCOld != CC) {
8358 // Error out on when there's already an attribute on the type
8359 // and the CCs don't match.
8361 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8364 << attr.isRegularKeywordAttribute();
8365 attr.setInvalid();
8366 return true;
8367 }
8368 }
8369
8370 // Diagnose use of variadic functions with calling conventions that
8371 // don't support them (e.g. because they're callee-cleanup).
8372 // We delay warning about this on unprototyped function declarations
8373 // until after redeclaration checking, just in case we pick up a
8374 // prototype that way. And apparently we also "delay" warning about
8375 // unprototyped function types in general, despite not necessarily having
8376 // much ability to diagnose it later.
8377 if (!supportsVariadicCall(CC)) {
8378 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
8379 if (FnP && FnP->isVariadic()) {
8380 // stdcall and fastcall are ignored with a warning for GCC and MS
8381 // compatibility.
8382 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
8383 return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported)
8386
8387 attr.setInvalid();
8388 return S.Diag(attr.getLoc(), diag::err_cconv_varargs)
8390 }
8391 }
8392
8393 // Also diagnose fastcall with regparm.
8394 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
8395 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8397 << attr.isRegularKeywordAttribute();
8398 attr.setInvalid();
8399 return true;
8400 }
8401
8402 // Modify the CC from the wrapped function type, wrap it all back, and then
8403 // wrap the whole thing in an AttributedType as written. The modified type
8404 // might have a different CC if we ignored the attribute.
8406 if (CCOld == CC) {
8407 Equivalent = type;
8408 } else {
8409 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
8410 Equivalent =
8411 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8412 }
8413 type = state.getAttributedType(CCAttr, type, Equivalent);
8414 return true;
8415}
8416
8418 const AttributedType *AT;
8419
8420 // Stop if we'd be stripping off a typedef sugar node to reach the
8421 // AttributedType.
8422 while ((AT = T->getAs<AttributedType>()) &&
8423 AT->getAs<TypedefType>() == T->getAs<TypedefType>()) {
8424 if (AT->isCallingConv())
8425 return true;
8426 T = AT->getModifiedType();
8427 }
8428 return false;
8429}
8430
8431void Sema::adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
8432 bool IsCtorOrDtor, SourceLocation Loc) {
8433 FunctionTypeUnwrapper Unwrapped(*this, T);
8434 const FunctionType *FT = Unwrapped.get();
8435 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
8436 cast<FunctionProtoType>(FT)->isVariadic());
8437 CallingConv CurCC = FT->getCallConv();
8438 CallingConv ToCC =
8439 Context.getDefaultCallingConvention(IsVariadic, HasThisPointer);
8440
8441 if (CurCC == ToCC)
8442 return;
8443
8444 // MS compiler ignores explicit calling convention attributes on structors. We
8445 // should do the same.
8446 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
8447 // Issue a warning on ignored calling convention -- except of __stdcall.
8448 // Again, this is what MS compiler does.
8449 if (CurCC != CC_X86StdCall)
8450 Diag(Loc, diag::warn_cconv_unsupported)
8453 // Default adjustment.
8454 } else {
8455 // Only adjust types with the default convention. For example, on Windows
8456 // we should adjust a __cdecl type to __thiscall for instance methods, and a
8457 // __thiscall type to __cdecl for static methods.
8458 CallingConv DefaultCC =
8459 Context.getDefaultCallingConvention(IsVariadic, !HasThisPointer);
8460
8461 if (CurCC != DefaultCC)
8462 return;
8463
8465 return;
8466 }
8467
8468 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
8469 QualType Wrapped = Unwrapped.wrap(*this, FT);
8470 T = Context.getAdjustedType(T, Wrapped);
8471}
8472
8473/// HandleVectorSizeAttribute - this attribute is only applicable to integral
8474/// and float scalars, although arrays, pointers, and function return values are
8475/// allowed in conjunction with this construct. Aggregates with this attribute
8476/// are invalid, even if they are of the same size as a corresponding scalar.
8477/// The raw attribute should contain precisely 1 argument, the vector size for
8478/// the variable, measured in bytes. If curType and rawAttr are well formed,
8479/// this routine will return a new vector type.
8480static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
8481 Sema &S) {
8482 // Check the attribute arguments.
8483 if (Attr.getNumArgs() != 1) {
8484 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8485 << 1;
8486 Attr.setInvalid();
8487 return;
8488 }
8489
8490 Expr *SizeExpr = Attr.getArgAsExpr(0);
8491 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
8492 if (!T.isNull())
8493 CurType = T;
8494 else
8495 Attr.setInvalid();
8496}
8497
8498/// Process the OpenCL-like ext_vector_type attribute when it occurs on
8499/// a type.
8501 Sema &S) {
8502 // check the attribute arguments.
8503 if (Attr.getNumArgs() != 1) {
8504 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8505 << 1;
8506 return;
8507 }
8508
8509 Expr *SizeExpr = Attr.getArgAsExpr(0);
8510 QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc());
8511 if (!T.isNull())
8512 CurType = T;
8513}
8514
8515static bool isPermittedNeonBaseType(QualType &Ty, VectorKind VecKind, Sema &S) {
8516 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
8517 if (!BTy)
8518 return false;
8519
8520 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
8521
8522 // Signed poly is mathematically wrong, but has been baked into some ABIs by
8523 // now.
8524 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
8525 Triple.getArch() == llvm::Triple::aarch64_32 ||
8526 Triple.getArch() == llvm::Triple::aarch64_be;
8527 if (VecKind == VectorKind::NeonPoly) {
8528 if (IsPolyUnsigned) {
8529 // AArch64 polynomial vectors are unsigned.
8530 return BTy->getKind() == BuiltinType::UChar ||
8531 BTy->getKind() == BuiltinType::UShort ||
8532 BTy->getKind() == BuiltinType::ULong ||
8533 BTy->getKind() == BuiltinType::ULongLong;
8534 } else {
8535 // AArch32 polynomial vectors are signed.
8536 return BTy->getKind() == BuiltinType::SChar ||
8537 BTy->getKind() == BuiltinType::Short ||
8538 BTy->getKind() == BuiltinType::LongLong;
8539 }
8540 }
8541
8542 // Non-polynomial vector types: the usual suspects are allowed, as well as
8543 // float64_t on AArch64.
8544 if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) &&
8545 BTy->getKind() == BuiltinType::Double)
8546 return true;
8547
8548 return BTy->getKind() == BuiltinType::SChar ||
8549 BTy->getKind() == BuiltinType::UChar ||
8550 BTy->getKind() == BuiltinType::Short ||
8551 BTy->getKind() == BuiltinType::UShort ||
8552 BTy->getKind() == BuiltinType::Int ||
8553 BTy->getKind() == BuiltinType::UInt ||
8554 BTy->getKind() == BuiltinType::Long ||
8555 BTy->getKind() == BuiltinType::ULong ||
8556 BTy->getKind() == BuiltinType::LongLong ||
8557 BTy->getKind() == BuiltinType::ULongLong ||
8558 BTy->getKind() == BuiltinType::Float ||
8559 BTy->getKind() == BuiltinType::Half ||
8560 BTy->getKind() == BuiltinType::BFloat16 ||
8561 BTy->getKind() == BuiltinType::MFloat8;
8562}
8563
8565 llvm::APSInt &Result) {
8566 const auto *AttrExpr = Attr.getArgAsExpr(0);
8567 if (!AttrExpr->isTypeDependent()) {
8568 if (std::optional<llvm::APSInt> Res =
8569 AttrExpr->getIntegerConstantExpr(S.Context)) {
8570 Result = *Res;
8571 return true;
8572 }
8573 }
8574 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
8575 << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange();
8576 Attr.setInvalid();
8577 return false;
8578}
8579
8580/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
8581/// "neon_polyvector_type" attributes are used to create vector types that
8582/// are mangled according to ARM's ABI. Otherwise, these types are identical
8583/// to those created with the "vector_size" attribute. Unlike "vector_size"
8584/// the argument to these Neon attributes is the number of vector elements,
8585/// not the vector size in bytes. The vector width and element type must
8586/// match one of the standard Neon vector types.
8588 Sema &S, VectorKind VecKind) {
8589 bool IsTargetOffloading = S.getLangOpts().isTargetDevice();
8590
8591 // Target must have NEON (or MVE, whose vectors are similar enough
8592 // not to need a separate attribute)
8593 if (!S.Context.getTargetInfo().hasFeature("mve") &&
8594 VecKind == VectorKind::Neon &&
8595 S.Context.getTargetInfo().getTriple().isArmMClass()) {
8596 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported_m_profile)
8597 << Attr << "'mve'";
8598 Attr.setInvalid();
8599 return;
8600 }
8601 if (!S.Context.getTargetInfo().hasFeature("mve") &&
8602 VecKind == VectorKind::NeonPoly &&
8603 S.Context.getTargetInfo().getTriple().isArmMClass()) {
8604 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported_m_profile)
8605 << Attr << "'mve'";
8606 Attr.setInvalid();
8607 return;
8608 }
8609
8610 // Check the attribute arguments.
8611 if (Attr.getNumArgs() != 1) {
8612 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8613 << Attr << 1;
8614 Attr.setInvalid();
8615 return;
8616 }
8617 // The number of elements must be an ICE.
8618 llvm::APSInt numEltsInt(32);
8619 if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt))
8620 return;
8621
8622 // Only certain element types are supported for Neon vectors.
8623 if (!isPermittedNeonBaseType(CurType, VecKind, S) && !IsTargetOffloading) {
8624 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
8625 Attr.setInvalid();
8626 return;
8627 }
8628
8629 // The total size of the vector must be 64 or 128 bits.
8630 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
8631 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
8632 unsigned vecSize = typeSize * numElts;
8633 if (vecSize != 64 && vecSize != 128) {
8634 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
8635 Attr.setInvalid();
8636 return;
8637 }
8638
8639 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
8640}
8641
8642/// Handle the __ptrauth qualifier.
8644 const ParsedAttr &Attr, Sema &S) {
8645
8646 assert((Attr.getNumArgs() > 0 && Attr.getNumArgs() <= 3) &&
8647 "__ptrauth qualifier takes between 1 and 3 arguments");
8648 Expr *KeyArg = Attr.getArgAsExpr(0);
8649 Expr *IsAddressDiscriminatedArg =
8650 Attr.getNumArgs() >= 2 ? Attr.getArgAsExpr(1) : nullptr;
8651 Expr *ExtraDiscriminatorArg =
8652 Attr.getNumArgs() >= 3 ? Attr.getArgAsExpr(2) : nullptr;
8653
8654 unsigned Key;
8655 if (S.checkConstantPointerAuthKey(KeyArg, Key)) {
8656 Attr.setInvalid();
8657 return;
8658 }
8659 assert(Key <= PointerAuthQualifier::MaxKey && "ptrauth key is out of range");
8660
8661 bool IsInvalid = false;
8662 unsigned IsAddressDiscriminated, ExtraDiscriminator;
8663 IsInvalid |= !S.checkPointerAuthDiscriminatorArg(IsAddressDiscriminatedArg,
8665 IsAddressDiscriminated);
8666 IsInvalid |= !S.checkPointerAuthDiscriminatorArg(
8667 ExtraDiscriminatorArg, PointerAuthDiscArgKind::Extra, ExtraDiscriminator);
8668
8669 if (IsInvalid) {
8670 Attr.setInvalid();
8671 return;
8672 }
8673
8674 if (!T->isSignableType(Ctx) && !T->isDependentType()) {
8675 S.Diag(Attr.getLoc(), diag::err_ptrauth_qualifier_invalid_target) << T;
8676 Attr.setInvalid();
8677 return;
8678 }
8679
8680 if (T.getPointerAuth()) {
8681 S.Diag(Attr.getLoc(), diag::err_ptrauth_qualifier_redundant) << T;
8682 Attr.setInvalid();
8683 return;
8684 }
8685
8686 if (!S.getLangOpts().PointerAuthIntrinsics) {
8687 S.Diag(Attr.getLoc(), diag::err_ptrauth_disabled) << Attr.getRange();
8688 Attr.setInvalid();
8689 return;
8690 }
8691
8692 assert((!IsAddressDiscriminatedArg || IsAddressDiscriminated <= 1) &&
8693 "address discriminator arg should be either 0 or 1");
8695 Key, IsAddressDiscriminated, ExtraDiscriminator,
8696 PointerAuthenticationMode::SignAndAuth, /*IsIsaPointer=*/false,
8697 /*AuthenticatesNullValues=*/false);
8698 T = S.Context.getPointerAuthType(T, Qual);
8699}
8700
8701/// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is
8702/// used to create fixed-length versions of sizeless SVE types defined by
8703/// the ACLE, such as svint32_t and svbool_t.
8705 Sema &S) {
8706 // Target must have SVE.
8707 if (!S.Context.getTargetInfo().hasFeature("sve")) {
8708 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'";
8709 Attr.setInvalid();
8710 return;
8711 }
8712
8713 // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or
8714 // if <bits>+ syntax is used.
8715 if (!S.getLangOpts().VScaleMin ||
8716 S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) {
8717 S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported)
8718 << Attr;
8719 Attr.setInvalid();
8720 return;
8721 }
8722
8723 // Check the attribute arguments.
8724 if (Attr.getNumArgs() != 1) {
8725 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8726 << Attr << 1;
8727 Attr.setInvalid();
8728 return;
8729 }
8730
8731 // The vector size must be an integer constant expression.
8732 llvm::APSInt SveVectorSizeInBits(32);
8733 if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits))
8734 return;
8735
8736 unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue());
8737
8738 // The attribute vector size must match -msve-vector-bits.
8739 if (VecSize != S.getLangOpts().VScaleMin * 128) {
8740 S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size)
8741 << VecSize << S.getLangOpts().VScaleMin * 128;
8742 Attr.setInvalid();
8743 return;
8744 }
8745
8746 // Attribute can only be attached to a single SVE vector or predicate type.
8747 if (!CurType->isSveVLSBuiltinType()) {
8748 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type)
8749 << Attr << CurType;
8750 Attr.setInvalid();
8751 return;
8752 }
8753
8754 const auto *BT = CurType->castAs<BuiltinType>();
8755
8756 QualType EltType = CurType->getSveEltType(S.Context);
8757 unsigned TypeSize = S.Context.getTypeSize(EltType);
8759 if (BT->getKind() == BuiltinType::SveBool) {
8760 // Predicates are represented as i8.
8761 VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth();
8763 } else
8764 VecSize /= TypeSize;
8765 CurType = S.Context.getVectorType(EltType, VecSize, VecKind);
8766}
8767
8768static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State,
8769 QualType &CurType,
8770 ParsedAttr &Attr) {
8771 const VectorType *VT = dyn_cast<VectorType>(CurType);
8772 if (!VT || VT->getVectorKind() != VectorKind::Neon) {
8773 State.getSema().Diag(Attr.getLoc(),
8774 diag::err_attribute_arm_mve_polymorphism);
8775 Attr.setInvalid();
8776 return;
8777 }
8778
8779 CurType =
8780 State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>(
8781 State.getSema().Context, Attr),
8782 CurType, CurType);
8783}
8784
8785/// HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is
8786/// used to create fixed-length versions of sizeless RVV types such as
8787/// vint8m1_t_t.
8789 ParsedAttr &Attr, Sema &S) {
8790 // Target must have vector extension.
8791 if (!S.Context.getTargetInfo().hasFeature("zve32x")) {
8792 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
8793 << Attr << "'zve32x'";
8794 Attr.setInvalid();
8795 return;
8796 }
8797
8798 auto VScale = S.Context.getTargetInfo().getVScaleRange(
8800 if (!VScale || !VScale->first || VScale->first != VScale->second) {
8801 S.Diag(Attr.getLoc(), diag::err_attribute_riscv_rvv_bits_unsupported)
8802 << Attr;
8803 Attr.setInvalid();
8804 return;
8805 }
8806
8807 // Check the attribute arguments.
8808 if (Attr.getNumArgs() != 1) {
8809 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8810 << Attr << 1;
8811 Attr.setInvalid();
8812 return;
8813 }
8814
8815 // The vector size must be an integer constant expression.
8816 llvm::APSInt RVVVectorSizeInBits(32);
8817 if (!verifyValidIntegerConstantExpr(S, Attr, RVVVectorSizeInBits))
8818 return;
8819
8820 // Attribute can only be attached to a single RVV vector type.
8821 if (!CurType->isRVVVLSBuiltinType()) {
8822 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_rvv_type)
8823 << Attr << CurType;
8824 Attr.setInvalid();
8825 return;
8826 }
8827
8828 unsigned VecSize = static_cast<unsigned>(RVVVectorSizeInBits.getZExtValue());
8829
8832 unsigned MinElts = Info.EC.getKnownMinValue();
8833
8835 unsigned ExpectedSize = VScale->first * MinElts;
8836 QualType EltType = CurType->getRVVEltType(S.Context);
8837 unsigned EltSize = S.Context.getTypeSize(EltType);
8838 unsigned NumElts;
8839 if (Info.ElementType == S.Context.BoolTy) {
8840 NumElts = VecSize / S.Context.getCharWidth();
8841 if (!NumElts) {
8842 NumElts = 1;
8843 switch (VecSize) {
8844 case 1:
8846 break;
8847 case 2:
8849 break;
8850 case 4:
8852 break;
8853 }
8854 } else
8856 } else {
8857 ExpectedSize *= EltSize;
8858 NumElts = VecSize / EltSize;
8859 }
8860
8861 // The attribute vector size must match -mrvv-vector-bits.
8862 if (VecSize != ExpectedSize) {
8863 S.Diag(Attr.getLoc(), diag::err_attribute_bad_rvv_vector_size)
8864 << VecSize << ExpectedSize;
8865 Attr.setInvalid();
8866 return;
8867 }
8868
8869 CurType = S.Context.getVectorType(EltType, NumElts, VecKind);
8870}
8871
8872/// Handle OpenCL Access Qualifier Attribute.
8873static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
8874 Sema &S) {
8875 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
8876 if (!(CurType->isImageType() || CurType->isPipeType())) {
8877 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
8878 Attr.setInvalid();
8879 return;
8880 }
8881
8882 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
8883 QualType BaseTy = TypedefTy->desugar();
8884
8885 std::string PrevAccessQual;
8886 if (BaseTy->isPipeType()) {
8887 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
8888 OpenCLAccessAttr *Attr =
8889 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
8890 PrevAccessQual = Attr->getSpelling();
8891 } else {
8892 PrevAccessQual = "read_only";
8893 }
8894 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
8895
8896 switch (ImgType->getKind()) {
8897 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8898 case BuiltinType::Id: \
8899 PrevAccessQual = #Access; \
8900 break;
8901 #include "clang/Basic/OpenCLImageTypes.def"
8902 default:
8903 llvm_unreachable("Unable to find corresponding image type.");
8904 }
8905 } else {
8906 llvm_unreachable("unexpected type");
8907 }
8908 StringRef AttrName = Attr.getAttrName()->getName();
8909 if (PrevAccessQual == AttrName.ltrim("_")) {
8910 // Duplicated qualifiers
8911 S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
8912 << AttrName << Attr.getRange();
8913 } else {
8914 // Contradicting qualifiers
8915 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
8916 }
8917
8918 S.Diag(TypedefTy->getDecl()->getBeginLoc(),
8919 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
8920 } else if (CurType->isPipeType()) {
8921 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
8922 QualType ElemType = CurType->castAs<PipeType>()->getElementType();
8923 CurType = S.Context.getWritePipeType(ElemType);
8924 }
8925 }
8926}
8927
8928/// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type
8929static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8930 Sema &S) {
8931 if (!S.getLangOpts().MatrixTypes) {
8932 S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled);
8933 return;
8934 }
8935
8936 if (Attr.getNumArgs() != 2) {
8937 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8938 << Attr << 2;
8939 return;
8940 }
8941
8942 Expr *RowsExpr = Attr.getArgAsExpr(0);
8943 Expr *ColsExpr = Attr.getArgAsExpr(1);
8944 QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc());
8945 if (!T.isNull())
8946 CurType = T;
8947}
8948
8949static void HandleAnnotateTypeAttr(TypeProcessingState &State,
8950 QualType &CurType, const ParsedAttr &PA) {
8951 Sema &S = State.getSema();
8952
8953 if (PA.getNumArgs() < 1) {
8954 S.Diag(PA.getLoc(), diag::err_attribute_too_few_arguments) << PA << 1;
8955 return;
8956 }
8957
8958 // Make sure that there is a string literal as the annotation's first
8959 // argument.
8960 StringRef Str;
8961 if (!S.checkStringLiteralArgumentAttr(PA, 0, Str))
8962 return;
8963
8965 Args.reserve(PA.getNumArgs() - 1);
8966 for (unsigned Idx = 1; Idx < PA.getNumArgs(); Idx++) {
8967 assert(!PA.isArgIdent(Idx));
8968 Args.push_back(PA.getArgAsExpr(Idx));
8969 }
8970 if (!S.ConstantFoldAttrArgs(PA, Args))
8971 return;
8972 auto *AnnotateTypeAttr =
8973 AnnotateTypeAttr::Create(S.Context, Str, Args.data(), Args.size(), PA);
8974 CurType = State.getAttributedType(AnnotateTypeAttr, CurType, CurType);
8975}
8976
8977static void HandleLifetimeBoundAttr(TypeProcessingState &State,
8978 QualType &CurType,
8979 ParsedAttr &Attr) {
8980 if (State.getDeclarator().isDeclarationOfFunction()) {
8981 CurType = State.getAttributedType(
8982 createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
8983 CurType, CurType);
8984 return;
8985 }
8986 State.getSema().Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
8989}
8990
8991static void HandleLifetimeCaptureByAttr(TypeProcessingState &State,
8992 QualType &CurType, ParsedAttr &PA) {
8993 if (State.getDeclarator().isDeclarationOfFunction()) {
8994 auto *Attr = State.getSema().ParseLifetimeCaptureByAttr(PA, "this");
8995 if (Attr)
8996 CurType = State.getAttributedType(Attr, CurType, CurType);
8997 }
8998}
8999
9000static void HandleHLSLParamModifierAttr(TypeProcessingState &State,
9001 QualType &CurType,
9002 const ParsedAttr &Attr, Sema &S) {
9003 // Don't apply this attribute to template dependent types. It is applied on
9004 // substitution during template instantiation. Also skip parsing this if we've
9005 // already modified the type based on an earlier attribute.
9006 if (CurType->isDependentType() || State.didParseHLSLParamMod())
9007 return;
9008 if (Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_inout ||
9009 Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_out) {
9010 State.setParsedHLSLParamMod(true);
9011 }
9012}
9013
9014static void processTypeAttrs(TypeProcessingState &state, QualType &type,
9015 TypeAttrLocation TAL,
9016 const ParsedAttributesView &attrs,
9017 CUDAFunctionTarget CFT) {
9018
9019 state.setParsedNoDeref(false);
9020 if (attrs.empty())
9021 return;
9022
9023 // Scan through and apply attributes to this type where it makes sense. Some
9024 // attributes (such as __address_space__, __vector_size__, etc) apply to the
9025 // type, but others can be present in the type specifiers even though they
9026 // apply to the decl. Here we apply type attributes and ignore the rest.
9027
9028 // This loop modifies the list pretty frequently, but we still need to make
9029 // sure we visit every element once. Copy the attributes list, and iterate
9030 // over that.
9031 ParsedAttributesView AttrsCopy{attrs};
9032 for (ParsedAttr &attr : AttrsCopy) {
9033
9034 // Skip attributes that were marked to be invalid.
9035 if (attr.isInvalid())
9036 continue;
9037
9038 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute()) {
9039 // [[gnu::...]] attributes are treated as declaration attributes, so may
9040 // not appertain to a DeclaratorChunk. If we handle them as type
9041 // attributes, accept them in that position and diagnose the GCC
9042 // incompatibility.
9043 if (attr.isGNUScope()) {
9044 assert(attr.isStandardAttributeSyntax());
9045 bool IsTypeAttr = attr.isTypeAttr();
9046 if (TAL == TAL_DeclChunk) {
9047 state.getSema().Diag(attr.getLoc(),
9048 IsTypeAttr
9049 ? diag::warn_gcc_ignores_type_attr
9050 : diag::warn_cxx11_gnu_attribute_on_type)
9051 << attr;
9052 if (!IsTypeAttr)
9053 continue;
9054 }
9055 } else if (TAL != TAL_DeclSpec && TAL != TAL_DeclChunk &&
9056 !attr.isTypeAttr()) {
9057 // Otherwise, only consider type processing for a C++11 attribute if
9058 // - it has actually been applied to a type (decl-specifier-seq or
9059 // declarator chunk), or
9060 // - it is a type attribute, irrespective of where it was applied (so
9061 // that we can support the legacy behavior of some type attributes
9062 // that can be applied to the declaration name).
9063 continue;
9064 }
9065 }
9066
9067 // If this is an attribute we can handle, do so now,
9068 // otherwise, add it to the FnAttrs list for rechaining.
9069 switch (attr.getKind()) {
9070 default:
9071 // A [[]] attribute on a declarator chunk must appertain to a type.
9072 if ((attr.isStandardAttributeSyntax() ||
9073 attr.isRegularKeywordAttribute()) &&
9074 TAL == TAL_DeclChunk) {
9075 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
9076 << attr << attr.isRegularKeywordAttribute();
9077 attr.setUsedAsTypeAttr();
9078 }
9079 break;
9080
9082 if (attr.isStandardAttributeSyntax()) {
9083 state.getSema().DiagnoseUnknownAttribute(attr);
9084 // Mark the attribute as invalid so we don't emit the same diagnostic
9085 // multiple times.
9086 attr.setInvalid();
9087 }
9088 break;
9089
9091 break;
9092
9093 case ParsedAttr::AT_BTFTypeTag:
9095 attr.setUsedAsTypeAttr();
9096 break;
9097
9098 case ParsedAttr::AT_MayAlias:
9099 // FIXME: This attribute needs to actually be handled, but if we ignore
9100 // it it breaks large amounts of Linux software.
9101 attr.setUsedAsTypeAttr();
9102 break;
9103 case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace:
9104 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace:
9105 state.getSema().Diag(attr.getLoc(), diag::warn_deprecated_attribute)
9106 << attr;
9107 [[fallthrough]];
9108 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
9109 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
9110 case ParsedAttr::AT_OpenCLLocalAddressSpace:
9111 case ParsedAttr::AT_OpenCLConstantAddressSpace:
9112 case ParsedAttr::AT_OpenCLGenericAddressSpace:
9113 case ParsedAttr::AT_AddressSpace:
9115 attr.setUsedAsTypeAttr();
9116 break;
9117 case ParsedAttr::AT_HLSLGroupSharedAddressSpace:
9119 if (state.getDeclarator().getContext() == DeclaratorContext::Prototype) {
9120 if (state.getSema().getLangOpts().getHLSLVersion() <
9122 state.getSema().Diag(attr.getLoc(), diag::warn_hlsl_groupshared_202x);
9123
9124 // Note: we don't check for the usage of HLSLParamModifiers in/out/inout
9125 // here because the check in the AT_HLSLParamModifier case is sufficient
9126 // regardless of the order of groupshared or in/out/inout specified in
9127 // the parameter. And checking there produces a better error message.
9128 }
9129 attr.setUsedAsTypeAttr();
9130 break;
9131 case ParsedAttr::AT_HLSLRowMajor:
9132 case ParsedAttr::AT_HLSLColumnMajor:
9133 if (Attr *A =
9134 state.getSema().HLSL().buildMatrixLayoutTypeAttr(type, attr))
9135 type = state.getAttributedType(A, type, type);
9136 attr.setUsedAsTypeAttr();
9137 break;
9139 if (!handleObjCPointerTypeAttr(state, attr, type))
9141 attr.setUsedAsTypeAttr();
9142 break;
9143 case ParsedAttr::AT_VectorSize:
9144 HandleVectorSizeAttr(type, attr, state.getSema());
9145 attr.setUsedAsTypeAttr();
9146 break;
9147 case ParsedAttr::AT_ExtVectorType:
9148 HandleExtVectorTypeAttr(type, attr, state.getSema());
9149 attr.setUsedAsTypeAttr();
9150 break;
9151 case ParsedAttr::AT_NeonVectorType:
9153 attr.setUsedAsTypeAttr();
9154 break;
9155 case ParsedAttr::AT_NeonPolyVectorType:
9156 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
9158 attr.setUsedAsTypeAttr();
9159 break;
9160 case ParsedAttr::AT_ArmSveVectorBits:
9161 HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema());
9162 attr.setUsedAsTypeAttr();
9163 break;
9164 case ParsedAttr::AT_ArmMveStrictPolymorphism: {
9166 attr.setUsedAsTypeAttr();
9167 break;
9168 }
9169 case ParsedAttr::AT_RISCVRVVVectorBits:
9170 HandleRISCVRVVVectorBitsTypeAttr(type, attr, state.getSema());
9171 attr.setUsedAsTypeAttr();
9172 break;
9173 case ParsedAttr::AT_OpenCLAccess:
9174 HandleOpenCLAccessAttr(type, attr, state.getSema());
9175 attr.setUsedAsTypeAttr();
9176 break;
9177 case ParsedAttr::AT_PointerAuth:
9178 HandlePtrAuthQualifier(state.getSema().Context, type, attr,
9179 state.getSema());
9180 attr.setUsedAsTypeAttr();
9181 break;
9182 case ParsedAttr::AT_LifetimeBound:
9183 if (TAL == TAL_DeclChunk)
9185 break;
9186 case ParsedAttr::AT_LifetimeCaptureBy:
9187 if (TAL == TAL_DeclChunk)
9189 break;
9190 case ParsedAttr::AT_OverflowBehavior:
9192 attr.setUsedAsTypeAttr();
9193 break;
9194
9195 case ParsedAttr::AT_NoDeref: {
9196 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
9197 // See https://github.com/llvm/llvm-project/issues/55790 for details.
9198 // For the time being, we simply emit a warning that the attribute is
9199 // ignored.
9200 if (attr.isStandardAttributeSyntax()) {
9201 state.getSema().Diag(attr.getLoc(), diag::warn_attribute_ignored)
9202 << attr;
9203 break;
9204 }
9205 ASTContext &Ctx = state.getSema().Context;
9206 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
9207 type, type);
9208 attr.setUsedAsTypeAttr();
9209 state.setParsedNoDeref(true);
9210 break;
9211 }
9212
9213 case ParsedAttr::AT_MatrixType:
9214 HandleMatrixTypeAttr(type, attr, state.getSema());
9215 attr.setUsedAsTypeAttr();
9216 break;
9217
9218 case ParsedAttr::AT_WebAssemblyFuncref: {
9220 attr.setUsedAsTypeAttr();
9221 break;
9222 }
9223
9224 case ParsedAttr::AT_HLSLParamModifier: {
9225 HandleHLSLParamModifierAttr(state, type, attr, state.getSema());
9226 if (attrs.hasAttribute(ParsedAttr::AT_HLSLGroupSharedAddressSpace)) {
9227 state.getSema().Diag(attr.getLoc(), diag::err_hlsl_attr_incompatible)
9228 << attr << "'groupshared'";
9229 attr.setInvalid();
9230 return;
9231 }
9232 attr.setUsedAsTypeAttr();
9233 break;
9234 }
9235
9236 case ParsedAttr::AT_SwiftAttr: {
9237 HandleSwiftAttr(state, TAL, type, attr);
9238 break;
9239 }
9240
9243 attr.setUsedAsTypeAttr();
9244 break;
9245
9246
9248 // Either add nullability here or try to distribute it. We
9249 // don't want to distribute the nullability specifier past any
9250 // dependent type, because that complicates the user model.
9251 if (type->canHaveNullability() || type->isDependentType() ||
9252 type->isArrayType() ||
9254 unsigned endIndex;
9255 if (TAL == TAL_DeclChunk)
9256 endIndex = state.getCurrentChunkIndex();
9257 else
9258 endIndex = state.getDeclarator().getNumTypeObjects();
9259 bool allowOnArrayType =
9260 state.getDeclarator().isPrototypeContext() &&
9261 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
9263 allowOnArrayType)) {
9264 attr.setInvalid();
9265 }
9266
9267 attr.setUsedAsTypeAttr();
9268 }
9269 break;
9270
9271 case ParsedAttr::AT_ObjCKindOf:
9272 // '__kindof' must be part of the decl-specifiers.
9273 switch (TAL) {
9274 case TAL_DeclSpec:
9275 break;
9276
9277 case TAL_DeclChunk:
9278 case TAL_DeclName:
9279 state.getSema().Diag(attr.getLoc(),
9280 diag::err_objc_kindof_wrong_position)
9281 << FixItHint::CreateRemoval(attr.getLoc())
9283 state.getDeclarator().getDeclSpec().getBeginLoc(),
9284 "__kindof ");
9285 break;
9286 }
9287
9288 // Apply it regardless.
9289 if (checkObjCKindOfType(state, type, attr))
9290 attr.setInvalid();
9291 break;
9292
9293 case ParsedAttr::AT_NoThrow:
9294 // Exception Specifications aren't generally supported in C mode throughout
9295 // clang, so revert to attribute-based handling for C.
9296 if (!state.getSema().getLangOpts().CPlusPlus)
9297 break;
9298 [[fallthrough]];
9300
9301 attr.setUsedAsTypeAttr();
9302
9303 // Attributes with standard syntax have strict rules for what they
9304 // appertain to and hence should not use the "distribution" logic below.
9305 if (attr.isStandardAttributeSyntax() ||
9306 attr.isRegularKeywordAttribute()) {
9307 if (!handleFunctionTypeAttr(state, attr, type, CFT)) {
9308 diagnoseBadTypeAttribute(state.getSema(), attr, type);
9309 attr.setInvalid();
9310 }
9311 break;
9312 }
9313
9314 // Never process function type attributes as part of the
9315 // declaration-specifiers.
9316 if (TAL == TAL_DeclSpec)
9318
9319 // Otherwise, handle the possible delays.
9320 else if (!handleFunctionTypeAttr(state, attr, type, CFT))
9322 break;
9323 case ParsedAttr::AT_AcquireHandle: {
9324 if (!type->isFunctionType())
9325 return;
9326
9327 if (attr.getNumArgs() != 1) {
9328 state.getSema().Diag(attr.getLoc(),
9329 diag::err_attribute_wrong_number_arguments)
9330 << attr << 1;
9331 attr.setInvalid();
9332 return;
9333 }
9334
9335 StringRef HandleType;
9336 if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType))
9337 return;
9338 type = state.getAttributedType(
9339 AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr),
9340 type, type);
9341 attr.setUsedAsTypeAttr();
9342 break;
9343 }
9344 case ParsedAttr::AT_AnnotateType: {
9346 attr.setUsedAsTypeAttr();
9347 break;
9348 }
9349 case ParsedAttr::AT_HLSLResourceClass:
9350 case ParsedAttr::AT_HLSLResourceDimension:
9351 case ParsedAttr::AT_HLSLROV:
9352 case ParsedAttr::AT_HLSLRawBuffer:
9353 case ParsedAttr::AT_HLSLIsArray:
9354 case ParsedAttr::AT_HLSLContainedType: {
9355 // Only collect HLSL resource type attributes that are in
9356 // decl-specifier-seq; do not collect attributes on declarations or those
9357 // that get to slide after declaration name.
9358 if (TAL == TAL_DeclSpec &&
9359 state.getSema().HLSL().handleResourceTypeAttr(type, attr))
9360 attr.setUsedAsTypeAttr();
9361 break;
9362 }
9363 }
9364
9365 // Handle attributes that are defined in a macro. We do not want this to be
9366 // applied to ObjC builtin attributes.
9367 if (isa<AttributedType>(type) && attr.hasMacroIdentifier() &&
9368 !type.getQualifiers().hasObjCLifetime() &&
9369 !type.getQualifiers().hasObjCGCAttr() &&
9370 attr.getKind() != ParsedAttr::AT_ObjCGC &&
9371 attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
9372 const IdentifierInfo *MacroII = attr.getMacroIdentifier();
9373 type = state.getSema().Context.getMacroQualifiedType(type, MacroII);
9374 state.setExpansionLocForMacroQualifiedType(
9375 cast<MacroQualifiedType>(type.getTypePtr()),
9376 attr.getMacroExpansionLoc());
9377 }
9378 }
9379}
9380
9382 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
9383 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
9384 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
9385 auto *Def = Var->getDefinition();
9386 if (!Def) {
9387 SourceLocation PointOfInstantiation = E->getExprLoc();
9388 runWithSufficientStackSpace(PointOfInstantiation, [&] {
9389 InstantiateVariableDefinition(PointOfInstantiation, Var);
9390 });
9391 Def = Var->getDefinition();
9392
9393 // If we don't already have a point of instantiation, and we managed
9394 // to instantiate a definition, this is the point of instantiation.
9395 // Otherwise, we don't request an end-of-TU instantiation, so this is
9396 // not a point of instantiation.
9397 // FIXME: Is this really the right behavior?
9398 if (Var->getPointOfInstantiation().isInvalid() && Def) {
9399 assert(Var->getTemplateSpecializationKind() ==
9401 "explicit instantiation with no point of instantiation");
9402 Var->setTemplateSpecializationKind(
9403 Var->getTemplateSpecializationKind(), PointOfInstantiation);
9404 }
9405 }
9406
9407 // Update the type to the definition's type both here and within the
9408 // expression.
9409 if (Def) {
9410 DRE->setDecl(Def);
9411 QualType T = Def->getType();
9412 DRE->setType(T);
9413 // FIXME: Update the type on all intervening expressions.
9414 E->setType(T);
9415 }
9416
9417 // We still go on to try to complete the type independently, as it
9418 // may also require instantiations or diagnostics if it remains
9419 // incomplete.
9420 }
9421 }
9422 }
9423 if (const auto CastE = dyn_cast<ExplicitCastExpr>(E)) {
9424 QualType DestType = CastE->getTypeAsWritten();
9425 if (const auto *IAT = Context.getAsIncompleteArrayType(DestType)) {
9426 // C++20 [expr.static.cast]p.4: ... If T is array of unknown bound,
9427 // this direct-initialization defines the type of the expression
9428 // as U[1]
9429 QualType ResultType = Context.getConstantArrayType(
9430 IAT->getElementType(),
9431 llvm::APInt(Context.getTypeSize(Context.getSizeType()), 1),
9432 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal,
9433 /*IndexTypeQuals=*/0);
9434 E->setType(ResultType);
9435 }
9436 }
9437}
9438
9440 // Incomplete array types may be completed by the initializer attached to
9441 // their definitions. For static data members of class templates and for
9442 // variable templates, we need to instantiate the definition to get this
9443 // initializer and complete the type.
9444 if (E->getType()->isIncompleteArrayType())
9446
9447 // FIXME: Are there other cases which require instantiating something other
9448 // than the type to complete the type of an expression?
9449
9450 return E->getType();
9451}
9452
9454 TypeDiagnoser &Diagnoser) {
9455 return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind,
9456 Diagnoser);
9457}
9458
9459bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
9460 BoundTypeDiagnoser<> Diagnoser(DiagID);
9462}
9463
9465 CompleteTypeKind Kind,
9466 TypeDiagnoser &Diagnoser) {
9467 if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser))
9468 return true;
9469 if (auto *TD = T->getAsTagDecl(); TD && !TD->isCompleteDefinitionRequired()) {
9470 TD->setCompleteDefinitionRequired();
9471 Consumer.HandleTagDeclRequiredDefinition(TD);
9472 }
9473 return false;
9474}
9475
9478 if (!Suggested)
9479 return false;
9480
9481 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
9482 // and isolate from other C++ specific checks.
9484 getLangOpts(), D->getASTContext(), Suggested->getASTContext(),
9485 NonEquivalentDecls, StructuralEquivalenceKind::Default,
9486 /*StrictTypeSpelling=*/false, /*Complain=*/true,
9487 /*ErrorOnTagTypeMismatch=*/true);
9488 return Ctx.IsEquivalent(D, Suggested);
9489}
9490
9492 AcceptableKind Kind, bool OnlyNeedComplete) {
9493 // Easy case: if we don't have modules, all declarations are visible.
9494 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
9495 return true;
9496
9497 // If this definition was instantiated from a template, map back to the
9498 // pattern from which it was instantiated.
9499 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined())
9500 // We're in the middle of defining it; this definition should be treated
9501 // as visible.
9502 return true;
9503
9504 auto DefinitionIsAcceptable = [&](NamedDecl *D) {
9505 // The (primary) definition might be in a visible module.
9506 if (isAcceptable(D, Kind))
9507 return true;
9508
9509 // A visible module might have a merged definition instead.
9512 if (CodeSynthesisContexts.empty() &&
9513 !getLangOpts().ModulesLocalVisibility) {
9514 // Cache the fact that this definition is implicitly visible because
9515 // there is a visible merged definition.
9517 }
9518 return true;
9519 }
9520
9521 return false;
9522 };
9523 auto IsDefinition = [](NamedDecl *D) {
9524 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
9525 return RD->isThisDeclarationADefinition();
9526 if (auto *ED = dyn_cast<EnumDecl>(D))
9527 return ED->isThisDeclarationADefinition();
9528 if (auto *FD = dyn_cast<FunctionDecl>(D))
9529 return FD->isThisDeclarationADefinition();
9530 if (auto *VD = dyn_cast<VarDecl>(D))
9531 return VD->isThisDeclarationADefinition() == VarDecl::Definition;
9532 llvm_unreachable("unexpected decl type");
9533 };
9534 auto FoundAcceptableDefinition = [&](NamedDecl *D) {
9536 return DefinitionIsAcceptable(D);
9537
9538 // See ASTDeclReader::attachPreviousDeclImpl. Now we still
9539 // may demote definition to declaration for decls in haeder modules,
9540 // so avoid looking at its redeclaration to save time.
9541 // NOTE: If we don't demote definition to declarations for decls
9542 // in header modules, remove the condition.
9544 return DefinitionIsAcceptable(D);
9545
9546 for (auto *RD : D->redecls()) {
9547 auto *ND = cast<NamedDecl>(RD);
9548 if (!IsDefinition(ND))
9549 continue;
9550 if (DefinitionIsAcceptable(ND)) {
9551 *Suggested = ND;
9552 return true;
9553 }
9554 }
9555
9556 return false;
9557 };
9558
9559 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9560 if (auto *Pattern = RD->getTemplateInstantiationPattern())
9561 RD = Pattern;
9562 D = RD->getDefinition();
9563 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
9564 if (auto *Pattern = ED->getTemplateInstantiationPattern())
9565 ED = Pattern;
9566 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) {
9567 // If the enum has a fixed underlying type, it may have been forward
9568 // declared. In -fms-compatibility, `enum Foo;` will also forward declare
9569 // the enum and assign it the underlying type of `int`. Since we're only
9570 // looking for a complete type (not a definition), any visible declaration
9571 // of it will do.
9572 *Suggested = nullptr;
9573 for (auto *Redecl : ED->redecls()) {
9574 if (isAcceptable(Redecl, Kind))
9575 return true;
9576 if (Redecl->isThisDeclarationADefinition() ||
9577 (Redecl->isCanonicalDecl() && !*Suggested))
9578 *Suggested = Redecl;
9579 }
9580
9581 return false;
9582 }
9583 D = ED->getDefinition();
9584 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
9585 if (auto *Pattern = FD->getTemplateInstantiationPattern())
9586 FD = Pattern;
9587 D = FD->getDefinition();
9588 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
9589 if (auto *Pattern = VD->getTemplateInstantiationPattern())
9590 VD = Pattern;
9591 D = VD->getDefinition();
9592 }
9593
9594 assert(D && "missing definition for pattern of instantiated definition");
9595
9596 *Suggested = D;
9597
9598 if (FoundAcceptableDefinition(D))
9599 return true;
9600
9601 // The external source may have additional definitions of this entity that are
9602 // visible, so complete the redeclaration chain now and ask again.
9603 if (auto *Source = Context.getExternalSource()) {
9604 Source->CompleteRedeclChain(D);
9605 return FoundAcceptableDefinition(D);
9606 }
9607
9608 return false;
9609}
9610
9611/// Determine whether there is any declaration of \p D that was ever a
9612/// definition (perhaps before module merging) and is currently visible.
9613/// \param D The definition of the entity.
9614/// \param Suggested Filled in with the declaration that should be made visible
9615/// in order to provide a definition of this entity.
9616/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9617/// not defined. This only matters for enums with a fixed underlying
9618/// type, since in all other cases, a type is complete if and only if it
9619/// is defined.
9621 bool OnlyNeedComplete) {
9623 OnlyNeedComplete);
9624}
9625
9626/// Determine whether there is any declaration of \p D that was ever a
9627/// definition (perhaps before module merging) and is currently
9628/// reachable.
9629/// \param D The definition of the entity.
9630/// \param Suggested Filled in with the declaration that should be made
9631/// reachable
9632/// in order to provide a definition of this entity.
9633/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9634/// not defined. This only matters for enums with a fixed underlying
9635/// type, since in all other cases, a type is complete if and only if it
9636/// is defined.
9638 bool OnlyNeedComplete) {
9640 OnlyNeedComplete);
9641}
9642
9643/// Locks in the inheritance model for the given class and all of its bases.
9645 RD = RD->getMostRecentDecl();
9646 if (!RD->hasAttr<MSInheritanceAttr>()) {
9648 bool BestCase = false;
9651 BestCase = true;
9652 IM = RD->calculateInheritanceModel();
9653 break;
9656 break;
9659 break;
9662 break;
9663 }
9664
9667 : RD->getSourceRange();
9668 RD->addAttr(MSInheritanceAttr::CreateImplicit(
9669 S.getASTContext(), BestCase, Loc, MSInheritanceAttr::Spelling(IM)));
9671 }
9672}
9673
9674bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
9675 CompleteTypeKind Kind,
9676 TypeDiagnoser *Diagnoser) {
9677 // FIXME: Add this assertion to make sure we always get instantiation points.
9678 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
9679 // FIXME: Add this assertion to help us flush out problems with
9680 // checking for dependent types and type-dependent expressions.
9681 //
9682 // assert(!T->isDependentType() &&
9683 // "Can't ask whether a dependent type is complete");
9684
9685 if (const auto *MPTy = dyn_cast<MemberPointerType>(T.getCanonicalType())) {
9686 if (CXXRecordDecl *RD = MPTy->getMostRecentCXXRecordDecl();
9687 RD && !RD->isDependentType()) {
9688 CanQualType T = Context.getCanonicalTagType(RD);
9689 if (getLangOpts().CompleteMemberPointers && !RD->isBeingDefined() &&
9690 RequireCompleteType(Loc, T, Kind, diag::err_memptr_incomplete))
9691 return true;
9692
9693 // We lock in the inheritance model once somebody has asked us to ensure
9694 // that a pointer-to-member type is complete.
9695 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9696 (void)isCompleteType(Loc, T);
9697 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
9698 }
9699 }
9700 }
9701
9702 NamedDecl *Def = nullptr;
9704 bool Incomplete = (T->isIncompleteType(&Def) ||
9705 (!AcceptSizeless && T->isSizelessBuiltinType()));
9706
9707 // Check that any necessary explicit specializations are visible. For an
9708 // enum, we just need the declaration, so don't check this.
9709 if (Def && !isa<EnumDecl>(Def))
9711
9712 // If we have a complete type, we're done.
9713 if (!Incomplete) {
9714 NamedDecl *Suggested = nullptr;
9715 if (Def &&
9716 !hasReachableDefinition(Def, &Suggested, /*OnlyNeedComplete=*/true)) {
9717 // If the user is going to see an error here, recover by making the
9718 // definition visible.
9719 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
9720 if (Diagnoser && Suggested)
9722 /*Recover*/ TreatAsComplete);
9723 return !TreatAsComplete;
9724 } else if (Def && !TemplateInstCallbacks.empty()) {
9725 CodeSynthesisContext TempInst;
9727 TempInst.Template = Def;
9728 TempInst.Entity = Def;
9729 TempInst.PointOfInstantiation = Loc;
9730 atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
9731 atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
9732 }
9733
9734 return false;
9735 }
9736
9737 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
9738 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
9739
9740 // Give the external source a chance to provide a definition of the type.
9741 // This is kept separate from completing the redeclaration chain so that
9742 // external sources such as LLDB can avoid synthesizing a type definition
9743 // unless it's actually needed.
9744 if (Tag || IFace) {
9745 // Avoid diagnosing invalid decls as incomplete.
9746 if (Def->isInvalidDecl())
9747 return true;
9748
9749 // Give the external AST source a chance to complete the type.
9750 if (auto *Source = Context.getExternalSource()) {
9751 if (Tag && Tag->hasExternalLexicalStorage())
9752 Source->CompleteType(Tag);
9753 if (IFace && IFace->hasExternalLexicalStorage())
9754 Source->CompleteType(IFace);
9755 // If the external source completed the type, go through the motions
9756 // again to ensure we're allowed to use the completed type.
9757 if (!T->isIncompleteType())
9758 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9759 }
9760 }
9761
9762 // If we have a class template specialization or a class member of a
9763 // class template specialization, or an array with known size of such,
9764 // try to instantiate it.
9765 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
9766 bool Instantiated = false;
9767 bool Diagnosed = false;
9768 if (RD->isDependentContext()) {
9769 // Don't try to instantiate a dependent class (eg, a member template of
9770 // an instantiated class template specialization).
9771 // FIXME: Can this ever happen?
9772 } else if (auto *ClassTemplateSpec =
9773 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
9774 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
9777 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
9778 /*Complain=*/Diagnoser, ClassTemplateSpec->hasStrictPackMatch());
9779 });
9780 Instantiated = true;
9781 }
9782 } else {
9783 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
9784 if (!RD->isBeingDefined() && Pattern) {
9785 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
9786 assert(MSI && "Missing member specialization information?");
9787 // This record was instantiated from a class within a template.
9788 if (MSI->getTemplateSpecializationKind() !=
9791 Diagnosed = InstantiateClass(Loc, RD, Pattern,
9794 /*Complain=*/Diagnoser);
9795 });
9796 Instantiated = true;
9797 }
9798 }
9799 }
9800
9801 if (Instantiated) {
9802 // Instantiate* might have already complained that the template is not
9803 // defined, if we asked it to.
9804 if (Diagnoser && Diagnosed)
9805 return true;
9806 // If we instantiated a definition, check that it's usable, even if
9807 // instantiation produced an error, so that repeated calls to this
9808 // function give consistent answers.
9809 if (!T->isIncompleteType())
9810 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9811 }
9812 }
9813
9814 // FIXME: If we didn't instantiate a definition because of an explicit
9815 // specialization declaration, check that it's visible.
9816
9817 if (!Diagnoser)
9818 return true;
9819
9820 Diagnoser->diagnose(*this, Loc, T);
9821
9822 // If the type was a forward declaration of a class/struct/union
9823 // type, produce a note.
9824 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid())
9825 Diag(Tag->getLocation(), Tag->isBeingDefined()
9826 ? diag::note_type_being_defined
9827 : diag::note_forward_declaration)
9828 << Context.getCanonicalTagType(Tag);
9829
9830 // If the Objective-C class was a forward declaration, produce a note.
9831 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid())
9832 Diag(IFace->getLocation(), diag::note_forward_class);
9833
9834 // If we have external information that we can use to suggest a fix,
9835 // produce a note.
9836 if (ExternalSource)
9837 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
9838
9839 return true;
9840}
9841
9843 CompleteTypeKind Kind, unsigned DiagID) {
9844 BoundTypeDiagnoser<> Diagnoser(DiagID);
9845 return RequireCompleteType(Loc, T, Kind, Diagnoser);
9846}
9847
9848/// Get diagnostic %select index for tag kind for
9849/// literal type diagnostic message.
9850/// WARNING: Indexes apply to particular diagnostics only!
9851///
9852/// \returns diagnostic %select index.
9854 switch (Tag) {
9856 return 0;
9858 return 1;
9859 case TagTypeKind::Class:
9860 return 2;
9861 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
9862 }
9863}
9864
9866 TypeDiagnoser &Diagnoser) {
9867 assert(!T->isDependentType() && "type should not be dependent");
9868
9869 QualType ElemType = Context.getBaseElementType(T);
9870 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
9871 T->isLiteralType(Context))
9872 return false;
9873
9874 Diagnoser.diagnose(*this, Loc, T);
9875
9876 if (T->isVariableArrayType())
9877 return true;
9878
9879 if (!ElemType->isRecordType())
9880 return true;
9881
9882 // A partially-defined class type can't be a literal type, because a literal
9883 // class type must have a trivial destructor (which can't be checked until
9884 // the class definition is complete).
9885 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
9886 return true;
9887
9888 const auto *RD = ElemType->castAsCXXRecordDecl();
9889 // [expr.prim.lambda]p3:
9890 // This class type is [not] a literal type.
9891 if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
9892 Diag(RD->getLocation(), diag::note_non_literal_lambda);
9893 return true;
9894 }
9895
9896 // If the class has virtual base classes, then it's not an aggregate, and
9897 // cannot have any constexpr constructors or a trivial default constructor,
9898 // so is non-literal. This is better to diagnose than the resulting absence
9899 // of constexpr constructors.
9900 if (RD->getNumVBases()) {
9901 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
9902 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
9903 for (const auto &I : RD->vbases())
9904 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
9905 << I.getSourceRange();
9906 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
9907 !RD->hasTrivialDefaultConstructor()) {
9908 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
9909 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
9910 for (const auto &I : RD->bases()) {
9911 if (!I.getType()->isLiteralType(Context)) {
9912 Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
9913 << RD << I.getType() << I.getSourceRange();
9914 return true;
9915 }
9916 }
9917 for (const auto *I : RD->fields()) {
9918 if (!I->getType()->isLiteralType(Context) ||
9919 I->getType().isVolatileQualified()) {
9920 Diag(I->getLocation(), diag::note_non_literal_field)
9921 << RD << I << I->getType()
9922 << I->getType().isVolatileQualified();
9923 return true;
9924 }
9925 }
9926 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor()
9927 : !RD->hasTrivialDestructor()) {
9928 // All fields and bases are of literal types, so have trivial or constexpr
9929 // destructors. If this class's destructor is non-trivial / non-constexpr,
9930 // it must be user-declared.
9931 CXXDestructorDecl *Dtor = RD->getDestructor();
9932 assert(Dtor && "class has literal fields and bases but no dtor?");
9933 if (!Dtor)
9934 return true;
9935
9936 if (getLangOpts().CPlusPlus20) {
9937 Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor)
9938 << RD;
9939 } else {
9940 Diag(Dtor->getLocation(), Dtor->isUserProvided()
9941 ? diag::note_non_literal_user_provided_dtor
9942 : diag::note_non_literal_nontrivial_dtor)
9943 << RD;
9944 if (!Dtor->isUserProvided())
9947 /*Diagnose*/ true);
9948 }
9949 }
9950
9951 return true;
9952}
9953
9954bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
9955 BoundTypeDiagnoser<> Diagnoser(DiagID);
9956 return RequireLiteralType(Loc, T, Diagnoser);
9957}
9958
9960 assert(!E->hasPlaceholderType() && "unexpected placeholder");
9961
9962 if (!getLangOpts().CPlusPlus && E->refersToBitField())
9963 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
9964 << (Kind == TypeOfKind::Unqualified ? 3 : 2);
9965
9966 if (!E->isTypeDependent()) {
9967 QualType T = E->getType();
9968 if (const TagType *TT = T->getAs<TagType>())
9969 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
9970 }
9971 return Context.getTypeOfExprType(E, Kind);
9972}
9973
9974static void
9977 // Currently, 'counted_by' only allows direct DeclRefExpr to FieldDecl.
9978 auto *CountDecl = cast<DeclRefExpr>(E)->getDecl();
9979 Decls.push_back(TypeCoupledDeclRefInfo(CountDecl, /*IsDref*/ false));
9980}
9981
9983 Expr *CountExpr,
9984 bool CountInBytes,
9985 bool OrNull) {
9986 assert(WrappedTy->isIncompleteArrayType() || WrappedTy->isPointerType());
9987
9989 BuildTypeCoupledDecls(CountExpr, Decls);
9990 /// When the resulting expression is invalid, we still create the AST using
9991 /// the original count expression for the sake of AST dump.
9992 return Context.getCountAttributedType(WrappedTy, CountExpr, CountInBytes,
9993 OrNull, Decls);
9994}
9995
9996/// getDecltypeForExpr - Given an expr, will return the decltype for
9997/// that expression, according to the rules in C++11
9998/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
10000
10001 Expr *IDExpr = E;
10002 if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E))
10003 IDExpr = ImplCastExpr->getSubExpr();
10004
10005 if (auto *PackExpr = dyn_cast<PackIndexingExpr>(E)) {
10006 if (E->isInstantiationDependent())
10007 IDExpr = PackExpr->getPackIdExpression();
10008 else
10009 IDExpr = PackExpr->getSelectedExpr();
10010 }
10011
10012 if (E->isTypeDependent())
10013 return Context.DependentTy;
10014
10015 // C++11 [dcl.type.simple]p4:
10016 // The type denoted by decltype(e) is defined as follows:
10017
10018 // C++20:
10019 // - if E is an unparenthesized id-expression naming a non-type
10020 // template-parameter (13.2), decltype(E) is the type of the
10021 // template-parameter after performing any necessary type deduction
10022 // Note that this does not pick up the implicit 'const' for a template
10023 // parameter object. This rule makes no difference before C++20 so we apply
10024 // it unconditionally.
10025 if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr))
10026 IDExpr = SNTTPE->getReplacement();
10027
10028 // - if e is an unparenthesized id-expression or an unparenthesized class
10029 // member access (5.2.5), decltype(e) is the type of the entity named
10030 // by e. If there is no such entity, or if e names a set of overloaded
10031 // functions, the program is ill-formed;
10032 //
10033 // We apply the same rules for Objective-C ivar and property references.
10034 if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) {
10035 const ValueDecl *VD = DRE->getDecl();
10036 QualType T = VD->getType();
10037 return isa<TemplateParamObjectDecl>(VD) ? T.getUnqualifiedType() : T;
10038 }
10039 if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) {
10040 if (const auto *VD = ME->getMemberDecl())
10041 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
10042 return VD->getType();
10043 } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) {
10044 return IR->getDecl()->getType();
10045 } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) {
10046 if (PR->isExplicitProperty())
10047 return PR->getExplicitProperty()->getType();
10048 } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) {
10049 return PE->getType();
10050 }
10051
10052 // C++11 [expr.lambda.prim]p18:
10053 // Every occurrence of decltype((x)) where x is a possibly
10054 // parenthesized id-expression that names an entity of automatic
10055 // storage duration is treated as if x were transformed into an
10056 // access to a corresponding data member of the closure type that
10057 // would have been declared if x were an odr-use of the denoted
10058 // entity.
10059 if (getCurLambda() && isa<ParenExpr>(IDExpr)) {
10060 if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) {
10061 if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
10062 QualType T = getCapturedDeclRefType(Var, DRE->getLocation());
10063 if (!T.isNull())
10064 return Context.getLValueReferenceType(T);
10065 }
10066 }
10067 }
10068
10069 return Context.getReferenceQualifiedType(E);
10070}
10071
10072QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) {
10073 assert(!E->hasPlaceholderType() && "unexpected placeholder");
10074
10075 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
10076 !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) {
10077 // The expression operand for decltype is in an unevaluated expression
10078 // context, so side effects could result in unintended consequences.
10079 // Exclude instantiation-dependent expressions, because 'decltype' is often
10080 // used to build SFINAE gadgets.
10081 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
10082 }
10083 return Context.getDecltypeType(E, getDecltypeForExpr(E));
10084}
10085
10087 SourceLocation Loc,
10088 SourceLocation EllipsisLoc) {
10089 if (!IndexExpr)
10090 return QualType();
10091
10092 // Diagnose unexpanded packs but continue to improve recovery.
10093 if (!Pattern->containsUnexpandedParameterPack())
10094 Diag(Loc, diag::err_expected_name_of_pack) << Pattern;
10095
10096 QualType Type = BuildPackIndexingType(Pattern, IndexExpr, Loc, EllipsisLoc);
10097
10098 if (!Type.isNull())
10099 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::warn_cxx23_pack_indexing
10100 : diag::ext_pack_indexing);
10101 return Type;
10102}
10103
10105 SourceLocation Loc,
10106 SourceLocation EllipsisLoc,
10107 bool FullySubstituted,
10108 ArrayRef<QualType> Expansions) {
10109
10110 UnsignedOrNone Index = std::nullopt;
10111 if (!IndexExpr->isInstantiationDependent()) {
10112 llvm::APSInt Value;
10114 IndexExpr, Context.getSizeType(), Value, CCEKind::PackIndex);
10115
10116 if (!Res.isUsable() || !Value.isRepresentableByInt64())
10117 return QualType();
10118
10119 IndexExpr = Res.get();
10120 uint64_t V = Value.getZExtValue();
10121 if (FullySubstituted && V >= Expansions.size()) {
10122 Diag(IndexExpr->getBeginLoc(), diag::err_pack_index_out_of_bound)
10123 << V << Pattern << Expansions.size();
10124 return QualType();
10125 }
10126 Index = static_cast<unsigned>(V);
10127 }
10128
10129 return Context.getPackIndexingType(Pattern, IndexExpr, FullySubstituted,
10130 Expansions, Index);
10131}
10132
10134 SourceLocation Loc) {
10135 assert(BaseType->isEnumeralType());
10136 EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl();
10137
10138 S.DiagnoseUseOfDecl(ED, Loc);
10139
10140 QualType Underlying = ED->getIntegerType();
10141 if (Underlying.isNull()) {
10142 Underlying = ED->getDefinition()->getIntegerType();
10143 assert(!Underlying.isNull());
10144 }
10145
10146 return Underlying;
10147}
10148
10150 SourceLocation Loc) {
10151 if (!BaseType->isEnumeralType()) {
10152 Diag(Loc, diag::err_only_enums_have_underlying_types);
10153 return QualType();
10154 }
10155
10156 // The enum could be incomplete if we're parsing its definition or
10157 // recovering from an error.
10158 NamedDecl *FwdDecl = nullptr;
10159 if (BaseType->isIncompleteType(&FwdDecl)) {
10160 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
10161 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
10162 return QualType();
10163 }
10164
10165 return GetEnumUnderlyingType(*this, BaseType, Loc);
10166}
10167
10169 QualType Pointer = BaseType.isReferenceable() || BaseType->isVoidType()
10170 ? BuildPointerType(BaseType.getNonReferenceType(), Loc,
10172 : BaseType;
10173
10174 return Pointer.isNull() ? QualType() : Pointer;
10175}
10176
10178 if (!BaseType->isAnyPointerType())
10179 return BaseType;
10180
10181 return BaseType->getPointeeType();
10182}
10183
10185 QualType Underlying = BaseType.getNonReferenceType();
10186 if (Underlying->isArrayType())
10187 return Context.getDecayedType(Underlying);
10188
10189 if (Underlying->isFunctionType())
10190 return BuiltinAddPointer(BaseType, Loc);
10191
10192 SplitQualType Split = Underlying.getSplitUnqualifiedType();
10193 // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is
10194 // in the same group of qualifiers as 'const' and 'volatile', we're extending
10195 // '__decay(T)' so that it removes all qualifiers.
10196 Split.Quals.removeCVRQualifiers();
10197 return Context.getQualifiedType(Split);
10198}
10199
10201 SourceLocation Loc) {
10202 assert(LangOpts.CPlusPlus);
10204 BaseType.isReferenceable()
10205 ? BuildReferenceType(BaseType,
10206 UKind == UnaryTransformType::AddLvalueReference,
10207 Loc, DeclarationName())
10208 : BaseType;
10209 return Reference.isNull() ? QualType() : Reference;
10210}
10211
10213 SourceLocation Loc) {
10214 if (UKind == UnaryTransformType::RemoveAllExtents)
10215 return Context.getBaseElementType(BaseType);
10216
10217 if (const auto *AT = Context.getAsArrayType(BaseType))
10218 return AT->getElementType();
10219
10220 return BaseType;
10221}
10222
10224 SourceLocation Loc) {
10225 assert(LangOpts.CPlusPlus);
10226 QualType T = BaseType.getNonReferenceType();
10227 if (UKind == UTTKind::RemoveCVRef &&
10228 (T.isConstQualified() || T.isVolatileQualified())) {
10229 Qualifiers Quals;
10230 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
10231 Quals.removeConst();
10232 Quals.removeVolatile();
10233 T = Context.getQualifiedType(Unqual, Quals);
10234 }
10235 return T;
10236}
10237
10239 SourceLocation Loc) {
10240 if ((BaseType->isReferenceType() && UKind != UTTKind::RemoveRestrict) ||
10241 BaseType->isFunctionType())
10242 return BaseType;
10243
10244 Qualifiers Quals;
10245 QualType Unqual = Context.getUnqualifiedArrayType(BaseType, Quals);
10246
10247 if (UKind == UTTKind::RemoveConst || UKind == UTTKind::RemoveCV)
10248 Quals.removeConst();
10249 if (UKind == UTTKind::RemoveVolatile || UKind == UTTKind::RemoveCV)
10250 Quals.removeVolatile();
10251 if (UKind == UTTKind::RemoveRestrict)
10252 Quals.removeRestrict();
10253
10254 return Context.getQualifiedType(Unqual, Quals);
10255}
10256
10258 bool IsMakeSigned,
10259 SourceLocation Loc) {
10260 if (BaseType->isEnumeralType()) {
10261 QualType Underlying = GetEnumUnderlyingType(S, BaseType, Loc);
10262 if (auto *BitInt = dyn_cast<BitIntType>(Underlying)) {
10263 unsigned int Bits = BitInt->getNumBits();
10264 if (Bits > 1)
10265 return S.Context.getBitIntType(!IsMakeSigned, Bits);
10266
10267 S.Diag(Loc, diag::err_make_signed_integral_only)
10268 << IsMakeSigned << /*_BitInt(1)*/ true << BaseType << 1 << Underlying;
10269 return QualType();
10270 }
10271 if (Underlying->isBooleanType()) {
10272 S.Diag(Loc, diag::err_make_signed_integral_only)
10273 << IsMakeSigned << /*_BitInt(1)*/ false << BaseType << 1
10274 << Underlying;
10275 return QualType();
10276 }
10277 }
10278
10279 bool Int128Unsupported = !S.Context.getTargetInfo().hasInt128Type();
10280 std::array<CanQualType *, 6> AllSignedIntegers = {
10283 ArrayRef<CanQualType *> AvailableSignedIntegers(
10284 AllSignedIntegers.data(), AllSignedIntegers.size() - Int128Unsupported);
10285 std::array<CanQualType *, 6> AllUnsignedIntegers = {
10289 ArrayRef<CanQualType *> AvailableUnsignedIntegers(AllUnsignedIntegers.data(),
10290 AllUnsignedIntegers.size() -
10291 Int128Unsupported);
10292 ArrayRef<CanQualType *> *Consider =
10293 IsMakeSigned ? &AvailableSignedIntegers : &AvailableUnsignedIntegers;
10294
10295 uint64_t BaseSize = S.Context.getTypeSize(BaseType);
10296 auto *Result =
10297 llvm::find_if(*Consider, [&S, BaseSize](const CanQual<Type> *T) {
10298 return BaseSize == S.Context.getTypeSize(T->getTypePtr());
10299 });
10300
10301 assert(Result != Consider->end());
10302 return QualType((*Result)->getTypePtr(), 0);
10303}
10304
10306 SourceLocation Loc) {
10307 bool IsMakeSigned = UKind == UnaryTransformType::MakeSigned;
10308 if ((!BaseType->isIntegerType() && !BaseType->isEnumeralType()) ||
10309 BaseType->isBooleanType() ||
10310 (BaseType->isBitIntType() &&
10311 BaseType->getAs<BitIntType>()->getNumBits() < 2)) {
10312 Diag(Loc, diag::err_make_signed_integral_only)
10313 << IsMakeSigned << BaseType->isBitIntType() << BaseType << 0;
10314 return QualType();
10315 }
10316
10317 bool IsNonIntIntegral =
10318 BaseType->isChar16Type() || BaseType->isChar32Type() ||
10319 BaseType->isWideCharType() || BaseType->isEnumeralType();
10320
10321 QualType Underlying =
10322 IsNonIntIntegral
10323 ? ChangeIntegralSignedness(*this, BaseType, IsMakeSigned, Loc)
10324 : IsMakeSigned ? Context.getCorrespondingSignedType(BaseType)
10325 : Context.getCorrespondingUnsignedType(BaseType);
10326 if (Underlying.isNull())
10327 return Underlying;
10328 return Context.getQualifiedType(Underlying, BaseType.getQualifiers());
10329}
10330
10332 SourceLocation Loc) {
10333 if (BaseType->isDependentType())
10334 return Context.getUnaryTransformType(BaseType, BaseType, UKind);
10336 switch (UKind) {
10337 case UnaryTransformType::EnumUnderlyingType: {
10338 Result = BuiltinEnumUnderlyingType(BaseType, Loc);
10339 break;
10340 }
10341 case UnaryTransformType::AddPointer: {
10342 Result = BuiltinAddPointer(BaseType, Loc);
10343 break;
10344 }
10345 case UnaryTransformType::RemovePointer: {
10346 Result = BuiltinRemovePointer(BaseType, Loc);
10347 break;
10348 }
10349 case UnaryTransformType::Decay: {
10350 Result = BuiltinDecay(BaseType, Loc);
10351 break;
10352 }
10353 case UnaryTransformType::AddLvalueReference:
10354 case UnaryTransformType::AddRvalueReference: {
10355 Result = BuiltinAddReference(BaseType, UKind, Loc);
10356 break;
10357 }
10358 case UnaryTransformType::RemoveAllExtents:
10359 case UnaryTransformType::RemoveExtent: {
10360 Result = BuiltinRemoveExtent(BaseType, UKind, Loc);
10361 break;
10362 }
10363 case UnaryTransformType::RemoveCVRef:
10364 case UnaryTransformType::RemoveReference: {
10365 Result = BuiltinRemoveReference(BaseType, UKind, Loc);
10366 break;
10367 }
10368 case UnaryTransformType::RemoveConst:
10369 case UnaryTransformType::RemoveCV:
10370 case UnaryTransformType::RemoveRestrict:
10371 case UnaryTransformType::RemoveVolatile: {
10372 Result = BuiltinChangeCVRQualifiers(BaseType, UKind, Loc);
10373 break;
10374 }
10375 case UnaryTransformType::MakeSigned:
10376 case UnaryTransformType::MakeUnsigned: {
10377 Result = BuiltinChangeSignedness(BaseType, UKind, Loc);
10378 break;
10379 }
10380 }
10381
10382 return !Result.isNull()
10383 ? Context.getUnaryTransformType(BaseType, Result, UKind)
10384 : Result;
10385}
10386
10388 if (!T->isDependentType() && !isa<AutoType>(T)) {
10389 // FIXME: It isn't entirely clear whether incomplete atomic types
10390 // are allowed or not; for simplicity, ban them for the moment.
10391 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
10392 return QualType();
10393
10394 int DisallowedKind = -1;
10395 if (T->isArrayType())
10396 DisallowedKind = 1;
10397 else if (T->isFunctionType())
10398 DisallowedKind = 2;
10399 else if (T->isReferenceType())
10400 DisallowedKind = 3;
10401 else if (T->isAtomicType())
10402 DisallowedKind = 4;
10403 else if (T.hasQualifiers())
10404 DisallowedKind = 5;
10405 else if (T->isSizelessType())
10406 DisallowedKind = 6;
10407 else if (!T.isTriviallyCopyableType(Context) && getLangOpts().CPlusPlus)
10408 // Some other non-trivially-copyable type (probably a C++ class)
10409 DisallowedKind = 7;
10410 else if (T->isBitIntType())
10411 DisallowedKind = 8;
10412 else if (getLangOpts().C23 && T->isUndeducedAutoType())
10413 // _Atomic auto is prohibited in C23
10414 DisallowedKind = 9;
10415
10416 if (DisallowedKind != -1) {
10417 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
10418 return QualType();
10419 }
10420
10421 // FIXME: Do we need any handling for ARC here?
10422 }
10423
10424 // Build the pointer type.
10425 return Context.getAtomicType(T);
10426}
Defines the clang::ASTContext interface.
#define V(N, I)
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
Result
Implement __builtin_bit_cast and related operations.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
static StringRef getTriple(const Command &Job)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
llvm::json::Array Array
Defines the clang::Preprocessor interface.
static QualType getUnderlyingType(const SubRegion *R)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis for CUDA constructs.
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis for OpenMP constructs and clauses.
static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S, VectorKind VecKind)
HandleNeonVectorTypeAttr - The "neon_vector_type" and "neon_polyvector_type" attributes are used to c...
static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType)
static bool isPermittedNeonBaseType(QualType &Ty, VectorKind VecKind, Sema &S)
static void distributeObjCPointerTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType type)
Given that an objc_gc attribute was written somewhere on a declaration other than on the declarator i...
Definition SemaType.cpp:506
static void maybeSynthesizeBlockSignature(TypeProcessingState &state, QualType declSpecType)
Add a synthetic '()' to a block-literal declarator if it is required, given the return type.
Definition SemaType.cpp:764
#define MS_TYPE_ATTRS_CASELIST
Definition SemaType.cpp:172
#define CALLING_CONV_ATTRS_CASELIST
Definition SemaType.cpp:125
static void emitNullabilityConsistencyWarning(Sema &S, SimplePointerKind PointerKind, SourceLocation PointerLoc, SourceLocation PointerEndLoc)
static void fixItNullability(Sema &S, DiagBuilderT &Diag, SourceLocation PointerLoc, NullabilityKind Nullability)
Creates a fix-it to insert a C-style nullability keyword at pointerLoc, taking into account whitespac...
static ExprResult checkArraySize(Sema &S, Expr *&ArraySize, llvm::APSInt &SizeVal, unsigned VLADiag, bool VLAIsError)
Check whether the specified array bound can be evaluated using the relevant language rules.
static Attr * createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr, NullabilityKind NK)
static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S)
HandleVectorSizeAttribute - this attribute is only applicable to integral and float scalars,...
static void inferARCWriteback(TypeProcessingState &state, QualType &declSpecType)
Given that this is the declaration of a parameter under ARC, attempt to infer attributes and such for...
static TypeSourceInfo * GetTypeSourceInfoForDeclarator(TypeProcessingState &State, QualType T, TypeSourceInfo *ReturnTypeInfo)
Create and instantiate a TypeSourceInfo with type source information.
static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx, const Expr *AddrSpace, SourceLocation AttrLoc)
Build an AddressSpace index from a constant expression and diagnose any errors related to invalid add...
static void HandleBTFTypeTagAttribute(QualType &Type, const ParsedAttr &Attr, TypeProcessingState &State)
static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state, Qualifiers::ObjCLifetime ownership, unsigned chunkIndex)
static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
handleObjCGCTypeAttr - Process the attribute((objc_gc)) type attribute on the specified type.
static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk)
static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S)
Process the OpenCL-like ext_vector_type attribute when it occurs on a type.
static void HandleHLSLParamModifierAttr(TypeProcessingState &State, QualType &CurType, const ParsedAttr &Attr, Sema &S)
static void HandleLifetimeBoundAttr(TypeProcessingState &State, QualType &CurType, ParsedAttr &Attr)
static bool handleArmStateAttribute(Sema &S, FunctionProtoType::ExtProtoInfo &EPI, ParsedAttr &Attr, FunctionType::ArmStateValue State)
static bool handleArmAgnosticAttribute(Sema &S, FunctionProtoType::ExtProtoInfo &EPI, ParsedAttr &Attr)
static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType, CUDAFunctionTarget CFT)
A function type attribute was written in the decl spec.
Definition SemaType.cpp:674
static bool handleObjCPointerTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
Definition SemaType.cpp:421
static QualType inferARCLifetimeForPointee(Sema &S, QualType type, SourceLocation loc, bool isReference)
Given that we're building a pointer or reference to the given.
static bool handleNonBlockingNonAllocatingTypeAttr(TypeProcessingState &TPState, ParsedAttr &PAttr, QualType &QT, FunctionTypeUnwrapper &Unwrapped)
static QualType ChangeIntegralSignedness(Sema &S, QualType BaseType, bool IsMakeSigned, SourceLocation Loc)
static bool CheckNullabilityTypeSpecifier(Sema &S, TypeProcessingState *State, ParsedAttr *PAttr, QualType &QT, NullabilityKind Nullability, SourceLocation NullabilityLoc, bool IsContextSensitive, bool AllowOnArrayType, bool OverrideExisting)
#define OBJC_POINTER_TYPE_ATTRS_CASELIST
Definition SemaType.cpp:120
static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr, QualType type)
diagnoseBadTypeAttribute - Diagnoses a type attribute which doesn't apply to the given type.
Definition SemaType.cpp:80
static PointerDeclaratorKind classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator, PointerWrappingDeclaratorKind &wrappingKind)
Classify the given declarator, whose type-specified is type, based on what kind of pointer it refers ...
static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr, llvm::APSInt &Result)
static void HandleSwiftAttr(TypeProcessingState &State, TypeAttrLocation TAL, QualType &QT, ParsedAttr &PAttr)
static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
static bool shouldHaveNullability(QualType T)
static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State, QualType &CurType, ParsedAttr &Attr)
static void warnAboutAmbiguousFunction(Sema &S, Declarator &D, DeclaratorChunk &DeclType, QualType RT)
Produce an appropriate diagnostic for an ambiguity between a function declarator and a C++ direct-ini...
static void distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType)
Distribute an objc_gc type attribute that was written on the declarator.
Definition SemaType.cpp:562
static FileID getNullabilityCompletenessCheckFileID(Sema &S, SourceLocation loc)
static void HandleOverflowBehaviorAttr(QualType &Type, const ParsedAttr &Attr, TypeProcessingState &State)
static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr, Sema &S)
HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is used to create fixed-length v...
#define FUNCTION_TYPE_ATTRS_CASELIST
Definition SemaType.cpp:149
static void HandleLifetimeCaptureByAttr(TypeProcessingState &State, QualType &CurType, ParsedAttr &PA)
static bool distributeNullabilityTypeAttr(TypeProcessingState &state, QualType type, ParsedAttr &attr)
Distribute a nullability type attribute that cannot be applied to the type specifier to a pointer,...
static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state, QualType &declSpecType, CUDAFunctionTarget CFT)
Given that there are attributes written on the declarator or declaration itself, try to distribute an...
Definition SemaType.cpp:723
static void fillHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL, TypeProcessingState &State)
static void distributeFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType type)
A function type attribute was written somewhere in a declaration other than on the declarator itself ...
Definition SemaType.cpp:623
static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S)
HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type.
static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State, QualType &QT, ParsedAttr &PAttr)
static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex)
Returns true if any of the declarator chunks before endIndex include a level of indirection: array,...
static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr, Sema &S)
Handle OpenCL Access Qualifier Attribute.
static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind)
Map a nullability attribute kind to a nullability kind.
static bool distributeFunctionTypeAttrToInnermost(TypeProcessingState &state, ParsedAttr &attr, ParsedAttributesView &attrList, QualType &declSpecType, CUDAFunctionTarget CFT)
Try to distribute a function type attribute to the innermost function chunk or type.
Definition SemaType.cpp:654
#define NULLABILITY_TYPE_ATTRS_CASELIST
Definition SemaType.cpp:179
static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state, TypeSourceInfo *&ReturnTypeInfo)
static void checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind, SourceLocation pointerLoc, SourceLocation pointerEndLoc=SourceLocation())
Complains about missing nullability if the file containing pointerLoc has other uses of nullability (...
static void transferARCOwnership(TypeProcessingState &state, QualType &declSpecTy, Qualifiers::ObjCLifetime ownership)
Used for transferring ownership in casts resulting in l-values.
static std::string getPrintableNameForEntity(DeclarationName Entity)
static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy)
static QualType rebuildAttributedTypeWithoutNullability(ASTContext &Ctx, QualType Type)
Rebuild an attributed type without the nullability attribute on it.
static DeclaratorChunk * maybeMovePastReturnType(Declarator &declarator, unsigned i, bool onlyBlockPointers)
Given the index of a declarator chunk, check whether that chunk directly specifies the return type of...
Definition SemaType.cpp:438
static OpenCLAccessAttr::Spelling getImageAccess(const ParsedAttributesView &Attrs)
Definition SemaType.cpp:878
static void fillMatrixTypeLoc(MatrixTypeLoc MTL, const ParsedAttributesView &Attrs)
static UnaryTransformType::UTTKind TSTToUnaryTransformType(DeclSpec::TST SwitchTST)
Definition SemaType.cpp:886
static void HandleRISCVRVVVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr, Sema &S)
HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is used to create fixed-leng...
static void HandleAddressSpaceTypeAttribute(QualType &Type, const ParsedAttr &Attr, TypeProcessingState &State)
HandleAddressSpaceTypeAttribute - Process an address_space attribute on the specified type.
static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc, QualifiedFunctionKind QFK)
Check whether the type T is a qualified function type, and if it is, diagnose that it cannot be conta...
static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator, QualType Result)
Return true if this is omitted block return type.
Definition SemaType.cpp:848
static void HandlePtrAuthQualifier(ASTContext &Ctx, QualType &T, const ParsedAttr &Attr, Sema &S)
Handle the __ptrauth qualifier.
static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld, LangAS ASNew, SourceLocation AttrLoc)
static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T)
Produce an appropriate diagnostic for a declarator with top-level parentheses.
static QualType ConvertDeclSpecToType(TypeProcessingState &state)
Convert the specified declspec to the appropriate type object.
Definition SemaType.cpp:903
static std::pair< QualType, TypeSourceInfo * > InventTemplateParameter(TypeProcessingState &state, QualType T, TypeSourceInfo *TrailingTSI, AutoType *Auto, InventedTemplateParameterInfo &Info)
static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType, CUDAFunctionTarget CFT)
A function type attribute was written on the declarator or declaration.
Definition SemaType.cpp:694
static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS, unsigned &TypeQuals, QualType TypeSoFar, unsigned RemoveTQs, unsigned DiagID)
Definition SemaType.cpp:820
static CallingConv getCCForDeclaratorChunk(Sema &S, Declarator &D, const ParsedAttributesView &AttrList, const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex)
Helper for figuring out the default CC for a function declarator type.
static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for literal type diagnostic message.
static void recordNullabilitySeen(Sema &S, SourceLocation loc)
Marks that a nullability feature has been used in the file containing loc.
static bool CheckBitIntElementType(Sema &S, SourceLocation AttrLoc, const BitIntType *BIT, bool ForMatrixType=false)
static void checkExtParameterInfos(Sema &S, ArrayRef< QualType > paramTypes, const FunctionProtoType::ExtProtoInfo &EPI, llvm::function_ref< SourceLocation(unsigned)> getParamLoc)
Check the extended parameter information.
static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type, CUDAFunctionTarget CFT)
Process an individual function attribute.
static void transferARCOwnershipToDeclSpec(Sema &S, QualType &declSpecTy, Qualifiers::ObjCLifetime ownership)
static void BuildTypeCoupledDecls(Expr *E, llvm::SmallVectorImpl< TypeCoupledDeclRefInfo > &Decls)
static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD)
Locks in the inheritance model for the given class and all of its bases.
static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type, ParsedAttr &attr)
Check the application of the Objective-C '__kindof' qualifier to the given type.
static bool hasNullabilityAttr(const ParsedAttributesView &attrs)
Check whether there is a nullability attribute of any kind in the given attribute list.
static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
handleObjCOwnershipTypeAttr - Process an objc_ownership attribute on the specified type.
static void moveAttrFromListToList(ParsedAttr &attr, ParsedAttributesView &fromList, ParsedAttributesView &toList)
Definition SemaType.cpp:387
static void HandleAnnotateTypeAttr(TypeProcessingState &State, QualType &CurType, const ParsedAttr &PA)
static void fillAttributedTypeLoc(AttributedTypeLoc TL, TypeProcessingState &State)
static void fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL, const ParsedAttributesView &Attrs)
TypeAttrLocation
The location of a type attribute.
Definition SemaType.cpp:395
@ TAL_DeclChunk
The attribute is part of a DeclaratorChunk.
Definition SemaType.cpp:399
@ TAL_DeclSpec
The attribute is in the decl-specifier-seq.
Definition SemaType.cpp:397
@ TAL_DeclName
The attribute is immediately after the declaration's name.
Definition SemaType.cpp:401
static bool isOmittedBlockReturnType(const Declarator &D)
isOmittedBlockReturnType - Return true if this declarator is missing a return type because this is a ...
Definition SemaType.cpp:63
static TypeSourceInfo * GetFullTypeForDeclarator(TypeProcessingState &state, QualType declSpecType, TypeSourceInfo *TInfo)
TypeDiagSelector
Definition SemaType.cpp:55
@ TDS_ObjCObjOrBlock
Definition SemaType.cpp:58
@ TDS_Function
Definition SemaType.cpp:56
@ TDS_Pointer
Definition SemaType.cpp:57
static QualType GetEnumUnderlyingType(Sema &S, QualType BaseType, SourceLocation Loc)
static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk)
static AttrT * createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL)
static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, Declarator &D, unsigned FunctionChunkIndex)
static void processTypeAttrs(TypeProcessingState &state, QualType &type, TypeAttrLocation TAL, const ParsedAttributesView &attrs, CUDAFunctionTarget CFT=CUDAFunctionTarget::HostDevice)
static bool checkMutualExclusion(TypeProcessingState &state, const FunctionProtoType::ExtProtoInfo &EPI, ParsedAttr &Attr, AttributeCommonInfo::Kind OtherKind)
static Attr * getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr)
Defines the clang::SourceLocation class and associated facilities.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
__DEVICE__ int max(int __a, int __b)
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
TranslationUnitDecl * getTranslationUnitDecl() const
CanQualType LongTy
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
CanQualType Int128Ty
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:805
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
QualType getFunctionTypeWithExceptionSpec(QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const
Get a function type and produce the equivalent function type with the specified exception specificati...
QualType getAutoType(DeducedKind DK, QualType DeducedAsType, AutoTypeKeyword Keyword, TemplateDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
CanQualType BoolTy
CanQualType UnsignedLongTy
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CanQualType IntTy
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
LangAS getDefaultOpenCLPointeeAddrSpace()
Returns default address space based on OpenCL version and enabled features.
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
TypedefDecl * getBuiltinVaListDecl() const
Retrieve the C type declaration corresponding to the predefined __builtin_va_list type.
CanQualType VoidTy
CanQualType UnsignedCharTy
CanQualType UnsignedIntTy
TypeSourceInfo * CreateTypeSourceInfo(QualType T, unsigned Size=0) const
Allocate an uninitialized TypeSourceInfo.
CanQualType UnsignedLongLongTy
CanQualType UnsignedShortTy
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
CanQualType ShortTy
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
DiagnosticsEngine & getDiagnostics() const
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:924
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const
Return the uniqued reference to the type for an Objective-C gc-qualified type.
QualType getPointerAuthType(QualType Ty, PointerAuthQualifier PointerAuth)
Return a type with the given __ptrauth qualifier.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
QualType getBitIntType(bool Unsigned, unsigned NumBits) const
Return a bit-precise integer type with the specified signedness and bit count.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
void setLBracketLoc(SourceLocation Loc)
Definition TypeLoc.h:1783
void setRBracketLoc(SourceLocation Loc)
Definition TypeLoc.h:1791
void setSizeExpr(Expr *Size)
Definition TypeLoc.h:1803
TypeLoc getValueLoc() const
Definition TypeLoc.h:2661
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2673
void setParensRange(SourceRange Range)
Definition TypeLoc.h:2697
Attr - This represents one attribute.
Definition Attr.h:46
attr::Kind getKind() const
Definition Attr.h:92
const char * getSpelling() const
void setImplicit(bool I)
Definition Attr.h:106
Combines information about the source-code form of an attribute, including its syntax and spelling.
bool isContextSensitiveKeywordAttribute() const
SourceLocation getLoc() const
const IdentifierInfo * getAttrName() const
ParsedAttr * create(IdentifierInfo *attrName, SourceRange attrRange, AttributeScopeInfo scope, ArgsUnion *args, unsigned numArgs, ParsedAttr::Form form, SourceLocation ellipsisLoc=SourceLocation())
Definition ParsedAttr.h:735
Type source information for an attributed type.
Definition TypeLoc.h:1008
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1022
void setAttr(const Attr *A)
Definition TypeLoc.h:1034
bool hasExplicitTemplateArgs() const
Definition TypeLoc.h:2445
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition TypeLoc.h:2411
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:2461
SourceLocation getLAngleLoc() const
Definition TypeLoc.h:2454
void setConceptReference(ConceptReference *CR)
Definition TypeLoc.h:2405
NamedDecl * getFoundDecl() const
Definition TypeLoc.h:2429
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition TypeLoc.h:2472
unsigned getNumArgs() const
Definition TypeLoc.h:2468
TemplateDecl * getNamedConcept() const
Definition TypeLoc.h:2435
DeclarationNameInfo getConceptNameInfo() const
Definition TypeLoc.h:2441
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2399
TypeLoc getWrappedLoc() const
Definition TypeLoc.h:1060
Comparison function object.
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8299
unsigned getNumBits() const
Definition TypeBase.h:8311
void setCaretLoc(SourceLocation Loc)
Definition TypeLoc.h:1532
Pointer to a block type.
Definition TypeBase.h:3606
TypeSpecifierWidth getWrittenWidthSpec() const
Definition TypeLoc.h:641
bool needsExtraLocalData() const
Definition TypeLoc.h:606
void setBuiltinLoc(SourceLocation Loc)
Definition TypeLoc.h:583
WrittenBuiltinSpecs & getWrittenBuiltinSpecs()
Definition TypeLoc.h:599
TypeSpecifierSign getWrittenSignSpec() const
Definition TypeLoc.h:625
void expandBuiltinRange(SourceRange Range)
Definition TypeLoc.h:587
This class is used for builtin types like 'int'.
Definition TypeBase.h:3228
Kind getKind() const
Definition TypeBase.h:3276
Represents a C++ destructor within a class.
Definition DeclCXX.h:2898
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CXXRecordDecl * getMostRecentDecl()
Definition DeclCXX.h:539
bool hasUserProvidedDefaultConstructor() const
Whether this class has a user-provided default constructor per C++11.
Definition DeclCXX.h:787
bool hasDefinition() const
Definition DeclCXX.h:561
MSInheritanceModel calculateInheritanceModel() const
Calculate what the inheritance model would be for this class.
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1191
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:188
SourceRange getRange() const
Definition DeclSpec.h:82
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:186
Represents a canonical, potentially-qualified type.
SourceLocation getBegin() const
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
TypeLoc getNextTypeLoc() const
Definition TypeLoc.h:429
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition Type.cpp:251
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition Type.cpp:291
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool isRecord() const
Definition DeclBase.h:2206
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition DeclBase.h:2705
bool isFunctionOrMethod() const
Definition DeclBase.h:2178
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
const WrittenBuiltinSpecs & getWrittenBuiltinSpecs() const
Definition DeclSpec.h:896
bool isTypeSpecPipe() const
Definition DeclSpec.h:528
static const TST TST_typeof_unqualType
Definition DeclSpec.h:282
SourceLocation getTypeSpecSignLoc() const
Definition DeclSpec.h:566
bool hasAutoTypeSpec() const
Definition DeclSpec.h:580
static const TST TST_typename
Definition DeclSpec.h:279
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:561
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition DeclSpec.h:698
static const TST TST_char8
Definition DeclSpec.h:255
static const TST TST_BFloat16
Definition DeclSpec.h:262
Expr * getPackIndexingExpr() const
Definition DeclSpec.h:545
TST getTypeSpecType() const
Definition DeclSpec.h:522
SCS getStorageClassSpec() const
Definition DeclSpec.h:486
SourceLocation getOverflowBehaviorLoc() const
Definition DeclSpec.h:624
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:560
bool isTypeSpecSat() const
Definition DeclSpec.h:529
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:559
static const TST TST_auto_type
Definition DeclSpec.h:292
static const TST TST_interface
Definition DeclSpec.h:277
static const TST TST_double
Definition DeclSpec.h:264
static const TST TST_typeofExpr
Definition DeclSpec.h:281
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:602
TemplateIdAnnotation * getRepAsTemplateId() const
Definition DeclSpec.h:551
static const TST TST_union
Definition DeclSpec.h:275
static const TST TST_typename_pack_indexing
Definition DeclSpec.h:286
static const TST TST_char
Definition DeclSpec.h:253
static const TST TST_bool
Definition DeclSpec.h:270
static const TST TST_char16
Definition DeclSpec.h:256
static const TST TST_unknown_anytype
Definition DeclSpec.h:293
TSC getTypeSpecComplex() const
Definition DeclSpec.h:518
static const TST TST_int
Definition DeclSpec.h:258
ParsedType getRepAsType() const
Definition DeclSpec.h:532
static const TST TST_accum
Definition DeclSpec.h:266
static const TST TST_half
Definition DeclSpec.h:261
ParsedAttributes & getAttributes()
Definition DeclSpec.h:880
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:609
bool isTypeAltiVecPixel() const
Definition DeclSpec.h:524
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition DeclSpec.h:631
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:603
static const TST TST_ibm128
Definition DeclSpec.h:269
Expr * getRepAsExpr() const
Definition DeclSpec.h:540
static const TST TST_enum
Definition DeclSpec.h:274
AttributePool & getAttributePool() const
Definition DeclSpec.h:853
bool isWrapSpecified() const
Definition DeclSpec.h:615
static const TST TST_float128
Definition DeclSpec.h:268
static const TST TST_decltype
Definition DeclSpec.h:284
SourceRange getTypeSpecWidthRange() const
Definition DeclSpec.h:564
SourceLocation getTypeSpecTypeNameLoc() const
Definition DeclSpec.h:571
SourceLocation getTypeSpecWidthLoc() const
Definition DeclSpec.h:563
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:604
static const TST TST_typeof_unqualExpr
Definition DeclSpec.h:283
static const TST TST_class
Definition DeclSpec.h:278
TypeSpecifierType TST
Definition DeclSpec.h:250
bool isOverflowBehaviorSpecified() const
Definition DeclSpec.h:621
bool hasTagDefinition() const
Definition DeclSpec.cpp:433
static const TST TST_decimal64
Definition DeclSpec.h:272
unsigned getParsedSpecifiers() const
Return a bitmask of which flavors of specifiers this DeclSpec includes.
Definition DeclSpec.cpp:442
bool isTypeAltiVecBool() const
Definition DeclSpec.h:525
bool isConstrainedAuto() const
Definition DeclSpec.h:530
static const TST TST_wchar
Definition DeclSpec.h:254
SourceLocation getTypeSpecComplexLoc() const
Definition DeclSpec.h:565
static const TST TST_void
Definition DeclSpec.h:252
bool isTypeAltiVecVector() const
Definition DeclSpec.h:523
static const TST TST_bitint
Definition DeclSpec.h:260
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition DeclSpec.cpp:532
static const TST TST_float
Definition DeclSpec.h:263
static const TST TST_atomic
Definition DeclSpec.h:294
bool isTrapSpecified() const
Definition DeclSpec.h:618
static const TST TST_fract
Definition DeclSpec.h:267
Decl * getRepAsDecl() const
Definition DeclSpec.h:536
static const TST TST_float16
Definition DeclSpec.h:265
static bool isTransformTypeTrait(TST T)
Definition DeclSpec.h:458
static const TST TST_unspecified
Definition DeclSpec.h:251
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:606
TypeSpecifierSign getTypeSpecSign() const
Definition DeclSpec.h:519
CXXScopeSpec & getTypeSpecScope()
Definition DeclSpec.h:556
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:567
OverflowBehaviorState getOverflowBehaviorState() const
Definition DeclSpec.h:612
static const TST TST_decltype_auto
Definition DeclSpec.h:285
static const TST TST_error
Definition DeclSpec.h:301
void forEachQualifier(llvm::function_ref< void(TQ, StringRef, SourceLocation)> Handle)
This method calls the passed in handler on each qual being set.
Definition DeclSpec.cpp:427
static const TST TST_decimal32
Definition DeclSpec.h:271
TypeSpecifierWidth getTypeSpecWidth() const
Definition DeclSpec.h:515
static const TST TST_char32
Definition DeclSpec.h:257
static const TST TST_decimal128
Definition DeclSpec.h:273
bool isTypeSpecOwned() const
Definition DeclSpec.h:526
SourceLocation getTypeSpecSatLoc() const
Definition DeclSpec.h:569
SourceRange getTypeofParensRange() const
Definition DeclSpec.h:577
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:607
static const TST TST_int128
Definition DeclSpec.h:259
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:605
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:828
static const TST TST_typeofType
Definition DeclSpec.h:280
static const TST TST_auto
Definition DeclSpec.h:291
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:839
static const TST TST_struct
Definition DeclSpec.h:276
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
void addAttr(Attr *A)
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:854
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
void setImplicit(bool I=true)
Definition DeclBase.h:602
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1066
bool hasAttr() const
Definition DeclBase.h:585
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:435
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition DeclBase.h:882
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
NameKind getNameKind() const
Determine what kind of name this is.
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1952
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2508
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2450
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2099
const DeclaratorChunk * getInnermostNonParenChunk() const
Return the innermost (closest to the declarator) chunk of this declarator that is not a parens chunk,...
Definition DeclSpec.h:2476
void AddInnermostTypeInfo(const DeclaratorChunk &TI)
Add a new innermost chunk to this declarator.
Definition DeclSpec.h:2441
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition DeclSpec.h:2562
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2793
const ParsedAttributes & getAttributes() const
Definition DeclSpec.h:2735
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2388
bool hasTrailingReturnType() const
Determine whether a trailing return type was written (at any level) within this declarator.
Definition DeclSpec.h:2660
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2136
bool isExpressionContext() const
Determine whether this declaration appears in a context where an expression could appear.
Definition DeclSpec.h:2604
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition DeclSpec.h:2463
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2765
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2446
const ParsedAttributesView & getDeclarationAttributes() const
Definition DeclSpec.h:2738
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2778
DeclaratorContext getContext() const
Definition DeclSpec.h:2124
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2135
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2118
bool isFirstDeclarator() const
Definition DeclSpec.h:2773
SourceLocation getCommaLoc() const
Definition DeclSpec.h:2774
AttributePool & getAttributePool() const
Definition DeclSpec.h:2108
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2114
bool hasEllipsis() const
Definition DeclSpec.h:2777
ParsedType getTrailingReturnType() const
Get the trailing return type appearing (at any level) within this declarator.
Definition DeclSpec.h:2669
bool isInvalidType() const
Definition DeclSpec.h:2766
bool isExplicitObjectMemberFunction()
Definition DeclSpec.cpp:398
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2134
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition DeclSpec.h:2801
bool isPrototypeContext() const
Definition DeclSpec.h:2126
bool isStaticMember()
Returns true if this declares a static member.
Definition DeclSpec.cpp:389
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2106
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2539
void setEllipsisLoc(SourceLocation EL)
Definition DeclSpec.h:2779
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2382
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2291
void setDecltypeLoc(SourceLocation Loc)
Definition TypeLoc.h:2288
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:1977
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:1998
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4125
void copy(DependentNameTypeLoc Loc)
Definition TypeLoc.h:2612
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2096
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2068
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:961
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:730
Wrap a function effect's condition expression in another struct so that FunctionProtoType's TrailingO...
Definition TypeBase.h:5091
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation NameLoc)
Definition TypeLoc.h:744
Represents an enum.
Definition Decl.h:4030
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4203
EnumDecl * getDefinition() const
Definition Decl.h:4142
This represents one expression.
Definition Expr.h:112
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition Expr.cpp:3099
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3095
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
bool isPRValue() const
Definition Expr.h:285
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3697
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:526
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isInvalid() const
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:81
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:142
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:131
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:105
A SourceLocation and its associated SourceManager.
unsigned getSpellingLineNumber(bool *Invalid=nullptr) const
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5307
bool insert(const FunctionEffectWithCondition &NewEC, Conflicts &Errs)
Definition Type.cpp:5809
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5339
Represents an abstract function effect, using just an enumeration describing its kind.
Definition TypeBase.h:4984
Kind
Identifies the particular effect.
Definition TypeBase.h:4987
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5171
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5371
Qualifiers getMethodQuals() const
Definition TypeBase.h:5797
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5775
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5660
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5656
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition TypeBase.h:5805
unsigned getNumParams() const
Definition TypeLoc.h:1716
void setLocalRangeBegin(SourceLocation L)
Definition TypeLoc.h:1664
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1680
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1723
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1688
void setLocalRangeEnd(SourceLocation L)
Definition TypeLoc.h:1672
void setExceptionSpecRange(SourceRange R)
Definition TypeLoc.h:1702
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4678
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4790
CallingConv getCC() const
Definition TypeBase.h:4737
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4606
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4567
ExtInfo getExtInfo() const
Definition TypeBase.h:4923
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3708
AArch64SMETypeAttributes
The AArch64 SME ACLE (Arm C/C++ Language Extensions) define a number of function type attributes that...
Definition TypeBase.h:4843
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4876
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4872
CallingConv getCallConv() const
Definition TypeBase.h:4922
QualType getReturnType() const
Definition TypeBase.h:4907
bool getHasRegParm() const
Definition TypeBase.h:4909
Type source information for HLSL attributed resource type.
Definition TypeLoc.h:1113
void setContainedTypeSourceInfo(TypeSourceInfo *TSI) const
Definition TypeLoc.h:1120
void setSourceRange(const SourceRange &R)
Definition TypeLoc.h:1124
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
A simple pair of identifier info and location.
void setIdentifierInfo(IdentifierInfo *Ident)
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ElaboratedTypeKeyword getKeyword() const
Definition TypeBase.h:6048
void setAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1614
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3681
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
bool isImplicitIntAllowed() const
Returns true if implicit int is supported at all.
bool allowArrayReturnTypes() const
bool isTargetDevice() const
True when compiling for an offloading target device.
bool isImplicitIntRequired() const
Returns true if implicit int is part of the language requirements.
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Holds a QualType and a TypeSourceInfo* that came out of a declarator parsing.
Definition LocInfoType.h:28
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
Represents the results of name lookup.
Definition Lookup.h:147
TypeLoc getInnerLoc() const
Definition TypeLoc.h:1373
void setExpansionLoc(SourceLocation Loc)
Definition TypeLoc.h:1383
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6250
void setAttrRowOperand(Expr *e)
Definition TypeLoc.h:2131
void setAttrColumnOperand(Expr *e)
Definition TypeLoc.h:2137
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:2146
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:2125
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4422
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1550
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:1559
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3717
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3749
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5646
QualType getPointeeType() const
Definition TypeBase.h:3735
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:866
This represents a decl that may have a name.
Definition Decl.h:274
bool isModulePrivate() const
Whether this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:656
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NamespaceAndPrefix getAsNamespaceAndPrefix() const
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:1313
void setNameEndLoc(SourceLocation Loc)
Definition TypeLoc.h:1325
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8009
Wraps an ObjCPointerType with source location information.
Definition TypeLoc.h:1586
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1592
Represents a pointer to an Objective C object.
Definition TypeBase.h:8065
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8102
PtrTy get() const
Definition Ownership.h:81
static OpaquePtr make(QualType P)
Definition Ownership.h:61
OpenCL supported extensions and optional core features.
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
bool isSupported(llvm::StringRef Ext, const LangOptions &LO) const
TypeLoc getWrappedLoc() const
Definition TypeLoc.h:1084
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h:2316
A parameter attribute which changes the argument-passing ABI rule for the parameter.
Definition Attr.h:260
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1415
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1411
Represents a parameter to a function.
Definition Decl.h:1817
ParsedAttr - Represents a syntactic attribute.
Definition ParsedAttr.h:119
void setInvalid(bool b=true) const
Definition ParsedAttr.h:345
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this attribute.
Definition ParsedAttr.h:371
bool isArgIdent(unsigned Arg) const
Definition ParsedAttr.h:385
Expr * getArgAsExpr(unsigned Arg) const
Definition ParsedAttr.h:383
AttributeCommonInfo::Kind getKind() const
Definition ParsedAttr.h:610
void setUsedAsTypeAttr(bool Used=true)
Definition ParsedAttr.h:360
bool checkAtMostNumArgs(class Sema &S, unsigned Num) const
Check if the attribute has at most as many args as Num.
void addAtEnd(ParsedAttr *newAttr)
Definition ParsedAttr.h:827
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:897
void remove(ParsedAttr *ToBeRemoved)
Definition ParsedAttr.h:832
void takeOneFrom(ParsedAttributes &Other, ParsedAttr *PA)
Definition ParsedAttr.h:962
TypeLoc getValueLoc() const
Definition TypeLoc.h:2720
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2725
PipeType - OpenCL20.
Definition TypeBase.h:8265
Pointer-authentication qualifiers.
Definition TypeBase.h:152
static PointerAuthQualifier Create(unsigned Key, bool IsAddressDiscriminated, unsigned ExtraDiscriminator, PointerAuthenticationMode AuthenticationMode, bool IsIsaPointer, bool AuthenticatesNullValues)
Definition TypeBase.h:239
@ MaxKey
The maximum supported pointer-authentication key.
Definition TypeBase.h:229
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1519
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
SourceLocation getPragmaAssumeNonNullLoc() const
The location of the currently-active #pragma clang assume_nonnull begin.
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8531
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8536
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1468
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1311
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8447
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8487
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1453
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8632
QualType getCanonicalType() const
Definition TypeBase.h:8499
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1089
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8468
SplitQualType getSplitUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8548
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8568
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8493
UnqualTypeLoc getUnqualifiedLoc() const
Definition TypeLoc.h:304
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:495
void addAddressSpace(LangAS space)
Definition TypeBase.h:597
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:361
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:350
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:364
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:367
void removeObjCLifetime()
Definition TypeBase.h:551
void addCVRUQualifiers(unsigned mask)
Definition TypeBase.h:506
bool hasRestrict() const
Definition TypeBase.h:477
void removeRestrict()
Definition TypeBase.h:479
static Qualifiers fromCVRMask(unsigned CVR)
Definition TypeBase.h:435
bool empty() const
Definition TypeBase.h:647
void setUnaligned(bool flag)
Definition TypeBase.h:512
void removeVolatile()
Definition TypeBase.h:469
std::string getAsString() const
@ MaxAddressSpace
The maximum supported address space number.
Definition TypeBase.h:373
void addObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:552
void setAmpAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1628
QualType getPointeeType() const
Definition TypeBase.h:3655
bool isSpelledAsLValue() const
Definition TypeBase.h:3650
bool isFunctionDeclarationScope() const
isFunctionDeclarationScope - Return true if this scope is a function prototype scope.
Definition Scope.h:475
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:208
QualType ProcessResourceTypeAttributes(QualType Wrapped)
QualType getInoutParameterType(QualType Ty)
bool isCFError(RecordDecl *D)
IdentifierInfo * getNSErrorIdent()
Retrieve the identifier "NSError".
bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type)
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1399
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7798
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:869
bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a reachable definition.
QualType BuildParenType(QualType T)
Build a paren type including T.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
bool ConstantFoldAttrArgs(const AttributeCommonInfo &CI, MutableArrayRef< Expr * > Args)
ConstantFoldAttrArgs - Folds attribute arguments into ConstantExprs (unless they are value dependent ...
Definition SemaAttr.cpp:546
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13619
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1142
bool hasStructuralCompatLayout(Decl *D, Decl *Suggested)
Determine if D and Suggested have a structurally compatible layout as described in C11 6....
bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc)
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8325
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9415
UnaryTransformType::UTTKind UTTKind
Definition Sema.h:15450
QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc)
BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression is uninstantiated.
bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind, unsigned &IntVal)
QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc)
SemaOpenMP & OpenMP()
Definition Sema.h:1534
std::optional< FunctionEffectMode > ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName)
Try to parse the conditional expression attached to an effect attribute (e.g.
SemaCUDA & CUDA()
Definition Sema.h:1474
@ AcceptSizeless
Relax the normal rules for complete types so that they include sizeless built-in types.
Definition Sema.h:15135
class clang::Sema::DelayedDiagnostics DelayedDiagnostics
QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc)
Build an ext-vector type.
bool CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS)
Check whether the given variable declaration has a size that fits within the address space it is decl...
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def)
ASTContext & Context
Definition Sema.h:1309
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain, bool PrimaryStrictPackMatch)
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:227
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
SemaObjC & ObjC()
Definition Sema.h:1519
bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM, TrivialABIHandling TAH=TrivialABIHandling::IgnoreTrivialABI, bool Diagnose=false)
Determine whether a defaulted or deleted special member function is trivial, as specified in C++11 [c...
void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec)
ASTContext & getASTContext() const
Definition Sema.h:940
void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out)
Translates template arguments as provided by the parser into template arguments used by semantic anal...
void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef< ParsedType > DynamicExceptions, ArrayRef< SourceRange > DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl< QualType > &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI)
Check the given exception-specification and update the exception specification information with the r...
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD=nullptr, CUDAFunctionTarget CFT=CUDAFunctionTarget::InvalidTarget)
Check validaty of calling convention attribute attr.
bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Ensure that the type T is a literal type.
QualType BuildCountAttributedArrayOrPointerType(QualType WrappedTy, Expr *CountExpr, bool CountInBytes, bool OrNull)
std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const
Get a string to suggest for zero-initialization of a type.
bool CheckAttrNoArgs(const ParsedAttr &CurrAttr)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc)
Build a bit-precise integer type.
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition Sema.cpp:1744
QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind, SourceLocation Loc)
QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS=nullptr)
bool CheckFunctionReturnType(QualType T, SourceLocation Loc)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14499
const LangOptions & getLangOpts() const
Definition Sema.h:933
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
Preprocessor & PP
Definition Sema.h:1308
QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc)
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
const LangOptions & LangOpts
Definition Sema.h:1307
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2673
SemaHLSL & HLSL()
Definition Sema.h:1484
IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName, unsigned Index)
Invent a new identifier for parameters of abbreviated templates.
Definition Sema.cpp:140
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
SourceLocation ImplicitMSInheritanceAttrLoc
Source location for newly created implicit MSInheritanceAttrs.
Definition Sema.h:1836
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6583
std::vector< std::unique_ptr< TemplateInstantiationCallback > > TemplateInstCallbacks
The template instantiation callbacks to trace or track instantiations (objects can be chained).
Definition Sema.h:13666
void completeExprArrayBound(Expr *E)
bool hasExplicitCallingConv(QualType T)
bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value)
Checks a regparm attribute, returning true if it is ill-formed and otherwise setting numParams to the...
FileNullabilityMap NullabilityMap
A mapping that describes the nullability we've seen in each header file.
Definition Sema.h:15110
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1342
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition Sema.cpp:2410
QualType BuildMemberPointerType(QualType T, const CXXScopeSpec &SS, CXXRecordDecl *Cls, SourceLocation Loc, DeclarationName Entity)
Build a member pointer type T Class::*.
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:645
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1447
SemaOpenCL & OpenCL()
Definition Sema.h:1529
QualType BuiltinDecay(QualType BaseType, SourceLocation Loc)
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const Decl *D, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, UnsignedOrNone NumLevels=std::nullopt, bool SkipInnerNonInstantiated=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
IdentifierInfo * getNullabilityKeyword(NullabilityKind nullability)
Retrieve the keyword associated.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8258
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
bool isAcceptable(const NamedDecl *D, AcceptableKind Kind)
Determine whether a declaration is acceptable (visible/reachable).
Definition Sema.h:15562
QualType getDecltypeForExpr(Expr *E)
getDecltypeForExpr - Given an expr, will return the decltype for that expression, according to the ru...
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:13985
SourceManager & getSourceManager() const
Definition Sema.h:938
QualType BuiltinAddReference(QualType BaseType, UTTKind UKind, SourceLocation Loc)
bool hasVisibleMergedDefinition(const NamedDecl *Def)
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
@ NTCUK_Destruct
Definition Sema.h:4144
@ NTCUK_Copy
Definition Sema.h:4145
QualType BuildAtomicType(QualType T, SourceLocation Loc)
void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX, const FunctionEffectWithCondition &EC, SourceLocation NewAttrLoc)
Warn and return true if adding a function effect to a set would create a conflict.
TypeSourceInfo * ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
TypeResult ActOnTypeName(Declarator &D)
bool isSFINAEContext() const
Definition Sema.h:13718
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15504
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
void checkUnusedDeclAttributes(Declarator &D)
checkUnusedDeclAttributes - Given a declarator which is not being used to build a declaration,...
QualType BuildPointerType(QualType T, SourceLocation Loc, DeclarationName Entity)
Build a pointer type.
bool CheckAttrTarget(const ParsedAttr &CurrAttr)
QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc)
ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold=AllowFoldKind::No)
VerifyIntegerConstantExpression - Verifies that an expression is an ICE, and reports the appropriate ...
IntrusiveRefCntPtr< ExternalSemaSource > ExternalSource
Source of additional semantic information.
Definition Sema.h:1585
ASTConsumer & Consumer
Definition Sema.h:1310
bool CheckImplicitNullabilityTypeSpecifier(QualType &Type, NullabilityKind Nullability, SourceLocation DiagLoc, bool AllowArrayTypes, bool OverrideExisting)
Check whether a nullability type specifier can be added to the given type through some means not writ...
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
bool CheckDistantExceptionSpec(QualType T)
CheckDistantExceptionSpec - Check if the given type is a pointer or pointer to member to a function w...
QualType BuildDecltypeType(Expr *E, bool AsUnevaluated=true)
If AsUnevaluated is false, E is treated as though it were an evaluated context, such as when building...
QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind, SourceLocation Loc)
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
TypeSourceInfo * GetTypeForDeclaratorCast(Declarator &D, QualType FromTy)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
QualType getCapturedDeclRefType(ValueDecl *Var, SourceLocation Loc)
Given a variable, determine the type that a reference to that variable will have in the given scope.
QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind, SourceLocation Loc)
QualType getCompletedType(Expr *E)
Get the type of expression E, triggering instantiation to complete the type if necessary – that is,...
QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind, SourceLocation Loc)
bool isDependentScopeSpecifier(const CXXScopeSpec &SS)
SourceManager & SourceMgr
Definition Sema.h:1312
DiagnosticsEngine & Diags
Definition Sema.h:1311
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:934
QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc)
QualType BuildArrayType(QualType T, ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceRange Brackets, DeclarationName Entity)
Build an array type.
bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc)
QualType BuildReadPipeType(QualType T, SourceLocation Loc)
Build a Read-only Pipe type.
void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc=SourceLocation(), SourceLocation VolatileQualLoc=SourceLocation(), SourceLocation RestrictQualLoc=SourceLocation(), SourceLocation AtomicQualLoc=SourceLocation(), SourceLocation UnalignedQualLoc=SourceLocation())
LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod
Controls member pointer representation format under the MS ABI.
Definition Sema.h:1831
llvm::BumpPtrAllocator BumpAlloc
Definition Sema.h:1254
QualType BuildWritePipeType(QualType T, SourceLocation Loc)
Build a Write-only Pipe type.
QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc)
QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:631
QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, SourceLocation AttrLoc)
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2219
bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested, AcceptableKind Kind, bool OnlyNeedComplete=false)
QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind, SourceLocation Loc)
void adjustMemberFunctionCC(QualType &T, bool HasThisPointer, bool IsCtorOrDtor, SourceLocation Loc)
Adjust the calling convention of a method to be the ABI default if it wasn't specified explicitly.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
bool checkStringLiteralArgumentAttr(const AttributeCommonInfo &CI, const Expr *E, StringRef &Str, SourceLocation *ArgLocation=nullptr)
Check if the argument E is a ASCII string literal.
QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity)
Build a block pointer type.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
const SrcMgr::SLocEntry & getSLocEntry(FileID FID, bool *Invalid=nullptr) const
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Information about a FileID, basically just the logical file that it represents and include stack info...
CharacteristicKind getFileCharacteristic() const
Return whether this is a system header or not.
SourceLocation getIncludeLoc() const
This is a discriminated union of FileInfo and ExpansionInfo.
const FileInfo & getFile() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3736
void setEmbeddedInDeclarator(bool isInDeclarator)
True if this tag declaration is "embedded" (i.e., defined or declared for the very first time) in the...
Definition Decl.h:3867
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3837
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4917
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:816
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:824
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
Exposes information about the current target.
Definition TargetInfo.h:227
virtual bool hasBitIntType() const
Determine whether the _BitInt type is supported on this target.
Definition TargetInfo.h:690
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual size_t getMaxBitIntWidth() const
Definition TargetInfo.h:696
virtual std::optional< std::pair< unsigned, unsigned > > getVScaleRange(const LangOptions &LangOpts, ArmStreamingKind Mode, llvm::StringMap< bool > *FeatureMap=nullptr) const
Returns target-specific min and max values VScale_Range.
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition TargetInfo.h:490
virtual bool allowHalfArgsAndReturns() const
Whether half args and returns are supported.
Definition TargetInfo.h:715
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition TargetInfo.h:679
virtual bool hasFloat16Type() const
Determine whether the _Float16 type is supported on this target.
Definition TargetInfo.h:721
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:733
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:718
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition TargetInfo.h:724
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
A convenient class for passing around template argument information.
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
void addArgument(const TemplateArgumentLoc &Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
Location wrapper for a TemplateArgument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:1922
void copy(TemplateSpecializationTypeLoc Loc)
Definition TypeLoc.h:1925
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, int D, int P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
[BoundsSafety] Represents information of declarations referenced by the arguments of the counted_by a...
Definition TypeBase.h:3420
const Type * getTypeForDecl() const
Definition Decl.h:3557
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition TypeLoc.h:349
TypeLoc getNextTypeLoc() const
Get the next TypeLoc pointed by this TypeLoc, e.g for "int*" the TypeLoc is a PointerLoc and next Typ...
Definition TypeLoc.h:171
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition TypeLoc.h:217
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition TypeLoc.h:165
AutoTypeLoc getContainedAutoTypeLoc() const
Get the typeloc of an AutoType whose type will be deduced for a variable with an initializer of this ...
Definition TypeLoc.cpp:884
void * getOpaqueData() const
Get the pointer where source information is stored.
Definition TypeLoc.h:143
void copy(TypeLoc other)
Copies the other type loc into this one.
Definition TypeLoc.cpp:169
void initialize(ASTContext &Context, SourceLocation Loc) const
Initializes this to state that every location in this type is the given location.
Definition TypeLoc.h:211
SourceLocation getEndLoc() const
Get the end source location.
Definition TypeLoc.cpp:227
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
void setUnmodifiedTInfo(TypeSourceInfo *TI) const
Definition TypeLoc.h:2265
A container of type source information.
Definition TypeBase.h:8418
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8429
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1875
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2545
bool isBlockPointerType() const
Definition TypeBase.h:8704
bool isVoidType() const
Definition TypeBase.h:9050
bool isBooleanType() const
Definition TypeBase.h:9187
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2775
bool isIncompleteArrayType() const
Definition TypeBase.h:8791
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2177
bool isUndeducedAutoType() const
Definition TypeBase.h:8880
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isArrayType() const
Definition TypeBase.h:8783
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isPointerType() const
Definition TypeBase.h:8684
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9094
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
NestedNameSpecifier getPrefix() const
If this type represents a qualified-id, this returns its nested name specifier.
Definition Type.cpp:1977
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2705
const Type * getArrayElementTypeNoTypeQual() const
If this is an array type, return the element type of the array, potentially with type qualifiers miss...
Definition Type.cpp:508
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool canHaveNullability(bool ResultIfUnknown=true) const
Determine whether the given type can have a nullability specifier applied to it, i....
Definition Type.cpp:5169
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2744
bool isImageType() const
Definition TypeBase.h:8948
bool isPipeType() const
Definition TypeBase.h:8955
bool isBitIntType() const
Definition TypeBase.h:8959
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8807
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2846
bool isChar16Type() const
Definition Type.cpp:2219
bool isHalfType() const
Definition TypeBase.h:9054
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2465
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2655
bool isMemberPointerType() const
Definition TypeBase.h:8765
bool isAtomicType() const
Definition TypeBase.h:8876
bool isObjCObjectType() const
Definition TypeBase.h:8867
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9193
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2531
bool isFunctionType() const
Definition TypeBase.h:8680
bool isObjCObjectPointerType() const
Definition TypeBase.h:8863
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2757
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2409
bool isAnyPointerType() const
Definition TypeBase.h:8692
TypeClass getTypeClass() const
Definition TypeBase.h:2445
bool isSamplerT() const
Definition TypeBase.h:8928
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:690
bool isObjCARCImplicitlyUnretainedType() const
Determines if this type, which must satisfy isObjCLifetimeType(), is implicitly __unsafe_unretained r...
Definition Type.cpp:5404
bool isRecordType() const
Definition TypeBase.h:8811
bool isObjCRetainableType() const
Definition Type.cpp:5435
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5156
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3686
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3581
void setParensRange(SourceRange range)
Definition TypeLoc.h:2224
void setTypeofLoc(SourceLocation Loc)
Definition TypeLoc.h:2200
void setParensRange(SourceRange Range)
Definition TypeLoc.h:2368
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2344
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition TypeLoc.h:2356
Wrapper of type source information for a type with no direct qualifiers.
Definition TypeLoc.h:274
TypeLocClass getTypeLocClass() const
Definition TypeLoc.h:283
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition DeclSpec.h:1075
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1248
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1121
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3420
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:932
@ Definition
This declaration is definitely a definition.
Definition Decl.h:1322
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2045
Represents a GCC generic vector type.
Definition TypeBase.h:4239
VectorKind getVectorKind() const
Definition TypeBase.h:4259
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Retains information about a function, method, or block that is currently being parsed.
Definition ScopeInfo.h:104
Defines the clang::TargetInfo interface.
const internal::VariadicDynCastAllOfMatcher< Decl, TypedefDecl > typedefDecl
Matches typedef declarations.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const internal::VariadicDynCastAllOfMatcher< Decl, RecordDecl > recordDecl
Matches class, struct, and union declarations.
unsigned kind
All of the diagnostics that can be emitted by the frontend.
The JSON file list parser is used to communicate input to InstallAPI.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
@ TST_auto_type
Definition Specifiers.h:95
@ TST_auto
Definition Specifiers.h:93
@ TST_unspecified
Definition Specifiers.h:57
@ TST_typename
Definition Specifiers.h:85
@ TST_decltype_auto
Definition Specifiers.h:94
void atTemplateEnd(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition Specifiers.h:215
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
@ CPlusPlus26
@ CPlusPlus17
@ ExpectedParameterOrImplicitObjectParameter
@ ExpectedFunctionWithProtoType
void atTemplateBegin(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
@ GNUAutoType
__auto_type (GNU extension)
Definition TypeBase.h:1842
@ DecltypeAuto
decltype(auto)
Definition TypeBase.h:1839
llvm::StringRef getParameterABISpelling(ParameterABI kind)
FunctionEffectMode
Used with attributes/effects with a boolean condition, e.g. nonblocking.
Definition Sema.h:459
LLVM_READONLY bool isAsciiIdentifierContinue(unsigned char c)
Definition CharInfo.h:61
CUDAFunctionTarget
Definition Cuda.h:63
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:352
@ Nullable
Values of this type can be null.
Definition Specifiers.h:356
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:361
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:354
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1797
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1800
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1803
llvm::PointerUnion< Expr *, IdentifierLoc * > ArgsUnion
A union of the various pointer types that can be passed to an ParsedAttr as an argument.
Definition ParsedAttr.h:103
@ Success
Annotation was successful.
Definition Parser.h:65
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
Definition DeclSpec.h:1035
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1033
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1031
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:1027
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:1025
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1023
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1017
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:1029
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1019
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:1021
TypeOfKind
The kind of 'typeof' expression we're after.
Definition TypeBase.h:918
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
@ AANT_ArgumentIntegerConstant
@ AANT_ArgumentString
DeclaratorContext
Definition DeclSpec.h:1902
@ Result
The result type of a method or function.
Definition TypeBase.h:905
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
llvm::StringRef getNullabilitySpelling(NullabilityKind kind, bool isContextSensitive=false)
Retrieve the spelling of the given nullability kind.
ArraySizeModifier
Capture whether this is a normal array (e.g.
Definition TypeBase.h:3783
@ SwiftAsyncContext
This parameter (which must have pointer type) uses the special Swift asynchronous context-pointer ABI...
Definition Specifiers.h:405
@ SwiftErrorResult
This parameter (which must have pointer-to-pointer type) uses the special Swift error-result ABI trea...
Definition Specifiers.h:395
@ Ordinary
This parameter uses ordinary ABI rules for its type.
Definition Specifiers.h:386
@ SwiftIndirectResult
This parameter (which must have pointer type) is a Swift indirect result parameter.
Definition Specifiers.h:390
@ SwiftContext
This parameter (which must have pointer type) uses the special Swift context-pointer ABI treatment.
Definition Specifiers.h:400
OptionalUnsigned< unsigned > UnsignedOrNone
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition Specifiers.h:323
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
static bool isBlockPointer(Expr *Arg)
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5995
@ Interface
The "__interface" keyword.
Definition TypeBase.h:6000
@ Struct
The "struct" keyword.
Definition TypeBase.h:5997
@ Class
The "class" keyword.
Definition TypeBase.h:6006
@ Union
The "union" keyword.
Definition TypeBase.h:6003
@ Enum
The "enum" keyword.
Definition TypeBase.h:6009
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition CharInfo.h:108
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:562
@ Type
The name was classified as a type.
Definition Sema.h:564
LangAS
Defines the address space values used by the address space qualifier of QualType.
MutableArrayRef< ParsedTemplateArgument > ASTTemplateArgsPtr
Definition Ownership.h:261
@ Deduced
The normal deduced case.
Definition TypeBase.h:1814
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1809
MSInheritanceModel
Assigned inheritance model for a class in the MS C++ ABI.
Definition Specifiers.h:416
@ IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition Sema.h:647
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:379
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:201
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:282
@ CC_Swift
Definition Specifiers.h:297
@ CC_DeviceKernel
Definition Specifiers.h:296
@ CC_SwiftAsync
Definition Specifiers.h:298
@ CC_X86StdCall
Definition Specifiers.h:284
@ CC_X86FastCall
Definition Specifiers.h:285
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4209
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4218
@ AltiVecVector
is AltiVec vector
Definition TypeBase.h:4203
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4206
@ Neon
is ARM Neon vector
Definition TypeBase.h:4212
@ Generic
not a target-specific vector type
Definition TypeBase.h:4200
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4224
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4227
@ NeonPoly
is ARM Neon polynomial vector
Definition TypeBase.h:4215
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4221
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:844
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:851
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition TypeBase.h:5970
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2249
@ EST_DependentNoexcept
noexcept(expression), value-dependent
@ EST_Uninstantiated
not instantiated yet
@ EST_Unparsed
not parsed yet
@ EST_NoThrow
Microsoft __declspec(nothrow) extension.
@ EST_None
no exception specification
@ EST_MSAny
Microsoft throw(...) extension.
@ EST_BasicNoexcept
noexcept
@ EST_NoexceptFalse
noexcept(expression), evals to 'false'
@ EST_Unevaluated
not evaluated yet, for special member function
@ EST_NoexceptTrue
noexcept(expression), evals to 'true'
@ EST_Dynamic
throw(T1, T2)
@ Implicit
An implicit conversion.
Definition Sema.h:440
OptionalUnsigned< NullabilityKind > NullabilityKindOrNone
Definition Specifiers.h:368
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
unsigned isStar
True if this dimension was [*]. In this case, NumElts is null.
Definition DeclSpec.h:1360
unsigned TypeQuals
The type qualifiers for the array: const/volatile/restrict/__unaligned/_Atomic.
Definition DeclSpec.h:1352
unsigned hasStatic
True if this dimension included the 'static' keyword.
Definition DeclSpec.h:1356
Expr * NumElts
This is the size of the array, or null if [] or [*] was specified.
Definition DeclSpec.h:1365
unsigned TypeQuals
For now, sema will catch these as invalid.
Definition DeclSpec.h:1649
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with ',...)',...
Definition DeclSpec.h:1412
SourceLocation getTrailingReturnTypeLoc() const
Get the trailing-return-type location for this function declarator.
Definition DeclSpec.h:1639
SourceLocation getLParenLoc() const
Definition DeclSpec.h:1554
bool hasTrailingReturnType() const
Determine whether this function declarator had a trailing-return-type.
Definition DeclSpec.h:1630
TypeAndRange * Exceptions
Pointer to a new[]'d array of TypeAndRange objects that contain the types in the function's dynamic e...
Definition DeclSpec.h:1484
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1472
ParsedType getTrailingReturnType() const
Get the trailing-return-type for this function declarator.
Definition DeclSpec.h:1633
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition DeclSpec.h:1421
SourceLocation getExceptionSpecLocBeg() const
Definition DeclSpec.h:1560
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition DeclSpec.h:1475
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition DeclSpec.h:1573
SourceLocation getRParenLoc() const
Definition DeclSpec.h:1558
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:1556
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1447
unsigned getNumExceptions() const
Get the number of dynamic exception specifications.
Definition DeclSpec.h:1616
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition DeclSpec.h:1605
unsigned isAmbiguous
Can this declaration be a constructor-style initializer?
Definition DeclSpec.h:1416
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition DeclSpec.h:1406
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition DeclSpec.h:1598
SourceRange getExceptionSpecRange() const
Definition DeclSpec.h:1568
ExceptionSpecificationType getExceptionSpecType() const
Get the type of exception specification this function has.
Definition DeclSpec.h:1611
Expr * NoexceptExpr
Pointer to the expression in the noexcept-specifier of this function, if it has one.
Definition DeclSpec.h:1488
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
Definition DeclSpec.h:1658
SourceLocation StarLoc
Location of the '*' token.
Definition DeclSpec.h:1660
const IdentifierInfo * Ident
Definition DeclSpec.h:1378
SourceLocation OverflowBehaviorLoc
The location of an __ob_wrap or __ob_trap qualifier, if any.
Definition DeclSpec.h:1328
SourceLocation RestrictQualLoc
The location of the restrict-qualifier, if any.
Definition DeclSpec.h:1319
SourceLocation ConstQualLoc
The location of the const-qualifier, if any.
Definition DeclSpec.h:1313
SourceLocation VolatileQualLoc
The location of the volatile-qualifier, if any.
Definition DeclSpec.h:1316
SourceLocation UnalignedQualLoc
The location of the __unaligned-qualifier, if any.
Definition DeclSpec.h:1325
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/unaligned/atomic.
Definition DeclSpec.h:1310
SourceLocation AtomicQualLoc
The location of the _Atomic-qualifier, if any.
Definition DeclSpec.h:1322
unsigned OverflowBehaviorIsWrap
Whether the overflow behavior qualifier is wrap (true) or trap (false).
Definition DeclSpec.h:1333
bool LValueRef
True if this is an lvalue reference, false if it's an rvalue reference.
Definition DeclSpec.h:1343
bool HasRestrict
The type qualifier: restrict. [GNU] C++ extension.
Definition DeclSpec.h:1341
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1287
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition DeclSpec.h:1707
SourceLocation EndLoc
EndLoc - If valid, the place where this chunck ends.
Definition DeclSpec.h:1297
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl * > DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult(), SourceLocation TrailingReturnTypeLoc=SourceLocation(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition DeclSpec.cpp:132
ReferenceTypeInfo Ref
Definition DeclSpec.h:1684
BlockPointerTypeInfo Cls
Definition DeclSpec.h:1687
MemberPointerTypeInfo Mem
Definition DeclSpec.h:1688
ArrayTypeInfo Arr
Definition DeclSpec.h:1685
SourceLocation Loc
Loc - The place where this type was defined.
Definition DeclSpec.h:1295
FunctionTypeInfo Fun
Definition DeclSpec.h:1686
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
PointerTypeInfo Ptr
Definition DeclSpec.h:1683
Describes whether we've seen any nullability information for the given file.
Definition Sema.h:242
SourceLocation PointerEndLoc
The end location for the first pointer declarator in the file.
Definition Sema.h:249
SourceLocation PointerLoc
The first pointer declarator (of any pointer kind) in the file that does not have a corresponding nul...
Definition Sema.h:245
bool SawTypeNullability
Whether we saw any type nullability annotations in the given file.
Definition Sema.h:255
uint8_t PointerKind
Which kind of pointer declarator we saw.
Definition Sema.h:252
A FunctionEffect plus a potential boolean expression determining whether the effect is declared (e....
Definition TypeBase.h:5108
Holds information about the various types of exception specification.
Definition TypeBase.h:5428
Extra information about a function prototype.
Definition TypeBase.h:5456
FunctionTypeExtraAttributeInfo ExtraAttributeInfo
Definition TypeBase.h:5464
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5461
void setArmSMEAttribute(AArch64SMETypeAttributes Kind, bool Enable=true)
Definition TypeBase.h:5510
StringRef CFISalt
A CFI "salt" that differentiates functions with the same prototype.
Definition TypeBase.h:4833
SmallVector< NamedDecl *, 4 > TemplateParams
Store the list of the template parameters for a generic lambda or an abbreviated function template.
Definition DeclSpec.h:2948
unsigned AutoTemplateParameterDepth
If this is a generic lambda or abbreviated function template, use this as the depth of each 'auto' pa...
Definition DeclSpec.h:2939
static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
Definition Type.cpp:3352
Describes how types, statements, expressions, and declarations should be printed.
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13147
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ Memoization
Added for Template instantiation observation.
Definition Sema.h:13248
Abstract class used to diagnose incomplete types.
Definition Sema.h:8339
virtual void diagnose(Sema &S, SourceLocation Loc, QualType T)=0
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:870
SplitQualType getSingleStepDesugaredType() const
Definition TypeBase.h:8440
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:872
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:875
llvm::DenseSet< std::tuple< Decl *, Decl *, int > > NonEquivalentDeclSet
Store declaration pairs already found to be non-equivalent.
bool IsEquivalent(Decl *D1, Decl *D2)
Determine whether the two declarations are structurally equivalent.
Information about a template-id annotation token.
const IdentifierInfo * Name
FIXME: Temporarily stores the name of a specialization.
unsigned NumArgs
NumArgs - The number of template arguments.
SourceLocation TemplateNameLoc
TemplateNameLoc - The location of the template name within the source.
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
SourceLocation TemplateKWLoc
TemplateKWLoc - The location of the template keyword.
ParsedTemplateTy Template
The declaration of the template corresponding to the template-name.