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