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,
849 QualType Result) {
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
916 QualType Result;
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 // 'long long' is a C99 or C++11 feature.
1045 if (!S.getLangOpts().C99) {
1046 if (S.getLangOpts().CPlusPlus)
1048 S.getLangOpts().CPlusPlus11 ?
1049 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1050 else
1051 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1052 }
1053 break;
1054 }
1055 } else {
1056 switch (DS.getTypeSpecWidth()) {
1058 Result = Context.UnsignedIntTy;
1059 break;
1061 Result = Context.UnsignedShortTy;
1062 break;
1064 Result = Context.UnsignedLongTy;
1065 break;
1067 Result = Context.UnsignedLongLongTy;
1068
1069 // 'long long' is a C99 or C++11 feature.
1070 if (!S.getLangOpts().C99) {
1071 if (S.getLangOpts().CPlusPlus)
1073 S.getLangOpts().CPlusPlus11 ?
1074 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1075 else
1076 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1077 }
1078 break;
1079 }
1080 }
1081 break;
1082 }
1083 case DeclSpec::TST_bitint: {
1085 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_BitInt";
1086 Result =
1088 DS.getRepAsExpr(), DS.getBeginLoc());
1089 if (Result.isNull()) {
1090 Result = Context.IntTy;
1091 declarator.setInvalidType(true);
1092 }
1093 break;
1094 }
1095 case DeclSpec::TST_accum: {
1096 switch (DS.getTypeSpecWidth()) {
1098 Result = Context.ShortAccumTy;
1099 break;
1101 Result = Context.AccumTy;
1102 break;
1104 Result = Context.LongAccumTy;
1105 break;
1107 llvm_unreachable("Unable to specify long long as _Accum width");
1108 }
1109
1111 Result = Context.getCorrespondingUnsignedType(Result);
1112
1113 if (DS.isTypeSpecSat())
1114 Result = Context.getCorrespondingSaturatedType(Result);
1115
1116 break;
1117 }
1118 case DeclSpec::TST_fract: {
1119 switch (DS.getTypeSpecWidth()) {
1121 Result = Context.ShortFractTy;
1122 break;
1124 Result = Context.FractTy;
1125 break;
1127 Result = Context.LongFractTy;
1128 break;
1130 llvm_unreachable("Unable to specify long long as _Fract width");
1131 }
1132
1134 Result = Context.getCorrespondingUnsignedType(Result);
1135
1136 if (DS.isTypeSpecSat())
1137 Result = Context.getCorrespondingSaturatedType(Result);
1138
1139 break;
1140 }
1142 if (!S.Context.getTargetInfo().hasInt128Type() &&
1143 !(S.getLangOpts().isTargetDevice()))
1144 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1145 << "__int128";
1147 Result = Context.UnsignedInt128Ty;
1148 else
1149 Result = Context.Int128Ty;
1150 break;
1152 // CUDA host and device may have different _Float16 support, therefore
1153 // do not diagnose _Float16 usage to avoid false alarm.
1154 // ToDo: more precise diagnostics for CUDA.
1155 if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
1156 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1157 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1158 << "_Float16";
1159 Result = Context.Float16Ty;
1160 break;
1161 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1164 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice) &&
1165 !S.getLangOpts().SYCLIsDevice)
1166 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__bf16";
1167 Result = Context.BFloat16Ty;
1168 break;
1169 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1172 Result = Context.LongDoubleTy;
1173 else
1174 Result = Context.DoubleTy;
1175 if (S.getLangOpts().OpenCL) {
1176 if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts()))
1177 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1178 << 0 << Result
1179 << (S.getLangOpts().getOpenCLCompatibleVersion() == 300
1180 ? "cl_khr_fp64 and __opencl_c_fp64"
1181 : "cl_khr_fp64");
1182 else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts()))
1183 S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma);
1184 }
1185 break;
1189 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1190 << "__float128";
1191 Result = Context.Float128Ty;
1192 break;
1194 if (!S.Context.getTargetInfo().hasIbm128Type() &&
1195 !S.getLangOpts().SYCLIsDevice &&
1196 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1197 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128";
1198 Result = Context.Ibm128Ty;
1199 break;
1200 case DeclSpec::TST_bool:
1201 Result = Context.BoolTy; // _Bool or bool
1202 break;
1203 case DeclSpec::TST_decimal32: // _Decimal32
1204 case DeclSpec::TST_decimal64: // _Decimal64
1205 case DeclSpec::TST_decimal128: // _Decimal128
1206 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1207 Result = Context.IntTy;
1208 declarator.setInvalidType(true);
1209 break;
1211 case DeclSpec::TST_enum:
1215 TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1216 if (!D) {
1217 // This can happen in C++ with ambiguous lookups.
1218 Result = Context.IntTy;
1219 declarator.setInvalidType(true);
1220 break;
1221 }
1222
1223 // If the type is deprecated or unavailable, diagnose it.
1225
1227 DS.getTypeSpecComplex() == 0 &&
1229 "No qualifiers on tag names!");
1230
1233 // TypeQuals handled by caller.
1234 Result = Context.getTagType(Keyword, DS.getTypeSpecScope().getScopeRep(), D,
1235 DS.isTypeSpecOwned());
1236 break;
1237 }
1240 DS.getTypeSpecComplex() == 0 &&
1242 "Can't handle qualifiers on typedef names yet!");
1243 Result = S.GetTypeFromParser(DS.getRepAsType());
1244 if (Result.isNull()) {
1245 declarator.setInvalidType(true);
1246 }
1247
1248 // TypeQuals handled by caller.
1249 break;
1250 }
1253 // FIXME: Preserve type source info.
1254 Result = S.GetTypeFromParser(DS.getRepAsType());
1255 assert(!Result.isNull() && "Didn't get a type for typeof?");
1256 if (!Result->isDependentType())
1257 if (const auto *TT = Result->getAs<TagType>())
1258 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1259 // TypeQuals handled by caller.
1260 Result = Context.getTypeOfType(
1264 break;
1267 Expr *E = DS.getRepAsExpr();
1268 assert(E && "Didn't get an expression for typeof?");
1269 // TypeQuals handled by caller.
1270 Result = S.BuildTypeofExprType(E, DS.getTypeSpecType() ==
1274 if (Result.isNull()) {
1275 Result = Context.IntTy;
1276 declarator.setInvalidType(true);
1277 }
1278 break;
1279 }
1281 Expr *E = DS.getRepAsExpr();
1282 assert(E && "Didn't get an expression for decltype?");
1283 // TypeQuals handled by caller.
1284 Result = S.BuildDecltypeType(E);
1285 if (Result.isNull()) {
1286 Result = Context.IntTy;
1287 declarator.setInvalidType(true);
1288 }
1289 break;
1290 }
1292 Expr *E = DS.getPackIndexingExpr();
1293 assert(E && "Didn't get an expression for pack indexing");
1294 QualType Pattern = S.GetTypeFromParser(DS.getRepAsType());
1295 Result = S.BuildPackIndexingType(Pattern, E, DS.getBeginLoc(),
1296 DS.getEllipsisLoc());
1297 if (Result.isNull()) {
1298 declarator.setInvalidType(true);
1299 Result = Context.IntTy;
1300 }
1301 break;
1302 }
1303
1304#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
1305#include "clang/Basic/TransformTypeTraits.def"
1306 Result = S.GetTypeFromParser(DS.getRepAsType());
1307 assert(!Result.isNull() && "Didn't get a type for the transformation?");
1308 Result = S.BuildUnaryTransformType(
1310 DS.getTypeSpecTypeLoc());
1311 if (Result.isNull()) {
1312 Result = Context.IntTy;
1313 declarator.setInvalidType(true);
1314 }
1315 break;
1316
1317 case DeclSpec::TST_auto:
1319 auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1322
1323 TemplateDecl *TypeConstraintConcept = nullptr;
1325 if (DS.isConstrainedAuto()) {
1326 if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1327 TypeConstraintConcept =
1328 cast<TemplateDecl>(TemplateId->Template.get().getAsTemplateDecl());
1329 TemplateArgumentListInfo TemplateArgsInfo;
1330 TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1331 TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1332 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1333 TemplateId->NumArgs);
1334 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1335 for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1336 TemplateArgs.push_back(ArgLoc.getArgument());
1337 } else {
1338 declarator.setInvalidType(true);
1339 }
1340 }
1341 Result = S.Context.getAutoType(QualType(), AutoKW,
1342 /*IsDependent*/ false, /*IsPack=*/false,
1343 TypeConstraintConcept, TemplateArgs);
1344 break;
1345 }
1346
1348 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1349 break;
1350
1352 Result = Context.UnknownAnyTy;
1353 break;
1354
1356 Result = S.GetTypeFromParser(DS.getRepAsType());
1357 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1358 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1359 if (Result.isNull()) {
1360 Result = Context.IntTy;
1361 declarator.setInvalidType(true);
1362 }
1363 break;
1364
1365#define GENERIC_IMAGE_TYPE(ImgType, Id) \
1366 case DeclSpec::TST_##ImgType##_t: \
1367 switch (getImageAccess(DS.getAttributes())) { \
1368 case OpenCLAccessAttr::Keyword_write_only: \
1369 Result = Context.Id##WOTy; \
1370 break; \
1371 case OpenCLAccessAttr::Keyword_read_write: \
1372 Result = Context.Id##RWTy; \
1373 break; \
1374 case OpenCLAccessAttr::Keyword_read_only: \
1375 Result = Context.Id##ROTy; \
1376 break; \
1377 case OpenCLAccessAttr::SpellingNotCalculated: \
1378 llvm_unreachable("Spelling not yet calculated"); \
1379 } \
1380 break;
1381#include "clang/Basic/OpenCLImageTypes.def"
1382
1383#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1384 case DeclSpec::TST_##Name: \
1385 Result = Context.SingletonId; \
1386 break;
1387#include "clang/Basic/HLSLIntangibleTypes.def"
1388
1390 Result = Context.IntTy;
1391 declarator.setInvalidType(true);
1392 break;
1393 }
1394
1395 // FIXME: we want resulting declarations to be marked invalid, but claiming
1396 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1397 // a null type.
1398 if (Result->containsErrors())
1399 declarator.setInvalidType();
1400
1401 if (S.getLangOpts().OpenCL) {
1402 const auto &OpenCLOptions = S.getOpenCLOptions();
1403 bool IsOpenCLC30Compatible =
1405 // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1406 // support.
1407 // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1408 // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1409 // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1410 // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1411 // only when the optional feature is supported
1412 if ((Result->isImageType() || Result->isSamplerT()) &&
1413 (IsOpenCLC30Compatible &&
1414 !OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts()))) {
1415 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1416 << 0 << Result << "__opencl_c_images";
1417 declarator.setInvalidType();
1418 } else if (Result->isOCLImage3dWOType() &&
1419 !OpenCLOptions.isSupported("cl_khr_3d_image_writes",
1420 S.getLangOpts())) {
1421 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1422 << 0 << Result
1423 << (IsOpenCLC30Compatible
1424 ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes"
1425 : "cl_khr_3d_image_writes");
1426 declarator.setInvalidType();
1427 }
1428 }
1429
1430 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1432
1433 // Only fixed point types can be saturated
1434 if (DS.isTypeSpecSat() && !IsFixedPointType)
1435 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1437 Context.getPrintingPolicy());
1438
1439 // Handle complex types.
1441 if (S.getLangOpts().Freestanding)
1442 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1443 Result = Context.getComplexType(Result);
1444 } else if (DS.isTypeAltiVecVector()) {
1445 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1446 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1448 if (DS.isTypeAltiVecPixel())
1449 VecKind = VectorKind::AltiVecPixel;
1450 else if (DS.isTypeAltiVecBool())
1451 VecKind = VectorKind::AltiVecBool;
1452 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1453 }
1454
1455 // _Imaginary was a feature of C99 through C23 but was never supported in
1456 // Clang. The feature was removed in C2y, but we retain the unsupported
1457 // diagnostic for an improved user experience.
1459 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1460
1461 // Before we process any type attributes, synthesize a block literal
1462 // function declarator if necessary.
1463 if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1464 maybeSynthesizeBlockSignature(state, Result);
1465
1466 // Apply any type attributes from the decl spec. This may cause the
1467 // list of type attributes to be temporarily saved while the type
1468 // attributes are pushed around.
1469 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1470 if (!DS.isTypeSpecPipe()) {
1471 // We also apply declaration attributes that "slide" to the decl spec.
1472 // Ordering can be important for attributes. The decalaration attributes
1473 // come syntactically before the decl spec attributes, so we process them
1474 // in that order.
1475 ParsedAttributesView SlidingAttrs;
1476 for (ParsedAttr &AL : declarator.getDeclarationAttributes()) {
1477 if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
1478 SlidingAttrs.addAtEnd(&AL);
1479
1480 // For standard syntax attributes, which would normally appertain to the
1481 // declaration here, suggest moving them to the type instead. But only
1482 // do this for our own vendor attributes; moving other vendors'
1483 // attributes might hurt portability.
1484 // There's one special case that we need to deal with here: The
1485 // `MatrixType` attribute may only be used in a typedef declaration. If
1486 // it's being used anywhere else, don't output the warning as
1487 // ProcessDeclAttributes() will output an error anyway.
1488 if (AL.isStandardAttributeSyntax() && AL.isClangScope() &&
1489 !(AL.getKind() == ParsedAttr::AT_MatrixType &&
1491 S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl)
1492 << AL;
1493 }
1494 }
1495 }
1496 // During this call to processTypeAttrs(),
1497 // TypeProcessingState::getCurrentAttributes() will erroneously return a
1498 // reference to the DeclSpec attributes, rather than the declaration
1499 // attributes. However, this doesn't matter, as getCurrentAttributes()
1500 // is only called when distributing attributes from one attribute list
1501 // to another. Declaration attributes are always C++11 attributes, and these
1502 // are never distributed.
1503 processTypeAttrs(state, Result, TAL_DeclSpec, SlidingAttrs);
1504 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
1505 }
1506
1507 // Apply const/volatile/restrict qualifiers to T.
1508 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1509 // Warn about CV qualifiers on function types.
1510 // C99 6.7.3p8:
1511 // If the specification of a function type includes any type qualifiers,
1512 // the behavior is undefined.
1513 // C2y changed this behavior to be implementation-defined. Clang defines
1514 // the behavior in all cases to ignore the qualifier, as in C++.
1515 // C++11 [dcl.fct]p7:
1516 // The effect of a cv-qualifier-seq in a function declarator is not the
1517 // same as adding cv-qualification on top of the function type. In the
1518 // latter case, the cv-qualifiers are ignored.
1519 if (Result->isFunctionType()) {
1520 unsigned DiagId = diag::warn_typecheck_function_qualifiers_ignored;
1521 if (!S.getLangOpts().CPlusPlus && !S.getLangOpts().C2y)
1522 DiagId = diag::ext_typecheck_function_qualifiers_unspecified;
1524 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1525 DiagId);
1526 // No diagnostic for 'restrict' or '_Atomic' applied to a
1527 // function type; we'll diagnose those later, in BuildQualifiedType.
1528 }
1529
1530 // C++11 [dcl.ref]p1:
1531 // Cv-qualified references are ill-formed except when the
1532 // cv-qualifiers are introduced through the use of a typedef-name
1533 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1534 //
1535 // There don't appear to be any other contexts in which a cv-qualified
1536 // reference type could be formed, so the 'ill-formed' clause here appears
1537 // to never happen.
1538 if (TypeQuals && Result->isReferenceType()) {
1540 S, DS, TypeQuals, Result,
1542 diag::warn_typecheck_reference_qualifiers);
1543 }
1544
1545 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1546 // than once in the same specifier-list or qualifier-list, either directly
1547 // or via one or more typedefs."
1548 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1549 && TypeQuals & Result.getCVRQualifiers()) {
1550 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1551 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1552 << "const";
1553 }
1554
1555 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1556 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1557 << "volatile";
1558 }
1559
1560 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1561 // produce a warning in this case.
1562 }
1563
1564 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1565
1566 // If adding qualifiers fails, just use the unqualified type.
1567 if (Qualified.isNull())
1568 declarator.setInvalidType(true);
1569 else
1570 Result = Qualified;
1571 }
1572
1573 // Check for __ob_wrap and __ob_trap
1574 if (DS.isOverflowBehaviorSpecified() &&
1575 S.getLangOpts().OverflowBehaviorTypes) {
1576 if (!Result->isIntegerType()) {
1578 StringRef SpecifierName =
1580 S.Diag(Loc, diag::err_overflow_behavior_non_integer_type)
1581 << SpecifierName << Result.getAsString() << 1;
1582 } else {
1583 OverflowBehaviorType::OverflowBehaviorKind Kind =
1584 DS.isWrapSpecified()
1585 ? OverflowBehaviorType::OverflowBehaviorKind::Wrap
1586 : OverflowBehaviorType::OverflowBehaviorKind::Trap;
1587 Result = state.getOverflowBehaviorType(Kind, Result);
1588 }
1589 }
1590
1591 if (S.getLangOpts().HLSL)
1592 Result = S.HLSL().ProcessResourceTypeAttributes(Result);
1593
1594 assert(!Result.isNull() && "This function should not return a null type");
1595 return Result;
1596}
1597
1598static std::string getPrintableNameForEntity(DeclarationName Entity) {
1599 if (Entity)
1600 return Entity.getAsString();
1601
1602 return "type name";
1603}
1604
1606 if (T->isDependentType())
1607 return true;
1608
1609 const auto *AT = dyn_cast<AutoType>(T);
1610 return AT && AT->isGNUAutoType();
1611}
1612
1614 Qualifiers Qs, const DeclSpec *DS) {
1615 if (T.isNull())
1616 return QualType();
1617
1618 // Ignore any attempt to form a cv-qualified reference.
1619 if (T->isReferenceType()) {
1620 Qs.removeConst();
1621 Qs.removeVolatile();
1622 }
1623
1624 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1625 // object or incomplete types shall not be restrict-qualified."
1626 if (Qs.hasRestrict()) {
1627 unsigned DiagID = 0;
1628 QualType EltTy = Context.getBaseElementType(T);
1629
1630 if (EltTy->isAnyPointerType() || EltTy->isReferenceType() ||
1631 EltTy->isMemberPointerType()) {
1632
1633 if (const auto *PTy = EltTy->getAs<MemberPointerType>())
1634 EltTy = PTy->getPointeeType();
1635 else
1636 EltTy = EltTy->getPointeeType();
1637
1638 // If we have a pointer or reference, the pointee must have an object
1639 // incomplete type.
1640 if (!EltTy->isIncompleteOrObjectType())
1641 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1642
1643 } else if (!isDependentOrGNUAutoType(T)) {
1644 // For an __auto_type variable, we may not have seen the initializer yet
1645 // and so have no idea whether the underlying type is a pointer type or
1646 // not.
1647 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1648 EltTy = T;
1649 }
1650
1651 Loc = DS ? DS->getRestrictSpecLoc() : Loc;
1652 if (DiagID) {
1653 Diag(Loc, DiagID) << EltTy;
1654 Qs.removeRestrict();
1655 } else {
1656 if (T->isArrayType())
1657 Diag(Loc, getLangOpts().C23
1658 ? diag::warn_c23_compat_restrict_on_array_of_pointers
1659 : diag::ext_restrict_on_array_of_pointers_c23);
1660 }
1661 }
1662
1663 return Context.getQualifiedType(T, Qs);
1664}
1665
1667 unsigned CVRAU, const DeclSpec *DS) {
1668 if (T.isNull())
1669 return QualType();
1670
1671 // Ignore any attempt to form a cv-qualified reference.
1672 if (T->isReferenceType())
1673 CVRAU &=
1675
1676 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1677 // TQ_unaligned;
1678 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1679
1680 // C11 6.7.3/5:
1681 // If the same qualifier appears more than once in the same
1682 // specifier-qualifier-list, either directly or via one or more typedefs,
1683 // the behavior is the same as if it appeared only once.
1684 //
1685 // It's not specified what happens when the _Atomic qualifier is applied to
1686 // a type specified with the _Atomic specifier, but we assume that this
1687 // should be treated as if the _Atomic qualifier appeared multiple times.
1688 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1689 // C11 6.7.3/5:
1690 // If other qualifiers appear along with the _Atomic qualifier in a
1691 // specifier-qualifier-list, the resulting type is the so-qualified
1692 // atomic type.
1693 //
1694 // Don't need to worry about array types here, since _Atomic can't be
1695 // applied to such types.
1696 SplitQualType Split = T.getSplitUnqualifiedType();
1697 T = BuildAtomicType(QualType(Split.Ty, 0),
1698 DS ? DS->getAtomicSpecLoc() : Loc);
1699 if (T.isNull())
1700 return T;
1701 Split.Quals.addCVRQualifiers(CVR);
1702 return BuildQualifiedType(T, Loc, Split.Quals);
1703 }
1704
1707 return BuildQualifiedType(T, Loc, Q, DS);
1708}
1709
1711 return Context.getParenType(T);
1712}
1713
1714/// Given that we're building a pointer or reference to the given
1716 SourceLocation loc,
1717 bool isReference) {
1718 // Bail out if retention is unrequired or already specified.
1719 if (!type->isObjCLifetimeType() ||
1720 type.getObjCLifetime() != Qualifiers::OCL_None)
1721 return type;
1722
1724
1725 // If the object type is const-qualified, we can safely use
1726 // __unsafe_unretained. This is safe (because there are no read
1727 // barriers), and it'll be safe to coerce anything but __weak* to
1728 // the resulting type.
1729 if (type.isConstQualified()) {
1730 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1731
1732 // Otherwise, check whether the static type does not require
1733 // retaining. This currently only triggers for Class (possibly
1734 // protocol-qualifed, and arrays thereof).
1735 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1736 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1737
1738 // If we are in an unevaluated context, like sizeof, skip adding a
1739 // qualification.
1740 } else if (S.isUnevaluatedContext()) {
1741 return type;
1742
1743 // If that failed, give an error and recover using __strong. __strong
1744 // is the option most likely to prevent spurious second-order diagnostics,
1745 // like when binding a reference to a field.
1746 } else {
1747 // These types can show up in private ivars in system headers, so
1748 // we need this to not be an error in those cases. Instead we
1749 // want to delay.
1753 diag::err_arc_indirect_no_ownership, type, isReference));
1754 } else {
1755 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1756 }
1757 implicitLifetime = Qualifiers::OCL_Strong;
1758 }
1759 assert(implicitLifetime && "didn't infer any lifetime!");
1760
1761 Qualifiers qs;
1762 qs.addObjCLifetime(implicitLifetime);
1763 return S.Context.getQualifiedType(type, qs);
1764}
1765
1766static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1767 std::string Quals = FnTy->getMethodQuals().getAsString();
1768
1769 switch (FnTy->getRefQualifier()) {
1770 case RQ_None:
1771 break;
1772
1773 case RQ_LValue:
1774 if (!Quals.empty())
1775 Quals += ' ';
1776 Quals += '&';
1777 break;
1778
1779 case RQ_RValue:
1780 if (!Quals.empty())
1781 Quals += ' ';
1782 Quals += "&&";
1783 break;
1784 }
1785
1786 return Quals;
1787}
1788
1789namespace {
1790/// Kinds of declarator that cannot contain a qualified function type.
1791///
1792/// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1793/// a function type with a cv-qualifier or a ref-qualifier can only appear
1794/// at the topmost level of a type.
1795///
1796/// Parens and member pointers are permitted. We don't diagnose array and
1797/// function declarators, because they don't allow function types at all.
1798///
1799/// The values of this enum are used in diagnostics.
1800enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1801} // end anonymous namespace
1802
1803/// Check whether the type T is a qualified function type, and if it is,
1804/// diagnose that it cannot be contained within the given kind of declarator.
1806 QualifiedFunctionKind QFK) {
1807 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1808 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1809 if (!FPT ||
1810 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1811 return false;
1812
1813 S.Diag(Loc, diag::err_compound_qualified_function_type)
1814 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1816 return true;
1817}
1818
1820 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1821 if (!FPT ||
1822 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1823 return false;
1824
1825 Diag(Loc, diag::err_qualified_function_typeid)
1826 << T << getFunctionQualifiersAsString(FPT);
1827 return true;
1828}
1829
1830// Helper to deduce addr space of a pointee type in OpenCL mode.
1832 if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
1833 !PointeeType->isSamplerT() &&
1834 !PointeeType.hasAddressSpace())
1835 PointeeType = S.getASTContext().getAddrSpaceQualType(
1837 return PointeeType;
1838}
1839
1841 SourceLocation Loc, DeclarationName Entity) {
1842 if (T->isReferenceType()) {
1843 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1844 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1845 << getPrintableNameForEntity(Entity) << T;
1846 return QualType();
1847 }
1848
1849 if (T->isFunctionType() && getLangOpts().OpenCL &&
1850 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
1851 getLangOpts())) {
1852 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
1853 return QualType();
1854 }
1855
1856 if (getLangOpts().HLSL && Loc.isValid()) {
1857 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
1858 return QualType();
1859 }
1860
1861 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1862 return QualType();
1863
1864 if (T->isObjCObjectType())
1865 return Context.getObjCObjectPointerType(T);
1866
1867 // In ARC, it is forbidden to build pointers to unqualified pointers.
1868 if (getLangOpts().ObjCAutoRefCount)
1869 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1870
1871 if (getLangOpts().OpenCL)
1872 T = deduceOpenCLPointeeAddrSpace(*this, T);
1873
1874 // In WebAssembly, pointers to reference types and pointers to tables are
1875 // illegal.
1876 if (getASTContext().getTargetInfo().getTriple().isWasm()) {
1877 if (T.isWebAssemblyReferenceType()) {
1878 Diag(Loc, diag::err_wasm_reference_pr) << 0;
1879 return QualType();
1880 }
1881
1882 // We need to desugar the type here in case T is a ParenType.
1883 if (T->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
1884 Diag(Loc, diag::err_wasm_table_pr) << 0;
1885 return QualType();
1886 }
1887 }
1888
1889 // Build the pointer type.
1890 return Context.getPointerType(T);
1891}
1892
1894 SourceLocation Loc,
1895 DeclarationName Entity) {
1896 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1897 "Unresolved overloaded function type");
1898
1899 // C++0x [dcl.ref]p6:
1900 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1901 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1902 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1903 // the type "lvalue reference to T", while an attempt to create the type
1904 // "rvalue reference to cv TR" creates the type TR.
1905 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1906
1907 // C++ [dcl.ref]p4: There shall be no references to references.
1908 //
1909 // According to C++ DR 106, references to references are only
1910 // diagnosed when they are written directly (e.g., "int & &"),
1911 // but not when they happen via a typedef:
1912 //
1913 // typedef int& intref;
1914 // typedef intref& intref2;
1915 //
1916 // Parser::ParseDeclaratorInternal diagnoses the case where
1917 // references are written directly; here, we handle the
1918 // collapsing of references-to-references as described in C++0x.
1919 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1920
1921 // C++ [dcl.ref]p1:
1922 // A declarator that specifies the type "reference to cv void"
1923 // is ill-formed.
1924 if (T->isVoidType()) {
1925 Diag(Loc, diag::err_reference_to_void);
1926 return QualType();
1927 }
1928
1929 if (getLangOpts().HLSL && Loc.isValid()) {
1930 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1;
1931 return QualType();
1932 }
1933
1934 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1935 return QualType();
1936
1937 if (T->isFunctionType() && getLangOpts().OpenCL &&
1938 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
1939 getLangOpts())) {
1940 Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1;
1941 return QualType();
1942 }
1943
1944 // In ARC, it is forbidden to build references to unqualified pointers.
1945 if (getLangOpts().ObjCAutoRefCount)
1946 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1947
1948 if (getLangOpts().OpenCL)
1949 T = deduceOpenCLPointeeAddrSpace(*this, T);
1950
1951 // In WebAssembly, references to reference types and tables are illegal.
1952 if (getASTContext().getTargetInfo().getTriple().isWasm() &&
1953 T.isWebAssemblyReferenceType()) {
1954 Diag(Loc, diag::err_wasm_reference_pr) << 1;
1955 return QualType();
1956 }
1957 if (T->isWebAssemblyTableType()) {
1958 Diag(Loc, diag::err_wasm_table_pr) << 1;
1959 return QualType();
1960 }
1961
1962 // Handle restrict on references.
1963 if (LValueRef)
1964 return Context.getLValueReferenceType(T, SpelledAsLValue);
1965 return Context.getRValueReferenceType(T);
1966}
1967
1969 return Context.getReadPipeType(T);
1970}
1971
1973 return Context.getWritePipeType(T);
1974}
1975
1976QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth,
1977 SourceLocation Loc) {
1978 if (BitWidth->isInstantiationDependent())
1979 return Context.getDependentBitIntType(IsUnsigned, BitWidth);
1980
1981 llvm::APSInt Bits(32);
1983 BitWidth, &Bits, /*FIXME*/ AllowFoldKind::Allow);
1984
1985 if (ICE.isInvalid())
1986 return QualType();
1987
1988 size_t NumBits = Bits.getZExtValue();
1989 if (!IsUnsigned && NumBits < 2) {
1990 Diag(Loc, diag::err_bit_int_bad_size) << 0;
1991 return QualType();
1992 }
1993
1994 if (IsUnsigned && NumBits < 1) {
1995 Diag(Loc, diag::err_bit_int_bad_size) << 1;
1996 return QualType();
1997 }
1998
1999 const TargetInfo &TI = getASTContext().getTargetInfo();
2000 if (NumBits > TI.getMaxBitIntWidth()) {
2001 Diag(Loc, diag::err_bit_int_max_size)
2002 << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth());
2003 return QualType();
2004 }
2005
2006 return Context.getBitIntType(IsUnsigned, NumBits);
2007}
2008
2009/// Check whether the specified array bound can be evaluated using the relevant
2010/// language rules. If so, returns the possibly-converted expression and sets
2011/// SizeVal to the size. If not, but the expression might be a VLA bound,
2012/// returns ExprResult(). Otherwise, produces a diagnostic and returns
2013/// ExprError().
2014static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
2015 llvm::APSInt &SizeVal, unsigned VLADiag,
2016 bool VLAIsError) {
2017 if (S.getLangOpts().CPlusPlus14 &&
2018 (VLAIsError ||
2019 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) {
2020 // C++14 [dcl.array]p1:
2021 // The constant-expression shall be a converted constant expression of
2022 // type std::size_t.
2023 //
2024 // Don't apply this rule if we might be forming a VLA: in that case, we
2025 // allow non-constant expressions and constant-folding. We only need to use
2026 // the converted constant expression rules (to properly convert the source)
2027 // when the source expression is of class type.
2029 ArraySize, S.Context.getSizeType(), SizeVal, CCEKind::ArrayBound);
2030 }
2031
2032 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2033 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2034 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2035 public:
2036 unsigned VLADiag;
2037 bool VLAIsError;
2038 bool IsVLA = false;
2039
2040 VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2041 : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2042
2043 Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2044 QualType T) override {
2045 return S.Diag(Loc, diag::err_array_size_non_int) << T;
2046 }
2047
2048 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2049 SourceLocation Loc) override {
2050 IsVLA = !VLAIsError;
2051 return S.Diag(Loc, VLADiag);
2052 }
2053
2054 Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2055 SourceLocation Loc) override {
2056 return S.Diag(Loc, diag::ext_vla_folded_to_constant);
2057 }
2058 } Diagnoser(VLADiag, VLAIsError);
2059
2060 ExprResult R =
2061 S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser);
2062 if (Diagnoser.IsVLA)
2063 return ExprResult();
2064 return R;
2065}
2066
2068 EltTy = Context.getBaseElementType(EltTy);
2069 if (EltTy->isIncompleteType() || EltTy->isDependentType() ||
2070 EltTy->isUndeducedType())
2071 return true;
2072
2073 CharUnits Size = Context.getTypeSizeInChars(EltTy);
2074 CharUnits Alignment = Context.getTypeAlignInChars(EltTy);
2075
2076 if (Size.isMultipleOf(Alignment))
2077 return true;
2078
2079 Diag(Loc, diag::err_array_element_alignment)
2080 << EltTy << Size.getQuantity() << Alignment.getQuantity();
2081 return false;
2082}
2083
2085 Expr *ArraySize, unsigned Quals,
2086 SourceRange Brackets, DeclarationName Entity) {
2087
2088 SourceLocation Loc = Brackets.getBegin();
2089 if (getLangOpts().CPlusPlus) {
2090 // C++ [dcl.array]p1:
2091 // T is called the array element type; this type shall not be a reference
2092 // type, the (possibly cv-qualified) type void, a function type or an
2093 // abstract class type.
2094 //
2095 // C++ [dcl.array]p3:
2096 // When several "array of" specifications are adjacent, [...] only the
2097 // first of the constant expressions that specify the bounds of the arrays
2098 // may be omitted.
2099 //
2100 // Note: function types are handled in the common path with C.
2101 if (T->isReferenceType()) {
2102 Diag(Loc, diag::err_illegal_decl_array_of_references)
2103 << getPrintableNameForEntity(Entity) << T;
2104 return QualType();
2105 }
2106
2107 if (T->isVoidType() || T->isIncompleteArrayType()) {
2108 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2109 return QualType();
2110 }
2111
2112 if (RequireNonAbstractType(Brackets.getBegin(), T,
2113 diag::err_array_of_abstract_type))
2114 return QualType();
2115
2116 // Mentioning a member pointer type for an array type causes us to lock in
2117 // an inheritance model, even if it's inside an unused typedef.
2118 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2119 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2120 if (!MPTy->getQualifier().isDependent())
2121 (void)isCompleteType(Loc, T);
2122
2123 } else {
2124 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2125 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2126 if (!T.isWebAssemblyReferenceType() &&
2128 diag::err_array_incomplete_or_sizeless_type))
2129 return QualType();
2130 }
2131
2132 // Multi-dimensional arrays of WebAssembly references are not allowed.
2133 if (Context.getTargetInfo().getTriple().isWasm() && T->isArrayType()) {
2134 const auto *ATy = dyn_cast<ArrayType>(T);
2135 if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
2136 Diag(Loc, diag::err_wasm_reftype_multidimensional_array);
2137 return QualType();
2138 }
2139 }
2140
2141 if (T->isSizelessType() && !T.isWebAssemblyReferenceType()) {
2142 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2143 return QualType();
2144 }
2145
2146 if (T->isFunctionType()) {
2147 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2148 << getPrintableNameForEntity(Entity) << T;
2149 return QualType();
2150 }
2151
2152 if (const auto *RD = T->getAsRecordDecl()) {
2153 // If the element type is a struct or union that contains a variadic
2154 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2155 if (RD->hasFlexibleArrayMember())
2156 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2157 } else if (T->isObjCObjectType()) {
2158 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2159 return QualType();
2160 }
2161
2162 if (!checkArrayElementAlignment(T, Loc))
2163 return QualType();
2164
2165 // Do placeholder conversions on the array size expression.
2166 if (ArraySize && ArraySize->hasPlaceholderType()) {
2168 if (Result.isInvalid()) return QualType();
2169 ArraySize = Result.get();
2170 }
2171
2172 // Do lvalue-to-rvalue conversions on the array size expression.
2173 if (ArraySize && !ArraySize->isPRValue()) {
2175 if (Result.isInvalid())
2176 return QualType();
2177
2178 ArraySize = Result.get();
2179 }
2180
2181 // C99 6.7.5.2p1: The size expression shall have integer type.
2182 // C++11 allows contextual conversions to such types.
2183 if (!getLangOpts().CPlusPlus11 &&
2184 ArraySize && !ArraySize->isTypeDependent() &&
2186 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2187 << ArraySize->getType() << ArraySize->getSourceRange();
2188 return QualType();
2189 }
2190
2191 auto IsStaticAssertLike = [](const Expr *ArraySize, ASTContext &Context) {
2192 if (!ArraySize)
2193 return false;
2194
2195 // If the array size expression is a conditional expression whose branches
2196 // are both integer constant expressions, one negative and one positive,
2197 // then it's assumed to be like an old-style static assertion. e.g.,
2198 // int old_style_assert[expr ? 1 : -1];
2199 // We will accept any integer constant expressions instead of assuming the
2200 // values 1 and -1 are always used.
2201 if (const auto *CondExpr = dyn_cast_if_present<ConditionalOperator>(
2202 ArraySize->IgnoreParenImpCasts())) {
2203 std::optional<llvm::APSInt> LHS =
2204 CondExpr->getLHS()->getIntegerConstantExpr(Context);
2205 std::optional<llvm::APSInt> RHS =
2206 CondExpr->getRHS()->getIntegerConstantExpr(Context);
2207 return LHS && RHS && LHS->isNegative() != RHS->isNegative();
2208 }
2209 return false;
2210 };
2211
2212 // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2213 unsigned VLADiag;
2214 bool VLAIsError;
2215 if (getLangOpts().OpenCL) {
2216 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2217 VLADiag = diag::err_opencl_vla;
2218 VLAIsError = true;
2219 } else if (getLangOpts().C99) {
2220 VLADiag = diag::warn_vla_used;
2221 VLAIsError = false;
2222 } else if (isSFINAEContext()) {
2223 VLADiag = diag::err_vla_in_sfinae;
2224 VLAIsError = true;
2225 } else if (getLangOpts().OpenMP && OpenMP().isInOpenMPTaskUntiedContext()) {
2226 VLADiag = diag::err_openmp_vla_in_task_untied;
2227 VLAIsError = true;
2228 } else if (getLangOpts().CPlusPlus) {
2229 if (getLangOpts().CPlusPlus11 && IsStaticAssertLike(ArraySize, Context))
2230 VLADiag = getLangOpts().GNUMode
2231 ? diag::ext_vla_cxx_in_gnu_mode_static_assert
2232 : diag::ext_vla_cxx_static_assert;
2233 else
2234 VLADiag = getLangOpts().GNUMode ? diag::ext_vla_cxx_in_gnu_mode
2235 : diag::ext_vla_cxx;
2236 VLAIsError = false;
2237 } else {
2238 VLADiag = diag::ext_vla;
2239 VLAIsError = false;
2240 }
2241
2242 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2243 if (!ArraySize) {
2244 if (ASM == ArraySizeModifier::Star) {
2245 Diag(Loc, VLADiag);
2246 if (VLAIsError)
2247 return QualType();
2248
2249 T = Context.getVariableArrayType(T, nullptr, ASM, Quals);
2250 } else {
2251 T = Context.getIncompleteArrayType(T, ASM, Quals);
2252 }
2253 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2254 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals);
2255 } else {
2256 ExprResult R =
2257 checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError);
2258 if (R.isInvalid())
2259 return QualType();
2260
2261 if (!R.isUsable()) {
2262 // C99: an array with a non-ICE size is a VLA. We accept any expression
2263 // that we can fold to a non-zero positive value as a non-VLA as an
2264 // extension.
2265 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals);
2266 } else if (!T->isDependentType() && !T->isIncompleteType() &&
2267 !T->isConstantSizeType()) {
2268 // C99: an array with an element type that has a non-constant-size is a
2269 // VLA.
2270 // FIXME: Add a note to explain why this isn't a VLA.
2271 Diag(Loc, VLADiag);
2272 if (VLAIsError)
2273 return QualType();
2274 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals);
2275 } else {
2276 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2277 // have a value greater than zero.
2278 // In C++, this follows from narrowing conversions being disallowed.
2279 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2280 if (Entity)
2281 Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2282 << getPrintableNameForEntity(Entity)
2283 << ArraySize->getSourceRange();
2284 else
2285 Diag(ArraySize->getBeginLoc(),
2286 diag::err_typecheck_negative_array_size)
2287 << ArraySize->getSourceRange();
2288 return QualType();
2289 }
2290 if (ConstVal == 0 && !T.isWebAssemblyReferenceType()) {
2291 // GCC accepts zero sized static arrays. We allow them when
2292 // we're not in a SFINAE context.
2293 Diag(ArraySize->getBeginLoc(),
2294 isSFINAEContext() ? diag::err_typecheck_zero_array_size
2295 : diag::ext_typecheck_zero_array_size)
2296 << 0 << ArraySize->getSourceRange();
2297 if (isSFINAEContext())
2298 return QualType();
2299 }
2300
2301 // Is the array too large?
2302 unsigned ActiveSizeBits =
2303 (!T->isDependentType() && !T->isVariablyModifiedType() &&
2304 !T->isIncompleteType() && !T->isUndeducedType())
2306 : ConstVal.getActiveBits();
2307 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2308 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2309 << toString(ConstVal, 10, ConstVal.isSigned(),
2310 /*formatAsCLiteral=*/false, /*UpperCase=*/false,
2311 /*InsertSeparators=*/true)
2312 << ArraySize->getSourceRange();
2313 return QualType();
2314 }
2315
2316 T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2317 }
2318 }
2319
2320 if (T->isVariableArrayType()) {
2321 if (!Context.getTargetInfo().isVLASupported()) {
2322 // CUDA device code and some other targets don't support VLAs.
2323 bool IsCUDADevice = (getLangOpts().CUDA && getLangOpts().CUDAIsDevice);
2324 targetDiag(Loc,
2325 IsCUDADevice ? diag::err_cuda_vla : diag::err_vla_unsupported)
2326 << (IsCUDADevice ? llvm::to_underlying(CUDA().CurrentTarget()) : 0);
2327 } else if (sema::FunctionScopeInfo *FSI = getCurFunction()) {
2328 // VLAs are supported on this target, but we may need to do delayed
2329 // checking that the VLA is not being used within a coroutine.
2330 FSI->setHasVLA(Loc);
2331 }
2332 }
2333
2334 // If this is not C99, diagnose array size modifiers on non-VLAs.
2335 if (!getLangOpts().C99 && !T->isVariableArrayType() &&
2336 (ASM != ArraySizeModifier::Normal || Quals != 0)) {
2337 Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx
2338 : diag::ext_c99_array_usage)
2339 << ASM;
2340 }
2341
2342 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2343 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2344 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2345 if (getLangOpts().OpenCL) {
2346 const QualType ArrType = Context.getBaseElementType(T);
2347 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2348 ArrType->isSamplerT() || ArrType->isImageType()) {
2349 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2350 return QualType();
2351 }
2352 }
2353
2354 return T;
2355}
2356
2358 const BitIntType *BIT,
2359 bool ForMatrixType = false) {
2360 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2361 unsigned NumBits = BIT->getNumBits();
2362 if (!llvm::isPowerOf2_32(NumBits))
2363 return S.Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2364 << ForMatrixType;
2365 return false;
2366}
2367
2369 SourceLocation AttrLoc) {
2370 // The base type must be integer (not Boolean or enumeration) or float, and
2371 // can't already be a vector.
2372 if ((!CurType->isDependentType() &&
2373 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2374 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) &&
2375 !CurType->isBitIntType()) ||
2376 CurType->isArrayType()) {
2377 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2378 return QualType();
2379 }
2380
2381 if (const auto *BIT = CurType->getAs<BitIntType>();
2382 BIT && CheckBitIntElementType(*this, AttrLoc, BIT))
2383 return QualType();
2384
2385 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2386 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2388
2389 std::optional<llvm::APSInt> VecSize =
2391 if (!VecSize) {
2392 Diag(AttrLoc, diag::err_attribute_argument_type)
2393 << "vector_size" << AANT_ArgumentIntegerConstant
2394 << SizeExpr->getSourceRange();
2395 return QualType();
2396 }
2397
2398 if (VecSize->isNegative()) {
2399 Diag(SizeExpr->getExprLoc(), diag::err_attribute_vec_negative_size);
2400 return QualType();
2401 }
2402
2403 if (CurType->isDependentType())
2404 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2406
2407 // vecSize is specified in bytes - convert to bits.
2408 if (!VecSize->isIntN(61)) {
2409 // Bit size will overflow uint64.
2410 Diag(AttrLoc, diag::err_attribute_size_too_large)
2411 << SizeExpr->getSourceRange() << "vector";
2412 return QualType();
2413 }
2414 uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2415 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2416
2417 if (VectorSizeBits == 0) {
2418 Diag(AttrLoc, diag::err_attribute_zero_size)
2419 << SizeExpr->getSourceRange() << "vector";
2420 return QualType();
2421 }
2422
2423 if (!TypeSize || VectorSizeBits % TypeSize) {
2424 Diag(AttrLoc, diag::err_attribute_invalid_size)
2425 << SizeExpr->getSourceRange();
2426 return QualType();
2427 }
2428
2429 if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2430 Diag(AttrLoc, diag::err_attribute_size_too_large)
2431 << SizeExpr->getSourceRange() << "vector";
2432 return QualType();
2433 }
2434
2435 return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2437}
2438
2440 SourceLocation AttrLoc) {
2441 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2442 // in conjunction with complex types (pointers, arrays, functions, etc.).
2443 //
2444 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2445 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2446 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2447 // of bool aren't allowed.
2448 //
2449 // We explicitly allow bool elements in ext_vector_type for C/C++.
2450 bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus;
2451 if ((!T->isDependentType() && !T->isIntegerType() &&
2452 !T->isRealFloatingType()) ||
2453 (IsNoBoolVecLang && T->isBooleanType())) {
2454 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2455 return QualType();
2456 }
2457
2458 if (const auto *BIT = T->getAs<BitIntType>();
2459 BIT && CheckBitIntElementType(*this, AttrLoc, BIT))
2460 return QualType();
2461
2462 if (!SizeExpr->isTypeDependent() && !SizeExpr->isValueDependent()) {
2463 std::optional<llvm::APSInt> VecSize =
2465 if (!VecSize) {
2466 Diag(AttrLoc, diag::err_attribute_argument_type)
2467 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2468 << SizeExpr->getSourceRange();
2469 return QualType();
2470 }
2471
2472 if (VecSize->isNegative()) {
2473 Diag(SizeExpr->getExprLoc(), diag::err_attribute_vec_negative_size);
2474 return QualType();
2475 }
2476
2477 if (!VecSize->isIntN(32)) {
2478 Diag(AttrLoc, diag::err_attribute_size_too_large)
2479 << SizeExpr->getSourceRange() << "vector";
2480 return QualType();
2481 }
2482 // Unlike gcc's vector_size attribute, the size is specified as the
2483 // number of elements, not the number of bytes.
2484 unsigned VectorSize = static_cast<unsigned>(VecSize->getZExtValue());
2485
2486 if (VectorSize == 0) {
2487 Diag(AttrLoc, diag::err_attribute_zero_size)
2488 << SizeExpr->getSourceRange() << "vector";
2489 return QualType();
2490 }
2491
2492 return Context.getExtVectorType(T, VectorSize);
2493 }
2494
2495 return Context.getDependentSizedExtVectorType(T, SizeExpr, AttrLoc);
2496}
2497
2498QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2499 SourceLocation AttrLoc) {
2500 assert(Context.getLangOpts().MatrixTypes &&
2501 "Should never build a matrix type when it is disabled");
2502
2503 // Check element type, if it is not dependent.
2504 if (!ElementTy->isDependentType() &&
2506 Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2507 return QualType();
2508 }
2509
2510 if (const auto *BIT = ElementTy->getAs<BitIntType>();
2511 BIT &&
2512 CheckBitIntElementType(*this, AttrLoc, BIT, /*ForMatrixType=*/true))
2513 return QualType();
2514
2515 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2516 NumRows->isValueDependent() || NumCols->isValueDependent())
2517 return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2518 AttrLoc);
2519
2520 std::optional<llvm::APSInt> ValueRows =
2522 std::optional<llvm::APSInt> ValueColumns =
2524
2525 auto const RowRange = NumRows->getSourceRange();
2526 auto const ColRange = NumCols->getSourceRange();
2527
2528 // Both are row and column expressions are invalid.
2529 if (!ValueRows && !ValueColumns) {
2530 Diag(AttrLoc, diag::err_attribute_argument_type)
2531 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2532 << ColRange;
2533 return QualType();
2534 }
2535
2536 // Only the row expression is invalid.
2537 if (!ValueRows) {
2538 Diag(AttrLoc, diag::err_attribute_argument_type)
2539 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2540 return QualType();
2541 }
2542
2543 // Only the column expression is invalid.
2544 if (!ValueColumns) {
2545 Diag(AttrLoc, diag::err_attribute_argument_type)
2546 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2547 return QualType();
2548 }
2549
2550 // Check the matrix dimensions.
2551 unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2552 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2553 if (MatrixRows == 0 && MatrixColumns == 0) {
2554 Diag(AttrLoc, diag::err_attribute_zero_size)
2555 << "matrix" << RowRange << ColRange;
2556 return QualType();
2557 }
2558 if (MatrixRows == 0) {
2559 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2560 return QualType();
2561 }
2562 if (MatrixColumns == 0) {
2563 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2564 return QualType();
2565 }
2566 if (MatrixRows > Context.getLangOpts().MaxMatrixDimension &&
2567 MatrixColumns > Context.getLangOpts().MaxMatrixDimension) {
2568 Diag(AttrLoc, diag::err_attribute_size_too_large)
2569 << RowRange << ColRange << "matrix row and column";
2570 return QualType();
2571 }
2572 if (MatrixRows > Context.getLangOpts().MaxMatrixDimension) {
2573 Diag(AttrLoc, diag::err_attribute_size_too_large)
2574 << RowRange << "matrix row";
2575 return QualType();
2576 }
2577 if (MatrixColumns > Context.getLangOpts().MaxMatrixDimension) {
2578 Diag(AttrLoc, diag::err_attribute_size_too_large)
2579 << ColRange << "matrix column";
2580 return QualType();
2581 }
2582 return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2583}
2584
2586 if ((T->isArrayType() && !getLangOpts().allowArrayReturnTypes()) ||
2587 T->isFunctionType()) {
2588 Diag(Loc, diag::err_func_returning_array_function)
2589 << T->isFunctionType() << T;
2590 return true;
2591 }
2592
2593 // Functions cannot return half FP.
2594 if (T->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2595 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2596 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2598 return true;
2599 }
2600
2601 // Methods cannot return interface types. All ObjC objects are
2602 // passed by reference.
2603 if (T->isObjCObjectType()) {
2604 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2605 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2606 return true;
2607 }
2608
2609 // __ptrauth is illegal on a function return type.
2610 if (T.getPointerAuth()) {
2611 Diag(Loc, diag::err_ptrauth_qualifier_invalid) << T << 0;
2612 return true;
2613 }
2614
2615 if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2616 T.hasNonTrivialToPrimitiveCopyCUnion())
2619
2620 // C++2a [dcl.fct]p12:
2621 // A volatile-qualified return type is deprecated
2622 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2623 Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2624
2625 if (T.getAddressSpace() != LangAS::Default && getLangOpts().HLSL)
2626 return true;
2627 return false;
2628}
2629
2630/// Check the extended parameter information. Most of the necessary
2631/// checking should occur when applying the parameter attribute; the
2632/// only other checks required are positional restrictions.
2635 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2636 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2637
2638 bool emittedError = false;
2639 auto actualCC = EPI.ExtInfo.getCC();
2640 enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
2641 auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
2642 bool isCompatible =
2643 (required == RequiredCC::OnlySwift)
2644 ? (actualCC == CC_Swift)
2645 : (actualCC == CC_Swift || actualCC == CC_SwiftAsync);
2646 if (isCompatible || emittedError)
2647 return;
2648 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2650 << (required == RequiredCC::OnlySwift);
2651 emittedError = true;
2652 };
2653 for (size_t paramIndex = 0, numParams = paramTypes.size();
2654 paramIndex != numParams; ++paramIndex) {
2655 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2656 // Nothing interesting to check for orindary-ABI parameters.
2660 continue;
2661
2662 // swift_indirect_result parameters must be a prefix of the function
2663 // arguments.
2665 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2666 if (paramIndex != 0 &&
2667 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2669 S.Diag(getParamLoc(paramIndex),
2670 diag::err_swift_indirect_result_not_first);
2671 }
2672 continue;
2673
2675 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2676 continue;
2677
2678 // SwiftAsyncContext is not limited to swiftasynccall functions.
2680 continue;
2681
2682 // swift_error parameters must be preceded by a swift_context parameter.
2684 checkCompatible(paramIndex, RequiredCC::OnlySwift);
2685 if (paramIndex == 0 ||
2686 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2688 S.Diag(getParamLoc(paramIndex),
2689 diag::err_swift_error_result_not_after_swift_context);
2690 }
2691 continue;
2692 }
2693 llvm_unreachable("bad ABI kind");
2694 }
2695}
2696
2698 MutableArrayRef<QualType> ParamTypes,
2699 SourceLocation Loc, DeclarationName Entity,
2701 bool Invalid = false;
2702
2704
2705 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2706 // FIXME: Loc is too inprecise here, should use proper locations for args.
2707 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2708 if (ParamType->isVoidType()) {
2709 Diag(Loc, diag::err_param_with_void_type);
2710 Invalid = true;
2711 } else if (ParamType->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2712 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2713 // Disallow half FP arguments.
2714 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2716 Invalid = true;
2717 } else if (ParamType->isWebAssemblyTableType()) {
2718 Diag(Loc, diag::err_wasm_table_as_function_parameter);
2719 Invalid = true;
2720 } else if (ParamType.getPointerAuth()) {
2721 // __ptrauth is illegal on a function return type.
2722 Diag(Loc, diag::err_ptrauth_qualifier_invalid) << T << 1;
2723 Invalid = true;
2724 }
2725
2726 // C++2a [dcl.fct]p4:
2727 // A parameter with volatile-qualified type is deprecated
2728 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
2729 Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
2730
2731 ParamTypes[Idx] = ParamType;
2732 }
2733
2734 if (EPI.ExtParameterInfos) {
2735 checkExtParameterInfos(*this, ParamTypes, EPI,
2736 [=](unsigned i) { return Loc; });
2737 }
2738
2739 if (EPI.ExtInfo.getProducesResult()) {
2740 // This is just a warning, so we can't fail to build if we see it.
2742 }
2743
2744 if (Invalid)
2745 return QualType();
2746
2747 return Context.getFunctionType(T, ParamTypes, EPI);
2748}
2749
2751 CXXRecordDecl *Cls, SourceLocation Loc,
2752 DeclarationName Entity) {
2753 if (!Cls && !isDependentScopeSpecifier(SS)) {
2754 Cls = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS));
2755 if (!Cls) {
2756 auto D =
2757 Diag(SS.getBeginLoc(), diag::err_illegal_decl_mempointer_in_nonclass)
2758 << SS.getRange();
2759 if (const IdentifierInfo *II = Entity.getAsIdentifierInfo())
2760 D << II;
2761 else
2762 D << "member pointer";
2763 return QualType();
2764 }
2765 }
2766
2767 // Verify that we're not building a pointer to pointer to function with
2768 // exception specification.
2770 Diag(Loc, diag::err_distant_exception_spec);
2771 return QualType();
2772 }
2773
2774 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2775 // with reference type, or "cv void."
2776 if (T->isReferenceType()) {
2777 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2778 << getPrintableNameForEntity(Entity) << T;
2779 return QualType();
2780 }
2781
2782 if (T->isVoidType()) {
2783 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2784 << getPrintableNameForEntity(Entity);
2785 return QualType();
2786 }
2787
2788 if (T->isFunctionType() && getLangOpts().OpenCL &&
2789 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2790 getLangOpts())) {
2791 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2792 return QualType();
2793 }
2794
2795 if (getLangOpts().HLSL && Loc.isValid()) {
2796 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
2797 return QualType();
2798 }
2799
2800 // Adjust the default free function calling convention to the default method
2801 // calling convention.
2802 bool IsCtorOrDtor =
2805 if (T->isFunctionType())
2806 adjustMemberFunctionCC(T, /*HasThisPointer=*/true, IsCtorOrDtor, Loc);
2807
2808 return Context.getMemberPointerType(T, SS.getScopeRep(), Cls);
2809}
2810
2812 SourceLocation Loc,
2813 DeclarationName Entity) {
2814 if (!T->isFunctionType()) {
2815 Diag(Loc, diag::err_nonfunction_block_type);
2816 return QualType();
2817 }
2818
2819 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2820 return QualType();
2821
2822 if (getLangOpts().OpenCL)
2823 T = deduceOpenCLPointeeAddrSpace(*this, T);
2824
2825 return Context.getBlockPointerType(T);
2826}
2827
2829 QualType QT = Ty.get();
2830 if (QT.isNull()) {
2831 if (TInfo) *TInfo = nullptr;
2832 return QualType();
2833 }
2834
2835 TypeSourceInfo *TSI = nullptr;
2836 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2837 QT = LIT->getType();
2838 TSI = LIT->getTypeSourceInfo();
2839 }
2840
2841 if (TInfo)
2842 *TInfo = TSI;
2843 return QT;
2844}
2845
2846static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2847 Qualifiers::ObjCLifetime ownership,
2848 unsigned chunkIndex);
2849
2850/// Given that this is the declaration of a parameter under ARC,
2851/// attempt to infer attributes and such for pointer-to-whatever
2852/// types.
2853static void inferARCWriteback(TypeProcessingState &state,
2854 QualType &declSpecType) {
2855 Sema &S = state.getSema();
2856 Declarator &declarator = state.getDeclarator();
2857
2858 // TODO: should we care about decl qualifiers?
2859
2860 // Check whether the declarator has the expected form. We walk
2861 // from the inside out in order to make the block logic work.
2862 unsigned outermostPointerIndex = 0;
2863 bool isBlockPointer = false;
2864 unsigned numPointers = 0;
2865 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2866 unsigned chunkIndex = i;
2867 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2868 switch (chunk.Kind) {
2870 // Ignore parens.
2871 break;
2872
2875 // Count the number of pointers. Treat references
2876 // interchangeably as pointers; if they're mis-ordered, normal
2877 // type building will discover that.
2878 outermostPointerIndex = chunkIndex;
2879 numPointers++;
2880 break;
2881
2883 // If we have a pointer to block pointer, that's an acceptable
2884 // indirect reference; anything else is not an application of
2885 // the rules.
2886 if (numPointers != 1) return;
2887 numPointers++;
2888 outermostPointerIndex = chunkIndex;
2889 isBlockPointer = true;
2890
2891 // We don't care about pointer structure in return values here.
2892 goto done;
2893
2894 case DeclaratorChunk::Array: // suppress if written (id[])?
2898 return;
2899 }
2900 }
2901 done:
2902
2903 // If we have *one* pointer, then we want to throw the qualifier on
2904 // the declaration-specifiers, which means that it needs to be a
2905 // retainable object type.
2906 if (numPointers == 1) {
2907 // If it's not a retainable object type, the rule doesn't apply.
2908 if (!declSpecType->isObjCRetainableType()) return;
2909
2910 // If it already has lifetime, don't do anything.
2911 if (declSpecType.getObjCLifetime()) return;
2912
2913 // Otherwise, modify the type in-place.
2914 Qualifiers qs;
2915
2916 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2918 else
2920 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2921
2922 // If we have *two* pointers, then we want to throw the qualifier on
2923 // the outermost pointer.
2924 } else if (numPointers == 2) {
2925 // If we don't have a block pointer, we need to check whether the
2926 // declaration-specifiers gave us something that will turn into a
2927 // retainable object pointer after we slap the first pointer on it.
2928 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2929 return;
2930
2931 // Look for an explicit lifetime attribute there.
2932 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2933 if (chunk.Kind != DeclaratorChunk::Pointer &&
2935 return;
2936 for (const ParsedAttr &AL : chunk.getAttrs())
2937 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
2938 return;
2939
2941 outermostPointerIndex);
2942
2943 // Any other number of pointers/references does not trigger the rule.
2944 } else return;
2945
2946 // TODO: mark whether we did this inference?
2947}
2948
2949void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2950 SourceLocation FallbackLoc,
2951 SourceLocation ConstQualLoc,
2952 SourceLocation VolatileQualLoc,
2953 SourceLocation RestrictQualLoc,
2954 SourceLocation AtomicQualLoc,
2955 SourceLocation UnalignedQualLoc) {
2956 if (!Quals)
2957 return;
2958
2959 struct Qual {
2960 const char *Name;
2961 unsigned Mask;
2962 SourceLocation Loc;
2963 } const QualKinds[5] = {
2964 { "const", DeclSpec::TQ_const, ConstQualLoc },
2965 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2966 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2967 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2968 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2969 };
2970
2971 SmallString<32> QualStr;
2972 unsigned NumQuals = 0;
2973 SourceLocation Loc;
2974 FixItHint FixIts[5];
2975
2976 // Build a string naming the redundant qualifiers.
2977 for (auto &E : QualKinds) {
2978 if (Quals & E.Mask) {
2979 if (!QualStr.empty()) QualStr += ' ';
2980 QualStr += E.Name;
2981
2982 // If we have a location for the qualifier, offer a fixit.
2983 SourceLocation QualLoc = E.Loc;
2984 if (QualLoc.isValid()) {
2985 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2986 if (Loc.isInvalid() ||
2987 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2988 Loc = QualLoc;
2989 }
2990
2991 ++NumQuals;
2992 }
2993 }
2994
2995 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2996 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2997}
2998
2999// Diagnose pointless type qualifiers on the return type of a function.
3001 Declarator &D,
3002 unsigned FunctionChunkIndex) {
3004 D.getTypeObject(FunctionChunkIndex).Fun;
3005 if (FTI.hasTrailingReturnType()) {
3006 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3007 RetTy.getLocalCVRQualifiers(),
3009 return;
3010 }
3011
3012 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3013 End = D.getNumTypeObjects();
3014 OuterChunkIndex != End; ++OuterChunkIndex) {
3015 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
3016 switch (OuterChunk.Kind) {
3018 continue;
3019
3021 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3023 diag::warn_qual_return_type,
3024 PTI.TypeQuals,
3026 PTI.ConstQualLoc,
3027 PTI.VolatileQualLoc,
3028 PTI.RestrictQualLoc,
3029 PTI.AtomicQualLoc,
3030 PTI.UnalignedQualLoc);
3031 return;
3032 }
3033
3040 // FIXME: We can't currently provide an accurate source location and a
3041 // fix-it hint for these.
3042 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
3043 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3044 RetTy.getCVRQualifiers() | AtomicQual,
3045 D.getIdentifierLoc());
3046 return;
3047 }
3048
3049 llvm_unreachable("unknown declarator chunk kind");
3050 }
3051
3052 // If the qualifiers come from a conversion function type, don't diagnose
3053 // them -- they're not necessarily redundant, since such a conversion
3054 // operator can be explicitly called as "x.operator const int()".
3056 return;
3057
3058 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3059 // which are present there.
3060 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3062 D.getIdentifierLoc(),
3068}
3069
3070static std::pair<QualType, TypeSourceInfo *>
3071InventTemplateParameter(TypeProcessingState &state, QualType T,
3072 TypeSourceInfo *TrailingTSI, AutoType *Auto,
3074 Sema &S = state.getSema();
3075 Declarator &D = state.getDeclarator();
3076
3077 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3078 const unsigned AutoParameterPosition = Info.TemplateParams.size();
3079 const bool IsParameterPack = D.hasEllipsis();
3080
3081 // If auto is mentioned in a lambda parameter or abbreviated function
3082 // template context, convert it to a template parameter type.
3083
3084 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3085 // template parameter type. Template parameters are temporarily added
3086 // to the TU until the associated TemplateDecl is created.
3087 TemplateTypeParmDecl *InventedTemplateParam =
3090 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3091 /*NameLoc=*/D.getIdentifierLoc(),
3092 TemplateParameterDepth, AutoParameterPosition,
3094 D.getIdentifier(), AutoParameterPosition), false,
3095 IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3096 InventedTemplateParam->setImplicit();
3097 Info.TemplateParams.push_back(InventedTemplateParam);
3098
3099 // Attach type constraints to the new parameter.
3100 if (Auto->isConstrained()) {
3101 if (TrailingTSI) {
3102 // The 'auto' appears in a trailing return type we've already built;
3103 // extract its type constraints to attach to the template parameter.
3104 AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3105 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3106 bool Invalid = false;
3107 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3108 if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3111 Invalid = true;
3112 TAL.addArgument(AutoLoc.getArgLoc(Idx));
3113 }
3114
3115 if (!Invalid) {
3117 AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3118 AutoLoc.getNamedConcept(), /*FoundDecl=*/AutoLoc.getFoundDecl(),
3119 AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3120 InventedTemplateParam, D.getEllipsisLoc());
3121 }
3122 } else {
3123 // The 'auto' appears in the decl-specifiers; we've not finished forming
3124 // TypeSourceInfo for it yet.
3126 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
3127 TemplateId->RAngleLoc);
3128 bool Invalid = false;
3129 if (TemplateId->LAngleLoc.isValid()) {
3130 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3131 TemplateId->NumArgs);
3132 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3133
3134 if (D.getEllipsisLoc().isInvalid()) {
3135 for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3138 Invalid = true;
3139 break;
3140 }
3141 }
3142 }
3143 }
3144 if (!Invalid) {
3145 UsingShadowDecl *USD =
3146 TemplateId->Template.get().getAsUsingShadowDecl();
3147 TemplateDecl *CD = TemplateId->Template.get().getAsTemplateDecl();
3151 TemplateId->TemplateNameLoc),
3152 CD,
3153 /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
3154 TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3155 InventedTemplateParam, D.getEllipsisLoc());
3156 }
3157 }
3158 }
3159
3160 // Replace the 'auto' in the function parameter with this invented
3161 // template type parameter.
3162 // FIXME: Retain some type sugar to indicate that this was written
3163 // as 'auto'?
3164 QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3165 QualType NewT = state.ReplaceAutoType(T, Replacement);
3166 TypeSourceInfo *NewTSI =
3167 TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)
3168 : nullptr;
3169 return {NewT, NewTSI};
3170}
3171
3172static TypeSourceInfo *
3173GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3174 QualType T, TypeSourceInfo *ReturnTypeInfo);
3175
3176static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3177 TypeSourceInfo *&ReturnTypeInfo) {
3178 Sema &SemaRef = state.getSema();
3179 Declarator &D = state.getDeclarator();
3180 QualType T;
3181 ReturnTypeInfo = nullptr;
3182
3183 // The TagDecl owned by the DeclSpec.
3184 TagDecl *OwnedTagDecl = nullptr;
3185
3186 switch (D.getName().getKind()) {
3192 T = ConvertDeclSpecToType(state);
3193
3194 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3195 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3196 // Owned declaration is embedded in declarator.
3197 OwnedTagDecl->setEmbeddedInDeclarator(true);
3198 }
3199 break;
3200
3204 // Constructors and destructors don't have return types. Use
3205 // "void" instead.
3206 T = SemaRef.Context.VoidTy;
3209 break;
3210
3212 // Deduction guides have a trailing return type and no type in their
3213 // decl-specifier sequence. Use a placeholder return type for now.
3214 T = SemaRef.Context.DependentTy;
3215 break;
3216
3218 // The result type of a conversion function is the type that it
3219 // converts to.
3221 &ReturnTypeInfo);
3222 break;
3223 }
3224
3225 // Note: We don't need to distribute declaration attributes (i.e.
3226 // D.getDeclarationAttributes()) because those are always C++11 attributes,
3227 // and those don't get distributed.
3229 state, T, SemaRef.CUDA().IdentifyTarget(D.getAttributes()));
3230
3231 // Find the deduced type in this type. Look in the trailing return type if we
3232 // have one, otherwise in the DeclSpec type.
3233 // FIXME: The standard wording doesn't currently describe this.
3234 DeducedType *Deduced = T->getContainedDeducedType();
3235 bool DeducedIsTrailingReturnType = false;
3236 if (Deduced && isa<AutoType>(Deduced) && D.hasTrailingReturnType()) {
3238 Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3239 DeducedIsTrailingReturnType = true;
3240 }
3241
3242 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3243 if (Deduced) {
3244 AutoType *Auto = dyn_cast<AutoType>(Deduced);
3245 int Error = -1;
3246
3247 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3248 // class template argument deduction)?
3249 bool IsCXXAutoType =
3250 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3251 bool IsDeducedReturnType = false;
3252
3253 switch (D.getContext()) {
3255 // Declared return type of a lambda-declarator is implicit and is always
3256 // 'auto'.
3257 break;
3260 Error = 0;
3261 break;
3263 Error = 22;
3264 break;
3267 InventedTemplateParameterInfo *Info = nullptr;
3269 // With concepts we allow 'auto' in function parameters.
3270 if (!SemaRef.getLangOpts().CPlusPlus20 || !Auto ||
3271 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3272 Error = 0;
3273 break;
3274 } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3275 Error = 21;
3276 break;
3277 }
3278
3279 Info = &SemaRef.InventedParameterInfos.back();
3280 } else {
3281 // In C++14, generic lambdas allow 'auto' in their parameters.
3282 if (!SemaRef.getLangOpts().CPlusPlus14 && Auto &&
3283 Auto->getKeyword() == AutoTypeKeyword::Auto) {
3284 Error = 25; // auto not allowed in lambda parameter (before C++14)
3285 break;
3286 } else if (!Auto || Auto->getKeyword() != AutoTypeKeyword::Auto) {
3287 Error = 16; // __auto_type or decltype(auto) not allowed in lambda
3288 // parameter
3289 break;
3290 }
3291 Info = SemaRef.getCurLambda();
3292 assert(Info && "No LambdaScopeInfo on the stack!");
3293 }
3294
3295 // We'll deal with inventing template parameters for 'auto' in trailing
3296 // return types when we pick up the trailing return type when processing
3297 // the function chunk.
3298 if (!DeducedIsTrailingReturnType)
3299 T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3300 break;
3301 }
3303 if (D.isStaticMember() || D.isFunctionDeclarator())
3304 break;
3305 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3306 if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3307 Error = 6; // Interface member.
3308 } else {
3309 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3310 case TagTypeKind::Enum:
3311 llvm_unreachable("unhandled tag kind");
3313 Error = Cxx ? 1 : 2; /* Struct member */
3314 break;
3315 case TagTypeKind::Union:
3316 Error = Cxx ? 3 : 4; /* Union member */
3317 break;
3318 case TagTypeKind::Class:
3319 Error = 5; /* Class member */
3320 break;
3322 Error = 6; /* Interface member */
3323 break;
3324 }
3325 }
3327 Error = 20; // Friend type
3328 break;
3329 }
3332 Error = 7; // Exception declaration
3333 break;
3336 !SemaRef.getLangOpts().CPlusPlus20)
3337 Error = 19; // Template parameter (until C++20)
3338 else if (!SemaRef.getLangOpts().CPlusPlus17)
3339 Error = 8; // Template parameter (until C++17)
3340 break;
3342 Error = 9; // Block literal
3343 break;
3345 // Within a template argument list, a deduced template specialization
3346 // type will be reinterpreted as a template template argument.
3348 !D.getNumTypeObjects() &&
3350 break;
3351 [[fallthrough]];
3353 Error = 10; // Template type argument
3354 break;
3357 Error = 12; // Type alias
3358 break;
3361 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3362 Error = 13; // Function return type
3363 IsDeducedReturnType = true;
3364 break;
3366 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3367 Error = 14; // conversion-type-id
3368 IsDeducedReturnType = true;
3369 break;
3372 break;
3373 if (SemaRef.getLangOpts().CPlusPlus23 && IsCXXAutoType &&
3374 !Auto->isDecltypeAuto())
3375 break; // auto(x)
3376 [[fallthrough]];
3379 Error = 15; // Generic
3380 break;
3386 // FIXME: P0091R3 (erroneously) does not permit class template argument
3387 // deduction in conditions, for-init-statements, and other declarations
3388 // that are not simple-declarations.
3389 break;
3391 // FIXME: P0091R3 does not permit class template argument deduction here,
3392 // but we follow GCC and allow it anyway.
3393 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3394 Error = 17; // 'new' type
3395 break;
3397 Error = 18; // K&R function parameter
3398 break;
3399 }
3400
3402 Error = 11;
3403
3404 // In Objective-C it is an error to use 'auto' on a function declarator
3405 // (and everywhere for '__auto_type').
3406 if (D.isFunctionDeclarator() &&
3407 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3408 Error = 13;
3409
3410 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3412 AutoRange = D.getName().getSourceRange();
3413
3414 if (Error != -1) {
3415 unsigned Kind;
3416 if (Auto) {
3417 switch (Auto->getKeyword()) {
3418 case AutoTypeKeyword::Auto: Kind = 0; break;
3419 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3420 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3421 }
3422 } else {
3424 "unknown auto type");
3425 Kind = 3;
3426 }
3427
3428 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3429 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3430
3431 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3432 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3433 << QualType(Deduced, 0) << AutoRange;
3434 if (auto *TD = TN.getAsTemplateDecl())
3435 SemaRef.NoteTemplateLocation(*TD);
3436
3437 T = SemaRef.Context.IntTy;
3438 D.setInvalidType(true);
3439 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) {
3440 // If there was a trailing return type, we already got
3441 // warn_cxx98_compat_trailing_return_type in the parser.
3442 // If there was a decltype(auto), we already got
3443 // warn_cxx11_compat_decltype_auto_type_specifier.
3444 unsigned DiagId = 0;
3446 DiagId = diag::warn_cxx11_compat_generic_lambda;
3447 else if (IsDeducedReturnType)
3448 DiagId = diag::warn_cxx11_compat_deduced_return_type;
3449 else if (Auto->getKeyword() == AutoTypeKeyword::Auto)
3450 DiagId = diag::warn_cxx98_compat_auto_type_specifier;
3451
3452 if (DiagId)
3453 SemaRef.Diag(AutoRange.getBegin(), DiagId) << AutoRange;
3454 }
3455 }
3456
3457 if (SemaRef.getLangOpts().CPlusPlus &&
3458 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3459 // Check the contexts where C++ forbids the declaration of a new class
3460 // or enumeration in a type-specifier-seq.
3461 unsigned DiagID = 0;
3462 switch (D.getContext()) {
3465 // Class and enumeration definitions are syntactically not allowed in
3466 // trailing return types.
3467 llvm_unreachable("parser should not have allowed this");
3468 break;
3476 // C++11 [dcl.type]p3:
3477 // A type-specifier-seq shall not define a class or enumeration unless
3478 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3479 // the declaration of a template-declaration.
3481 break;
3483 DiagID = diag::err_type_defined_in_alias_template;
3484 break;
3495 DiagID = diag::err_type_defined_in_type_specifier;
3496 break;
3503 // C++ [dcl.fct]p6:
3504 // Types shall not be defined in return or parameter types.
3505 DiagID = diag::err_type_defined_in_param_type;
3506 break;
3508 // C++ 6.4p2:
3509 // The type-specifier-seq shall not contain typedef and shall not declare
3510 // a new class or enumeration.
3511 DiagID = diag::err_type_defined_in_condition;
3512 break;
3513 }
3514
3515 if (DiagID != 0) {
3516 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3517 << SemaRef.Context.getCanonicalTagType(OwnedTagDecl);
3518 D.setInvalidType(true);
3519 }
3520 }
3521
3522 assert(!T.isNull() && "This function should not return a null type");
3523 return T;
3524}
3525
3526/// Produce an appropriate diagnostic for an ambiguity between a function
3527/// declarator and a C++ direct-initializer.
3529 DeclaratorChunk &DeclType, QualType RT) {
3530 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3531 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3532
3533 // If the return type is void there is no ambiguity.
3534 if (RT->isVoidType())
3535 return;
3536
3537 // An initializer for a non-class type can have at most one argument.
3538 if (!RT->isRecordType() && FTI.NumParams > 1)
3539 return;
3540
3541 // An initializer for a reference must have exactly one argument.
3542 if (RT->isReferenceType() && FTI.NumParams != 1)
3543 return;
3544
3545 // Only warn if this declarator is declaring a function at block scope, and
3546 // doesn't have a storage class (such as 'extern') specified.
3547 if (!D.isFunctionDeclarator() ||
3551 return;
3552
3553 // Inside a condition, a direct initializer is not permitted. We allow one to
3554 // be parsed in order to give better diagnostics in condition parsing.
3556 return;
3557
3558 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3559
3560 S.Diag(DeclType.Loc,
3561 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3562 : diag::warn_empty_parens_are_function_decl)
3563 << ParenRange;
3564
3565 // If the declaration looks like:
3566 // T var1,
3567 // f();
3568 // and name lookup finds a function named 'f', then the ',' was
3569 // probably intended to be a ';'.
3570 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3571 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3573 if (Comma.getFileID() != Name.getFileID() ||
3574 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3577 if (S.LookupName(Result, S.getCurScope()))
3578 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3580 << D.getIdentifier();
3581 Result.suppressDiagnostics();
3582 }
3583 }
3584
3585 if (FTI.NumParams > 0) {
3586 // For a declaration with parameters, eg. "T var(T());", suggest adding
3587 // parens around the first parameter to turn the declaration into a
3588 // variable declaration.
3589 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3590 SourceLocation B = Range.getBegin();
3591 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3592 // FIXME: Maybe we should suggest adding braces instead of parens
3593 // in C++11 for classes that don't have an initializer_list constructor.
3594 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3596 << FixItHint::CreateInsertion(E, ")");
3597 } else {
3598 // For a declaration without parameters, eg. "T var();", suggest replacing
3599 // the parens with an initializer to turn the declaration into a variable
3600 // declaration.
3601 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3602
3603 // Empty parens mean value-initialization, and no parens mean
3604 // default initialization. These are equivalent if the default
3605 // constructor is user-provided or if zero-initialization is a
3606 // no-op.
3607 if (RD && RD->hasDefinition() &&
3609 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3610 << FixItHint::CreateRemoval(ParenRange);
3611 else {
3612 std::string Init =
3613 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3614 if (Init.empty() && S.LangOpts.CPlusPlus11)
3615 Init = "{}";
3616 if (!Init.empty())
3617 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3618 << FixItHint::CreateReplacement(ParenRange, Init);
3619 }
3620 }
3621}
3622
3623/// Produce an appropriate diagnostic for a declarator with top-level
3624/// parentheses.
3627 assert(Paren.Kind == DeclaratorChunk::Paren &&
3628 "do not have redundant top-level parentheses");
3629
3630 // This is a syntactic check; we're not interested in cases that arise
3631 // during template instantiation.
3633 return;
3634
3635 // Check whether this could be intended to be a construction of a temporary
3636 // object in C++ via a function-style cast.
3637 bool CouldBeTemporaryObject =
3638 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3639 !D.isInvalidType() && D.getIdentifier() &&
3641 (T->isRecordType() || T->isDependentType()) &&
3643
3644 bool StartsWithDeclaratorId = true;
3645 for (auto &C : D.type_objects()) {
3646 switch (C.Kind) {
3648 if (&C == &Paren)
3649 continue;
3650 [[fallthrough]];
3652 StartsWithDeclaratorId = false;
3653 continue;
3654
3656 if (!C.Arr.NumElts)
3657 CouldBeTemporaryObject = false;
3658 continue;
3659
3661 // FIXME: Suppress the warning here if there is no initializer; we're
3662 // going to give an error anyway.
3663 // We assume that something like 'T (&x) = y;' is highly likely to not
3664 // be intended to be a temporary object.
3665 CouldBeTemporaryObject = false;
3666 StartsWithDeclaratorId = false;
3667 continue;
3668
3670 // In a new-type-id, function chunks require parentheses.
3672 return;
3673 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3674 // redundant-parens warning, but we don't know whether the function
3675 // chunk was syntactically valid as an expression here.
3676 CouldBeTemporaryObject = false;
3677 continue;
3678
3682 // These cannot appear in expressions.
3683 CouldBeTemporaryObject = false;
3684 StartsWithDeclaratorId = false;
3685 continue;
3686 }
3687 }
3688
3689 // FIXME: If there is an initializer, assume that this is not intended to be
3690 // a construction of a temporary object.
3691
3692 // Check whether the name has already been declared; if not, this is not a
3693 // function-style cast.
3694 if (CouldBeTemporaryObject) {
3697 if (!S.LookupName(Result, S.getCurScope()))
3698 CouldBeTemporaryObject = false;
3699 Result.suppressDiagnostics();
3700 }
3701
3702 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3703
3704 if (!CouldBeTemporaryObject) {
3705 // If we have A (::B), the parentheses affect the meaning of the program.
3706 // Suppress the warning in that case. Don't bother looking at the DeclSpec
3707 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3708 // formally unambiguous.
3709 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3711 for (;;) {
3712 switch (NNS.getKind()) {
3714 return;
3716 NNS = NNS.getAsType()->getPrefix();
3717 continue;
3719 NNS = NNS.getAsNamespaceAndPrefix().Prefix;
3720 continue;
3721 default:
3722 goto out;
3723 }
3724 }
3725 out:;
3726 }
3727
3728 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3729 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3731 return;
3732 }
3733
3734 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3735 << ParenRange << D.getIdentifier();
3736 auto *RD = T->getAsCXXRecordDecl();
3737 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3738 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3739 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3740 << D.getIdentifier();
3741 // FIXME: A cast to void is probably a better suggestion in cases where it's
3742 // valid (when there is no initializer and we're not in a condition).
3743 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3746 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3749}
3750
3751/// Helper for figuring out the default CC for a function declarator type. If
3752/// this is the outermost chunk, then we can determine the CC from the
3753/// declarator context. If not, then this could be either a member function
3754/// type or normal function type.
3756 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3757 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3758 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3759
3760 // Check for an explicit CC attribute.
3761 for (const ParsedAttr &AL : AttrList) {
3762 switch (AL.getKind()) {
3764 // Ignore attributes that don't validate or can't apply to the
3765 // function type. We'll diagnose the failure to apply them in
3766 // handleFunctionTypeAttr.
3767 CallingConv CC;
3768 if (!S.CheckCallingConvAttr(AL, CC, /*FunctionDecl=*/nullptr,
3769 S.CUDA().IdentifyTarget(D.getAttributes())) &&
3770 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3771 return CC;
3772 }
3773 break;
3774 }
3775
3776 default:
3777 break;
3778 }
3779 }
3780
3781 bool IsCXXInstanceMethod = false;
3782
3783 if (S.getLangOpts().CPlusPlus) {
3784 // Look inwards through parentheses to see if this chunk will form a
3785 // member pointer type or if we're the declarator. Any type attributes
3786 // between here and there will override the CC we choose here.
3787 unsigned I = ChunkIndex;
3788 bool FoundNonParen = false;
3789 while (I && !FoundNonParen) {
3790 --I;
3792 FoundNonParen = true;
3793 }
3794
3795 if (FoundNonParen) {
3796 // If we're not the declarator, we're a regular function type unless we're
3797 // in a member pointer.
3798 IsCXXInstanceMethod =
3800 } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
3801 // This can only be a call operator for a lambda, which is an instance
3802 // method, unless explicitly specified as 'static'.
3803 IsCXXInstanceMethod =
3805 } else {
3806 // We're the innermost decl chunk, so must be a function declarator.
3807 assert(D.isFunctionDeclarator());
3808
3809 // If we're inside a record, we're declaring a method, but it could be
3810 // explicitly or implicitly static.
3811 IsCXXInstanceMethod =
3814 !D.isStaticMember();
3815 }
3816 }
3817
3819 IsCXXInstanceMethod);
3820
3821 if (S.getLangOpts().CUDA) {
3822 // If we're compiling CUDA/HIP code and targeting HIPSPV we need to make
3823 // sure the kernels will be marked with the right calling convention so that
3824 // they will be visible by the APIs that ingest SPIR-V. We do not do this
3825 // when targeting AMDGCNSPIRV, as it does not rely on OpenCL.
3826 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
3827 if (Triple.isSPIRV() && Triple.getVendor() != llvm::Triple::AMD) {
3828 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3829 if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) {
3830 CC = CC_DeviceKernel;
3831 break;
3832 }
3833 }
3834 }
3835 }
3836
3837 for (const ParsedAttr &AL : llvm::concat<ParsedAttr>(
3840 if (AL.getKind() == ParsedAttr::AT_DeviceKernel) {
3841 CC = CC_DeviceKernel;
3842 break;
3843 }
3844 }
3845 return CC;
3846}
3847
3848namespace {
3849 /// A simple notion of pointer kinds, which matches up with the various
3850 /// pointer declarators.
3851 enum class SimplePointerKind {
3852 Pointer,
3853 BlockPointer,
3854 MemberPointer,
3855 Array,
3856 };
3857} // end anonymous namespace
3858
3860 switch (nullability) {
3862 if (!Ident__Nonnull)
3863 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3864 return Ident__Nonnull;
3865
3867 if (!Ident__Nullable)
3868 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3869 return Ident__Nullable;
3870
3872 if (!Ident__Nullable_result)
3873 Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
3874 return Ident__Nullable_result;
3875
3877 if (!Ident__Null_unspecified)
3878 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3879 return Ident__Null_unspecified;
3880 }
3881 llvm_unreachable("Unknown nullability kind.");
3882}
3883
3884/// Check whether there is a nullability attribute of any kind in the given
3885/// attribute list.
3886static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
3887 for (const ParsedAttr &AL : attrs) {
3888 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
3889 AL.getKind() == ParsedAttr::AT_TypeNullable ||
3890 AL.getKind() == ParsedAttr::AT_TypeNullableResult ||
3891 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
3892 return true;
3893 }
3894
3895 return false;
3896}
3897
3898namespace {
3899 /// Describes the kind of a pointer a declarator describes.
3900 enum class PointerDeclaratorKind {
3901 // Not a pointer.
3902 NonPointer,
3903 // Single-level pointer.
3904 SingleLevelPointer,
3905 // Multi-level pointer (of any pointer kind).
3906 MultiLevelPointer,
3907 // CFFooRef*
3908 MaybePointerToCFRef,
3909 // CFErrorRef*
3910 CFErrorRefPointer,
3911 // NSError**
3912 NSErrorPointerPointer,
3913 };
3914
3915 /// Describes a declarator chunk wrapping a pointer that marks inference as
3916 /// unexpected.
3917 // These values must be kept in sync with diagnostics.
3918 enum class PointerWrappingDeclaratorKind {
3919 /// Pointer is top-level.
3920 None = -1,
3921 /// Pointer is an array element.
3922 Array = 0,
3923 /// Pointer is the referent type of a C++ reference.
3924 Reference = 1
3925 };
3926} // end anonymous namespace
3927
3928/// Classify the given declarator, whose type-specified is \c type, based on
3929/// what kind of pointer it refers to.
3930///
3931/// This is used to determine the default nullability.
3932static PointerDeclaratorKind
3934 PointerWrappingDeclaratorKind &wrappingKind) {
3935 unsigned numNormalPointers = 0;
3936
3937 // For any dependent type, we consider it a non-pointer.
3938 if (type->isDependentType())
3939 return PointerDeclaratorKind::NonPointer;
3940
3941 // Look through the declarator chunks to identify pointers.
3942 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3943 DeclaratorChunk &chunk = declarator.getTypeObject(i);
3944 switch (chunk.Kind) {
3946 if (numNormalPointers == 0)
3947 wrappingKind = PointerWrappingDeclaratorKind::Array;
3948 break;
3949
3952 break;
3953
3956 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3957 : PointerDeclaratorKind::SingleLevelPointer;
3958
3960 break;
3961
3963 if (numNormalPointers == 0)
3964 wrappingKind = PointerWrappingDeclaratorKind::Reference;
3965 break;
3966
3968 ++numNormalPointers;
3969 if (numNormalPointers > 2)
3970 return PointerDeclaratorKind::MultiLevelPointer;
3971 break;
3972 }
3973 }
3974
3975 // Then, dig into the type specifier itself.
3976 unsigned numTypeSpecifierPointers = 0;
3977 do {
3978 // Decompose normal pointers.
3979 if (auto ptrType = type->getAs<PointerType>()) {
3980 ++numNormalPointers;
3981
3982 if (numNormalPointers > 2)
3983 return PointerDeclaratorKind::MultiLevelPointer;
3984
3985 type = ptrType->getPointeeType();
3986 ++numTypeSpecifierPointers;
3987 continue;
3988 }
3989
3990 // Decompose block pointers.
3991 if (type->getAs<BlockPointerType>()) {
3992 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3993 : PointerDeclaratorKind::SingleLevelPointer;
3994 }
3995
3996 // Decompose member pointers.
3997 if (type->getAs<MemberPointerType>()) {
3998 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3999 : PointerDeclaratorKind::SingleLevelPointer;
4000 }
4001
4002 // Look at Objective-C object pointers.
4003 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
4004 ++numNormalPointers;
4005 ++numTypeSpecifierPointers;
4006
4007 // If this is NSError**, report that.
4008 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
4009 if (objcClassDecl->getIdentifier() == S.ObjC().getNSErrorIdent() &&
4010 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
4011 return PointerDeclaratorKind::NSErrorPointerPointer;
4012 }
4013 }
4014
4015 break;
4016 }
4017
4018 // Look at Objective-C class types.
4019 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
4020 if (objcClass->getInterface()->getIdentifier() ==
4021 S.ObjC().getNSErrorIdent()) {
4022 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
4023 return PointerDeclaratorKind::NSErrorPointerPointer;
4024 }
4025
4026 break;
4027 }
4028
4029 // If at this point we haven't seen a pointer, we won't see one.
4030 if (numNormalPointers == 0)
4031 return PointerDeclaratorKind::NonPointer;
4032
4033 if (auto *recordDecl = type->getAsRecordDecl()) {
4034 // If this is CFErrorRef*, report it as such.
4035 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 &&
4036 S.ObjC().isCFError(recordDecl)) {
4037 return PointerDeclaratorKind::CFErrorRefPointer;
4038 }
4039 break;
4040 }
4041
4042 break;
4043 } while (true);
4044
4045 switch (numNormalPointers) {
4046 case 0:
4047 return PointerDeclaratorKind::NonPointer;
4048
4049 case 1:
4050 return PointerDeclaratorKind::SingleLevelPointer;
4051
4052 case 2:
4053 return PointerDeclaratorKind::MaybePointerToCFRef;
4054
4055 default:
4056 return PointerDeclaratorKind::MultiLevelPointer;
4057 }
4058}
4059
4061 SourceLocation loc) {
4062 // If we're anywhere in a function, method, or closure context, don't perform
4063 // completeness checks.
4064 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
4065 if (ctx->isFunctionOrMethod())
4066 return FileID();
4067
4068 if (ctx->isFileContext())
4069 break;
4070 }
4071
4072 // We only care about the expansion location.
4073 loc = S.SourceMgr.getExpansionLoc(loc);
4074 FileID file = S.SourceMgr.getFileID(loc);
4075 if (file.isInvalid())
4076 return FileID();
4077
4078 // Retrieve file information.
4079 bool invalid = false;
4080 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4081 if (invalid || !sloc.isFile())
4082 return FileID();
4083
4084 // We don't want to perform completeness checks on the main file or in
4085 // system headers.
4086 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4087 if (fileInfo.getIncludeLoc().isInvalid())
4088 return FileID();
4089 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4091 return FileID();
4092 }
4093
4094 return file;
4095}
4096
4097/// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4098/// taking into account whitespace before and after.
4099template <typename DiagBuilderT>
4100static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4101 SourceLocation PointerLoc,
4102 NullabilityKind Nullability) {
4103 assert(PointerLoc.isValid());
4104 if (PointerLoc.isMacroID())
4105 return;
4106
4107 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4108 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4109 return;
4110
4111 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4112 if (!NextChar)
4113 return;
4114
4115 SmallString<32> InsertionTextBuf{" "};
4116 InsertionTextBuf += getNullabilitySpelling(Nullability);
4117 InsertionTextBuf += " ";
4118 StringRef InsertionText = InsertionTextBuf.str();
4119
4120 if (isWhitespace(*NextChar)) {
4121 InsertionText = InsertionText.drop_back();
4122 } else if (NextChar[-1] == '[') {
4123 if (NextChar[0] == ']')
4124 InsertionText = InsertionText.drop_back().drop_front();
4125 else
4126 InsertionText = InsertionText.drop_front();
4127 } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) &&
4128 !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) {
4129 InsertionText = InsertionText.drop_back().drop_front();
4130 }
4131
4132 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4133}
4134
4136 SimplePointerKind PointerKind,
4137 SourceLocation PointerLoc,
4138 SourceLocation PointerEndLoc) {
4139 assert(PointerLoc.isValid());
4140
4141 if (PointerKind == SimplePointerKind::Array) {
4142 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4143 } else {
4144 S.Diag(PointerLoc, diag::warn_nullability_missing)
4145 << static_cast<unsigned>(PointerKind);
4146 }
4147
4148 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4149 if (FixItLoc.isMacroID())
4150 return;
4151
4152 auto addFixIt = [&](NullabilityKind Nullability) {
4153 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4154 Diag << static_cast<unsigned>(Nullability);
4155 Diag << static_cast<unsigned>(PointerKind);
4156 fixItNullability(S, Diag, FixItLoc, Nullability);
4157 };
4158 addFixIt(NullabilityKind::Nullable);
4159 addFixIt(NullabilityKind::NonNull);
4160}
4161
4162/// Complains about missing nullability if the file containing \p pointerLoc
4163/// has other uses of nullability (either the keywords or the \c assume_nonnull
4164/// pragma).
4165///
4166/// If the file has \e not seen other uses of nullability, this particular
4167/// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4168static void
4169checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4170 SourceLocation pointerLoc,
4171 SourceLocation pointerEndLoc = SourceLocation()) {
4172 // Determine which file we're performing consistency checking for.
4173 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4174 if (file.isInvalid())
4175 return;
4176
4177 // If we haven't seen any type nullability in this file, we won't warn now
4178 // about anything.
4179 FileNullability &fileNullability = S.NullabilityMap[file];
4180 if (!fileNullability.SawTypeNullability) {
4181 // If this is the first pointer declarator in the file, and the appropriate
4182 // warning is on, record it in case we need to diagnose it retroactively.
4183 diag::kind diagKind;
4184 if (pointerKind == SimplePointerKind::Array)
4185 diagKind = diag::warn_nullability_missing_array;
4186 else
4187 diagKind = diag::warn_nullability_missing;
4188
4189 if (fileNullability.PointerLoc.isInvalid() &&
4190 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
4191 fileNullability.PointerLoc = pointerLoc;
4192 fileNullability.PointerEndLoc = pointerEndLoc;
4193 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4194 }
4195
4196 return;
4197 }
4198
4199 // Complain about missing nullability.
4200 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4201}
4202
4203/// Marks that a nullability feature has been used in the file containing
4204/// \p loc.
4205///
4206/// If this file already had pointer types in it that were missing nullability,
4207/// the first such instance is retroactively diagnosed.
4208///
4209/// \sa checkNullabilityConsistency
4212 if (file.isInvalid())
4213 return;
4214
4215 FileNullability &fileNullability = S.NullabilityMap[file];
4216 if (fileNullability.SawTypeNullability)
4217 return;
4218 fileNullability.SawTypeNullability = true;
4219
4220 // If we haven't seen any type nullability before, now we have. Retroactively
4221 // diagnose the first unannotated pointer, if there was one.
4222 if (fileNullability.PointerLoc.isInvalid())
4223 return;
4224
4225 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4227 fileNullability.PointerEndLoc);
4228}
4229
4230/// Returns true if any of the declarator chunks before \p endIndex include a
4231/// level of indirection: array, pointer, reference, or pointer-to-member.
4232///
4233/// Because declarator chunks are stored in outer-to-inner order, testing
4234/// every chunk before \p endIndex is testing all chunks that embed the current
4235/// chunk as part of their type.
4236///
4237/// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4238/// end index, in which case all chunks are tested.
4239static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4240 unsigned i = endIndex;
4241 while (i != 0) {
4242 // Walk outwards along the declarator chunks.
4243 --i;
4244 const DeclaratorChunk &DC = D.getTypeObject(i);
4245 switch (DC.Kind) {
4247 break;
4252 return true;
4256 // These are invalid anyway, so just ignore.
4257 break;
4258 }
4259 }
4260 return false;
4261}
4262
4263static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk) {
4264 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4265 Chunk.Kind == DeclaratorChunk::Array);
4266}
4267
4268template<typename AttrT>
4269static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4270 AL.setUsedAsTypeAttr();
4271 return ::new (Ctx) AttrT(Ctx, AL);
4272}
4273
4275 NullabilityKind NK) {
4276 switch (NK) {
4279
4282
4285
4288 }
4289 llvm_unreachable("unknown NullabilityKind");
4290}
4291
4292// Diagnose whether this is a case with the multiple addr spaces.
4293// Returns true if this is an invalid case.
4294// ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4295// by qualifiers for two or more different address spaces."
4297 LangAS ASNew,
4298 SourceLocation AttrLoc) {
4299 if (ASOld != LangAS::Default) {
4300 if (ASOld != ASNew) {
4301 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4302 return true;
4303 }
4304 // Emit a warning if they are identical; it's likely unintended.
4305 S.Diag(AttrLoc,
4306 diag::warn_attribute_address_multiple_identical_qualifiers);
4307 }
4308 return false;
4309}
4310
4311// Whether this is a type broadly expected to have nullability attached.
4312// These types are affected by `#pragma assume_nonnull`, and missing nullability
4313// will be diagnosed with -Wnullability-completeness.
4315 return T->canHaveNullability(/*ResultIfUnknown=*/false) &&
4316 // For now, do not infer/require nullability on C++ smart pointers.
4317 // It's unclear whether the pragma's behavior is useful for C++.
4318 // e.g. treating type-aliases and template-type-parameters differently
4319 // from types of declarations can be surprising.
4321 T->getCanonicalTypeInternal());
4322}
4323
4324static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4325 QualType declSpecType,
4326 TypeSourceInfo *TInfo) {
4327 // The TypeSourceInfo that this function returns will not be a null type.
4328 // If there is an error, this function will fill in a dummy type as fallback.
4329 QualType T = declSpecType;
4330 Declarator &D = state.getDeclarator();
4331 Sema &S = state.getSema();
4332 ASTContext &Context = S.Context;
4333 const LangOptions &LangOpts = S.getLangOpts();
4334
4335 // The name we're declaring, if any.
4336 DeclarationName Name;
4337 if (D.getIdentifier())
4338 Name = D.getIdentifier();
4339
4340 // Does this declaration declare a typedef-name?
4341 bool IsTypedefName =
4345
4346 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4347 bool IsQualifiedFunction = T->isFunctionProtoType() &&
4348 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4349 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4350
4351 // If T is 'decltype(auto)', the only declarators we can have are parens
4352 // and at most one function declarator if this is a function declaration.
4353 // If T is a deduced class template specialization type, only parentheses
4354 // are allowed.
4355 if (auto *DT = T->getAs<DeducedType>()) {
4356 const AutoType *AT = T->getAs<AutoType>();
4357 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4358 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4359 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4360 unsigned Index = E - I - 1;
4361 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4362 unsigned DiagId = IsClassTemplateDeduction
4363 ? diag::err_deduced_class_template_compound_type
4364 : diag::err_decltype_auto_compound_type;
4365 unsigned DiagKind = 0;
4366 switch (DeclChunk.Kind) {
4368 continue;
4370 if (IsClassTemplateDeduction) {
4371 DiagKind = 3;
4372 break;
4373 }
4374 unsigned FnIndex;
4376 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4377 continue;
4378 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4379 break;
4380 }
4384 DiagKind = 0;
4385 break;
4387 DiagKind = 1;
4388 break;
4390 DiagKind = 2;
4391 break;
4393 break;
4394 }
4395
4396 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4397 D.setInvalidType(true);
4398 break;
4399 }
4400 }
4401 }
4402
4403 // Determine whether we should infer _Nonnull on pointer types.
4404 std::optional<NullabilityKind> inferNullability;
4405 bool inferNullabilityCS = false;
4406 bool inferNullabilityInnerOnly = false;
4407 bool inferNullabilityInnerOnlyComplete = false;
4408
4409 // Are we in an assume-nonnull region?
4410 bool inAssumeNonNullRegion = false;
4411 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4412 if (assumeNonNullLoc.isValid()) {
4413 inAssumeNonNullRegion = true;
4414 recordNullabilitySeen(S, assumeNonNullLoc);
4415 }
4416
4417 // Whether to complain about missing nullability specifiers or not.
4418 enum {
4419 /// Never complain.
4420 CAMN_No,
4421 /// Complain on the inner pointers (but not the outermost
4422 /// pointer).
4423 CAMN_InnerPointers,
4424 /// Complain about any pointers that don't have nullability
4425 /// specified or inferred.
4426 CAMN_Yes
4427 } complainAboutMissingNullability = CAMN_No;
4428 unsigned NumPointersRemaining = 0;
4429 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4430
4431 if (IsTypedefName) {
4432 // For typedefs, we do not infer any nullability (the default),
4433 // and we only complain about missing nullability specifiers on
4434 // inner pointers.
4435 complainAboutMissingNullability = CAMN_InnerPointers;
4436
4437 if (shouldHaveNullability(T) && !T->getNullability()) {
4438 // Note that we allow but don't require nullability on dependent types.
4439 ++NumPointersRemaining;
4440 }
4441
4442 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4443 DeclaratorChunk &chunk = D.getTypeObject(i);
4444 switch (chunk.Kind) {
4448 break;
4449
4452 ++NumPointersRemaining;
4453 break;
4454
4457 continue;
4458
4460 ++NumPointersRemaining;
4461 continue;
4462 }
4463 }
4464 } else {
4465 bool isFunctionOrMethod = false;
4466 switch (auto context = state.getDeclarator().getContext()) {
4472 isFunctionOrMethod = true;
4473 [[fallthrough]];
4474
4476 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4477 complainAboutMissingNullability = CAMN_No;
4478 break;
4479 }
4480
4481 // Weak properties are inferred to be nullable.
4482 if (state.getDeclarator().isObjCWeakProperty()) {
4483 // Weak properties cannot be nonnull, and should not complain about
4484 // missing nullable attributes during completeness checks.
4485 complainAboutMissingNullability = CAMN_No;
4486 if (inAssumeNonNullRegion) {
4487 inferNullability = NullabilityKind::Nullable;
4488 }
4489 break;
4490 }
4491
4492 [[fallthrough]];
4493
4496 complainAboutMissingNullability = CAMN_Yes;
4497
4498 // Nullability inference depends on the type and declarator.
4499 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4500 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4501 case PointerDeclaratorKind::NonPointer:
4502 case PointerDeclaratorKind::MultiLevelPointer:
4503 // Cannot infer nullability.
4504 break;
4505
4506 case PointerDeclaratorKind::SingleLevelPointer:
4507 // Infer _Nonnull if we are in an assumes-nonnull region.
4508 if (inAssumeNonNullRegion) {
4509 complainAboutInferringWithinChunk = wrappingKind;
4510 inferNullability = NullabilityKind::NonNull;
4511 inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4513 }
4514 break;
4515
4516 case PointerDeclaratorKind::CFErrorRefPointer:
4517 case PointerDeclaratorKind::NSErrorPointerPointer:
4518 // Within a function or method signature, infer _Nullable at both
4519 // levels.
4520 if (isFunctionOrMethod && inAssumeNonNullRegion)
4521 inferNullability = NullabilityKind::Nullable;
4522 break;
4523
4524 case PointerDeclaratorKind::MaybePointerToCFRef:
4525 if (isFunctionOrMethod) {
4526 // On pointer-to-pointer parameters marked cf_returns_retained or
4527 // cf_returns_not_retained, if the outer pointer is explicit then
4528 // infer the inner pointer as _Nullable.
4529 auto hasCFReturnsAttr =
4530 [](const ParsedAttributesView &AttrList) -> bool {
4531 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4532 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4533 };
4534 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4535 if (hasCFReturnsAttr(D.getDeclarationAttributes()) ||
4536 hasCFReturnsAttr(D.getAttributes()) ||
4537 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4538 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4539 inferNullability = NullabilityKind::Nullable;
4540 inferNullabilityInnerOnly = true;
4541 }
4542 }
4543 }
4544 break;
4545 }
4546 break;
4547 }
4548
4550 complainAboutMissingNullability = CAMN_Yes;
4551 break;
4552
4572 // Don't infer in these contexts.
4573 break;
4574 }
4575 }
4576
4577 // Local function that returns true if its argument looks like a va_list.
4578 auto isVaList = [&S](QualType T) -> bool {
4579 auto *typedefTy = T->getAs<TypedefType>();
4580 if (!typedefTy)
4581 return false;
4582 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4583 do {
4584 if (typedefTy->getDecl() == vaListTypedef)
4585 return true;
4586 if (auto *name = typedefTy->getDecl()->getIdentifier())
4587 if (name->isStr("va_list"))
4588 return true;
4589 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4590 } while (typedefTy);
4591 return false;
4592 };
4593
4594 // Local function that checks the nullability for a given pointer declarator.
4595 // Returns true if _Nonnull was inferred.
4596 auto inferPointerNullability =
4597 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4598 SourceLocation pointerEndLoc,
4599 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4600 // We've seen a pointer.
4601 if (NumPointersRemaining > 0)
4602 --NumPointersRemaining;
4603
4604 // If a nullability attribute is present, there's nothing to do.
4605 if (hasNullabilityAttr(attrs))
4606 return nullptr;
4607
4608 // If we're supposed to infer nullability, do so now.
4609 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4610 ParsedAttr::Form form =
4611 inferNullabilityCS
4612 ? ParsedAttr::Form::ContextSensitiveKeyword()
4613 : ParsedAttr::Form::Keyword(false /*IsAlignAs*/,
4614 false /*IsRegularKeywordAttribute*/);
4615 ParsedAttr *nullabilityAttr = Pool.create(
4616 S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4617 AttributeScopeInfo(), nullptr, 0, form);
4618
4619 attrs.addAtEnd(nullabilityAttr);
4620
4621 if (inferNullabilityCS) {
4622 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4623 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4624 }
4625
4626 if (pointerLoc.isValid() &&
4627 complainAboutInferringWithinChunk !=
4628 PointerWrappingDeclaratorKind::None) {
4629 auto Diag =
4630 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4631 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4633 }
4634
4635 if (inferNullabilityInnerOnly)
4636 inferNullabilityInnerOnlyComplete = true;
4637 return nullabilityAttr;
4638 }
4639
4640 // If we're supposed to complain about missing nullability, do so
4641 // now if it's truly missing.
4642 switch (complainAboutMissingNullability) {
4643 case CAMN_No:
4644 break;
4645
4646 case CAMN_InnerPointers:
4647 if (NumPointersRemaining == 0)
4648 break;
4649 [[fallthrough]];
4650
4651 case CAMN_Yes:
4652 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4653 }
4654 return nullptr;
4655 };
4656
4657 // If the type itself could have nullability but does not, infer pointer
4658 // nullability and perform consistency checking.
4659 if (S.CodeSynthesisContexts.empty()) {
4660 if (shouldHaveNullability(T) && !T->getNullability()) {
4661 if (isVaList(T)) {
4662 // Record that we've seen a pointer, but do nothing else.
4663 if (NumPointersRemaining > 0)
4664 --NumPointersRemaining;
4665 } else {
4666 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4667 if (T->isBlockPointerType())
4668 pointerKind = SimplePointerKind::BlockPointer;
4669 else if (T->isMemberPointerType())
4670 pointerKind = SimplePointerKind::MemberPointer;
4671
4672 if (auto *attr = inferPointerNullability(
4673 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4674 D.getDeclSpec().getEndLoc(),
4677 T = state.getAttributedType(
4678 createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4679 }
4680 }
4681 }
4682
4683 if (complainAboutMissingNullability == CAMN_Yes && T->isArrayType() &&
4684 !T->getNullability() && !isVaList(T) && D.isPrototypeContext() &&
4686 checkNullabilityConsistency(S, SimplePointerKind::Array,
4688 }
4689 }
4690
4691 bool ExpectNoDerefChunk =
4692 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4693
4694 // Walk the DeclTypeInfo, building the recursive type as we go.
4695 // DeclTypeInfos are ordered from the identifier out, which is
4696 // opposite of what we want :).
4697
4698 // Track if the produced type matches the structure of the declarator.
4699 // This is used later to decide if we can fill `TypeLoc` from
4700 // `DeclaratorChunk`s. E.g. it must be false if Clang recovers from
4701 // an error by replacing the type with `int`.
4702 bool AreDeclaratorChunksValid = true;
4703 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4704 unsigned chunkIndex = e - i - 1;
4705 state.setCurrentChunkIndex(chunkIndex);
4706 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4707 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4708 switch (DeclType.Kind) {
4710 if (i == 0)
4711 warnAboutRedundantParens(S, D, T);
4712 T = S.BuildParenType(T);
4713 break;
4715 // If blocks are disabled, emit an error.
4716 if (!LangOpts.Blocks)
4717 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4718
4719 // Handle pointer nullability.
4720 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4721 DeclType.EndLoc, DeclType.getAttrs(),
4722 state.getDeclarator().getAttributePool());
4723
4724 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4725 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4726 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4727 // qualified with const.
4728 if (LangOpts.OpenCL)
4729 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4730 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4731 }
4732 break;
4734 // Verify that we're not building a pointer to pointer to function with
4735 // exception specification.
4736 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4737 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4738 D.setInvalidType(true);
4739 // Build the type anyway.
4740 }
4741
4742 // Handle pointer nullability
4743 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4744 DeclType.EndLoc, DeclType.getAttrs(),
4745 state.getDeclarator().getAttributePool());
4746
4747 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
4748 T = Context.getObjCObjectPointerType(T);
4749 if (DeclType.Ptr.TypeQuals)
4750 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4751 break;
4752 }
4753
4754 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4755 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4756 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4757 if (LangOpts.OpenCL) {
4758 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4759 T->isBlockPointerType()) {
4760 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4761 D.setInvalidType(true);
4762 }
4763 }
4764
4765 T = S.BuildPointerType(T, DeclType.Loc, Name);
4766 if (DeclType.Ptr.TypeQuals)
4767 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4768 if (DeclType.Ptr.OverflowBehaviorLoc.isValid()) {
4769 auto OBState = DeclType.Ptr.OverflowBehaviorIsWrap
4772 S.Diag(DeclType.Ptr.OverflowBehaviorLoc,
4773 diag::err_overflow_behavior_non_integer_type)
4774 << DeclSpec::getSpecifierName(OBState) << T.getAsString() << 1;
4775 D.setInvalidType(true);
4776 }
4777 break;
4779 // Verify that we're not building a reference to pointer to function with
4780 // exception specification.
4781 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4782 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4783 D.setInvalidType(true);
4784 // Build the type anyway.
4785 }
4786 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4787
4788 if (DeclType.Ref.HasRestrict)
4789 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4790 break;
4791 }
4793 // Verify that we're not building an array of pointers to function with
4794 // exception specification.
4795 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4796 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4797 D.setInvalidType(true);
4798 // Build the type anyway.
4799 }
4800 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4801 Expr *ArraySize = ATI.NumElts;
4803
4804 // Microsoft property fields can have multiple sizeless array chunks
4805 // (i.e. int x[][][]). Skip all of these except one to avoid creating
4806 // bad incomplete array types.
4807 if (chunkIndex != 0 && !ArraySize &&
4809 // This is a sizeless chunk. If the next is also, skip this one.
4810 DeclaratorChunk &NextDeclType = D.getTypeObject(chunkIndex - 1);
4811 if (NextDeclType.Kind == DeclaratorChunk::Array &&
4812 !NextDeclType.Arr.NumElts)
4813 break;
4814 }
4815
4816 if (ATI.isStar)
4818 else if (ATI.hasStatic)
4820 else
4822 if (ASM == ArraySizeModifier::Star && !D.isPrototypeContext()) {
4823 // FIXME: This check isn't quite right: it allows star in prototypes
4824 // for function definitions, and disallows some edge cases detailed
4825 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4826 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4828 D.setInvalidType(true);
4829 }
4830
4831 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4832 // shall appear only in a declaration of a function parameter with an
4833 // array type, ...
4834 if (ASM == ArraySizeModifier::Static || ATI.TypeQuals) {
4835 if (!(D.isPrototypeContext() ||
4837 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype)
4838 << (ASM == ArraySizeModifier::Static ? "'static'"
4839 : "type qualifier");
4840 // Remove the 'static' and the type qualifiers.
4841 if (ASM == ArraySizeModifier::Static)
4843 ATI.TypeQuals = 0;
4844 D.setInvalidType(true);
4845 }
4846
4847 // C99 6.7.5.2p1: ... and then only in the outermost array type
4848 // derivation.
4849 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4850 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost)
4851 << (ASM == ArraySizeModifier::Static ? "'static'"
4852 : "type qualifier");
4853 if (ASM == ArraySizeModifier::Static)
4855 ATI.TypeQuals = 0;
4856 D.setInvalidType(true);
4857 }
4858 }
4859
4860 // Array parameters can be marked nullable as well, although it's not
4861 // necessary if they're marked 'static'.
4862 if (complainAboutMissingNullability == CAMN_Yes &&
4863 !hasNullabilityAttr(DeclType.getAttrs()) &&
4865 !hasOuterPointerLikeChunk(D, chunkIndex)) {
4866 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4867 }
4868
4869 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4870 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4871 break;
4872 }
4874 // If the function declarator has a prototype (i.e. it is not () and
4875 // does not have a K&R-style identifier list), then the arguments are part
4876 // of the type, otherwise the argument list is ().
4877 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4878 IsQualifiedFunction =
4880
4881 auto IsClassType = [&](CXXScopeSpec &SS) {
4882 // If there already was an problem with the scope, don’t issue another
4883 // error about the explicit object parameter.
4884 return SS.isInvalid() ||
4885 isa_and_present<CXXRecordDecl>(S.computeDeclContext(SS));
4886 };
4887
4888 // C++23 [dcl.fct]p6:
4889 //
4890 // An explicit-object-parameter-declaration is a parameter-declaration
4891 // with a this specifier. An explicit-object-parameter-declaration shall
4892 // appear only as the first parameter-declaration of a
4893 // parameter-declaration-list of one of:
4894 //
4895 // - a declaration of a member function or member function template
4896 // ([class.mem]), or
4897 //
4898 // - an explicit instantiation ([temp.explicit]) or explicit
4899 // specialization ([temp.expl.spec]) of a templated member function,
4900 // or
4901 //
4902 // - a lambda-declarator [expr.prim.lambda].
4905 FTI.NumParams ? dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param)
4906 : nullptr;
4907
4908 bool IsFunctionDecl = D.getInnermostNonParenChunk() == &DeclType;
4909 if (First && First->isExplicitObjectParameter() &&
4911
4912 // Either not a member or nested declarator in a member.
4913 //
4914 // Note that e.g. 'static' or 'friend' declarations are accepted
4915 // here; we diagnose them later when we build the member function
4916 // because it's easier that way.
4917 (C != DeclaratorContext::Member || !IsFunctionDecl) &&
4918
4919 // Allow out-of-line definitions of member functions.
4920 !IsClassType(D.getCXXScopeSpec())) {
4921 if (IsFunctionDecl)
4922 S.Diag(First->getBeginLoc(),
4923 diag::err_explicit_object_parameter_nonmember)
4924 << /*non-member*/ 2 << /*function*/ 0 << First->getSourceRange();
4925 else
4926 S.Diag(First->getBeginLoc(),
4927 diag::err_explicit_object_parameter_invalid)
4928 << First->getSourceRange();
4929
4930 // Do let non-member function have explicit parameters
4931 // to not break assumptions elsewhere in the code.
4932 First->setExplicitObjectParameterLoc(SourceLocation());
4933 D.setInvalidType();
4934 AreDeclaratorChunksValid = false;
4935 }
4936
4937 // Check for auto functions and trailing return type and adjust the
4938 // return type accordingly.
4939 if (!D.isInvalidType()) {
4940 // trailing-return-type is only required if we're declaring a function,
4941 // and not, for instance, a pointer to a function.
4942 if (D.getDeclSpec().hasAutoTypeSpec() &&
4943 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
4944 if (!S.getLangOpts().CPlusPlus14) {
4947 ? diag::err_auto_missing_trailing_return
4948 : diag::err_deduced_return_type);
4949 T = Context.IntTy;
4950 D.setInvalidType(true);
4951 AreDeclaratorChunksValid = false;
4952 } else {
4954 diag::warn_cxx11_compat_deduced_return_type);
4955 }
4956 } else if (FTI.hasTrailingReturnType()) {
4957 // T must be exactly 'auto' at this point. See CWG issue 681.
4958 if (isa<ParenType>(T)) {
4959 S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
4960 << T << D.getSourceRange();
4961 D.setInvalidType(true);
4962 // FIXME: recover and fill decls in `TypeLoc`s.
4963 AreDeclaratorChunksValid = false;
4964 } else if (D.getName().getKind() ==
4966 if (T != Context.DependentTy) {
4968 diag::err_deduction_guide_with_complex_decl)
4969 << D.getSourceRange();
4970 D.setInvalidType(true);
4971 // FIXME: recover and fill decls in `TypeLoc`s.
4972 AreDeclaratorChunksValid = false;
4973 }
4974 } else if (D.getContext() != DeclaratorContext::LambdaExpr &&
4975 (T.hasQualifiers() || !isa<AutoType>(T) ||
4976 cast<AutoType>(T)->getKeyword() !=
4978 cast<AutoType>(T)->isConstrained())) {
4979 // Attach a valid source location for diagnostics on functions with
4980 // trailing return types missing 'auto'. Attempt to get the location
4981 // from the declared type; if invalid, fall back to the trailing
4982 // return type's location.
4985 if (Loc.isInvalid()) {
4986 Loc = FTI.getTrailingReturnTypeLoc();
4987 SR = D.getSourceRange();
4988 }
4989 S.Diag(Loc, diag::err_trailing_return_without_auto) << T << SR;
4990 D.setInvalidType(true);
4991 // FIXME: recover and fill decls in `TypeLoc`s.
4992 AreDeclaratorChunksValid = false;
4993 }
4994 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
4995 if (T.isNull()) {
4996 // An error occurred parsing the trailing return type.
4997 T = Context.IntTy;
4998 D.setInvalidType(true);
4999 } else if (AutoType *Auto = T->getContainedAutoType()) {
5000 // If the trailing return type contains an `auto`, we may need to
5001 // invent a template parameter for it, for cases like
5002 // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
5003 InventedTemplateParameterInfo *InventedParamInfo = nullptr;
5005 InventedParamInfo = &S.InventedParameterInfos.back();
5007 InventedParamInfo = S.getCurLambda();
5008 if (InventedParamInfo) {
5009 std::tie(T, TInfo) = InventTemplateParameter(
5010 state, T, TInfo, Auto, *InventedParamInfo);
5011 }
5012 }
5013 } else {
5014 // This function type is not the type of the entity being declared,
5015 // so checking the 'auto' is not the responsibility of this chunk.
5016 }
5017 }
5018
5019 // C99 6.7.5.3p1: The return type may not be a function or array type.
5020 // For conversion functions, we'll diagnose this particular error later.
5021 if (!D.isInvalidType() &&
5022 ((T->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
5023 T->isFunctionType()) &&
5024 (D.getName().getKind() !=
5026 unsigned diagID = diag::err_func_returning_array_function;
5027 // Last processing chunk in block context means this function chunk
5028 // represents the block.
5029 if (chunkIndex == 0 &&
5031 diagID = diag::err_block_returning_array_function;
5032 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
5033 T = Context.IntTy;
5034 D.setInvalidType(true);
5035 AreDeclaratorChunksValid = false;
5036 }
5037
5038 // Do not allow returning half FP value.
5039 // FIXME: This really should be in BuildFunctionType.
5040 if (T->isHalfType()) {
5041 if (S.getLangOpts().OpenCL) {
5042 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5043 S.getLangOpts())) {
5044 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5045 << T << 0 /*pointer hint*/;
5046 D.setInvalidType(true);
5047 }
5048 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5050 S.Diag(D.getIdentifierLoc(),
5051 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
5052 D.setInvalidType(true);
5053 }
5054 }
5055
5056 // __ptrauth is illegal on a function return type.
5057 if (T.getPointerAuth()) {
5058 S.Diag(DeclType.Loc, diag::err_ptrauth_qualifier_invalid) << T << 0;
5059 }
5060
5061 if (LangOpts.OpenCL) {
5062 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
5063 // function.
5064 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
5065 T->isPipeType()) {
5066 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5067 << T << 1 /*hint off*/;
5068 D.setInvalidType(true);
5069 }
5070 // OpenCL doesn't support variadic functions and blocks
5071 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
5072 // We also allow here any toolchain reserved identifiers.
5073 if (FTI.isVariadic &&
5075 "__cl_clang_variadic_functions", S.getLangOpts()) &&
5076 !(D.getIdentifier() &&
5077 ((D.getIdentifier()->getName() == "printf" &&
5078 LangOpts.getOpenCLCompatibleVersion() >= 120) ||
5079 D.getIdentifier()->getName().starts_with("__")))) {
5080 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
5081 D.setInvalidType(true);
5082 }
5083 }
5084
5085 // Methods cannot return interface types. All ObjC objects are
5086 // passed by reference.
5087 if (T->isObjCObjectType()) {
5088 SourceLocation DiagLoc, FixitLoc;
5089 if (TInfo) {
5090 DiagLoc = TInfo->getTypeLoc().getBeginLoc();
5091 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
5092 } else {
5093 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5094 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
5095 }
5096 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
5097 << 0 << T
5098 << FixItHint::CreateInsertion(FixitLoc, "*");
5099
5100 T = Context.getObjCObjectPointerType(T);
5101 if (TInfo) {
5102 TypeLocBuilder TLB;
5103 TLB.pushFullCopy(TInfo->getTypeLoc());
5105 TLoc.setStarLoc(FixitLoc);
5106 TInfo = TLB.getTypeSourceInfo(Context, T);
5107 } else {
5108 AreDeclaratorChunksValid = false;
5109 }
5110
5111 D.setInvalidType(true);
5112 }
5113
5114 // cv-qualifiers on return types are pointless except when the type is a
5115 // class type in C++.
5116 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
5117 // A dependent type or an undeduced type might later become a class
5118 // type.
5119 !(S.getLangOpts().CPlusPlus &&
5120 (T->isRecordType() || T->isDependentType() ||
5121 T->isUndeducedAutoType()))) {
5122 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
5125 // [6.9.1/3] qualified void return is invalid on a C
5126 // function definition. Apparently ok on declarations and
5127 // in C++ though (!)
5128 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
5129 } else
5130 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
5131 }
5132
5133 // C++2a [dcl.fct]p12:
5134 // A volatile-qualified return type is deprecated
5135 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20)
5136 S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T;
5137
5138 // Objective-C ARC ownership qualifiers are ignored on the function
5139 // return type (by type canonicalization). Complain if this attribute
5140 // was written here.
5141 if (T.getQualifiers().hasObjCLifetime()) {
5142 SourceLocation AttrLoc;
5143 if (chunkIndex + 1 < D.getNumTypeObjects()) {
5144 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
5145 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5146 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5147 AttrLoc = AL.getLoc();
5148 break;
5149 }
5150 }
5151 }
5152 if (AttrLoc.isInvalid()) {
5153 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5154 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5155 AttrLoc = AL.getLoc();
5156 break;
5157 }
5158 }
5159 }
5160
5161 if (AttrLoc.isValid()) {
5162 // The ownership attributes are almost always written via
5163 // the predefined
5164 // __strong/__weak/__autoreleasing/__unsafe_unretained.
5165 if (AttrLoc.isMacroID())
5166 AttrLoc =
5168
5169 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
5170 << T.getQualifiers().getObjCLifetime();
5171 }
5172 }
5173
5174 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
5175 // C++ [dcl.fct]p6:
5176 // Types shall not be defined in return or parameter types.
5178 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
5179 << Context.getCanonicalTagType(Tag);
5180 }
5181
5182 // Exception specs are not allowed in typedefs. Complain, but add it
5183 // anyway.
5184 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
5186 diag::err_exception_spec_in_typedef)
5189
5190 // If we see "T var();" or "T var(T());" at block scope, it is probably
5191 // an attempt to initialize a variable, not a function declaration.
5192 if (FTI.isAmbiguous)
5193 warnAboutAmbiguousFunction(S, D, DeclType, T);
5194
5196 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
5197
5198 // OpenCL disallows functions without a prototype, but it doesn't enforce
5199 // strict prototypes as in C23 because it allows a function definition to
5200 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
5201 if (!FTI.NumParams && !FTI.isVariadic &&
5202 !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) {
5203 // Simple void foo(), where the incoming T is the result type.
5204 T = Context.getFunctionNoProtoType(T, EI);
5205 } else {
5206 // We allow a zero-parameter variadic function in C if the
5207 // function is marked with the "overloadable" attribute. Scan
5208 // for this attribute now. We also allow it in C23 per WG14 N2975.
5209 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
5210 if (LangOpts.C23)
5211 S.Diag(FTI.getEllipsisLoc(),
5212 diag::warn_c17_compat_ellipsis_only_parameter);
5214 ParsedAttr::AT_Overloadable) &&
5216 ParsedAttr::AT_Overloadable) &&
5218 ParsedAttr::AT_Overloadable))
5219 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
5220 }
5221
5222 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
5223 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5224 // definition.
5225 S.Diag(FTI.Params[0].IdentLoc,
5226 diag::err_ident_list_in_fn_declaration);
5227 D.setInvalidType(true);
5228 // Recover by creating a K&R-style function type, if possible.
5229 T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL)
5230 ? Context.getFunctionNoProtoType(T, EI)
5231 : Context.IntTy;
5232 AreDeclaratorChunksValid = false;
5233 break;
5234 }
5235
5237 EPI.ExtInfo = EI;
5238 EPI.Variadic = FTI.isVariadic;
5239 EPI.EllipsisLoc = FTI.getEllipsisLoc();
5243 : 0);
5246 : RQ_RValue;
5247
5248 // Otherwise, we have a function with a parameter list that is
5249 // potentially variadic.
5251 ParamTys.reserve(FTI.NumParams);
5252
5254 ExtParameterInfos(FTI.NumParams);
5255 bool HasAnyInterestingExtParameterInfos = false;
5256
5257 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
5258 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5259 QualType ParamTy = Param->getType();
5260 assert(!ParamTy.isNull() && "Couldn't parse type?");
5261
5262 // Look for 'void'. void is allowed only as a single parameter to a
5263 // function with no other parameters (C99 6.7.5.3p10). We record
5264 // int(void) as a FunctionProtoType with an empty parameter list.
5265 if (ParamTy->isVoidType()) {
5266 // If this is something like 'float(int, void)', reject it. 'void'
5267 // is an incomplete type (C99 6.2.5p19) and function decls cannot
5268 // have parameters of incomplete type.
5269 if (FTI.NumParams != 1 || FTI.isVariadic) {
5270 S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param);
5271 ParamTy = Context.IntTy;
5272 Param->setType(ParamTy);
5273 } else if (FTI.Params[i].Ident) {
5274 // Reject, but continue to parse 'int(void abc)'.
5275 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
5276 ParamTy = Context.IntTy;
5277 Param->setType(ParamTy);
5278 } else {
5279 // Reject, but continue to parse 'float(const void)'.
5280 if (ParamTy.hasQualifiers())
5281 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
5282
5283 for (const auto *A : Param->attrs()) {
5284 S.Diag(A->getLoc(), diag::warn_attribute_on_void_param)
5285 << A << A->getRange();
5286 }
5287
5288 // Reject, but continue to parse 'float(this void)' as
5289 // 'float(void)'.
5290 if (Param->isExplicitObjectParameter()) {
5291 S.Diag(Param->getLocation(),
5292 diag::err_void_explicit_object_param);
5293 Param->setExplicitObjectParameterLoc(SourceLocation());
5294 }
5295
5296 // Do not add 'void' to the list.
5297 break;
5298 }
5299 } else if (ParamTy->isHalfType()) {
5300 // Disallow half FP parameters.
5301 // FIXME: This really should be in BuildFunctionType.
5302 if (S.getLangOpts().OpenCL) {
5303 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5304 S.getLangOpts())) {
5305 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5306 << ParamTy << 0;
5307 D.setInvalidType();
5308 Param->setInvalidDecl();
5309 }
5310 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5312 S.Diag(Param->getLocation(),
5313 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5314 D.setInvalidType();
5315 }
5316 } else if (!FTI.hasPrototype) {
5317 if (Context.isPromotableIntegerType(ParamTy)) {
5318 ParamTy = Context.getPromotedIntegerType(ParamTy);
5319 Param->setKNRPromoted(true);
5320 } else if (const BuiltinType *BTy = ParamTy->getAs<BuiltinType>()) {
5321 if (BTy->getKind() == BuiltinType::Float) {
5322 ParamTy = Context.DoubleTy;
5323 Param->setKNRPromoted(true);
5324 }
5325 }
5326 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) {
5327 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5328 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5329 << ParamTy << 1 /*hint off*/;
5330 D.setInvalidType();
5331 }
5332
5333 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
5334 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
5335 HasAnyInterestingExtParameterInfos = true;
5336 }
5337
5338 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5339 ExtParameterInfos[i] =
5340 ExtParameterInfos[i].withABI(attr->getABI());
5341 HasAnyInterestingExtParameterInfos = true;
5342 }
5343
5344 if (Param->hasAttr<PassObjectSizeAttr>()) {
5345 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5346 HasAnyInterestingExtParameterInfos = true;
5347 }
5348
5349 if (Param->hasAttr<NoEscapeAttr>()) {
5350 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
5351 HasAnyInterestingExtParameterInfos = true;
5352 }
5353
5354 ParamTys.push_back(ParamTy);
5355 }
5356
5357 if (HasAnyInterestingExtParameterInfos) {
5358 EPI.ExtParameterInfos = ExtParameterInfos.data();
5359 checkExtParameterInfos(S, ParamTys, EPI,
5360 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
5361 }
5362
5363 SmallVector<QualType, 4> Exceptions;
5364 SmallVector<ParsedType, 2> DynamicExceptions;
5365 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5366 Expr *NoexceptExpr = nullptr;
5367
5368 if (FTI.getExceptionSpecType() == EST_Dynamic) {
5369 // FIXME: It's rather inefficient to have to split into two vectors
5370 // here.
5371 unsigned N = FTI.getNumExceptions();
5372 DynamicExceptions.reserve(N);
5373 DynamicExceptionRanges.reserve(N);
5374 for (unsigned I = 0; I != N; ++I) {
5375 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
5376 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
5377 }
5378 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
5379 NoexceptExpr = FTI.NoexceptExpr;
5380 }
5381
5384 DynamicExceptions,
5385 DynamicExceptionRanges,
5386 NoexceptExpr,
5387 Exceptions,
5388 EPI.ExceptionSpec);
5389
5390 // FIXME: Set address space from attrs for C++ mode here.
5391 // OpenCLCPlusPlus: A class member function has an address space.
5392 auto IsClassMember = [&]() {
5393 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5394 state.getDeclarator()
5395 .getCXXScopeSpec()
5396 .getScopeRep()
5397 .getKind() == NestedNameSpecifier::Kind::Type) ||
5398 state.getDeclarator().getContext() ==
5400 state.getDeclarator().getContext() ==
5402 };
5403
5404 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
5405 LangAS ASIdx = LangAS::Default;
5406 // Take address space attr if any and mark as invalid to avoid adding
5407 // them later while creating QualType.
5408 if (FTI.MethodQualifiers)
5410 LangAS ASIdxNew = attr.asOpenCLLangAS();
5411 if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
5412 attr.getLoc()))
5413 D.setInvalidType(true);
5414 else
5415 ASIdx = ASIdxNew;
5416 }
5417 // If a class member function's address space is not set, set it to
5418 // __generic.
5419 LangAS AS =
5421 : ASIdx);
5422 EPI.TypeQuals.addAddressSpace(AS);
5423 }
5424 T = Context.getFunctionType(T, ParamTys, EPI);
5425 }
5426 break;
5427 }
5429 // The scope spec must refer to a class, or be dependent.
5430 CXXScopeSpec &SS = DeclType.Mem.Scope();
5431
5432 // Handle pointer nullability.
5433 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5434 DeclType.EndLoc, DeclType.getAttrs(),
5435 state.getDeclarator().getAttributePool());
5436
5437 if (SS.isInvalid()) {
5438 // Avoid emitting extra errors if we already errored on the scope.
5439 D.setInvalidType(true);
5440 AreDeclaratorChunksValid = false;
5441 } else {
5442 T = S.BuildMemberPointerType(T, SS, /*Cls=*/nullptr, DeclType.Loc,
5443 D.getIdentifier());
5444 }
5445
5446 if (T.isNull()) {
5447 T = Context.IntTy;
5448 D.setInvalidType(true);
5449 AreDeclaratorChunksValid = false;
5450 } else if (DeclType.Mem.TypeQuals) {
5451 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
5452 }
5453 break;
5454 }
5455
5456 case DeclaratorChunk::Pipe: {
5457 T = S.BuildReadPipeType(T, DeclType.Loc);
5460 break;
5461 }
5462 }
5463
5464 if (T.isNull()) {
5465 D.setInvalidType(true);
5466 T = Context.IntTy;
5467 AreDeclaratorChunksValid = false;
5468 }
5469
5470 // See if there are any attributes on this declarator chunk.
5471 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs(),
5473
5474 if (DeclType.Kind != DeclaratorChunk::Paren) {
5475 if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
5476 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5477
5478 ExpectNoDerefChunk = state.didParseNoDeref();
5479 }
5480 }
5481
5482 if (ExpectNoDerefChunk)
5483 S.Diag(state.getDeclarator().getBeginLoc(),
5484 diag::warn_noderef_on_non_pointer_or_array);
5485
5486 // GNU warning -Wstrict-prototypes
5487 // Warn if a function declaration or definition is without a prototype.
5488 // This warning is issued for all kinds of unprototyped function
5489 // declarations (i.e. function type typedef, function pointer etc.)
5490 // C99 6.7.5.3p14:
5491 // The empty list in a function declarator that is not part of a definition
5492 // of that function specifies that no information about the number or types
5493 // of the parameters is supplied.
5494 // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of
5495 // function declarations whose behavior changes in C23.
5496 if (!LangOpts.requiresStrictPrototypes()) {
5497 bool IsBlock = false;
5498 for (const DeclaratorChunk &DeclType : D.type_objects()) {
5499 switch (DeclType.Kind) {
5501 IsBlock = true;
5502 break;
5504 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5505 // We suppress the warning when there's no LParen location, as this
5506 // indicates the declaration was an implicit declaration, which gets
5507 // warned about separately via -Wimplicit-function-declaration. We also
5508 // suppress the warning when we know the function has a prototype.
5509 if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic &&
5510 FTI.getLParenLoc().isValid())
5511 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5512 << IsBlock
5513 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5514 IsBlock = false;
5515 break;
5516 }
5517 default:
5518 break;
5519 }
5520 }
5521 }
5522
5523 assert(!T.isNull() && "T must not be null after this point");
5524
5525 if (LangOpts.CPlusPlus && T->isFunctionType()) {
5526 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5527 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
5528
5529 // C++ 8.3.5p4:
5530 // A cv-qualifier-seq shall only be part of the function type
5531 // for a nonstatic member function, the function type to which a pointer
5532 // to member refers, or the top-level function type of a function typedef
5533 // declaration.
5534 //
5535 // Core issue 547 also allows cv-qualifiers on function types that are
5536 // top-level template type arguments.
5537 enum {
5538 NonMember,
5539 Member,
5540 ExplicitObjectMember,
5541 DeductionGuide
5542 } Kind = NonMember;
5544 Kind = DeductionGuide;
5545 else if (!D.getCXXScopeSpec().isSet()) {
5549 Kind = Member;
5550 } else {
5552 if (!DC || DC->isRecord())
5553 Kind = Member;
5554 }
5555
5556 if (Kind == Member) {
5557 unsigned I;
5558 if (D.isFunctionDeclarator(I)) {
5559 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5560 if (Chunk.Fun.NumParams) {
5561 auto *P = dyn_cast_or_null<ParmVarDecl>(Chunk.Fun.Params->Param);
5562 if (P && P->isExplicitObjectParameter())
5563 Kind = ExplicitObjectMember;
5564 }
5565 }
5566 }
5567
5568 // C++11 [dcl.fct]p6 (w/DR1417):
5569 // An attempt to specify a function type with a cv-qualifier-seq or a
5570 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5571 // - the function type for a non-static member function,
5572 // - the function type to which a pointer to member refers,
5573 // - the top-level function type of a function typedef declaration or
5574 // alias-declaration,
5575 // - the type-id in the default argument of a type-parameter, or
5576 // - the type-id of a template-argument for a type-parameter
5577 //
5578 // C++23 [dcl.fct]p6 (P0847R7)
5579 // ... A member-declarator with an explicit-object-parameter-declaration
5580 // shall not include a ref-qualifier or a cv-qualifier-seq and shall not be
5581 // declared static or virtual ...
5582 //
5583 // FIXME: Checking this here is insufficient. We accept-invalid on:
5584 //
5585 // template<typename T> struct S { void f(T); };
5586 // S<int() const> s;
5587 //
5588 // ... for instance.
5589 if (IsQualifiedFunction &&
5590 // Check for non-static member function and not and
5591 // explicit-object-parameter-declaration
5592 (Kind != Member || D.isExplicitObjectMemberFunction() ||
5595 D.isStaticMember())) &&
5596 !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg &&
5598 SourceLocation Loc = D.getBeginLoc();
5599 SourceRange RemovalRange;
5600 unsigned I;
5601 if (D.isFunctionDeclarator(I)) {
5603 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5604 assert(Chunk.Kind == DeclaratorChunk::Function);
5605
5606 if (Chunk.Fun.hasRefQualifier())
5607 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5608
5609 if (Chunk.Fun.hasMethodTypeQualifiers())
5611 [&](DeclSpec::TQ TypeQual, StringRef QualName,
5612 SourceLocation SL) { RemovalLocs.push_back(SL); });
5613
5614 if (!RemovalLocs.empty()) {
5615 llvm::sort(RemovalLocs,
5617 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5618 Loc = RemovalLocs.front();
5619 }
5620 }
5621
5622 S.Diag(Loc, diag::err_invalid_qualified_function_type)
5623 << Kind << D.isFunctionDeclarator() << T
5625 << FixItHint::CreateRemoval(RemovalRange);
5626
5627 // Strip the cv-qualifiers and ref-qualifiers from the type.
5630 EPI.RefQualifier = RQ_None;
5631
5632 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5633 EPI);
5634 // Rebuild any parens around the identifier in the function type.
5635 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5637 break;
5638 T = S.BuildParenType(T);
5639 }
5640 }
5641 }
5642
5643 // Apply any undistributed attributes from the declaration or declarator.
5644 ParsedAttributesView NonSlidingAttrs;
5645 for (ParsedAttr &AL : D.getDeclarationAttributes()) {
5646 if (!AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
5647 NonSlidingAttrs.addAtEnd(&AL);
5648 }
5649 }
5650 processTypeAttrs(state, T, TAL_DeclName, NonSlidingAttrs);
5652
5653 // Diagnose any ignored type attributes.
5654 state.diagnoseIgnoredTypeAttrs(T);
5655
5656 // C++0x [dcl.constexpr]p9:
5657 // A constexpr specifier used in an object declaration declares the object
5658 // as const.
5660 T->isObjectType())
5661 T.addConst();
5662
5663 // C++2a [dcl.fct]p4:
5664 // A parameter with volatile-qualified type is deprecated
5665 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 &&
5668 S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T;
5669
5670 // If there was an ellipsis in the declarator, the declaration declares a
5671 // parameter pack whose type may be a pack expansion type.
5672 if (D.hasEllipsis()) {
5673 // C++0x [dcl.fct]p13:
5674 // A declarator-id or abstract-declarator containing an ellipsis shall
5675 // only be used in a parameter-declaration. Such a parameter-declaration
5676 // is a parameter pack (14.5.3). [...]
5677 switch (D.getContext()) {
5681 // C++0x [dcl.fct]p13:
5682 // [...] When it is part of a parameter-declaration-clause, the
5683 // parameter pack is a function parameter pack (14.5.3). The type T
5684 // of the declarator-id of the function parameter pack shall contain
5685 // a template parameter pack; each template parameter pack in T is
5686 // expanded by the function parameter pack.
5687 //
5688 // We represent function parameter packs as function parameters whose
5689 // type is a pack expansion.
5690 if (!T->containsUnexpandedParameterPack() &&
5691 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) {
5692 S.Diag(D.getEllipsisLoc(),
5693 diag::err_function_parameter_pack_without_parameter_packs)
5694 << T << D.getSourceRange();
5696 } else {
5697 T = Context.getPackExpansionType(T, std::nullopt,
5698 /*ExpectPackInType=*/false);
5699 }
5700 break;
5702 // C++0x [temp.param]p15:
5703 // If a template-parameter is a [...] is a parameter-declaration that
5704 // declares a parameter pack (8.3.5), then the template-parameter is a
5705 // template parameter pack (14.5.3).
5706 //
5707 // Note: core issue 778 clarifies that, if there are any unexpanded
5708 // parameter packs in the type of the non-type template parameter, then
5709 // it expands those parameter packs.
5710 if (T->containsUnexpandedParameterPack())
5711 T = Context.getPackExpansionType(T, std::nullopt);
5712 else
5713 S.Diag(D.getEllipsisLoc(),
5714 LangOpts.CPlusPlus11
5715 ? diag::warn_cxx98_compat_variadic_templates
5716 : diag::ext_variadic_templates);
5717 break;
5718
5721 case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here?
5722 case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here?
5743 // FIXME: We may want to allow parameter packs in block-literal contexts
5744 // in the future.
5745 S.Diag(D.getEllipsisLoc(),
5746 diag::err_ellipsis_in_declarator_not_parameter);
5748 break;
5749 }
5750 }
5751
5752 assert(!T.isNull() && "T must not be null at the end of this function");
5753 if (!AreDeclaratorChunksValid)
5754 return Context.getTrivialTypeSourceInfo(T);
5755
5756 if (state.didParseHLSLParamMod() && !T->isConstantArrayType())
5757 T = S.HLSL().getInoutParameterType(T);
5758 return GetTypeSourceInfoForDeclarator(state, T, TInfo);
5759}
5760
5762 // Determine the type of the declarator. Not all forms of declarator
5763 // have a type.
5764
5765 TypeProcessingState state(*this, D);
5766
5767 TypeSourceInfo *ReturnTypeInfo = nullptr;
5768 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5769 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5770 inferARCWriteback(state, T);
5771
5772 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5773}
5774
5776 QualType &declSpecTy,
5777 Qualifiers::ObjCLifetime ownership) {
5778 if (declSpecTy->isObjCRetainableType() &&
5779 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5780 Qualifiers qs;
5781 qs.addObjCLifetime(ownership);
5782 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5783 }
5784}
5785
5786static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5787 Qualifiers::ObjCLifetime ownership,
5788 unsigned chunkIndex) {
5789 Sema &S = state.getSema();
5790 Declarator &D = state.getDeclarator();
5791
5792 // Look for an explicit lifetime attribute.
5793 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5794 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
5795 return;
5796
5797 const char *attrStr = nullptr;
5798 switch (ownership) {
5799 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5800 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5801 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5802 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5803 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5804 }
5805
5806 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5807 Arg->setIdentifierInfo(&S.Context.Idents.get(attrStr));
5808
5809 ArgsUnion Args(Arg);
5810
5811 // If there wasn't one, add one (with an invalid source location
5812 // so that we don't make an AttributedType for it).
5813 ParsedAttr *attr =
5814 D.getAttributePool().create(&S.Context.Idents.get("objc_ownership"),
5816 /*args*/ &Args, 1, ParsedAttr::Form::GNU());
5817 chunk.getAttrs().addAtEnd(attr);
5818 // TODO: mark whether we did this inference?
5819}
5820
5821/// Used for transferring ownership in casts resulting in l-values.
5822static void transferARCOwnership(TypeProcessingState &state,
5823 QualType &declSpecTy,
5824 Qualifiers::ObjCLifetime ownership) {
5825 Sema &S = state.getSema();
5826 Declarator &D = state.getDeclarator();
5827
5828 int inner = -1;
5829 bool hasIndirection = false;
5830 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5831 DeclaratorChunk &chunk = D.getTypeObject(i);
5832 switch (chunk.Kind) {
5834 // Ignore parens.
5835 break;
5836
5840 if (inner != -1)
5841 hasIndirection = true;
5842 inner = i;
5843 break;
5844
5846 if (inner != -1)
5847 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5848 return;
5849
5853 return;
5854 }
5855 }
5856
5857 if (inner == -1)
5858 return;
5859
5860 DeclaratorChunk &chunk = D.getTypeObject(inner);
5861 if (chunk.Kind == DeclaratorChunk::Pointer) {
5862 if (declSpecTy->isObjCRetainableType())
5863 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5864 if (declSpecTy->isObjCObjectType() && hasIndirection)
5865 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5866 } else {
5867 assert(chunk.Kind == DeclaratorChunk::Array ||
5869 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5870 }
5871}
5872
5874 TypeProcessingState state(*this, D);
5875
5876 TypeSourceInfo *ReturnTypeInfo = nullptr;
5877 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5878
5879 if (getLangOpts().ObjC) {
5880 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
5881 if (ownership != Qualifiers::OCL_None)
5882 transferARCOwnership(state, declSpecTy, ownership);
5883 }
5884
5885 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
5886}
5887
5889 TypeProcessingState &State) {
5890 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
5891}
5892
5894 TypeProcessingState &State) {
5896 State.getSema().HLSL().TakeLocForHLSLAttribute(TL.getTypePtr());
5897 TL.setSourceRange(LocInfo.Range);
5899}
5900
5902 const ParsedAttributesView &Attrs) {
5903 for (const ParsedAttr &AL : Attrs) {
5904 if (AL.getKind() == ParsedAttr::AT_MatrixType) {
5905 MTL.setAttrNameLoc(AL.getLoc());
5906 MTL.setAttrRowOperand(AL.getArgAsExpr(0));
5907 MTL.setAttrColumnOperand(AL.getArgAsExpr(1));
5909 return;
5910 }
5911 }
5912
5913 llvm_unreachable("no matrix_type attribute found at the expected location!");
5914}
5915
5916static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5917 SourceLocation Loc;
5918 switch (Chunk.Kind) {
5923 llvm_unreachable("cannot be _Atomic qualified");
5924
5926 Loc = Chunk.Ptr.AtomicQualLoc;
5927 break;
5928
5932 // FIXME: Provide a source location for the _Atomic keyword.
5933 break;
5934 }
5935
5936 ATL.setKWLoc(Loc);
5938}
5939
5940namespace {
5941 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5942 Sema &SemaRef;
5943 ASTContext &Context;
5944 TypeProcessingState &State;
5945 const DeclSpec &DS;
5946
5947 public:
5948 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
5949 const DeclSpec &DS)
5950 : SemaRef(S), Context(Context), State(State), DS(DS) {}
5951
5952 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5953 Visit(TL.getModifiedLoc());
5954 fillAttributedTypeLoc(TL, State);
5955 }
5956 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
5957 Visit(TL.getWrappedLoc());
5958 }
5959 void VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
5960 Visit(TL.getWrappedLoc());
5961 }
5962 void VisitHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL) {
5963 Visit(TL.getWrappedLoc());
5965 }
5966 void VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {}
5967 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
5968 Visit(TL.getInnerLoc());
5969 TL.setExpansionLoc(
5970 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
5971 }
5972 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5973 Visit(TL.getUnqualifiedLoc());
5974 }
5975 // Allow to fill pointee's type locations, e.g.,
5976 // int __attr * __attr * __attr *p;
5977 void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); }
5978 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5979 if (DS.getTypeSpecType() == TST_typename) {
5980 TypeSourceInfo *TInfo = nullptr;
5982 if (TInfo) {
5983 TL.copy(TInfo->getTypeLoc().castAs<TypedefTypeLoc>());
5984 return;
5985 }
5986 }
5987 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
5988 ? DS.getTypeSpecTypeLoc()
5989 : SourceLocation(),
5992 }
5993 void VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5994 if (DS.getTypeSpecType() == TST_typename) {
5995 TypeSourceInfo *TInfo = nullptr;
5997 if (TInfo) {
5998 TL.copy(TInfo->getTypeLoc().castAs<UnresolvedUsingTypeLoc>());
5999 return;
6000 }
6001 }
6002 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6003 ? DS.getTypeSpecTypeLoc()
6004 : SourceLocation(),
6007 }
6008 void VisitUsingTypeLoc(UsingTypeLoc TL) {
6009 if (DS.getTypeSpecType() == TST_typename) {
6010 TypeSourceInfo *TInfo = nullptr;
6012 if (TInfo) {
6013 TL.copy(TInfo->getTypeLoc().castAs<UsingTypeLoc>());
6014 return;
6015 }
6016 }
6017 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6018 ? DS.getTypeSpecTypeLoc()
6019 : SourceLocation(),
6022 }
6023 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6025 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
6026 // addition field. What we have is good enough for display of location
6027 // of 'fixit' on interface name.
6028 TL.setNameEndLoc(DS.getEndLoc());
6029 }
6030 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6031 TypeSourceInfo *RepTInfo = nullptr;
6032 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6033 TL.copy(RepTInfo->getTypeLoc());
6034 }
6035 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6036 TypeSourceInfo *RepTInfo = nullptr;
6037 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6038 TL.copy(RepTInfo->getTypeLoc());
6039 }
6040 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
6041 TypeSourceInfo *TInfo = nullptr;
6043
6044 // If we got no declarator info from previous Sema routines,
6045 // just fill with the typespec loc.
6046 if (!TInfo) {
6047 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
6048 return;
6049 }
6050
6051 TypeLoc OldTL = TInfo->getTypeLoc();
6052 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
6053 assert(TL.getRAngleLoc() ==
6054 OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
6055 }
6056 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6061 }
6062 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6067 assert(DS.getRepAsType());
6068 TypeSourceInfo *TInfo = nullptr;
6070 TL.setUnmodifiedTInfo(TInfo);
6071 }
6072 void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6076 }
6077 void VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
6080 }
6081 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6082 assert(DS.isTransformTypeTrait(DS.getTypeSpecType()));
6085 assert(DS.getRepAsType());
6086 TypeSourceInfo *TInfo = nullptr;
6088 TL.setUnderlyingTInfo(TInfo);
6089 }
6090 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6091 // By default, use the source location of the type specifier.
6093 if (TL.needsExtraLocalData()) {
6094 // Set info for the written builtin specifiers.
6096 // Try to have a meaningful source location.
6097 if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified)
6099 if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified)
6101 }
6102 }
6103 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6104 assert(DS.getTypeSpecType() == TST_typename);
6105 TypeSourceInfo *TInfo = nullptr;
6107 assert(TInfo);
6108 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
6109 }
6110 void VisitAutoTypeLoc(AutoTypeLoc TL) {
6111 assert(DS.getTypeSpecType() == TST_auto ||
6118 if (!DS.isConstrainedAuto())
6119 return;
6120 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
6121 if (!TemplateId)
6122 return;
6123
6124 NestedNameSpecifierLoc NNS =
6125 (DS.getTypeSpecScope().isNotEmpty()
6127 : NestedNameSpecifierLoc());
6128 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
6129 TemplateId->RAngleLoc);
6130 if (TemplateId->NumArgs > 0) {
6131 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6132 TemplateId->NumArgs);
6133 SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
6134 }
6135 DeclarationNameInfo DNI = DeclarationNameInfo(
6136 TL.getTypePtr()->getTypeConstraintConcept()->getDeclName(),
6137 TemplateId->TemplateNameLoc);
6138
6139 NamedDecl *FoundDecl;
6140 if (auto TN = TemplateId->Template.get();
6141 UsingShadowDecl *USD = TN.getAsUsingShadowDecl())
6142 FoundDecl = cast<NamedDecl>(USD);
6143 else
6144 FoundDecl = cast_if_present<NamedDecl>(TN.getAsTemplateDecl());
6145
6146 auto *CR = ConceptReference::Create(
6147 Context, NNS, TemplateId->TemplateKWLoc, DNI, FoundDecl,
6148 /*NamedDecl=*/TL.getTypePtr()->getTypeConstraintConcept(),
6149 ASTTemplateArgumentListInfo::Create(Context, TemplateArgsInfo));
6150 TL.setConceptReference(CR);
6151 }
6152 void VisitDeducedTemplateSpecializationTypeLoc(
6153 DeducedTemplateSpecializationTypeLoc TL) {
6154 assert(DS.getTypeSpecType() == TST_typename);
6155 TypeSourceInfo *TInfo = nullptr;
6157 assert(TInfo);
6158 TL.copy(
6159 TInfo->getTypeLoc().castAs<DeducedTemplateSpecializationTypeLoc>());
6160 }
6161 void VisitTagTypeLoc(TagTypeLoc TL) {
6162 if (DS.getTypeSpecType() == TST_typename) {
6163 TypeSourceInfo *TInfo = nullptr;
6165 if (TInfo) {
6166 TL.copy(TInfo->getTypeLoc().castAs<TagTypeLoc>());
6167 return;
6168 }
6169 }
6170 TL.setElaboratedKeywordLoc(TL.getTypePtr()->getKeyword() !=
6171 ElaboratedTypeKeyword::None
6172 ? DS.getTypeSpecTypeLoc()
6173 : SourceLocation());
6176 }
6177 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6178 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
6179 // or an _Atomic qualifier.
6183
6184 TypeSourceInfo *TInfo = nullptr;
6186 assert(TInfo);
6188 } else {
6189 TL.setKWLoc(DS.getAtomicSpecLoc());
6190 // No parens, to indicate this was spelled as an _Atomic qualifier.
6191 TL.setParensRange(SourceRange());
6192 Visit(TL.getValueLoc());
6193 }
6194 }
6195
6196 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6198
6199 TypeSourceInfo *TInfo = nullptr;
6202 }
6203
6204 void VisitExtIntTypeLoc(BitIntTypeLoc TL) {
6206 }
6207
6208 void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) {
6210 }
6211
6212 void VisitTypeLoc(TypeLoc TL) {
6213 // FIXME: add other typespec types and change this to an assert.
6214 TL.initialize(Context, DS.getTypeSpecTypeLoc());
6215 }
6216 };
6217
6218 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
6219 ASTContext &Context;
6220 TypeProcessingState &State;
6221 const DeclaratorChunk &Chunk;
6222
6223 public:
6224 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
6225 const DeclaratorChunk &Chunk)
6226 : Context(Context), State(State), Chunk(Chunk) {}
6227
6228 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6229 llvm_unreachable("qualified type locs not expected here!");
6230 }
6231 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6232 llvm_unreachable("decayed type locs not expected here!");
6233 }
6234 void VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
6235 llvm_unreachable("array parameter type locs not expected here!");
6236 }
6237
6238 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6239 fillAttributedTypeLoc(TL, State);
6240 }
6241 void VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
6242 // nothing
6243 }
6244 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6245 // nothing
6246 }
6247 void VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
6248 // nothing
6249 }
6250 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6251 // nothing
6252 }
6253 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6254 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
6255 TL.setCaretLoc(Chunk.Loc);
6256 }
6257 void VisitPointerTypeLoc(PointerTypeLoc TL) {
6258 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6259 TL.setStarLoc(Chunk.Loc);
6260 }
6261 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6262 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6263 TL.setStarLoc(Chunk.Loc);
6264 }
6265 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6266 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
6267 TL.setStarLoc(Chunk.Mem.StarLoc);
6268 TL.setQualifierLoc(Chunk.Mem.Scope().getWithLocInContext(Context));
6269 }
6270 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6271 assert(Chunk.Kind == DeclaratorChunk::Reference);
6272 // 'Amp' is misleading: this might have been originally
6273 /// spelled with AmpAmp.
6274 TL.setAmpLoc(Chunk.Loc);
6275 }
6276 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6277 assert(Chunk.Kind == DeclaratorChunk::Reference);
6278 assert(!Chunk.Ref.LValueRef);
6279 TL.setAmpAmpLoc(Chunk.Loc);
6280 }
6281 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
6282 assert(Chunk.Kind == DeclaratorChunk::Array);
6283 TL.setLBracketLoc(Chunk.Loc);
6284 TL.setRBracketLoc(Chunk.EndLoc);
6285 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
6286 }
6287 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6288 assert(Chunk.Kind == DeclaratorChunk::Function);
6289 TL.setLocalRangeBegin(Chunk.Loc);
6290 TL.setLocalRangeEnd(Chunk.EndLoc);
6291
6292 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
6293 TL.setLParenLoc(FTI.getLParenLoc());
6294 TL.setRParenLoc(FTI.getRParenLoc());
6295 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
6296 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
6297 TL.setParam(tpi++, Param);
6298 }
6300 }
6301 void VisitParenTypeLoc(ParenTypeLoc TL) {
6302 assert(Chunk.Kind == DeclaratorChunk::Paren);
6303 TL.setLParenLoc(Chunk.Loc);
6304 TL.setRParenLoc(Chunk.EndLoc);
6305 }
6306 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6307 assert(Chunk.Kind == DeclaratorChunk::Pipe);
6308 TL.setKWLoc(Chunk.Loc);
6309 }
6310 void VisitBitIntTypeLoc(BitIntTypeLoc TL) {
6311 TL.setNameLoc(Chunk.Loc);
6312 }
6313 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6314 TL.setExpansionLoc(Chunk.Loc);
6315 }
6316 void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); }
6317 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) {
6318 TL.setNameLoc(Chunk.Loc);
6319 }
6320 void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6321 TL.setNameLoc(Chunk.Loc);
6322 }
6323 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6324 fillAtomicQualLoc(TL, Chunk);
6325 }
6326 void
6327 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) {
6328 TL.setNameLoc(Chunk.Loc);
6329 }
6330 void VisitMatrixTypeLoc(MatrixTypeLoc TL) {
6331 fillMatrixTypeLoc(TL, Chunk.getAttrs());
6332 }
6333
6334 void VisitTypeLoc(TypeLoc TL) {
6335 llvm_unreachable("unsupported TypeLoc kind in declarator!");
6336 }
6337 };
6338} // end anonymous namespace
6339
6340static void
6342 const ParsedAttributesView &Attrs) {
6343 for (const ParsedAttr &AL : Attrs) {
6344 if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
6345 DASTL.setAttrNameLoc(AL.getLoc());
6346 DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
6348 return;
6349 }
6350 }
6351
6352 llvm_unreachable(
6353 "no address_space attribute found at the expected location!");
6354}
6355
6356/// Create and instantiate a TypeSourceInfo with type source information.
6357///
6358/// \param T QualType referring to the type as written in source code.
6359///
6360/// \param ReturnTypeInfo For declarators whose return type does not show
6361/// up in the normal place in the declaration specifiers (such as a C++
6362/// conversion function), this pointer will refer to a type source information
6363/// for that return type.
6364static TypeSourceInfo *
6365GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
6366 QualType T, TypeSourceInfo *ReturnTypeInfo) {
6367 Sema &S = State.getSema();
6368 Declarator &D = State.getDeclarator();
6369
6371 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
6372
6373 // Handle parameter packs whose type is a pack expansion.
6374 if (isa<PackExpansionType>(T)) {
6375 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
6376 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6377 }
6378
6379 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6380 // Microsoft property fields can have multiple sizeless array chunks
6381 // (i.e. int x[][][]). Don't create more than one level of incomplete array.
6382 if (CurrTL.getTypeLocClass() == TypeLoc::IncompleteArray && e != 1 &&
6384 continue;
6385
6386 // An AtomicTypeLoc might be produced by an atomic qualifier in this
6387 // declarator chunk.
6388 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
6390 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
6391 }
6392
6393 bool HasDesugaredTypeLoc = true;
6394 while (HasDesugaredTypeLoc) {
6395 switch (CurrTL.getTypeLocClass()) {
6396 case TypeLoc::MacroQualified: {
6397 auto TL = CurrTL.castAs<MacroQualifiedTypeLoc>();
6398 TL.setExpansionLoc(
6399 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6400 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6401 break;
6402 }
6403
6404 case TypeLoc::Attributed: {
6405 auto TL = CurrTL.castAs<AttributedTypeLoc>();
6406 fillAttributedTypeLoc(TL, State);
6407 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6408 break;
6409 }
6410
6411 case TypeLoc::Adjusted:
6412 case TypeLoc::BTFTagAttributed: {
6413 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6414 break;
6415 }
6416
6417 case TypeLoc::DependentAddressSpace: {
6418 auto TL = CurrTL.castAs<DependentAddressSpaceTypeLoc>();
6420 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
6421 break;
6422 }
6423
6424 default:
6425 HasDesugaredTypeLoc = false;
6426 break;
6427 }
6428 }
6429
6430 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
6431 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6432 }
6433
6434 // If we have different source information for the return type, use
6435 // that. This really only applies to C++ conversion functions.
6436 if (ReturnTypeInfo) {
6437 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
6438 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
6439 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
6440 } else {
6441 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL);
6442 }
6443
6444 return TInfo;
6445}
6446
6447/// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
6449 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6450 // and Sema during declaration parsing. Try deallocating/caching them when
6451 // it's appropriate, instead of allocating them and keeping them around.
6452 LocInfoType *LocT = (LocInfoType *)BumpAlloc.Allocate(sizeof(LocInfoType),
6453 alignof(LocInfoType));
6454 new (LocT) LocInfoType(T, TInfo);
6455 assert(LocT->getTypeClass() != T->getTypeClass() &&
6456 "LocInfoType's TypeClass conflicts with an existing Type class");
6457 return ParsedType::make(QualType(LocT, 0));
6458}
6459
6461 const PrintingPolicy &Policy) const {
6462 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6463 " was used directly instead of getting the QualType through"
6464 " GetTypeFromParser");
6465}
6466
6468 // C99 6.7.6: Type names have no identifier. This is already validated by
6469 // the parser.
6470 assert(D.getIdentifier() == nullptr &&
6471 "Type name should have no identifier!");
6472
6474 QualType T = TInfo->getType();
6475 if (D.isInvalidType())
6476 return true;
6477
6478 // Make sure there are no unused decl attributes on the declarator.
6479 // We don't want to do this for ObjC parameters because we're going
6480 // to apply them to the actual parameter declaration.
6481 // Likewise, we don't want to do this for alias declarations, because
6482 // we are actually going to build a declaration from this eventually.
6487
6488 if (getLangOpts().CPlusPlus) {
6489 // Check that there are no default arguments (C++ only).
6491 }
6492
6493 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
6494 const AutoType *AT = TL.getTypePtr();
6495 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
6496 }
6497 return CreateParsedType(T, TInfo);
6498}
6499
6500//===----------------------------------------------------------------------===//
6501// Type Attribute Processing
6502//===----------------------------------------------------------------------===//
6503
6504/// Build an AddressSpace index from a constant expression and diagnose any
6505/// errors related to invalid address_spaces. Returns true on successfully
6506/// building an AddressSpace index.
6507static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
6508 const Expr *AddrSpace,
6509 SourceLocation AttrLoc) {
6510 if (!AddrSpace->isValueDependent()) {
6511 std::optional<llvm::APSInt> OptAddrSpace =
6512 AddrSpace->getIntegerConstantExpr(S.Context);
6513 if (!OptAddrSpace) {
6514 S.Diag(AttrLoc, diag::err_attribute_argument_type)
6515 << "'address_space'" << AANT_ArgumentIntegerConstant
6516 << AddrSpace->getSourceRange();
6517 return false;
6518 }
6519 llvm::APSInt &addrSpace = *OptAddrSpace;
6520
6521 // Bounds checking.
6522 if (addrSpace.isSigned()) {
6523 if (addrSpace.isNegative()) {
6524 S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
6525 << AddrSpace->getSourceRange();
6526 return false;
6527 }
6528 addrSpace.setIsSigned(false);
6529 }
6530
6531 llvm::APSInt max(addrSpace.getBitWidth());
6532 max =
6534
6535 if (addrSpace > max) {
6536 S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
6537 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
6538 return false;
6539 }
6540
6541 ASIdx =
6542 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
6543 return true;
6544 }
6545
6546 // Default value for DependentAddressSpaceTypes
6547 ASIdx = LangAS::Default;
6548 return true;
6549}
6550
6552 SourceLocation AttrLoc) {
6553 if (!AddrSpace->isValueDependent()) {
6554 if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
6555 AttrLoc))
6556 return QualType();
6557
6558 return Context.getAddrSpaceQualType(T, ASIdx);
6559 }
6560
6561 // A check with similar intentions as checking if a type already has an
6562 // address space except for on a dependent types, basically if the
6563 // current type is already a DependentAddressSpaceType then its already
6564 // lined up to have another address space on it and we can't have
6565 // multiple address spaces on the one pointer indirection
6566 if (T->getAs<DependentAddressSpaceType>()) {
6567 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
6568 return QualType();
6569 }
6570
6571 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
6572}
6573
6575 SourceLocation AttrLoc) {
6576 LangAS ASIdx;
6577 if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
6578 return QualType();
6579 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
6580}
6581
6583 TypeProcessingState &State) {
6584 Sema &S = State.getSema();
6585
6586 // This attribute is only supported in C.
6587 // FIXME: we should implement checkCommonAttributeFeatures() in SemaAttr.cpp
6588 // such that it handles type attributes, and then call that from
6589 // processTypeAttrs() instead of one-off checks like this.
6590 if (!Attr.diagnoseLangOpts(S)) {
6591 Attr.setInvalid();
6592 return;
6593 }
6594
6595 // Check the number of attribute arguments.
6596 if (Attr.getNumArgs() != 1) {
6597 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6598 << Attr << 1;
6599 Attr.setInvalid();
6600 return;
6601 }
6602
6603 // Ensure the argument is a string.
6604 auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6605 if (!StrLiteral) {
6606 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6608 Attr.setInvalid();
6609 return;
6610 }
6611
6612 ASTContext &Ctx = S.Context;
6613 StringRef BTFTypeTag = StrLiteral->getString();
6614 Type = State.getBTFTagAttributedType(
6615 ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type);
6616}
6617
6618/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6619/// specified type. The attribute contains 1 argument, the id of the address
6620/// space for the type.
6622 const ParsedAttr &Attr,
6623 TypeProcessingState &State) {
6624 Sema &S = State.getSema();
6625
6626 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6627 // qualified by an address-space qualifier."
6628 if (Type->isFunctionType()) {
6629 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
6630 Attr.setInvalid();
6631 return;
6632 }
6633
6634 LangAS ASIdx;
6635 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
6636
6637 // Check the attribute arguments.
6638 if (Attr.getNumArgs() != 1) {
6639 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
6640 << 1;
6641 Attr.setInvalid();
6642 return;
6643 }
6644
6645 Expr *ASArgExpr = Attr.getArgAsExpr(0);
6646 LangAS ASIdx;
6647 if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
6648 Attr.setInvalid();
6649 return;
6650 }
6651
6652 ASTContext &Ctx = S.Context;
6653 auto *ASAttr =
6654 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
6655
6656 // If the expression is not value dependent (not templated), then we can
6657 // apply the address space qualifiers just to the equivalent type.
6658 // Otherwise, we make an AttributedType with the modified and equivalent
6659 // type the same, and wrap it in a DependentAddressSpaceType. When this
6660 // dependent type is resolved, the qualifier is added to the equivalent type
6661 // later.
6662 QualType T;
6663 if (!ASArgExpr->isValueDependent()) {
6664 QualType EquivType =
6665 S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
6666 if (EquivType.isNull()) {
6667 Attr.setInvalid();
6668 return;
6669 }
6670 T = State.getAttributedType(ASAttr, Type, EquivType);
6671 } else {
6672 T = State.getAttributedType(ASAttr, Type, Type);
6673 T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
6674 }
6675
6676 if (!T.isNull())
6677 Type = T;
6678 else
6679 Attr.setInvalid();
6680 } else {
6681 // The keyword-based type attributes imply which address space to use.
6682 ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS()
6683 : Attr.asOpenCLLangAS();
6684 if (S.getLangOpts().HLSL)
6685 ASIdx = Attr.asHLSLLangAS();
6686
6687 if (ASIdx == LangAS::Default)
6688 llvm_unreachable("Invalid address space");
6689
6690 if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
6691 Attr.getLoc())) {
6692 Attr.setInvalid();
6693 return;
6694 }
6695
6697 }
6698}
6699
6701 TypeProcessingState &State) {
6702 Sema &S = State.getSema();
6703
6704 // Check for -fexperimental-overflow-behavior-types
6705 if (!S.getLangOpts().OverflowBehaviorTypes) {
6706 S.Diag(Attr.getLoc(), diag::warn_overflow_behavior_attribute_disabled)
6707 << Attr << 1;
6708 Attr.setInvalid();
6709 return;
6710 }
6711
6712 // Check the number of attribute arguments.
6713 if (Attr.getNumArgs() != 1) {
6714 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6715 << Attr << 1;
6716 Attr.setInvalid();
6717 return;
6718 }
6719
6720 // Check that the underlying type is an integer type
6721 if (!Type->isIntegerType()) {
6722 S.Diag(Attr.getLoc(), diag::err_overflow_behavior_non_integer_type)
6723 << Attr << Type.getAsString() << 0; // 0 for attribute
6724 Attr.setInvalid();
6725 return;
6726 }
6727
6728 StringRef KindName = "";
6729 IdentifierInfo *Ident = nullptr;
6730
6731 if (Attr.isArgIdent(0)) {
6732 Ident = Attr.getArgAsIdent(0)->getIdentifierInfo();
6733 KindName = Ident->getName();
6734 }
6735
6736 // Support identifier or string argument types. Failure to provide one of
6737 // these two types results in a diagnostic that hints towards using string
6738 // arguments (either "wrap" or "trap") as this is the most common use
6739 // pattern.
6740 if (!Ident) {
6741 auto *Str = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6742 if (Str)
6743 KindName = Str->getString();
6744 else {
6745 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6747 Attr.setInvalid();
6748 return;
6749 }
6750 }
6751
6752 OverflowBehaviorType::OverflowBehaviorKind Kind;
6753 if (KindName == "wrap") {
6754 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
6755 } else if (KindName == "trap") {
6756 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
6757 } else {
6758 S.Diag(Attr.getLoc(), diag::err_overflow_behavior_unknown_ident)
6759 << KindName << Attr;
6760 Attr.setInvalid();
6761 return;
6762 }
6763
6764 // Check for mixed specifier/attribute usage
6765 const DeclSpec &DS = State.getDeclarator().getDeclSpec();
6766 if (DS.isWrapSpecified() || DS.isTrapSpecified()) {
6767 // We have both specifier and attribute on the same type. If
6768 // OverflowBehaviorKinds are the same we can just warn.
6769 OverflowBehaviorType::OverflowBehaviorKind SpecifierKind =
6770 DS.isWrapSpecified() ? OverflowBehaviorType::OverflowBehaviorKind::Wrap
6771 : OverflowBehaviorType::OverflowBehaviorKind::Trap;
6772
6773 if (SpecifierKind != Kind) {
6774 StringRef SpecifierName = DS.isWrapSpecified() ? "wrap" : "trap";
6775 S.Diag(Attr.getLoc(), diag::err_conflicting_overflow_behaviors)
6776 << 1 << SpecifierName << KindName;
6777 Attr.setInvalid();
6778 return;
6779 }
6780 S.Diag(Attr.getLoc(), diag::warn_redundant_overflow_behaviors_mixed)
6781 << KindName;
6782 Attr.setInvalid();
6783 return;
6784 }
6785
6786 // Check for conflicting overflow behavior attributes
6787 if (const auto *ExistingOBT = Type->getAs<OverflowBehaviorType>()) {
6788 OverflowBehaviorType::OverflowBehaviorKind ExistingKind =
6789 ExistingOBT->getBehaviorKind();
6790 if (ExistingKind != Kind) {
6791 S.Diag(Attr.getLoc(), diag::err_conflicting_overflow_behaviors) << 0;
6792 if (Kind == OverflowBehaviorType::OverflowBehaviorKind::Trap) {
6793 Type = State.getOverflowBehaviorType(Kind,
6794 ExistingOBT->getUnderlyingType());
6795 }
6796 return;
6797 }
6798 } else {
6799 Type = State.getOverflowBehaviorType(Kind, Type);
6800 }
6801}
6802
6803/// handleObjCOwnershipTypeAttr - Process an objc_ownership
6804/// attribute on the specified type.
6805///
6806/// Returns 'true' if the attribute was handled.
6807static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6809 bool NonObjCPointer = false;
6810
6811 if (!type->isDependentType() && !type->isUndeducedType()) {
6812 if (const PointerType *ptr = type->getAs<PointerType>()) {
6813 QualType pointee = ptr->getPointeeType();
6814 if (pointee->isObjCRetainableType() || pointee->isPointerType())
6815 return false;
6816 // It is important not to lose the source info that there was an attribute
6817 // applied to non-objc pointer. We will create an attributed type but
6818 // its type will be the same as the original type.
6819 NonObjCPointer = true;
6820 } else if (!type->isObjCRetainableType()) {
6821 return false;
6822 }
6823
6824 // Don't accept an ownership attribute in the declspec if it would
6825 // just be the return type of a block pointer.
6826 if (state.isProcessingDeclSpec()) {
6827 Declarator &D = state.getDeclarator();
6829 /*onlyBlockPointers=*/true))
6830 return false;
6831 }
6832 }
6833
6834 Sema &S = state.getSema();
6835 SourceLocation AttrLoc = attr.getLoc();
6836 if (AttrLoc.isMacroID())
6837 AttrLoc =
6839
6840 if (!attr.isArgIdent(0)) {
6841 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
6843 attr.setInvalid();
6844 return true;
6845 }
6846
6847 IdentifierInfo *II = attr.getArgAsIdent(0)->getIdentifierInfo();
6848 Qualifiers::ObjCLifetime lifetime;
6849 if (II->isStr("none"))
6851 else if (II->isStr("strong"))
6852 lifetime = Qualifiers::OCL_Strong;
6853 else if (II->isStr("weak"))
6854 lifetime = Qualifiers::OCL_Weak;
6855 else if (II->isStr("autoreleasing"))
6857 else {
6858 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II;
6859 attr.setInvalid();
6860 return true;
6861 }
6862
6863 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6864 // outside of ARC mode.
6865 if (!S.getLangOpts().ObjCAutoRefCount &&
6866 lifetime != Qualifiers::OCL_Weak &&
6867 lifetime != Qualifiers::OCL_ExplicitNone) {
6868 return true;
6869 }
6870
6871 SplitQualType underlyingType = type.split();
6872
6873 // Check for redundant/conflicting ownership qualifiers.
6874 if (Qualifiers::ObjCLifetime previousLifetime
6875 = type.getQualifiers().getObjCLifetime()) {
6876 // If it's written directly, that's an error.
6878 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
6879 << type;
6880 return true;
6881 }
6882
6883 // Otherwise, if the qualifiers actually conflict, pull sugar off
6884 // and remove the ObjCLifetime qualifiers.
6885 if (previousLifetime != lifetime) {
6886 // It's possible to have multiple local ObjCLifetime qualifiers. We
6887 // can't stop after we reach a type that is directly qualified.
6888 const Type *prevTy = nullptr;
6889 while (!prevTy || prevTy != underlyingType.Ty) {
6890 prevTy = underlyingType.Ty;
6891 underlyingType = underlyingType.getSingleStepDesugaredType();
6892 }
6893 underlyingType.Quals.removeObjCLifetime();
6894 }
6895 }
6896
6897 underlyingType.Quals.addObjCLifetime(lifetime);
6898
6899 if (NonObjCPointer) {
6900 StringRef name = attr.getAttrName()->getName();
6901 switch (lifetime) {
6904 break;
6905 case Qualifiers::OCL_Strong: name = "__strong"; break;
6906 case Qualifiers::OCL_Weak: name = "__weak"; break;
6907 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
6908 }
6909 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
6911 }
6912
6913 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
6914 // because having both 'T' and '__unsafe_unretained T' exist in the type
6915 // system causes unfortunate widespread consistency problems. (For example,
6916 // they're not considered compatible types, and we mangle them identicially
6917 // as template arguments.) These problems are all individually fixable,
6918 // but it's easier to just not add the qualifier and instead sniff it out
6919 // in specific places using isObjCInertUnsafeUnretainedType().
6920 //
6921 // Doing this does means we miss some trivial consistency checks that
6922 // would've triggered in ARC, but that's better than trying to solve all
6923 // the coexistence problems with __unsafe_unretained.
6924 if (!S.getLangOpts().ObjCAutoRefCount &&
6925 lifetime == Qualifiers::OCL_ExplicitNone) {
6926 type = state.getAttributedType(
6928 type, type);
6929 return true;
6930 }
6931
6932 QualType origType = type;
6933 if (!NonObjCPointer)
6934 type = S.Context.getQualifiedType(underlyingType);
6935
6936 // If we have a valid source location for the attribute, use an
6937 // AttributedType instead.
6938 if (AttrLoc.isValid()) {
6939 type = state.getAttributedType(::new (S.Context)
6940 ObjCOwnershipAttr(S.Context, attr, II),
6941 origType, type);
6942 }
6943
6944 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
6945 unsigned diagnostic, QualType type) {
6950 diagnostic, type, /*ignored*/ 0));
6951 } else {
6952 S.Diag(loc, diagnostic);
6953 }
6954 };
6955
6956 // Sometimes, __weak isn't allowed.
6957 if (lifetime == Qualifiers::OCL_Weak &&
6958 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
6959
6960 // Use a specialized diagnostic if the runtime just doesn't support them.
6961 unsigned diagnostic =
6962 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
6963 : diag::err_arc_weak_no_runtime);
6964
6965 // In any case, delay the diagnostic until we know what we're parsing.
6966 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
6967
6968 attr.setInvalid();
6969 return true;
6970 }
6971
6972 // Forbid __weak for class objects marked as
6973 // objc_arc_weak_reference_unavailable
6974 if (lifetime == Qualifiers::OCL_Weak) {
6975 if (const ObjCObjectPointerType *ObjT =
6976 type->getAs<ObjCObjectPointerType>()) {
6977 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
6978 if (Class->isArcWeakrefUnavailable()) {
6979 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
6980 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
6981 diag::note_class_declared);
6982 }
6983 }
6984 }
6985 }
6986
6987 return true;
6988}
6989
6990/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
6991/// attribute on the specified type. Returns true to indicate that
6992/// the attribute was handled, false to indicate that the type does
6993/// not permit the attribute.
6994static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
6995 QualType &type) {
6996 Sema &S = state.getSema();
6997
6998 // Delay if this isn't some kind of pointer.
6999 if (!type->isPointerType() &&
7000 !type->isObjCObjectPointerType() &&
7001 !type->isBlockPointerType())
7002 return false;
7003
7004 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
7005 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
7006 attr.setInvalid();
7007 return true;
7008 }
7009
7010 // Check the attribute arguments.
7011 if (!attr.isArgIdent(0)) {
7012 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
7014 attr.setInvalid();
7015 return true;
7016 }
7017 Qualifiers::GC GCAttr;
7018 if (attr.getNumArgs() > 1) {
7019 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
7020 << 1;
7021 attr.setInvalid();
7022 return true;
7023 }
7024
7025 IdentifierInfo *II = attr.getArgAsIdent(0)->getIdentifierInfo();
7026 if (II->isStr("weak"))
7027 GCAttr = Qualifiers::Weak;
7028 else if (II->isStr("strong"))
7029 GCAttr = Qualifiers::Strong;
7030 else {
7031 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
7032 << attr << II;
7033 attr.setInvalid();
7034 return true;
7035 }
7036
7037 QualType origType = type;
7038 type = S.Context.getObjCGCQualType(origType, GCAttr);
7039
7040 // Make an attributed type to preserve the source information.
7041 if (attr.getLoc().isValid())
7042 type = state.getAttributedType(
7043 ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type);
7044
7045 return true;
7046}
7047
7048namespace {
7049 /// A helper class to unwrap a type down to a function for the
7050 /// purposes of applying attributes there.
7051 ///
7052 /// Use:
7053 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
7054 /// if (unwrapped.isFunctionType()) {
7055 /// const FunctionType *fn = unwrapped.get();
7056 /// // change fn somehow
7057 /// T = unwrapped.wrap(fn);
7058 /// }
7059 struct FunctionTypeUnwrapper {
7060 enum WrapKind {
7061 Desugar,
7062 Attributed,
7063 Parens,
7064 Array,
7065 Pointer,
7066 BlockPointer,
7067 Reference,
7068 MemberPointer,
7069 MacroQualified,
7070 };
7071
7072 QualType Original;
7073 const FunctionType *Fn;
7074 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
7075
7076 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
7077 while (true) {
7078 const Type *Ty = T.getTypePtr();
7079 if (isa<FunctionType>(Ty)) {
7080 Fn = cast<FunctionType>(Ty);
7081 return;
7082 } else if (isa<ParenType>(Ty)) {
7083 T = cast<ParenType>(Ty)->getInnerType();
7084 Stack.push_back(Parens);
7085 } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) ||
7087 T = cast<ArrayType>(Ty)->getElementType();
7088 Stack.push_back(Array);
7089 } else if (isa<PointerType>(Ty)) {
7090 T = cast<PointerType>(Ty)->getPointeeType();
7091 Stack.push_back(Pointer);
7092 } else if (isa<BlockPointerType>(Ty)) {
7093 T = cast<BlockPointerType>(Ty)->getPointeeType();
7094 Stack.push_back(BlockPointer);
7095 } else if (isa<MemberPointerType>(Ty)) {
7096 T = cast<MemberPointerType>(Ty)->getPointeeType();
7097 Stack.push_back(MemberPointer);
7098 } else if (isa<ReferenceType>(Ty)) {
7099 T = cast<ReferenceType>(Ty)->getPointeeType();
7100 Stack.push_back(Reference);
7101 } else if (isa<AttributedType>(Ty)) {
7102 T = cast<AttributedType>(Ty)->getEquivalentType();
7103 Stack.push_back(Attributed);
7104 } else if (isa<MacroQualifiedType>(Ty)) {
7105 T = cast<MacroQualifiedType>(Ty)->getUnderlyingType();
7106 Stack.push_back(MacroQualified);
7107 } else {
7108 const Type *DTy = Ty->getUnqualifiedDesugaredType();
7109 if (Ty == DTy) {
7110 Fn = nullptr;
7111 return;
7112 }
7113
7114 T = QualType(DTy, 0);
7115 Stack.push_back(Desugar);
7116 }
7117 }
7118 }
7119
7120 bool isFunctionType() const { return (Fn != nullptr); }
7121 const FunctionType *get() const { return Fn; }
7122
7123 QualType wrap(Sema &S, const FunctionType *New) {
7124 // If T wasn't modified from the unwrapped type, do nothing.
7125 if (New == get()) return Original;
7126
7127 Fn = New;
7128 return wrap(S.Context, Original, 0);
7129 }
7130
7131 private:
7132 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
7133 if (I == Stack.size())
7134 return C.getQualifiedType(Fn, Old.getQualifiers());
7135
7136 // Build up the inner type, applying the qualifiers from the old
7137 // type to the new type.
7138 SplitQualType SplitOld = Old.split();
7139
7140 // As a special case, tail-recurse if there are no qualifiers.
7141 if (SplitOld.Quals.empty())
7142 return wrap(C, SplitOld.Ty, I);
7143 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
7144 }
7145
7146 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
7147 if (I == Stack.size()) return QualType(Fn, 0);
7148
7149 switch (static_cast<WrapKind>(Stack[I++])) {
7150 case Desugar:
7151 // This is the point at which we potentially lose source
7152 // information.
7153 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
7154
7155 case Attributed:
7156 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
7157
7158 case Parens: {
7159 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
7160 return C.getParenType(New);
7161 }
7162
7163 case MacroQualified:
7164 return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I);
7165
7166 case Array: {
7167 if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) {
7168 QualType New = wrap(C, CAT->getElementType(), I);
7169 return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(),
7170 CAT->getSizeModifier(),
7171 CAT->getIndexTypeCVRQualifiers());
7172 }
7173
7174 if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) {
7175 QualType New = wrap(C, VAT->getElementType(), I);
7176 return C.getVariableArrayType(New, VAT->getSizeExpr(),
7177 VAT->getSizeModifier(),
7178 VAT->getIndexTypeCVRQualifiers());
7179 }
7180
7181 const auto *IAT = cast<IncompleteArrayType>(Old);
7182 QualType New = wrap(C, IAT->getElementType(), I);
7183 return C.getIncompleteArrayType(New, IAT->getSizeModifier(),
7184 IAT->getIndexTypeCVRQualifiers());
7185 }
7186
7187 case Pointer: {
7188 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
7189 return C.getPointerType(New);
7190 }
7191
7192 case BlockPointer: {
7193 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
7194 return C.getBlockPointerType(New);
7195 }
7196
7197 case MemberPointer: {
7198 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
7199 QualType New = wrap(C, OldMPT->getPointeeType(), I);
7200 return C.getMemberPointerType(New, OldMPT->getQualifier(),
7201 OldMPT->getMostRecentCXXRecordDecl());
7202 }
7203
7204 case Reference: {
7205 const ReferenceType *OldRef = cast<ReferenceType>(Old);
7206 QualType New = wrap(C, OldRef->getPointeeType(), I);
7207 if (isa<LValueReferenceType>(OldRef))
7208 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
7209 else
7210 return C.getRValueReferenceType(New);
7211 }
7212 }
7213
7214 llvm_unreachable("unknown wrapping kind");
7215 }
7216 };
7217} // end anonymous namespace
7218
7219static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
7220 ParsedAttr &PAttr, QualType &Type) {
7221 Sema &S = State.getSema();
7222
7223 Attr *A;
7224 switch (PAttr.getKind()) {
7225 default: llvm_unreachable("Unknown attribute kind");
7226 case ParsedAttr::AT_Ptr32:
7228 break;
7229 case ParsedAttr::AT_Ptr64:
7231 break;
7232 case ParsedAttr::AT_SPtr:
7233 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
7234 break;
7235 case ParsedAttr::AT_UPtr:
7236 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
7237 break;
7238 }
7239
7240 std::bitset<attr::LastAttr> Attrs;
7241 QualType Desugared = Type;
7242 for (;;) {
7243 if (const TypedefType *TT = dyn_cast<TypedefType>(Desugared)) {
7244 Desugared = TT->desugar();
7245 continue;
7246 }
7247 const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
7248 if (!AT)
7249 break;
7250 Attrs[AT->getAttrKind()] = true;
7251 Desugared = AT->getModifiedType();
7252 }
7253
7254 // You cannot specify duplicate type attributes, so if the attribute has
7255 // already been applied, flag it.
7256 attr::Kind NewAttrKind = A->getKind();
7257 if (Attrs[NewAttrKind]) {
7258 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7259 return true;
7260 }
7261 Attrs[NewAttrKind] = true;
7262
7263 // You cannot have both __sptr and __uptr on the same type, nor can you
7264 // have __ptr32 and __ptr64.
7265 if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) {
7266 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7267 << "'__ptr32'"
7268 << "'__ptr64'" << /*isRegularKeyword=*/0;
7269 return true;
7270 } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) {
7271 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7272 << "'__sptr'"
7273 << "'__uptr'" << /*isRegularKeyword=*/0;
7274 return true;
7275 }
7276
7277 // Check the raw (i.e., desugared) Canonical type to see if it
7278 // is a pointer type.
7279 if (!isa<PointerType>(Desugared)) {
7280 // Pointer type qualifiers can only operate on pointer types, but not
7281 // pointer-to-member types.
7283 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
7284 else
7285 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
7286 return true;
7287 }
7288
7289 // Add address space to type based on its attributes.
7290 LangAS ASIdx = LangAS::Default;
7291 uint64_t PtrWidth =
7293 if (PtrWidth == 32) {
7294 if (Attrs[attr::Ptr64])
7295 ASIdx = LangAS::ptr64;
7296 else if (Attrs[attr::UPtr])
7297 ASIdx = LangAS::ptr32_uptr;
7298 } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) {
7299 if (S.Context.getTargetInfo().getTriple().isOSzOS() || Attrs[attr::UPtr])
7300 ASIdx = LangAS::ptr32_uptr;
7301 else
7302 ASIdx = LangAS::ptr32_sptr;
7303 }
7304
7305 QualType Pointee = Type->getPointeeType();
7306 if (ASIdx != LangAS::Default)
7307 Pointee = S.Context.getAddrSpaceQualType(
7308 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7309 Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee));
7310 return false;
7311}
7312
7313static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State,
7314 QualType &QT, ParsedAttr &PAttr) {
7315 assert(PAttr.getKind() == ParsedAttr::AT_WebAssemblyFuncref);
7316
7317 Sema &S = State.getSema();
7319
7320 std::bitset<attr::LastAttr> Attrs;
7321 attr::Kind NewAttrKind = A->getKind();
7322 const auto *AT = dyn_cast<AttributedType>(QT);
7323 while (AT) {
7324 Attrs[AT->getAttrKind()] = true;
7325 AT = dyn_cast<AttributedType>(AT->getModifiedType());
7326 }
7327
7328 // You cannot specify duplicate type attributes, so if the attribute has
7329 // already been applied, flag it.
7330 if (Attrs[NewAttrKind]) {
7331 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7332 return true;
7333 }
7334
7335 // Check that the type is a function pointer type.
7336 QualType Desugared = QT.getDesugaredType(S.Context);
7337 const auto *Ptr = dyn_cast<PointerType>(Desugared);
7338 if (!Ptr || !Ptr->getPointeeType()->isFunctionType()) {
7339 S.Diag(PAttr.getLoc(), diag::err_attribute_webassembly_funcref);
7340 return true;
7341 }
7342
7343 // Add address space to type based on its attributes.
7345 QualType Pointee = QT->getPointeeType();
7346 Pointee = S.Context.getAddrSpaceQualType(
7347 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7348 QT = State.getAttributedType(A, QT, S.Context.getPointerType(Pointee));
7349 return false;
7350}
7351
7352static void HandleSwiftAttr(TypeProcessingState &State, TypeAttrLocation TAL,
7353 QualType &QT, ParsedAttr &PAttr) {
7354 if (TAL == TAL_DeclName)
7355 return;
7356
7357 Sema &S = State.getSema();
7358 auto &D = State.getDeclarator();
7359
7360 // If the attribute appears in declaration specifiers
7361 // it should be handled as a declaration attribute,
7362 // unless it's associated with a type or a function
7363 // prototype (i.e. appears on a parameter or result type).
7364 if (State.isProcessingDeclSpec()) {
7365 if (!(D.isPrototypeContext() ||
7366 D.getContext() == DeclaratorContext::TypeName))
7367 return;
7368
7369 if (auto *chunk = D.getInnermostNonParenChunk()) {
7370 moveAttrFromListToList(PAttr, State.getCurrentAttributes(),
7371 const_cast<DeclaratorChunk *>(chunk)->getAttrs());
7372 return;
7373 }
7374 }
7375
7376 StringRef Str;
7377 if (!S.checkStringLiteralArgumentAttr(PAttr, 0, Str)) {
7378 PAttr.setInvalid();
7379 return;
7380 }
7381
7382 // If the attribute as attached to a paren move it closer to
7383 // the declarator. This can happen in block declarations when
7384 // an attribute is placed before `^` i.e. `(__attribute__((...)) ^)`.
7385 //
7386 // Note that it's actually invalid to use GNU style attributes
7387 // in a block but such cases are currently handled gracefully
7388 // but the parser and behavior should be consistent between
7389 // cases when attribute appears before/after block's result
7390 // type and inside (^).
7391 if (TAL == TAL_DeclChunk) {
7392 auto chunkIdx = State.getCurrentChunkIndex();
7393 if (chunkIdx >= 1 &&
7394 D.getTypeObject(chunkIdx).Kind == DeclaratorChunk::Paren) {
7395 moveAttrFromListToList(PAttr, State.getCurrentAttributes(),
7396 D.getTypeObject(chunkIdx - 1).getAttrs());
7397 return;
7398 }
7399 }
7400
7401 auto *A = ::new (S.Context) SwiftAttrAttr(S.Context, PAttr, Str);
7402 QT = State.getAttributedType(A, QT, QT);
7403 PAttr.setUsedAsTypeAttr();
7404}
7405
7406/// Rebuild an attributed type without the nullability attribute on it.
7408 QualType Type) {
7409 auto Attributed = dyn_cast<AttributedType>(Type.getTypePtr());
7410 if (!Attributed)
7411 return Type;
7412
7413 // Skip the nullability attribute; we're done.
7414 if (Attributed->getImmediateNullability())
7415 return Attributed->getModifiedType();
7416
7417 // Build the modified type.
7419 Ctx, Attributed->getModifiedType());
7420 assert(Modified.getTypePtr() != Attributed->getModifiedType().getTypePtr());
7421 return Ctx.getAttributedType(Attributed->getAttrKind(), Modified,
7422 Attributed->getEquivalentType(),
7423 Attributed->getAttr());
7424}
7425
7426/// Map a nullability attribute kind to a nullability kind.
7428 switch (kind) {
7429 case ParsedAttr::AT_TypeNonNull:
7431
7432 case ParsedAttr::AT_TypeNullable:
7434
7435 case ParsedAttr::AT_TypeNullableResult:
7437
7438 case ParsedAttr::AT_TypeNullUnspecified:
7440
7441 default:
7442 llvm_unreachable("not a nullability attribute kind");
7443 }
7444}
7445
7447 Sema &S, TypeProcessingState *State, ParsedAttr *PAttr, QualType &QT,
7448 NullabilityKind Nullability, SourceLocation NullabilityLoc,
7449 bool IsContextSensitive, bool AllowOnArrayType, bool OverrideExisting) {
7450 bool Implicit = (State == nullptr);
7451 if (!Implicit)
7452 recordNullabilitySeen(S, NullabilityLoc);
7453
7454 // Check for existing nullability attributes on the type.
7455 QualType Desugared = QT;
7456 while (auto *Attributed = dyn_cast<AttributedType>(Desugared.getTypePtr())) {
7457 // Check whether there is already a null
7458 if (auto ExistingNullability = Attributed->getImmediateNullability()) {
7459 // Duplicated nullability.
7460 if (Nullability == *ExistingNullability) {
7461 if (Implicit)
7462 break;
7463
7464 S.Diag(NullabilityLoc, diag::warn_nullability_duplicate)
7465 << DiagNullabilityKind(Nullability, IsContextSensitive)
7466 << FixItHint::CreateRemoval(NullabilityLoc);
7467
7468 break;
7469 }
7470
7471 if (!OverrideExisting) {
7472 // Conflicting nullability.
7473 S.Diag(NullabilityLoc, diag::err_nullability_conflicting)
7474 << DiagNullabilityKind(Nullability, IsContextSensitive)
7475 << DiagNullabilityKind(*ExistingNullability, false);
7476 return true;
7477 }
7478
7479 // Rebuild the attributed type, dropping the existing nullability.
7481 }
7482
7483 Desugared = Attributed->getModifiedType();
7484 }
7485
7486 // If there is already a different nullability specifier, complain.
7487 // This (unlike the code above) looks through typedefs that might
7488 // have nullability specifiers on them, which means we cannot
7489 // provide a useful Fix-It.
7490 if (auto ExistingNullability = Desugared->getNullability()) {
7491 if (Nullability != *ExistingNullability && !Implicit) {
7492 S.Diag(NullabilityLoc, diag::err_nullability_conflicting)
7493 << DiagNullabilityKind(Nullability, IsContextSensitive)
7494 << DiagNullabilityKind(*ExistingNullability, false);
7495
7496 // Try to find the typedef with the existing nullability specifier.
7497 if (auto TT = Desugared->getAs<TypedefType>()) {
7498 TypedefNameDecl *typedefDecl = TT->getDecl();
7499 QualType underlyingType = typedefDecl->getUnderlyingType();
7500 if (auto typedefNullability =
7501 AttributedType::stripOuterNullability(underlyingType)) {
7502 if (*typedefNullability == *ExistingNullability) {
7503 S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
7504 << DiagNullabilityKind(*ExistingNullability, false);
7505 }
7506 }
7507 }
7508
7509 return true;
7510 }
7511 }
7512
7513 // If this definitely isn't a pointer type, reject the specifier.
7514 if (!Desugared->canHaveNullability() &&
7515 !(AllowOnArrayType && Desugared->isArrayType())) {
7516 if (!Implicit)
7517 S.Diag(NullabilityLoc, diag::err_nullability_nonpointer)
7518 << DiagNullabilityKind(Nullability, IsContextSensitive) << QT;
7519
7520 return true;
7521 }
7522
7523 // For the context-sensitive keywords/Objective-C property
7524 // attributes, require that the type be a single-level pointer.
7525 if (IsContextSensitive) {
7526 // Make sure that the pointee isn't itself a pointer type.
7527 const Type *pointeeType = nullptr;
7528 if (Desugared->isArrayType())
7529 pointeeType = Desugared->getArrayElementTypeNoTypeQual();
7530 else if (Desugared->isAnyPointerType())
7531 pointeeType = Desugared->getPointeeType().getTypePtr();
7532
7533 if (pointeeType && (pointeeType->isAnyPointerType() ||
7534 pointeeType->isObjCObjectPointerType() ||
7535 pointeeType->isMemberPointerType())) {
7536 S.Diag(NullabilityLoc, diag::err_nullability_cs_multilevel)
7537 << DiagNullabilityKind(Nullability, true) << QT;
7538 S.Diag(NullabilityLoc, diag::note_nullability_type_specifier)
7539 << DiagNullabilityKind(Nullability, false) << QT
7540 << FixItHint::CreateReplacement(NullabilityLoc,
7541 getNullabilitySpelling(Nullability));
7542 return true;
7543 }
7544 }
7545
7546 // Form the attributed type.
7547 if (State) {
7548 assert(PAttr);
7549 Attr *A = createNullabilityAttr(S.Context, *PAttr, Nullability);
7550 QT = State->getAttributedType(A, QT, QT);
7551 } else {
7552 QT = S.Context.getAttributedType(Nullability, QT, QT);
7553 }
7554 return false;
7555}
7556
7557static bool CheckNullabilityTypeSpecifier(TypeProcessingState &State,
7559 bool AllowOnArrayType) {
7561 SourceLocation NullabilityLoc = Attr.getLoc();
7562 bool IsContextSensitive = Attr.isContextSensitiveKeywordAttribute();
7563
7564 return CheckNullabilityTypeSpecifier(State.getSema(), &State, &Attr, Type,
7565 Nullability, NullabilityLoc,
7566 IsContextSensitive, AllowOnArrayType,
7567 /*overrideExisting*/ false);
7568}
7569
7571 NullabilityKind Nullability,
7572 SourceLocation DiagLoc,
7573 bool AllowArrayTypes,
7574 bool OverrideExisting) {
7576 *this, nullptr, nullptr, Type, Nullability, DiagLoc,
7577 /*isContextSensitive*/ false, AllowArrayTypes, OverrideExisting);
7578}
7579
7581 QualType T = VD->getType();
7582
7583 // Check that the variable's type can fit in the specified address space. This
7584 // is determined by how far a pointer in that address space can reach.
7585 llvm::APInt MaxSizeForAddrSpace =
7586 llvm::APInt::getMaxValue(Context.getTargetInfo().getPointerWidth(AS));
7587 std::optional<CharUnits> TSizeInChars = Context.getTypeSizeInCharsIfKnown(T);
7588 if (TSizeInChars && static_cast<uint64_t>(TSizeInChars->getQuantity()) >
7589 MaxSizeForAddrSpace.getZExtValue()) {
7590 Diag(VD->getLocation(), diag::err_type_too_large_for_address_space)
7591 << T << MaxSizeForAddrSpace;
7592 return false;
7593 }
7594
7595 return true;
7596}
7597
7598/// Check the application of the Objective-C '__kindof' qualifier to
7599/// the given type.
7600static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
7601 ParsedAttr &attr) {
7602 Sema &S = state.getSema();
7603
7605 // Build the attributed type to record where __kindof occurred.
7606 type = state.getAttributedType(
7608 return false;
7609 }
7610
7611 // Find out if it's an Objective-C object or object pointer type;
7612 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
7613 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
7614 : type->getAs<ObjCObjectType>();
7615
7616 // If not, we can't apply __kindof.
7617 if (!objType) {
7618 // FIXME: Handle dependent types that aren't yet object types.
7619 S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
7620 << type;
7621 return true;
7622 }
7623
7624 // Rebuild the "equivalent" type, which pushes __kindof down into
7625 // the object type.
7626 // There is no need to apply kindof on an unqualified id type.
7627 QualType equivType = S.Context.getObjCObjectType(
7628 objType->getBaseType(), objType->getTypeArgsAsWritten(),
7629 objType->getProtocols(),
7630 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
7631
7632 // If we started with an object pointer type, rebuild it.
7633 if (ptrType) {
7634 equivType = S.Context.getObjCObjectPointerType(equivType);
7635 if (auto nullability = type->getNullability()) {
7636 // We create a nullability attribute from the __kindof attribute.
7637 // Make sure that will make sense.
7638 assert(attr.getAttributeSpellingListIndex() == 0 &&
7639 "multiple spellings for __kindof?");
7640 Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
7641 A->setImplicit(true);
7642 equivType = state.getAttributedType(A, equivType, equivType);
7643 }
7644 }
7645
7646 // Build the attributed type to record where __kindof occurred.
7647 type = state.getAttributedType(
7649 return false;
7650}
7651
7652/// Distribute a nullability type attribute that cannot be applied to
7653/// the type specifier to a pointer, block pointer, or member pointer
7654/// declarator, complaining if necessary.
7655///
7656/// \returns true if the nullability annotation was distributed, false
7657/// otherwise.
7658static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
7660 Declarator &declarator = state.getDeclarator();
7661
7662 /// Attempt to move the attribute to the specified chunk.
7663 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
7664 // If there is already a nullability attribute there, don't add
7665 // one.
7666 if (hasNullabilityAttr(chunk.getAttrs()))
7667 return false;
7668
7669 // Complain about the nullability qualifier being in the wrong
7670 // place.
7671 enum {
7672 PK_Pointer,
7673 PK_BlockPointer,
7674 PK_MemberPointer,
7675 PK_FunctionPointer,
7676 PK_MemberFunctionPointer,
7677 } pointerKind
7678 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
7679 : PK_Pointer)
7680 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
7681 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
7682
7683 auto diag = state.getSema().Diag(attr.getLoc(),
7684 diag::warn_nullability_declspec)
7686 attr.isContextSensitiveKeywordAttribute())
7687 << type
7688 << static_cast<unsigned>(pointerKind);
7689
7690 // FIXME: MemberPointer chunks don't carry the location of the *.
7691 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
7694 state.getSema().getPreprocessor().getLocForEndOfToken(
7695 chunk.Loc),
7696 " " + attr.getAttrName()->getName().str() + " ");
7697 }
7698
7699 moveAttrFromListToList(attr, state.getCurrentAttributes(),
7700 chunk.getAttrs());
7701 return true;
7702 };
7703
7704 // Move it to the outermost pointer, member pointer, or block
7705 // pointer declarator.
7706 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
7707 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
7708 switch (chunk.Kind) {
7712 return moveToChunk(chunk, false);
7713
7716 continue;
7717
7719 // Try to move past the return type to a function/block/member
7720 // function pointer.
7722 declarator, i,
7723 /*onlyBlockPointers=*/false)) {
7724 return moveToChunk(*dest, true);
7725 }
7726
7727 return false;
7728
7729 // Don't walk through these.
7732 return false;
7733 }
7734 }
7735
7736 return false;
7737}
7738
7740 assert(!Attr.isInvalid());
7741 switch (Attr.getKind()) {
7742 default:
7743 llvm_unreachable("not a calling convention attribute");
7744 case ParsedAttr::AT_CDecl:
7745 return createSimpleAttr<CDeclAttr>(Ctx, Attr);
7746 case ParsedAttr::AT_FastCall:
7748 case ParsedAttr::AT_StdCall:
7750 case ParsedAttr::AT_ThisCall:
7752 case ParsedAttr::AT_RegCall:
7754 case ParsedAttr::AT_Pascal:
7756 case ParsedAttr::AT_SwiftCall:
7758 case ParsedAttr::AT_SwiftAsyncCall:
7760 case ParsedAttr::AT_VectorCall:
7762 case ParsedAttr::AT_AArch64VectorPcs:
7764 case ParsedAttr::AT_AArch64SVEPcs:
7766 case ParsedAttr::AT_ArmStreaming:
7768 case ParsedAttr::AT_Pcs: {
7769 // The attribute may have had a fixit applied where we treated an
7770 // identifier as a string literal. The contents of the string are valid,
7771 // but the form may not be.
7772 StringRef Str;
7773 if (Attr.isArgExpr(0))
7774 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
7775 else
7776 Str = Attr.getArgAsIdent(0)->getIdentifierInfo()->getName();
7777 PcsAttr::PCSType Type;
7778 if (!PcsAttr::ConvertStrToPCSType(Str, Type))
7779 llvm_unreachable("already validated the attribute");
7780 return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
7781 }
7782 case ParsedAttr::AT_IntelOclBicc:
7784 case ParsedAttr::AT_MSABI:
7785 return createSimpleAttr<MSABIAttr>(Ctx, Attr);
7786 case ParsedAttr::AT_SysVABI:
7788 case ParsedAttr::AT_PreserveMost:
7790 case ParsedAttr::AT_PreserveAll:
7792 case ParsedAttr::AT_M68kRTD:
7794 case ParsedAttr::AT_PreserveNone:
7796 case ParsedAttr::AT_RISCVVectorCC:
7798 case ParsedAttr::AT_RISCVVLSCC: {
7799 // If the riscv_abi_vlen doesn't have any argument, we set set it to default
7800 // value 128.
7801 unsigned ABIVLen = 128;
7802 if (Attr.getNumArgs()) {
7803 std::optional<llvm::APSInt> MaybeABIVLen =
7804 Attr.getArgAsExpr(0)->getIntegerConstantExpr(Ctx);
7805 if (!MaybeABIVLen)
7806 llvm_unreachable("Invalid RISC-V ABI VLEN");
7807 ABIVLen = MaybeABIVLen->getZExtValue();
7808 }
7809
7810 return ::new (Ctx) RISCVVLSCCAttr(Ctx, Attr, ABIVLen);
7811 }
7812 }
7813 llvm_unreachable("unexpected attribute kind!");
7814}
7815
7816std::optional<FunctionEffectMode>
7817Sema::ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName) {
7818 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent())
7820
7821 std::optional<llvm::APSInt> ConditionValue =
7823 if (!ConditionValue) {
7824 // FIXME: err_attribute_argument_type doesn't quote the attribute
7825 // name but needs to; users are inconsistent.
7826 Diag(CondExpr->getExprLoc(), diag::err_attribute_argument_type)
7827 << AttributeName << AANT_ArgumentIntegerConstant
7828 << CondExpr->getSourceRange();
7829 return std::nullopt;
7830 }
7831 return !ConditionValue->isZero() ? FunctionEffectMode::True
7833}
7834
7835static bool
7836handleNonBlockingNonAllocatingTypeAttr(TypeProcessingState &TPState,
7837 ParsedAttr &PAttr, QualType &QT,
7838 FunctionTypeUnwrapper &Unwrapped) {
7839 // Delay if this is not a function type.
7840 if (!Unwrapped.isFunctionType())
7841 return false;
7842
7843 Sema &S = TPState.getSema();
7844
7845 // Require FunctionProtoType.
7846 auto *FPT = Unwrapped.get()->getAs<FunctionProtoType>();
7847 if (FPT == nullptr) {
7848 S.Diag(PAttr.getLoc(), diag::err_func_with_effects_no_prototype)
7849 << PAttr.getAttrName()->getName();
7850 return true;
7851 }
7852
7853 // Parse the new attribute.
7854 // non/blocking or non/allocating? Or conditional (computed)?
7855 bool IsNonBlocking = PAttr.getKind() == ParsedAttr::AT_NonBlocking ||
7856 PAttr.getKind() == ParsedAttr::AT_Blocking;
7857
7859 Expr *CondExpr = nullptr; // only valid if dependent
7860
7861 if (PAttr.getKind() == ParsedAttr::AT_NonBlocking ||
7862 PAttr.getKind() == ParsedAttr::AT_NonAllocating) {
7863 if (!PAttr.checkAtMostNumArgs(S, 1)) {
7864 PAttr.setInvalid();
7865 return true;
7866 }
7867
7868 // Parse the condition, if any.
7869 if (PAttr.getNumArgs() == 1) {
7870 CondExpr = PAttr.getArgAsExpr(0);
7871 std::optional<FunctionEffectMode> MaybeMode =
7872 S.ActOnEffectExpression(CondExpr, PAttr.getAttrName()->getName());
7873 if (!MaybeMode) {
7874 PAttr.setInvalid();
7875 return true;
7876 }
7877 NewMode = *MaybeMode;
7878 if (NewMode != FunctionEffectMode::Dependent)
7879 CondExpr = nullptr;
7880 } else {
7881 NewMode = FunctionEffectMode::True;
7882 }
7883 } else {
7884 // This is the `blocking` or `allocating` attribute.
7885 if (S.CheckAttrNoArgs(PAttr)) {
7886 // The attribute has been marked invalid.
7887 return true;
7888 }
7889 NewMode = FunctionEffectMode::False;
7890 }
7891
7892 const FunctionEffect::Kind FEKind =
7893 (NewMode == FunctionEffectMode::False)
7894 ? (IsNonBlocking ? FunctionEffect::Kind::Blocking
7896 : (IsNonBlocking ? FunctionEffect::Kind::NonBlocking
7898 const FunctionEffectWithCondition NewEC{FunctionEffect(FEKind),
7899 EffectConditionExpr(CondExpr)};
7900
7901 if (S.diagnoseConflictingFunctionEffect(FPT->getFunctionEffects(), NewEC,
7902 PAttr.getLoc())) {
7903 PAttr.setInvalid();
7904 return true;
7905 }
7906
7907 // Add the effect to the FunctionProtoType.
7908 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7911 [[maybe_unused]] bool Success = FX.insert(NewEC, Errs);
7912 assert(Success && "effect conflicts should have been diagnosed above");
7914
7915 QualType NewType = S.Context.getFunctionType(FPT->getReturnType(),
7916 FPT->getParamTypes(), EPI);
7917 QT = Unwrapped.wrap(S, NewType->getAs<FunctionType>());
7918 return true;
7919}
7920
7921static bool checkMutualExclusion(TypeProcessingState &state,
7924 AttributeCommonInfo::Kind OtherKind) {
7925 auto OtherAttr = llvm::find_if(
7926 state.getCurrentAttributes(),
7927 [OtherKind](const ParsedAttr &A) { return A.getKind() == OtherKind; });
7928 if (OtherAttr == state.getCurrentAttributes().end() || OtherAttr->isInvalid())
7929 return false;
7930
7931 Sema &S = state.getSema();
7932 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
7933 << *OtherAttr << Attr
7934 << (OtherAttr->isRegularKeywordAttribute() ||
7936 S.Diag(OtherAttr->getLoc(), diag::note_conflicting_attribute);
7937 Attr.setInvalid();
7938 return true;
7939}
7940
7943 ParsedAttr &Attr) {
7944 if (!Attr.getNumArgs()) {
7945 S.Diag(Attr.getLoc(), diag::err_missing_arm_state) << Attr;
7946 Attr.setInvalid();
7947 return true;
7948 }
7949
7950 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
7951 StringRef StateName;
7952 SourceLocation LiteralLoc;
7953 if (!S.checkStringLiteralArgumentAttr(Attr, I, StateName, &LiteralLoc))
7954 return true;
7955
7956 if (StateName != "sme_za_state") {
7957 S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName;
7958 Attr.setInvalid();
7959 return true;
7960 }
7961
7962 if (EPI.AArch64SMEAttributes &
7964 S.Diag(Attr.getLoc(), diag::err_conflicting_attributes_arm_agnostic);
7965 Attr.setInvalid();
7966 return true;
7967 }
7968
7970 }
7971
7972 return false;
7973}
7974
7979 if (!Attr.getNumArgs()) {
7980 S.Diag(Attr.getLoc(), diag::err_missing_arm_state) << Attr;
7981 Attr.setInvalid();
7982 return true;
7983 }
7984
7985 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
7986 StringRef StateName;
7987 SourceLocation LiteralLoc;
7988 if (!S.checkStringLiteralArgumentAttr(Attr, I, StateName, &LiteralLoc))
7989 return true;
7990
7991 unsigned Shift;
7992 FunctionType::ArmStateValue ExistingState;
7993 if (StateName == "za") {
7996 } else if (StateName == "zt0") {
7999 } else {
8000 S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName;
8001 Attr.setInvalid();
8002 return true;
8003 }
8004
8006 S.Diag(LiteralLoc, diag::err_conflicting_attributes_arm_agnostic);
8007 Attr.setInvalid();
8008 return true;
8009 }
8010
8011 // __arm_in(S), __arm_out(S), __arm_inout(S) and __arm_preserves(S)
8012 // are all mutually exclusive for the same S, so check if there are
8013 // conflicting attributes.
8014 if (ExistingState != FunctionType::ARM_None && ExistingState != State) {
8015 S.Diag(LiteralLoc, diag::err_conflicting_attributes_arm_state)
8016 << StateName;
8017 Attr.setInvalid();
8018 return true;
8019 }
8020
8022 (FunctionType::AArch64SMETypeAttributes)((State << Shift)));
8023 }
8024 return false;
8025}
8026
8027/// Process an individual function attribute. Returns true to
8028/// indicate that the attribute was handled, false if it wasn't.
8029static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
8031 Sema &S = state.getSema();
8032
8033 FunctionTypeUnwrapper unwrapped(S, type);
8034
8035 if (attr.getKind() == ParsedAttr::AT_NoReturn) {
8036 if (S.CheckAttrNoArgs(attr))
8037 return true;
8038
8039 // Delay if this is not a function type.
8040 if (!unwrapped.isFunctionType())
8041 return false;
8042
8043 // Otherwise we can process right away.
8044 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
8045 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8046 return true;
8047 }
8048
8049 if (attr.getKind() == ParsedAttr::AT_CFIUncheckedCallee) {
8050 // Delay if this is not a prototyped function type.
8051 if (!unwrapped.isFunctionType())
8052 return false;
8053
8054 if (!unwrapped.get()->isFunctionProtoType()) {
8055 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
8056 << attr << attr.isRegularKeywordAttribute()
8058 attr.setInvalid();
8059 return true;
8060 }
8061
8062 const auto *FPT = unwrapped.get()->getAs<FunctionProtoType>();
8064 FPT->getReturnType(), FPT->getParamTypes(),
8065 FPT->getExtProtoInfo().withCFIUncheckedCallee(true));
8066 type = unwrapped.wrap(S, cast<FunctionType>(type.getTypePtr()));
8067 return true;
8068 }
8069
8070 if (attr.getKind() == ParsedAttr::AT_CmseNSCall) {
8071 // Delay if this is not a function type.
8072 if (!unwrapped.isFunctionType())
8073 return false;
8074
8075 // Ignore if we don't have CMSE enabled.
8076 if (!S.getLangOpts().Cmse) {
8077 S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr;
8078 attr.setInvalid();
8079 return true;
8080 }
8081
8082 // Otherwise we can process right away.
8084 unwrapped.get()->getExtInfo().withCmseNSCall(true);
8085 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8086 return true;
8087 }
8088
8089 // ns_returns_retained is not always a type attribute, but if we got
8090 // here, we're treating it as one right now.
8091 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
8092 if (attr.getNumArgs()) return true;
8093
8094 // Delay if this is not a function type.
8095 if (!unwrapped.isFunctionType())
8096 return false;
8097
8098 // Check whether the return type is reasonable.
8100 attr.getLoc(), unwrapped.get()->getReturnType()))
8101 return true;
8102
8103 // Only actually change the underlying type in ARC builds.
8104 QualType origType = type;
8105 if (state.getSema().getLangOpts().ObjCAutoRefCount) {
8107 = unwrapped.get()->getExtInfo().withProducesResult(true);
8108 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8109 }
8110 type = state.getAttributedType(
8112 origType, type);
8113 return true;
8114 }
8115
8116 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
8118 return true;
8119
8120 // Delay if this is not a function type.
8121 if (!unwrapped.isFunctionType())
8122 return false;
8123
8125 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
8126 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8127 return true;
8128 }
8129
8130 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
8131 if (!S.getLangOpts().CFProtectionBranch) {
8132 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
8133 attr.setInvalid();
8134 return true;
8135 }
8136
8138 return true;
8139
8140 // If this is not a function type, warning will be asserted by subject
8141 // check.
8142 if (!unwrapped.isFunctionType())
8143 return true;
8144
8146 unwrapped.get()->getExtInfo().withNoCfCheck(true);
8147 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8148 return true;
8149 }
8150
8151 if (attr.getKind() == ParsedAttr::AT_Regparm) {
8152 unsigned value;
8153 if (S.CheckRegparmAttr(attr, value))
8154 return true;
8155
8156 // Delay if this is not a function type.
8157 if (!unwrapped.isFunctionType())
8158 return false;
8159
8160 // Diagnose regparm with fastcall.
8161 const FunctionType *fn = unwrapped.get();
8162 CallingConv CC = fn->getCallConv();
8163 if (CC == CC_X86FastCall) {
8164 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8165 << FunctionType::getNameForCallConv(CC) << "regparm"
8166 << attr.isRegularKeywordAttribute();
8167 attr.setInvalid();
8168 return true;
8169 }
8170
8172 unwrapped.get()->getExtInfo().withRegParm(value);
8173 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8174 return true;
8175 }
8176
8177 if (attr.getKind() == ParsedAttr::AT_CFISalt) {
8178 if (attr.getNumArgs() != 1)
8179 return true;
8180
8181 StringRef Argument;
8182 if (!S.checkStringLiteralArgumentAttr(attr, 0, Argument))
8183 return true;
8184
8185 // Delay if this is not a function type.
8186 if (!unwrapped.isFunctionType())
8187 return false;
8188
8189 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8190 if (!FnTy) {
8191 S.Diag(attr.getLoc(), diag::err_attribute_wrong_decl_type)
8192 << attr << attr.isRegularKeywordAttribute()
8194 attr.setInvalid();
8195 return true;
8196 }
8197
8198 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8199 EPI.ExtraAttributeInfo.CFISalt = Argument;
8200
8201 QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(),
8202 FnTy->getParamTypes(), EPI);
8203 type = unwrapped.wrap(S, newtype->getAs<FunctionType>());
8204 return true;
8205 }
8206
8207 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8208 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible ||
8209 attr.getKind() == ParsedAttr::AT_ArmPreserves ||
8210 attr.getKind() == ParsedAttr::AT_ArmIn ||
8211 attr.getKind() == ParsedAttr::AT_ArmOut ||
8212 attr.getKind() == ParsedAttr::AT_ArmInOut ||
8213 attr.getKind() == ParsedAttr::AT_ArmAgnostic) {
8214 if (S.CheckAttrTarget(attr))
8215 return true;
8216
8217 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8218 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible)
8219 if (S.CheckAttrNoArgs(attr))
8220 return true;
8221
8222 if (!unwrapped.isFunctionType())
8223 return false;
8224
8225 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8226 if (!FnTy) {
8227 // SME ACLE attributes are not supported on K&R-style unprototyped C
8228 // functions.
8229 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
8230 << attr << attr.isRegularKeywordAttribute()
8232 attr.setInvalid();
8233 return false;
8234 }
8235
8236 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8237 switch (attr.getKind()) {
8238 case ParsedAttr::AT_ArmStreaming:
8239 if (checkMutualExclusion(state, EPI, attr,
8240 ParsedAttr::AT_ArmStreamingCompatible))
8241 return true;
8243 break;
8244 case ParsedAttr::AT_ArmStreamingCompatible:
8245 if (checkMutualExclusion(state, EPI, attr, ParsedAttr::AT_ArmStreaming))
8246 return true;
8248 break;
8249 case ParsedAttr::AT_ArmPreserves:
8251 return true;
8252 break;
8253 case ParsedAttr::AT_ArmIn:
8255 return true;
8256 break;
8257 case ParsedAttr::AT_ArmOut:
8259 return true;
8260 break;
8261 case ParsedAttr::AT_ArmInOut:
8263 return true;
8264 break;
8265 case ParsedAttr::AT_ArmAgnostic:
8266 if (handleArmAgnosticAttribute(S, EPI, attr))
8267 return true;
8268 break;
8269 default:
8270 llvm_unreachable("Unsupported attribute");
8271 }
8272
8273 QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(),
8274 FnTy->getParamTypes(), EPI);
8275 type = unwrapped.wrap(S, newtype->getAs<FunctionType>());
8276 return true;
8277 }
8278
8279 if (attr.getKind() == ParsedAttr::AT_NoThrow) {
8280 // Delay if this is not a function type.
8281 if (!unwrapped.isFunctionType())
8282 return false;
8283
8284 if (S.CheckAttrNoArgs(attr)) {
8285 attr.setInvalid();
8286 return true;
8287 }
8288
8289 // Otherwise we can process right away.
8290 auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
8291
8292 // MSVC ignores nothrow if it is in conflict with an explicit exception
8293 // specification.
8294 if (Proto->hasExceptionSpec()) {
8295 switch (Proto->getExceptionSpecType()) {
8296 case EST_None:
8297 llvm_unreachable("This doesn't have an exception spec!");
8298
8299 case EST_DynamicNone:
8300 case EST_BasicNoexcept:
8301 case EST_NoexceptTrue:
8302 case EST_NoThrow:
8303 // Exception spec doesn't conflict with nothrow, so don't warn.
8304 [[fallthrough]];
8305 case EST_Unparsed:
8306 case EST_Uninstantiated:
8308 case EST_Unevaluated:
8309 // We don't have enough information to properly determine if there is a
8310 // conflict, so suppress the warning.
8311 break;
8312 case EST_Dynamic:
8313 case EST_MSAny:
8314 case EST_NoexceptFalse:
8315 S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored);
8316 break;
8317 }
8318 return true;
8319 }
8320
8321 type = unwrapped.wrap(
8322 S, S.Context
8324 QualType{Proto, 0},
8326 ->getAs<FunctionType>());
8327 return true;
8328 }
8329
8330 if (attr.getKind() == ParsedAttr::AT_NonBlocking ||
8331 attr.getKind() == ParsedAttr::AT_NonAllocating ||
8332 attr.getKind() == ParsedAttr::AT_Blocking ||
8333 attr.getKind() == ParsedAttr::AT_Allocating) {
8334 return handleNonBlockingNonAllocatingTypeAttr(state, attr, type, unwrapped);
8335 }
8336
8337 // Delay if the type didn't work out to a function.
8338 if (!unwrapped.isFunctionType()) return false;
8339
8340 // Otherwise, a calling convention.
8341 CallingConv CC;
8342 if (S.CheckCallingConvAttr(attr, CC, /*FunctionDecl=*/nullptr, CFT))
8343 return true;
8344
8345 const FunctionType *fn = unwrapped.get();
8346 CallingConv CCOld = fn->getCallConv();
8347 Attr *CCAttr = getCCTypeAttr(S.Context, attr);
8348
8349 if (CCOld != CC) {
8350 // Error out on when there's already an attribute on the type
8351 // and the CCs don't match.
8353 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8356 << attr.isRegularKeywordAttribute();
8357 attr.setInvalid();
8358 return true;
8359 }
8360 }
8361
8362 // Diagnose use of variadic functions with calling conventions that
8363 // don't support them (e.g. because they're callee-cleanup).
8364 // We delay warning about this on unprototyped function declarations
8365 // until after redeclaration checking, just in case we pick up a
8366 // prototype that way. And apparently we also "delay" warning about
8367 // unprototyped function types in general, despite not necessarily having
8368 // much ability to diagnose it later.
8369 if (!supportsVariadicCall(CC)) {
8370 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
8371 if (FnP && FnP->isVariadic()) {
8372 // stdcall and fastcall are ignored with a warning for GCC and MS
8373 // compatibility.
8374 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
8375 return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported)
8378
8379 attr.setInvalid();
8380 return S.Diag(attr.getLoc(), diag::err_cconv_varargs)
8382 }
8383 }
8384
8385 // Also diagnose fastcall with regparm.
8386 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
8387 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8389 << attr.isRegularKeywordAttribute();
8390 attr.setInvalid();
8391 return true;
8392 }
8393
8394 // Modify the CC from the wrapped function type, wrap it all back, and then
8395 // wrap the whole thing in an AttributedType as written. The modified type
8396 // might have a different CC if we ignored the attribute.
8398 if (CCOld == CC) {
8399 Equivalent = type;
8400 } else {
8401 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
8402 Equivalent =
8403 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8404 }
8405 type = state.getAttributedType(CCAttr, type, Equivalent);
8406 return true;
8407}
8408
8410 const AttributedType *AT;
8411
8412 // Stop if we'd be stripping off a typedef sugar node to reach the
8413 // AttributedType.
8414 while ((AT = T->getAs<AttributedType>()) &&
8415 AT->getAs<TypedefType>() == T->getAs<TypedefType>()) {
8416 if (AT->isCallingConv())
8417 return true;
8418 T = AT->getModifiedType();
8419 }
8420 return false;
8421}
8422
8423void Sema::adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
8424 bool IsCtorOrDtor, SourceLocation Loc) {
8425 FunctionTypeUnwrapper Unwrapped(*this, T);
8426 const FunctionType *FT = Unwrapped.get();
8427 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
8428 cast<FunctionProtoType>(FT)->isVariadic());
8429 CallingConv CurCC = FT->getCallConv();
8430 CallingConv ToCC =
8431 Context.getDefaultCallingConvention(IsVariadic, HasThisPointer);
8432
8433 if (CurCC == ToCC)
8434 return;
8435
8436 // MS compiler ignores explicit calling convention attributes on structors. We
8437 // should do the same.
8438 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
8439 // Issue a warning on ignored calling convention -- except of __stdcall.
8440 // Again, this is what MS compiler does.
8441 if (CurCC != CC_X86StdCall)
8442 Diag(Loc, diag::warn_cconv_unsupported)
8445 // Default adjustment.
8446 } else {
8447 // Only adjust types with the default convention. For example, on Windows
8448 // we should adjust a __cdecl type to __thiscall for instance methods, and a
8449 // __thiscall type to __cdecl for static methods.
8450 CallingConv DefaultCC =
8451 Context.getDefaultCallingConvention(IsVariadic, !HasThisPointer);
8452
8453 if (CurCC != DefaultCC)
8454 return;
8455
8457 return;
8458 }
8459
8460 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
8461 QualType Wrapped = Unwrapped.wrap(*this, FT);
8462 T = Context.getAdjustedType(T, Wrapped);
8463}
8464
8465/// HandleVectorSizeAttribute - this attribute is only applicable to integral
8466/// and float scalars, although arrays, pointers, and function return values are
8467/// allowed in conjunction with this construct. Aggregates with this attribute
8468/// are invalid, even if they are of the same size as a corresponding scalar.
8469/// The raw attribute should contain precisely 1 argument, the vector size for
8470/// the variable, measured in bytes. If curType and rawAttr are well formed,
8471/// this routine will return a new vector type.
8472static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
8473 Sema &S) {
8474 // Check the attribute arguments.
8475 if (Attr.getNumArgs() != 1) {
8476 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8477 << 1;
8478 Attr.setInvalid();
8479 return;
8480 }
8481
8482 Expr *SizeExpr = Attr.getArgAsExpr(0);
8483 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
8484 if (!T.isNull())
8485 CurType = T;
8486 else
8487 Attr.setInvalid();
8488}
8489
8490/// Process the OpenCL-like ext_vector_type attribute when it occurs on
8491/// a type.
8493 Sema &S) {
8494 // check the attribute arguments.
8495 if (Attr.getNumArgs() != 1) {
8496 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8497 << 1;
8498 return;
8499 }
8500
8501 Expr *SizeExpr = Attr.getArgAsExpr(0);
8502 QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc());
8503 if (!T.isNull())
8504 CurType = T;
8505}
8506
8507static bool isPermittedNeonBaseType(QualType &Ty, VectorKind VecKind, Sema &S) {
8508 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
8509 if (!BTy)
8510 return false;
8511
8512 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
8513
8514 // Signed poly is mathematically wrong, but has been baked into some ABIs by
8515 // now.
8516 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
8517 Triple.getArch() == llvm::Triple::aarch64_32 ||
8518 Triple.getArch() == llvm::Triple::aarch64_be;
8519 if (VecKind == VectorKind::NeonPoly) {
8520 if (IsPolyUnsigned) {
8521 // AArch64 polynomial vectors are unsigned.
8522 return BTy->getKind() == BuiltinType::UChar ||
8523 BTy->getKind() == BuiltinType::UShort ||
8524 BTy->getKind() == BuiltinType::ULong ||
8525 BTy->getKind() == BuiltinType::ULongLong;
8526 } else {
8527 // AArch32 polynomial vectors are signed.
8528 return BTy->getKind() == BuiltinType::SChar ||
8529 BTy->getKind() == BuiltinType::Short ||
8530 BTy->getKind() == BuiltinType::LongLong;
8531 }
8532 }
8533
8534 // Non-polynomial vector types: the usual suspects are allowed, as well as
8535 // float64_t on AArch64.
8536 if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) &&
8537 BTy->getKind() == BuiltinType::Double)
8538 return true;
8539
8540 return BTy->getKind() == BuiltinType::SChar ||
8541 BTy->getKind() == BuiltinType::UChar ||
8542 BTy->getKind() == BuiltinType::Short ||
8543 BTy->getKind() == BuiltinType::UShort ||
8544 BTy->getKind() == BuiltinType::Int ||
8545 BTy->getKind() == BuiltinType::UInt ||
8546 BTy->getKind() == BuiltinType::Long ||
8547 BTy->getKind() == BuiltinType::ULong ||
8548 BTy->getKind() == BuiltinType::LongLong ||
8549 BTy->getKind() == BuiltinType::ULongLong ||
8550 BTy->getKind() == BuiltinType::Float ||
8551 BTy->getKind() == BuiltinType::Half ||
8552 BTy->getKind() == BuiltinType::BFloat16 ||
8553 BTy->getKind() == BuiltinType::MFloat8;
8554}
8555
8557 llvm::APSInt &Result) {
8558 const auto *AttrExpr = Attr.getArgAsExpr(0);
8559 if (!AttrExpr->isTypeDependent()) {
8560 if (std::optional<llvm::APSInt> Res =
8561 AttrExpr->getIntegerConstantExpr(S.Context)) {
8562 Result = *Res;
8563 return true;
8564 }
8565 }
8566 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
8567 << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange();
8568 Attr.setInvalid();
8569 return false;
8570}
8571
8572/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
8573/// "neon_polyvector_type" attributes are used to create vector types that
8574/// are mangled according to ARM's ABI. Otherwise, these types are identical
8575/// to those created with the "vector_size" attribute. Unlike "vector_size"
8576/// the argument to these Neon attributes is the number of vector elements,
8577/// not the vector size in bytes. The vector width and element type must
8578/// match one of the standard Neon vector types.
8580 Sema &S, VectorKind VecKind) {
8581 bool IsTargetOffloading = S.getLangOpts().isTargetDevice();
8582
8583 // Target must have NEON (or MVE, whose vectors are similar enough
8584 // not to need a separate attribute)
8585 if (!S.Context.getTargetInfo().hasFeature("mve") &&
8586 VecKind == VectorKind::Neon &&
8587 S.Context.getTargetInfo().getTriple().isArmMClass()) {
8588 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported_m_profile)
8589 << Attr << "'mve'";
8590 Attr.setInvalid();
8591 return;
8592 }
8593 if (!S.Context.getTargetInfo().hasFeature("mve") &&
8594 VecKind == VectorKind::NeonPoly &&
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
8602 // Check the attribute arguments.
8603 if (Attr.getNumArgs() != 1) {
8604 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8605 << Attr << 1;
8606 Attr.setInvalid();
8607 return;
8608 }
8609 // The number of elements must be an ICE.
8610 llvm::APSInt numEltsInt(32);
8611 if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt))
8612 return;
8613
8614 // Only certain element types are supported for Neon vectors.
8615 if (!isPermittedNeonBaseType(CurType, VecKind, S) && !IsTargetOffloading) {
8616 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
8617 Attr.setInvalid();
8618 return;
8619 }
8620
8621 // The total size of the vector must be 64 or 128 bits.
8622 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
8623 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
8624 unsigned vecSize = typeSize * numElts;
8625 if (vecSize != 64 && vecSize != 128) {
8626 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
8627 Attr.setInvalid();
8628 return;
8629 }
8630
8631 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
8632}
8633
8634/// Handle the __ptrauth qualifier.
8636 const ParsedAttr &Attr, Sema &S) {
8637
8638 assert((Attr.getNumArgs() > 0 && Attr.getNumArgs() <= 3) &&
8639 "__ptrauth qualifier takes between 1 and 3 arguments");
8640 Expr *KeyArg = Attr.getArgAsExpr(0);
8641 Expr *IsAddressDiscriminatedArg =
8642 Attr.getNumArgs() >= 2 ? Attr.getArgAsExpr(1) : nullptr;
8643 Expr *ExtraDiscriminatorArg =
8644 Attr.getNumArgs() >= 3 ? Attr.getArgAsExpr(2) : nullptr;
8645
8646 unsigned Key;
8647 if (S.checkConstantPointerAuthKey(KeyArg, Key)) {
8648 Attr.setInvalid();
8649 return;
8650 }
8651 assert(Key <= PointerAuthQualifier::MaxKey && "ptrauth key is out of range");
8652
8653 bool IsInvalid = false;
8654 unsigned IsAddressDiscriminated, ExtraDiscriminator;
8655 IsInvalid |= !S.checkPointerAuthDiscriminatorArg(IsAddressDiscriminatedArg,
8657 IsAddressDiscriminated);
8658 IsInvalid |= !S.checkPointerAuthDiscriminatorArg(
8659 ExtraDiscriminatorArg, PointerAuthDiscArgKind::Extra, ExtraDiscriminator);
8660
8661 if (IsInvalid) {
8662 Attr.setInvalid();
8663 return;
8664 }
8665
8666 if (!T->isSignableType(Ctx) && !T->isDependentType()) {
8667 S.Diag(Attr.getLoc(), diag::err_ptrauth_qualifier_invalid_target) << T;
8668 Attr.setInvalid();
8669 return;
8670 }
8671
8672 if (T.getPointerAuth()) {
8673 S.Diag(Attr.getLoc(), diag::err_ptrauth_qualifier_redundant) << T;
8674 Attr.setInvalid();
8675 return;
8676 }
8677
8678 if (!S.getLangOpts().PointerAuthIntrinsics) {
8679 S.Diag(Attr.getLoc(), diag::err_ptrauth_disabled) << Attr.getRange();
8680 Attr.setInvalid();
8681 return;
8682 }
8683
8684 assert((!IsAddressDiscriminatedArg || IsAddressDiscriminated <= 1) &&
8685 "address discriminator arg should be either 0 or 1");
8687 Key, IsAddressDiscriminated, ExtraDiscriminator,
8688 PointerAuthenticationMode::SignAndAuth, /*IsIsaPointer=*/false,
8689 /*AuthenticatesNullValues=*/false);
8690 T = S.Context.getPointerAuthType(T, Qual);
8691}
8692
8693/// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is
8694/// used to create fixed-length versions of sizeless SVE types defined by
8695/// the ACLE, such as svint32_t and svbool_t.
8697 Sema &S) {
8698 // Target must have SVE.
8699 if (!S.Context.getTargetInfo().hasFeature("sve")) {
8700 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'";
8701 Attr.setInvalid();
8702 return;
8703 }
8704
8705 // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or
8706 // if <bits>+ syntax is used.
8707 if (!S.getLangOpts().VScaleMin ||
8708 S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) {
8709 S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported)
8710 << Attr;
8711 Attr.setInvalid();
8712 return;
8713 }
8714
8715 // Check the attribute arguments.
8716 if (Attr.getNumArgs() != 1) {
8717 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8718 << Attr << 1;
8719 Attr.setInvalid();
8720 return;
8721 }
8722
8723 // The vector size must be an integer constant expression.
8724 llvm::APSInt SveVectorSizeInBits(32);
8725 if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits))
8726 return;
8727
8728 unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue());
8729
8730 // The attribute vector size must match -msve-vector-bits.
8731 if (VecSize != S.getLangOpts().VScaleMin * 128) {
8732 S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size)
8733 << VecSize << S.getLangOpts().VScaleMin * 128;
8734 Attr.setInvalid();
8735 return;
8736 }
8737
8738 // Attribute can only be attached to a single SVE vector or predicate type.
8739 if (!CurType->isSveVLSBuiltinType()) {
8740 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type)
8741 << Attr << CurType;
8742 Attr.setInvalid();
8743 return;
8744 }
8745
8746 const auto *BT = CurType->castAs<BuiltinType>();
8747
8748 QualType EltType = CurType->getSveEltType(S.Context);
8749 unsigned TypeSize = S.Context.getTypeSize(EltType);
8751 if (BT->getKind() == BuiltinType::SveBool) {
8752 // Predicates are represented as i8.
8753 VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth();
8755 } else
8756 VecSize /= TypeSize;
8757 CurType = S.Context.getVectorType(EltType, VecSize, VecKind);
8758}
8759
8760static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State,
8761 QualType &CurType,
8762 ParsedAttr &Attr) {
8763 const VectorType *VT = dyn_cast<VectorType>(CurType);
8764 if (!VT || VT->getVectorKind() != VectorKind::Neon) {
8765 State.getSema().Diag(Attr.getLoc(),
8766 diag::err_attribute_arm_mve_polymorphism);
8767 Attr.setInvalid();
8768 return;
8769 }
8770
8771 CurType =
8772 State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>(
8773 State.getSema().Context, Attr),
8774 CurType, CurType);
8775}
8776
8777/// HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is
8778/// used to create fixed-length versions of sizeless RVV types such as
8779/// vint8m1_t_t.
8781 ParsedAttr &Attr, Sema &S) {
8782 // Target must have vector extension.
8783 if (!S.Context.getTargetInfo().hasFeature("zve32x")) {
8784 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
8785 << Attr << "'zve32x'";
8786 Attr.setInvalid();
8787 return;
8788 }
8789
8790 auto VScale = S.Context.getTargetInfo().getVScaleRange(
8792 if (!VScale || !VScale->first || VScale->first != VScale->second) {
8793 S.Diag(Attr.getLoc(), diag::err_attribute_riscv_rvv_bits_unsupported)
8794 << Attr;
8795 Attr.setInvalid();
8796 return;
8797 }
8798
8799 // Check the attribute arguments.
8800 if (Attr.getNumArgs() != 1) {
8801 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8802 << Attr << 1;
8803 Attr.setInvalid();
8804 return;
8805 }
8806
8807 // The vector size must be an integer constant expression.
8808 llvm::APSInt RVVVectorSizeInBits(32);
8809 if (!verifyValidIntegerConstantExpr(S, Attr, RVVVectorSizeInBits))
8810 return;
8811
8812 // Attribute can only be attached to a single RVV vector type.
8813 if (!CurType->isRVVVLSBuiltinType()) {
8814 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_rvv_type)
8815 << Attr << CurType;
8816 Attr.setInvalid();
8817 return;
8818 }
8819
8820 unsigned VecSize = static_cast<unsigned>(RVVVectorSizeInBits.getZExtValue());
8821
8824 unsigned MinElts = Info.EC.getKnownMinValue();
8825
8827 unsigned ExpectedSize = VScale->first * MinElts;
8828 QualType EltType = CurType->getRVVEltType(S.Context);
8829 unsigned EltSize = S.Context.getTypeSize(EltType);
8830 unsigned NumElts;
8831 if (Info.ElementType == S.Context.BoolTy) {
8832 NumElts = VecSize / S.Context.getCharWidth();
8833 if (!NumElts) {
8834 NumElts = 1;
8835 switch (VecSize) {
8836 case 1:
8838 break;
8839 case 2:
8841 break;
8842 case 4:
8844 break;
8845 }
8846 } else
8848 } else {
8849 ExpectedSize *= EltSize;
8850 NumElts = VecSize / EltSize;
8851 }
8852
8853 // The attribute vector size must match -mrvv-vector-bits.
8854 if (VecSize != ExpectedSize) {
8855 S.Diag(Attr.getLoc(), diag::err_attribute_bad_rvv_vector_size)
8856 << VecSize << ExpectedSize;
8857 Attr.setInvalid();
8858 return;
8859 }
8860
8861 CurType = S.Context.getVectorType(EltType, NumElts, VecKind);
8862}
8863
8864/// Handle OpenCL Access Qualifier Attribute.
8865static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
8866 Sema &S) {
8867 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
8868 if (!(CurType->isImageType() || CurType->isPipeType())) {
8869 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
8870 Attr.setInvalid();
8871 return;
8872 }
8873
8874 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
8875 QualType BaseTy = TypedefTy->desugar();
8876
8877 std::string PrevAccessQual;
8878 if (BaseTy->isPipeType()) {
8879 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
8880 OpenCLAccessAttr *Attr =
8881 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
8882 PrevAccessQual = Attr->getSpelling();
8883 } else {
8884 PrevAccessQual = "read_only";
8885 }
8886 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
8887
8888 switch (ImgType->getKind()) {
8889 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8890 case BuiltinType::Id: \
8891 PrevAccessQual = #Access; \
8892 break;
8893 #include "clang/Basic/OpenCLImageTypes.def"
8894 default:
8895 llvm_unreachable("Unable to find corresponding image type.");
8896 }
8897 } else {
8898 llvm_unreachable("unexpected type");
8899 }
8900 StringRef AttrName = Attr.getAttrName()->getName();
8901 if (PrevAccessQual == AttrName.ltrim("_")) {
8902 // Duplicated qualifiers
8903 S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
8904 << AttrName << Attr.getRange();
8905 } else {
8906 // Contradicting qualifiers
8907 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
8908 }
8909
8910 S.Diag(TypedefTy->getDecl()->getBeginLoc(),
8911 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
8912 } else if (CurType->isPipeType()) {
8913 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
8914 QualType ElemType = CurType->castAs<PipeType>()->getElementType();
8915 CurType = S.Context.getWritePipeType(ElemType);
8916 }
8917 }
8918}
8919
8920/// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type
8921static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8922 Sema &S) {
8923 if (!S.getLangOpts().MatrixTypes) {
8924 S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled);
8925 return;
8926 }
8927
8928 if (Attr.getNumArgs() != 2) {
8929 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8930 << Attr << 2;
8931 return;
8932 }
8933
8934 Expr *RowsExpr = Attr.getArgAsExpr(0);
8935 Expr *ColsExpr = Attr.getArgAsExpr(1);
8936 QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc());
8937 if (!T.isNull())
8938 CurType = T;
8939}
8940
8941static void HandleAnnotateTypeAttr(TypeProcessingState &State,
8942 QualType &CurType, const ParsedAttr &PA) {
8943 Sema &S = State.getSema();
8944
8945 if (PA.getNumArgs() < 1) {
8946 S.Diag(PA.getLoc(), diag::err_attribute_too_few_arguments) << PA << 1;
8947 return;
8948 }
8949
8950 // Make sure that there is a string literal as the annotation's first
8951 // argument.
8952 StringRef Str;
8953 if (!S.checkStringLiteralArgumentAttr(PA, 0, Str))
8954 return;
8955
8957 Args.reserve(PA.getNumArgs() - 1);
8958 for (unsigned Idx = 1; Idx < PA.getNumArgs(); Idx++) {
8959 assert(!PA.isArgIdent(Idx));
8960 Args.push_back(PA.getArgAsExpr(Idx));
8961 }
8962 if (!S.ConstantFoldAttrArgs(PA, Args))
8963 return;
8964 auto *AnnotateTypeAttr =
8965 AnnotateTypeAttr::Create(S.Context, Str, Args.data(), Args.size(), PA);
8966 CurType = State.getAttributedType(AnnotateTypeAttr, CurType, CurType);
8967}
8968
8969static void HandleLifetimeBoundAttr(TypeProcessingState &State,
8970 QualType &CurType,
8971 ParsedAttr &Attr) {
8972 if (State.getDeclarator().isDeclarationOfFunction()) {
8973 CurType = State.getAttributedType(
8974 createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
8975 CurType, CurType);
8976 return;
8977 }
8978 State.getSema().Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
8981}
8982
8983static void HandleLifetimeCaptureByAttr(TypeProcessingState &State,
8984 QualType &CurType, ParsedAttr &PA) {
8985 if (State.getDeclarator().isDeclarationOfFunction()) {
8986 auto *Attr = State.getSema().ParseLifetimeCaptureByAttr(PA, "this");
8987 if (Attr)
8988 CurType = State.getAttributedType(Attr, CurType, CurType);
8989 }
8990}
8991
8992static void HandleHLSLParamModifierAttr(TypeProcessingState &State,
8993 QualType &CurType,
8994 const ParsedAttr &Attr, Sema &S) {
8995 // Don't apply this attribute to template dependent types. It is applied on
8996 // substitution during template instantiation. Also skip parsing this if we've
8997 // already modified the type based on an earlier attribute.
8998 if (CurType->isDependentType() || State.didParseHLSLParamMod())
8999 return;
9000 if (Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_inout ||
9001 Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_out) {
9002 State.setParsedHLSLParamMod(true);
9003 }
9004}
9005
9006static void processTypeAttrs(TypeProcessingState &state, QualType &type,
9007 TypeAttrLocation TAL,
9008 const ParsedAttributesView &attrs,
9009 CUDAFunctionTarget CFT) {
9010
9011 state.setParsedNoDeref(false);
9012 if (attrs.empty())
9013 return;
9014
9015 // Scan through and apply attributes to this type where it makes sense. Some
9016 // attributes (such as __address_space__, __vector_size__, etc) apply to the
9017 // type, but others can be present in the type specifiers even though they
9018 // apply to the decl. Here we apply type attributes and ignore the rest.
9019
9020 // This loop modifies the list pretty frequently, but we still need to make
9021 // sure we visit every element once. Copy the attributes list, and iterate
9022 // over that.
9023 ParsedAttributesView AttrsCopy{attrs};
9024 for (ParsedAttr &attr : AttrsCopy) {
9025
9026 // Skip attributes that were marked to be invalid.
9027 if (attr.isInvalid())
9028 continue;
9029
9030 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute()) {
9031 // [[gnu::...]] attributes are treated as declaration attributes, so may
9032 // not appertain to a DeclaratorChunk. If we handle them as type
9033 // attributes, accept them in that position and diagnose the GCC
9034 // incompatibility.
9035 if (attr.isGNUScope()) {
9036 assert(attr.isStandardAttributeSyntax());
9037 bool IsTypeAttr = attr.isTypeAttr();
9038 if (TAL == TAL_DeclChunk) {
9039 state.getSema().Diag(attr.getLoc(),
9040 IsTypeAttr
9041 ? diag::warn_gcc_ignores_type_attr
9042 : diag::warn_cxx11_gnu_attribute_on_type)
9043 << attr;
9044 if (!IsTypeAttr)
9045 continue;
9046 }
9047 } else if (TAL != TAL_DeclSpec && TAL != TAL_DeclChunk &&
9048 !attr.isTypeAttr()) {
9049 // Otherwise, only consider type processing for a C++11 attribute if
9050 // - it has actually been applied to a type (decl-specifier-seq or
9051 // declarator chunk), or
9052 // - it is a type attribute, irrespective of where it was applied (so
9053 // that we can support the legacy behavior of some type attributes
9054 // that can be applied to the declaration name).
9055 continue;
9056 }
9057 }
9058
9059 // If this is an attribute we can handle, do so now,
9060 // otherwise, add it to the FnAttrs list for rechaining.
9061 switch (attr.getKind()) {
9062 default:
9063 // A [[]] attribute on a declarator chunk must appertain to a type.
9064 if ((attr.isStandardAttributeSyntax() ||
9065 attr.isRegularKeywordAttribute()) &&
9066 TAL == TAL_DeclChunk) {
9067 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
9068 << attr << attr.isRegularKeywordAttribute();
9069 attr.setUsedAsTypeAttr();
9070 }
9071 break;
9072
9074 if (attr.isStandardAttributeSyntax()) {
9075 state.getSema().DiagnoseUnknownAttribute(attr);
9076 // Mark the attribute as invalid so we don't emit the same diagnostic
9077 // multiple times.
9078 attr.setInvalid();
9079 }
9080 break;
9081
9083 break;
9084
9085 case ParsedAttr::AT_BTFTypeTag:
9087 attr.setUsedAsTypeAttr();
9088 break;
9089
9090 case ParsedAttr::AT_MayAlias:
9091 // FIXME: This attribute needs to actually be handled, but if we ignore
9092 // it it breaks large amounts of Linux software.
9093 attr.setUsedAsTypeAttr();
9094 break;
9095 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
9096 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
9097 case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace:
9098 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace:
9099 case ParsedAttr::AT_OpenCLLocalAddressSpace:
9100 case ParsedAttr::AT_OpenCLConstantAddressSpace:
9101 case ParsedAttr::AT_OpenCLGenericAddressSpace:
9102 case ParsedAttr::AT_AddressSpace:
9104 attr.setUsedAsTypeAttr();
9105 break;
9106 case ParsedAttr::AT_HLSLGroupSharedAddressSpace:
9108 if (state.getDeclarator().getContext() == DeclaratorContext::Prototype) {
9109 if (state.getSema().getLangOpts().getHLSLVersion() <
9111 state.getSema().Diag(attr.getLoc(), diag::warn_hlsl_groupshared_202x);
9112
9113 // Note: we don't check for the usage of HLSLParamModifiers in/out/inout
9114 // here because the check in the AT_HLSLParamModifier case is sufficient
9115 // regardless of the order of groupshared or in/out/inout specified in
9116 // the parameter. And checking there produces a better error message.
9117 }
9118 attr.setUsedAsTypeAttr();
9119 break;
9121 if (!handleObjCPointerTypeAttr(state, attr, type))
9123 attr.setUsedAsTypeAttr();
9124 break;
9125 case ParsedAttr::AT_VectorSize:
9126 HandleVectorSizeAttr(type, attr, state.getSema());
9127 attr.setUsedAsTypeAttr();
9128 break;
9129 case ParsedAttr::AT_ExtVectorType:
9130 HandleExtVectorTypeAttr(type, attr, state.getSema());
9131 attr.setUsedAsTypeAttr();
9132 break;
9133 case ParsedAttr::AT_NeonVectorType:
9135 attr.setUsedAsTypeAttr();
9136 break;
9137 case ParsedAttr::AT_NeonPolyVectorType:
9138 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
9140 attr.setUsedAsTypeAttr();
9141 break;
9142 case ParsedAttr::AT_ArmSveVectorBits:
9143 HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema());
9144 attr.setUsedAsTypeAttr();
9145 break;
9146 case ParsedAttr::AT_ArmMveStrictPolymorphism: {
9148 attr.setUsedAsTypeAttr();
9149 break;
9150 }
9151 case ParsedAttr::AT_RISCVRVVVectorBits:
9152 HandleRISCVRVVVectorBitsTypeAttr(type, attr, state.getSema());
9153 attr.setUsedAsTypeAttr();
9154 break;
9155 case ParsedAttr::AT_OpenCLAccess:
9156 HandleOpenCLAccessAttr(type, attr, state.getSema());
9157 attr.setUsedAsTypeAttr();
9158 break;
9159 case ParsedAttr::AT_PointerAuth:
9160 HandlePtrAuthQualifier(state.getSema().Context, type, attr,
9161 state.getSema());
9162 attr.setUsedAsTypeAttr();
9163 break;
9164 case ParsedAttr::AT_LifetimeBound:
9165 if (TAL == TAL_DeclChunk)
9167 break;
9168 case ParsedAttr::AT_LifetimeCaptureBy:
9169 if (TAL == TAL_DeclChunk)
9171 break;
9172 case ParsedAttr::AT_OverflowBehavior:
9174 attr.setUsedAsTypeAttr();
9175 break;
9176
9177 case ParsedAttr::AT_NoDeref: {
9178 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
9179 // See https://github.com/llvm/llvm-project/issues/55790 for details.
9180 // For the time being, we simply emit a warning that the attribute is
9181 // ignored.
9182 if (attr.isStandardAttributeSyntax()) {
9183 state.getSema().Diag(attr.getLoc(), diag::warn_attribute_ignored)
9184 << attr;
9185 break;
9186 }
9187 ASTContext &Ctx = state.getSema().Context;
9188 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
9189 type, type);
9190 attr.setUsedAsTypeAttr();
9191 state.setParsedNoDeref(true);
9192 break;
9193 }
9194
9195 case ParsedAttr::AT_MatrixType:
9196 HandleMatrixTypeAttr(type, attr, state.getSema());
9197 attr.setUsedAsTypeAttr();
9198 break;
9199
9200 case ParsedAttr::AT_WebAssemblyFuncref: {
9202 attr.setUsedAsTypeAttr();
9203 break;
9204 }
9205
9206 case ParsedAttr::AT_HLSLParamModifier: {
9207 HandleHLSLParamModifierAttr(state, type, attr, state.getSema());
9208 if (attrs.hasAttribute(ParsedAttr::AT_HLSLGroupSharedAddressSpace)) {
9209 state.getSema().Diag(attr.getLoc(), diag::err_hlsl_attr_incompatible)
9210 << attr << "'groupshared'";
9211 attr.setInvalid();
9212 return;
9213 }
9214 attr.setUsedAsTypeAttr();
9215 break;
9216 }
9217
9218 case ParsedAttr::AT_SwiftAttr: {
9219 HandleSwiftAttr(state, TAL, type, attr);
9220 break;
9221 }
9222
9225 attr.setUsedAsTypeAttr();
9226 break;
9227
9228
9230 // Either add nullability here or try to distribute it. We
9231 // don't want to distribute the nullability specifier past any
9232 // dependent type, because that complicates the user model.
9233 if (type->canHaveNullability() || type->isDependentType() ||
9234 type->isArrayType() ||
9236 unsigned endIndex;
9237 if (TAL == TAL_DeclChunk)
9238 endIndex = state.getCurrentChunkIndex();
9239 else
9240 endIndex = state.getDeclarator().getNumTypeObjects();
9241 bool allowOnArrayType =
9242 state.getDeclarator().isPrototypeContext() &&
9243 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
9245 allowOnArrayType)) {
9246 attr.setInvalid();
9247 }
9248
9249 attr.setUsedAsTypeAttr();
9250 }
9251 break;
9252
9253 case ParsedAttr::AT_ObjCKindOf:
9254 // '__kindof' must be part of the decl-specifiers.
9255 switch (TAL) {
9256 case TAL_DeclSpec:
9257 break;
9258
9259 case TAL_DeclChunk:
9260 case TAL_DeclName:
9261 state.getSema().Diag(attr.getLoc(),
9262 diag::err_objc_kindof_wrong_position)
9263 << FixItHint::CreateRemoval(attr.getLoc())
9265 state.getDeclarator().getDeclSpec().getBeginLoc(),
9266 "__kindof ");
9267 break;
9268 }
9269
9270 // Apply it regardless.
9271 if (checkObjCKindOfType(state, type, attr))
9272 attr.setInvalid();
9273 break;
9274
9275 case ParsedAttr::AT_NoThrow:
9276 // Exception Specifications aren't generally supported in C mode throughout
9277 // clang, so revert to attribute-based handling for C.
9278 if (!state.getSema().getLangOpts().CPlusPlus)
9279 break;
9280 [[fallthrough]];
9282
9283 attr.setUsedAsTypeAttr();
9284
9285 // Attributes with standard syntax have strict rules for what they
9286 // appertain to and hence should not use the "distribution" logic below.
9287 if (attr.isStandardAttributeSyntax() ||
9288 attr.isRegularKeywordAttribute()) {
9289 if (!handleFunctionTypeAttr(state, attr, type, CFT)) {
9290 diagnoseBadTypeAttribute(state.getSema(), attr, type);
9291 attr.setInvalid();
9292 }
9293 break;
9294 }
9295
9296 // Never process function type attributes as part of the
9297 // declaration-specifiers.
9298 if (TAL == TAL_DeclSpec)
9300
9301 // Otherwise, handle the possible delays.
9302 else if (!handleFunctionTypeAttr(state, attr, type, CFT))
9304 break;
9305 case ParsedAttr::AT_AcquireHandle: {
9306 if (!type->isFunctionType())
9307 return;
9308
9309 if (attr.getNumArgs() != 1) {
9310 state.getSema().Diag(attr.getLoc(),
9311 diag::err_attribute_wrong_number_arguments)
9312 << attr << 1;
9313 attr.setInvalid();
9314 return;
9315 }
9316
9317 StringRef HandleType;
9318 if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType))
9319 return;
9320 type = state.getAttributedType(
9321 AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr),
9322 type, type);
9323 attr.setUsedAsTypeAttr();
9324 break;
9325 }
9326 case ParsedAttr::AT_AnnotateType: {
9328 attr.setUsedAsTypeAttr();
9329 break;
9330 }
9331 case ParsedAttr::AT_HLSLResourceClass:
9332 case ParsedAttr::AT_HLSLROV:
9333 case ParsedAttr::AT_HLSLRawBuffer:
9334 case ParsedAttr::AT_HLSLContainedType: {
9335 // Only collect HLSL resource type attributes that are in
9336 // decl-specifier-seq; do not collect attributes on declarations or those
9337 // that get to slide after declaration name.
9338 if (TAL == TAL_DeclSpec &&
9339 state.getSema().HLSL().handleResourceTypeAttr(type, attr))
9340 attr.setUsedAsTypeAttr();
9341 break;
9342 }
9343 }
9344
9345 // Handle attributes that are defined in a macro. We do not want this to be
9346 // applied to ObjC builtin attributes.
9347 if (isa<AttributedType>(type) && attr.hasMacroIdentifier() &&
9348 !type.getQualifiers().hasObjCLifetime() &&
9349 !type.getQualifiers().hasObjCGCAttr() &&
9350 attr.getKind() != ParsedAttr::AT_ObjCGC &&
9351 attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
9352 const IdentifierInfo *MacroII = attr.getMacroIdentifier();
9353 type = state.getSema().Context.getMacroQualifiedType(type, MacroII);
9354 state.setExpansionLocForMacroQualifiedType(
9355 cast<MacroQualifiedType>(type.getTypePtr()),
9356 attr.getMacroExpansionLoc());
9357 }
9358 }
9359}
9360
9362 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
9363 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
9364 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
9365 auto *Def = Var->getDefinition();
9366 if (!Def) {
9367 SourceLocation PointOfInstantiation = E->getExprLoc();
9368 runWithSufficientStackSpace(PointOfInstantiation, [&] {
9369 InstantiateVariableDefinition(PointOfInstantiation, Var);
9370 });
9371 Def = Var->getDefinition();
9372
9373 // If we don't already have a point of instantiation, and we managed
9374 // to instantiate a definition, this is the point of instantiation.
9375 // Otherwise, we don't request an end-of-TU instantiation, so this is
9376 // not a point of instantiation.
9377 // FIXME: Is this really the right behavior?
9378 if (Var->getPointOfInstantiation().isInvalid() && Def) {
9379 assert(Var->getTemplateSpecializationKind() ==
9381 "explicit instantiation with no point of instantiation");
9382 Var->setTemplateSpecializationKind(
9383 Var->getTemplateSpecializationKind(), PointOfInstantiation);
9384 }
9385 }
9386
9387 // Update the type to the definition's type both here and within the
9388 // expression.
9389 if (Def) {
9390 DRE->setDecl(Def);
9391 QualType T = Def->getType();
9392 DRE->setType(T);
9393 // FIXME: Update the type on all intervening expressions.
9394 E->setType(T);
9395 }
9396
9397 // We still go on to try to complete the type independently, as it
9398 // may also require instantiations or diagnostics if it remains
9399 // incomplete.
9400 }
9401 }
9402 }
9403 if (const auto CastE = dyn_cast<ExplicitCastExpr>(E)) {
9404 QualType DestType = CastE->getTypeAsWritten();
9405 if (const auto *IAT = Context.getAsIncompleteArrayType(DestType)) {
9406 // C++20 [expr.static.cast]p.4: ... If T is array of unknown bound,
9407 // this direct-initialization defines the type of the expression
9408 // as U[1]
9409 QualType ResultType = Context.getConstantArrayType(
9410 IAT->getElementType(),
9411 llvm::APInt(Context.getTypeSize(Context.getSizeType()), 1),
9412 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal,
9413 /*IndexTypeQuals=*/0);
9414 E->setType(ResultType);
9415 }
9416 }
9417}
9418
9420 // Incomplete array types may be completed by the initializer attached to
9421 // their definitions. For static data members of class templates and for
9422 // variable templates, we need to instantiate the definition to get this
9423 // initializer and complete the type.
9424 if (E->getType()->isIncompleteArrayType())
9426
9427 // FIXME: Are there other cases which require instantiating something other
9428 // than the type to complete the type of an expression?
9429
9430 return E->getType();
9431}
9432
9434 TypeDiagnoser &Diagnoser) {
9435 return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind,
9436 Diagnoser);
9437}
9438
9439bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
9440 BoundTypeDiagnoser<> Diagnoser(DiagID);
9442}
9443
9445 CompleteTypeKind Kind,
9446 TypeDiagnoser &Diagnoser) {
9447 if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser))
9448 return true;
9449 if (auto *TD = T->getAsTagDecl(); TD && !TD->isCompleteDefinitionRequired()) {
9450 TD->setCompleteDefinitionRequired();
9451 Consumer.HandleTagDeclRequiredDefinition(TD);
9452 }
9453 return false;
9454}
9455
9458 if (!Suggested)
9459 return false;
9460
9461 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
9462 // and isolate from other C++ specific checks.
9464 getLangOpts(), D->getASTContext(), Suggested->getASTContext(),
9465 NonEquivalentDecls, StructuralEquivalenceKind::Default,
9466 /*StrictTypeSpelling=*/false, /*Complain=*/true,
9467 /*ErrorOnTagTypeMismatch=*/true);
9468 return Ctx.IsEquivalent(D, Suggested);
9469}
9470
9472 AcceptableKind Kind, bool OnlyNeedComplete) {
9473 // Easy case: if we don't have modules, all declarations are visible.
9474 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
9475 return true;
9476
9477 // If this definition was instantiated from a template, map back to the
9478 // pattern from which it was instantiated.
9479 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined())
9480 // We're in the middle of defining it; this definition should be treated
9481 // as visible.
9482 return true;
9483
9484 auto DefinitionIsAcceptable = [&](NamedDecl *D) {
9485 // The (primary) definition might be in a visible module.
9486 if (isAcceptable(D, Kind))
9487 return true;
9488
9489 // A visible module might have a merged definition instead.
9492 if (CodeSynthesisContexts.empty() &&
9493 !getLangOpts().ModulesLocalVisibility) {
9494 // Cache the fact that this definition is implicitly visible because
9495 // there is a visible merged definition.
9497 }
9498 return true;
9499 }
9500
9501 return false;
9502 };
9503 auto IsDefinition = [](NamedDecl *D) {
9504 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
9505 return RD->isThisDeclarationADefinition();
9506 if (auto *ED = dyn_cast<EnumDecl>(D))
9507 return ED->isThisDeclarationADefinition();
9508 if (auto *FD = dyn_cast<FunctionDecl>(D))
9509 return FD->isThisDeclarationADefinition();
9510 if (auto *VD = dyn_cast<VarDecl>(D))
9511 return VD->isThisDeclarationADefinition() == VarDecl::Definition;
9512 llvm_unreachable("unexpected decl type");
9513 };
9514 auto FoundAcceptableDefinition = [&](NamedDecl *D) {
9516 return DefinitionIsAcceptable(D);
9517
9518 // See ASTDeclReader::attachPreviousDeclImpl. Now we still
9519 // may demote definition to declaration for decls in haeder modules,
9520 // so avoid looking at its redeclaration to save time.
9521 // NOTE: If we don't demote definition to declarations for decls
9522 // in header modules, remove the condition.
9524 return DefinitionIsAcceptable(D);
9525
9526 for (auto *RD : D->redecls()) {
9527 auto *ND = cast<NamedDecl>(RD);
9528 if (!IsDefinition(ND))
9529 continue;
9530 if (DefinitionIsAcceptable(ND)) {
9531 *Suggested = ND;
9532 return true;
9533 }
9534 }
9535
9536 return false;
9537 };
9538
9539 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9540 if (auto *Pattern = RD->getTemplateInstantiationPattern())
9541 RD = Pattern;
9542 D = RD->getDefinition();
9543 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
9544 if (auto *Pattern = ED->getTemplateInstantiationPattern())
9545 ED = Pattern;
9546 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) {
9547 // If the enum has a fixed underlying type, it may have been forward
9548 // declared. In -fms-compatibility, `enum Foo;` will also forward declare
9549 // the enum and assign it the underlying type of `int`. Since we're only
9550 // looking for a complete type (not a definition), any visible declaration
9551 // of it will do.
9552 *Suggested = nullptr;
9553 for (auto *Redecl : ED->redecls()) {
9554 if (isAcceptable(Redecl, Kind))
9555 return true;
9556 if (Redecl->isThisDeclarationADefinition() ||
9557 (Redecl->isCanonicalDecl() && !*Suggested))
9558 *Suggested = Redecl;
9559 }
9560
9561 return false;
9562 }
9563 D = ED->getDefinition();
9564 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
9565 if (auto *Pattern = FD->getTemplateInstantiationPattern())
9566 FD = Pattern;
9567 D = FD->getDefinition();
9568 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
9569 if (auto *Pattern = VD->getTemplateInstantiationPattern())
9570 VD = Pattern;
9571 D = VD->getDefinition();
9572 }
9573
9574 assert(D && "missing definition for pattern of instantiated definition");
9575
9576 *Suggested = D;
9577
9578 if (FoundAcceptableDefinition(D))
9579 return true;
9580
9581 // The external source may have additional definitions of this entity that are
9582 // visible, so complete the redeclaration chain now and ask again.
9583 if (auto *Source = Context.getExternalSource()) {
9584 Source->CompleteRedeclChain(D);
9585 return FoundAcceptableDefinition(D);
9586 }
9587
9588 return false;
9589}
9590
9591/// Determine whether there is any declaration of \p D that was ever a
9592/// definition (perhaps before module merging) and is currently visible.
9593/// \param D The definition of the entity.
9594/// \param Suggested Filled in with the declaration that should be made visible
9595/// in order to provide a definition of this entity.
9596/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9597/// not defined. This only matters for enums with a fixed underlying
9598/// type, since in all other cases, a type is complete if and only if it
9599/// is defined.
9601 bool OnlyNeedComplete) {
9603 OnlyNeedComplete);
9604}
9605
9606/// Determine whether there is any declaration of \p D that was ever a
9607/// definition (perhaps before module merging) and is currently
9608/// reachable.
9609/// \param D The definition of the entity.
9610/// \param Suggested Filled in with the declaration that should be made
9611/// reachable
9612/// in order to provide a definition of this entity.
9613/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9614/// not defined. This only matters for enums with a fixed underlying
9615/// type, since in all other cases, a type is complete if and only if it
9616/// is defined.
9618 bool OnlyNeedComplete) {
9620 OnlyNeedComplete);
9621}
9622
9623/// Locks in the inheritance model for the given class and all of its bases.
9625 RD = RD->getMostRecentDecl();
9626 if (!RD->hasAttr<MSInheritanceAttr>()) {
9628 bool BestCase = false;
9631 BestCase = true;
9632 IM = RD->calculateInheritanceModel();
9633 break;
9636 break;
9639 break;
9642 break;
9643 }
9644
9647 : RD->getSourceRange();
9648 RD->addAttr(MSInheritanceAttr::CreateImplicit(
9649 S.getASTContext(), BestCase, Loc, MSInheritanceAttr::Spelling(IM)));
9651 }
9652}
9653
9654bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
9655 CompleteTypeKind Kind,
9656 TypeDiagnoser *Diagnoser) {
9657 // FIXME: Add this assertion to make sure we always get instantiation points.
9658 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
9659 // FIXME: Add this assertion to help us flush out problems with
9660 // checking for dependent types and type-dependent expressions.
9661 //
9662 // assert(!T->isDependentType() &&
9663 // "Can't ask whether a dependent type is complete");
9664
9665 if (const auto *MPTy = dyn_cast<MemberPointerType>(T.getCanonicalType())) {
9666 if (CXXRecordDecl *RD = MPTy->getMostRecentCXXRecordDecl();
9667 RD && !RD->isDependentType()) {
9668 CanQualType T = Context.getCanonicalTagType(RD);
9669 if (getLangOpts().CompleteMemberPointers && !RD->isBeingDefined() &&
9670 RequireCompleteType(Loc, T, Kind, diag::err_memptr_incomplete))
9671 return true;
9672
9673 // We lock in the inheritance model once somebody has asked us to ensure
9674 // that a pointer-to-member type is complete.
9675 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9676 (void)isCompleteType(Loc, T);
9677 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
9678 }
9679 }
9680 }
9681
9682 NamedDecl *Def = nullptr;
9684 bool Incomplete = (T->isIncompleteType(&Def) ||
9685 (!AcceptSizeless && T->isSizelessBuiltinType()));
9686
9687 // Check that any necessary explicit specializations are visible. For an
9688 // enum, we just need the declaration, so don't check this.
9689 if (Def && !isa<EnumDecl>(Def))
9691
9692 // If we have a complete type, we're done.
9693 if (!Incomplete) {
9694 NamedDecl *Suggested = nullptr;
9695 if (Def &&
9696 !hasReachableDefinition(Def, &Suggested, /*OnlyNeedComplete=*/true)) {
9697 // If the user is going to see an error here, recover by making the
9698 // definition visible.
9699 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
9700 if (Diagnoser && Suggested)
9702 /*Recover*/ TreatAsComplete);
9703 return !TreatAsComplete;
9704 } else if (Def && !TemplateInstCallbacks.empty()) {
9705 CodeSynthesisContext TempInst;
9707 TempInst.Template = Def;
9708 TempInst.Entity = Def;
9709 TempInst.PointOfInstantiation = Loc;
9710 atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
9711 atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
9712 }
9713
9714 return false;
9715 }
9716
9717 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
9718 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
9719
9720 // Give the external source a chance to provide a definition of the type.
9721 // This is kept separate from completing the redeclaration chain so that
9722 // external sources such as LLDB can avoid synthesizing a type definition
9723 // unless it's actually needed.
9724 if (Tag || IFace) {
9725 // Avoid diagnosing invalid decls as incomplete.
9726 if (Def->isInvalidDecl())
9727 return true;
9728
9729 // Give the external AST source a chance to complete the type.
9730 if (auto *Source = Context.getExternalSource()) {
9731 if (Tag && Tag->hasExternalLexicalStorage())
9732 Source->CompleteType(Tag);
9733 if (IFace && IFace->hasExternalLexicalStorage())
9734 Source->CompleteType(IFace);
9735 // If the external source completed the type, go through the motions
9736 // again to ensure we're allowed to use the completed type.
9737 if (!T->isIncompleteType())
9738 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9739 }
9740 }
9741
9742 // If we have a class template specialization or a class member of a
9743 // class template specialization, or an array with known size of such,
9744 // try to instantiate it.
9745 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
9746 bool Instantiated = false;
9747 bool Diagnosed = false;
9748 if (RD->isDependentContext()) {
9749 // Don't try to instantiate a dependent class (eg, a member template of
9750 // an instantiated class template specialization).
9751 // FIXME: Can this ever happen?
9752 } else if (auto *ClassTemplateSpec =
9753 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
9754 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
9757 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
9758 /*Complain=*/Diagnoser, ClassTemplateSpec->hasStrictPackMatch());
9759 });
9760 Instantiated = true;
9761 }
9762 } else {
9763 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
9764 if (!RD->isBeingDefined() && Pattern) {
9765 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
9766 assert(MSI && "Missing member specialization information?");
9767 // This record was instantiated from a class within a template.
9768 if (MSI->getTemplateSpecializationKind() !=
9771 Diagnosed = InstantiateClass(Loc, RD, Pattern,
9774 /*Complain=*/Diagnoser);
9775 });
9776 Instantiated = true;
9777 }
9778 }
9779 }
9780
9781 if (Instantiated) {
9782 // Instantiate* might have already complained that the template is not
9783 // defined, if we asked it to.
9784 if (Diagnoser && Diagnosed)
9785 return true;
9786 // If we instantiated a definition, check that it's usable, even if
9787 // instantiation produced an error, so that repeated calls to this
9788 // function give consistent answers.
9789 if (!T->isIncompleteType())
9790 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9791 }
9792 }
9793
9794 // FIXME: If we didn't instantiate a definition because of an explicit
9795 // specialization declaration, check that it's visible.
9796
9797 if (!Diagnoser)
9798 return true;
9799
9800 Diagnoser->diagnose(*this, Loc, T);
9801
9802 // If the type was a forward declaration of a class/struct/union
9803 // type, produce a note.
9804 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid())
9805 Diag(Tag->getLocation(), Tag->isBeingDefined()
9806 ? diag::note_type_being_defined
9807 : diag::note_forward_declaration)
9808 << Context.getCanonicalTagType(Tag);
9809
9810 // If the Objective-C class was a forward declaration, produce a note.
9811 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid())
9812 Diag(IFace->getLocation(), diag::note_forward_class);
9813
9814 // If we have external information that we can use to suggest a fix,
9815 // produce a note.
9816 if (ExternalSource)
9817 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
9818
9819 return true;
9820}
9821
9823 CompleteTypeKind Kind, unsigned DiagID) {
9824 BoundTypeDiagnoser<> Diagnoser(DiagID);
9825 return RequireCompleteType(Loc, T, Kind, Diagnoser);
9826}
9827
9828/// Get diagnostic %select index for tag kind for
9829/// literal type diagnostic message.
9830/// WARNING: Indexes apply to particular diagnostics only!
9831///
9832/// \returns diagnostic %select index.
9834 switch (Tag) {
9836 return 0;
9838 return 1;
9839 case TagTypeKind::Class:
9840 return 2;
9841 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
9842 }
9843}
9844
9846 TypeDiagnoser &Diagnoser) {
9847 assert(!T->isDependentType() && "type should not be dependent");
9848
9849 QualType ElemType = Context.getBaseElementType(T);
9850 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
9851 T->isLiteralType(Context))
9852 return false;
9853
9854 Diagnoser.diagnose(*this, Loc, T);
9855
9856 if (T->isVariableArrayType())
9857 return true;
9858
9859 if (!ElemType->isRecordType())
9860 return true;
9861
9862 // A partially-defined class type can't be a literal type, because a literal
9863 // class type must have a trivial destructor (which can't be checked until
9864 // the class definition is complete).
9865 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
9866 return true;
9867
9868 const auto *RD = ElemType->castAsCXXRecordDecl();
9869 // [expr.prim.lambda]p3:
9870 // This class type is [not] a literal type.
9871 if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
9872 Diag(RD->getLocation(), diag::note_non_literal_lambda);
9873 return true;
9874 }
9875
9876 // If the class has virtual base classes, then it's not an aggregate, and
9877 // cannot have any constexpr constructors or a trivial default constructor,
9878 // so is non-literal. This is better to diagnose than the resulting absence
9879 // of constexpr constructors.
9880 if (RD->getNumVBases()) {
9881 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
9882 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
9883 for (const auto &I : RD->vbases())
9884 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
9885 << I.getSourceRange();
9886 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
9887 !RD->hasTrivialDefaultConstructor()) {
9888 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
9889 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
9890 for (const auto &I : RD->bases()) {
9891 if (!I.getType()->isLiteralType(Context)) {
9892 Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
9893 << RD << I.getType() << I.getSourceRange();
9894 return true;
9895 }
9896 }
9897 for (const auto *I : RD->fields()) {
9898 if (!I->getType()->isLiteralType(Context) ||
9899 I->getType().isVolatileQualified()) {
9900 Diag(I->getLocation(), diag::note_non_literal_field)
9901 << RD << I << I->getType()
9902 << I->getType().isVolatileQualified();
9903 return true;
9904 }
9905 }
9906 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor()
9907 : !RD->hasTrivialDestructor()) {
9908 // All fields and bases are of literal types, so have trivial or constexpr
9909 // destructors. If this class's destructor is non-trivial / non-constexpr,
9910 // it must be user-declared.
9911 CXXDestructorDecl *Dtor = RD->getDestructor();
9912 assert(Dtor && "class has literal fields and bases but no dtor?");
9913 if (!Dtor)
9914 return true;
9915
9916 if (getLangOpts().CPlusPlus20) {
9917 Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor)
9918 << RD;
9919 } else {
9920 Diag(Dtor->getLocation(), Dtor->isUserProvided()
9921 ? diag::note_non_literal_user_provided_dtor
9922 : diag::note_non_literal_nontrivial_dtor)
9923 << RD;
9924 if (!Dtor->isUserProvided())
9927 /*Diagnose*/ true);
9928 }
9929 }
9930
9931 return true;
9932}
9933
9934bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
9935 BoundTypeDiagnoser<> Diagnoser(DiagID);
9936 return RequireLiteralType(Loc, T, Diagnoser);
9937}
9938
9940 assert(!E->hasPlaceholderType() && "unexpected placeholder");
9941
9942 if (!getLangOpts().CPlusPlus && E->refersToBitField())
9943 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
9944 << (Kind == TypeOfKind::Unqualified ? 3 : 2);
9945
9946 if (!E->isTypeDependent()) {
9947 QualType T = E->getType();
9948 if (const TagType *TT = T->getAs<TagType>())
9949 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
9950 }
9951 return Context.getTypeOfExprType(E, Kind);
9952}
9953
9954static void
9957 // Currently, 'counted_by' only allows direct DeclRefExpr to FieldDecl.
9958 auto *CountDecl = cast<DeclRefExpr>(E)->getDecl();
9959 Decls.push_back(TypeCoupledDeclRefInfo(CountDecl, /*IsDref*/ false));
9960}
9961
9963 Expr *CountExpr,
9964 bool CountInBytes,
9965 bool OrNull) {
9966 assert(WrappedTy->isIncompleteArrayType() || WrappedTy->isPointerType());
9967
9969 BuildTypeCoupledDecls(CountExpr, Decls);
9970 /// When the resulting expression is invalid, we still create the AST using
9971 /// the original count expression for the sake of AST dump.
9972 return Context.getCountAttributedType(WrappedTy, CountExpr, CountInBytes,
9973 OrNull, Decls);
9974}
9975
9976/// getDecltypeForExpr - Given an expr, will return the decltype for
9977/// that expression, according to the rules in C++11
9978/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
9980
9981 Expr *IDExpr = E;
9982 if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E))
9983 IDExpr = ImplCastExpr->getSubExpr();
9984
9985 if (auto *PackExpr = dyn_cast<PackIndexingExpr>(E)) {
9986 if (E->isInstantiationDependent())
9987 IDExpr = PackExpr->getPackIdExpression();
9988 else
9989 IDExpr = PackExpr->getSelectedExpr();
9990 }
9991
9992 if (E->isTypeDependent())
9993 return Context.DependentTy;
9994
9995 // C++11 [dcl.type.simple]p4:
9996 // The type denoted by decltype(e) is defined as follows:
9997
9998 // C++20:
9999 // - if E is an unparenthesized id-expression naming a non-type
10000 // template-parameter (13.2), decltype(E) is the type of the
10001 // template-parameter after performing any necessary type deduction
10002 // Note that this does not pick up the implicit 'const' for a template
10003 // parameter object. This rule makes no difference before C++20 so we apply
10004 // it unconditionally.
10005 if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr))
10006 return SNTTPE->getParameterType(Context);
10007
10008 // - if e is an unparenthesized id-expression or an unparenthesized class
10009 // member access (5.2.5), decltype(e) is the type of the entity named
10010 // by e. If there is no such entity, or if e names a set of overloaded
10011 // functions, the program is ill-formed;
10012 //
10013 // We apply the same rules for Objective-C ivar and property references.
10014 if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) {
10015 const ValueDecl *VD = DRE->getDecl();
10016 QualType T = VD->getType();
10017 return isa<TemplateParamObjectDecl>(VD) ? T.getUnqualifiedType() : T;
10018 }
10019 if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) {
10020 if (const auto *VD = ME->getMemberDecl())
10021 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
10022 return VD->getType();
10023 } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) {
10024 return IR->getDecl()->getType();
10025 } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) {
10026 if (PR->isExplicitProperty())
10027 return PR->getExplicitProperty()->getType();
10028 } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) {
10029 return PE->getType();
10030 }
10031
10032 // C++11 [expr.lambda.prim]p18:
10033 // Every occurrence of decltype((x)) where x is a possibly
10034 // parenthesized id-expression that names an entity of automatic
10035 // storage duration is treated as if x were transformed into an
10036 // access to a corresponding data member of the closure type that
10037 // would have been declared if x were an odr-use of the denoted
10038 // entity.
10039 if (getCurLambda() && isa<ParenExpr>(IDExpr)) {
10040 if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) {
10041 if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
10042 QualType T = getCapturedDeclRefType(Var, DRE->getLocation());
10043 if (!T.isNull())
10044 return Context.getLValueReferenceType(T);
10045 }
10046 }
10047 }
10048
10049 return Context.getReferenceQualifiedType(E);
10050}
10051
10052QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) {
10053 assert(!E->hasPlaceholderType() && "unexpected placeholder");
10054
10055 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
10056 !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) {
10057 // The expression operand for decltype is in an unevaluated expression
10058 // context, so side effects could result in unintended consequences.
10059 // Exclude instantiation-dependent expressions, because 'decltype' is often
10060 // used to build SFINAE gadgets.
10061 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
10062 }
10063 return Context.getDecltypeType(E, getDecltypeForExpr(E));
10064}
10065
10067 SourceLocation Loc,
10068 SourceLocation EllipsisLoc) {
10069 if (!IndexExpr)
10070 return QualType();
10071
10072 // Diagnose unexpanded packs but continue to improve recovery.
10073 if (!Pattern->containsUnexpandedParameterPack())
10074 Diag(Loc, diag::err_expected_name_of_pack) << Pattern;
10075
10076 QualType Type = BuildPackIndexingType(Pattern, IndexExpr, Loc, EllipsisLoc);
10077
10078 if (!Type.isNull())
10079 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::warn_cxx23_pack_indexing
10080 : diag::ext_pack_indexing);
10081 return Type;
10082}
10083
10085 SourceLocation Loc,
10086 SourceLocation EllipsisLoc,
10087 bool FullySubstituted,
10088 ArrayRef<QualType> Expansions) {
10089
10090 UnsignedOrNone Index = std::nullopt;
10091 if (FullySubstituted && !IndexExpr->isValueDependent() &&
10092 !IndexExpr->isTypeDependent()) {
10093 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
10095 IndexExpr, Context.getSizeType(), Value, CCEKind::ArrayBound);
10096 if (!Res.isUsable())
10097 return QualType();
10098 IndexExpr = Res.get();
10099 int64_t V = Value.getExtValue();
10100 if (FullySubstituted && (V < 0 || V >= int64_t(Expansions.size()))) {
10101 Diag(IndexExpr->getBeginLoc(), diag::err_pack_index_out_of_bound)
10102 << V << Pattern << Expansions.size();
10103 return QualType();
10104 }
10105 Index = static_cast<unsigned>(V);
10106 }
10107
10108 return Context.getPackIndexingType(Pattern, IndexExpr, FullySubstituted,
10109 Expansions, Index);
10110}
10111
10113 SourceLocation Loc) {
10114 assert(BaseType->isEnumeralType());
10115 EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl();
10116
10117 S.DiagnoseUseOfDecl(ED, Loc);
10118
10119 QualType Underlying = ED->getIntegerType();
10120 if (Underlying.isNull()) {
10121 Underlying = ED->getDefinition()->getIntegerType();
10122 assert(!Underlying.isNull());
10123 }
10124
10125 return Underlying;
10126}
10127
10129 SourceLocation Loc) {
10130 if (!BaseType->isEnumeralType()) {
10131 Diag(Loc, diag::err_only_enums_have_underlying_types);
10132 return QualType();
10133 }
10134
10135 // The enum could be incomplete if we're parsing its definition or
10136 // recovering from an error.
10137 NamedDecl *FwdDecl = nullptr;
10138 if (BaseType->isIncompleteType(&FwdDecl)) {
10139 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
10140 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
10141 return QualType();
10142 }
10143
10144 return GetEnumUnderlyingType(*this, BaseType, Loc);
10145}
10146
10148 QualType Pointer = BaseType.isReferenceable() || BaseType->isVoidType()
10149 ? BuildPointerType(BaseType.getNonReferenceType(), Loc,
10151 : BaseType;
10152
10153 return Pointer.isNull() ? QualType() : Pointer;
10154}
10155
10157 if (!BaseType->isAnyPointerType())
10158 return BaseType;
10159
10160 return BaseType->getPointeeType();
10161}
10162
10164 QualType Underlying = BaseType.getNonReferenceType();
10165 if (Underlying->isArrayType())
10166 return Context.getDecayedType(Underlying);
10167
10168 if (Underlying->isFunctionType())
10169 return BuiltinAddPointer(BaseType, Loc);
10170
10171 SplitQualType Split = Underlying.getSplitUnqualifiedType();
10172 // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is
10173 // in the same group of qualifiers as 'const' and 'volatile', we're extending
10174 // '__decay(T)' so that it removes all qualifiers.
10175 Split.Quals.removeCVRQualifiers();
10176 return Context.getQualifiedType(Split);
10177}
10178
10180 SourceLocation Loc) {
10181 assert(LangOpts.CPlusPlus);
10183 BaseType.isReferenceable()
10184 ? BuildReferenceType(BaseType,
10185 UKind == UnaryTransformType::AddLvalueReference,
10186 Loc, DeclarationName())
10187 : BaseType;
10188 return Reference.isNull() ? QualType() : Reference;
10189}
10190
10192 SourceLocation Loc) {
10193 if (UKind == UnaryTransformType::RemoveAllExtents)
10194 return Context.getBaseElementType(BaseType);
10195
10196 if (const auto *AT = Context.getAsArrayType(BaseType))
10197 return AT->getElementType();
10198
10199 return BaseType;
10200}
10201
10203 SourceLocation Loc) {
10204 assert(LangOpts.CPlusPlus);
10205 QualType T = BaseType.getNonReferenceType();
10206 if (UKind == UTTKind::RemoveCVRef &&
10207 (T.isConstQualified() || T.isVolatileQualified())) {
10208 Qualifiers Quals;
10209 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
10210 Quals.removeConst();
10211 Quals.removeVolatile();
10212 T = Context.getQualifiedType(Unqual, Quals);
10213 }
10214 return T;
10215}
10216
10218 SourceLocation Loc) {
10219 if ((BaseType->isReferenceType() && UKind != UTTKind::RemoveRestrict) ||
10220 BaseType->isFunctionType())
10221 return BaseType;
10222
10223 Qualifiers Quals;
10224 QualType Unqual = Context.getUnqualifiedArrayType(BaseType, Quals);
10225
10226 if (UKind == UTTKind::RemoveConst || UKind == UTTKind::RemoveCV)
10227 Quals.removeConst();
10228 if (UKind == UTTKind::RemoveVolatile || UKind == UTTKind::RemoveCV)
10229 Quals.removeVolatile();
10230 if (UKind == UTTKind::RemoveRestrict)
10231 Quals.removeRestrict();
10232
10233 return Context.getQualifiedType(Unqual, Quals);
10234}
10235
10237 bool IsMakeSigned,
10238 SourceLocation Loc) {
10239 if (BaseType->isEnumeralType()) {
10240 QualType Underlying = GetEnumUnderlyingType(S, BaseType, Loc);
10241 if (auto *BitInt = dyn_cast<BitIntType>(Underlying)) {
10242 unsigned int Bits = BitInt->getNumBits();
10243 if (Bits > 1)
10244 return S.Context.getBitIntType(!IsMakeSigned, Bits);
10245
10246 S.Diag(Loc, diag::err_make_signed_integral_only)
10247 << IsMakeSigned << /*_BitInt(1)*/ true << BaseType << 1 << Underlying;
10248 return QualType();
10249 }
10250 if (Underlying->isBooleanType()) {
10251 S.Diag(Loc, diag::err_make_signed_integral_only)
10252 << IsMakeSigned << /*_BitInt(1)*/ false << BaseType << 1
10253 << Underlying;
10254 return QualType();
10255 }
10256 }
10257
10258 bool Int128Unsupported = !S.Context.getTargetInfo().hasInt128Type();
10259 std::array<CanQualType *, 6> AllSignedIntegers = {
10262 ArrayRef<CanQualType *> AvailableSignedIntegers(
10263 AllSignedIntegers.data(), AllSignedIntegers.size() - Int128Unsupported);
10264 std::array<CanQualType *, 6> AllUnsignedIntegers = {
10268 ArrayRef<CanQualType *> AvailableUnsignedIntegers(AllUnsignedIntegers.data(),
10269 AllUnsignedIntegers.size() -
10270 Int128Unsupported);
10271 ArrayRef<CanQualType *> *Consider =
10272 IsMakeSigned ? &AvailableSignedIntegers : &AvailableUnsignedIntegers;
10273
10274 uint64_t BaseSize = S.Context.getTypeSize(BaseType);
10275 auto *Result =
10276 llvm::find_if(*Consider, [&S, BaseSize](const CanQual<Type> *T) {
10277 return BaseSize == S.Context.getTypeSize(T->getTypePtr());
10278 });
10279
10280 assert(Result != Consider->end());
10281 return QualType((*Result)->getTypePtr(), 0);
10282}
10283
10285 SourceLocation Loc) {
10286 bool IsMakeSigned = UKind == UnaryTransformType::MakeSigned;
10287 if ((!BaseType->isIntegerType() && !BaseType->isEnumeralType()) ||
10288 BaseType->isBooleanType() ||
10289 (BaseType->isBitIntType() &&
10290 BaseType->getAs<BitIntType>()->getNumBits() < 2)) {
10291 Diag(Loc, diag::err_make_signed_integral_only)
10292 << IsMakeSigned << BaseType->isBitIntType() << BaseType << 0;
10293 return QualType();
10294 }
10295
10296 bool IsNonIntIntegral =
10297 BaseType->isChar16Type() || BaseType->isChar32Type() ||
10298 BaseType->isWideCharType() || BaseType->isEnumeralType();
10299
10300 QualType Underlying =
10301 IsNonIntIntegral
10302 ? ChangeIntegralSignedness(*this, BaseType, IsMakeSigned, Loc)
10303 : IsMakeSigned ? Context.getCorrespondingSignedType(BaseType)
10304 : Context.getCorrespondingUnsignedType(BaseType);
10305 if (Underlying.isNull())
10306 return Underlying;
10307 return Context.getQualifiedType(Underlying, BaseType.getQualifiers());
10308}
10309
10311 SourceLocation Loc) {
10312 if (BaseType->isDependentType())
10313 return Context.getUnaryTransformType(BaseType, BaseType, UKind);
10315 switch (UKind) {
10316 case UnaryTransformType::EnumUnderlyingType: {
10317 Result = BuiltinEnumUnderlyingType(BaseType, Loc);
10318 break;
10319 }
10320 case UnaryTransformType::AddPointer: {
10321 Result = BuiltinAddPointer(BaseType, Loc);
10322 break;
10323 }
10324 case UnaryTransformType::RemovePointer: {
10325 Result = BuiltinRemovePointer(BaseType, Loc);
10326 break;
10327 }
10328 case UnaryTransformType::Decay: {
10329 Result = BuiltinDecay(BaseType, Loc);
10330 break;
10331 }
10332 case UnaryTransformType::AddLvalueReference:
10333 case UnaryTransformType::AddRvalueReference: {
10334 Result = BuiltinAddReference(BaseType, UKind, Loc);
10335 break;
10336 }
10337 case UnaryTransformType::RemoveAllExtents:
10338 case UnaryTransformType::RemoveExtent: {
10339 Result = BuiltinRemoveExtent(BaseType, UKind, Loc);
10340 break;
10341 }
10342 case UnaryTransformType::RemoveCVRef:
10343 case UnaryTransformType::RemoveReference: {
10344 Result = BuiltinRemoveReference(BaseType, UKind, Loc);
10345 break;
10346 }
10347 case UnaryTransformType::RemoveConst:
10348 case UnaryTransformType::RemoveCV:
10349 case UnaryTransformType::RemoveRestrict:
10350 case UnaryTransformType::RemoveVolatile: {
10351 Result = BuiltinChangeCVRQualifiers(BaseType, UKind, Loc);
10352 break;
10353 }
10354 case UnaryTransformType::MakeSigned:
10355 case UnaryTransformType::MakeUnsigned: {
10356 Result = BuiltinChangeSignedness(BaseType, UKind, Loc);
10357 break;
10358 }
10359 }
10360
10361 return !Result.isNull()
10362 ? Context.getUnaryTransformType(BaseType, Result, UKind)
10363 : Result;
10364}
10365
10367 if (!isDependentOrGNUAutoType(T)) {
10368 // FIXME: It isn't entirely clear whether incomplete atomic types
10369 // are allowed or not; for simplicity, ban them for the moment.
10370 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
10371 return QualType();
10372
10373 int DisallowedKind = -1;
10374 if (T->isArrayType())
10375 DisallowedKind = 1;
10376 else if (T->isFunctionType())
10377 DisallowedKind = 2;
10378 else if (T->isReferenceType())
10379 DisallowedKind = 3;
10380 else if (T->isAtomicType())
10381 DisallowedKind = 4;
10382 else if (T.hasQualifiers())
10383 DisallowedKind = 5;
10384 else if (T->isSizelessType())
10385 DisallowedKind = 6;
10386 else if (!T.isTriviallyCopyableType(Context) && getLangOpts().CPlusPlus)
10387 // Some other non-trivially-copyable type (probably a C++ class)
10388 DisallowedKind = 7;
10389 else if (T->isBitIntType())
10390 DisallowedKind = 8;
10391 else if (getLangOpts().C23 && T->isUndeducedAutoType())
10392 // _Atomic auto is prohibited in C23
10393 DisallowedKind = 9;
10394
10395 if (DisallowedKind != -1) {
10396 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
10397 return QualType();
10398 }
10399
10400 // FIXME: Do we need any handling for ARC here?
10401 }
10402
10403 // Build the pointer type.
10404 return Context.getAtomicType(T);
10405}
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.
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.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
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 bool isDependentOrGNUAutoType(QualType T)
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:226
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:797
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...
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
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack=false, TemplateDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
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:916
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:8240
unsigned getNumBits() const
Definition TypeBase.h:8252
void setCaretLoc(SourceLocation Loc)
Definition TypeLoc.h:1532
Pointer to a block type.
Definition TypeBase.h:3550
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:3172
Kind getKind() const
Definition TypeBase.h:3220
Represents a C++ destructor within a class.
Definition DeclCXX.h:2876
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:786
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:1186
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:74
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:186
SourceRange getRange() const
Definition DeclSpec.h:80
SourceLocation getBeginLoc() const
Definition DeclSpec.h:84
bool isSet() const
Deprecated.
Definition DeclSpec.h:199
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:95
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:184
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:215
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:255
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
bool isRecord() const
Definition DeclBase.h:2189
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition DeclBase.h:2688
bool isFunctionOrMethod() const
Definition DeclBase.h:2161
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1273
Captures information about "declaration specifiers".
Definition DeclSpec.h:218
const WrittenBuiltinSpecs & getWrittenBuiltinSpecs() const
Definition DeclSpec.h:890
bool isTypeSpecPipe() const
Definition DeclSpec.h:526
static const TST TST_typeof_unqualType
Definition DeclSpec.h:280
SourceLocation getTypeSpecSignLoc() const
Definition DeclSpec.h:564
bool hasAutoTypeSpec() const
Definition DeclSpec.h:578
static const TST TST_typename
Definition DeclSpec.h:277
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:559
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition DeclSpec.h:696
static const TST TST_char8
Definition DeclSpec.h:253
static const TST TST_BFloat16
Definition DeclSpec.h:260
Expr * getPackIndexingExpr() const
Definition DeclSpec.h:543
TST getTypeSpecType() const
Definition DeclSpec.h:520
SCS getStorageClassSpec() const
Definition DeclSpec.h:484
SourceLocation getOverflowBehaviorLoc() const
Definition DeclSpec.h:622
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:558
bool isTypeSpecSat() const
Definition DeclSpec.h:527
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:557
static const TST TST_auto_type
Definition DeclSpec.h:290
static const TST TST_interface
Definition DeclSpec.h:275
static const TST TST_double
Definition DeclSpec.h:262
static const TST TST_typeofExpr
Definition DeclSpec.h:279
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:600
TemplateIdAnnotation * getRepAsTemplateId() const
Definition DeclSpec.h:549
static const TST TST_union
Definition DeclSpec.h:273
static const TST TST_typename_pack_indexing
Definition DeclSpec.h:284
static const TST TST_char
Definition DeclSpec.h:251
static const TST TST_bool
Definition DeclSpec.h:268
static const TST TST_char16
Definition DeclSpec.h:254
static const TST TST_unknown_anytype
Definition DeclSpec.h:291
TSC getTypeSpecComplex() const
Definition DeclSpec.h:516
static const TST TST_int
Definition DeclSpec.h:256
ParsedType getRepAsType() const
Definition DeclSpec.h:530
static const TST TST_accum
Definition DeclSpec.h:264
static const TST TST_half
Definition DeclSpec.h:259
ParsedAttributes & getAttributes()
Definition DeclSpec.h:878
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:607
bool isTypeAltiVecPixel() const
Definition DeclSpec.h:522
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition DeclSpec.h:629
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:601
static const TST TST_ibm128
Definition DeclSpec.h:267
Expr * getRepAsExpr() const
Definition DeclSpec.h:538
static const TST TST_enum
Definition DeclSpec.h:272
AttributePool & getAttributePool() const
Definition DeclSpec.h:851
bool isWrapSpecified() const
Definition DeclSpec.h:613
static const TST TST_float128
Definition DeclSpec.h:266
static const TST TST_decltype
Definition DeclSpec.h:282
SourceRange getTypeSpecWidthRange() const
Definition DeclSpec.h:562
SourceLocation getTypeSpecTypeNameLoc() const
Definition DeclSpec.h:569
SourceLocation getTypeSpecWidthLoc() const
Definition DeclSpec.h:561
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:602
static const TST TST_typeof_unqualExpr
Definition DeclSpec.h:281
static const TST TST_class
Definition DeclSpec.h:276
TypeSpecifierType TST
Definition DeclSpec.h:248
bool isOverflowBehaviorSpecified() const
Definition DeclSpec.h:619
bool hasTagDefinition() const
Definition DeclSpec.cpp:433
static const TST TST_decimal64
Definition DeclSpec.h:270
unsigned getParsedSpecifiers() const
Return a bitmask of which flavors of specifiers this DeclSpec includes.
Definition DeclSpec.cpp:442
bool isTypeAltiVecBool() const
Definition DeclSpec.h:523
bool isConstrainedAuto() const
Definition DeclSpec.h:528
static const TST TST_wchar
Definition DeclSpec.h:252
SourceLocation getTypeSpecComplexLoc() const
Definition DeclSpec.h:563
static const TST TST_void
Definition DeclSpec.h:250
bool isTypeAltiVecVector() const
Definition DeclSpec.h:521
static const TST TST_bitint
Definition DeclSpec.h:258
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:261
static const TST TST_atomic
Definition DeclSpec.h:292
bool isTrapSpecified() const
Definition DeclSpec.h:616
static const TST TST_fract
Definition DeclSpec.h:265
Decl * getRepAsDecl() const
Definition DeclSpec.h:534
static const TST TST_float16
Definition DeclSpec.h:263
static bool isTransformTypeTrait(TST T)
Definition DeclSpec.h:456
static const TST TST_unspecified
Definition DeclSpec.h:249
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:604
TypeSpecifierSign getTypeSpecSign() const
Definition DeclSpec.h:517
CXXScopeSpec & getTypeSpecScope()
Definition DeclSpec.h:554
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:565
OverflowBehaviorState getOverflowBehaviorState() const
Definition DeclSpec.h:610
static const TST TST_decltype_auto
Definition DeclSpec.h:283
static const TST TST_error
Definition DeclSpec.h:299
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:269
TypeSpecifierWidth getTypeSpecWidth() const
Definition DeclSpec.h:513
static const TST TST_char32
Definition DeclSpec.h:255
static const TST TST_decimal128
Definition DeclSpec.h:271
bool isTypeSpecOwned() const
Definition DeclSpec.h:524
SourceLocation getTypeSpecSatLoc() const
Definition DeclSpec.h:567
SourceRange getTypeofParensRange() const
Definition DeclSpec.h:575
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:605
static const TST TST_int128
Definition DeclSpec.h:257
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:603
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:826
static const TST TST_typeofType
Definition DeclSpec.h:278
static const TST TST_auto
Definition DeclSpec.h:289
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:837
static const TST TST_struct
Definition DeclSpec.h:274
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:546
void addAttr(Attr *A)
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:842
bool isInvalidDecl() const
Definition DeclBase.h:588
SourceLocation getLocation() const
Definition DeclBase.h:439
void setImplicit(bool I=true)
Definition DeclBase.h:594
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1049
bool hasAttr() const
Definition DeclBase.h:577
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:427
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition DeclBase.h:870
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:1921
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2477
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2419
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2068
const DeclaratorChunk * getInnermostNonParenChunk() const
Return the innermost (closest to the declarator) chunk of this declarator that is not a parens chunk,...
Definition DeclSpec.h:2445
void AddInnermostTypeInfo(const DeclaratorChunk &TI)
Add a new innermost chunk to this declarator.
Definition DeclSpec.h:2410
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition DeclSpec.h:2531
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2762
const ParsedAttributes & getAttributes() const
Definition DeclSpec.h:2704
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2357
bool hasTrailingReturnType() const
Determine whether a trailing return type was written (at any level) within this declarator.
Definition DeclSpec.h:2629
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2105
bool isExpressionContext() const
Determine whether this declaration appears in a context where an expression could appear.
Definition DeclSpec.h:2573
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition DeclSpec.h:2432
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2734
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2415
const ParsedAttributesView & getDeclarationAttributes() const
Definition DeclSpec.h:2707
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2747
DeclaratorContext getContext() const
Definition DeclSpec.h:2093
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2104
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2087
bool isFirstDeclarator() const
Definition DeclSpec.h:2742
SourceLocation getCommaLoc() const
Definition DeclSpec.h:2743
AttributePool & getAttributePool() const
Definition DeclSpec.h:2077
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2083
bool hasEllipsis() const
Definition DeclSpec.h:2746
ParsedType getTrailingReturnType() const
Get the trailing return type appearing (at any level) within this declarator.
Definition DeclSpec.h:2638
bool isInvalidType() const
Definition DeclSpec.h:2735
bool isExplicitObjectMemberFunction()
Definition DeclSpec.cpp:398
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2103
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition DeclSpec.h:2770
bool isPrototypeContext() const
Definition DeclSpec.h:2095
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:2075
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2508
void setEllipsisLoc(SourceLocation EL)
Definition DeclSpec.h:2748
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2351
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:4069
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:959
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:728
Wrap a function effect's condition expression in another struct so that FunctionProtoType's TrailingO...
Definition TypeBase.h:5035
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation NameLoc)
Definition TypeLoc.h:744
Represents an enum.
Definition Decl.h:4013
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4186
EnumDecl * getDefinition() const
Definition Decl.h:4125
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:3090
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3086
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:3670
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:277
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:79
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:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
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:103
A SourceLocation and its associated SourceManager.
unsigned getSpellingLineNumber(bool *Invalid=nullptr) const
bool isUserProvided() const
True if this method is user-declared and was not deleted or defaulted on its first declaration.
Definition Decl.h:2410
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5251
bool insert(const FunctionEffectWithCondition &NewEC, Conflicts &Errs)
Definition Type.cpp:5665
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5283
Represents an abstract function effect, using just an enumeration describing its kind.
Definition TypeBase.h:4928
Kind
Identifies the particular effect.
Definition TypeBase.h:4931
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5115
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5315
Qualifiers getMethodQuals() const
Definition TypeBase.h:5741
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5719
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5604
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5600
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition TypeBase.h:5749
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:4622
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4734
CallingConv getCC() const
Definition TypeBase.h:4681
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4550
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4511
ExtInfo getExtInfo() const
Definition TypeBase.h:4867
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3646
AArch64SMETypeAttributes
The AArch64 SME ACLE (Arm C/C++ Language Extensions) define a number of function type attributes that...
Definition TypeBase.h:4787
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4820
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4816
CallingConv getCallConv() const
Definition TypeBase.h:4866
QualType getReturnType() const
Definition TypeBase.h:4851
bool getHasRegParm() const
Definition TypeBase.h:4853
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:5992
void setAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1614
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3625
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:6194
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:4366
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:3661
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3693
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5530
QualType getPointeeType() const
Definition TypeBase.h:3679
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:648
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:648
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:7950
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:8006
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8043
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:258
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:1790
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:8206
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:3336
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:8472
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8477
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1459
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1302
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:8388
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8428
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1444
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:8573
QualType getCanonicalType() const
Definition TypeBase.h:8440
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:8409
SplitQualType getSplitUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8489
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8509
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8434
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:3599
bool isSpelledAsLValue() const
Definition TypeBase.h:3594
bool isFunctionDeclarationScope() const
isFunctionDeclarationScope - Return true if this scope is a function prototype scope.
Definition Scope.h:493
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
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:212
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:1390
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7768
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:868
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:507
SmallVector< CodeSynthesisContext, 16 > CodeSynthesisContexts
List of active code synthesis contexts.
Definition Sema.h:13660
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1133
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:8295
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9382
UnaryTransformType::UTTKind UTTKind
Definition Sema.h:15476
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:1525
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:1465
@ AcceptSizeless
Relax the normal rules for complete types so that they include sizeless built-in types.
Definition Sema.h:15161
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:1300
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:225
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
SemaObjC & ObjC()
Definition Sema.h:1510
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:939
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:1693
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:83
@ UPPC_TypeConstraint
A type constraint.
Definition Sema.h:14537
const LangOptions & getLangOpts() const
Definition Sema.h:932
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:1299
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:1298
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2578
SemaHLSL & HLSL()
Definition Sema.h:1475
IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(const IdentifierInfo *ParamName, unsigned Index)
Invent a new identifier for parameters of abbreviated templates.
Definition Sema.cpp:139
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
SourceLocation ImplicitMSInheritanceAttrLoc
Source location for newly created implicit MSInheritanceAttrs.
Definition Sema.h:1827
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6545
std::vector< std::unique_ptr< TemplateInstantiationCallback > > TemplateInstCallbacks
The template instantiation callbacks to trace or track instantiations (objects can be chained).
Definition Sema.h:13707
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:15136
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1333
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:2315
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:643
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1438
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
SemaOpenCL & OpenCL()
Definition Sema.h:1520
QualType BuiltinDecay(QualType BaseType, SourceLocation Loc)
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:8228
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
bool isAcceptable(const NamedDecl *D, AcceptableKind Kind)
Determine whether a declaration is acceptable (visible/reachable).
Definition Sema.h:15588
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:14026
SourceManager & getSourceManager() const
Definition Sema.h:937
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:4130
@ NTCUK_Copy
Definition Sema.h:4131
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:13759
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15530
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:1576
ASTConsumer & Consumer
Definition Sema.h:1301
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:1303
DiagnosticsEngine & Diags
Definition Sema.h:1302
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:933
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:1822
llvm::BumpPtrAllocator BumpAlloc
Definition Sema.h:1245
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:625
QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, SourceLocation AttrLoc)
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2124
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:3717
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:3848
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3818
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4894
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:226
virtual bool hasBitIntType() const
Determine whether the _BitInt type is supported on this target.
Definition TargetInfo.h:689
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual size_t getMaxBitIntWidth() const
Definition TargetInfo.h:695
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:489
virtual bool allowHalfArgsAndReturns() const
Whether half args and returns are supported.
Definition TargetInfo.h:714
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition TargetInfo.h:678
virtual bool hasFloat16Type() const
Determine whether the _Float16 type is supported on this target.
Definition TargetInfo.h:720
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:732
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:717
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition TargetInfo.h:723
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, unsigned D, unsigned 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:3364
const Type * getTypeForDecl() const
Definition Decl.h:3538
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:887
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:8359
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:8370
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1839
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2491
bool isBlockPointerType() const
Definition TypeBase.h:8645
bool isVoidType() const
Definition TypeBase.h:8991
bool isBooleanType() const
Definition TypeBase.h:9128
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2721
bool isIncompleteArrayType() const
Definition TypeBase.h:8732
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2137
bool isUndeducedAutoType() const
Definition TypeBase.h:8821
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:8724
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isPointerType() const
Definition TypeBase.h:8625
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9035
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9285
bool isReferenceType() const
Definition TypeBase.h:8649
NestedNameSpecifier getPrefix() const
If this type represents a qualified-id, this returns its nested name specifier.
Definition Type.cpp:1941
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2651
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:472
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:753
bool canHaveNullability(bool ResultIfUnknown=true) const
Determine whether the given type can have a nullability specifier applied to it, i....
Definition Type.cpp:5107
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2690
bool isImageType() const
Definition TypeBase.h:8889
bool isPipeType() const
Definition TypeBase.h:8896
bool isBitIntType() const
Definition TypeBase.h:8900
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8748
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2790
bool isChar16Type() const
Definition Type.cpp:2179
bool isHalfType() const
Definition TypeBase.h:8995
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2411
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2601
bool isMemberPointerType() const
Definition TypeBase.h:8706
bool isAtomicType() const
Definition TypeBase.h:8817
bool isObjCObjectType() const
Definition TypeBase.h:8808
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9134
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2479
bool isFunctionType() const
Definition TypeBase.h:8621
bool isObjCObjectPointerType() const
Definition TypeBase.h:8804
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2703
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2357
bool isAnyPointerType() const
Definition TypeBase.h:8633
TypeClass getTypeClass() const
Definition TypeBase.h:2391
bool isSamplerT() const
Definition TypeBase.h:8869
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9218
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:654
bool isObjCARCImplicitlyUnretainedType() const
Determines if this type, which must satisfy isObjCLifetimeType(), is implicitly __unsafe_unretained r...
Definition Type.cpp:5333
bool isRecordType() const
Definition TypeBase.h:8752
bool isObjCRetainableType() const
Definition Type.cpp:5364
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5094
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3667
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3562
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:1069
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1242
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1115
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3402
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:926
@ Definition
This declaration is definitely a definition.
Definition Decl.h:1301
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2045
Represents a GCC generic vector type.
Definition TypeBase.h:4183
VectorKind getVectorKind() const
Definition TypeBase.h:4203
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.
llvm::json::Array Array
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:94
@ TST_auto
Definition Specifiers.h:92
@ TST_unspecified
Definition Specifiers.h:56
@ TST_typename
Definition Specifiers.h:84
@ TST_decltype_auto
Definition Specifiers.h:93
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:212
@ 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:1806
@ DecltypeAuto
decltype(auto)
Definition TypeBase.h:1803
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:61
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:348
@ Nullable
Values of this type can be null.
Definition Specifiers.h:352
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:357
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:350
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1788
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1791
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1794
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:1029
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1027
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1025
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:1021
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:1019
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1017
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1011
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:1023
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1013
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:1015
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:1871
@ 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:3727
@ SwiftAsyncContext
This parameter (which must have pointer type) uses the special Swift asynchronous context-pointer ABI...
Definition Specifiers.h:399
@ SwiftErrorResult
This parameter (which must have pointer-to-pointer type) uses the special Swift error-result ABI trea...
Definition Specifiers.h:389
@ Ordinary
This parameter uses ordinary ABI rules for its type.
Definition Specifiers.h:380
@ SwiftIndirectResult
This parameter (which must have pointer type) is a Swift indirect result parameter.
Definition Specifiers.h:384
@ SwiftContext
This parameter (which must have pointer type) uses the special Swift context-pointer ABI treatment.
Definition Specifiers.h:394
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition Specifiers.h:319
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
static bool isBlockPointer(Expr *Arg)
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:5939
@ Interface
The "__interface" keyword.
Definition TypeBase.h:5944
@ Struct
The "struct" keyword.
Definition TypeBase.h:5941
@ Class
The "class" keyword.
Definition TypeBase.h:5950
@ Union
The "union" keyword.
Definition TypeBase.h:5947
@ Enum
The "enum" keyword.
Definition TypeBase.h:5953
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
MSInheritanceModel
Assigned inheritance model for a class in the MS C++ ABI.
Definition Specifiers.h:410
@ 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:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
@ CC_Swift
Definition Specifiers.h:293
@ CC_DeviceKernel
Definition Specifiers.h:292
@ CC_SwiftAsync
Definition Specifiers.h:294
@ CC_X86StdCall
Definition Specifiers.h:280
@ CC_X86FastCall
Definition Specifiers.h:281
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4153
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4162
@ AltiVecVector
is AltiVec vector
Definition TypeBase.h:4147
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4150
@ Neon
is ARM Neon vector
Definition TypeBase.h:4156
@ Generic
not a target-specific vector type
Definition TypeBase.h:4144
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4168
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4171
@ NeonPoly
is ARM Neon polynomial vector
Definition TypeBase.h:4159
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4165
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
@ None
The alignment was not explicit in code.
Definition ASTContext.h:179
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:844
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:5914
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2246
@ 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
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:1329
unsigned TypeQuals
The type qualifiers for the array: const/volatile/restrict/__unaligned/_Atomic.
Definition DeclSpec.h:1321
unsigned hasStatic
True if this dimension included the 'static' keyword.
Definition DeclSpec.h:1325
Expr * NumElts
This is the size of the array, or null if [] or [*] was specified.
Definition DeclSpec.h:1334
unsigned TypeQuals
For now, sema will catch these as invalid.
Definition DeclSpec.h:1618
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with ',...)',...
Definition DeclSpec.h:1381
SourceLocation getTrailingReturnTypeLoc() const
Get the trailing-return-type location for this function declarator.
Definition DeclSpec.h:1608
SourceLocation getLParenLoc() const
Definition DeclSpec.h:1523
bool hasTrailingReturnType() const
Determine whether this function declarator had a trailing-return-type.
Definition DeclSpec.h:1599
TypeAndRange * Exceptions
Pointer to a new[]'d array of TypeAndRange objects that contain the types in the function's dynamic e...
Definition DeclSpec.h:1453
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1441
ParsedType getTrailingReturnType() const
Get the trailing-return-type for this function declarator.
Definition DeclSpec.h:1602
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition DeclSpec.h:1390
SourceLocation getExceptionSpecLocBeg() const
Definition DeclSpec.h:1529
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition DeclSpec.h:1444
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition DeclSpec.h:1542
SourceLocation getRParenLoc() const
Definition DeclSpec.h:1527
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:1525
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1416
unsigned getNumExceptions() const
Get the number of dynamic exception specifications.
Definition DeclSpec.h:1585
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition DeclSpec.h:1574
unsigned isAmbiguous
Can this declaration be a constructor-style initializer?
Definition DeclSpec.h:1385
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition DeclSpec.h:1375
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition DeclSpec.h:1567
SourceRange getExceptionSpecRange() const
Definition DeclSpec.h:1537
ExceptionSpecificationType getExceptionSpecType() const
Get the type of exception specification this function has.
Definition DeclSpec.h:1580
Expr * NoexceptExpr
Pointer to the expression in the noexcept-specifier of this function, if it has one.
Definition DeclSpec.h:1457
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
Definition DeclSpec.h:1627
SourceLocation StarLoc
Location of the '*' token.
Definition DeclSpec.h:1629
const IdentifierInfo * Ident
Definition DeclSpec.h:1347
SourceLocation OverflowBehaviorLoc
The location of an __ob_wrap or __ob_trap qualifier, if any.
Definition DeclSpec.h:1297
SourceLocation RestrictQualLoc
The location of the restrict-qualifier, if any.
Definition DeclSpec.h:1288
SourceLocation ConstQualLoc
The location of the const-qualifier, if any.
Definition DeclSpec.h:1282
SourceLocation VolatileQualLoc
The location of the volatile-qualifier, if any.
Definition DeclSpec.h:1285
SourceLocation UnalignedQualLoc
The location of the __unaligned-qualifier, if any.
Definition DeclSpec.h:1294
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/unaligned/atomic.
Definition DeclSpec.h:1279
SourceLocation AtomicQualLoc
The location of the _Atomic-qualifier, if any.
Definition DeclSpec.h:1291
unsigned OverflowBehaviorIsWrap
Whether the overflow behavior qualifier is wrap (true) or trap (false).
Definition DeclSpec.h:1302
bool LValueRef
True if this is an lvalue reference, false if it's an rvalue reference.
Definition DeclSpec.h:1312
bool HasRestrict
The type qualifier: restrict. [GNU] C++ extension.
Definition DeclSpec.h:1310
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1256
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition DeclSpec.h:1676
SourceLocation EndLoc
EndLoc - If valid, the place where this chunck ends.
Definition DeclSpec.h:1266
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:1653
BlockPointerTypeInfo Cls
Definition DeclSpec.h:1656
MemberPointerTypeInfo Mem
Definition DeclSpec.h:1657
ArrayTypeInfo Arr
Definition DeclSpec.h:1654
SourceLocation Loc
Loc - The place where this type was defined.
Definition DeclSpec.h:1264
FunctionTypeInfo Fun
Definition DeclSpec.h:1655
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
PointerTypeInfo Ptr
Definition DeclSpec.h:1652
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:5052
Holds information about the various types of exception specification.
Definition TypeBase.h:5372
Extra information about a function prototype.
Definition TypeBase.h:5400
FunctionTypeExtraAttributeInfo ExtraAttributeInfo
Definition TypeBase.h:5408
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5405
void setArmSMEAttribute(AArch64SMETypeAttributes Kind, bool Enable=true)
Definition TypeBase.h:5454
StringRef CFISalt
A CFI "salt" that differentiates functions with the same prototype.
Definition TypeBase.h:4777
SmallVector< NamedDecl *, 4 > TemplateParams
Store the list of the template parameters for a generic lambda or an abbreviated function template.
Definition DeclSpec.h:2917
unsigned AutoTemplateParameterDepth
If this is a generic lambda or abbreviated function template, use this as the depth of each 'auto' pa...
Definition DeclSpec.h:2908
static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
Definition Type.cpp:3290
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:13165
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ Memoization
Added for Template instantiation observation.
Definition Sema.h:13269
Abstract class used to diagnose incomplete types.
Definition Sema.h:8309
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:8381
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.