clang 24.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"
44#include "llvm/ADT/ArrayRef.h"
45#include "llvm/ADT/STLForwardCompat.h"
46#include "llvm/ADT/StringExtras.h"
47#include "llvm/IR/DerivedTypes.h"
48#include "llvm/Support/ErrorHandling.h"
49#include <bitset>
50#include <optional>
51
52using namespace clang;
53
59
60/// isOmittedBlockReturnType - Return true if this declarator is missing a
61/// return type because this is a omitted return type on a block literal.
62static bool isOmittedBlockReturnType(const Declarator &D) {
65 return false;
66
67 if (D.getNumTypeObjects() == 0)
68 return true; // ^{ ... }
69
70 if (D.getNumTypeObjects() == 1 &&
72 return true; // ^(int X, float Y) { ... }
73
74 return false;
75}
76
77/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
78/// doesn't apply to the given type.
80 QualType type) {
81 TypeDiagSelector WhichType;
82 bool useExpansionLoc = true;
83 switch (attr.getKind()) {
84 case ParsedAttr::AT_ObjCGC:
85 WhichType = TDS_Pointer;
86 break;
87 case ParsedAttr::AT_ObjCOwnership:
88 WhichType = TDS_ObjCObjOrBlock;
89 break;
90 default:
91 // Assume everything else was a function attribute.
92 WhichType = TDS_Function;
93 useExpansionLoc = false;
94 break;
95 }
96
97 SourceLocation loc = attr.getLoc();
98 StringRef name = attr.getAttrName()->getName();
99
100 // The GC attributes are usually written with macros; special-case them.
101 IdentifierInfo *II =
102 attr.isArgIdent(0) ? attr.getArgAsIdent(0)->getIdentifierInfo() : nullptr;
103 if (useExpansionLoc && loc.isMacroID() && II) {
104 if (II->isStr("strong")) {
105 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
106 } else if (II->isStr("weak")) {
107 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
108 }
109 }
110
111 S.Diag(loc, attr.isRegularKeywordAttribute()
112 ? diag::err_type_attribute_wrong_type
113 : diag::warn_type_attribute_wrong_type)
114 << name << WhichType << type;
115}
116
117// objc_gc applies to Objective-C pointers or, otherwise, to the
118// smallest available pointer type (i.e. 'void*' in 'void**').
119#define OBJC_POINTER_TYPE_ATTRS_CASELIST \
120 case ParsedAttr::AT_ObjCGC: \
121 case ParsedAttr::AT_ObjCOwnership
122
123// Calling convention attributes.
124#define CALLING_CONV_ATTRS_CASELIST \
125 case ParsedAttr::AT_CDecl: \
126 case ParsedAttr::AT_FastCall: \
127 case ParsedAttr::AT_StdCall: \
128 case ParsedAttr::AT_ThisCall: \
129 case ParsedAttr::AT_RegCall: \
130 case ParsedAttr::AT_Pascal: \
131 case ParsedAttr::AT_SwiftCall: \
132 case ParsedAttr::AT_SwiftAsyncCall: \
133 case ParsedAttr::AT_VectorCall: \
134 case ParsedAttr::AT_AArch64VectorPcs: \
135 case ParsedAttr::AT_AArch64SVEPcs: \
136 case ParsedAttr::AT_MSABI: \
137 case ParsedAttr::AT_SysVABI: \
138 case ParsedAttr::AT_Pcs: \
139 case ParsedAttr::AT_IntelOclBicc: \
140 case ParsedAttr::AT_PreserveMost: \
141 case ParsedAttr::AT_PreserveAll: \
142 case ParsedAttr::AT_M68kRTD: \
143 case ParsedAttr::AT_PreserveNone: \
144 case ParsedAttr::AT_RISCVVectorCC: \
145 case ParsedAttr::AT_RISCVVLSCC
146
147// Function type attributes.
148#define FUNCTION_TYPE_ATTRS_CASELIST \
149 case ParsedAttr::AT_NSReturnsRetained: \
150 case ParsedAttr::AT_NoReturn: \
151 case ParsedAttr::AT_NonBlocking: \
152 case ParsedAttr::AT_NonAllocating: \
153 case ParsedAttr::AT_Blocking: \
154 case ParsedAttr::AT_Allocating: \
155 case ParsedAttr::AT_Regparm: \
156 case ParsedAttr::AT_CFIUncheckedCallee: \
157 case ParsedAttr::AT_CFISalt: \
158 case ParsedAttr::AT_CmseNSCall: \
159 case ParsedAttr::AT_ArmStreaming: \
160 case ParsedAttr::AT_ArmStreamingCompatible: \
161 case ParsedAttr::AT_ArmPreserves: \
162 case ParsedAttr::AT_ArmIn: \
163 case ParsedAttr::AT_ArmOut: \
164 case ParsedAttr::AT_ArmInOut: \
165 case ParsedAttr::AT_ArmAgnostic: \
166 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
167 case ParsedAttr::AT_AnyX86NoCfCheck: \
168 CALLING_CONV_ATTRS_CASELIST
169
170// Microsoft-specific type qualifiers.
171#define MS_TYPE_ATTRS_CASELIST \
172 case ParsedAttr::AT_Ptr32: \
173 case ParsedAttr::AT_Ptr64: \
174 case ParsedAttr::AT_SPtr: \
175 case ParsedAttr::AT_UPtr
176
177// Nullability qualifiers.
178#define NULLABILITY_TYPE_ATTRS_CASELIST \
179 case ParsedAttr::AT_TypeNonNull: \
180 case ParsedAttr::AT_TypeNullable: \
181 case ParsedAttr::AT_TypeNullableResult: \
182 case ParsedAttr::AT_TypeNullUnspecified
183
184namespace {
185 /// An object which stores processing state for the entire
186 /// GetTypeForDeclarator process.
187 class TypeProcessingState {
188 Sema &sema;
189
190 /// The declarator being processed.
191 Declarator &declarator;
192
193 /// The index of the declarator chunk we're currently processing.
194 /// May be the total number of valid chunks, indicating the
195 /// DeclSpec.
196 unsigned chunkIndex;
197
198 /// The original set of attributes on the DeclSpec.
200
201 /// A list of attributes to diagnose the uselessness of when the
202 /// processing is complete.
203 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
204
205 /// Attributes corresponding to AttributedTypeLocs that we have not yet
206 /// populated.
207 // FIXME: The two-phase mechanism by which we construct Types and fill
208 // their TypeLocs makes it hard to correctly assign these. We keep the
209 // attributes in creation order as an attempt to make them line up
210 // properly.
211 using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
212 SmallVector<TypeAttrPair, 8> AttrsForTypes;
213 bool AttrsForTypesSorted = true;
214
215 /// MacroQualifiedTypes mapping to macro expansion locations that will be
216 /// stored in a MacroQualifiedTypeLoc.
217 llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
218
219 /// Flag to indicate we parsed a noderef attribute. This is used for
220 /// validating that noderef was used on a pointer or array.
221 bool parsedNoDeref;
222
223 // Flag to indicate that we already parsed a HLSL parameter modifier
224 // attribute. This prevents double-mutating the type.
225 bool ParsedHLSLParamMod;
226
227 public:
228 TypeProcessingState(Sema &sema, Declarator &declarator)
229 : sema(sema), declarator(declarator),
230 chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false),
231 ParsedHLSLParamMod(false) {}
232
233 Sema &getSema() const {
234 return sema;
235 }
236
237 Declarator &getDeclarator() const {
238 return declarator;
239 }
240
241 bool isProcessingDeclSpec() const {
242 return chunkIndex == declarator.getNumTypeObjects();
243 }
244
245 unsigned getCurrentChunkIndex() const {
246 return chunkIndex;
247 }
248
249 void setCurrentChunkIndex(unsigned idx) {
250 assert(idx <= declarator.getNumTypeObjects());
251 chunkIndex = idx;
252 }
253
254 ParsedAttributesView &getCurrentAttributes() const {
255 if (isProcessingDeclSpec())
256 return getMutableDeclSpec().getAttributes();
257 return declarator.getTypeObject(chunkIndex).getAttrs();
258 }
259
260 /// Save the current set of attributes on the DeclSpec.
261 void saveDeclSpecAttrs() {
262 // Don't try to save them multiple times.
263 if (!savedAttrs.empty())
264 return;
265
266 DeclSpec &spec = getMutableDeclSpec();
267 llvm::append_range(savedAttrs,
268 llvm::make_pointer_range(spec.getAttributes()));
269 }
270
271 /// Record that we had nowhere to put the given type attribute.
272 /// We will diagnose such attributes later.
273 void addIgnoredTypeAttr(ParsedAttr &attr) {
274 ignoredTypeAttrs.push_back(&attr);
275 }
276
277 /// Diagnose all the ignored type attributes, given that the
278 /// declarator worked out to the given type.
279 void diagnoseIgnoredTypeAttrs(QualType type) const {
280 for (auto *Attr : ignoredTypeAttrs)
281 diagnoseBadTypeAttribute(getSema(), *Attr, type);
282 }
283
284 /// Get an attributed type for the given attribute, and remember the Attr
285 /// object so that we can attach it to the AttributedTypeLoc.
286 QualType getAttributedType(Attr *A, QualType ModifiedType,
287 QualType EquivType) {
288 QualType T =
289 sema.Context.getAttributedType(A, ModifiedType, EquivType);
290 AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
291 AttrsForTypesSorted = false;
292 return T;
293 }
294
295 /// Get a BTFTagAttributed type for the btf_type_tag attribute.
296 QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
297 QualType WrappedType) {
298 return sema.Context.getBTFTagAttributedType(BTFAttr, WrappedType);
299 }
300
301 /// Get a OverflowBehaviorType type for the overflow_behavior type
302 /// attribute.
304 getOverflowBehaviorType(OverflowBehaviorType::OverflowBehaviorKind Kind,
305 QualType UnderlyingType) {
306 return sema.Context.getOverflowBehaviorType(Kind, UnderlyingType);
307 }
308
309 /// Completely replace the \c auto in \p TypeWithAuto by
310 /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
311 /// necessary.
312 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
313 QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
314 if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
315 // Attributed type still should be an attributed type after replacement.
316 auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
317 for (TypeAttrPair &A : AttrsForTypes) {
318 if (A.first == AttrTy)
319 A.first = NewAttrTy;
320 }
321 AttrsForTypesSorted = false;
322 }
323 return T;
324 }
325
326 /// Extract and remove the Attr* for a given attributed type.
327 const Attr *takeAttrForAttributedType(const AttributedType *AT) {
328 if (!AttrsForTypesSorted) {
329 llvm::stable_sort(AttrsForTypes, llvm::less_first());
330 AttrsForTypesSorted = true;
331 }
332
333 // FIXME: This is quadratic if we have lots of reuses of the same
334 // attributed type.
335 for (auto It = llvm::partition_point(
336 AttrsForTypes,
337 [=](const TypeAttrPair &A) { return A.first < AT; });
338 It != AttrsForTypes.end() && It->first == AT; ++It) {
339 if (It->second) {
340 const Attr *Result = It->second;
341 It->second = nullptr;
342 return Result;
343 }
344 }
345
346 llvm_unreachable("no Attr* for AttributedType*");
347 }
348
350 getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
351 auto FoundLoc = LocsForMacros.find(MQT);
352 assert(FoundLoc != LocsForMacros.end() &&
353 "Unable to find macro expansion location for MacroQualifedType");
354 return FoundLoc->second;
355 }
356
357 void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
358 SourceLocation Loc) {
359 LocsForMacros[MQT] = Loc;
360 }
361
362 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
363
364 bool didParseNoDeref() const { return parsedNoDeref; }
365
366 void setParsedHLSLParamMod(bool Parsed) { ParsedHLSLParamMod = Parsed; }
367
368 bool didParseHLSLParamMod() const { return ParsedHLSLParamMod; }
369
370 ~TypeProcessingState() {
371 if (savedAttrs.empty())
372 return;
373
374 getMutableDeclSpec().getAttributes().clearListOnly();
375 for (ParsedAttr *AL : savedAttrs)
376 getMutableDeclSpec().getAttributes().addAtEnd(AL);
377 }
378
379 private:
380 DeclSpec &getMutableDeclSpec() const {
381 return const_cast<DeclSpec&>(declarator.getDeclSpec());
382 }
383 };
384} // end anonymous namespace
385
387 ParsedAttributesView &fromList,
388 ParsedAttributesView &toList) {
389 fromList.remove(&attr);
390 toList.addAtEnd(&attr);
391}
392
393/// The location of a type attribute.
395 /// The attribute is in the decl-specifier-seq.
397 /// The attribute is part of a DeclaratorChunk.
399 /// The attribute is immediately after the declaration's name.
401};
402
403static void
404processTypeAttrs(TypeProcessingState &state, QualType &type,
405 TypeAttrLocation TAL, const ParsedAttributesView &attrs,
407
408static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
410
411static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
413
414static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
415 QualType &type);
416
417static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
419
420static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
422 if (attr.getKind() == ParsedAttr::AT_ObjCGC)
423 return handleObjCGCTypeAttr(state, attr, type);
424 assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
425 return handleObjCOwnershipTypeAttr(state, attr, type);
426}
427
428/// Given the index of a declarator chunk, check whether that chunk
429/// directly specifies the return type of a function and, if so, find
430/// an appropriate place for it.
431///
432/// \param i - a notional index which the search will start
433/// immediately inside
434///
435/// \param onlyBlockPointers Whether we should only look into block
436/// pointer types (vs. all pointer types).
438 unsigned i,
439 bool onlyBlockPointers) {
440 assert(i <= declarator.getNumTypeObjects());
441
442 DeclaratorChunk *result = nullptr;
443
444 // First, look inwards past parens for a function declarator.
445 for (; i != 0; --i) {
446 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
447 switch (fnChunk.Kind) {
449 continue;
450
451 // If we find anything except a function, bail out.
458 return result;
459
460 // If we do find a function declarator, scan inwards from that,
461 // looking for a (block-)pointer declarator.
463 for (--i; i != 0; --i) {
464 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
465 switch (ptrChunk.Kind) {
471 continue;
472
475 if (onlyBlockPointers)
476 continue;
477
478 [[fallthrough]];
479
481 result = &ptrChunk;
482 goto continue_outer;
483 }
484 llvm_unreachable("bad declarator chunk kind");
485 }
486
487 // If we run out of declarators doing that, we're done.
488 return result;
489 }
490 llvm_unreachable("bad declarator chunk kind");
491
492 // Okay, reconsider from our new point.
493 continue_outer: ;
494 }
495
496 // Ran out of chunks, bail out.
497 return result;
498}
499
500/// Given that an objc_gc attribute was written somewhere on a
501/// declaration *other* than on the declarator itself (for which, use
502/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
503/// didn't apply in whatever position it was written in, try to move
504/// it to a more appropriate position.
505static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
507 Declarator &declarator = state.getDeclarator();
508
509 // Move it to the outermost normal or block pointer declarator.
510 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
511 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
512 switch (chunk.Kind) {
515 // But don't move an ARC ownership attribute to the return type
516 // of a block.
517 DeclaratorChunk *destChunk = nullptr;
518 if (state.isProcessingDeclSpec() &&
519 attr.getKind() == ParsedAttr::AT_ObjCOwnership)
520 destChunk = maybeMovePastReturnType(declarator, i - 1,
521 /*onlyBlockPointers=*/true);
522 if (!destChunk) destChunk = &chunk;
523
524 moveAttrFromListToList(attr, state.getCurrentAttributes(),
525 destChunk->getAttrs());
526 return;
527 }
528
531 continue;
532
533 // We may be starting at the return type of a block.
535 if (state.isProcessingDeclSpec() &&
536 attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
538 declarator, i,
539 /*onlyBlockPointers=*/true)) {
540 moveAttrFromListToList(attr, state.getCurrentAttributes(),
541 dest->getAttrs());
542 return;
543 }
544 }
545 goto error;
546
547 // Don't walk through these.
551 goto error;
552 }
553 }
554 error:
555
556 diagnoseBadTypeAttribute(state.getSema(), attr, type);
557}
558
559/// Distribute an objc_gc type attribute that was written on the
560/// declarator.
562 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
563 Declarator &declarator = state.getDeclarator();
564
565 // objc_gc goes on the innermost pointer to something that's not a
566 // pointer.
567 unsigned innermost = -1U;
568 bool considerDeclSpec = true;
569 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
570 DeclaratorChunk &chunk = declarator.getTypeObject(i);
571 switch (chunk.Kind) {
574 innermost = i;
575 continue;
576
582 continue;
583
585 considerDeclSpec = false;
586 goto done;
587 }
588 }
589 done:
590
591 // That might actually be the decl spec if we weren't blocked by
592 // anything in the declarator.
593 if (considerDeclSpec) {
594 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
595 // Splice the attribute into the decl spec. Prevents the
596 // attribute from being applied multiple times and gives
597 // the source-location-filler something to work with.
598 state.saveDeclSpecAttrs();
600 declarator.getAttributes(), &attr);
601 return;
602 }
603 }
604
605 // Otherwise, if we found an appropriate chunk, splice the attribute
606 // into it.
607 if (innermost != -1U) {
609 declarator.getTypeObject(innermost).getAttrs());
610 return;
611 }
612
613 // Otherwise, diagnose when we're done building the type.
614 declarator.getAttributes().remove(&attr);
615 state.addIgnoredTypeAttr(attr);
616}
617
618/// A function type attribute was written somewhere in a declaration
619/// *other* than on the declarator itself or in the decl spec. Given
620/// that it didn't apply in whatever position it was written in, try
621/// to move it to a more appropriate position.
622static void distributeFunctionTypeAttr(TypeProcessingState &state,
624 Declarator &declarator = state.getDeclarator();
625
626 // Try to push the attribute from the return type of a function to
627 // the function itself.
628 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
629 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
630 switch (chunk.Kind) {
632 moveAttrFromListToList(attr, state.getCurrentAttributes(),
633 chunk.getAttrs());
634 return;
635
643 continue;
644 }
645 }
646
647 diagnoseBadTypeAttribute(state.getSema(), attr, type);
648}
649
650/// Try to distribute a function type attribute to the innermost
651/// function chunk or type. Returns true if the attribute was
652/// distributed, false if no location was found.
654 TypeProcessingState &state, ParsedAttr &attr,
655 ParsedAttributesView &attrList, QualType &declSpecType,
656 CUDAFunctionTarget CFT) {
657 Declarator &declarator = state.getDeclarator();
658
659 // Put it on the innermost function chunk, if there is one.
660 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
661 DeclaratorChunk &chunk = declarator.getTypeObject(i);
662 if (chunk.Kind != DeclaratorChunk::Function) continue;
663
664 moveAttrFromListToList(attr, attrList, chunk.getAttrs());
665 return true;
666 }
667
668 return handleFunctionTypeAttr(state, attr, declSpecType, CFT);
669}
670
671/// A function type attribute was written in the decl spec. Try to
672/// apply it somewhere.
673static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
675 QualType &declSpecType,
676 CUDAFunctionTarget CFT) {
677 state.saveDeclSpecAttrs();
678
679 // Try to distribute to the innermost.
681 state, attr, state.getCurrentAttributes(), declSpecType, CFT))
682 return;
683
684 // If that failed, diagnose the bad attribute when the declarator is
685 // fully built.
686 state.addIgnoredTypeAttr(attr);
687}
688
689/// A function type attribute was written on the declarator or declaration.
690/// Try to apply it somewhere.
691/// `Attrs` is the attribute list containing the declaration (either of the
692/// declarator or the declaration).
693static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
695 QualType &declSpecType,
696 CUDAFunctionTarget CFT) {
697 Declarator &declarator = state.getDeclarator();
698
699 // Try to distribute to the innermost.
701 state, attr, declarator.getAttributes(), declSpecType, CFT))
702 return;
703
704 // If that failed, diagnose the bad attribute when the declarator is
705 // fully built.
706 declarator.getAttributes().remove(&attr);
707 state.addIgnoredTypeAttr(attr);
708}
709
710/// Given that there are attributes written on the declarator or declaration
711/// itself, try to distribute any type attributes to the appropriate
712/// declarator chunk.
713///
714/// These are attributes like the following:
715/// int f ATTR;
716/// int (f ATTR)();
717/// but not necessarily this:
718/// int f() ATTR;
719///
720/// `Attrs` is the attribute list containing the declaration (either of the
721/// declarator or the declaration).
722static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
723 QualType &declSpecType,
724 CUDAFunctionTarget CFT) {
725 // The called functions in this loop actually remove things from the current
726 // list, so iterating over the existing list isn't possible. Instead, make a
727 // non-owning copy and iterate over that.
728 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
729 for (ParsedAttr &attr : AttrsCopy) {
730 // Do not distribute [[]] attributes. They have strict rules for what
731 // they appertain to.
732 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute())
733 continue;
734
735 switch (attr.getKind()) {
738 break;
739
741 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType, CFT);
742 break;
743
745 // Microsoft type attributes cannot go after the declarator-id.
746 continue;
747
749 // Nullability specifiers cannot go after the declarator-id.
750
751 // Objective-C __kindof does not get distributed.
752 case ParsedAttr::AT_ObjCKindOf:
753 continue;
754
755 default:
756 break;
757 }
758 }
759}
760
761/// Add a synthetic '()' to a block-literal declarator if it is
762/// required, given the return type.
763static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
764 QualType declSpecType) {
765 Declarator &declarator = state.getDeclarator();
766
767 // First, check whether the declarator would produce a function,
768 // i.e. whether the innermost semantic chunk is a function.
769 if (declarator.isFunctionDeclarator()) {
770 // If so, make that declarator a prototyped declarator.
771 declarator.getFunctionTypeInfo().hasPrototype = true;
772 return;
773 }
774
775 // If there are any type objects, the type as written won't name a
776 // function, regardless of the decl spec type. This is because a
777 // block signature declarator is always an abstract-declarator, and
778 // abstract-declarators can't just be parentheses chunks. Therefore
779 // we need to build a function chunk unless there are no type
780 // objects and the decl spec type is a function.
781 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
782 return;
783
784 // Note that there *are* cases with invalid declarators where
785 // declarators consist solely of parentheses. In general, these
786 // occur only in failed efforts to make function declarators, so
787 // faking up the function chunk is still the right thing to do.
788
789 // Otherwise, we need to fake up a function declarator.
790 SourceLocation loc = declarator.getBeginLoc();
791
792 // ...and *prepend* it to the declarator.
793 SourceLocation NoLoc;
795 /*HasProto=*/true,
796 /*IsAmbiguous=*/false,
797 /*LParenLoc=*/NoLoc,
798 /*ArgInfo=*/nullptr,
799 /*NumParams=*/0,
800 /*EllipsisLoc=*/NoLoc,
801 /*RParenLoc=*/NoLoc,
802 /*RefQualifierIsLvalueRef=*/true,
803 /*RefQualifierLoc=*/NoLoc,
804 /*MutableLoc=*/NoLoc, EST_None,
805 /*ESpecRange=*/SourceRange(),
806 /*Exceptions=*/nullptr,
807 /*ExceptionRanges=*/nullptr,
808 /*NumExceptions=*/0,
809 /*NoexceptExpr=*/nullptr,
810 /*ExceptionSpecTokens=*/nullptr,
811 /*DeclsInPrototype=*/{}, loc, loc, declarator));
812
813 // For consistency, make sure the state still has us as processing
814 // the decl spec.
815 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
816 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
817}
818
820 unsigned &TypeQuals,
821 QualType TypeSoFar,
822 unsigned RemoveTQs,
823 unsigned DiagID) {
824 // If this occurs outside a template instantiation, warn the user about
825 // it; they probably didn't mean to specify a redundant qualifier.
826 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
827 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
830 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
831 if (!(RemoveTQs & Qual.first))
832 continue;
833
834 if (!S.inTemplateInstantiation()) {
835 if (TypeQuals & Qual.first)
836 S.Diag(Qual.second, DiagID)
837 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
838 << FixItHint::CreateRemoval(Qual.second);
839 }
840
841 TypeQuals &= ~Qual.first;
842 }
843}
844
845/// Return true if this is omitted block return type. Also check type
846/// attributes and type qualifiers when returning true.
847static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
849 if (!isOmittedBlockReturnType(declarator))
850 return false;
851
852 // Warn if we see type attributes for omitted return type on a block literal.
854 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
855 if (AL.isInvalid() || !AL.isTypeAttr())
856 continue;
857 S.Diag(AL.getLoc(),
858 diag::warn_block_literal_attributes_on_omitted_return_type)
859 << AL;
860 ToBeRemoved.push_back(&AL);
861 }
862 // Remove bad attributes from the list.
863 for (ParsedAttr *AL : ToBeRemoved)
864 declarator.getMutableDeclSpec().getAttributes().remove(AL);
865
866 // Warn if we see type qualifiers for omitted return type on a block literal.
867 const DeclSpec &DS = declarator.getDeclSpec();
868 unsigned TypeQuals = DS.getTypeQualifiers();
869 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
870 diag::warn_block_literal_qualifiers_on_omitted_return_type);
872
873 return true;
874}
875
876static OpenCLAccessAttr::Spelling
878 for (const ParsedAttr &AL : Attrs)
879 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
880 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
881 return OpenCLAccessAttr::Keyword_read_only;
882}
883
884static UnaryTransformType::UTTKind
886 switch (SwitchTST) {
887#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
888 case TST_##Trait: \
889 return UnaryTransformType::Enum;
890#include "clang/Basic/BuiltinTraits.inc"
891 default:
892 llvm_unreachable("attempted to parse a non-unary transform builtin");
893 }
894}
895
896/// Convert the specified declspec to the appropriate type
897/// object.
898/// \param state Specifies the declarator containing the declaration specifier
899/// to be converted, along with other associated processing state.
900/// \returns The type described by the declaration specifiers. This function
901/// never returns null.
902static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
903 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
904 // checking.
905
906 Sema &S = state.getSema();
907 Declarator &declarator = state.getDeclarator();
908 DeclSpec &DS = declarator.getMutableDeclSpec();
909 SourceLocation DeclLoc = declarator.getIdentifierLoc();
910 if (DeclLoc.isInvalid())
911 DeclLoc = DS.getBeginLoc();
912
913 ASTContext &Context = S.Context;
914
916 switch (DS.getTypeSpecType()) {
918 Result = Context.VoidTy;
919 break;
922 Result = Context.CharTy;
924 Result = Context.SignedCharTy;
925 else {
927 "Unknown TSS value");
928 Result = Context.UnsignedCharTy;
929 }
930 break;
933 Result = Context.WCharTy;
935 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
937 Context.getPrintingPolicy());
938 Result = Context.getSignedWCharType();
939 } else {
941 "Unknown TSS value");
942 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
944 Context.getPrintingPolicy());
945 Result = Context.getUnsignedWCharType();
946 }
947 break;
950 "Unknown TSS value");
951 Result = Context.Char8Ty;
952 break;
955 "Unknown TSS value");
956 Result = Context.Char16Ty;
957 break;
960 "Unknown TSS value");
961 Result = Context.Char32Ty;
962 break;
964 // If this is a missing declspec in a block literal return context, then it
965 // is inferred from the return statements inside the block.
966 // The declspec is always missing in a lambda expr context; it is either
967 // specified with a trailing return type or inferred.
968 if (S.getLangOpts().CPlusPlus14 &&
970 // In C++1y, a lambda's implicit return type is 'auto'.
971 Result = Context.getAutoDeductType();
972 break;
973 } else if (declarator.getContext() == DeclaratorContext::LambdaExpr ||
974 checkOmittedBlockReturnType(S, declarator,
975 Context.DependentTy)) {
976 Result = Context.DependentTy;
977 break;
978 }
979
980 // Unspecified typespec defaults to int in C90. However, the C90 grammar
981 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
982 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
983 // Note that the one exception to this is function definitions, which are
984 // allowed to be completely missing a declspec. This is handled in the
985 // parser already though by it pretending to have seen an 'int' in this
986 // case.
988 // Only emit the diagnostic for the first declarator in a DeclGroup, as
989 // the warning is always implied for all subsequent declarators, and the
990 // fix must only be applied exactly once as well.
991 if (declarator.isFirstDeclarator()) {
992 S.Diag(DeclLoc, diag::warn_missing_type_specifier)
993 << DS.getSourceRange()
995 }
996 } else if (!DS.hasTypeSpecifier()) {
997 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
998 // "At least one type specifier shall be given in the declaration
999 // specifiers in each declaration, and in the specifier-qualifier list
1000 // in each struct declaration and type name."
1001 if (!S.getLangOpts().isImplicitIntAllowed() && !DS.isTypeSpecPipe()) {
1002 if (declarator.isFirstDeclarator()) {
1003 S.Diag(DeclLoc, diag::err_missing_type_specifier)
1004 << DS.getSourceRange();
1005 }
1006
1007 // When this occurs, often something is very broken with the value
1008 // being declared, poison it as invalid so we don't get chains of
1009 // errors.
1010 declarator.setInvalidType(true);
1011 } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 &&
1012 DS.isTypeSpecPipe()) {
1013 if (declarator.isFirstDeclarator()) {
1014 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1015 << DS.getSourceRange();
1016 }
1017 declarator.setInvalidType(true);
1018 } else if (declarator.isFirstDeclarator()) {
1019 assert(S.getLangOpts().isImplicitIntAllowed() &&
1020 "implicit int is disabled?");
1021 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1022 << DS.getSourceRange()
1023 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int ");
1024 }
1025 }
1026
1027 [[fallthrough]];
1028 case DeclSpec::TST_int: {
1030 switch (DS.getTypeSpecWidth()) {
1032 Result = Context.IntTy;
1033 break;
1035 Result = Context.ShortTy;
1036 break;
1038 Result = Context.LongTy;
1039 break;
1041 Result = Context.LongLongTy;
1042
1043 if (S.getLangOpts().OpenCL) {
1044 // OpenCL v3.0 s6.3.4: 'long long' is a reserved data type.
1045 S.Diag(DS.getTypeSpecWidthLoc(), diag::warn_opencl_longlong);
1046 } else if (!S.getLangOpts().C99) {
1047 // 'long long' is a C99 or C++11 feature.
1048 if (S.getLangOpts().CPlusPlus)
1050 S.getLangOpts().CPlusPlus11 ?
1051 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1052 else
1053 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1054 }
1055 break;
1056 }
1057 } else {
1058 switch (DS.getTypeSpecWidth()) {
1060 Result = Context.UnsignedIntTy;
1061 break;
1063 Result = Context.UnsignedShortTy;
1064 break;
1066 Result = Context.UnsignedLongTy;
1067 break;
1069 Result = Context.UnsignedLongLongTy;
1070
1071 if (S.getLangOpts().OpenCL) {
1072 // OpenCL v3.0 s6.3.4: 'long long' is a reserved data type.
1073 S.Diag(DS.getTypeSpecWidthLoc(), diag::warn_opencl_longlong);
1074 } else if (!S.getLangOpts().C99) {
1075 // 'long long' is a C99 or C++11 feature.
1076 if (S.getLangOpts().CPlusPlus)
1078 S.getLangOpts().CPlusPlus11 ?
1079 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1080 else
1081 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1082 }
1083 break;
1084 }
1085 }
1086 break;
1087 }
1088 case DeclSpec::TST_bitint: {
1090 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_BitInt";
1091 Result =
1093 DS.getRepAsExpr(), DS.getBeginLoc());
1094 if (Result.isNull()) {
1095 Result = Context.IntTy;
1096 declarator.setInvalidType(true);
1097 }
1098 break;
1099 }
1100 case DeclSpec::TST_accum: {
1101 switch (DS.getTypeSpecWidth()) {
1103 Result = Context.ShortAccumTy;
1104 break;
1106 Result = Context.AccumTy;
1107 break;
1109 Result = Context.LongAccumTy;
1110 break;
1112 llvm_unreachable("Unable to specify long long as _Accum width");
1113 }
1114
1116 Result = Context.getCorrespondingUnsignedType(Result);
1117
1118 if (DS.isTypeSpecSat())
1119 Result = Context.getCorrespondingSaturatedType(Result);
1120
1121 break;
1122 }
1123 case DeclSpec::TST_fract: {
1124 switch (DS.getTypeSpecWidth()) {
1126 Result = Context.ShortFractTy;
1127 break;
1129 Result = Context.FractTy;
1130 break;
1132 Result = Context.LongFractTy;
1133 break;
1135 llvm_unreachable("Unable to specify long long as _Fract width");
1136 }
1137
1139 Result = Context.getCorrespondingUnsignedType(Result);
1140
1141 if (DS.isTypeSpecSat())
1142 Result = Context.getCorrespondingSaturatedType(Result);
1143
1144 break;
1145 }
1147 if (!S.Context.getTargetInfo().hasInt128Type() &&
1148 !(S.getLangOpts().isTargetDevice()))
1149 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1150 << "__int128";
1152 Result = Context.UnsignedInt128Ty;
1153 else
1154 Result = Context.Int128Ty;
1155 break;
1157 // CUDA host and device may have different _Float16 support, therefore
1158 // do not diagnose _Float16 usage to avoid false alarm.
1159 // ToDo: more precise diagnostics for CUDA.
1160 if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
1161 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1162 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1163 << "_Float16";
1164 Result = Context.Float16Ty;
1165 break;
1166 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1169 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice) &&
1170 !S.getLangOpts().SYCLIsDevice)
1171 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__bf16";
1172 Result = Context.BFloat16Ty;
1173 break;
1174 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1177 Result = Context.LongDoubleTy;
1178 else
1179 Result = Context.DoubleTy;
1180 if (S.getLangOpts().OpenCL) {
1181 if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts()))
1182 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1183 << 0 << Result
1184 << (S.getLangOpts().getOpenCLCompatibleVersion() >= 300
1185 ? "cl_khr_fp64 and __opencl_c_fp64"
1186 : "cl_khr_fp64");
1187 else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts()))
1188 S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma);
1189 }
1190 break;
1194 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1195 << "__float128";
1196 Result = Context.Float128Ty;
1197 break;
1199 if (!S.Context.getTargetInfo().hasIbm128Type() &&
1200 !S.getLangOpts().SYCLIsDevice &&
1201 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1202 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128";
1203 Result = Context.Ibm128Ty;
1204 break;
1205 case DeclSpec::TST_bool:
1206 Result = Context.BoolTy; // _Bool or bool
1207 break;
1208 case DeclSpec::TST_decimal32: // _Decimal32
1209 case DeclSpec::TST_decimal64: // _Decimal64
1210 case DeclSpec::TST_decimal128: // _Decimal128
1211 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1212 Result = Context.IntTy;
1213 declarator.setInvalidType(true);
1214 break;
1216 case DeclSpec::TST_enum:
1220 TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1221 if (!D) {
1222 // This can happen in C++ with ambiguous lookups.
1223 Result = Context.IntTy;
1224 declarator.setInvalidType(true);
1225 break;
1226 }
1227
1228 // If the type is deprecated or unavailable, diagnose it.
1230
1232 DS.getTypeSpecComplex() == 0 &&
1234 "No qualifiers on tag names!");
1235
1238 // TypeQuals handled by caller.
1239 Result = Context.getTagType(Keyword, DS.getTypeSpecScope().getScopeRep(), D,
1240 DS.isTypeSpecOwned());
1241 break;
1242 }
1245 DS.getTypeSpecComplex() == 0 &&
1247 "Can't handle qualifiers on typedef names yet!");
1249 if (Result.isNull()) {
1250 declarator.setInvalidType(true);
1251 }
1252
1253 // TypeQuals handled by caller.
1254 break;
1255 }
1258 // FIXME: Preserve type source info.
1260 assert(!Result.isNull() && "Didn't get a type for typeof?");
1261 if (!Result->isDependentType())
1262 if (const auto *TT = Result->getAs<TagType>())
1263 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1264 // TypeQuals handled by caller.
1265 Result = Context.getTypeOfType(
1269 break;
1272 Expr *E = DS.getRepAsExpr();
1273 assert(E && "Didn't get an expression for typeof?");
1274 // TypeQuals handled by caller.
1279 if (Result.isNull()) {
1280 Result = Context.IntTy;
1281 declarator.setInvalidType(true);
1282 }
1283 break;
1284 }
1286 Expr *E = DS.getRepAsExpr();
1287 assert(E && "Didn't get an expression for decltype?");
1288 // TypeQuals handled by caller.
1290 if (Result.isNull()) {
1291 Result = Context.IntTy;
1292 declarator.setInvalidType(true);
1293 }
1294 break;
1295 }
1297 Expr *E = DS.getPackIndexingExpr();
1298 assert(E && "Didn't get an expression for pack indexing");
1299 QualType Pattern = S.GetTypeFromParser(DS.getRepAsType());
1300 Result = S.BuildPackIndexingType(Pattern, E, DS.getBeginLoc(),
1301 DS.getEllipsisLoc());
1302 if (Result.isNull()) {
1303 declarator.setInvalidType(true);
1304 Result = Context.IntTy;
1305 }
1306 break;
1307 }
1308
1309#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
1310#include "clang/Basic/BuiltinTraits.inc"
1312 assert(!Result.isNull() && "Didn't get a type for the transformation?");
1315 DS.getTypeSpecTypeLoc());
1316 if (Result.isNull()) {
1317 Result = Context.IntTy;
1318 declarator.setInvalidType(true);
1319 }
1320 break;
1321
1322 case DeclSpec::TST_auto:
1324 auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1327
1328 TemplateDecl *TypeConstraintConcept = nullptr;
1330 if (DS.isConstrainedAuto()) {
1331 if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1332 TypeConstraintConcept =
1333 cast<TemplateDecl>(TemplateId->Template.get().getAsTemplateDecl());
1334 TemplateArgumentListInfo TemplateArgsInfo;
1335 TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1336 TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1337 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1338 TemplateId->NumArgs);
1339 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1340 for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1341 TemplateArgs.push_back(ArgLoc.getArgument());
1342 } else {
1343 declarator.setInvalidType(true);
1344 }
1345 }
1347 TypeConstraintConcept, TemplateArgs);
1348 break;
1349 }
1350
1352 Result = Context.getAutoType(DeducedKind::Undeduced, QualType(),
1354 break;
1355
1357 Result = Context.UnknownAnyTy;
1358 break;
1359
1362 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1364 if (Result.isNull()) {
1365 Result = Context.IntTy;
1366 declarator.setInvalidType(true);
1367 }
1368 break;
1369
1370#define GENERIC_IMAGE_TYPE(ImgType, Id) \
1371 case DeclSpec::TST_##ImgType##_t: \
1372 switch (getImageAccess(DS.getAttributes())) { \
1373 case OpenCLAccessAttr::Keyword_write_only: \
1374 Result = Context.Id##WOTy; \
1375 break; \
1376 case OpenCLAccessAttr::Keyword_read_write: \
1377 Result = Context.Id##RWTy; \
1378 break; \
1379 case OpenCLAccessAttr::Keyword_read_only: \
1380 Result = Context.Id##ROTy; \
1381 break; \
1382 case OpenCLAccessAttr::SpellingNotCalculated: \
1383 llvm_unreachable("Spelling not yet calculated"); \
1384 } \
1385 break;
1386#include "clang/Basic/OpenCLImageTypes.def"
1387
1388#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1389 case DeclSpec::TST_##Name: \
1390 Result = Context.SingletonId; \
1391 break;
1392#include "clang/Basic/HLSLIntangibleTypes.def"
1393
1395 Result = Context.IntTy;
1396 declarator.setInvalidType(true);
1397 break;
1398 }
1399
1400 // FIXME: we want resulting declarations to be marked invalid, but claiming
1401 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1402 // a null type.
1403 if (Result->containsErrors())
1404 declarator.setInvalidType();
1405
1406 if (S.getLangOpts().OpenCL) {
1407 const auto &OpenCLOptions = S.getOpenCLOptions();
1408 bool IsOpenCLC30Compatible =
1410 // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1411 // support.
1412 // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1413 // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1414 // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1415 // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1416 // only when the optional feature is supported
1417 if ((Result->isImageType() || Result->isSamplerT()) &&
1418 (IsOpenCLC30Compatible &&
1419 !OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts()))) {
1420 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1421 << 0 << Result << "__opencl_c_images";
1422 declarator.setInvalidType();
1423 } else if (Result->isOCLImage3dWOType() &&
1424 !OpenCLOptions.isSupported("cl_khr_3d_image_writes",
1425 S.getLangOpts())) {
1426 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1427 << 0 << Result
1428 << (IsOpenCLC30Compatible
1429 ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes"
1430 : "cl_khr_3d_image_writes");
1431 declarator.setInvalidType();
1432 }
1433 }
1434
1435 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1437
1438 // Only fixed point types can be saturated
1439 if (DS.isTypeSpecSat() && !IsFixedPointType)
1440 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1442 Context.getPrintingPolicy());
1443
1444 // Handle complex types.
1446 if (S.getLangOpts().Freestanding)
1447 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1448 Result = Context.getComplexType(Result);
1449 } else if (DS.isTypeAltiVecVector()) {
1450 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1451 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1453 if (DS.isTypeAltiVecPixel())
1454 VecKind = VectorKind::AltiVecPixel;
1455 else if (DS.isTypeAltiVecBool())
1456 VecKind = VectorKind::AltiVecBool;
1457 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1458 }
1459
1460 // _Imaginary was a feature of C99 through C23 but was never supported in
1461 // Clang. The feature was removed in C2y, but we retain the unsupported
1462 // diagnostic for an improved user experience.
1464 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1465
1466 // Before we process any type attributes, synthesize a block literal
1467 // function declarator if necessary.
1468 if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1470
1471 // Apply any type attributes from the decl spec. This may cause the
1472 // list of type attributes to be temporarily saved while the type
1473 // attributes are pushed around.
1474 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1475 if (!DS.isTypeSpecPipe()) {
1476 // We also apply declaration attributes that "slide" to the decl spec.
1477 // Ordering can be important for attributes. The decalaration attributes
1478 // come syntactically before the decl spec attributes, so we process them
1479 // in that order.
1480 ParsedAttributesView SlidingAttrs;
1481 for (ParsedAttr &AL : declarator.getDeclarationAttributes()) {
1482 if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
1483 SlidingAttrs.addAtEnd(&AL);
1484
1485 // For standard syntax attributes, which would normally appertain to the
1486 // declaration here, suggest moving them to the type instead. But only
1487 // do this for our own vendor attributes; moving other vendors'
1488 // attributes might hurt portability.
1489 // There's one special case that we need to deal with here: The
1490 // `MatrixType` attribute may only be used in a typedef declaration. If
1491 // it's being used anywhere else, don't output the warning as
1492 // ProcessDeclAttributes() will output an error anyway.
1493 if (AL.isStandardAttributeSyntax() && AL.isClangScope() &&
1494 !(AL.getKind() == ParsedAttr::AT_MatrixType &&
1496 S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl)
1497 << AL;
1498 }
1499 }
1500 }
1501 // During this call to processTypeAttrs(),
1502 // TypeProcessingState::getCurrentAttributes() will erroneously return a
1503 // reference to the DeclSpec attributes, rather than the declaration
1504 // attributes. However, this doesn't matter, as getCurrentAttributes()
1505 // is only called when distributing attributes from one attribute list
1506 // to another. Declaration attributes are always C++11 attributes, and these
1507 // are never distributed.
1508 processTypeAttrs(state, Result, TAL_DeclSpec, SlidingAttrs);
1510 }
1511
1512 // Apply const/volatile/restrict qualifiers to T.
1513 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1514 // Warn about CV qualifiers on function types.
1515 // C99 6.7.3p8:
1516 // If the specification of a function type includes any type qualifiers,
1517 // the behavior is undefined.
1518 // C2y changed this behavior to be implementation-defined. Clang defines
1519 // the behavior in all cases to ignore the qualifier, as in C++.
1520 // C++11 [dcl.fct]p7:
1521 // The effect of a cv-qualifier-seq in a function declarator is not the
1522 // same as adding cv-qualification on top of the function type. In the
1523 // latter case, the cv-qualifiers are ignored.
1524 if (Result->isFunctionType()) {
1525 unsigned DiagId = diag::warn_typecheck_function_qualifiers_ignored;
1526 if (!S.getLangOpts().CPlusPlus && !S.getLangOpts().C2y)
1527 DiagId = diag::ext_typecheck_function_qualifiers_unspecified;
1529 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1530 DiagId);
1531 // No diagnostic for 'restrict' or '_Atomic' applied to a
1532 // function type; we'll diagnose those later, in BuildQualifiedType.
1533 }
1534
1535 // C++11 [dcl.ref]p1:
1536 // Cv-qualified references are ill-formed except when the
1537 // cv-qualifiers are introduced through the use of a typedef-name
1538 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1539 //
1540 // There don't appear to be any other contexts in which a cv-qualified
1541 // reference type could be formed, so the 'ill-formed' clause here appears
1542 // to never happen.
1543 if (TypeQuals && Result->isReferenceType()) {
1545 S, DS, TypeQuals, Result,
1547 diag::warn_typecheck_reference_qualifiers);
1548 }
1549
1550 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1551 // than once in the same specifier-list or qualifier-list, either directly
1552 // or via one or more typedefs."
1553 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1554 && TypeQuals & Result.getCVRQualifiers()) {
1555 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1556 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1557 << "const";
1558 }
1559
1560 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1561 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1562 << "volatile";
1563 }
1564
1565 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1566 // produce a warning in this case.
1567 }
1568
1569 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1570
1571 // If adding qualifiers fails, just use the unqualified type.
1572 if (Qualified.isNull())
1573 declarator.setInvalidType(true);
1574 else
1575 Result = Qualified;
1576 }
1577
1578 // Check for __ob_wrap and __ob_trap
1579 if (DS.isOverflowBehaviorSpecified() &&
1580 S.getLangOpts().OverflowBehaviorTypes) {
1581 if (!Result->isIntegerType()) {
1583 StringRef SpecifierName =
1585 S.Diag(Loc, diag::err_overflow_behavior_non_integer_type)
1586 << SpecifierName << Result.getAsString() << 1;
1587 } else {
1588 OverflowBehaviorType::OverflowBehaviorKind Kind =
1589 DS.isWrapSpecified()
1590 ? OverflowBehaviorType::OverflowBehaviorKind::Wrap
1591 : OverflowBehaviorType::OverflowBehaviorKind::Trap;
1592 Result = state.getOverflowBehaviorType(Kind, Result);
1593 }
1594 }
1595
1596 if (S.getLangOpts().HLSL)
1598
1599 assert(!Result.isNull() && "This function should not return a null type");
1600 return Result;
1601}
1602
1603static std::string getPrintableNameForEntity(DeclarationName Entity) {
1604 if (Entity)
1605 return Entity.getAsString();
1606
1607 return "type name";
1608}
1609
1611 Qualifiers Qs, const DeclSpec *DS) {
1612 if (T.isNull())
1613 return QualType();
1614
1615 // Ignore any attempt to form a cv-qualified reference.
1616 if (T->isReferenceType()) {
1617 Qs.removeConst();
1618 Qs.removeVolatile();
1619 }
1620
1621 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1622 // object or incomplete types shall not be restrict-qualified."
1623 if (Qs.hasRestrict()) {
1624 unsigned DiagID = 0;
1625 QualType EltTy = Context.getBaseElementType(T);
1626
1627 if (EltTy->isAnyPointerType() || EltTy->isReferenceType() ||
1628 EltTy->isMemberPointerType()) {
1629
1630 if (const auto *PTy = EltTy->getAs<MemberPointerType>())
1631 EltTy = PTy->getPointeeType();
1632 else
1633 EltTy = EltTy->getPointeeType();
1634
1635 // If we have a pointer or reference, the pointee must have an object
1636 // incomplete type.
1637 if (!EltTy->isIncompleteOrObjectType())
1638 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1639
1640 } else if (!T->isDependentType() && !isa<AutoType>(T)) {
1641 // For an inferred type, we may not have seen the initializer yet and so
1642 // have no idea whether the underlying type is a pointer type or not.
1643 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1644 EltTy = T;
1645 }
1646
1647 Loc = DS ? DS->getRestrictSpecLoc() : Loc;
1648 if (DiagID) {
1649 Diag(Loc, DiagID) << EltTy;
1650 Qs.removeRestrict();
1651 } else {
1652 if (T->isArrayType())
1653 DiagCompat(Loc, diag_compat::restrict_on_array_of_pointers);
1654 }
1655 }
1656
1657 return Context.getQualifiedType(T, Qs);
1658}
1659
1661 unsigned CVRAU, const DeclSpec *DS) {
1662 if (T.isNull())
1663 return QualType();
1664
1665 // Ignore any attempt to form a cv-qualified reference.
1666 if (T->isReferenceType())
1667 CVRAU &=
1669
1670 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1671 // TQ_unaligned;
1672 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1673
1674 // C11 6.7.3/5:
1675 // If the same qualifier appears more than once in the same
1676 // specifier-qualifier-list, either directly or via one or more typedefs,
1677 // the behavior is the same as if it appeared only once.
1678 //
1679 // It's not specified what happens when the _Atomic qualifier is applied to
1680 // a type specified with the _Atomic specifier, but we assume that this
1681 // should be treated as if the _Atomic qualifier appeared multiple times.
1682 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1683 // C11 6.7.3/5:
1684 // If other qualifiers appear along with the _Atomic qualifier in a
1685 // specifier-qualifier-list, the resulting type is the so-qualified
1686 // atomic type.
1687 //
1688 // Don't need to worry about array types here, since _Atomic can't be
1689 // applied to such types.
1690 SplitQualType Split = T.getSplitUnqualifiedType();
1691 T = BuildAtomicType(QualType(Split.Ty, 0),
1692 DS ? DS->getAtomicSpecLoc() : Loc);
1693 if (T.isNull())
1694 return T;
1695 Split.Quals.addCVRQualifiers(CVR);
1696 return BuildQualifiedType(T, Loc, Split.Quals);
1697 }
1698
1701 return BuildQualifiedType(T, Loc, Q, DS);
1702}
1703
1705 return Context.getParenType(T);
1706}
1707
1708/// Given that we're building a pointer or reference to the given
1710 SourceLocation loc,
1711 bool isReference) {
1712 // Bail out if retention is unrequired or already specified.
1713 if (!type->isObjCLifetimeType() ||
1714 type.getObjCLifetime() != Qualifiers::OCL_None)
1715 return type;
1716
1718
1719 // If the object type is const-qualified, we can safely use
1720 // __unsafe_unretained. This is safe (because there are no read
1721 // barriers), and it'll be safe to coerce anything but __weak* to
1722 // the resulting type.
1723 if (type.isConstQualified()) {
1724 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1725
1726 // Otherwise, check whether the static type does not require
1727 // retaining. This currently only triggers for Class (possibly
1728 // protocol-qualifed, and arrays thereof).
1729 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1730 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1731
1732 // If we are in an unevaluated context, like sizeof, skip adding a
1733 // qualification.
1734 } else if (S.isUnevaluatedContext()) {
1735 return type;
1736
1737 // If that failed, give an error and recover using __strong. __strong
1738 // is the option most likely to prevent spurious second-order diagnostics,
1739 // like when binding a reference to a field.
1740 } else {
1741 // These types can show up in private ivars in system headers, so
1742 // we need this to not be an error in those cases. Instead we
1743 // want to delay.
1747 diag::err_arc_indirect_no_ownership, type, isReference));
1748 } else {
1749 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1750 }
1751 implicitLifetime = Qualifiers::OCL_Strong;
1752 }
1753 assert(implicitLifetime && "didn't infer any lifetime!");
1754
1755 Qualifiers qs;
1756 qs.addObjCLifetime(implicitLifetime);
1757 return S.Context.getQualifiedType(type, qs);
1758}
1759
1760static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1761 std::string Quals = FnTy->getMethodQuals().getAsString();
1762
1763 switch (FnTy->getRefQualifier()) {
1764 case RQ_None:
1765 break;
1766
1767 case RQ_LValue:
1768 if (!Quals.empty())
1769 Quals += ' ';
1770 Quals += '&';
1771 break;
1772
1773 case RQ_RValue:
1774 if (!Quals.empty())
1775 Quals += ' ';
1776 Quals += "&&";
1777 break;
1778 }
1779
1780 return Quals;
1781}
1782
1783namespace {
1784/// Kinds of declarator that cannot contain a qualified function type.
1785///
1786/// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1787/// a function type with a cv-qualifier or a ref-qualifier can only appear
1788/// at the topmost level of a type.
1789///
1790/// Parens and member pointers are permitted. We don't diagnose array and
1791/// function declarators, because they don't allow function types at all.
1792///
1793/// The values of this enum are used in diagnostics.
1794enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1795} // end anonymous namespace
1796
1797/// Check whether the type T is a qualified function type, and if it is,
1798/// diagnose that it cannot be contained within the given kind of declarator.
1800 QualifiedFunctionKind QFK) {
1801 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1802 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1803 if (!FPT ||
1804 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1805 return false;
1806
1807 S.Diag(Loc, diag::err_compound_qualified_function_type)
1808 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1810 return true;
1811}
1812
1814 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1815 if (!FPT ||
1816 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1817 return false;
1818
1819 Diag(Loc, diag::err_qualified_function_typeid)
1821 return true;
1822}
1823
1824// Helper to deduce addr space of a pointee type in OpenCL mode.
1826 if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
1827 !PointeeType->isSamplerT() &&
1828 !PointeeType.hasAddressSpace())
1829 PointeeType = S.getASTContext().getAddrSpaceQualType(
1831 return PointeeType;
1832}
1833
1835 SourceLocation Loc, DeclarationName Entity) {
1836 if (T->isReferenceType()) {
1837 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1838 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1839 << getPrintableNameForEntity(Entity) << T;
1840 return QualType();
1841 }
1842
1843 if (T->isFunctionType() && getLangOpts().OpenCL &&
1844 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
1845 getLangOpts())) {
1846 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
1847 return QualType();
1848 }
1849
1850 if (getLangOpts().HLSL && Loc.isValid()) {
1851 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
1852 return QualType();
1853 }
1854
1855 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1856 return QualType();
1857
1858 if (T->isObjCObjectType())
1859 return Context.getObjCObjectPointerType(T);
1860
1861 // In ARC, it is forbidden to build pointers to unqualified pointers.
1862 if (getLangOpts().ObjCAutoRefCount)
1863 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1864
1865 if (getLangOpts().OpenCL)
1867
1868 // In WebAssembly, pointers to reference types and pointers to tables are
1869 // illegal.
1870 if (getASTContext().getTargetInfo().getTriple().isWasm()) {
1871 if (T.isWebAssemblyReferenceType()) {
1872 Diag(Loc, diag::err_wasm_reference_pr) << 0;
1873 return QualType();
1874 }
1875
1876 // We need to desugar the type here in case T is a ParenType.
1877 if (T->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
1878 Diag(Loc, diag::err_wasm_table_pr) << 0;
1879 return QualType();
1880 }
1881 }
1882
1883 // Build the pointer type.
1884 return Context.getPointerType(T);
1885}
1886
1888 SourceLocation Loc,
1889 DeclarationName Entity) {
1890 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1891 "Unresolved overloaded function type");
1892
1893 // C++0x [dcl.ref]p6:
1894 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1895 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1896 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1897 // the type "lvalue reference to T", while an attempt to create the type
1898 // "rvalue reference to cv TR" creates the type TR.
1899 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1900
1901 // C++ [dcl.ref]p4: There shall be no references to references.
1902 //
1903 // According to C++ DR 106, references to references are only
1904 // diagnosed when they are written directly (e.g., "int & &"),
1905 // but not when they happen via a typedef:
1906 //
1907 // typedef int& intref;
1908 // typedef intref& intref2;
1909 //
1910 // Parser::ParseDeclaratorInternal diagnoses the case where
1911 // references are written directly; here, we handle the
1912 // collapsing of references-to-references as described in C++0x.
1913 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1914
1915 // C++ [dcl.ref]p1:
1916 // A declarator that specifies the type "reference to cv void"
1917 // is ill-formed.
1918 if (T->isVoidType()) {
1919 Diag(Loc, diag::err_reference_to_void);
1920 return QualType();
1921 }
1922
1923 if (getLangOpts().HLSL && Loc.isValid()) {
1924 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1;
1925 return QualType();
1926 }
1927
1928 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1929 return QualType();
1930
1931 if (T->isFunctionType() && getLangOpts().OpenCL &&
1932 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
1933 getLangOpts())) {
1934 Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1;
1935 return QualType();
1936 }
1937
1938 // In ARC, it is forbidden to build references to unqualified pointers.
1939 if (getLangOpts().ObjCAutoRefCount)
1940 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1941
1942 if (getLangOpts().OpenCL)
1944
1945 // In WebAssembly, references to reference types and tables are illegal.
1946 if (getASTContext().getTargetInfo().getTriple().isWasm() &&
1947 T.isWebAssemblyReferenceType()) {
1948 Diag(Loc, diag::err_wasm_reference_pr) << 1;
1949 return QualType();
1950 }
1951 if (T->isWebAssemblyTableType()) {
1952 Diag(Loc, diag::err_wasm_table_pr) << 1;
1953 return QualType();
1954 }
1955
1956 // Handle restrict on references.
1957 if (LValueRef)
1958 return Context.getLValueReferenceType(T, SpelledAsLValue);
1959 return Context.getRValueReferenceType(T);
1960}
1961
1963 return Context.getReadPipeType(T);
1964}
1965
1967 return Context.getWritePipeType(T);
1968}
1969
1970QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth,
1971 SourceLocation Loc) {
1972 if (BitWidth->isInstantiationDependent())
1973 return Context.getDependentBitIntType(IsUnsigned, BitWidth);
1974
1975 llvm::APSInt Bits(32);
1977 BitWidth, &Bits, /*FIXME*/ AllowFoldKind::Allow);
1978
1979 if (ICE.isInvalid())
1980 return QualType();
1981
1982 size_t NumBits = Bits.getZExtValue();
1983 if (!IsUnsigned && NumBits < 2) {
1984 Diag(Loc, diag::err_bit_int_bad_size) << 0;
1985 return QualType();
1986 }
1987
1988 if (IsUnsigned && NumBits < 1) {
1989 Diag(Loc, diag::err_bit_int_bad_size) << 1;
1990 return QualType();
1991 }
1992
1993 const TargetInfo &TI = getASTContext().getTargetInfo();
1994 if (NumBits > TI.getMaxBitIntWidth()) {
1995 Diag(Loc, diag::err_bit_int_max_size)
1996 << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth());
1997 return QualType();
1998 }
1999
2000 return Context.getBitIntType(IsUnsigned, NumBits);
2001}
2002
2003/// Check whether the specified array bound can be evaluated using the relevant
2004/// language rules. If so, returns the possibly-converted expression and sets
2005/// SizeVal to the size. If not, but the expression might be a VLA bound,
2006/// returns ExprResult(). Otherwise, produces a diagnostic and returns
2007/// ExprError().
2008static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
2009 llvm::APSInt &SizeVal, unsigned VLADiag,
2010 bool VLAIsError) {
2011 if (S.getLangOpts().CPlusPlus14 &&
2012 (VLAIsError ||
2013 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) {
2014 // C++14 [dcl.array]p1:
2015 // The constant-expression shall be a converted constant expression of
2016 // type std::size_t.
2017 //
2018 // Don't apply this rule if we might be forming a VLA: in that case, we
2019 // allow non-constant expressions and constant-folding. We only need to use
2020 // the converted constant expression rules (to properly convert the source)
2021 // when the source expression is of class type.
2023 ArraySize, S.Context.getSizeType(), SizeVal, CCEKind::ArrayBound);
2024 }
2025
2026 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2027 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2028 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2029 public:
2030 unsigned VLADiag;
2031 bool VLAIsError;
2032 bool IsVLA = false;
2033
2034 VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2035 : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2036
2037 Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2038 QualType T) override {
2039 return S.Diag(Loc, diag::err_array_size_non_int) << T;
2040 }
2041
2042 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2043 SourceLocation Loc) override {
2044 IsVLA = !VLAIsError;
2045 return S.Diag(Loc, VLADiag);
2046 }
2047
2048 Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2049 SourceLocation Loc) override {
2050 return S.Diag(Loc, diag::ext_vla_folded_to_constant);
2051 }
2052 } Diagnoser(VLADiag, VLAIsError);
2053
2054 ExprResult R =
2055 S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser);
2056 if (Diagnoser.IsVLA)
2057 return ExprResult();
2058 return R;
2059}
2060
2062 EltTy = Context.getBaseElementType(EltTy);
2063 if (EltTy->isIncompleteType() || EltTy->isDependentType() ||
2064 EltTy->isUndeducedType())
2065 return true;
2066
2067 CharUnits Size = Context.getTypeSizeInChars(EltTy);
2068 CharUnits Alignment = Context.getTypeAlignInChars(EltTy);
2069
2070 if (Size.isMultipleOf(Alignment))
2071 return true;
2072
2073 Diag(Loc, diag::err_array_element_alignment)
2074 << EltTy << Size.getQuantity() << Alignment.getQuantity();
2075 return false;
2076}
2077
2079 Expr *ArraySize, unsigned Quals,
2080 SourceRange Brackets, DeclarationName Entity) {
2081
2082 SourceLocation Loc = Brackets.getBegin();
2083 if (getLangOpts().CPlusPlus) {
2084 // C++ [dcl.array]p1:
2085 // T is called the array element type; this type shall not be a reference
2086 // type, the (possibly cv-qualified) type void, a function type or an
2087 // abstract class type.
2088 //
2089 // C++ [dcl.array]p3:
2090 // When several "array of" specifications are adjacent, [...] only the
2091 // first of the constant expressions that specify the bounds of the arrays
2092 // may be omitted.
2093 //
2094 // Note: function types are handled in the common path with C.
2095 if (T->isReferenceType()) {
2096 Diag(Loc, diag::err_illegal_decl_array_of_references)
2097 << getPrintableNameForEntity(Entity) << T;
2098 return QualType();
2099 }
2100
2101 if (T->isVoidType() || T->isIncompleteArrayType()) {
2102 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2103 return QualType();
2104 }
2105
2106 if (RequireNonAbstractType(Brackets.getBegin(), T,
2107 diag::err_array_of_abstract_type))
2108 return QualType();
2109
2110 // Mentioning a member pointer type for an array type causes us to lock in
2111 // an inheritance model, even if it's inside an unused typedef.
2112 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2113 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2114 if (!MPTy->getQualifier().isDependent())
2115 (void)isCompleteType(Loc, T);
2116
2117 } else {
2118 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2119 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2120 if (!T.isWebAssemblyReferenceType() &&
2122 diag::err_array_incomplete_or_sizeless_type))
2123 return QualType();
2124 }
2125
2126 // Multi-dimensional arrays of WebAssembly references are not allowed.
2127 if (Context.getTargetInfo().getTriple().isWasm() && T->isArrayType()) {
2128 const auto *ATy = dyn_cast<ArrayType>(T);
2129 if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
2130 Diag(Loc, diag::err_wasm_reftype_multidimensional_array);
2131 return QualType();
2132 }
2133 }
2134
2135 if (T->isSizelessType() && !T.isWebAssemblyReferenceType()) {
2136 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2137 return QualType();
2138 }
2139
2140 if (T->isFunctionType()) {
2141 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2142 << getPrintableNameForEntity(Entity) << T;
2143 return QualType();
2144 }
2145
2146 if (const auto *RD = T->getAsRecordDecl()) {
2147 // If the element type is a struct or union that contains a variadic
2148 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2149 if (RD->hasFlexibleArrayMember())
2150 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2151 } else if (T->isObjCObjectType()) {
2152 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2153 return QualType();
2154 }
2155
2156 if (!checkArrayElementAlignment(T, Loc))
2157 return QualType();
2158
2159 // Do placeholder conversions on the array size expression.
2160 if (ArraySize && ArraySize->hasPlaceholderType()) {
2162 if (Result.isInvalid()) return QualType();
2163 ArraySize = Result.get();
2164 }
2165
2166 // Do lvalue-to-rvalue conversions on the array size expression.
2167 if (ArraySize && !ArraySize->isPRValue()) {
2169 if (Result.isInvalid())
2170 return QualType();
2171
2172 ArraySize = Result.get();
2173 }
2174
2175 // C99 6.7.5.2p1: The size expression shall have integer type.
2176 // C++11 allows contextual conversions to such types.
2177 if (!getLangOpts().CPlusPlus11 &&
2178 ArraySize && !ArraySize->isTypeDependent() &&
2180 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2181 << ArraySize->getType() << ArraySize->getSourceRange();
2182 return QualType();
2183 }
2184
2185 auto IsStaticAssertLike = [](const Expr *ArraySize, ASTContext &Context) {
2186 if (!ArraySize)
2187 return false;
2188
2189 // If the array size expression is a conditional expression whose branches
2190 // are both integer constant expressions, one negative and one positive,
2191 // then it's assumed to be like an old-style static assertion. e.g.,
2192 // int old_style_assert[expr ? 1 : -1];
2193 // We will accept any integer constant expressions instead of assuming the
2194 // values 1 and -1 are always used.
2195 if (const auto *CondExpr = dyn_cast_if_present<ConditionalOperator>(
2196 ArraySize->IgnoreParenImpCasts())) {
2197 std::optional<llvm::APSInt> LHS =
2198 CondExpr->getLHS()->getIntegerConstantExpr(Context);
2199 std::optional<llvm::APSInt> RHS =
2200 CondExpr->getRHS()->getIntegerConstantExpr(Context);
2201 return LHS && RHS && LHS->isNegative() != RHS->isNegative();
2202 }
2203 return false;
2204 };
2205
2206 // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2207 unsigned VLADiag;
2208 bool VLAIsError;
2209 if (getLangOpts().OpenCL) {
2210 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2211 VLADiag = diag::err_opencl_vla;
2212 VLAIsError = true;
2213 } else if (getLangOpts().C99) {
2214 VLADiag = diag::warn_vla_used;
2215 VLAIsError = false;
2216 } else if (isSFINAEContext()) {
2217 VLADiag = diag::err_vla_in_sfinae;
2218 VLAIsError = true;
2219 } else if (getLangOpts().OpenMP && OpenMP().isInOpenMPTaskUntiedContext()) {
2220 VLADiag = diag::err_openmp_vla_in_task_untied;
2221 VLAIsError = true;
2222 } else if (getLangOpts().CPlusPlus) {
2223 if (getLangOpts().CPlusPlus11 && IsStaticAssertLike(ArraySize, Context))
2224 VLADiag = getLangOpts().GNUMode
2225 ? diag::ext_vla_cxx_in_gnu_mode_static_assert
2226 : diag::ext_vla_cxx_static_assert;
2227 else
2228 VLADiag = getLangOpts().GNUMode ? diag::ext_vla_cxx_in_gnu_mode
2229 : diag::ext_vla_cxx;
2230 VLAIsError = false;
2231 } else {
2232 VLADiag = diag::ext_vla;
2233 VLAIsError = false;
2234 }
2235
2236 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2237 if (!ArraySize) {
2238 if (ASM == ArraySizeModifier::Star) {
2239 Diag(Loc, VLADiag);
2240 if (VLAIsError)
2241 return QualType();
2242
2243 T = Context.getVariableArrayType(T, nullptr, ASM, Quals);
2244 } else {
2245 T = Context.getIncompleteArrayType(T, ASM, Quals);
2246 }
2247 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2248 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals);
2249 } else {
2250 ExprResult R =
2251 checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError);
2252 if (R.isInvalid())
2253 return QualType();
2254
2255 if (!R.isUsable()) {
2256 // C99: an array with a non-ICE size is a VLA. We accept any expression
2257 // that we can fold to a non-zero positive value as a non-VLA as an
2258 // extension.
2259 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals);
2260 } else if (!T->isDependentType() && !T->isIncompleteType() &&
2261 !T->isConstantSizeType()) {
2262 // C99: an array with an element type that has a non-constant-size is a
2263 // VLA.
2264 // FIXME: Add a note to explain why this isn't a VLA.
2265 Diag(Loc, VLADiag);
2266 if (VLAIsError)
2267 return QualType();
2268 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals);
2269 } else {
2270 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2271 // have a value greater than zero.
2272 // In C++, this follows from narrowing conversions being disallowed.
2273 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2274 if (Entity)
2275 Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2276 << getPrintableNameForEntity(Entity)
2277 << ArraySize->getSourceRange();
2278 else
2279 Diag(ArraySize->getBeginLoc(),
2280 diag::err_typecheck_negative_array_size)
2281 << ArraySize->getSourceRange();
2282 return QualType();
2283 }
2284 if (ConstVal == 0 && !T.isWebAssemblyReferenceType()) {
2285 if (getLangOpts().OpenCL) {
2286 Diag(ArraySize->getBeginLoc(), diag::err_typecheck_zero_array_size)
2287 << 3 << ArraySize->getSourceRange();
2288 return QualType();
2289 }
2290
2291 // GCC accepts zero sized static arrays. We allow them when
2292 // we're not in a SFINAE context.
2293 Diag(ArraySize->getBeginLoc(),
2294 isSFINAEContext() ? diag::err_typecheck_zero_array_size
2295 : diag::ext_typecheck_zero_array_size)
2296 << 0 << ArraySize->getSourceRange();
2297 if (isSFINAEContext())
2298 return QualType();
2299 }
2300
2301 // Is the array too large?
2302 unsigned ActiveSizeBits =
2303 (!T->isDependentType() && !T->isVariablyModifiedType() &&
2304 !T->isIncompleteType() && !T->isUndeducedType())
2306 : ConstVal.getActiveBits();
2307 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2308 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2309 << toString(ConstVal, 10, ConstVal.isSigned(),
2310 /*formatAsCLiteral=*/false, /*UpperCase=*/false,
2311 /*InsertSeparators=*/true)
2312 << ArraySize->getSourceRange();
2313 return QualType();
2314 }
2315
2316 T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2317 }
2318 }
2319
2320 if (T->isVariableArrayType()) {
2321 if (!Context.getTargetInfo().isVLASupported()) {
2322 // CUDA device code and some other targets don't support VLAs.
2323 bool IsCUDADevice = (getLangOpts().CUDA && getLangOpts().CUDAIsDevice);
2324 targetDiag(Loc,
2325 IsCUDADevice ? diag::err_cuda_vla : diag::err_vla_unsupported)
2326 << (IsCUDADevice ? llvm::to_underlying(CUDA().CurrentTarget()) : 0);
2327 } else if (sema::FunctionScopeInfo *FSI = getCurFunction()) {
2328 // VLAs are supported on this target, but we may need to do delayed
2329 // checking that the VLA is not being used within a coroutine.
2330 FSI->setHasVLA(Loc);
2331 }
2332 }
2333
2334 // If this is not C99, diagnose array size modifiers on non-VLAs.
2335 if (!getLangOpts().C99 && !T->isVariableArrayType() &&
2336 (ASM != ArraySizeModifier::Normal || Quals != 0)) {
2337 Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx
2338 : diag::ext_c99_array_usage)
2339 << ASM;
2340 }
2341
2342 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2343 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2344 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2345 if (getLangOpts().OpenCL) {
2346 const QualType ArrType = Context.getBaseElementType(T);
2347 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2348 ArrType->isSamplerT() || ArrType->isImageType()) {
2349 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2350 return QualType();
2351 }
2352 }
2353
2354 return T;
2355}
2356
2358 const BitIntType *BIT,
2359 bool ForMatrixType = false) {
2360 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2361 unsigned NumBits = BIT->getNumBits();
2362 if (!llvm::isPowerOf2_32(NumBits))
2363 return S.Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2364 << ForMatrixType;
2365 return false;
2366}
2367
2369 SourceLocation AttrLoc) {
2370 // The base type must be integer (not Boolean or enumeration) or float, and
2371 // can't already be a vector.
2372 if ((!CurType->isDependentType() &&
2373 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2374 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) &&
2375 !CurType->isBitIntType()) ||
2376 CurType->isArrayType()) {
2377 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2378 return QualType();
2379 }
2380
2381 if (const auto *BIT = CurType->getAs<BitIntType>();
2382 BIT && CheckBitIntElementType(*this, AttrLoc, BIT))
2383 return QualType();
2384
2385 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2386 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2388
2389 std::optional<llvm::APSInt> VecSize =
2391 if (!VecSize) {
2392 Diag(AttrLoc, diag::err_attribute_argument_type)
2393 << "vector_size" << AANT_ArgumentIntegerConstant
2394 << SizeExpr->getSourceRange();
2395 return QualType();
2396 }
2397
2398 if (VecSize->isNegative()) {
2399 Diag(SizeExpr->getExprLoc(), diag::err_attribute_vec_negative_size);
2400 return QualType();
2401 }
2402
2403 if (CurType->isDependentType())
2404 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2406
2407 // vecSize is specified in bytes - convert to bits.
2408 if (!VecSize->isIntN(61)) {
2409 // Bit size will overflow uint64.
2410 Diag(AttrLoc, diag::err_attribute_size_too_large)
2411 << SizeExpr->getSourceRange() << "vector";
2412 return QualType();
2413 }
2414 uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2415 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2416
2417 if (VectorSizeBits == 0) {
2418 Diag(AttrLoc, diag::err_attribute_zero_size)
2419 << SizeExpr->getSourceRange() << "vector";
2420 return QualType();
2421 }
2422
2423 if (!TypeSize || VectorSizeBits % TypeSize) {
2424 Diag(AttrLoc, diag::err_attribute_invalid_size)
2425 << SizeExpr->getSourceRange();
2426 return QualType();
2427 }
2428
2429 if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2430 Diag(AttrLoc, diag::err_attribute_size_too_large)
2431 << SizeExpr->getSourceRange() << "vector";
2432 return QualType();
2433 }
2434
2435 return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2437}
2438
2440 SourceLocation AttrLoc) {
2441 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2442 // in conjunction with complex types (pointers, arrays, functions, etc.).
2443 //
2444 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2445 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2446 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2447 // of bool aren't allowed.
2448 //
2449 // We explicitly allow bool elements in ext_vector_type for C/C++.
2450 bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus;
2451 if ((!T->isDependentType() && !T->isIntegerType() &&
2452 !T->isRealFloatingType()) ||
2453 (IsNoBoolVecLang && T->isBooleanType())) {
2454 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2455 return QualType();
2456 }
2457
2458 if (const auto *BIT = T->getAs<BitIntType>();
2459 BIT && CheckBitIntElementType(*this, AttrLoc, BIT))
2460 return QualType();
2461
2462 if (!SizeExpr->isTypeDependent() && !SizeExpr->isValueDependent()) {
2463 std::optional<llvm::APSInt> VecSize =
2465 if (!VecSize) {
2466 Diag(AttrLoc, diag::err_attribute_argument_type)
2467 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2468 << SizeExpr->getSourceRange();
2469 return QualType();
2470 }
2471
2472 if (VecSize->isNegative()) {
2473 Diag(SizeExpr->getExprLoc(), diag::err_attribute_vec_negative_size);
2474 return QualType();
2475 }
2476
2477 if (!VecSize->isIntN(32)) {
2478 Diag(AttrLoc, diag::err_attribute_size_too_large)
2479 << SizeExpr->getSourceRange() << "vector";
2480 return QualType();
2481 }
2482 // Unlike gcc's vector_size attribute, the size is specified as the
2483 // number of elements, not the number of bytes.
2484 unsigned VectorSize = static_cast<unsigned>(VecSize->getZExtValue());
2485
2486 if (VectorSize == 0) {
2487 Diag(AttrLoc, diag::err_attribute_zero_size)
2488 << SizeExpr->getSourceRange() << "vector";
2489 return QualType();
2490 }
2491
2492 return Context.getExtVectorType(T, VectorSize);
2493 }
2494
2495 return Context.getDependentSizedExtVectorType(T, SizeExpr, AttrLoc);
2496}
2497
2498QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2499 SourceLocation AttrLoc) {
2500 assert(Context.getLangOpts().MatrixTypes &&
2501 "Should never build a matrix type when it is disabled");
2502
2503 // Check element type, if it is not dependent.
2504 if (!ElementTy->isDependentType() &&
2506 Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2507 return QualType();
2508 }
2509
2510 if (const auto *BIT = ElementTy->getAs<BitIntType>();
2511 BIT &&
2512 CheckBitIntElementType(*this, AttrLoc, BIT, /*ForMatrixType=*/true))
2513 return QualType();
2514
2515 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2516 NumRows->isValueDependent() || NumCols->isValueDependent())
2517 return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2518 AttrLoc);
2519
2520 std::optional<llvm::APSInt> ValueRows =
2522 std::optional<llvm::APSInt> ValueColumns =
2524
2525 auto const RowRange = NumRows->getSourceRange();
2526 auto const ColRange = NumCols->getSourceRange();
2527
2528 // Both are row and column expressions are invalid.
2529 if (!ValueRows && !ValueColumns) {
2530 Diag(AttrLoc, diag::err_attribute_argument_type)
2531 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2532 << ColRange;
2533 return QualType();
2534 }
2535
2536 // Only the row expression is invalid.
2537 if (!ValueRows) {
2538 Diag(AttrLoc, diag::err_attribute_argument_type)
2539 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2540 return QualType();
2541 }
2542
2543 // Only the column expression is invalid.
2544 if (!ValueColumns) {
2545 Diag(AttrLoc, diag::err_attribute_argument_type)
2546 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2547 return QualType();
2548 }
2549
2550 // Check the matrix dimensions.
2551 unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2552 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2553 if (MatrixRows == 0 && MatrixColumns == 0) {
2554 Diag(AttrLoc, diag::err_attribute_zero_size)
2555 << "matrix" << RowRange << ColRange;
2556 return QualType();
2557 }
2558 if (MatrixRows == 0) {
2559 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2560 return QualType();
2561 }
2562 if (MatrixColumns == 0) {
2563 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2564 return QualType();
2565 }
2566 if (MatrixRows > Context.getLangOpts().MaxMatrixDimension &&
2567 MatrixColumns > Context.getLangOpts().MaxMatrixDimension) {
2568 Diag(AttrLoc, diag::err_attribute_size_too_large)
2569 << RowRange << ColRange << "matrix row and column";
2570 return QualType();
2571 }
2572 if (MatrixRows > Context.getLangOpts().MaxMatrixDimension) {
2573 Diag(AttrLoc, diag::err_attribute_size_too_large)
2574 << RowRange << "matrix row";
2575 return QualType();
2576 }
2577 if (MatrixColumns > Context.getLangOpts().MaxMatrixDimension) {
2578 Diag(AttrLoc, diag::err_attribute_size_too_large)
2579 << ColRange << "matrix column";
2580 return QualType();
2581 }
2582 return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2583}
2584
2586 if ((T->isArrayType() && !getLangOpts().allowArrayReturnTypes()) ||
2587 T->isFunctionType()) {
2588 Diag(Loc, diag::err_func_returning_array_function)
2589 << T->isFunctionType() << T;
2590 return true;
2591 }
2592
2593 // Functions cannot return half FP.
2594 if (T->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2595 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2596 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2598 return true;
2599 }
2600
2601 // Methods cannot return interface types. All ObjC objects are
2602 // passed by reference.
2603 if (T->isObjCObjectType()) {
2604 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2605 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2606 return true;
2607 }
2608
2609 // __ptrauth is illegal on a function return type.
2610 if (T.getPointerAuth()) {
2611 Diag(Loc, diag::err_ptrauth_qualifier_invalid) << T << 0;
2612 return true;
2613 }
2614
2615 if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2616 T.hasNonTrivialToPrimitiveCopyCUnion())
2619
2620 // C++2a [dcl.fct]p12:
2621 // A volatile-qualified return type is deprecated
2622 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2623 Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2624
2625 if (T.getAddressSpace() != LangAS::Default && getLangOpts().HLSL)
2626 return true;
2627 return false;
2628}
2629
2630/// Check the extended parameter information. Most of the necessary
2631/// checking should occur when applying the parameter attribute; the
2632/// only other checks required are positional restrictions.
2635 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2636 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2637
2638 bool emittedError = false;
2639 auto actualCC = EPI.ExtInfo.getCC();
2640 enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
2641 auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
2642 bool isCompatible =
2643 (required == RequiredCC::OnlySwift)
2644 ? (actualCC == CC_Swift)
2645 : (actualCC == CC_Swift || actualCC == CC_SwiftAsync);
2646 if (isCompatible || emittedError)
2647 return;
2648 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2650 << (required == RequiredCC::OnlySwift);
2651 emittedError = true;
2652 };
2653 for (size_t paramIndex = 0, numParams = paramTypes.size();
2654 paramIndex != numParams; ++paramIndex) {
2655 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2656 // Nothing interesting to check for orindary-ABI parameters.
2660 continue;
2661
2662 // swift_indirect_result parameters must be a prefix of the function
2663 // arguments.
2665 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2666 if (paramIndex != 0 &&
2667 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2669 S.Diag(getParamLoc(paramIndex),
2670 diag::err_swift_indirect_result_not_first);
2671 }
2672 continue;
2673
2675 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2676 continue;
2677
2678 // SwiftAsyncContext is not limited to swiftasynccall functions.
2680 continue;
2681
2682 // swift_error parameters must be preceded by a swift_context parameter.
2684 checkCompatible(paramIndex, RequiredCC::OnlySwift);
2685 if (paramIndex == 0 ||
2686 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2688 S.Diag(getParamLoc(paramIndex),
2689 diag::err_swift_error_result_not_after_swift_context);
2690 }
2691 continue;
2692 }
2693 llvm_unreachable("bad ABI kind");
2694 }
2695}
2696
2698 MutableArrayRef<QualType> ParamTypes,
2699 SourceLocation Loc, DeclarationName Entity,
2701 bool Invalid = false;
2702
2704
2705 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2706 // FIXME: Loc is too inprecise here, should use proper locations for args.
2707 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2708 if (ParamType->isVoidType()) {
2709 Diag(Loc, diag::err_param_with_void_type);
2710 Invalid = true;
2711 } else if (ParamType->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2712 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2713 // Disallow half FP arguments.
2714 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2716 Invalid = true;
2717 } else if (ParamType->isWebAssemblyTableType()) {
2718 Diag(Loc, diag::err_wasm_table_as_function_parameter);
2719 Invalid = true;
2720 } else if (ParamType.getPointerAuth()) {
2721 // __ptrauth is illegal on a function return type.
2722 Diag(Loc, diag::err_ptrauth_qualifier_invalid) << T << 1;
2723 Invalid = true;
2724 }
2725
2726 // C++2a [dcl.fct]p4:
2727 // A parameter with volatile-qualified type is deprecated
2728 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
2729 Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
2730
2731 ParamTypes[Idx] = ParamType;
2732 }
2733
2734 if (EPI.ExtParameterInfos) {
2735 checkExtParameterInfos(*this, ParamTypes, EPI,
2736 [=](unsigned i) { return Loc; });
2737 }
2738
2739 if (EPI.ExtInfo.getProducesResult()) {
2740 // This is just a warning, so we can't fail to build if we see it.
2742 }
2743
2744 if (Invalid)
2745 return QualType();
2746
2747 return Context.getFunctionType(T, ParamTypes, EPI);
2748}
2749
2751 CXXRecordDecl *Cls, SourceLocation Loc,
2752 DeclarationName Entity) {
2753 if (!Cls && !isDependentScopeSpecifier(SS)) {
2754 Cls = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS));
2755 if (!Cls) {
2756 auto D =
2757 Diag(SS.getBeginLoc(), diag::err_illegal_decl_mempointer_in_nonclass)
2758 << SS.getRange();
2759 if (const IdentifierInfo *II = Entity.getAsIdentifierInfo())
2760 D << II;
2761 else
2762 D << "member pointer";
2763 return QualType();
2764 }
2765 }
2766
2767 // Verify that we're not building a pointer to pointer to function with
2768 // exception specification.
2770 Diag(Loc, diag::err_distant_exception_spec);
2771 return QualType();
2772 }
2773
2774 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2775 // with reference type, or "cv void."
2776 if (T->isReferenceType()) {
2777 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2778 << getPrintableNameForEntity(Entity) << T;
2779 return QualType();
2780 }
2781
2782 if (T->isVoidType()) {
2783 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2784 << getPrintableNameForEntity(Entity);
2785 return QualType();
2786 }
2787
2788 if (T->isFunctionType() && getLangOpts().OpenCL &&
2789 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2790 getLangOpts())) {
2791 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2792 return QualType();
2793 }
2794
2795 if (getLangOpts().HLSL && Loc.isValid()) {
2796 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
2797 return QualType();
2798 }
2799
2800 // Adjust the default free function calling convention to the default method
2801 // calling convention.
2802 bool IsCtorOrDtor =
2805 if (T->isFunctionType())
2806 adjustMemberFunctionCC(T, /*HasThisPointer=*/true, IsCtorOrDtor, Loc);
2807
2808 return Context.getMemberPointerType(T, SS.getScopeRep(), Cls);
2809}
2810
2812 SourceLocation Loc,
2813 DeclarationName Entity) {
2814 if (!T->isFunctionType()) {
2815 Diag(Loc, diag::err_nonfunction_block_type);
2816 return QualType();
2817 }
2818
2819 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2820 return QualType();
2821
2822 if (getLangOpts().OpenCL)
2824
2825 return Context.getBlockPointerType(T);
2826}
2827
2829 QualType QT = Ty.get();
2830 if (QT.isNull()) {
2831 if (TInfo) *TInfo = nullptr;
2832 return QualType();
2833 }
2834
2835 TypeSourceInfo *TSI = nullptr;
2836 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2837 QT = LIT->getType();
2838 TSI = LIT->getTypeSourceInfo();
2839 }
2840
2841 if (TInfo)
2842 *TInfo = TSI;
2843 return QT;
2844}
2845
2846static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2847 Qualifiers::ObjCLifetime ownership,
2848 unsigned chunkIndex);
2849
2850/// Given that this is the declaration of a parameter under ARC,
2851/// attempt to infer attributes and such for pointer-to-whatever
2852/// types.
2853static void inferARCWriteback(TypeProcessingState &state,
2854 QualType &declSpecType) {
2855 Sema &S = state.getSema();
2856 Declarator &declarator = state.getDeclarator();
2857
2858 // TODO: should we care about decl qualifiers?
2859
2860 // Check whether the declarator has the expected form. We walk
2861 // from the inside out in order to make the block logic work.
2862 unsigned outermostPointerIndex = 0;
2863 bool isBlockPointer = false;
2864 unsigned numPointers = 0;
2865 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2866 unsigned chunkIndex = i;
2867 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2868 switch (chunk.Kind) {
2870 // Ignore parens.
2871 break;
2872
2875 // Count the number of pointers. Treat references
2876 // interchangeably as pointers; if they're mis-ordered, normal
2877 // type building will discover that.
2878 outermostPointerIndex = chunkIndex;
2879 numPointers++;
2880 break;
2881
2883 // If we have a pointer to block pointer, that's an acceptable
2884 // indirect reference; anything else is not an application of
2885 // the rules.
2886 if (numPointers != 1) return;
2887 numPointers++;
2888 outermostPointerIndex = chunkIndex;
2889 isBlockPointer = true;
2890
2891 // We don't care about pointer structure in return values here.
2892 goto done;
2893
2894 case DeclaratorChunk::Array: // suppress if written (id[])?
2898 return;
2899 }
2900 }
2901 done:
2902
2903 // If we have *one* pointer, then we want to throw the qualifier on
2904 // the declaration-specifiers, which means that it needs to be a
2905 // retainable object type.
2906 if (numPointers == 1) {
2907 // If it's not a retainable object type, the rule doesn't apply.
2908 if (!declSpecType->isObjCRetainableType()) return;
2909
2910 // If it already has lifetime, don't do anything.
2911 if (declSpecType.getObjCLifetime()) return;
2912
2913 // Otherwise, modify the type in-place.
2914 Qualifiers qs;
2915
2916 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2918 else
2920 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2921
2922 // If we have *two* pointers, then we want to throw the qualifier on
2923 // the outermost pointer.
2924 } else if (numPointers == 2) {
2925 // If we don't have a block pointer, we need to check whether the
2926 // declaration-specifiers gave us something that will turn into a
2927 // retainable object pointer after we slap the first pointer on it.
2928 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2929 return;
2930
2931 // Look for an explicit lifetime attribute there.
2932 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2933 if (chunk.Kind != DeclaratorChunk::Pointer &&
2935 return;
2936 for (const ParsedAttr &AL : chunk.getAttrs())
2937 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
2938 return;
2939
2941 outermostPointerIndex);
2942
2943 // Any other number of pointers/references does not trigger the rule.
2944 } else return;
2945
2946 // TODO: mark whether we did this inference?
2947}
2948
2949void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2950 SourceLocation FallbackLoc,
2951 SourceLocation ConstQualLoc,
2952 SourceLocation VolatileQualLoc,
2953 SourceLocation RestrictQualLoc,
2954 SourceLocation AtomicQualLoc,
2955 SourceLocation UnalignedQualLoc) {
2956 if (!Quals)
2957 return;
2958
2959 struct Qual {
2960 const char *Name;
2961 unsigned Mask;
2962 SourceLocation Loc;
2963 } const QualKinds[5] = {
2964 { "const", DeclSpec::TQ_const, ConstQualLoc },
2965 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2966 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2967 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2968 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2969 };
2970
2971 SmallString<32> QualStr;
2972 unsigned NumQuals = 0;
2973 SourceLocation Loc;
2974 FixItHint FixIts[5];
2975
2976 // Build a string naming the redundant qualifiers.
2977 for (auto &E : QualKinds) {
2978 if (Quals & E.Mask) {
2979 if (!QualStr.empty()) QualStr += ' ';
2980 QualStr += E.Name;
2981
2982 // If we have a location for the qualifier, offer a fixit.
2983 SourceLocation QualLoc = E.Loc;
2984 if (QualLoc.isValid()) {
2985 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2986 if (Loc.isInvalid() ||
2987 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2988 Loc = QualLoc;
2989 }
2990
2991 ++NumQuals;
2992 }
2993 }
2994
2995 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2996 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2997}
2998
2999// Diagnose pointless type qualifiers on the return type of a function.
3001 Declarator &D,
3002 unsigned FunctionChunkIndex) {
3004 D.getTypeObject(FunctionChunkIndex).Fun;
3005 if (FTI.hasTrailingReturnType()) {
3006 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3007 RetTy.getLocalCVRQualifiers(),
3009 return;
3010 }
3011
3012 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3013 End = D.getNumTypeObjects();
3014 OuterChunkIndex != End; ++OuterChunkIndex) {
3015 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
3016 switch (OuterChunk.Kind) {
3018 continue;
3019
3021 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3023 diag::warn_qual_return_type,
3024 PTI.TypeQuals,
3026 PTI.ConstQualLoc,
3027 PTI.VolatileQualLoc,
3028 PTI.RestrictQualLoc,
3029 PTI.AtomicQualLoc,
3030 PTI.UnalignedQualLoc);
3031 return;
3032 }
3033
3040 // FIXME: We can't currently provide an accurate source location and a
3041 // fix-it hint for these.
3042 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
3043 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3044 RetTy.getCVRQualifiers() | AtomicQual,
3045 D.getIdentifierLoc());
3046 return;
3047 }
3048
3049 llvm_unreachable("unknown declarator chunk kind");
3050 }
3051
3052 // If the qualifiers come from a conversion function type, don't diagnose
3053 // them -- they're not necessarily redundant, since such a conversion
3054 // operator can be explicitly called as "x.operator const int()".
3056 return;
3057
3058 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3059 // which are present there.
3060 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3062 D.getIdentifierLoc(),
3068}
3069
3070static std::pair<QualType, TypeSourceInfo *>
3071InventTemplateParameter(TypeProcessingState &state, QualType T,
3072 TypeSourceInfo *TrailingTSI, AutoType *Auto,
3074 Sema &S = state.getSema();
3075 Declarator &D = state.getDeclarator();
3076
3077 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3078 const unsigned AutoParameterPosition = Info.TemplateParams.size();
3079 const bool IsParameterPack = D.hasEllipsis();
3080
3081 // If auto is mentioned in a lambda parameter or abbreviated function
3082 // template context, convert it to a template parameter type.
3083
3084 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3085 // template parameter type. Template parameters are temporarily added
3086 // to the TU until the associated TemplateDecl is created.
3087 TemplateTypeParmDecl *InventedTemplateParam =
3090 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3091 /*NameLoc=*/D.getIdentifierLoc(),
3092 TemplateParameterDepth, AutoParameterPosition,
3094 D.getIdentifier(), AutoParameterPosition), false,
3095 IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3096 InventedTemplateParam->setImplicit();
3097 Info.TemplateParams.push_back(InventedTemplateParam);
3098
3099 // Attach type constraints to the new parameter.
3100 if (Auto->isConstrained()) {
3101 if (TrailingTSI) {
3102 // The 'auto' appears in a trailing return type we've already built;
3103 // extract its type constraints to attach to the template parameter.
3104 AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3105 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3106 bool Invalid = false;
3107 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3108 if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3111 Invalid = true;
3112 TAL.addArgument(AutoLoc.getArgLoc(Idx));
3113 }
3114
3115 if (!Invalid) {
3117 AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3118 AutoLoc.getNamedConcept(), /*FoundDecl=*/AutoLoc.getFoundDecl(),
3119 AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3120 InventedTemplateParam, D.getEllipsisLoc());
3121 }
3122 } else {
3123 // The 'auto' appears in the decl-specifiers; we've not finished forming
3124 // TypeSourceInfo for it yet.
3126 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
3127 TemplateId->RAngleLoc);
3128 bool Invalid = false;
3129 if (TemplateId->LAngleLoc.isValid()) {
3130 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3131 TemplateId->NumArgs);
3132 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3133
3134 if (D.getEllipsisLoc().isInvalid()) {
3135 for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3138 Invalid = true;
3139 break;
3140 }
3141 }
3142 }
3143 }
3144 if (!Invalid) {
3145 UsingShadowDecl *USD =
3146 TemplateId->Template.get().getAsUsingShadowDecl();
3147 TemplateDecl *CD = TemplateId->Template.get().getAsTemplateDecl();
3151 TemplateId->TemplateNameLoc),
3152 CD,
3153 /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
3154 TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3155 InventedTemplateParam, D.getEllipsisLoc());
3156 }
3157 }
3158 }
3159
3160 // Replace the 'auto' in the function parameter with this invented
3161 // template type parameter.
3162 // FIXME: Retain some type sugar to indicate that this was written
3163 // as 'auto'?
3164 QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3165 QualType NewT = state.ReplaceAutoType(T, Replacement);
3166 TypeSourceInfo *NewTSI =
3167 TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)
3168 : nullptr;
3169 return {NewT, NewTSI};
3170}
3171
3172static TypeSourceInfo *
3173GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3174 QualType T, TypeSourceInfo *ReturnTypeInfo);
3175
3176static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3177 TypeSourceInfo *&ReturnTypeInfo) {
3178 Sema &SemaRef = state.getSema();
3179 Declarator &D = state.getDeclarator();
3180 QualType T;
3181 ReturnTypeInfo = nullptr;
3182
3183 // The TagDecl owned by the DeclSpec.
3184 TagDecl *OwnedTagDecl = nullptr;
3185
3186 switch (D.getName().getKind()) {
3192 T = ConvertDeclSpecToType(state);
3193
3194 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3195 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3196 // Owned declaration is embedded in declarator.
3197 OwnedTagDecl->setEmbeddedInDeclarator(true);
3198 }
3199 break;
3200
3204 // Constructors and destructors don't have return types. Use
3205 // "void" instead.
3206 T = SemaRef.Context.VoidTy;
3209 break;
3210
3212 // Deduction guides have a trailing return type and no type in their
3213 // decl-specifier sequence. Use a placeholder return type for now.
3214 T = SemaRef.Context.DependentTy;
3215 break;
3216
3218 // The result type of a conversion function is the type that it
3219 // converts to.
3221 &ReturnTypeInfo);
3222 break;
3223 }
3224
3225 // Note: We don't need to distribute declaration attributes (i.e.
3226 // D.getDeclarationAttributes()) because those are always C++11 attributes,
3227 // and those don't get distributed.
3229 state, T, SemaRef.CUDA().IdentifyTarget(D.getAttributes()));
3230
3231 // Find the deduced type in this type. Look in the trailing return type if we
3232 // have one, otherwise in the DeclSpec type.
3233 // FIXME: The standard wording doesn't currently describe this.
3234 DeducedType *Deduced = T->getContainedDeducedType();
3235 bool DeducedIsTrailingReturnType = false;
3238 Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3239 DeducedIsTrailingReturnType = true;
3240 }
3241
3242 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3243 if (Deduced) {
3244 AutoType *Auto = dyn_cast<AutoType>(Deduced);
3245 int Error = -1;
3246
3247 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3248 // class template argument deduction)?
3249 bool IsCXXAutoType =
3250 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3251 bool IsDeducedReturnType = false;
3252
3253 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3255 AutoRange = D.getName().getSourceRange();
3256
3257 switch (D.getContext()) {
3259 // Declared return type of a lambda-declarator is implicit and is always
3260 // 'auto'.
3261 break;
3264 Error = 0;
3265 break;
3267 Error = 22;
3268 break;
3271 InventedTemplateParameterInfo *Info = nullptr;
3273 // With concepts we allow 'auto' in function parameters.
3274 if (!SemaRef.getLangOpts().CPlusPlus || !Auto ||
3275 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3276 Error = 0;
3277 break;
3278 }
3279
3280 if (!SemaRef.getLangOpts().CPlusPlus20)
3281 SemaRef.DiagCompat(AutoRange.getBegin(), diag_compat::auto_param);
3282
3283 if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3284 Error = 21;
3285 break;
3286 }
3287
3288 Info = &SemaRef.InventedParameterInfos.back();
3289 } else {
3290 // In C++14, generic lambdas allow 'auto' in their parameters.
3291 if (!SemaRef.getLangOpts().CPlusPlus14 && Auto &&
3292 Auto->getKeyword() == AutoTypeKeyword::Auto) {
3293 Error = 25; // auto not allowed in lambda parameter (before C++14)
3294 break;
3295 } else if (!Auto || Auto->getKeyword() != AutoTypeKeyword::Auto) {
3296 Error = 16; // __auto_type or decltype(auto) not allowed in lambda
3297 // parameter
3298 break;
3299 }
3300 Info = SemaRef.getCurLambda();
3301 assert(Info && "No LambdaScopeInfo on the stack!");
3302 }
3303
3304 // We'll deal with inventing template parameters for 'auto' in trailing
3305 // return types when we pick up the trailing return type when processing
3306 // the function chunk.
3307 if (!DeducedIsTrailingReturnType)
3308 T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3309 break;
3310 }
3312 if (D.isStaticMember() || D.isFunctionDeclarator())
3313 break;
3314 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3315 if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3316 Error = 6; // Interface member.
3317 } else {
3318 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3319 case TagTypeKind::Enum:
3320 llvm_unreachable("unhandled tag kind");
3322 Error = Cxx ? 1 : 2; /* Struct member */
3323 break;
3324 case TagTypeKind::Union:
3325 Error = Cxx ? 3 : 4; /* Union member */
3326 break;
3327 case TagTypeKind::Class:
3328 Error = 5; /* Class member */
3329 break;
3331 Error = 6; /* Interface member */
3332 break;
3333 }
3334 }
3336 Error = 20; // Friend type
3337 break;
3338 }
3341 Error = 7; // Exception declaration
3342 break;
3345 !SemaRef.getLangOpts().CPlusPlus20)
3346 Error = 19; // Template parameter (until C++20)
3347 else if (!SemaRef.getLangOpts().CPlusPlus17)
3348 Error = 8; // Template parameter (until C++17)
3349 break;
3351 Error = 9; // Block literal
3352 break;
3354 // Within a template argument list, a deduced template specialization
3355 // type will be reinterpreted as a template template argument.
3357 !D.getNumTypeObjects() &&
3359 break;
3360 [[fallthrough]];
3362 Error = 10; // Template type argument
3363 break;
3366 Error = 12; // Type alias
3367 break;
3370 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3371 Error = 13; // Function return type
3372 IsDeducedReturnType = true;
3373 break;
3375 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3376 Error = 14; // conversion-type-id
3377 IsDeducedReturnType = true;
3378 break;
3381 break;
3382 if (IsCXXAutoType && !Auto->isDecltypeAuto())
3383 break; // auto(x)
3384 [[fallthrough]];
3387 Error = 15; // Generic
3388 break;
3394 // FIXME: P0091R3 (erroneously) does not permit class template argument
3395 // deduction in conditions, for-init-statements, and other declarations
3396 // that are not simple-declarations.
3397 break;
3399 // FIXME: P0091R3 does not permit class template argument deduction here,
3400 // but we follow GCC and allow it anyway.
3401 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3402 Error = 17; // 'new' type
3403 break;
3405 Error = 18; // K&R function parameter
3406 break;
3407 }
3408
3410 Error = 11;
3411
3412 // In Objective-C it is an error to use 'auto' on a function declarator
3413 // (and everywhere for '__auto_type').
3414 if (D.isFunctionDeclarator() &&
3415 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3416 Error = 13;
3417
3418 if (Error != -1) {
3419 unsigned Kind;
3420 if (Auto) {
3421 switch (Auto->getKeyword()) {
3422 case AutoTypeKeyword::Auto: Kind = 0; break;
3423 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3424 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3425 }
3426 } else {
3428 "unknown auto type");
3429 Kind = 3;
3430 }
3431
3432 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3433 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3434
3435 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3436 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3437 << QualType(Deduced, 0) << AutoRange;
3438 if (auto *TD = TN.getAsTemplateDecl())
3439 SemaRef.NoteTemplateLocation(*TD);
3440
3441 T = SemaRef.Context.IntTy;
3442 D.setInvalidType(true);
3443 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) {
3444 // If there was a trailing return type, we already got
3445 // warn_cxx98_compat_trailing_return_type in the parser.
3446 // If there was a decltype(auto), we already got
3447 // warn_cxx11_compat_decltype_auto_type_specifier.
3448 unsigned DiagId = 0;
3450 DiagId = diag::warn_cxx11_compat_generic_lambda;
3451 else if (IsDeducedReturnType)
3452 DiagId = diag::warn_cxx11_compat_deduced_return_type;
3453 else if (Auto->getKeyword() == AutoTypeKeyword::Auto)
3454 DiagId = diag::warn_cxx98_compat_auto_type_specifier;
3455
3456 if (DiagId)
3457 SemaRef.Diag(AutoRange.getBegin(), DiagId) << AutoRange;
3458 }
3459 }
3460
3461 if (SemaRef.getLangOpts().CPlusPlus &&
3462 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3463 // Check the contexts where C++ forbids the declaration of a new class
3464 // or enumeration in a type-specifier-seq.
3465 unsigned DiagID = 0;
3466 switch (D.getContext()) {
3469 // Class and enumeration definitions are syntactically not allowed in
3470 // trailing return types.
3471 llvm_unreachable("parser should not have allowed this");
3472 break;
3480 // C++11 [dcl.type]p3:
3481 // A type-specifier-seq shall not define a class or enumeration unless
3482 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3483 // the declaration of a template-declaration.
3485 break;
3487 DiagID = diag::err_type_defined_in_alias_template;
3488 break;
3499 DiagID = diag::err_type_defined_in_type_specifier;
3500 break;
3507 // C++ [dcl.fct]p6:
3508 // Types shall not be defined in return or parameter types.
3509 DiagID = diag::err_type_defined_in_param_type;
3510 break;
3512 // C++ 6.4p2:
3513 // The type-specifier-seq shall not contain typedef and shall not declare
3514 // a new class or enumeration.
3515 DiagID = diag::err_type_defined_in_condition;
3516 break;
3517 }
3518
3519 if (DiagID != 0) {
3520 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3521 << SemaRef.Context.getCanonicalTagType(OwnedTagDecl);
3522 D.setInvalidType(true);
3523 }
3524 }
3525
3526 assert(!T.isNull() && "This function should not return a null type");
3527 return T;
3528}
3529
3530/// Produce an appropriate diagnostic for an ambiguity between a function
3531/// declarator and a C++ direct-initializer.
3533 DeclaratorChunk &DeclType, QualType RT) {
3534 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3535 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3536
3537 // If the return type is void there is no ambiguity.
3538 if (RT->isVoidType())
3539 return;
3540
3541 // An initializer for a non-class type can have at most one argument.
3542 if (!RT->isRecordType() && FTI.NumParams > 1)
3543 return;
3544
3545 // An initializer for a reference must have exactly one argument.
3546 if (RT->isReferenceType() && FTI.NumParams != 1)
3547 return;
3548
3549 // Only warn if this declarator is declaring a function at block scope, and
3550 // doesn't have a storage class (such as 'extern') specified.
3551 if (!D.isFunctionDeclarator() ||
3555 return;
3556
3557 // Inside a condition, a direct initializer is not permitted. We allow one to
3558 // be parsed in order to give better diagnostics in condition parsing.
3560 return;
3561
3562 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3563
3564 S.Diag(DeclType.Loc,
3565 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3566 : diag::warn_empty_parens_are_function_decl)
3567 << ParenRange;
3568
3569 // If the declaration looks like:
3570 // T var1,
3571 // f();
3572 // and name lookup finds a function named 'f', then the ',' was
3573 // probably intended to be a ';'.
3574 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3575 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3577 if (Comma.getFileID() != Name.getFileID() ||
3578 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3581 if (S.LookupName(Result, S.getCurScope()))
3582 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3584 << D.getIdentifier();
3585 Result.suppressDiagnostics();
3586 }
3587 }
3588
3589 if (FTI.NumParams > 0) {
3590 // For a declaration with parameters, eg. "T var(T());", suggest adding
3591 // parens around the first parameter to turn the declaration into a
3592 // variable declaration.
3593 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3594 SourceLocation B = Range.getBegin();
3595 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3596 // FIXME: Maybe we should suggest adding braces instead of parens
3597 // in C++11 for classes that don't have an initializer_list constructor.
3598 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3600 << FixItHint::CreateInsertion(E, ")");
3601 } else {
3602 // For a declaration without parameters, eg. "T var();", suggest replacing
3603 // the parens with an initializer to turn the declaration into a variable
3604 // declaration.
3605 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3606
3607 // Empty parens mean value-initialization, and no parens mean
3608 // default initialization. These are equivalent if the default
3609 // constructor is user-provided or if zero-initialization is a
3610 // no-op.
3611 if (RD && RD->hasDefinition() &&
3613 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3614 << FixItHint::CreateRemoval(ParenRange);
3615 else {
3616 std::string Init =
3617 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3618 if (Init.empty() && S.LangOpts.CPlusPlus11)
3619 Init = "{}";
3620 if (!Init.empty())
3621 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3622 << FixItHint::CreateReplacement(ParenRange, Init);
3623 }
3624 }
3625}
3626
3627/// Produce an appropriate diagnostic for a declarator with top-level
3628/// parentheses.
3631 assert(Paren.Kind == DeclaratorChunk::Paren &&
3632 "do not have redundant top-level parentheses");
3633
3634 // This is a syntactic check; we're not interested in cases that arise
3635 // during template instantiation.
3637 return;
3638
3639 // Check whether this could be intended to be a construction of a temporary
3640 // object in C++ via a function-style cast.
3641 bool CouldBeTemporaryObject =
3642 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3643 !D.isInvalidType() && D.getIdentifier() &&
3645 (T->isRecordType() || T->isDependentType()) &&
3647
3648 bool StartsWithDeclaratorId = true;
3649 for (auto &C : D.type_objects()) {
3650 switch (C.Kind) {
3652 if (&C == &Paren)
3653 continue;
3654 [[fallthrough]];
3656 StartsWithDeclaratorId = false;
3657 continue;
3658
3660 if (!C.Arr.NumElts)
3661 CouldBeTemporaryObject = false;
3662 continue;
3663
3665 // FIXME: Suppress the warning here if there is no initializer; we're
3666 // going to give an error anyway.
3667 // We assume that something like 'T (&x) = y;' is highly likely to not
3668 // be intended to be a temporary object.
3669 CouldBeTemporaryObject = false;
3670 StartsWithDeclaratorId = false;
3671 continue;
3672
3674 // In a new-type-id, function chunks require parentheses.
3676 return;
3677 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3678 // redundant-parens warning, but we don't know whether the function
3679 // chunk was syntactically valid as an expression here.
3680 CouldBeTemporaryObject = false;
3681 continue;
3682
3686 // These cannot appear in expressions.
3687 CouldBeTemporaryObject = false;
3688 StartsWithDeclaratorId = false;
3689 continue;
3690 }
3691 }
3692
3693 // FIXME: If there is an initializer, assume that this is not intended to be
3694 // a construction of a temporary object.
3695
3696 // Check whether the name has already been declared; if not, this is not a
3697 // function-style cast.
3698 if (CouldBeTemporaryObject) {
3701 if (!S.LookupName(Result, S.getCurScope()))
3702 CouldBeTemporaryObject = false;
3703 Result.suppressDiagnostics();
3704 }
3705
3706 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3707
3708 if (!CouldBeTemporaryObject) {
3709 // If we have A (::B), the parentheses affect the meaning of the program.
3710 // Suppress the warning in that case. Don't bother looking at the DeclSpec
3711 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3712 // formally unambiguous.
3713 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3715 for (;;) {
3716 switch (NNS.getKind()) {
3718 return;
3720 NNS = NNS.getAsType()->getPrefix();
3721 continue;
3723 NNS = NNS.getAsNamespaceAndPrefix().Prefix;
3724 continue;
3725 default:
3726 goto out;
3727 }
3728 }
3729 out:;
3730 }
3731
3732 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3733 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3735 return;
3736 }
3737
3738 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3739 << ParenRange << D.getIdentifier();
3740 auto *RD = T->getAsCXXRecordDecl();
3741 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3742 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3743 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3744 << D.getIdentifier();
3745 // FIXME: A cast to void is probably a better suggestion in cases where it's
3746 // valid (when there is no initializer and we're not in a condition).
3747 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3750 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3753}
3754
3755/// Helper for figuring out the default CC for a function declarator type. If
3756/// this is the outermost chunk, then we can determine the CC from the
3757/// declarator context. If not, then this could be either a member function
3758/// type or normal function type.
3760 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3761 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3762 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3763
3764 // Check for an explicit CC attribute.
3765 for (const ParsedAttr &AL : AttrList) {
3766 switch (AL.getKind()) {
3768 // Ignore attributes that don't validate or can't apply to the
3769 // function type. We'll diagnose the failure to apply them in
3770 // handleFunctionTypeAttr.
3771 CallingConv CC;
3772 if (!S.CheckCallingConvAttr(AL, CC, /*FunctionDecl=*/nullptr,
3773 S.CUDA().IdentifyTarget(D.getAttributes())) &&
3774 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3775 return CC;
3776 }
3777 break;
3778 }
3779
3780 default:
3781 break;
3782 }
3783 }
3784
3785 bool IsCXXInstanceMethod = false;
3786
3787 if (S.getLangOpts().CPlusPlus) {
3788 // Look inwards through parentheses to see if this chunk will form a
3789 // member pointer type or if we're the declarator. Any type attributes
3790 // between here and there will override the CC we choose here.
3791 unsigned I = ChunkIndex;
3792 bool FoundNonParen = false;
3793 while (I && !FoundNonParen) {
3794 --I;
3796 FoundNonParen = true;
3797 }
3798
3799 if (FoundNonParen) {
3800 // If we're not the declarator, we're a regular function type unless we're
3801 // in a member pointer.
3802 IsCXXInstanceMethod =
3804 } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
3805 // This can only be a call operator for a lambda, which is an instance
3806 // method, unless explicitly specified as 'static'.
3807 IsCXXInstanceMethod =
3809 } else {
3810 // We're the innermost decl chunk, so must be a function declarator.
3811 assert(D.isFunctionDeclarator());
3812
3813 // If we're inside a record, we're declaring a method, but it could be
3814 // explicitly or implicitly static.
3815 IsCXXInstanceMethod =
3818 !D.isStaticMember();
3819 }
3820 }
3821
3823 IsCXXInstanceMethod);
3824
3825 if (S.getLangOpts().CUDA) {
3826 // If we're compiling CUDA/HIP code and targeting HIPSPV we need to make
3827 // sure the kernels will be marked with the right calling convention so that
3828 // they will be visible by the APIs that ingest SPIR-V. We do not do this
3829 // when targeting AMDGCNSPIRV, as it does not rely on OpenCL.
3830 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
3831 if (Triple.isSPIRV() && Triple.getVendor() != llvm::Triple::AMD) {
3832 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3833 if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) {
3834 CC = CC_DeviceKernel;
3835 break;
3836 }
3837 }
3838 }
3839 }
3840
3841 for (const ParsedAttr &AL : llvm::concat<ParsedAttr>(
3844 if (AL.getKind() == ParsedAttr::AT_DeviceKernel) {
3845 CC = CC_DeviceKernel;
3846 break;
3847 }
3848 }
3849 return CC;
3850}
3851
3852namespace {
3853 /// A simple notion of pointer kinds, which matches up with the various
3854 /// pointer declarators.
3855 enum class SimplePointerKind {
3856 Pointer,
3857 BlockPointer,
3858 MemberPointer,
3859 Array,
3860 };
3861} // end anonymous namespace
3862
3864 switch (nullability) {
3866 if (!Ident__Nonnull)
3867 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3868 return Ident__Nonnull;
3869
3871 if (!Ident__Nullable)
3872 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3873 return Ident__Nullable;
3874
3876 if (!Ident__Nullable_result)
3877 Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
3878 return Ident__Nullable_result;
3879
3881 if (!Ident__Null_unspecified)
3882 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3883 return Ident__Null_unspecified;
3884 }
3885 llvm_unreachable("Unknown nullability kind.");
3886}
3887
3888/// Check whether there is a nullability attribute of any kind in the given
3889/// attribute list.
3890static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
3891 for (const ParsedAttr &AL : attrs) {
3892 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
3893 AL.getKind() == ParsedAttr::AT_TypeNullable ||
3894 AL.getKind() == ParsedAttr::AT_TypeNullableResult ||
3895 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
3896 return true;
3897 }
3898
3899 return false;
3900}
3901
3902namespace {
3903 /// Describes the kind of a pointer a declarator describes.
3904 enum class PointerDeclaratorKind {
3905 // Not a pointer.
3906 NonPointer,
3907 // Single-level pointer.
3908 SingleLevelPointer,
3909 // Multi-level pointer (of any pointer kind).
3910 MultiLevelPointer,
3911 // CFFooRef*
3912 MaybePointerToCFRef,
3913 // CFErrorRef*
3914 CFErrorRefPointer,
3915 // NSError**
3916 NSErrorPointerPointer,
3917 };
3918
3919 /// Describes a declarator chunk wrapping a pointer that marks inference as
3920 /// unexpected.
3921 // These values must be kept in sync with diagnostics.
3922 enum class PointerWrappingDeclaratorKind {
3923 /// Pointer is top-level.
3924 None = -1,
3925 /// Pointer is an array element.
3926 Array = 0,
3927 /// Pointer is the referent type of a C++ reference.
3928 Reference = 1
3929 };
3930} // end anonymous namespace
3931
3932/// Classify the given declarator, whose type-specified is \c type, based on
3933/// what kind of pointer it refers to.
3934///
3935/// This is used to determine the default nullability.
3936static PointerDeclaratorKind
3938 PointerWrappingDeclaratorKind &wrappingKind) {
3939 unsigned numNormalPointers = 0;
3940
3941 // For any dependent type, we consider it a non-pointer.
3942 if (type->isDependentType())
3943 return PointerDeclaratorKind::NonPointer;
3944
3945 // Look through the declarator chunks to identify pointers.
3946 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3947 DeclaratorChunk &chunk = declarator.getTypeObject(i);
3948 switch (chunk.Kind) {
3950 if (numNormalPointers == 0)
3951 wrappingKind = PointerWrappingDeclaratorKind::Array;
3952 break;
3953
3956 break;
3957
3960 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3961 : PointerDeclaratorKind::SingleLevelPointer;
3962
3964 break;
3965
3967 if (numNormalPointers == 0)
3968 wrappingKind = PointerWrappingDeclaratorKind::Reference;
3969 break;
3970
3972 ++numNormalPointers;
3973 if (numNormalPointers > 2)
3974 return PointerDeclaratorKind::MultiLevelPointer;
3975 break;
3976 }
3977 }
3978
3979 // Then, dig into the type specifier itself.
3980 unsigned numTypeSpecifierPointers = 0;
3981 do {
3982 // Decompose normal pointers.
3983 if (auto ptrType = type->getAs<PointerType>()) {
3984 ++numNormalPointers;
3985
3986 if (numNormalPointers > 2)
3987 return PointerDeclaratorKind::MultiLevelPointer;
3988
3989 type = ptrType->getPointeeType();
3990 ++numTypeSpecifierPointers;
3991 continue;
3992 }
3993
3994 // Decompose block pointers.
3995 if (type->getAs<BlockPointerType>()) {
3996 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3997 : PointerDeclaratorKind::SingleLevelPointer;
3998 }
3999
4000 // Decompose member pointers.
4001 if (type->getAs<MemberPointerType>()) {
4002 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4003 : PointerDeclaratorKind::SingleLevelPointer;
4004 }
4005
4006 // Look at Objective-C object pointers.
4007 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
4008 ++numNormalPointers;
4009 ++numTypeSpecifierPointers;
4010
4011 // If this is NSError**, report that.
4012 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
4013 if (objcClassDecl->getIdentifier() == S.ObjC().getNSErrorIdent() &&
4014 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
4015 return PointerDeclaratorKind::NSErrorPointerPointer;
4016 }
4017 }
4018
4019 break;
4020 }
4021
4022 // Look at Objective-C class types.
4023 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
4024 if (objcClass->getInterface()->getIdentifier() ==
4025 S.ObjC().getNSErrorIdent()) {
4026 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
4027 return PointerDeclaratorKind::NSErrorPointerPointer;
4028 }
4029
4030 break;
4031 }
4032
4033 // If at this point we haven't seen a pointer, we won't see one.
4034 if (numNormalPointers == 0)
4035 return PointerDeclaratorKind::NonPointer;
4036
4037 if (auto *recordDecl = type->getAsRecordDecl()) {
4038 // If this is CFErrorRef*, report it as such.
4039 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 &&
4040 S.ObjC().isCFError(recordDecl)) {
4041 return PointerDeclaratorKind::CFErrorRefPointer;
4042 }
4043 break;
4044 }
4045
4046 break;
4047 } while (true);
4048
4049 switch (numNormalPointers) {
4050 case 0:
4051 return PointerDeclaratorKind::NonPointer;
4052
4053 case 1:
4054 return PointerDeclaratorKind::SingleLevelPointer;
4055
4056 case 2:
4057 return PointerDeclaratorKind::MaybePointerToCFRef;
4058
4059 default:
4060 return PointerDeclaratorKind::MultiLevelPointer;
4061 }
4062}
4063
4065 SourceLocation loc) {
4066 // If we're anywhere in a function, method, or closure context, don't perform
4067 // completeness checks.
4068 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
4069 if (ctx->isFunctionOrMethod())
4070 return FileID();
4071
4072 if (ctx->isFileContext())
4073 break;
4074 }
4075
4076 // We only care about the expansion location.
4077 loc = S.SourceMgr.getExpansionLoc(loc);
4078 FileID file = S.SourceMgr.getFileID(loc);
4079 if (file.isInvalid())
4080 return FileID();
4081
4082 // Retrieve file information.
4083 bool invalid = false;
4084 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4085 if (invalid || !sloc.isFile())
4086 return FileID();
4087
4088 // We don't want to perform completeness checks on the main file or in
4089 // system headers.
4090 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4091 if (fileInfo.getIncludeLoc().isInvalid())
4092 return FileID();
4093 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4095 return FileID();
4096 }
4097
4098 return file;
4099}
4100
4101/// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4102/// taking into account whitespace before and after.
4103template <typename DiagBuilderT>
4104static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4105 SourceLocation PointerLoc,
4106 NullabilityKind Nullability) {
4107 assert(PointerLoc.isValid());
4108 if (PointerLoc.isMacroID())
4109 return;
4110
4111 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4112 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4113 return;
4114
4115 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4116 if (!NextChar)
4117 return;
4118
4119 SmallString<32> InsertionTextBuf{" "};
4120 InsertionTextBuf += getNullabilitySpelling(Nullability);
4121 InsertionTextBuf += " ";
4122 StringRef InsertionText = InsertionTextBuf.str();
4123
4124 if (isWhitespace(*NextChar)) {
4125 InsertionText = InsertionText.drop_back();
4126 } else if (NextChar[-1] == '[') {
4127 if (NextChar[0] == ']')
4128 InsertionText = InsertionText.drop_back().drop_front();
4129 else
4130 InsertionText = InsertionText.drop_front();
4131 } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) &&
4132 !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) {
4133 InsertionText = InsertionText.drop_back().drop_front();
4134 }
4135
4136 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4137}
4138
4140 SimplePointerKind PointerKind,
4141 SourceLocation PointerLoc,
4142 SourceLocation PointerEndLoc) {
4143 assert(PointerLoc.isValid());
4144
4145 if (PointerKind == SimplePointerKind::Array) {
4146 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4147 } else {
4148 S.Diag(PointerLoc, diag::warn_nullability_missing)
4149 << static_cast<unsigned>(PointerKind);
4150 }
4151
4152 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4153 if (FixItLoc.isMacroID())
4154 return;
4155
4156 auto addFixIt = [&](NullabilityKind Nullability) {
4157 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4158 Diag << static_cast<unsigned>(Nullability);
4159 Diag << static_cast<unsigned>(PointerKind);
4160 fixItNullability(S, Diag, FixItLoc, Nullability);
4161 };
4162 addFixIt(NullabilityKind::Nullable);
4163 addFixIt(NullabilityKind::NonNull);
4164}
4165
4166/// Complains about missing nullability if the file containing \p pointerLoc
4167/// has other uses of nullability (either the keywords or the \c assume_nonnull
4168/// pragma).
4169///
4170/// If the file has \e not seen other uses of nullability, this particular
4171/// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4172static void
4173checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4174 SourceLocation pointerLoc,
4175 SourceLocation pointerEndLoc = SourceLocation()) {
4176 // Determine which file we're performing consistency checking for.
4177 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4178 if (file.isInvalid())
4179 return;
4180
4181 // If we haven't seen any type nullability in this file, we won't warn now
4182 // about anything.
4183 FileNullability &fileNullability = S.NullabilityMap[file];
4184 if (!fileNullability.SawTypeNullability) {
4185 // If this is the first pointer declarator in the file, and the appropriate
4186 // warning is on, record it in case we need to diagnose it retroactively.
4187 diag::kind diagKind;
4188 if (pointerKind == SimplePointerKind::Array)
4189 diagKind = diag::warn_nullability_missing_array;
4190 else
4191 diagKind = diag::warn_nullability_missing;
4192
4193 if (fileNullability.PointerLoc.isInvalid() &&
4194 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
4195 fileNullability.PointerLoc = pointerLoc;
4196 fileNullability.PointerEndLoc = pointerEndLoc;
4197 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4198 }
4199
4200 return;
4201 }
4202
4203 // Complain about missing nullability.
4204 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4205}
4206
4207/// Marks that a nullability feature has been used in the file containing
4208/// \p loc.
4209///
4210/// If this file already had pointer types in it that were missing nullability,
4211/// the first such instance is retroactively diagnosed.
4212///
4213/// \sa checkNullabilityConsistency
4216 if (file.isInvalid())
4217 return;
4218
4219 FileNullability &fileNullability = S.NullabilityMap[file];
4220 if (fileNullability.SawTypeNullability)
4221 return;
4222 fileNullability.SawTypeNullability = true;
4223
4224 // If we haven't seen any type nullability before, now we have. Retroactively
4225 // diagnose the first unannotated pointer, if there was one.
4226 if (fileNullability.PointerLoc.isInvalid())
4227 return;
4228
4229 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4231 fileNullability.PointerEndLoc);
4232}
4233
4234/// Returns true if any of the declarator chunks before \p endIndex include a
4235/// level of indirection: array, pointer, reference, or pointer-to-member.
4236///
4237/// Because declarator chunks are stored in outer-to-inner order, testing
4238/// every chunk before \p endIndex is testing all chunks that embed the current
4239/// chunk as part of their type.
4240///
4241/// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4242/// end index, in which case all chunks are tested.
4243static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4244 unsigned i = endIndex;
4245 while (i != 0) {
4246 // Walk outwards along the declarator chunks.
4247 --i;
4248 const DeclaratorChunk &DC = D.getTypeObject(i);
4249 switch (DC.Kind) {
4251 break;
4256 return true;
4260 // These are invalid anyway, so just ignore.
4261 break;
4262 }
4263 }
4264 return false;
4265}
4266
4267static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk) {
4268 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4269 Chunk.Kind == DeclaratorChunk::Array);
4270}
4271
4272template<typename AttrT>
4273static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4274 AL.setUsedAsTypeAttr();
4275 return ::new (Ctx) AttrT(Ctx, AL);
4276}
4277
4279 NullabilityKind NK) {
4280 switch (NK) {
4283
4286
4289
4292 }
4293 llvm_unreachable("unknown NullabilityKind");
4294}
4295
4296// Diagnose whether this is a case with the multiple addr spaces.
4297// Returns true if this is an invalid case.
4298// ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4299// by qualifiers for two or more different address spaces."
4301 LangAS ASNew,
4302 SourceLocation AttrLoc) {
4303 if (ASOld != LangAS::Default) {
4304 if (ASOld != ASNew) {
4305 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4306 return true;
4307 }
4308 // Emit a warning if they are identical; it's likely unintended.
4309 S.Diag(AttrLoc,
4310 diag::warn_attribute_address_multiple_identical_qualifiers);
4311 }
4312 return false;
4313}
4314
4315// Whether this is a type broadly expected to have nullability attached.
4316// These types are affected by `#pragma assume_nonnull`, and missing nullability
4317// will be diagnosed with -Wnullability-completeness.
4319 return T->canHaveNullability(/*ResultIfUnknown=*/false) &&
4320 // For now, do not infer/require nullability on C++ smart pointers.
4321 // It's unclear whether the pragma's behavior is useful for C++.
4322 // e.g. treating type-aliases and template-type-parameters differently
4323 // from types of declarations can be surprising.
4325 T->getCanonicalTypeInternal());
4326}
4327
4328static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4329 QualType declSpecType,
4330 TypeSourceInfo *TInfo) {
4331 // The TypeSourceInfo that this function returns will not be a null type.
4332 // If there is an error, this function will fill in a dummy type as fallback.
4333 QualType T = declSpecType;
4334 Declarator &D = state.getDeclarator();
4335 Sema &S = state.getSema();
4336 ASTContext &Context = S.Context;
4337 const LangOptions &LangOpts = S.getLangOpts();
4338
4339 // The name we're declaring, if any.
4340 DeclarationName Name;
4341 if (D.getIdentifier())
4342 Name = D.getIdentifier();
4343
4344 // Does this declaration declare a typedef-name?
4345 bool IsTypedefName =
4349
4350 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4351 bool IsQualifiedFunction = T->isFunctionProtoType() &&
4352 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4353 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4354
4355 // If T is 'decltype(auto)', the only declarators we can have are parens
4356 // and at most one function declarator if this is a function declaration.
4357 // If T is a deduced class template specialization type, only parentheses
4358 // are allowed.
4359 if (auto *DT = T->getAs<DeducedType>()) {
4360 const AutoType *AT = T->getAs<AutoType>();
4361 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4362 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4363 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4364 unsigned Index = E - I - 1;
4365 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4366 unsigned DiagId = IsClassTemplateDeduction
4367 ? diag::err_deduced_class_template_compound_type
4368 : diag::err_decltype_auto_compound_type;
4369 unsigned DiagKind = 0;
4370 switch (DeclChunk.Kind) {
4372 continue;
4374 if (IsClassTemplateDeduction) {
4375 DiagKind = 3;
4376 break;
4377 }
4378 unsigned FnIndex;
4380 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4381 continue;
4382 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4383 break;
4384 }
4388 DiagKind = 0;
4389 break;
4391 DiagKind = 1;
4392 break;
4394 DiagKind = 2;
4395 break;
4397 break;
4398 }
4399
4400 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4401 D.setInvalidType(true);
4402 break;
4403 }
4404 }
4405 }
4406
4407 // Determine whether we should infer _Nonnull on pointer types.
4408 NullabilityKindOrNone inferNullability = std::nullopt;
4409 bool inferNullabilityCS = false;
4410 bool inferNullabilityInnerOnly = false;
4411 bool inferNullabilityInnerOnlyComplete = false;
4412
4413 // Are we in an assume-nonnull region?
4414 bool inAssumeNonNullRegion = false;
4415 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4416 if (assumeNonNullLoc.isValid()) {
4417 inAssumeNonNullRegion = true;
4418 recordNullabilitySeen(S, assumeNonNullLoc);
4419 }
4420
4421 // Whether to complain about missing nullability specifiers or not.
4422 enum {
4423 /// Never complain.
4424 CAMN_No,
4425 /// Complain on the inner pointers (but not the outermost
4426 /// pointer).
4427 CAMN_InnerPointers,
4428 /// Complain about any pointers that don't have nullability
4429 /// specified or inferred.
4430 CAMN_Yes
4431 } complainAboutMissingNullability = CAMN_No;
4432 unsigned NumPointersRemaining = 0;
4433 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4434
4435 if (IsTypedefName) {
4436 // For typedefs, we do not infer any nullability (the default),
4437 // and we only complain about missing nullability specifiers on
4438 // inner pointers.
4439 complainAboutMissingNullability = CAMN_InnerPointers;
4440
4441 if (shouldHaveNullability(T) && !T->getNullability()) {
4442 // Note that we allow but don't require nullability on dependent types.
4443 ++NumPointersRemaining;
4444 }
4445
4446 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4447 DeclaratorChunk &chunk = D.getTypeObject(i);
4448 switch (chunk.Kind) {
4452 break;
4453
4456 ++NumPointersRemaining;
4457 break;
4458
4461 continue;
4462
4464 ++NumPointersRemaining;
4465 continue;
4466 }
4467 }
4468 } else {
4469 bool isFunctionOrMethod = false;
4470 switch (auto context = state.getDeclarator().getContext()) {
4476 isFunctionOrMethod = true;
4477 [[fallthrough]];
4478
4480 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4481 complainAboutMissingNullability = CAMN_No;
4482 break;
4483 }
4484
4485 // Weak properties are inferred to be nullable.
4486 if (state.getDeclarator().isObjCWeakProperty()) {
4487 // Weak properties cannot be nonnull, and should not complain about
4488 // missing nullable attributes during completeness checks.
4489 complainAboutMissingNullability = CAMN_No;
4490 if (inAssumeNonNullRegion) {
4491 inferNullability = NullabilityKind::Nullable;
4492 }
4493 break;
4494 }
4495
4496 [[fallthrough]];
4497
4500 complainAboutMissingNullability = CAMN_Yes;
4501
4502 // Nullability inference depends on the type and declarator.
4503 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4504 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4505 case PointerDeclaratorKind::NonPointer:
4506 case PointerDeclaratorKind::MultiLevelPointer:
4507 // Cannot infer nullability.
4508 break;
4509
4510 case PointerDeclaratorKind::SingleLevelPointer:
4511 // Infer _Nonnull if we are in an assumes-nonnull region.
4512 if (inAssumeNonNullRegion) {
4513 complainAboutInferringWithinChunk = wrappingKind;
4514 inferNullability = NullabilityKind::NonNull;
4515 inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4517 }
4518 break;
4519
4520 case PointerDeclaratorKind::CFErrorRefPointer:
4521 case PointerDeclaratorKind::NSErrorPointerPointer:
4522 // Within a function or method signature, infer _Nullable at both
4523 // levels.
4524 if (isFunctionOrMethod && inAssumeNonNullRegion)
4525 inferNullability = NullabilityKind::Nullable;
4526 break;
4527
4528 case PointerDeclaratorKind::MaybePointerToCFRef:
4529 if (isFunctionOrMethod) {
4530 // On pointer-to-pointer parameters marked cf_returns_retained or
4531 // cf_returns_not_retained, if the outer pointer is explicit then
4532 // infer the inner pointer as _Nullable.
4533 auto hasCFReturnsAttr =
4534 [](const ParsedAttributesView &AttrList) -> bool {
4535 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4536 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4537 };
4538 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4539 if (hasCFReturnsAttr(D.getDeclarationAttributes()) ||
4540 hasCFReturnsAttr(D.getAttributes()) ||
4541 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4542 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4543 inferNullability = NullabilityKind::Nullable;
4544 inferNullabilityInnerOnly = true;
4545 }
4546 }
4547 }
4548 break;
4549 }
4550 break;
4551 }
4552
4554 complainAboutMissingNullability = CAMN_Yes;
4555 break;
4556
4576 // Don't infer in these contexts.
4577 break;
4578 }
4579 }
4580
4581 // Local function that returns true if its argument looks like a va_list.
4582 auto isVaList = [&S](QualType T) -> bool {
4583 auto *typedefTy = T->getAs<TypedefType>();
4584 if (!typedefTy)
4585 return false;
4586 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4587 do {
4588 if (typedefTy->getDecl() == vaListTypedef)
4589 return true;
4590 if (auto *name = typedefTy->getDecl()->getIdentifier())
4591 if (name->isStr("va_list"))
4592 return true;
4593 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4594 } while (typedefTy);
4595 return false;
4596 };
4597
4598 // Local function that checks the nullability for a given pointer declarator.
4599 // Returns true if _Nonnull was inferred.
4600 auto inferPointerNullability =
4601 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4602 SourceLocation pointerEndLoc,
4603 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4604 // We've seen a pointer.
4605 if (NumPointersRemaining > 0)
4606 --NumPointersRemaining;
4607
4608 // If a nullability attribute is present, there's nothing to do.
4609 if (hasNullabilityAttr(attrs))
4610 return nullptr;
4611
4612 // If we're supposed to infer nullability, do so now.
4613 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4614 ParsedAttr::Form form =
4615 inferNullabilityCS
4616 ? ParsedAttr::Form::ContextSensitiveKeyword()
4617 : ParsedAttr::Form::Keyword(false /*IsAlignAs*/,
4618 false /*IsRegularKeywordAttribute*/);
4619 ParsedAttr *nullabilityAttr = Pool.create(
4620 S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4621 AttributeScopeInfo(), nullptr, 0, form);
4622
4623 attrs.addAtEnd(nullabilityAttr);
4624
4625 if (inferNullabilityCS) {
4626 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4627 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4628 }
4629
4630 if (pointerLoc.isValid() &&
4631 complainAboutInferringWithinChunk !=
4632 PointerWrappingDeclaratorKind::None) {
4633 auto Diag =
4634 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4635 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4637 }
4638
4639 if (inferNullabilityInnerOnly)
4640 inferNullabilityInnerOnlyComplete = true;
4641 return nullabilityAttr;
4642 }
4643
4644 // If we're supposed to complain about missing nullability, do so
4645 // now if it's truly missing.
4646 switch (complainAboutMissingNullability) {
4647 case CAMN_No:
4648 break;
4649
4650 case CAMN_InnerPointers:
4651 if (NumPointersRemaining == 0)
4652 break;
4653 [[fallthrough]];
4654
4655 case CAMN_Yes:
4656 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4657 }
4658 return nullptr;
4659 };
4660
4661 // If the type itself could have nullability but does not, infer pointer
4662 // nullability and perform consistency checking.
4663 if (S.CodeSynthesisContexts.empty()) {
4664 if (shouldHaveNullability(T) && !T->getNullability()) {
4665 if (isVaList(T)) {
4666 // Record that we've seen a pointer, but do nothing else.
4667 if (NumPointersRemaining > 0)
4668 --NumPointersRemaining;
4669 } else {
4670 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4671 if (T->isBlockPointerType())
4672 pointerKind = SimplePointerKind::BlockPointer;
4673 else if (T->isMemberPointerType())
4674 pointerKind = SimplePointerKind::MemberPointer;
4675
4676 if (auto *attr = inferPointerNullability(
4677 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4678 D.getDeclSpec().getEndLoc(),
4681 T = state.getAttributedType(
4682 createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4683 }
4684 }
4685 }
4686
4687 if (complainAboutMissingNullability == CAMN_Yes && T->isArrayType() &&
4688 !T->getNullability() && !isVaList(T) && D.isPrototypeContext() &&
4690 checkNullabilityConsistency(S, SimplePointerKind::Array,
4692 }
4693 }
4694
4695 bool ExpectNoDerefChunk =
4696 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4697
4698 // Walk the DeclTypeInfo, building the recursive type as we go.
4699 // DeclTypeInfos are ordered from the identifier out, which is
4700 // opposite of what we want :).
4701
4702 // Track if the produced type matches the structure of the declarator.
4703 // This is used later to decide if we can fill `TypeLoc` from
4704 // `DeclaratorChunk`s. E.g. it must be false if Clang recovers from
4705 // an error by replacing the type with `int`.
4706 bool AreDeclaratorChunksValid = true;
4707 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4708 unsigned chunkIndex = e - i - 1;
4709 state.setCurrentChunkIndex(chunkIndex);
4710 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4711 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4712 switch (DeclType.Kind) {
4714 if (i == 0)
4716 T = S.BuildParenType(T);
4717 break;
4719 // If blocks are disabled, emit an error.
4720 if (!LangOpts.Blocks)
4721 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4722
4723 // Handle pointer nullability.
4724 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4725 DeclType.EndLoc, DeclType.getAttrs(),
4726 state.getDeclarator().getAttributePool());
4727
4728 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4729 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4730 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4731 // qualified with const.
4732 if (LangOpts.OpenCL)
4733 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4734 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4735 }
4736 break;
4738 // Verify that we're not building a pointer to pointer to function with
4739 // exception specification.
4740 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4741 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4742 D.setInvalidType(true);
4743 // Build the type anyway.
4744 }
4745
4746 // Handle pointer nullability
4747 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4748 DeclType.EndLoc, DeclType.getAttrs(),
4749 state.getDeclarator().getAttributePool());
4750
4751 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
4752 T = Context.getObjCObjectPointerType(T);
4753 if (DeclType.Ptr.TypeQuals)
4754 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4755 break;
4756 }
4757
4758 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4759 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4760 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4761 if (LangOpts.OpenCL) {
4762 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4763 T->isBlockPointerType()) {
4764 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4765 D.setInvalidType(true);
4766 }
4767 }
4768
4769 T = S.BuildPointerType(T, DeclType.Loc, Name);
4770 if (DeclType.Ptr.TypeQuals)
4771 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4772 if (DeclType.Ptr.OverflowBehaviorLoc.isValid()) {
4773 auto OBState = DeclType.Ptr.OverflowBehaviorIsWrap
4776 S.Diag(DeclType.Ptr.OverflowBehaviorLoc,
4777 diag::err_overflow_behavior_non_integer_type)
4778 << DeclSpec::getSpecifierName(OBState) << T.getAsString() << 1;
4779 D.setInvalidType(true);
4780 }
4781 break;
4783 // Verify that we're not building a reference to pointer to function with
4784 // exception specification.
4785 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4786 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4787 D.setInvalidType(true);
4788 // Build the type anyway.
4789 }
4790 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4791
4792 if (DeclType.Ref.HasRestrict)
4794 break;
4795 }
4797 // Verify that we're not building an array of pointers to function with
4798 // exception specification.
4799 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4800 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4801 D.setInvalidType(true);
4802 // Build the type anyway.
4803 }
4804 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4805 Expr *ArraySize = ATI.NumElts;
4807
4808 // Microsoft property fields can have multiple sizeless array chunks
4809 // (i.e. int x[][][]). Skip all of these except one to avoid creating
4810 // bad incomplete array types.
4811 if (chunkIndex != 0 && !ArraySize &&
4813 // This is a sizeless chunk. If the next is also, skip this one.
4814 DeclaratorChunk &NextDeclType = D.getTypeObject(chunkIndex - 1);
4815 if (NextDeclType.Kind == DeclaratorChunk::Array &&
4816 !NextDeclType.Arr.NumElts)
4817 break;
4818 }
4819
4820 if (ATI.isStar)
4822 else if (ATI.hasStatic)
4824 else
4826 if (ASM == ArraySizeModifier::Star && !D.isPrototypeContext()) {
4827 // FIXME: This check isn't quite right: it allows star in prototypes
4828 // for function definitions, and disallows some edge cases detailed
4829 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4830 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4832 D.setInvalidType(true);
4833 }
4834
4835 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4836 // shall appear only in a declaration of a function parameter with an
4837 // array type, ...
4838 if (ASM == ArraySizeModifier::Static || ATI.TypeQuals) {
4839 if (!(D.isPrototypeContext() ||
4841 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype)
4842 << (ASM == ArraySizeModifier::Static ? "'static'"
4843 : "type qualifier");
4844 // Remove the 'static' and the type qualifiers.
4845 if (ASM == ArraySizeModifier::Static)
4847 ATI.TypeQuals = 0;
4848 D.setInvalidType(true);
4849 }
4850
4851 // C99 6.7.5.2p1: ... and then only in the outermost array type
4852 // derivation.
4853 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4854 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost)
4855 << (ASM == ArraySizeModifier::Static ? "'static'"
4856 : "type qualifier");
4857 if (ASM == ArraySizeModifier::Static)
4859 ATI.TypeQuals = 0;
4860 D.setInvalidType(true);
4861 }
4862 }
4863
4864 // Array parameters can be marked nullable as well, although it's not
4865 // necessary if they're marked 'static'.
4866 if (complainAboutMissingNullability == CAMN_Yes &&
4867 !hasNullabilityAttr(DeclType.getAttrs()) &&
4869 !hasOuterPointerLikeChunk(D, chunkIndex)) {
4870 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4871 }
4872
4873 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4874 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4875 break;
4876 }
4878 // If the function declarator has a prototype (i.e. it is not () and
4879 // does not have a K&R-style identifier list), then the arguments are part
4880 // of the type, otherwise the argument list is ().
4881 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4882 IsQualifiedFunction =
4884
4885 auto IsClassType = [&](CXXScopeSpec &SS) {
4886 // If there already was an problem with the scope, don’t issue another
4887 // error about the explicit object parameter.
4888 return SS.isInvalid() ||
4889 isa_and_present<CXXRecordDecl>(
4890 S.computeDeclContext(SS, /*EnteringContext=*/true));
4891 };
4892
4893 // C++23 [dcl.fct]p6:
4894 //
4895 // An explicit-object-parameter-declaration is a parameter-declaration
4896 // with a this specifier. An explicit-object-parameter-declaration shall
4897 // appear only as the first parameter-declaration of a
4898 // parameter-declaration-list of one of:
4899 //
4900 // - a declaration of a member function or member function template
4901 // ([class.mem]), or
4902 //
4903 // - an explicit instantiation ([temp.explicit]) or explicit
4904 // specialization ([temp.expl.spec]) of a templated member function,
4905 // or
4906 //
4907 // - a lambda-declarator [expr.prim.lambda].
4910 FTI.NumParams ? dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param)
4911 : nullptr;
4912
4913 bool IsFunctionDecl = D.getInnermostNonParenChunk() == &DeclType;
4914 if (First && First->isExplicitObjectParameter() &&
4916
4917 // Either not a member or nested declarator in a member.
4918 //
4919 // Note that e.g. 'static' or 'friend' declarations are accepted
4920 // here; we diagnose them later when we build the member function
4921 // because it's easier that way.
4922 (C != DeclaratorContext::Member || !IsFunctionDecl) &&
4923
4924 // Allow out-of-line definitions of member functions.
4925 !IsClassType(D.getCXXScopeSpec())) {
4926 if (IsFunctionDecl)
4927 S.Diag(First->getBeginLoc(),
4928 diag::err_explicit_object_parameter_nonmember)
4929 << /*non-member*/ 2 << /*function*/ 0 << First->getSourceRange();
4930 else
4931 S.Diag(First->getBeginLoc(),
4932 diag::err_explicit_object_parameter_invalid)
4933 << First->getSourceRange();
4934
4935 // Do let non-member function have explicit parameters
4936 // to not break assumptions elsewhere in the code.
4937 First->setExplicitObjectParameterLoc(SourceLocation());
4938 D.setInvalidType();
4939 AreDeclaratorChunksValid = false;
4940 }
4941
4942 // Check for auto functions and trailing return type and adjust the
4943 // return type accordingly.
4944 if (!D.isInvalidType()) {
4945 // trailing-return-type is only required if we're declaring a function,
4946 // and not, for instance, a pointer to a function.
4947 if (D.getDeclSpec().hasAutoTypeSpec() &&
4948 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
4949 if (!S.getLangOpts().CPlusPlus14) {
4952 ? diag::err_auto_missing_trailing_return
4953 : diag::err_deduced_return_type);
4954 T = Context.IntTy;
4955 D.setInvalidType(true);
4956 AreDeclaratorChunksValid = false;
4957 } else {
4959 diag::warn_cxx11_compat_deduced_return_type);
4960 }
4961 } else if (FTI.hasTrailingReturnType()) {
4962 // T must be exactly 'auto' at this point. See CWG issue 681.
4963 if (isa<ParenType>(T)) {
4964 S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
4965 << T << D.getSourceRange();
4966 D.setInvalidType(true);
4967 // FIXME: recover and fill decls in `TypeLoc`s.
4968 AreDeclaratorChunksValid = false;
4969 } else if (D.getName().getKind() ==
4971 if (T != Context.DependentTy) {
4973 diag::err_deduction_guide_with_complex_decl)
4974 << D.getSourceRange();
4975 D.setInvalidType(true);
4976 // FIXME: recover and fill decls in `TypeLoc`s.
4977 AreDeclaratorChunksValid = false;
4978 }
4979 } else if (D.getContext() != DeclaratorContext::LambdaExpr &&
4980 (T.hasQualifiers() || !isa<AutoType>(T) ||
4981 cast<AutoType>(T)->getKeyword() !=
4983 cast<AutoType>(T)->isConstrained())) {
4984 // Attach a valid source location for diagnostics on functions with
4985 // trailing return types missing 'auto'. Attempt to get the location
4986 // from the declared type; if invalid, fall back to the trailing
4987 // return type's location.
4990 if (Loc.isInvalid()) {
4991 Loc = FTI.getTrailingReturnTypeLoc();
4992 SR = D.getSourceRange();
4993 }
4994 S.Diag(Loc, diag::err_trailing_return_without_auto) << T << SR;
4995 D.setInvalidType(true);
4996 // FIXME: recover and fill decls in `TypeLoc`s.
4997 AreDeclaratorChunksValid = false;
4998 }
4999 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
5000 if (T.isNull()) {
5001 // An error occurred parsing the trailing return type.
5002 T = Context.IntTy;
5003 D.setInvalidType(true);
5004 } else if (AutoType *Auto = T->getContainedAutoType()) {
5005 // If the trailing return type contains an `auto`, we may need to
5006 // invent a template parameter for it, for cases like
5007 // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
5008 InventedTemplateParameterInfo *InventedParamInfo = nullptr;
5010 InventedParamInfo = &S.InventedParameterInfos.back();
5012 InventedParamInfo = S.getCurLambda();
5013 if (InventedParamInfo) {
5014 std::tie(T, TInfo) = InventTemplateParameter(
5015 state, T, TInfo, Auto, *InventedParamInfo);
5016 }
5017 }
5018 } else {
5019 // This function type is not the type of the entity being declared,
5020 // so checking the 'auto' is not the responsibility of this chunk.
5021 }
5022 }
5023
5024 // C99 6.7.5.3p1: The return type may not be a function or array type.
5025 // For conversion functions, we'll diagnose this particular error later.
5026 if (!D.isInvalidType() &&
5027 ((T->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
5028 T->isFunctionType()) &&
5029 (D.getName().getKind() !=
5031 unsigned diagID = diag::err_func_returning_array_function;
5032 // Last processing chunk in block context means this function chunk
5033 // represents the block.
5034 if (chunkIndex == 0 &&
5036 diagID = diag::err_block_returning_array_function;
5037 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
5038 T = Context.IntTy;
5039 D.setInvalidType(true);
5040 AreDeclaratorChunksValid = false;
5041 }
5042
5043 // Do not allow returning half FP value.
5044 // FIXME: This really should be in BuildFunctionType.
5045 if (T->isHalfType()) {
5046 if (S.getLangOpts().OpenCL) {
5047 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5048 S.getLangOpts())) {
5049 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5050 << T << 0 /*pointer hint*/;
5051 D.setInvalidType(true);
5052 }
5053 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5055 S.Diag(D.getIdentifierLoc(),
5056 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
5057 D.setInvalidType(true);
5058 }
5059 }
5060
5061 // __ptrauth is illegal on a function return type.
5062 if (T.getPointerAuth()) {
5063 S.Diag(DeclType.Loc, diag::err_ptrauth_qualifier_invalid) << T << 0;
5064 }
5065
5066 if (LangOpts.OpenCL) {
5067 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
5068 // function.
5069 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
5070 T->isPipeType()) {
5071 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5072 << T << 1 /*hint off*/;
5073 D.setInvalidType(true);
5074 }
5075 // OpenCL doesn't support variadic functions and blocks
5076 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
5077 // We also allow here any toolchain reserved identifiers.
5078 if (FTI.isVariadic &&
5080 "__cl_clang_variadic_functions", S.getLangOpts()) &&
5081 !(D.getIdentifier() &&
5082 ((D.getIdentifier()->getName() == "printf" &&
5083 LangOpts.getOpenCLCompatibleVersion() >= 120) ||
5084 D.getIdentifier()->getName().starts_with("__")))) {
5085 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
5086 D.setInvalidType(true);
5087 }
5088 }
5089
5090 // Methods cannot return interface types. All ObjC objects are
5091 // passed by reference.
5092 if (T->isObjCObjectType()) {
5093 SourceLocation DiagLoc, FixitLoc;
5094 if (TInfo) {
5095 DiagLoc = TInfo->getTypeLoc().getBeginLoc();
5096 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
5097 } else {
5098 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5099 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
5100 }
5101 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
5102 << 0 << T
5103 << FixItHint::CreateInsertion(FixitLoc, "*");
5104
5105 T = Context.getObjCObjectPointerType(T);
5106 if (TInfo) {
5107 TypeLocBuilder TLB;
5108 TLB.pushFullCopy(TInfo->getTypeLoc());
5110 TLoc.setStarLoc(FixitLoc);
5111 TInfo = TLB.getTypeSourceInfo(Context, T);
5112 } else {
5113 AreDeclaratorChunksValid = false;
5114 }
5115
5116 D.setInvalidType(true);
5117 }
5118
5119 // cv-qualifiers on return types are pointless except when the type is a
5120 // class type in C++.
5121 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
5122 // A dependent type or an undeduced type might later become a class
5123 // type.
5124 !(S.getLangOpts().CPlusPlus &&
5125 (T->isRecordType() || T->isDependentType() ||
5126 T->isUndeducedAutoType()))) {
5127 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
5130 // [6.9.1/3] qualified void return is invalid on a C
5131 // function definition. Apparently ok on declarations and
5132 // in C++ though (!)
5133 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
5134 } else
5135 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
5136 }
5137
5138 // C++2a [dcl.fct]p12:
5139 // A volatile-qualified return type is deprecated
5140 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20)
5141 S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T;
5142
5143 // Objective-C ARC ownership qualifiers are ignored on the function
5144 // return type (by type canonicalization). Complain if this attribute
5145 // was written here.
5146 if (T.getQualifiers().hasObjCLifetime()) {
5147 SourceLocation AttrLoc;
5148 if (chunkIndex + 1 < D.getNumTypeObjects()) {
5149 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
5150 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5151 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5152 AttrLoc = AL.getLoc();
5153 break;
5154 }
5155 }
5156 }
5157 if (AttrLoc.isInvalid()) {
5158 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5159 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5160 AttrLoc = AL.getLoc();
5161 break;
5162 }
5163 }
5164 }
5165
5166 if (AttrLoc.isValid()) {
5167 // The ownership attributes are almost always written via
5168 // the predefined
5169 // __strong/__weak/__autoreleasing/__unsafe_unretained.
5170 if (AttrLoc.isMacroID())
5171 AttrLoc =
5173
5174 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
5175 << T.getQualifiers().getObjCLifetime();
5176 }
5177 }
5178
5179 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
5180 // C++ [dcl.fct]p6:
5181 // Types shall not be defined in return or parameter types.
5183 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
5184 << Context.getCanonicalTagType(Tag);
5185 }
5186
5187 // Exception specs are not allowed in typedefs. Complain, but add it
5188 // anyway.
5189 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
5191 diag::err_exception_spec_in_typedef)
5194
5195 // If we see "T var();" or "T var(T());" at block scope, it is probably
5196 // an attempt to initialize a variable, not a function declaration.
5197 if (FTI.isAmbiguous)
5198 warnAboutAmbiguousFunction(S, D, DeclType, T);
5199
5201 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
5202
5203 // OpenCL disallows functions without a prototype, but it doesn't enforce
5204 // strict prototypes as in C23 because it allows a function definition to
5205 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
5206 if (!FTI.NumParams && !FTI.isVariadic &&
5207 !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) {
5208 // Simple void foo(), where the incoming T is the result type.
5209 T = Context.getFunctionNoProtoType(T, EI);
5210 } else {
5211 // We allow a zero-parameter variadic function in C if the
5212 // function is marked with the "overloadable" attribute. Scan
5213 // for this attribute now. We also allow it in C23 per WG14 N2975.
5214 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
5215 if (LangOpts.C23)
5216 S.Diag(FTI.getEllipsisLoc(),
5217 diag::warn_c17_compat_ellipsis_only_parameter);
5219 ParsedAttr::AT_Overloadable) &&
5221 ParsedAttr::AT_Overloadable) &&
5223 ParsedAttr::AT_Overloadable))
5224 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
5225 }
5226
5227 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
5228 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5229 // definition.
5230 S.Diag(FTI.Params[0].IdentLoc,
5231 diag::err_ident_list_in_fn_declaration);
5232 D.setInvalidType(true);
5233 // Recover by creating a K&R-style function type, if possible.
5234 T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL)
5235 ? Context.getFunctionNoProtoType(T, EI)
5236 : Context.IntTy;
5237 AreDeclaratorChunksValid = false;
5238 break;
5239 }
5240
5242 EPI.ExtInfo = EI;
5243 EPI.Variadic = FTI.isVariadic;
5244 EPI.EllipsisLoc = FTI.getEllipsisLoc();
5248 : 0);
5251 : RQ_RValue;
5252
5253 // Otherwise, we have a function with a parameter list that is
5254 // potentially variadic.
5256 ParamTys.reserve(FTI.NumParams);
5257
5259 ExtParameterInfos(FTI.NumParams);
5260 bool HasAnyInterestingExtParameterInfos = false;
5261
5262 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
5263 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5264 QualType ParamTy = Param->getType();
5265 assert(!ParamTy.isNull() && "Couldn't parse type?");
5266
5267 // Look for 'void'. void is allowed only as a single parameter to a
5268 // function with no other parameters (C99 6.7.5.3p10). We record
5269 // int(void) as a FunctionProtoType with an empty parameter list.
5270 if (ParamTy->isVoidType()) {
5271 // If this is something like 'float(int, void)', reject it. 'void'
5272 // is an incomplete type (C99 6.2.5p19) and function decls cannot
5273 // have parameters of incomplete type.
5274 if (FTI.NumParams != 1 || FTI.isVariadic) {
5275 S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param);
5276 ParamTy = Context.IntTy;
5277 Param->setType(ParamTy);
5278 } else if (FTI.Params[i].Ident) {
5279 // Reject, but continue to parse 'int(void abc)'.
5280 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
5281 ParamTy = Context.IntTy;
5282 Param->setType(ParamTy);
5283 } else {
5284 // Reject, but continue to parse 'float(const void)'.
5285 if (ParamTy.hasQualifiers())
5286 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
5287
5288 for (const auto *A : Param->attrs()) {
5289 S.Diag(A->getLoc(), diag::warn_attribute_on_void_param)
5290 << A << A->getRange();
5291 }
5292
5293 // Reject, but continue to parse 'float(this void)' as
5294 // 'float(void)'.
5295 if (Param->isExplicitObjectParameter()) {
5296 S.Diag(Param->getLocation(),
5297 diag::err_void_explicit_object_param);
5298 Param->setExplicitObjectParameterLoc(SourceLocation());
5299 }
5300
5301 // Do not add 'void' to the list.
5302 break;
5303 }
5304 } else if (ParamTy->isHalfType()) {
5305 // Disallow half FP parameters.
5306 // FIXME: This really should be in BuildFunctionType.
5307 if (S.getLangOpts().OpenCL) {
5308 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5309 S.getLangOpts())) {
5310 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5311 << ParamTy << 0;
5312 D.setInvalidType();
5313 Param->setInvalidDecl();
5314 }
5315 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5317 S.Diag(Param->getLocation(),
5318 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5319 D.setInvalidType();
5320 }
5321 } else if (!FTI.hasPrototype) {
5322 if (Context.isPromotableIntegerType(ParamTy)) {
5323 ParamTy = Context.getPromotedIntegerType(ParamTy);
5324 Param->setKNRPromoted(true);
5325 } else if (const BuiltinType *BTy = ParamTy->getAs<BuiltinType>()) {
5326 if (BTy->getKind() == BuiltinType::Float) {
5327 ParamTy = Context.DoubleTy;
5328 Param->setKNRPromoted(true);
5329 }
5330 }
5331 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) {
5332 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5333 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5334 << ParamTy << 1 /*hint off*/;
5335 D.setInvalidType();
5336 }
5337
5338 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
5339 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
5340 HasAnyInterestingExtParameterInfos = true;
5341 }
5342
5343 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5344 ExtParameterInfos[i] =
5345 ExtParameterInfos[i].withABI(attr->getABI());
5346 HasAnyInterestingExtParameterInfos = true;
5347 }
5348
5349 if (Param->hasAttr<PassObjectSizeAttr>()) {
5350 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5351 HasAnyInterestingExtParameterInfos = true;
5352 }
5353
5354 if (Param->hasAttr<NoEscapeAttr>()) {
5355 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
5356 HasAnyInterestingExtParameterInfos = true;
5357 }
5358
5359 ParamTys.push_back(ParamTy);
5360 }
5361
5362 if (HasAnyInterestingExtParameterInfos) {
5363 EPI.ExtParameterInfos = ExtParameterInfos.data();
5364 checkExtParameterInfos(S, ParamTys, EPI,
5365 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
5366 }
5367
5368 SmallVector<QualType, 4> Exceptions;
5369 SmallVector<ParsedType, 2> DynamicExceptions;
5370 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5371 Expr *NoexceptExpr = nullptr;
5372
5373 if (FTI.getExceptionSpecType() == EST_Dynamic) {
5374 // FIXME: It's rather inefficient to have to split into two vectors
5375 // here.
5376 unsigned N = FTI.getNumExceptions();
5377 DynamicExceptions.reserve(N);
5378 DynamicExceptionRanges.reserve(N);
5379 for (unsigned I = 0; I != N; ++I) {
5380 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
5381 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
5382 }
5383 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
5384 NoexceptExpr = FTI.NoexceptExpr;
5385 }
5386
5389 DynamicExceptions,
5390 DynamicExceptionRanges,
5391 NoexceptExpr,
5392 Exceptions,
5393 EPI.ExceptionSpec);
5394
5395 // FIXME: Set address space from attrs for C++ mode here.
5396 // OpenCLCPlusPlus: A class member function has an address space.
5397 auto IsClassMember = [&]() {
5398 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5399 state.getDeclarator()
5400 .getCXXScopeSpec()
5401 .getScopeRep()
5402 .getKind() == NestedNameSpecifier::Kind::Type) ||
5403 state.getDeclarator().getContext() ==
5405 state.getDeclarator().getContext() ==
5407 };
5408
5409 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
5410 LangAS ASIdx = LangAS::Default;
5411 // Take address space attr if any and mark as invalid to avoid adding
5412 // them later while creating QualType.
5413 if (FTI.MethodQualifiers)
5415 LangAS ASIdxNew = attr.asOpenCLLangAS();
5416 if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
5417 attr.getLoc()))
5418 D.setInvalidType(true);
5419 else
5420 ASIdx = ASIdxNew;
5421 }
5422 // If a class member function's address space is not set, set it to
5423 // __generic.
5424 LangAS AS =
5426 : ASIdx);
5427 EPI.TypeQuals.addAddressSpace(AS);
5428 }
5429 T = Context.getFunctionType(T, ParamTys, EPI);
5430 }
5431 break;
5432 }
5434 // The scope spec must refer to a class, or be dependent.
5435 CXXScopeSpec &SS = DeclType.Mem.Scope();
5436
5437 // Handle pointer nullability.
5438 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5439 DeclType.EndLoc, DeclType.getAttrs(),
5440 state.getDeclarator().getAttributePool());
5441
5442 if (SS.isInvalid()) {
5443 // Avoid emitting extra errors if we already errored on the scope.
5444 D.setInvalidType(true);
5445 AreDeclaratorChunksValid = false;
5446 } else {
5447 T = S.BuildMemberPointerType(T, SS, /*Cls=*/nullptr, DeclType.Loc,
5448 D.getIdentifier());
5449 }
5450
5451 if (T.isNull()) {
5452 T = Context.IntTy;
5453 D.setInvalidType(true);
5454 AreDeclaratorChunksValid = false;
5455 } else if (DeclType.Mem.TypeQuals) {
5456 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
5457 }
5458 break;
5459 }
5460
5461 case DeclaratorChunk::Pipe: {
5462 T = S.BuildReadPipeType(T, DeclType.Loc);
5465 break;
5466 }
5467 }
5468
5469 if (T.isNull()) {
5470 D.setInvalidType(true);
5471 T = Context.IntTy;
5472 AreDeclaratorChunksValid = false;
5473 }
5474
5475 // See if there are any attributes on this declarator chunk.
5476 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs(),
5478
5479 if (DeclType.Kind != DeclaratorChunk::Paren) {
5480 if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
5481 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5482
5483 ExpectNoDerefChunk = state.didParseNoDeref();
5484 }
5485 }
5486
5487 if (ExpectNoDerefChunk)
5488 S.Diag(state.getDeclarator().getBeginLoc(),
5489 diag::warn_noderef_on_non_pointer_or_array);
5490
5491 // GNU warning -Wstrict-prototypes
5492 // Warn if a function declaration or definition is without a prototype.
5493 // This warning is issued for all kinds of unprototyped function
5494 // declarations (i.e. function type typedef, function pointer etc.)
5495 // C99 6.7.5.3p14:
5496 // The empty list in a function declarator that is not part of a definition
5497 // of that function specifies that no information about the number or types
5498 // of the parameters is supplied.
5499 // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of
5500 // function declarations whose behavior changes in C23.
5501 if (!LangOpts.requiresStrictPrototypes()) {
5502 bool IsBlock = false;
5503 for (const DeclaratorChunk &DeclType : D.type_objects()) {
5504 switch (DeclType.Kind) {
5506 IsBlock = true;
5507 break;
5509 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5510 // We suppress the warning when there's no LParen location, as this
5511 // indicates the declaration was an implicit declaration, which gets
5512 // warned about separately via -Wimplicit-function-declaration. We also
5513 // suppress the warning when we know the function has a prototype.
5514 if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic &&
5515 FTI.getLParenLoc().isValid())
5516 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5517 << IsBlock
5518 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5519 IsBlock = false;
5520 break;
5521 }
5522 default:
5523 break;
5524 }
5525 }
5526 }
5527
5528 assert(!T.isNull() && "T must not be null after this point");
5529
5530 if (LangOpts.CPlusPlus && T->isFunctionType()) {
5531 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5532 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
5533
5534 // C++ 8.3.5p4:
5535 // A cv-qualifier-seq shall only be part of the function type
5536 // for a nonstatic member function, the function type to which a pointer
5537 // to member refers, or the top-level function type of a function typedef
5538 // declaration.
5539 //
5540 // Core issue 547 also allows cv-qualifiers on function types that are
5541 // top-level template type arguments.
5542 enum {
5543 NonMember,
5544 Member,
5545 ExplicitObjectMember,
5546 DeductionGuide
5547 } Kind = NonMember;
5549 Kind = DeductionGuide;
5550 else if (!D.getCXXScopeSpec().isSet()) {
5554 Kind = Member;
5555 } else {
5557 if (!DC || DC->isRecord())
5558 Kind = Member;
5559 }
5560
5561 if (Kind == Member) {
5562 unsigned I;
5563 if (D.isFunctionDeclarator(I)) {
5564 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5565 if (Chunk.Fun.NumParams) {
5566 auto *P = dyn_cast_or_null<ParmVarDecl>(Chunk.Fun.Params->Param);
5567 if (P && P->isExplicitObjectParameter())
5568 Kind = ExplicitObjectMember;
5569 }
5570 }
5571 }
5572
5573 // C++11 [dcl.fct]p6 (w/DR1417):
5574 // An attempt to specify a function type with a cv-qualifier-seq or a
5575 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5576 // - the function type for a non-static member function,
5577 // - the function type to which a pointer to member refers,
5578 // - the top-level function type of a function typedef declaration or
5579 // alias-declaration,
5580 // - the type-id in the default argument of a type-parameter, or
5581 // - the type-id of a template-argument for a type-parameter
5582 //
5583 // C++23 [dcl.fct]p6 (P0847R7)
5584 // ... A member-declarator with an explicit-object-parameter-declaration
5585 // shall not include a ref-qualifier or a cv-qualifier-seq and shall not be
5586 // declared static or virtual ...
5587 //
5588 // FIXME: Checking this here is insufficient. We accept-invalid on:
5589 //
5590 // template<typename T> struct S { void f(T); };
5591 // S<int() const> s;
5592 //
5593 // ... for instance.
5594 if (IsQualifiedFunction &&
5595 // Check for non-static member function and not and
5596 // explicit-object-parameter-declaration
5597 (Kind != Member || D.isExplicitObjectMemberFunction() ||
5600 D.isStaticMember())) &&
5601 !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg &&
5604 SourceLocation Loc = D.getBeginLoc();
5605 SourceRange RemovalRange;
5606 unsigned I;
5607 if (D.isFunctionDeclarator(I)) {
5609 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5610 assert(Chunk.Kind == DeclaratorChunk::Function);
5611
5612 if (Chunk.Fun.hasRefQualifier())
5613 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5614
5615 if (Chunk.Fun.hasMethodTypeQualifiers())
5617 [&](DeclSpec::TQ TypeQual, StringRef QualName,
5618 SourceLocation SL) { RemovalLocs.push_back(SL); });
5619
5620 if (!RemovalLocs.empty()) {
5621 llvm::sort(RemovalLocs,
5623 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5624 Loc = RemovalLocs.front();
5625 }
5626 }
5627
5628 S.Diag(Loc, diag::err_invalid_qualified_function_type)
5629 << Kind << D.isFunctionDeclarator() << T
5631 << FixItHint::CreateRemoval(RemovalRange);
5632
5633 // Strip the cv-qualifiers and ref-qualifiers from the type.
5636 EPI.RefQualifier = RQ_None;
5637
5638 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5639 EPI);
5640 // Rebuild any parens around the identifier in the function type.
5641 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5643 break;
5644 T = S.BuildParenType(T);
5645 }
5646 }
5647 }
5648
5649 // Apply any undistributed attributes from the declaration or declarator.
5650 ParsedAttributesView NonSlidingAttrs;
5651 for (ParsedAttr &AL : D.getDeclarationAttributes()) {
5652 if (!AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
5653 NonSlidingAttrs.addAtEnd(&AL);
5654 }
5655 }
5656 processTypeAttrs(state, T, TAL_DeclName, NonSlidingAttrs);
5658
5659 // Diagnose any ignored type attributes.
5660 state.diagnoseIgnoredTypeAttrs(T);
5661
5662 // C++0x [dcl.constexpr]p9:
5663 // A constexpr specifier used in an object declaration declares the object
5664 // as const.
5666 T->isObjectType())
5667 T.addConst();
5668
5669 // C++2a [dcl.fct]p4:
5670 // A parameter with volatile-qualified type is deprecated
5671 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 &&
5674 S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T;
5675
5676 // If there was an ellipsis in the declarator, the declaration declares a
5677 // parameter pack whose type may be a pack expansion type.
5678 if (D.hasEllipsis()) {
5679 // C++0x [dcl.fct]p13:
5680 // A declarator-id or abstract-declarator containing an ellipsis shall
5681 // only be used in a parameter-declaration. Such a parameter-declaration
5682 // is a parameter pack (14.5.3). [...]
5683 switch (D.getContext()) {
5687 // C++0x [dcl.fct]p13:
5688 // [...] When it is part of a parameter-declaration-clause, the
5689 // parameter pack is a function parameter pack (14.5.3). The type T
5690 // of the declarator-id of the function parameter pack shall contain
5691 // a template parameter pack; each template parameter pack in T is
5692 // expanded by the function parameter pack.
5693 //
5694 // We represent function parameter packs as function parameters whose
5695 // type is a pack expansion.
5696 if (!T->containsUnexpandedParameterPack() &&
5697 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) {
5698 S.Diag(D.getEllipsisLoc(),
5699 diag::err_function_parameter_pack_without_parameter_packs)
5700 << T << D.getSourceRange();
5702 } else {
5703 T = Context.getPackExpansionType(T, std::nullopt,
5704 /*ExpectPackInType=*/false);
5705 }
5706 break;
5708 // C++0x [temp.param]p15:
5709 // If a template-parameter is a [...] is a parameter-declaration that
5710 // declares a parameter pack (8.3.5), then the template-parameter is a
5711 // template parameter pack (14.5.3).
5712 //
5713 // Note: core issue 778 clarifies that, if there are any unexpanded
5714 // parameter packs in the type of the non-type template parameter, then
5715 // it expands those parameter packs.
5716 if (T->containsUnexpandedParameterPack())
5717 T = Context.getPackExpansionType(T, std::nullopt);
5718 else
5719 S.Diag(D.getEllipsisLoc(),
5720 LangOpts.CPlusPlus11
5721 ? diag::warn_cxx98_compat_variadic_templates
5722 : diag::ext_variadic_templates);
5723 break;
5724
5727 case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here?
5728 case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here?
5749 // FIXME: We may want to allow parameter packs in block-literal contexts
5750 // in the future.
5751 S.Diag(D.getEllipsisLoc(),
5752 diag::err_ellipsis_in_declarator_not_parameter);
5754 break;
5755 }
5756 }
5757
5758 assert(!T.isNull() && "T must not be null at the end of this function");
5759 if (!AreDeclaratorChunksValid)
5760 return Context.getTrivialTypeSourceInfo(T);
5761
5762 if (state.didParseHLSLParamMod() && !T->isConstantArrayType())
5764 return GetTypeSourceInfoForDeclarator(state, T, TInfo);
5765}
5766
5768 // Determine the type of the declarator. Not all forms of declarator
5769 // have a type.
5770
5771 TypeProcessingState state(*this, D);
5772
5773 TypeSourceInfo *ReturnTypeInfo = nullptr;
5774 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5775 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5776 inferARCWriteback(state, T);
5777
5778 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5779}
5780
5782 QualType &declSpecTy,
5783 Qualifiers::ObjCLifetime ownership) {
5784 if (declSpecTy->isObjCRetainableType() &&
5785 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5786 Qualifiers qs;
5787 qs.addObjCLifetime(ownership);
5788 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5789 }
5790}
5791
5792static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5793 Qualifiers::ObjCLifetime ownership,
5794 unsigned chunkIndex) {
5795 Sema &S = state.getSema();
5796 Declarator &D = state.getDeclarator();
5797
5798 // Look for an explicit lifetime attribute.
5799 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5800 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
5801 return;
5802
5803 const char *attrStr = nullptr;
5804 switch (ownership) {
5805 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5806 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5807 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5808 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5809 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5810 }
5811
5812 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5813 Arg->setIdentifierInfo(&S.Context.Idents.get(attrStr));
5814
5815 ArgsUnion Args(Arg);
5816
5817 // If there wasn't one, add one (with an invalid source location
5818 // so that we don't make an AttributedType for it).
5819 ParsedAttr *attr =
5820 D.getAttributePool().create(&S.Context.Idents.get("objc_ownership"),
5822 /*args*/ &Args, 1, ParsedAttr::Form::GNU());
5823 chunk.getAttrs().addAtEnd(attr);
5824 // TODO: mark whether we did this inference?
5825}
5826
5827/// Used for transferring ownership in casts resulting in l-values.
5828static void transferARCOwnership(TypeProcessingState &state,
5829 QualType &declSpecTy,
5830 Qualifiers::ObjCLifetime ownership) {
5831 Sema &S = state.getSema();
5832 Declarator &D = state.getDeclarator();
5833
5834 int inner = -1;
5835 bool hasIndirection = false;
5836 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5837 DeclaratorChunk &chunk = D.getTypeObject(i);
5838 switch (chunk.Kind) {
5840 // Ignore parens.
5841 break;
5842
5846 if (inner != -1)
5847 hasIndirection = true;
5848 inner = i;
5849 break;
5850
5852 if (inner != -1)
5853 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5854 return;
5855
5859 return;
5860 }
5861 }
5862
5863 if (inner == -1)
5864 return;
5865
5866 DeclaratorChunk &chunk = D.getTypeObject(inner);
5867 if (chunk.Kind == DeclaratorChunk::Pointer) {
5868 if (declSpecTy->isObjCRetainableType())
5869 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5870 if (declSpecTy->isObjCObjectType() && hasIndirection)
5871 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5872 } else {
5873 assert(chunk.Kind == DeclaratorChunk::Array ||
5875 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5876 }
5877}
5878
5880 TypeProcessingState state(*this, D);
5881
5882 TypeSourceInfo *ReturnTypeInfo = nullptr;
5883 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5884
5885 if (getLangOpts().ObjC) {
5886 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
5887 if (ownership != Qualifiers::OCL_None)
5888 transferARCOwnership(state, declSpecTy, ownership);
5889 }
5890
5891 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
5892}
5893
5895 TypeProcessingState &State) {
5896 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
5897}
5898
5900 TypeProcessingState &State) {
5902 State.getSema().HLSL().TakeLocForHLSLAttribute(TL.getTypePtr());
5903 TL.setSourceRange(LocInfo.Range);
5905}
5906
5908 const ParsedAttributesView &Attrs) {
5909 for (const ParsedAttr &AL : Attrs) {
5910 if (AL.getKind() == ParsedAttr::AT_MatrixType) {
5911 MTL.setAttrNameLoc(AL.getLoc());
5912 MTL.setAttrRowOperand(AL.getArgAsExpr(0));
5913 MTL.setAttrColumnOperand(AL.getArgAsExpr(1));
5915 return;
5916 }
5917 }
5918
5919 llvm_unreachable("no matrix_type attribute found at the expected location!");
5920}
5921
5922static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5923 SourceLocation Loc;
5924 switch (Chunk.Kind) {
5929 llvm_unreachable("cannot be _Atomic qualified");
5930
5932 Loc = Chunk.Ptr.AtomicQualLoc;
5933 break;
5934
5938 // FIXME: Provide a source location for the _Atomic keyword.
5939 break;
5940 }
5941
5942 ATL.setKWLoc(Loc);
5944}
5945
5946namespace {
5947 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5948 Sema &SemaRef;
5949 ASTContext &Context;
5950 TypeProcessingState &State;
5951 const DeclSpec &DS;
5952
5953 public:
5954 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
5955 const DeclSpec &DS)
5956 : SemaRef(S), Context(Context), State(State), DS(DS) {}
5957
5958 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5959 Visit(TL.getModifiedLoc());
5960 fillAttributedTypeLoc(TL, State);
5961 }
5962 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
5963 Visit(TL.getWrappedLoc());
5964 }
5965 void VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
5966 Visit(TL.getWrappedLoc());
5967 }
5968 void VisitHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL) {
5969 Visit(TL.getWrappedLoc());
5971 }
5972 void VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {}
5973 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
5974 Visit(TL.getInnerLoc());
5975 TL.setExpansionLoc(
5976 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
5977 }
5978 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5979 Visit(TL.getUnqualifiedLoc());
5980 }
5981 // Allow to fill pointee's type locations, e.g.,
5982 // int __attr * __attr * __attr *p;
5983 void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); }
5984 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5985 if (DS.getTypeSpecType() == TST_typename) {
5986 TypeSourceInfo *TInfo = nullptr;
5988 if (TInfo) {
5989 TL.copy(TInfo->getTypeLoc().castAs<TypedefTypeLoc>());
5990 return;
5991 }
5992 }
5993 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
5994 ? DS.getTypeSpecTypeLoc()
5995 : SourceLocation(),
5998 }
5999 void VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6000 if (DS.getTypeSpecType() == TST_typename) {
6001 TypeSourceInfo *TInfo = nullptr;
6003 if (TInfo) {
6004 TL.copy(TInfo->getTypeLoc().castAs<UnresolvedUsingTypeLoc>());
6005 return;
6006 }
6007 }
6008 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6009 ? DS.getTypeSpecTypeLoc()
6010 : SourceLocation(),
6013 }
6014 void VisitUsingTypeLoc(UsingTypeLoc TL) {
6015 if (DS.getTypeSpecType() == TST_typename) {
6016 TypeSourceInfo *TInfo = nullptr;
6018 if (TInfo) {
6019 TL.copy(TInfo->getTypeLoc().castAs<UsingTypeLoc>());
6020 return;
6021 }
6022 }
6023 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6024 ? DS.getTypeSpecTypeLoc()
6025 : SourceLocation(),
6028 }
6029 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6031 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
6032 // addition field. What we have is good enough for display of location
6033 // of 'fixit' on interface name.
6034 TL.setNameEndLoc(DS.getEndLoc());
6035 }
6036 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6037 TypeSourceInfo *RepTInfo = nullptr;
6038 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6039 TL.copy(RepTInfo->getTypeLoc());
6040 }
6041 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6042 TypeSourceInfo *RepTInfo = nullptr;
6043 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6044 TL.copy(RepTInfo->getTypeLoc());
6045 }
6046 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
6047 TypeSourceInfo *TInfo = nullptr;
6049
6050 // If we got no declarator info from previous Sema routines,
6051 // just fill with the typespec loc.
6052 if (!TInfo) {
6053 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
6054 return;
6055 }
6056
6057 TypeLoc OldTL = TInfo->getTypeLoc();
6058 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
6059 assert(TL.getRAngleLoc() ==
6060 OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
6061 }
6062 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6067 }
6068 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6073 assert(DS.getRepAsType());
6074 TypeSourceInfo *TInfo = nullptr;
6076 TL.setUnmodifiedTInfo(TInfo);
6077 }
6078 void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6082 }
6083 void VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
6086 }
6087 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6088 assert(DS.isTransformTypeTrait(DS.getTypeSpecType()));
6091 assert(DS.getRepAsType());
6092 TypeSourceInfo *TInfo = nullptr;
6094 TL.setUnderlyingTInfo(TInfo);
6095 }
6096 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6097 // By default, use the source location of the type specifier.
6099 if (TL.needsExtraLocalData()) {
6100 // Set info for the written builtin specifiers.
6102 // Try to have a meaningful source location.
6103 if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified)
6105 if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified)
6107 }
6108 }
6109 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6110 assert(DS.getTypeSpecType() == TST_typename);
6111 TypeSourceInfo *TInfo = nullptr;
6113 assert(TInfo);
6114 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
6115 }
6116 void VisitAutoTypeLoc(AutoTypeLoc TL) {
6117 assert(DS.getTypeSpecType() == TST_auto ||
6124 if (!DS.isConstrainedAuto())
6125 return;
6126 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
6127 if (!TemplateId)
6128 return;
6129
6130 NestedNameSpecifierLoc NNS =
6131 (DS.getTypeSpecScope().isNotEmpty()
6133 : NestedNameSpecifierLoc());
6134 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
6135 TemplateId->RAngleLoc);
6136 if (TemplateId->NumArgs > 0) {
6137 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6138 TemplateId->NumArgs);
6139 SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
6140 }
6141 DeclarationNameInfo DNI = DeclarationNameInfo(
6142 TL.getTypePtr()->getTypeConstraintConcept()->getDeclName(),
6143 TemplateId->TemplateNameLoc);
6144
6145 NamedDecl *FoundDecl;
6146 if (auto TN = TemplateId->Template.get();
6147 UsingShadowDecl *USD = TN.getAsUsingShadowDecl())
6148 FoundDecl = cast<NamedDecl>(USD);
6149 else
6150 FoundDecl = cast_if_present<NamedDecl>(TN.getAsTemplateDecl());
6151
6152 auto *CR = ConceptReference::Create(
6153 Context, NNS, TemplateId->TemplateKWLoc, DNI, FoundDecl,
6154 /*NamedDecl=*/TL.getTypePtr()->getTypeConstraintConcept(),
6155 ASTTemplateArgumentListInfo::Create(Context, TemplateArgsInfo));
6156 TL.setConceptReference(CR);
6157 }
6158 void VisitDeducedTemplateSpecializationTypeLoc(
6159 DeducedTemplateSpecializationTypeLoc TL) {
6160 assert(DS.getTypeSpecType() == TST_typename);
6161 TypeSourceInfo *TInfo = nullptr;
6163 assert(TInfo);
6164 TL.copy(
6165 TInfo->getTypeLoc().castAs<DeducedTemplateSpecializationTypeLoc>());
6166 }
6167 void VisitTagTypeLoc(TagTypeLoc TL) {
6168 if (DS.getTypeSpecType() == TST_typename) {
6169 TypeSourceInfo *TInfo = nullptr;
6171 if (TInfo) {
6172 TL.copy(TInfo->getTypeLoc().castAs<TagTypeLoc>());
6173 return;
6174 }
6175 }
6176 TL.setElaboratedKeywordLoc(TL.getTypePtr()->getKeyword() !=
6177 ElaboratedTypeKeyword::None
6178 ? DS.getTypeSpecTypeLoc()
6179 : SourceLocation());
6182 }
6183 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6184 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
6185 // or an _Atomic qualifier.
6189
6190 TypeSourceInfo *TInfo = nullptr;
6192 assert(TInfo);
6194 } else {
6195 TL.setKWLoc(DS.getAtomicSpecLoc());
6196 // No parens, to indicate this was spelled as an _Atomic qualifier.
6197 TL.setParensRange(SourceRange());
6198 Visit(TL.getValueLoc());
6199 }
6200 }
6201
6202 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6204
6205 TypeSourceInfo *TInfo = nullptr;
6208 }
6209
6210 void VisitExtIntTypeLoc(BitIntTypeLoc TL) {
6212 }
6213
6214 void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) {
6216 }
6217
6218 void VisitTypeLoc(TypeLoc TL) {
6219 // FIXME: add other typespec types and change this to an assert.
6220 TL.initialize(Context, DS.getTypeSpecTypeLoc());
6221 }
6222 };
6223
6224 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
6225 ASTContext &Context;
6226 TypeProcessingState &State;
6227 const DeclaratorChunk &Chunk;
6228
6229 public:
6230 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
6231 const DeclaratorChunk &Chunk)
6232 : Context(Context), State(State), Chunk(Chunk) {}
6233
6234 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6235 llvm_unreachable("qualified type locs not expected here!");
6236 }
6237 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6238 llvm_unreachable("decayed type locs not expected here!");
6239 }
6240 void VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
6241 llvm_unreachable("array parameter type locs not expected here!");
6242 }
6243
6244 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6245 fillAttributedTypeLoc(TL, State);
6246 }
6247 void VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
6248 // nothing
6249 }
6250 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6251 // nothing
6252 }
6253 void VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
6254 // nothing
6255 }
6256 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6257 // nothing
6258 }
6259 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6260 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
6261 TL.setCaretLoc(Chunk.Loc);
6262 }
6263 void VisitPointerTypeLoc(PointerTypeLoc TL) {
6264 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6265 TL.setStarLoc(Chunk.Loc);
6266 }
6267 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6268 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6269 TL.setStarLoc(Chunk.Loc);
6270 }
6271 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6272 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
6273 TL.setStarLoc(Chunk.Mem.StarLoc);
6274 TL.setQualifierLoc(Chunk.Mem.Scope().getWithLocInContext(Context));
6275 }
6276 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6277 assert(Chunk.Kind == DeclaratorChunk::Reference);
6278 // 'Amp' is misleading: this might have been originally
6279 /// spelled with AmpAmp.
6280 TL.setAmpLoc(Chunk.Loc);
6281 }
6282 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6283 assert(Chunk.Kind == DeclaratorChunk::Reference);
6284 assert(!Chunk.Ref.LValueRef);
6285 TL.setAmpAmpLoc(Chunk.Loc);
6286 }
6287 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
6288 assert(Chunk.Kind == DeclaratorChunk::Array);
6289 TL.setLBracketLoc(Chunk.Loc);
6290 TL.setRBracketLoc(Chunk.EndLoc);
6291 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
6292 }
6293 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6294 assert(Chunk.Kind == DeclaratorChunk::Function);
6295 TL.setLocalRangeBegin(Chunk.Loc);
6296 TL.setLocalRangeEnd(Chunk.EndLoc);
6297
6298 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
6299 TL.setLParenLoc(FTI.getLParenLoc());
6300 TL.setRParenLoc(FTI.getRParenLoc());
6301 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
6302 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
6303 TL.setParam(tpi++, Param);
6304 }
6306 }
6307 void VisitParenTypeLoc(ParenTypeLoc TL) {
6308 assert(Chunk.Kind == DeclaratorChunk::Paren);
6309 TL.setLParenLoc(Chunk.Loc);
6310 TL.setRParenLoc(Chunk.EndLoc);
6311 }
6312 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6313 assert(Chunk.Kind == DeclaratorChunk::Pipe);
6314 TL.setKWLoc(Chunk.Loc);
6315 }
6316 void VisitBitIntTypeLoc(BitIntTypeLoc TL) {
6317 TL.setNameLoc(Chunk.Loc);
6318 }
6319 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6320 TL.setExpansionLoc(Chunk.Loc);
6321 }
6322 void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); }
6323 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) {
6324 TL.setNameLoc(Chunk.Loc);
6325 }
6326 void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6327 TL.setNameLoc(Chunk.Loc);
6328 }
6329 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6330 fillAtomicQualLoc(TL, Chunk);
6331 }
6332 void
6333 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) {
6334 TL.setNameLoc(Chunk.Loc);
6335 }
6336 void VisitMatrixTypeLoc(MatrixTypeLoc TL) {
6337 fillMatrixTypeLoc(TL, Chunk.getAttrs());
6338 }
6339
6340 void VisitTypeLoc(TypeLoc TL) {
6341 llvm_unreachable("unsupported TypeLoc kind in declarator!");
6342 }
6343 };
6344} // end anonymous namespace
6345
6346static void
6348 const ParsedAttributesView &Attrs) {
6349 for (const ParsedAttr &AL : Attrs) {
6350 if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
6351 DASTL.setAttrNameLoc(AL.getLoc());
6352 DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
6354 return;
6355 }
6356 }
6357
6358 llvm_unreachable(
6359 "no address_space attribute found at the expected location!");
6360}
6361
6362/// Create and instantiate a TypeSourceInfo with type source information.
6363///
6364/// \param T QualType referring to the type as written in source code.
6365///
6366/// \param ReturnTypeInfo For declarators whose return type does not show
6367/// up in the normal place in the declaration specifiers (such as a C++
6368/// conversion function), this pointer will refer to a type source information
6369/// for that return type.
6370static TypeSourceInfo *
6371GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
6372 QualType T, TypeSourceInfo *ReturnTypeInfo) {
6373 Sema &S = State.getSema();
6374 Declarator &D = State.getDeclarator();
6375
6377 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
6378
6379 // Handle parameter packs whose type is a pack expansion.
6381 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
6382 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6383 }
6384
6385 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6386 // Microsoft property fields can have multiple sizeless array chunks
6387 // (i.e. int x[][][]). Don't create more than one level of incomplete array.
6388 if (CurrTL.getTypeLocClass() == TypeLoc::IncompleteArray && e != 1 &&
6390 continue;
6391
6392 // An AtomicTypeLoc might be produced by an atomic qualifier in this
6393 // declarator chunk.
6394 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
6396 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
6397 }
6398
6399 bool HasDesugaredTypeLoc = true;
6400 while (HasDesugaredTypeLoc) {
6401 switch (CurrTL.getTypeLocClass()) {
6402 case TypeLoc::MacroQualified: {
6403 auto TL = CurrTL.castAs<MacroQualifiedTypeLoc>();
6404 TL.setExpansionLoc(
6405 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6406 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6407 break;
6408 }
6409
6410 case TypeLoc::Attributed: {
6411 auto TL = CurrTL.castAs<AttributedTypeLoc>();
6412 fillAttributedTypeLoc(TL, State);
6413 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6414 break;
6415 }
6416
6417 case TypeLoc::Adjusted:
6418 case TypeLoc::BTFTagAttributed: {
6419 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6420 break;
6421 }
6422
6423 case TypeLoc::DependentAddressSpace: {
6424 auto TL = CurrTL.castAs<DependentAddressSpaceTypeLoc>();
6426 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
6427 break;
6428 }
6429
6430 default:
6431 HasDesugaredTypeLoc = false;
6432 break;
6433 }
6434 }
6435
6436 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
6437 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6438 }
6439
6440 // If we have different source information for the return type, use
6441 // that. This really only applies to C++ conversion functions.
6442 if (ReturnTypeInfo) {
6443 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
6444 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
6445 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
6446 } else {
6447 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL);
6448 }
6449
6450 return TInfo;
6451}
6452
6453/// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
6455 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6456 // and Sema during declaration parsing. Try deallocating/caching them when
6457 // it's appropriate, instead of allocating them and keeping them around.
6458 LocInfoType *LocT = (LocInfoType *)BumpAlloc.Allocate(sizeof(LocInfoType),
6459 alignof(LocInfoType));
6460 new (LocT) LocInfoType(T, TInfo);
6461 assert(LocT->getTypeClass() != T->getTypeClass() &&
6462 "LocInfoType's TypeClass conflicts with an existing Type class");
6463 return ParsedType::make(QualType(LocT, 0));
6464}
6465
6467 const PrintingPolicy &Policy) const {
6468 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6469 " was used directly instead of getting the QualType through"
6470 " GetTypeFromParser");
6471}
6472
6474 // C99 6.7.6: Type names have no identifier. This is already validated by
6475 // the parser.
6476 assert(D.getIdentifier() == nullptr &&
6477 "Type name should have no identifier!");
6478
6480 QualType T = TInfo->getType();
6481 if (D.isInvalidType())
6482 return true;
6483
6484 // Make sure there are no unused decl attributes on the declarator.
6485 // We don't want to do this for ObjC parameters because we're going
6486 // to apply them to the actual parameter declaration.
6487 // Likewise, we don't want to do this for alias declarations, because
6488 // we are actually going to build a declaration from this eventually.
6493
6494 if (getLangOpts().CPlusPlus) {
6495 // Check that there are no default arguments (C++ only).
6497 }
6498
6499 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
6500 const AutoType *AT = TL.getTypePtr();
6501 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
6502 }
6503 return CreateParsedType(T, TInfo);
6504}
6505
6506//===----------------------------------------------------------------------===//
6507// Type Attribute Processing
6508//===----------------------------------------------------------------------===//
6509
6510/// Build an AddressSpace index from a constant expression and diagnose any
6511/// errors related to invalid address_spaces. Returns true on successfully
6512/// building an AddressSpace index.
6513static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
6514 const Expr *AddrSpace,
6515 SourceLocation AttrLoc) {
6516 if (!AddrSpace->isValueDependent()) {
6517 std::optional<llvm::APSInt> OptAddrSpace =
6518 AddrSpace->getIntegerConstantExpr(S.Context);
6519 if (!OptAddrSpace) {
6520 S.Diag(AttrLoc, diag::err_attribute_argument_type)
6521 << "'address_space'" << AANT_ArgumentIntegerConstant
6522 << AddrSpace->getSourceRange();
6523 return false;
6524 }
6525 llvm::APSInt &addrSpace = *OptAddrSpace;
6526
6527 // Bounds checking.
6528 if (addrSpace.isSigned()) {
6529 if (addrSpace.isNegative()) {
6530 S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
6531 << AddrSpace->getSourceRange();
6532 return false;
6533 }
6534 addrSpace.setIsSigned(false);
6535 }
6536
6537 llvm::APSInt max(addrSpace.getBitWidth());
6538 max =
6540
6541 if (addrSpace > max) {
6542 S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
6543 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
6544 return false;
6545 }
6546
6547 ASIdx =
6548 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
6549 return true;
6550 }
6551
6552 // Default value for DependentAddressSpaceTypes
6553 ASIdx = LangAS::Default;
6554 return true;
6555}
6556
6558 SourceLocation AttrLoc) {
6559 if (!AddrSpace->isValueDependent()) {
6560 if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
6561 AttrLoc))
6562 return QualType();
6563
6564 return Context.getAddrSpaceQualType(T, ASIdx);
6565 }
6566
6567 // A check with similar intentions as checking if a type already has an
6568 // address space except for on a dependent types, basically if the
6569 // current type is already a DependentAddressSpaceType then its already
6570 // lined up to have another address space on it and we can't have
6571 // multiple address spaces on the one pointer indirection
6572 if (T->getAs<DependentAddressSpaceType>()) {
6573 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
6574 return QualType();
6575 }
6576
6577 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
6578}
6579
6581 SourceLocation AttrLoc) {
6582 LangAS ASIdx;
6583 if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
6584 return QualType();
6585 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
6586}
6587
6589 TypeProcessingState &State) {
6590 Sema &S = State.getSema();
6591
6592 // This attribute is only supported in C.
6593 // FIXME: we should implement checkCommonAttributeFeatures() in SemaAttr.cpp
6594 // such that it handles type attributes, and then call that from
6595 // processTypeAttrs() instead of one-off checks like this.
6596 if (!Attr.diagnoseLangOpts(S)) {
6597 Attr.setInvalid();
6598 return;
6599 }
6600
6601 // Check the number of attribute arguments.
6602 if (Attr.getNumArgs() != 1) {
6603 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6604 << Attr << 1;
6605 Attr.setInvalid();
6606 return;
6607 }
6608
6609 // Ensure the argument is a string.
6610 auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6611 if (!StrLiteral) {
6612 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6614 Attr.setInvalid();
6615 return;
6616 }
6617
6618 ASTContext &Ctx = S.Context;
6619 StringRef BTFTypeTag = StrLiteral->getString();
6620 Type = State.getBTFTagAttributedType(
6621 ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type);
6622}
6623
6624/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6625/// specified type. The attribute contains 1 argument, the id of the address
6626/// space for the type.
6628 const ParsedAttr &Attr,
6629 TypeProcessingState &State) {
6630 Sema &S = State.getSema();
6631
6632 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6633 // qualified by an address-space qualifier."
6634 if (Type->isFunctionType()) {
6635 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
6636 Attr.setInvalid();
6637 return;
6638 }
6639
6640 LangAS ASIdx;
6641 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
6642
6643 // Check the attribute arguments.
6644 if (Attr.getNumArgs() != 1) {
6645 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
6646 << 1;
6647 Attr.setInvalid();
6648 return;
6649 }
6650
6651 Expr *ASArgExpr = Attr.getArgAsExpr(0);
6652 LangAS ASIdx;
6653 if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
6654 Attr.setInvalid();
6655 return;
6656 }
6657
6658 ASTContext &Ctx = S.Context;
6659 auto *ASAttr =
6660 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
6661
6662 // If the expression is not value dependent (not templated), then we can
6663 // apply the address space qualifiers just to the equivalent type.
6664 // Otherwise, we make an AttributedType with the modified and equivalent
6665 // type the same, and wrap it in a DependentAddressSpaceType. When this
6666 // dependent type is resolved, the qualifier is added to the equivalent type
6667 // later.
6668 QualType T;
6669 if (!ASArgExpr->isValueDependent()) {
6670 QualType EquivType =
6671 S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
6672 if (EquivType.isNull()) {
6673 Attr.setInvalid();
6674 return;
6675 }
6676 T = State.getAttributedType(ASAttr, Type, EquivType);
6677 } else {
6678 T = State.getAttributedType(ASAttr, Type, Type);
6679 T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
6680 }
6681
6682 if (!T.isNull())
6683 Type = T;
6684 else
6685 Attr.setInvalid();
6686 } else {
6687 // The keyword-based type attributes imply which address space to use.
6688 ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS()
6689 : Attr.asOpenCLLangAS();
6690 if (S.getLangOpts().HLSL)
6691 ASIdx = Attr.asHLSLLangAS();
6692
6693 if (ASIdx == LangAS::Default)
6694 llvm_unreachable("Invalid address space");
6695
6696 if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
6697 Attr.getLoc())) {
6698 Attr.setInvalid();
6699 return;
6700 }
6701
6703 }
6704}
6705
6707 TypeProcessingState &State) {
6708 Sema &S = State.getSema();
6709
6710 // Check for -fexperimental-overflow-behavior-types
6711 if (!S.getLangOpts().OverflowBehaviorTypes) {
6712 S.Diag(Attr.getLoc(), diag::warn_overflow_behavior_attribute_disabled)
6713 << Attr << 1;
6714 Attr.setInvalid();
6715 return;
6716 }
6717
6718 // Check the number of attribute arguments.
6719 if (Attr.getNumArgs() != 1) {
6720 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6721 << Attr << 1;
6722 Attr.setInvalid();
6723 return;
6724 }
6725
6726 // Check that the underlying type is an integer type
6727 if (!Type->isIntegerType()) {
6728 S.Diag(Attr.getLoc(), diag::err_overflow_behavior_non_integer_type)
6729 << Attr << Type.getAsString() << 0; // 0 for attribute
6730 Attr.setInvalid();
6731 return;
6732 }
6733
6734 StringRef KindName = "";
6735 IdentifierInfo *Ident = nullptr;
6736
6737 if (Attr.isArgIdent(0)) {
6738 Ident = Attr.getArgAsIdent(0)->getIdentifierInfo();
6739 KindName = Ident->getName();
6740 }
6741
6742 // Support identifier or string argument types. Failure to provide one of
6743 // these two types results in a diagnostic that hints towards using string
6744 // arguments (either "wrap" or "trap") as this is the most common use
6745 // pattern.
6746 if (!Ident) {
6747 auto *Str = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6748 if (Str)
6749 KindName = Str->getString();
6750 else {
6751 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6753 Attr.setInvalid();
6754 return;
6755 }
6756 }
6757
6758 OverflowBehaviorType::OverflowBehaviorKind Kind;
6759 if (KindName == "wrap") {
6760 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
6761 } else if (KindName == "trap") {
6762 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
6763 } else {
6764 S.Diag(Attr.getLoc(), diag::err_overflow_behavior_unknown_ident)
6765 << KindName << Attr;
6766 Attr.setInvalid();
6767 return;
6768 }
6769
6770 // Check for mixed specifier/attribute usage
6771 const DeclSpec &DS = State.getDeclarator().getDeclSpec();
6772 if (DS.isWrapSpecified() || DS.isTrapSpecified()) {
6773 // We have both specifier and attribute on the same type. If
6774 // OverflowBehaviorKinds are the same we can just warn.
6775 OverflowBehaviorType::OverflowBehaviorKind SpecifierKind =
6776 DS.isWrapSpecified() ? OverflowBehaviorType::OverflowBehaviorKind::Wrap
6777 : OverflowBehaviorType::OverflowBehaviorKind::Trap;
6778
6779 if (SpecifierKind != Kind) {
6780 StringRef SpecifierName = DS.isWrapSpecified() ? "wrap" : "trap";
6781 S.Diag(Attr.getLoc(), diag::err_conflicting_overflow_behaviors)
6782 << 1 << SpecifierName << KindName;
6783 Attr.setInvalid();
6784 return;
6785 }
6786 S.Diag(Attr.getLoc(), diag::warn_redundant_overflow_behaviors_mixed)
6787 << KindName;
6788 Attr.setInvalid();
6789 return;
6790 }
6791
6792 // Check for conflicting overflow behavior attributes
6793 if (const auto *ExistingOBT = Type->getAs<OverflowBehaviorType>()) {
6794 OverflowBehaviorType::OverflowBehaviorKind ExistingKind =
6795 ExistingOBT->getBehaviorKind();
6796 if (ExistingKind != Kind) {
6797 S.Diag(Attr.getLoc(), diag::err_conflicting_overflow_behaviors) << 0;
6798 if (Kind == OverflowBehaviorType::OverflowBehaviorKind::Trap) {
6799 Type = State.getOverflowBehaviorType(Kind,
6800 ExistingOBT->getUnderlyingType());
6801 }
6802 return;
6803 }
6804 } else {
6805 Type = State.getOverflowBehaviorType(Kind, Type);
6806 }
6807}
6808
6809/// handleObjCOwnershipTypeAttr - Process an objc_ownership
6810/// attribute on the specified type.
6811///
6812/// Returns 'true' if the attribute was handled.
6813static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6815 bool NonObjCPointer = false;
6816
6817 if (!type->isDependentType() && !type->isUndeducedType()) {
6818 if (const PointerType *ptr = type->getAs<PointerType>()) {
6819 QualType pointee = ptr->getPointeeType();
6820 if (pointee->isObjCRetainableType() || pointee->isPointerType())
6821 return false;
6822 // It is important not to lose the source info that there was an attribute
6823 // applied to non-objc pointer. We will create an attributed type but
6824 // its type will be the same as the original type.
6825 NonObjCPointer = true;
6826 } else if (!type->isObjCRetainableType()) {
6827 return false;
6828 }
6829
6830 // Don't accept an ownership attribute in the declspec if it would
6831 // just be the return type of a block pointer.
6832 if (state.isProcessingDeclSpec()) {
6833 Declarator &D = state.getDeclarator();
6835 /*onlyBlockPointers=*/true))
6836 return false;
6837 }
6838 }
6839
6840 Sema &S = state.getSema();
6841 SourceLocation AttrLoc = attr.getLoc();
6842 if (AttrLoc.isMacroID())
6843 AttrLoc =
6845
6846 if (!attr.isArgIdent(0)) {
6847 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
6849 attr.setInvalid();
6850 return true;
6851 }
6852
6853 IdentifierInfo *II = attr.getArgAsIdent(0)->getIdentifierInfo();
6854 Qualifiers::ObjCLifetime lifetime;
6855 if (II->isStr("none"))
6857 else if (II->isStr("strong"))
6858 lifetime = Qualifiers::OCL_Strong;
6859 else if (II->isStr("weak"))
6860 lifetime = Qualifiers::OCL_Weak;
6861 else if (II->isStr("autoreleasing"))
6863 else {
6864 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II;
6865 attr.setInvalid();
6866 return true;
6867 }
6868
6869 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6870 // outside of ARC mode.
6871 if (!S.getLangOpts().ObjCAutoRefCount &&
6872 lifetime != Qualifiers::OCL_Weak &&
6873 lifetime != Qualifiers::OCL_ExplicitNone) {
6874 return true;
6875 }
6876
6877 SplitQualType underlyingType = type.split();
6878
6879 // Check for redundant/conflicting ownership qualifiers.
6880 if (Qualifiers::ObjCLifetime previousLifetime
6881 = type.getQualifiers().getObjCLifetime()) {
6882 // If it's written directly, that's an error.
6884 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
6885 << type;
6886 return true;
6887 }
6888
6889 // Otherwise, if the qualifiers actually conflict, pull sugar off
6890 // and remove the ObjCLifetime qualifiers.
6891 if (previousLifetime != lifetime) {
6892 // It's possible to have multiple local ObjCLifetime qualifiers. We
6893 // can't stop after we reach a type that is directly qualified.
6894 const Type *prevTy = nullptr;
6895 while (!prevTy || prevTy != underlyingType.Ty) {
6896 prevTy = underlyingType.Ty;
6897 underlyingType = underlyingType.getSingleStepDesugaredType();
6898 }
6899 underlyingType.Quals.removeObjCLifetime();
6900 }
6901 }
6902
6903 underlyingType.Quals.addObjCLifetime(lifetime);
6904
6905 if (NonObjCPointer) {
6906 StringRef name = attr.getAttrName()->getName();
6907 switch (lifetime) {
6910 break;
6911 case Qualifiers::OCL_Strong: name = "__strong"; break;
6912 case Qualifiers::OCL_Weak: name = "__weak"; break;
6913 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
6914 }
6915 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
6917 }
6918
6919 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
6920 // because having both 'T' and '__unsafe_unretained T' exist in the type
6921 // system causes unfortunate widespread consistency problems. (For example,
6922 // they're not considered compatible types, and we mangle them identicially
6923 // as template arguments.) These problems are all individually fixable,
6924 // but it's easier to just not add the qualifier and instead sniff it out
6925 // in specific places using isObjCInertUnsafeUnretainedType().
6926 //
6927 // Doing this does means we miss some trivial consistency checks that
6928 // would've triggered in ARC, but that's better than trying to solve all
6929 // the coexistence problems with __unsafe_unretained.
6930 if (!S.getLangOpts().ObjCAutoRefCount &&
6931 lifetime == Qualifiers::OCL_ExplicitNone) {
6932 type = state.getAttributedType(
6934 type, type);
6935 return true;
6936 }
6937
6938 QualType origType = type;
6939 if (!NonObjCPointer)
6940 type = S.Context.getQualifiedType(underlyingType);
6941
6942 // If we have a valid source location for the attribute, use an
6943 // AttributedType instead.
6944 if (AttrLoc.isValid()) {
6945 type = state.getAttributedType(::new (S.Context)
6946 ObjCOwnershipAttr(S.Context, attr, II),
6947 origType, type);
6948 }
6949
6950 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
6951 unsigned diagnostic, QualType type) {
6956 diagnostic, type, /*ignored*/ 0));
6957 } else {
6958 S.Diag(loc, diagnostic);
6959 }
6960 };
6961
6962 // Sometimes, __weak isn't allowed.
6963 if (lifetime == Qualifiers::OCL_Weak &&
6964 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
6965
6966 // Use a specialized diagnostic if the runtime just doesn't support them.
6967 unsigned diagnostic =
6968 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
6969 : diag::err_arc_weak_no_runtime);
6970
6971 // In any case, delay the diagnostic until we know what we're parsing.
6972 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
6973
6974 attr.setInvalid();
6975 return true;
6976 }
6977
6978 // Forbid __weak for class objects marked as
6979 // objc_arc_weak_reference_unavailable
6980 if (lifetime == Qualifiers::OCL_Weak) {
6981 if (const ObjCObjectPointerType *ObjT =
6982 type->getAs<ObjCObjectPointerType>()) {
6983 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
6984 if (Class->isArcWeakrefUnavailable()) {
6985 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
6986 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
6987 diag::note_class_declared);
6988 }
6989 }
6990 }
6991 }
6992
6993 return true;
6994}
6995
6996/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
6997/// attribute on the specified type. Returns true to indicate that
6998/// the attribute was handled, false to indicate that the type does
6999/// not permit the attribute.
7000static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7001 QualType &type) {
7002 Sema &S = state.getSema();
7003
7004 // Delay if this isn't some kind of pointer.
7005 if (!type->isPointerType() &&
7006 !type->isObjCObjectPointerType() &&
7007 !type->isBlockPointerType())
7008 return false;
7009
7010 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
7011 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
7012 attr.setInvalid();
7013 return true;
7014 }
7015
7016 // Check the attribute arguments.
7017 if (!attr.isArgIdent(0)) {
7018 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
7020 attr.setInvalid();
7021 return true;
7022 }
7023 Qualifiers::GC GCAttr;
7024 if (attr.getNumArgs() > 1) {
7025 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
7026 << 1;
7027 attr.setInvalid();
7028 return true;
7029 }
7030
7031 IdentifierInfo *II = attr.getArgAsIdent(0)->getIdentifierInfo();
7032 if (II->isStr("weak"))
7033 GCAttr = Qualifiers::Weak;
7034 else if (II->isStr("strong"))
7035 GCAttr = Qualifiers::Strong;
7036 else {
7037 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
7038 << attr << II;
7039 attr.setInvalid();
7040 return true;
7041 }
7042
7043 QualType origType = type;
7044 type = S.Context.getObjCGCQualType(origType, GCAttr);
7045
7046 // Make an attributed type to preserve the source information.
7047 if (attr.getLoc().isValid())
7048 type = state.getAttributedType(
7049 ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type);
7050
7051 return true;
7052}
7053
7054namespace {
7055 /// A helper class to unwrap a type down to a function for the
7056 /// purposes of applying attributes there.
7057 ///
7058 /// Use:
7059 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
7060 /// if (unwrapped.isFunctionType()) {
7061 /// const FunctionType *fn = unwrapped.get();
7062 /// // change fn somehow
7063 /// T = unwrapped.wrap(fn);
7064 /// }
7065 struct FunctionTypeUnwrapper {
7066 enum WrapKind {
7067 Desugar,
7068 Attributed,
7069 Parens,
7070 Array,
7071 Pointer,
7072 BlockPointer,
7073 Reference,
7074 MemberPointer,
7075 MacroQualified,
7076 };
7077
7078 QualType Original;
7079 const FunctionType *Fn;
7080 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
7081
7082 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
7083 while (true) {
7084 const Type *Ty = T.getTypePtr();
7085 if (isa<FunctionType>(Ty)) {
7086 Fn = cast<FunctionType>(Ty);
7087 return;
7088 } else if (isa<ParenType>(Ty)) {
7089 T = cast<ParenType>(Ty)->getInnerType();
7090 Stack.push_back(Parens);
7091 } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) ||
7093 T = cast<ArrayType>(Ty)->getElementType();
7094 Stack.push_back(Array);
7095 } else if (isa<PointerType>(Ty)) {
7096 T = cast<PointerType>(Ty)->getPointeeType();
7097 Stack.push_back(Pointer);
7098 } else if (isa<BlockPointerType>(Ty)) {
7099 T = cast<BlockPointerType>(Ty)->getPointeeType();
7100 Stack.push_back(BlockPointer);
7101 } else if (isa<MemberPointerType>(Ty)) {
7102 T = cast<MemberPointerType>(Ty)->getPointeeType();
7103 Stack.push_back(MemberPointer);
7104 } else if (isa<ReferenceType>(Ty)) {
7105 T = cast<ReferenceType>(Ty)->getPointeeType();
7106 Stack.push_back(Reference);
7107 } else if (isa<AttributedType>(Ty)) {
7108 T = cast<AttributedType>(Ty)->getEquivalentType();
7109 Stack.push_back(Attributed);
7110 } else if (isa<MacroQualifiedType>(Ty)) {
7111 T = cast<MacroQualifiedType>(Ty)->getUnderlyingType();
7112 Stack.push_back(MacroQualified);
7113 } else {
7114 const Type *DTy = Ty->getUnqualifiedDesugaredType();
7115 if (Ty == DTy) {
7116 Fn = nullptr;
7117 return;
7118 }
7119
7120 T = QualType(DTy, 0);
7121 Stack.push_back(Desugar);
7122 }
7123 }
7124 }
7125
7126 bool isFunctionType() const { return (Fn != nullptr); }
7127 const FunctionType *get() const { return Fn; }
7128
7129 QualType wrap(Sema &S, const FunctionType *New) {
7130 // If T wasn't modified from the unwrapped type, do nothing.
7131 if (New == get()) return Original;
7132
7133 Fn = New;
7134 return wrap(S.Context, Original, 0);
7135 }
7136
7137 private:
7138 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
7139 if (I == Stack.size())
7140 return C.getQualifiedType(Fn, Old.getQualifiers());
7141
7142 // Build up the inner type, applying the qualifiers from the old
7143 // type to the new type.
7144 SplitQualType SplitOld = Old.split();
7145
7146 // As a special case, tail-recurse if there are no qualifiers.
7147 if (SplitOld.Quals.empty())
7148 return wrap(C, SplitOld.Ty, I);
7149 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
7150 }
7151
7152 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
7153 if (I == Stack.size()) return QualType(Fn, 0);
7154
7155 switch (static_cast<WrapKind>(Stack[I++])) {
7156 case Desugar:
7157 // This is the point at which we potentially lose source
7158 // information.
7159 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
7160
7161 case Attributed:
7162 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
7163
7164 case Parens: {
7165 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
7166 return C.getParenType(New);
7167 }
7168
7169 case MacroQualified:
7170 return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I);
7171
7172 case Array: {
7173 if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) {
7174 QualType New = wrap(C, CAT->getElementType(), I);
7175 return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(),
7176 CAT->getSizeModifier(),
7177 CAT->getIndexTypeCVRQualifiers());
7178 }
7179
7180 if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) {
7181 QualType New = wrap(C, VAT->getElementType(), I);
7182 return C.getVariableArrayType(New, VAT->getSizeExpr(),
7183 VAT->getSizeModifier(),
7184 VAT->getIndexTypeCVRQualifiers());
7185 }
7186
7187 const auto *IAT = cast<IncompleteArrayType>(Old);
7188 QualType New = wrap(C, IAT->getElementType(), I);
7189 return C.getIncompleteArrayType(New, IAT->getSizeModifier(),
7190 IAT->getIndexTypeCVRQualifiers());
7191 }
7192
7193 case Pointer: {
7194 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
7195 return C.getPointerType(New);
7196 }
7197
7198 case BlockPointer: {
7199 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
7200 return C.getBlockPointerType(New);
7201 }
7202
7203 case MemberPointer: {
7204 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
7205 QualType New = wrap(C, OldMPT->getPointeeType(), I);
7206 return C.getMemberPointerType(New, OldMPT->getQualifier(),
7207 OldMPT->getMostRecentCXXRecordDecl());
7208 }
7209
7210 case Reference: {
7211 const ReferenceType *OldRef = cast<ReferenceType>(Old);
7212 QualType New = wrap(C, OldRef->getPointeeType(), I);
7213 if (isa<LValueReferenceType>(OldRef))
7214 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
7215 else
7216 return C.getRValueReferenceType(New);
7217 }
7218 }
7219
7220 llvm_unreachable("unknown wrapping kind");
7221 }
7222 };
7223} // end anonymous namespace
7224
7225static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
7226 ParsedAttr &PAttr, QualType &Type) {
7227 Sema &S = State.getSema();
7228
7229 Attr *A;
7230 switch (PAttr.getKind()) {
7231 default: llvm_unreachable("Unknown attribute kind");
7232 case ParsedAttr::AT_Ptr32:
7234 break;
7235 case ParsedAttr::AT_Ptr64:
7237 break;
7238 case ParsedAttr::AT_SPtr:
7239 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
7240 break;
7241 case ParsedAttr::AT_UPtr:
7242 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
7243 break;
7244 }
7245
7246 std::bitset<attr::LastAttr> Attrs;
7247 QualType Desugared = Type;
7248 for (;;) {
7249 if (const TypedefType *TT = dyn_cast<TypedefType>(Desugared)) {
7250 Desugared = TT->desugar();
7251 continue;
7252 }
7253 const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
7254 if (!AT)
7255 break;
7256 Attrs[AT->getAttrKind()] = true;
7257 Desugared = AT->getModifiedType();
7258 }
7259
7260 // You cannot specify duplicate type attributes, so if the attribute has
7261 // already been applied, flag it.
7262 attr::Kind NewAttrKind = A->getKind();
7263 if (Attrs[NewAttrKind]) {
7264 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7265 return true;
7266 }
7267 Attrs[NewAttrKind] = true;
7268
7269 // You cannot have both __sptr and __uptr on the same type, nor can you
7270 // have __ptr32 and __ptr64.
7271 if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) {
7272 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7273 << "'__ptr32'"
7274 << "'__ptr64'" << /*isRegularKeyword=*/0;
7275 return true;
7276 } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) {
7277 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7278 << "'__sptr'"
7279 << "'__uptr'" << /*isRegularKeyword=*/0;
7280 return true;
7281 }
7282
7283 // Check the raw (i.e., desugared) Canonical type to see if it
7284 // is a pointer type.
7285 if (!isa<PointerType>(Desugared)) {
7286 // Pointer type qualifiers can only operate on pointer types, but not
7287 // pointer-to-member types.
7289 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
7290 else
7291 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
7292 return true;
7293 }
7294
7295 // Add address space to type based on its attributes.
7296 LangAS ASIdx = LangAS::Default;
7297 uint64_t PtrWidth =
7299 if (PtrWidth == 32) {
7300 if (Attrs[attr::Ptr64])
7301 ASIdx = LangAS::ptr64;
7302 else if (Attrs[attr::UPtr])
7303 ASIdx = LangAS::ptr32_uptr;
7304 } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) {
7305 if (S.Context.getTargetInfo().getTriple().isOSzOS() || Attrs[attr::UPtr])
7306 ASIdx = LangAS::ptr32_uptr;
7307 else
7308 ASIdx = LangAS::ptr32_sptr;
7309 }
7310
7311 QualType Pointee = Type->getPointeeType();
7312 if (ASIdx != LangAS::Default)
7313 Pointee = S.Context.getAddrSpaceQualType(
7314 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7315
7317 S.Context.getPointerType(Pointee), Type.getQualifiers());
7318 Type = State.getAttributedType(A, Type, Equivalent);
7319 return false;
7320}
7321
7322static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State,
7323 QualType &QT, ParsedAttr &PAttr) {
7324 assert(PAttr.getKind() == ParsedAttr::AT_WebAssemblyFuncref);
7325
7326 Sema &S = State.getSema();
7328
7329 std::bitset<attr::LastAttr> Attrs;
7330 attr::Kind NewAttrKind = A->getKind();
7331 const auto *AT = dyn_cast<AttributedType>(QT);
7332 while (AT) {
7333 Attrs[AT->getAttrKind()] = true;
7334 AT = dyn_cast<AttributedType>(AT->getModifiedType());
7335 }
7336
7337 // You cannot specify duplicate type attributes, so if the attribute has
7338 // already been applied, flag it.
7339 if (Attrs[NewAttrKind]) {
7340 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7341 return true;
7342 }
7343
7344 // Check that the type is a function pointer type.
7345 QualType Desugared = QT.getDesugaredType(S.Context);
7346 const auto *Ptr = dyn_cast<PointerType>(Desugared);
7347 if (!Ptr || !Ptr->getPointeeType()->isFunctionType()) {
7348 S.Diag(PAttr.getLoc(), diag::err_attribute_webassembly_funcref);
7349 return true;
7350 }
7351
7352 // Add address space to type based on its attributes.
7354 QualType Pointee = QT->getPointeeType();
7355 Pointee = S.Context.getAddrSpaceQualType(
7356 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7357
7359 S.Context.getPointerType(Pointee), QT.getQualifiers());
7360 QT = State.getAttributedType(A, QT, Equivalent);
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_OpenCLGlobalDeviceAddressSpace:
9108 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace:
9109 state.getSema().Diag(attr.getLoc(), diag::warn_deprecated_attribute)
9110 << attr;
9111 [[fallthrough]];
9112 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
9113 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
9114 case ParsedAttr::AT_OpenCLLocalAddressSpace:
9115 case ParsedAttr::AT_OpenCLConstantAddressSpace:
9116 case ParsedAttr::AT_OpenCLGenericAddressSpace:
9117 case ParsedAttr::AT_AddressSpace:
9119 attr.setUsedAsTypeAttr();
9120 break;
9121 case ParsedAttr::AT_HLSLGroupSharedAddressSpace:
9123 if (state.getDeclarator().getContext() == DeclaratorContext::Prototype) {
9124 if (state.getSema().getLangOpts().getHLSLVersion() <
9126 state.getSema().Diag(attr.getLoc(), diag::warn_hlsl_groupshared_202x);
9127
9128 // Note: we don't check for the usage of HLSLParamModifiers in/out/inout
9129 // here because the check in the AT_HLSLParamModifier case is sufficient
9130 // regardless of the order of groupshared or in/out/inout specified in
9131 // the parameter. And checking there produces a better error message.
9132 }
9133 attr.setUsedAsTypeAttr();
9134 break;
9135 case ParsedAttr::AT_HLSLRowMajor:
9136 case ParsedAttr::AT_HLSLColumnMajor:
9137 if (Attr *A =
9138 state.getSema().HLSL().buildMatrixLayoutTypeAttr(type, attr))
9139 type = state.getAttributedType(A, type, type);
9140 attr.setUsedAsTypeAttr();
9141 break;
9143 if (!handleObjCPointerTypeAttr(state, attr, type))
9145 attr.setUsedAsTypeAttr();
9146 break;
9147 case ParsedAttr::AT_VectorSize:
9148 HandleVectorSizeAttr(type, attr, state.getSema());
9149 attr.setUsedAsTypeAttr();
9150 break;
9151 case ParsedAttr::AT_ExtVectorType:
9152 HandleExtVectorTypeAttr(type, attr, state.getSema());
9153 attr.setUsedAsTypeAttr();
9154 break;
9155 case ParsedAttr::AT_NeonVectorType:
9157 attr.setUsedAsTypeAttr();
9158 break;
9159 case ParsedAttr::AT_NeonPolyVectorType:
9160 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
9162 attr.setUsedAsTypeAttr();
9163 break;
9164 case ParsedAttr::AT_ArmSveVectorBits:
9165 HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema());
9166 attr.setUsedAsTypeAttr();
9167 break;
9168 case ParsedAttr::AT_ArmMveStrictPolymorphism: {
9170 attr.setUsedAsTypeAttr();
9171 break;
9172 }
9173 case ParsedAttr::AT_RISCVRVVVectorBits:
9174 HandleRISCVRVVVectorBitsTypeAttr(type, attr, state.getSema());
9175 attr.setUsedAsTypeAttr();
9176 break;
9177 case ParsedAttr::AT_OpenCLAccess:
9178 HandleOpenCLAccessAttr(type, attr, state.getSema());
9179 attr.setUsedAsTypeAttr();
9180 break;
9181 case ParsedAttr::AT_PointerAuth:
9182 HandlePtrAuthQualifier(state.getSema().Context, type, attr,
9183 state.getSema());
9184 attr.setUsedAsTypeAttr();
9185 break;
9186 case ParsedAttr::AT_LifetimeBound:
9187 if (TAL == TAL_DeclChunk)
9189 break;
9190 case ParsedAttr::AT_LifetimeCaptureBy:
9191 if (TAL == TAL_DeclChunk)
9193 break;
9194 case ParsedAttr::AT_OverflowBehavior:
9196 attr.setUsedAsTypeAttr();
9197 break;
9198
9199 case ParsedAttr::AT_NoDeref: {
9200 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
9201 // See https://github.com/llvm/llvm-project/issues/55790 for details.
9202 // For the time being, we simply emit a warning that the attribute is
9203 // ignored.
9204 if (attr.isStandardAttributeSyntax()) {
9205 state.getSema().Diag(attr.getLoc(), diag::warn_attribute_ignored)
9206 << attr;
9207 break;
9208 }
9209 ASTContext &Ctx = state.getSema().Context;
9210 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
9211 type, type);
9212 attr.setUsedAsTypeAttr();
9213 state.setParsedNoDeref(true);
9214 break;
9215 }
9216
9217 case ParsedAttr::AT_MatrixType:
9218 HandleMatrixTypeAttr(type, attr, state.getSema());
9219 attr.setUsedAsTypeAttr();
9220 break;
9221
9222 case ParsedAttr::AT_WebAssemblyFuncref: {
9224 attr.setUsedAsTypeAttr();
9225 break;
9226 }
9227
9228 case ParsedAttr::AT_HLSLParamModifier: {
9229 HandleHLSLParamModifierAttr(state, type, attr, state.getSema());
9230 if (attrs.hasAttribute(ParsedAttr::AT_HLSLGroupSharedAddressSpace)) {
9231 state.getSema().Diag(attr.getLoc(), diag::err_hlsl_attr_incompatible)
9232 << attr << "'groupshared'";
9233 attr.setInvalid();
9234 return;
9235 }
9236 attr.setUsedAsTypeAttr();
9237 break;
9238 }
9239
9240 case ParsedAttr::AT_SwiftAttr: {
9241 HandleSwiftAttr(state, TAL, type, attr);
9242 break;
9243 }
9244
9247 attr.setUsedAsTypeAttr();
9248 break;
9249
9250
9252 // Either add nullability here or try to distribute it. We
9253 // don't want to distribute the nullability specifier past any
9254 // dependent type, because that complicates the user model.
9255 if (type->canHaveNullability() || type->isDependentType() ||
9256 type->isArrayType() ||
9258 unsigned endIndex;
9259 if (TAL == TAL_DeclChunk)
9260 endIndex = state.getCurrentChunkIndex();
9261 else
9262 endIndex = state.getDeclarator().getNumTypeObjects();
9263 bool allowOnArrayType =
9264 state.getDeclarator().isPrototypeContext() &&
9265 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
9267 allowOnArrayType)) {
9268 attr.setInvalid();
9269 }
9270
9271 attr.setUsedAsTypeAttr();
9272 }
9273 break;
9274
9275 case ParsedAttr::AT_ObjCKindOf:
9276 // '__kindof' must be part of the decl-specifiers.
9277 switch (TAL) {
9278 case TAL_DeclSpec:
9279 break;
9280
9281 case TAL_DeclChunk:
9282 case TAL_DeclName:
9283 state.getSema().Diag(attr.getLoc(),
9284 diag::err_objc_kindof_wrong_position)
9285 << FixItHint::CreateRemoval(attr.getLoc())
9287 state.getDeclarator().getDeclSpec().getBeginLoc(),
9288 "__kindof ");
9289 break;
9290 }
9291
9292 // Apply it regardless.
9293 if (checkObjCKindOfType(state, type, attr))
9294 attr.setInvalid();
9295 break;
9296
9297 case ParsedAttr::AT_NoThrow:
9298 // Exception Specifications aren't generally supported in C mode throughout
9299 // clang, so revert to attribute-based handling for C.
9300 if (!state.getSema().getLangOpts().CPlusPlus)
9301 break;
9302 [[fallthrough]];
9304
9305 attr.setUsedAsTypeAttr();
9306
9307 // Attributes with standard syntax have strict rules for what they
9308 // appertain to and hence should not use the "distribution" logic below.
9309 if (attr.isStandardAttributeSyntax() ||
9310 attr.isRegularKeywordAttribute()) {
9311 if (!handleFunctionTypeAttr(state, attr, type, CFT)) {
9312 diagnoseBadTypeAttribute(state.getSema(), attr, type);
9313 attr.setInvalid();
9314 }
9315 break;
9316 }
9317
9318 // Never process function type attributes as part of the
9319 // declaration-specifiers.
9320 if (TAL == TAL_DeclSpec)
9322
9323 // Otherwise, handle the possible delays.
9324 else if (!handleFunctionTypeAttr(state, attr, type, CFT))
9326 break;
9327 case ParsedAttr::AT_AcquireHandle: {
9328 if (!type->isFunctionType())
9329 return;
9330
9331 if (attr.getNumArgs() != 1) {
9332 state.getSema().Diag(attr.getLoc(),
9333 diag::err_attribute_wrong_number_arguments)
9334 << attr << 1;
9335 attr.setInvalid();
9336 return;
9337 }
9338
9339 StringRef HandleType;
9340 if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType))
9341 return;
9342 type = state.getAttributedType(
9343 AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr),
9344 type, type);
9345 attr.setUsedAsTypeAttr();
9346 break;
9347 }
9348 case ParsedAttr::AT_AnnotateType: {
9350 attr.setUsedAsTypeAttr();
9351 break;
9352 }
9353 case ParsedAttr::AT_HLSLResourceClass:
9354 case ParsedAttr::AT_HLSLResourceDimension:
9355 case ParsedAttr::AT_HLSLIsROV:
9356 case ParsedAttr::AT_HLSLRawBuffer:
9357 case ParsedAttr::AT_HLSLIsArray:
9358 case ParsedAttr::AT_HLSLIsMultiSampled:
9359 case ParsedAttr::AT_HLSLContainedType: {
9360 // Only collect HLSL resource type attributes that are in
9361 // decl-specifier-seq; do not collect attributes on declarations or those
9362 // that get to slide after declaration name.
9363 if (TAL == TAL_DeclSpec &&
9364 state.getSema().HLSL().handleResourceTypeAttr(type, attr))
9365 attr.setUsedAsTypeAttr();
9366 break;
9367 }
9368 }
9369
9370 // Handle attributes that are defined in a macro. We do not want this to be
9371 // applied to ObjC builtin attributes.
9372 if (isa<AttributedType>(type) && attr.hasMacroIdentifier() &&
9373 !type.getQualifiers().hasObjCLifetime() &&
9374 !type.getQualifiers().hasObjCGCAttr() &&
9375 attr.getKind() != ParsedAttr::AT_ObjCGC &&
9376 attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
9377 const IdentifierInfo *MacroII = attr.getMacroIdentifier();
9378 type = state.getSema().Context.getMacroQualifiedType(type, MacroII);
9379 state.setExpansionLocForMacroQualifiedType(
9380 cast<MacroQualifiedType>(type.getTypePtr()),
9381 attr.getMacroExpansionLoc());
9382 }
9383 }
9384}
9385
9387 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
9388 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
9389 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
9390 auto *Def = Var->getDefinition();
9391 if (!Def) {
9392 SourceLocation PointOfInstantiation = E->getExprLoc();
9393 runWithSufficientStackSpace(PointOfInstantiation, [&] {
9394 InstantiateVariableDefinition(PointOfInstantiation, Var);
9395 });
9396 Def = Var->getDefinition();
9397
9398 // If we don't already have a point of instantiation, and we managed
9399 // to instantiate a definition, this is the point of instantiation.
9400 // Otherwise, we don't request an end-of-TU instantiation, so this is
9401 // not a point of instantiation.
9402 // FIXME: Is this really the right behavior?
9403 if (Var->getPointOfInstantiation().isInvalid() && Def) {
9404 assert(Var->getTemplateSpecializationKind() ==
9406 "explicit instantiation with no point of instantiation");
9407 Var->setTemplateSpecializationKind(
9408 Var->getTemplateSpecializationKind(), PointOfInstantiation);
9409 }
9410 }
9411
9412 // Update the type to the definition's type both here and within the
9413 // expression.
9414 if (Def) {
9415 DRE->setDecl(Def);
9416 QualType T = Def->getType();
9417 DRE->setType(T);
9418 // FIXME: Update the type on all intervening expressions.
9419 E->setType(T);
9420 }
9421
9422 // We still go on to try to complete the type independently, as it
9423 // may also require instantiations or diagnostics if it remains
9424 // incomplete.
9425 }
9426 }
9427 }
9428 if (const auto CastE = dyn_cast<ExplicitCastExpr>(E)) {
9429 QualType DestType = CastE->getTypeAsWritten();
9430 if (const auto *IAT = Context.getAsIncompleteArrayType(DestType)) {
9431 // C++20 [expr.static.cast]p.4: ... If T is array of unknown bound,
9432 // this direct-initialization defines the type of the expression
9433 // as U[1]
9434 QualType ResultType = Context.getConstantArrayType(
9435 IAT->getElementType(),
9436 llvm::APInt(Context.getTypeSize(Context.getSizeType()), 1),
9437 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal,
9438 /*IndexTypeQuals=*/0);
9439 E->setType(ResultType);
9440 }
9441 }
9442}
9443
9445 // Incomplete array types may be completed by the initializer attached to
9446 // their definitions. For static data members of class templates and for
9447 // variable templates, we need to instantiate the definition to get this
9448 // initializer and complete the type.
9449 if (E->getType()->isIncompleteArrayType())
9451
9452 // FIXME: Are there other cases which require instantiating something other
9453 // than the type to complete the type of an expression?
9454
9455 return E->getType();
9456}
9457
9459 TypeDiagnoser &Diagnoser) {
9460 return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind,
9461 Diagnoser);
9462}
9463
9464bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
9465 BoundTypeDiagnoser<> Diagnoser(DiagID);
9467}
9468
9470 CompleteTypeKind Kind,
9471 TypeDiagnoser &Diagnoser) {
9472 if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser))
9473 return true;
9474 if (auto *TD = T->getAsTagDecl(); TD && !TD->isCompleteDefinitionRequired()) {
9475 TD->setCompleteDefinitionRequired();
9476 Consumer.HandleTagDeclRequiredDefinition(TD);
9477 }
9478 return false;
9479}
9480
9483 if (!Suggested)
9484 return false;
9485
9486 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
9487 // and isolate from other C++ specific checks.
9489 getLangOpts(), D->getASTContext(), Suggested->getASTContext(),
9490 NonEquivalentDecls, StructuralEquivalenceKind::Default,
9491 /*StrictTypeSpelling=*/false, /*Complain=*/true,
9492 /*ErrorOnTagTypeMismatch=*/true);
9493 return Ctx.IsEquivalent(D, Suggested);
9494}
9495
9497 AcceptableKind Kind, bool OnlyNeedComplete) {
9498 // Easy case: if we don't have modules, all declarations are visible.
9499 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
9500 return true;
9501
9502 // If this definition was instantiated from a template, map back to the
9503 // pattern from which it was instantiated.
9504 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined())
9505 // We're in the middle of defining it; this definition should be treated
9506 // as visible.
9507 return true;
9508
9509 auto DefinitionIsAcceptable = [&](NamedDecl *D) {
9510 // The (primary) definition might be in a visible module.
9511 if (isAcceptable(D, Kind))
9512 return true;
9513
9514 // A visible module might have a merged definition instead.
9517 if (CodeSynthesisContexts.empty() &&
9518 !getLangOpts().ModulesLocalVisibility) {
9519 // Cache the fact that this definition is implicitly visible because
9520 // there is a visible merged definition.
9522 }
9523 return true;
9524 }
9525
9526 return false;
9527 };
9528 auto IsDefinition = [](NamedDecl *D) {
9529 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
9530 return RD->isThisDeclarationADefinition();
9531 if (auto *ED = dyn_cast<EnumDecl>(D))
9532 return ED->isThisDeclarationADefinition();
9533 if (auto *FD = dyn_cast<FunctionDecl>(D))
9534 return FD->isThisDeclarationADefinition();
9535 if (auto *VD = dyn_cast<VarDecl>(D))
9536 return VD->isThisDeclarationADefinition() == VarDecl::Definition;
9537 llvm_unreachable("unexpected decl type");
9538 };
9539 auto FoundAcceptableDefinition = [&](NamedDecl *D) {
9541 return DefinitionIsAcceptable(D);
9542
9543 // See ASTDeclReader::attachPreviousDeclImpl. Now we still
9544 // may demote definition to declaration for decls in haeder modules,
9545 // so avoid looking at its redeclaration to save time.
9546 // NOTE: If we don't demote definition to declarations for decls
9547 // in header modules, remove the condition.
9549 return DefinitionIsAcceptable(D);
9550
9551 for (auto *RD : D->redecls()) {
9552 auto *ND = cast<NamedDecl>(RD);
9553 if (!IsDefinition(ND))
9554 continue;
9555 if (DefinitionIsAcceptable(ND)) {
9556 *Suggested = ND;
9557 return true;
9558 }
9559 }
9560
9561 return false;
9562 };
9563
9564 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9565 if (auto *Pattern = RD->getTemplateInstantiationPattern())
9566 RD = Pattern;
9567 D = RD->getDefinition();
9568 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
9569 if (auto *Pattern = ED->getTemplateInstantiationPattern())
9570 ED = Pattern;
9571 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) {
9572 // If the enum has a fixed underlying type, it may have been forward
9573 // declared. In -fms-compatibility, `enum Foo;` will also forward declare
9574 // the enum and assign it the underlying type of `int`. Since we're only
9575 // looking for a complete type (not a definition), any visible declaration
9576 // of it will do.
9577 *Suggested = nullptr;
9578 for (auto *Redecl : ED->redecls()) {
9579 if (isAcceptable(Redecl, Kind))
9580 return true;
9581 if (Redecl->isThisDeclarationADefinition() ||
9582 (Redecl->isCanonicalDecl() && !*Suggested))
9583 *Suggested = Redecl;
9584 }
9585
9586 return false;
9587 }
9588 D = ED->getDefinition();
9589 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
9590 if (auto *Pattern = FD->getTemplateInstantiationPattern())
9591 FD = Pattern;
9592 D = FD->getDefinition();
9593 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
9594 if (auto *Pattern = VD->getTemplateInstantiationPattern())
9595 VD = Pattern;
9596 D = VD->getDefinition();
9597 }
9598
9599 assert(D && "missing definition for pattern of instantiated definition");
9600
9601 *Suggested = D;
9602
9603 if (FoundAcceptableDefinition(D))
9604 return true;
9605
9606 // The external source may have additional definitions of this entity that are
9607 // visible, so complete the redeclaration chain now and ask again.
9608 if (auto *Source = Context.getExternalSource()) {
9609 Source->CompleteRedeclChain(D);
9610 return FoundAcceptableDefinition(D);
9611 }
9612
9613 return false;
9614}
9615
9616/// Determine whether there is any declaration of \p D that was ever a
9617/// definition (perhaps before module merging) and is currently visible.
9618/// \param D The definition of the entity.
9619/// \param Suggested Filled in with the declaration that should be made visible
9620/// in order to provide a definition of this entity.
9621/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9622/// not defined. This only matters for enums with a fixed underlying
9623/// type, since in all other cases, a type is complete if and only if it
9624/// is defined.
9626 bool OnlyNeedComplete) {
9628 OnlyNeedComplete);
9629}
9630
9631/// Determine whether there is any declaration of \p D that was ever a
9632/// definition (perhaps before module merging) and is currently
9633/// reachable.
9634/// \param D The definition of the entity.
9635/// \param Suggested Filled in with the declaration that should be made
9636/// reachable
9637/// in order to provide a definition of this entity.
9638/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9639/// not defined. This only matters for enums with a fixed underlying
9640/// type, since in all other cases, a type is complete if and only if it
9641/// is defined.
9643 bool OnlyNeedComplete) {
9645 OnlyNeedComplete);
9646}
9647
9648/// Locks in the inheritance model for the given class and all of its bases.
9650 RD = RD->getMostRecentDecl();
9651 if (!RD->hasAttr<MSInheritanceAttr>()) {
9653 bool BestCase = false;
9656 BestCase = true;
9657 IM = RD->calculateInheritanceModel();
9658 break;
9661 break;
9664 break;
9667 break;
9668 }
9669
9672 : RD->getSourceRange();
9673 RD->addAttr(MSInheritanceAttr::CreateImplicit(
9674 S.getASTContext(), BestCase, Loc, MSInheritanceAttr::Spelling(IM)));
9676 }
9677}
9678
9679bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
9680 CompleteTypeKind Kind,
9681 TypeDiagnoser *Diagnoser) {
9682 // FIXME: Add this assertion to make sure we always get instantiation points.
9683 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
9684 // FIXME: Add this assertion to help us flush out problems with
9685 // checking for dependent types and type-dependent expressions.
9686 //
9687 // assert(!T->isDependentType() &&
9688 // "Can't ask whether a dependent type is complete");
9689
9690 if (const auto *MPTy = dyn_cast<MemberPointerType>(T.getCanonicalType())) {
9691 if (CXXRecordDecl *RD = MPTy->getMostRecentCXXRecordDecl();
9692 RD && !RD->isDependentType()) {
9693 CanQualType T = Context.getCanonicalTagType(RD);
9694 if (getLangOpts().CompleteMemberPointers && !RD->isBeingDefined() &&
9695 RequireCompleteType(Loc, T, Kind, diag::err_memptr_incomplete))
9696 return true;
9697
9698 // We lock in the inheritance model once somebody has asked us to ensure
9699 // that a pointer-to-member type is complete.
9700 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9701 (void)isCompleteType(Loc, T);
9702 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
9703 }
9704 }
9705 }
9706
9707 NamedDecl *Def = nullptr;
9709 bool Incomplete = (T->isIncompleteType(&Def) ||
9711
9712 // Check that any necessary explicit specializations are visible. For an
9713 // enum, we just need the declaration, so don't check this.
9714 if (Def && !isa<EnumDecl>(Def))
9716
9717 // If we have a complete type, we're done.
9718 if (!Incomplete) {
9719 NamedDecl *Suggested = nullptr;
9720 if (Def &&
9721 !hasReachableDefinition(Def, &Suggested, /*OnlyNeedComplete=*/true)) {
9722 // If the user is going to see an error here, recover by making the
9723 // definition visible.
9724 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
9725 if (Diagnoser && Suggested)
9727 /*Recover*/ TreatAsComplete);
9728 return !TreatAsComplete;
9729 }
9730 return false;
9731 }
9732
9733 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
9734 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
9735
9736 // Give the external source a chance to provide a definition of the type.
9737 // This is kept separate from completing the redeclaration chain so that
9738 // external sources such as LLDB can avoid synthesizing a type definition
9739 // unless it's actually needed.
9740 if (Tag || IFace) {
9741 // Avoid diagnosing invalid decls as incomplete.
9742 if (Def->isInvalidDecl())
9743 return true;
9744
9745 // Give the external AST source a chance to complete the type.
9746 if (auto *Source = Context.getExternalSource()) {
9747 if (Tag && Tag->hasExternalLexicalStorage())
9748 Source->CompleteType(Tag);
9749 if (IFace && IFace->hasExternalLexicalStorage())
9750 Source->CompleteType(IFace);
9751 // If the external source completed the type, go through the motions
9752 // again to ensure we're allowed to use the completed type.
9753 if (!T->isIncompleteType())
9754 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9755 }
9756 }
9757
9758 // If we have a class template specialization or a class member of a
9759 // class template specialization, or an array with known size of such,
9760 // try to instantiate it.
9761 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
9762 bool Instantiated = false;
9763 bool Diagnosed = false;
9764 if (RD->isDependentContext()) {
9765 // Don't try to instantiate a dependent class (eg, a member template of
9766 // an instantiated class template specialization).
9767 // FIXME: Can this ever happen?
9768 } else if (auto *ClassTemplateSpec =
9769 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
9770 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
9773 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
9774 /*Complain=*/Diagnoser, ClassTemplateSpec->hasStrictPackMatch());
9775 });
9776 Instantiated = true;
9777 }
9778 } else {
9779 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
9780 if (!RD->isBeingDefined() && Pattern) {
9781 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
9782 assert(MSI && "Missing member specialization information?");
9783 // This record was instantiated from a class within a template.
9784 if (MSI->getTemplateSpecializationKind() !=
9787 Diagnosed = InstantiateClass(Loc, RD, Pattern,
9790 /*Complain=*/Diagnoser);
9791 });
9792 Instantiated = true;
9793 }
9794 }
9795 }
9796
9797 if (Instantiated) {
9798 // Instantiate* might have already complained that the template is not
9799 // defined, if we asked it to.
9800 if (Diagnoser && Diagnosed)
9801 return true;
9802 // If we instantiated a definition, check that it's usable, even if
9803 // instantiation produced an error, so that repeated calls to this
9804 // function give consistent answers.
9805 if (!T->isIncompleteType())
9806 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9807 }
9808 }
9809
9810 // FIXME: If we didn't instantiate a definition because of an explicit
9811 // specialization declaration, check that it's visible.
9812
9813 if (!Diagnoser)
9814 return true;
9815
9816 Diagnoser->diagnose(*this, Loc, T);
9817
9818 // If the type was a forward declaration of a class/struct/union
9819 // type, produce a note.
9820 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid())
9821 Diag(Tag->getLocation(), Tag->isBeingDefined()
9822 ? diag::note_type_being_defined
9823 : diag::note_forward_declaration)
9824 << Context.getCanonicalTagType(Tag);
9825
9826 // If the Objective-C class was a forward declaration, produce a note.
9827 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid())
9828 Diag(IFace->getLocation(), diag::note_forward_class);
9829
9830 // If we have external information that we can use to suggest a fix,
9831 // produce a note.
9832 if (ExternalSource)
9833 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
9834
9835 return true;
9836}
9837
9839 CompleteTypeKind Kind, unsigned DiagID) {
9840 BoundTypeDiagnoser<> Diagnoser(DiagID);
9841 return RequireCompleteType(Loc, T, Kind, Diagnoser);
9842}
9843
9844/// Get diagnostic %select index for tag kind for
9845/// literal type diagnostic message.
9846/// WARNING: Indexes apply to particular diagnostics only!
9847///
9848/// \returns diagnostic %select index.
9850 switch (Tag) {
9852 return 0;
9854 return 1;
9855 case TagTypeKind::Class:
9856 return 2;
9857 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
9858 }
9859}
9860
9862 TypeDiagnoser &Diagnoser) {
9863 assert(!T->isDependentType() && "type should not be dependent");
9864
9865 QualType ElemType = Context.getBaseElementType(T);
9866 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
9867 T->isLiteralType(Context))
9868 return false;
9869
9870 Diagnoser.diagnose(*this, Loc, T);
9871
9872 if (T->isVariableArrayType())
9873 return true;
9874
9875 if (!ElemType->isRecordType())
9876 return true;
9877
9878 // A partially-defined class type can't be a literal type, because a literal
9879 // class type must have a trivial destructor (which can't be checked until
9880 // the class definition is complete).
9881 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
9882 return true;
9883
9884 const auto *RD = ElemType->castAsCXXRecordDecl();
9885 // [expr.prim.lambda]p3:
9886 // This class type is [not] a literal type.
9887 if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
9888 Diag(RD->getLocation(), diag::note_non_literal_lambda);
9889 return true;
9890 }
9891
9892 // If the class has virtual base classes, then it's not an aggregate, and
9893 // cannot have any constexpr constructors or a trivial default constructor,
9894 // so is non-literal. This is better to diagnose than the resulting absence
9895 // of constexpr constructors.
9896 if (!getLangOpts().CPlusPlus26 && RD->getNumVBases()) {
9897 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
9898 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
9899 for (const auto &I : RD->vbases())
9900 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
9901 << I.getSourceRange();
9902 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
9903 !RD->hasTrivialDefaultConstructor()) {
9904 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
9905 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
9906 for (const auto &I : RD->bases()) {
9907 if (!I.getType()->isLiteralType(Context)) {
9908 Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
9909 << RD << I.getType() << I.getSourceRange();
9910 return true;
9911 }
9912 }
9913 for (const auto *I : RD->fields()) {
9914 if (!I->getType()->isLiteralType(Context) ||
9915 I->getType().isVolatileQualified()) {
9916 Diag(I->getLocation(), diag::note_non_literal_field)
9917 << RD << I << I->getType()
9918 << I->getType().isVolatileQualified();
9919 return true;
9920 }
9921 }
9922 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor()
9923 : !RD->hasTrivialDestructor()) {
9924 // All fields and bases are of literal types, so have trivial or constexpr
9925 // destructors. If this class's destructor is non-trivial / non-constexpr,
9926 // it must be user-declared.
9927 CXXDestructorDecl *Dtor = RD->getDestructor();
9928 assert(Dtor && "class has literal fields and bases but no dtor?");
9929 if (!Dtor)
9930 return true;
9931
9932 if (getLangOpts().CPlusPlus20) {
9933 Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor)
9934 << RD;
9935 } else {
9936 Diag(Dtor->getLocation(), Dtor->isUserProvided()
9937 ? diag::note_non_literal_user_provided_dtor
9938 : diag::note_non_literal_nontrivial_dtor)
9939 << RD;
9940 if (!Dtor->isUserProvided())
9943 /*Diagnose*/ true);
9944 }
9945 }
9946
9947 return true;
9948}
9949
9951 BoundTypeDiagnoser<> Diagnoser(DiagID);
9952 return RequireLiteralType(Loc, T, Diagnoser);
9953}
9954
9956 assert(!E->hasPlaceholderType() && "unexpected placeholder");
9957
9958 if (!getLangOpts().CPlusPlus && E->refersToBitField())
9959 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
9960 << (Kind == TypeOfKind::Unqualified ? 3 : 2);
9961
9962 if (!E->isTypeDependent()) {
9963 QualType T = E->getType();
9964 if (const TagType *TT = T->getAs<TagType>())
9965 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
9966 }
9967 return Context.getTypeOfExprType(E, Kind);
9968}
9969
9970static void
9973 // Currently, 'counted_by' only allows direct DeclRefExpr to FieldDecl.
9974 auto *CountDecl = cast<DeclRefExpr>(E)->getDecl();
9975 Decls.push_back(TypeCoupledDeclRefInfo(CountDecl, /*IsDref*/ false));
9976}
9977
9979 Expr *CountExpr,
9980 bool CountInBytes,
9981 bool OrNull) {
9982 assert(WrappedTy->isIncompleteArrayType() || WrappedTy->isPointerType());
9983
9985 BuildTypeCoupledDecls(CountExpr, Decls);
9986 /// When the resulting expression is invalid, we still create the AST using
9987 /// the original count expression for the sake of AST dump.
9988 return Context.getCountAttributedType(WrappedTy, CountExpr, CountInBytes,
9989 OrNull, Decls);
9990}
9991
9992/// getDecltypeForExpr - Given an expr, will return the decltype for
9993/// that expression, according to the rules in C++11
9994/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
9996
9997 Expr *IDExpr = E;
9998 if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E))
9999 IDExpr = ImplCastExpr->getSubExpr();
10000
10001 if (auto *PackExpr = dyn_cast<PackIndexingExpr>(E)) {
10002 if (E->isInstantiationDependent())
10003 IDExpr = PackExpr->getPackIdExpression();
10004 else
10005 IDExpr = PackExpr->getSelectedExpr();
10006 }
10007
10008 if (E->isTypeDependent())
10009 return Context.DependentTy;
10010
10011 // C++11 [dcl.type.simple]p4:
10012 // The type denoted by decltype(e) is defined as follows:
10013
10014 // C++20:
10015 // - if E is an unparenthesized id-expression naming a non-type
10016 // template-parameter (13.2), decltype(E) is the type of the
10017 // template-parameter after performing any necessary type deduction
10018 // Note that this does not pick up the implicit 'const' for a template
10019 // parameter object. This rule makes no difference before C++20 so we apply
10020 // it unconditionally.
10021 if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr))
10022 IDExpr = SNTTPE->getReplacement();
10023
10024 // - if e is an unparenthesized id-expression or an unparenthesized class
10025 // member access (5.2.5), decltype(e) is the type of the entity named
10026 // by e. If there is no such entity, or if e names a set of overloaded
10027 // functions, the program is ill-formed;
10028 //
10029 // We apply the same rules for Objective-C ivar and property references.
10030 if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) {
10031 const ValueDecl *VD = DRE->getDecl();
10032 QualType T = VD->getType();
10033 return isa<TemplateParamObjectDecl>(VD) ? T.getUnqualifiedType() : T;
10034 }
10035 if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) {
10036 if (const auto *VD = ME->getMemberDecl())
10037 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
10038 return VD->getType();
10039 } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) {
10040 return IR->getDecl()->getType();
10041 } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) {
10042 if (PR->isExplicitProperty())
10043 return PR->getExplicitProperty()->getType();
10044 } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) {
10045 return PE->getType();
10046 }
10047
10048 // C++11 [expr.lambda.prim]p18:
10049 // Every occurrence of decltype((x)) where x is a possibly
10050 // parenthesized id-expression that names an entity of automatic
10051 // storage duration is treated as if x were transformed into an
10052 // access to a corresponding data member of the closure type that
10053 // would have been declared if x were an odr-use of the denoted
10054 // entity.
10055 if (getCurLambda() && isa<ParenExpr>(IDExpr)) {
10056 if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) {
10057 if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
10058 QualType T = getCapturedDeclRefType(Var, DRE->getLocation());
10059 if (!T.isNull())
10060 return Context.getLValueReferenceType(T);
10061 }
10062 }
10063 }
10064
10065 return Context.getReferenceQualifiedType(E);
10066}
10067
10068QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) {
10069 assert(!E->hasPlaceholderType() && "unexpected placeholder");
10070
10071 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
10072 !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) {
10073 // The expression operand for decltype is in an unevaluated expression
10074 // context, so side effects could result in unintended consequences.
10075 // Exclude instantiation-dependent expressions, because 'decltype' is often
10076 // used to build SFINAE gadgets.
10077 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
10078 }
10079 return Context.getDecltypeType(E, getDecltypeForExpr(E));
10080}
10081
10083 SourceLocation Loc,
10084 SourceLocation EllipsisLoc) {
10085 if (!IndexExpr)
10086 return QualType();
10087
10088 // Diagnose unexpanded packs but continue to improve recovery.
10089 if (!Pattern->containsUnexpandedParameterPack())
10090 Diag(Loc, diag::err_expected_name_of_pack) << Pattern;
10091
10092 QualType Type = BuildPackIndexingType(Pattern, IndexExpr, Loc, EllipsisLoc);
10093
10094 if (!Type.isNull())
10095 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::warn_cxx23_pack_indexing
10096 : diag::ext_pack_indexing);
10097 return Type;
10098}
10099
10101 SourceLocation Loc,
10102 SourceLocation EllipsisLoc,
10103 bool FullySubstituted,
10104 ArrayRef<QualType> Expansions) {
10105
10106 UnsignedOrNone Index = std::nullopt;
10107 if (!IndexExpr->isInstantiationDependent()) {
10108 llvm::APSInt Value;
10110 IndexExpr, Context.getSizeType(), Value, CCEKind::PackIndex);
10111
10112 if (!Res.isUsable() || !Value.isRepresentableByInt64())
10113 return QualType();
10114
10115 IndexExpr = Res.get();
10116 uint64_t V = Value.getZExtValue();
10117 if (FullySubstituted && V >= Expansions.size()) {
10118 Diag(IndexExpr->getBeginLoc(), diag::err_pack_index_out_of_bound)
10119 << V << Pattern << Expansions.size();
10120 return QualType();
10121 }
10122 Index = static_cast<unsigned>(V);
10123 }
10124
10125 return Context.getPackIndexingType(Pattern, IndexExpr, FullySubstituted,
10126 Expansions, Index);
10127}
10128
10130 SourceLocation Loc) {
10131 assert(BaseType->isEnumeralType());
10132 EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl();
10133
10134 S.DiagnoseUseOfDecl(ED, Loc);
10135
10136 QualType Underlying = ED->getIntegerType();
10137 if (Underlying.isNull()) {
10138 Underlying = ED->getDefinition()->getIntegerType();
10139 assert(!Underlying.isNull());
10140 }
10141
10142 return Underlying;
10143}
10144
10146 SourceLocation Loc) {
10147 if (!BaseType->isEnumeralType()) {
10148 Diag(Loc, diag::err_only_enums_have_underlying_types);
10149 return QualType();
10150 }
10151
10152 // The enum could be incomplete if we're parsing its definition or
10153 // recovering from an error.
10154 NamedDecl *FwdDecl = nullptr;
10155 if (BaseType->isIncompleteType(&FwdDecl)) {
10156 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
10157 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
10158 return QualType();
10159 }
10160
10161 return GetEnumUnderlyingType(*this, BaseType, Loc);
10162}
10163
10165 QualType Pointer = BaseType.isReferenceable() || BaseType->isVoidType()
10166 ? BuildPointerType(BaseType.getNonReferenceType(), Loc,
10168 : BaseType;
10169
10170 return Pointer.isNull() ? QualType() : Pointer;
10171}
10172
10174 if (!BaseType->isAnyPointerType())
10175 return BaseType;
10176
10177 return BaseType->getPointeeType();
10178}
10179
10181 QualType Underlying = BaseType.getNonReferenceType();
10182 if (Underlying->isArrayType())
10183 return Context.getDecayedType(Underlying);
10184
10185 if (Underlying->isFunctionType())
10186 return BuiltinAddPointer(BaseType, Loc);
10187
10188 SplitQualType Split = Underlying.getSplitUnqualifiedType();
10189 // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is
10190 // in the same group of qualifiers as 'const' and 'volatile', we're extending
10191 // '__decay(T)' so that it removes all qualifiers.
10192 Split.Quals.removeCVRQualifiers();
10193 return Context.getQualifiedType(Split);
10194}
10195
10197 SourceLocation Loc) {
10198 assert(LangOpts.CPlusPlus);
10200 BaseType.isReferenceable()
10201 ? BuildReferenceType(BaseType,
10202 UKind == UnaryTransformType::AddLvalueReference,
10203 Loc, DeclarationName())
10204 : BaseType;
10205 return Reference.isNull() ? QualType() : Reference;
10206}
10207
10209 SourceLocation Loc) {
10210 if (UKind == UnaryTransformType::RemoveAllExtents)
10211 return Context.getBaseElementType(BaseType);
10212
10213 if (const auto *AT = Context.getAsArrayType(BaseType))
10214 return AT->getElementType();
10215
10216 return BaseType;
10217}
10218
10220 SourceLocation Loc) {
10221 assert(LangOpts.CPlusPlus);
10222 QualType T = BaseType.getNonReferenceType();
10223 if (UKind == UTTKind::RemoveCVRef &&
10224 (T.isConstQualified() || T.isVolatileQualified())) {
10225 Qualifiers Quals;
10226 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
10227 Quals.removeConst();
10228 Quals.removeVolatile();
10229 T = Context.getQualifiedType(Unqual, Quals);
10230 }
10231 return T;
10232}
10233
10235 SourceLocation Loc) {
10236 if ((BaseType->isReferenceType() && UKind != UTTKind::RemoveRestrict) ||
10237 BaseType->isFunctionType())
10238 return BaseType;
10239
10240 Qualifiers Quals;
10241 QualType Unqual = Context.getUnqualifiedArrayType(BaseType, Quals);
10242
10243 if (UKind == UTTKind::RemoveConst || UKind == UTTKind::RemoveCV)
10244 Quals.removeConst();
10245 if (UKind == UTTKind::RemoveVolatile || UKind == UTTKind::RemoveCV)
10246 Quals.removeVolatile();
10247 if (UKind == UTTKind::RemoveRestrict)
10248 Quals.removeRestrict();
10249
10250 return Context.getQualifiedType(Unqual, Quals);
10251}
10252
10254 bool IsMakeSigned,
10255 SourceLocation Loc) {
10256 if (BaseType->isEnumeralType()) {
10257 QualType Underlying = GetEnumUnderlyingType(S, BaseType, Loc);
10258 if (auto *BitInt = dyn_cast<BitIntType>(Underlying)) {
10259 unsigned int Bits = BitInt->getNumBits();
10260 if (Bits > 1)
10261 return S.Context.getBitIntType(!IsMakeSigned, Bits);
10262
10263 S.Diag(Loc, diag::err_make_signed_integral_only)
10264 << IsMakeSigned << /*_BitInt(1)*/ true << BaseType << 1 << Underlying;
10265 return QualType();
10266 }
10267 if (Underlying->isBooleanType()) {
10268 S.Diag(Loc, diag::err_make_signed_integral_only)
10269 << IsMakeSigned << /*_BitInt(1)*/ false << BaseType << 1
10270 << Underlying;
10271 return QualType();
10272 }
10273 }
10274
10275 bool Int128Unsupported = !S.Context.getTargetInfo().hasInt128Type();
10276 std::array<CanQualType *, 6> AllSignedIntegers = {
10279 ArrayRef<CanQualType *> AvailableSignedIntegers(
10280 AllSignedIntegers.data(), AllSignedIntegers.size() - Int128Unsupported);
10281 std::array<CanQualType *, 6> AllUnsignedIntegers = {
10285 ArrayRef<CanQualType *> AvailableUnsignedIntegers(AllUnsignedIntegers.data(),
10286 AllUnsignedIntegers.size() -
10287 Int128Unsupported);
10288 ArrayRef<CanQualType *> *Consider =
10289 IsMakeSigned ? &AvailableSignedIntegers : &AvailableUnsignedIntegers;
10290
10291 uint64_t BaseSize = S.Context.getTypeSize(BaseType);
10292 auto *Result =
10293 llvm::find_if(*Consider, [&S, BaseSize](const CanQual<Type> *T) {
10294 return BaseSize == S.Context.getTypeSize(T->getTypePtr());
10295 });
10296
10297 assert(Result != Consider->end());
10298 return QualType((*Result)->getTypePtr(), 0);
10299}
10300
10302 SourceLocation Loc) {
10303 bool IsMakeSigned = UKind == UnaryTransformType::MakeSigned;
10304 if ((!BaseType->isIntegerType() && !BaseType->isEnumeralType()) ||
10305 BaseType->isBooleanType() ||
10306 (BaseType->isBitIntType() &&
10307 BaseType->getAs<BitIntType>()->getNumBits() < 2)) {
10308 Diag(Loc, diag::err_make_signed_integral_only)
10309 << IsMakeSigned << BaseType->isBitIntType() << BaseType << 0;
10310 return QualType();
10311 }
10312
10313 bool IsNonIntIntegral =
10314 BaseType->isChar16Type() || BaseType->isChar32Type() ||
10315 BaseType->isWideCharType() || BaseType->isEnumeralType();
10316
10317 QualType Underlying =
10318 IsNonIntIntegral
10319 ? ChangeIntegralSignedness(*this, BaseType, IsMakeSigned, Loc)
10320 : IsMakeSigned ? Context.getCorrespondingSignedType(BaseType)
10321 : Context.getCorrespondingUnsignedType(BaseType);
10322 if (Underlying.isNull())
10323 return Underlying;
10324 return Context.getQualifiedType(Underlying, BaseType.getQualifiers());
10325}
10326
10328 SourceLocation Loc) {
10329 if (BaseType->isDependentType())
10330 return Context.getUnaryTransformType(BaseType, BaseType, UKind);
10332 switch (UKind) {
10333 case UnaryTransformType::EnumUnderlyingType: {
10334 Result = BuiltinEnumUnderlyingType(BaseType, Loc);
10335 break;
10336 }
10337 case UnaryTransformType::AddPointer: {
10338 Result = BuiltinAddPointer(BaseType, Loc);
10339 break;
10340 }
10341 case UnaryTransformType::RemovePointer: {
10342 Result = BuiltinRemovePointer(BaseType, Loc);
10343 break;
10344 }
10345 case UnaryTransformType::Decay: {
10346 Result = BuiltinDecay(BaseType, Loc);
10347 break;
10348 }
10349 case UnaryTransformType::AddLvalueReference:
10350 case UnaryTransformType::AddRvalueReference: {
10351 Result = BuiltinAddReference(BaseType, UKind, Loc);
10352 break;
10353 }
10354 case UnaryTransformType::RemoveAllExtents:
10355 case UnaryTransformType::RemoveExtent: {
10356 Result = BuiltinRemoveExtent(BaseType, UKind, Loc);
10357 break;
10358 }
10359 case UnaryTransformType::RemoveCVRef:
10360 case UnaryTransformType::RemoveReference: {
10361 Result = BuiltinRemoveReference(BaseType, UKind, Loc);
10362 break;
10363 }
10364 case UnaryTransformType::RemoveConst:
10365 case UnaryTransformType::RemoveCV:
10366 case UnaryTransformType::RemoveRestrict:
10367 case UnaryTransformType::RemoveVolatile: {
10368 Result = BuiltinChangeCVRQualifiers(BaseType, UKind, Loc);
10369 break;
10370 }
10371 case UnaryTransformType::MakeSigned:
10372 case UnaryTransformType::MakeUnsigned: {
10373 Result = BuiltinChangeSignedness(BaseType, UKind, Loc);
10374 break;
10375 }
10376 }
10377
10378 return !Result.isNull()
10379 ? Context.getUnaryTransformType(BaseType, Result, UKind)
10380 : Result;
10381}
10382
10384 if (!T->isDependentType() && !isa<AutoType>(T)) {
10385 // FIXME: It isn't entirely clear whether incomplete atomic types
10386 // are allowed or not; for simplicity, ban them for the moment.
10387 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
10388 return QualType();
10389
10390 int DisallowedKind = -1;
10391 if (T->isArrayType())
10392 DisallowedKind = 1;
10393 else if (T->isFunctionType())
10394 DisallowedKind = 2;
10395 else if (T->isReferenceType())
10396 DisallowedKind = 3;
10397 else if (T->isAtomicType())
10398 DisallowedKind = 4;
10399 else if (T.hasQualifiers())
10400 DisallowedKind = 5;
10401 else if (T->isSizelessType())
10402 DisallowedKind = 6;
10403 else if (!T.isTriviallyCopyableType(Context) && getLangOpts().CPlusPlus)
10404 // Some other non-trivially-copyable type (probably a C++ class)
10405 DisallowedKind = 7;
10406 else if (T->isBitIntType())
10407 DisallowedKind = 8;
10408 else if (getLangOpts().C23 && T->isUndeducedAutoType())
10409 // _Atomic auto is prohibited in C23
10410 DisallowedKind = 9;
10411
10412 if (DisallowedKind != -1) {
10413 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
10414 return QualType();
10415 }
10416
10417 // FIXME: Do we need any handling for ARC here?
10418 }
10419
10420 // Build the pointer type.
10421 return Context.getAtomicType(T);
10422}
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:505
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:763
#define MS_TYPE_ATTRS_CASELIST
Definition SemaType.cpp:171
#define CALLING_CONV_ATTRS_CASELIST
Definition SemaType.cpp:124
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:673
static bool handleObjCPointerTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType &type)
Definition SemaType.cpp:420
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:119
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:79
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:561
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:148
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:722
static void fillHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL, TypeProcessingState &State)
static void distributeFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr, QualType type)
A function type attribute was written somewhere in a declaration other than on the declarator itself ...
Definition SemaType.cpp:622
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:653
#define NULLABILITY_TYPE_ATTRS_CASELIST
Definition SemaType.cpp:178
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:437
static OpenCLAccessAttr::Spelling getImageAccess(const ParsedAttributesView &Attrs)
Definition SemaType.cpp:877
static void fillMatrixTypeLoc(MatrixTypeLoc MTL, const ParsedAttributesView &Attrs)
static UnaryTransformType::UTTKind TSTToUnaryTransformType(DeclSpec::TST SwitchTST)
Definition SemaType.cpp:885
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:847
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:902
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:693
static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS, unsigned &TypeQuals, QualType TypeSoFar, unsigned RemoveTQs, unsigned DiagID)
Definition SemaType.cpp:819
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:386
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:394
@ TAL_DeclChunk
The attribute is part of a DeclaratorChunk.
Definition SemaType.cpp:398
@ TAL_DeclSpec
The attribute is in the decl-specifier-seq.
Definition SemaType.cpp:396
@ TAL_DeclName
The attribute is immediately after the declaration's name.
Definition SemaType.cpp:400
static bool isOmittedBlockReturnType(const Declarator &D)
isOmittedBlockReturnType - Return true if this declarator is missing a return type because this is a ...
Definition SemaType.cpp:62
static TypeSourceInfo * GetFullTypeForDeclarator(TypeProcessingState &state, QualType declSpecType, TypeSourceInfo *TInfo)
TypeDiagSelector
Definition SemaType.cpp:54
@ TDS_ObjCObjOrBlock
Definition SemaType.cpp:57
@ TDS_Function
Definition SemaType.cpp:55
@ TDS_Pointer
Definition SemaType.cpp:56
static QualType GetEnumUnderlyingType(Sema &S, QualType BaseType, SourceLocation Loc)
static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk)
static AttrT * createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL)
static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy, Declarator &D, unsigned FunctionChunkIndex)
static void processTypeAttrs(TypeProcessingState &state, QualType &type, TypeAttrLocation TAL, const ParsedAttributesView &attrs, CUDAFunctionTarget CFT=CUDAFunctionTarget::HostDevice)
static bool checkMutualExclusion(TypeProcessingState &state, const FunctionProtoType::ExtProtoInfo &EPI, ParsedAttr &Attr, AttributeCommonInfo::Kind OtherKind)
static Attr * getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr)
Defines the clang::SourceLocation class and associated facilities.
Defines various enumerations that describe declaration and type specifiers.
static QualType getPointeeType(const MemRegion *R)
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
__DEVICE__ int max(int __a, int __b)
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
BuiltinVectorTypeInfo getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const
Returns the element type, element count and number of vectors (in case of tuple) for a builtin vector...
TranslationUnitDecl * getTranslationUnitDecl() const
CanQualType LongTy
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
CanQualType Int128Ty
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:823
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:942
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:1814
void setRBracketLoc(SourceLocation Loc)
Definition TypeLoc.h:1822
void setSizeExpr(Expr *Size)
Definition TypeLoc.h:1834
TypeLoc getValueLoc() const
Definition TypeLoc.h:2692
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2704
void setParensRange(SourceRange Range)
Definition TypeLoc.h:2728
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:2476
const NestedNameSpecifierLoc getNestedNameSpecifierLoc() const
Definition TypeLoc.h:2442
SourceLocation getRAngleLoc() const
Definition TypeLoc.h:2492
SourceLocation getLAngleLoc() const
Definition TypeLoc.h:2485
void setConceptReference(ConceptReference *CR)
Definition TypeLoc.h:2436
NamedDecl * getFoundDecl() const
Definition TypeLoc.h:2460
TemplateArgumentLoc getArgLoc(unsigned i) const
Definition TypeLoc.h:2503
unsigned getNumArgs() const
Definition TypeLoc.h:2499
TemplateDecl * getNamedConcept() const
Definition TypeLoc.h:2466
DeclarationNameInfo getConceptNameInfo() const
Definition TypeLoc.h:2472
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2430
TypeLoc getWrappedLoc() const
Definition TypeLoc.h:1060
Comparison function object.
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8356
unsigned getNumBits() const
Definition TypeBase.h:8368
void setCaretLoc(SourceLocation Loc)
Definition TypeLoc.h:1563
Pointer to a block type.
Definition TypeBase.h:3656
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:3241
Kind getKind() const
Definition TypeBase.h:3292
Represents a C++ destructor within a class.
Definition DeclCXX.h:2902
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CXXRecordDecl * getMostRecentDecl()
Definition DeclCXX.h:539
bool hasUserProvidedDefaultConstructor() const
Whether this class has a user-provided default constructor per C++11.
Definition DeclCXX.h:787
bool hasDefinition() const
Definition DeclCXX.h:561
MSInheritanceModel calculateInheritanceModel() const
Calculate what the inheritance model would be for this class.
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1191
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition DeclSpec.h:188
SourceRange getRange() const
Definition DeclSpec.h:82
SourceLocation getBeginLoc() const
Definition DeclSpec.h:86
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
NestedNameSpecifier getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition DeclSpec.h:97
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition DeclSpec.cpp:123
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition DeclSpec.h:186
Represents a canonical, potentially-qualified type.
SourceLocation getBegin() const
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, TemplateDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
TypeLoc getNextTypeLoc() const
Definition TypeLoc.h:429
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition Type.cpp:251
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition Type.cpp:291
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
bool isRecord() const
Definition DeclBase.h:2206
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition DeclBase.h:2718
bool isFunctionOrMethod() const
Definition DeclBase.h:2178
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1281
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
const WrittenBuiltinSpecs & getWrittenBuiltinSpecs() const
Definition DeclSpec.h:896
bool isTypeSpecPipe() const
Definition DeclSpec.h:528
static const TST TST_typeof_unqualType
Definition DeclSpec.h:282
SourceLocation getTypeSpecSignLoc() const
Definition DeclSpec.h:566
bool hasAutoTypeSpec() const
Definition DeclSpec.h:580
static const TST TST_typename
Definition DeclSpec.h:279
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:561
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition DeclSpec.h:698
static const TST TST_char8
Definition DeclSpec.h:255
static const TST TST_BFloat16
Definition DeclSpec.h:262
Expr * getPackIndexingExpr() const
Definition DeclSpec.h:545
TST getTypeSpecType() const
Definition DeclSpec.h:522
SCS getStorageClassSpec() const
Definition DeclSpec.h:486
SourceLocation getOverflowBehaviorLoc() const
Definition DeclSpec.h:624
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:560
bool isTypeSpecSat() const
Definition DeclSpec.h:529
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:559
static const TST TST_auto_type
Definition DeclSpec.h:292
static const TST TST_interface
Definition DeclSpec.h:277
static const TST TST_double
Definition DeclSpec.h:264
static const TST TST_typeofExpr
Definition DeclSpec.h:281
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition DeclSpec.h:602
TemplateIdAnnotation * getRepAsTemplateId() const
Definition DeclSpec.h:551
static const TST TST_union
Definition DeclSpec.h:275
static const TST TST_typename_pack_indexing
Definition DeclSpec.h:286
static const TST TST_char
Definition DeclSpec.h:253
static const TST TST_bool
Definition DeclSpec.h:270
static const TST TST_char16
Definition DeclSpec.h:256
static const TST TST_unknown_anytype
Definition DeclSpec.h:293
TSC getTypeSpecComplex() const
Definition DeclSpec.h:518
static const TST TST_int
Definition DeclSpec.h:258
ParsedType getRepAsType() const
Definition DeclSpec.h:532
static const TST TST_accum
Definition DeclSpec.h:266
static const TST TST_half
Definition DeclSpec.h:261
ParsedAttributes & getAttributes()
Definition DeclSpec.h:880
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:609
bool isTypeAltiVecPixel() const
Definition DeclSpec.h:524
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition DeclSpec.h:631
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:603
static const TST TST_ibm128
Definition DeclSpec.h:269
Expr * getRepAsExpr() const
Definition DeclSpec.h:540
static const TST TST_enum
Definition DeclSpec.h:274
AttributePool & getAttributePool() const
Definition DeclSpec.h:853
bool isWrapSpecified() const
Definition DeclSpec.h:615
static const TST TST_float128
Definition DeclSpec.h:268
static const TST TST_decltype
Definition DeclSpec.h:284
SourceRange getTypeSpecWidthRange() const
Definition DeclSpec.h:564
SourceLocation getTypeSpecTypeNameLoc() const
Definition DeclSpec.h:571
SourceLocation getTypeSpecWidthLoc() const
Definition DeclSpec.h:563
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:604
static const TST TST_typeof_unqualExpr
Definition DeclSpec.h:283
static const TST TST_class
Definition DeclSpec.h:278
TypeSpecifierType TST
Definition DeclSpec.h:250
bool isOverflowBehaviorSpecified() const
Definition DeclSpec.h:621
bool hasTagDefinition() const
Definition DeclSpec.cpp:433
static const TST TST_decimal64
Definition DeclSpec.h:272
unsigned getParsedSpecifiers() const
Return a bitmask of which flavors of specifiers this DeclSpec includes.
Definition DeclSpec.cpp:442
bool isTypeAltiVecBool() const
Definition DeclSpec.h:525
bool isConstrainedAuto() const
Definition DeclSpec.h:530
static const TST TST_wchar
Definition DeclSpec.h:254
SourceLocation getTypeSpecComplexLoc() const
Definition DeclSpec.h:565
static const TST TST_void
Definition DeclSpec.h:252
bool isTypeAltiVecVector() const
Definition DeclSpec.h:523
static const TST TST_bitint
Definition DeclSpec.h:260
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition DeclSpec.cpp:532
static const TST TST_float
Definition DeclSpec.h:263
static const TST TST_atomic
Definition DeclSpec.h:294
bool isTrapSpecified() const
Definition DeclSpec.h:618
static const TST TST_fract
Definition DeclSpec.h:267
Decl * getRepAsDecl() const
Definition DeclSpec.h:536
static const TST TST_float16
Definition DeclSpec.h:265
static bool isTransformTypeTrait(TST T)
Definition DeclSpec.h:458
static const TST TST_unspecified
Definition DeclSpec.h:251
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:606
TypeSpecifierSign getTypeSpecSign() const
Definition DeclSpec.h:519
CXXScopeSpec & getTypeSpecScope()
Definition DeclSpec.h:556
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:567
OverflowBehaviorState getOverflowBehaviorState() const
Definition DeclSpec.h:612
static const TST TST_decltype_auto
Definition DeclSpec.h:285
static const TST TST_error
Definition DeclSpec.h:301
void forEachQualifier(llvm::function_ref< void(TQ, StringRef, SourceLocation)> Handle)
This method calls the passed in handler on each qual being set.
Definition DeclSpec.cpp:427
static const TST TST_decimal32
Definition DeclSpec.h:271
TypeSpecifierWidth getTypeSpecWidth() const
Definition DeclSpec.h:515
static const TST TST_char32
Definition DeclSpec.h:257
static const TST TST_decimal128
Definition DeclSpec.h:273
bool isTypeSpecOwned() const
Definition DeclSpec.h:526
SourceLocation getTypeSpecSatLoc() const
Definition DeclSpec.h:569
SourceRange getTypeofParensRange() const
Definition DeclSpec.h:577
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:607
static const TST TST_int128
Definition DeclSpec.h:259
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:605
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:828
static const TST TST_typeofType
Definition DeclSpec.h:280
static const TST TST_auto
Definition DeclSpec.h:291
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:839
static const TST TST_struct
Definition DeclSpec.h:276
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:550
void addAttr(Attr *A)
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition DeclBase.h:854
bool isInvalidDecl() const
Definition DeclBase.h:596
SourceLocation getLocation() const
Definition DeclBase.h:447
void setImplicit(bool I=true)
Definition DeclBase.h:602
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition DeclBase.h:1066
bool hasAttr() const
Definition DeclBase.h:585
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:435
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition DeclBase.h:882
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
std::string getAsString() const
Retrieve the human-readable string for this name.
NameKind getNameKind() const
Determine what kind of name this is.
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1952
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2508
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2450
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2099
const DeclaratorChunk * getInnermostNonParenChunk() const
Return the innermost (closest to the declarator) chunk of this declarator that is not a parens chunk,...
Definition DeclSpec.h:2476
void AddInnermostTypeInfo(const DeclaratorChunk &TI)
Add a new innermost chunk to this declarator.
Definition DeclSpec.h:2441
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition DeclSpec.h:2562
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2793
const ParsedAttributes & getAttributes() const
Definition DeclSpec.h:2735
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2388
bool hasTrailingReturnType() const
Determine whether a trailing return type was written (at any level) within this declarator.
Definition DeclSpec.h:2660
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2136
bool isExpressionContext() const
Determine whether this declaration appears in a context where an expression could appear.
Definition DeclSpec.h:2604
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition DeclSpec.h:2463
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2765
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2446
const ParsedAttributesView & getDeclarationAttributes() const
Definition DeclSpec.h:2738
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2778
DeclaratorContext getContext() const
Definition DeclSpec.h:2124
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2135
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2118
bool isFirstDeclarator() const
Definition DeclSpec.h:2773
SourceLocation getCommaLoc() const
Definition DeclSpec.h:2774
AttributePool & getAttributePool() const
Definition DeclSpec.h:2108
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2114
bool hasEllipsis() const
Definition DeclSpec.h:2777
ParsedType getTrailingReturnType() const
Get the trailing return type appearing (at any level) within this declarator.
Definition DeclSpec.h:2669
bool isInvalidType() const
Definition DeclSpec.h:2766
bool isExplicitObjectMemberFunction()
Definition DeclSpec.cpp:398
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2134
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition DeclSpec.h:2801
bool isPrototypeContext() const
Definition DeclSpec.h:2126
bool isStaticMember()
Returns true if this declares a static member.
Definition DeclSpec.cpp:389
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2106
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2539
void setEllipsisLoc(SourceLocation EL)
Definition DeclSpec.h:2779
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2382
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:2322
void setDecltypeLoc(SourceLocation Loc)
Definition TypeLoc.h:2319
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:2008
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:2029
Represents an extended address space qualifier where the input address space value is dependent.
Definition TypeBase.h:4175
void copy(DependentNameTypeLoc Loc)
Definition TypeLoc.h:2643
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2127
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2099
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:972
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:741
Wrap a function effect's condition expression in another struct so that FunctionProtoType's TrailingO...
Definition TypeBase.h:5141
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation NameLoc)
Definition TypeLoc.h:744
Represents an enum.
Definition Decl.h:4145
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4318
EnumDecl * getDefinition() const
Definition Decl.h:4257
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:3101
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3097
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:3700
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:526
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isInvalid() const
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:81
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:142
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:131
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:105
A SourceLocation and its associated SourceManager.
unsigned getSpellingLineNumber(bool *Invalid=nullptr) const
A mutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5357
bool insert(const FunctionEffectWithCondition &NewEC, Conflicts &Errs)
Definition Type.cpp:5864
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5389
Represents an abstract function effect, using just an enumeration describing its kind.
Definition TypeBase.h:5034
Kind
Identifies the particular effect.
Definition TypeBase.h:5037
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5221
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5421
Qualifiers getMethodQuals() const
Definition TypeBase.h:5847
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5825
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5710
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5706
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition TypeBase.h:5855
unsigned getNumParams() const
Definition TypeLoc.h:1747
void setLocalRangeBegin(SourceLocation L)
Definition TypeLoc.h:1695
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1711
void setParam(unsigned i, ParmVarDecl *VD)
Definition TypeLoc.h:1754
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1719
void setLocalRangeEnd(SourceLocation L)
Definition TypeLoc.h:1703
void setExceptionSpecRange(SourceRange R)
Definition TypeLoc.h:1733
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4728
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4840
CallingConv getCC() const
Definition TypeBase.h:4787
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4656
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4617
ExtInfo getExtInfo() const
Definition TypeBase.h:4973
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3738
AArch64SMETypeAttributes
The AArch64 SME ACLE (Arm C/C++ Language Extensions) define a number of function type attributes that...
Definition TypeBase.h:4893
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4926
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4922
CallingConv getCallConv() const
Definition TypeBase.h:4972
QualType getReturnType() const
Definition TypeBase.h:4957
bool getHasRegParm() const
Definition TypeBase.h:4959
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:6098
void setAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1645
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3731
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:1404
void setExpansionLoc(SourceLocation Loc)
Definition TypeLoc.h:1414
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition TypeBase.h:6300
void setAttrRowOperand(Expr *e)
Definition TypeLoc.h:2162
void setAttrColumnOperand(Expr *e)
Definition TypeLoc.h:2168
void setAttrOperandParensRange(SourceRange range)
Definition TypeLoc.h:2177
void setAttrNameLoc(SourceLocation loc)
Definition TypeLoc.h:2156
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
Definition TypeBase.h:4472
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1581
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:1590
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3767
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3799
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5701
QualType getPointeeType() const
Definition TypeBase.h:3785
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
bool isHeaderLikeModule() const
Is this module have similar semantics as headers.
Definition Module.h:866
This represents a decl that may have a name.
Definition Decl.h:274
bool isModulePrivate() const
Whether this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:656
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NamespaceAndPrefix getAsNamespaceAndPrefix() const
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace-like entity, stored as a NamespaceBaseDecl*.
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
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:8066
Wraps an ObjCPointerType with source location information.
Definition TypeLoc.h:1617
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1623
Represents a pointer to an Objective C object.
Definition TypeBase.h:8122
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8159
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:2347
A parameter attribute which changes the argument-passing ABI rule for the parameter.
Definition Attr.h:260
void setRParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1446
void setLParenLoc(SourceLocation Loc)
Definition TypeLoc.h:1442
Represents a parameter to a function.
Definition Decl.h:1819
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:2751
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2756
PipeType - OpenCL20.
Definition TypeBase.h:8322
Pointer-authentication qualifiers.
Definition TypeBase.h:153
static PointerAuthQualifier Create(unsigned Key, bool IsAddressDiscriminated, unsigned ExtraDiscriminator, PointerAuthenticationMode AuthenticationMode, bool IsIsaPointer, bool AuthenticatesNullValues)
Definition TypeBase.h:240
@ MaxKey
The maximum supported pointer-authentication key.
Definition TypeBase.h:230
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1550
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3408
SourceLocation getPragmaAssumeNonNullLoc() const
The location of the currently-active #pragma clang assume_nonnull begin.
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8588
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8593
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1469
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition TypeBase.h:1312
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8504
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8544
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
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:8689
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1090
SplitQualType split() const
Divides a QualType into its unqualified type and a set of local qualifiers.
Definition TypeBase.h:8525
SplitQualType getSplitUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8605
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8625
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8550
UnqualTypeLoc getUnqualifiedLoc() const
Definition TypeLoc.h:304
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:496
void addAddressSpace(LangAS space)
Definition TypeBase.h:598
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
void removeObjCLifetime()
Definition TypeBase.h:552
void addCVRUQualifiers(unsigned mask)
Definition TypeBase.h:507
bool hasRestrict() const
Definition TypeBase.h:478
void removeRestrict()
Definition TypeBase.h:480
static Qualifiers fromCVRMask(unsigned CVR)
Definition TypeBase.h:436
bool empty() const
Definition TypeBase.h:648
void setUnaligned(bool flag)
Definition TypeBase.h:513
void removeVolatile()
Definition TypeBase.h:470
std::string getAsString() const
@ MaxAddressSpace
The maximum supported address space number.
Definition TypeBase.h:374
void addObjCLifetime(ObjCLifetime type)
Definition TypeBase.h:553
void setAmpAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1659
QualType getPointeeType() const
Definition TypeBase.h:3705
bool isSpelledAsLValue() const
Definition TypeBase.h:3700
bool isFunctionDeclarationScope() const
isFunctionDeclarationScope - Return true if this scope is a function prototype scope.
Definition Scope.h:479
A generic diagnostic builder for errors which may or may not be deferred.
Definition SemaBase.h:111
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:208
QualType ProcessResourceTypeAttributes(QualType Wrapped)
QualType getInoutParameterType(QualType Ty)
bool isCFError(RecordDecl *D)
IdentifierInfo * getNSErrorIdent()
Retrieve the identifier "NSError".
bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type)
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition Sema.h:1397
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7734
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:864
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:1138
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:8257
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9359
UnaryTransformType::UTTKind UTTKind
Definition Sema.h:15505
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:1532
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:1472
@ AcceptSizeless
Relax the normal rules for complete types so that they include sizeless built-in types.
Definition Sema.h:15190
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:1305
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain, bool PrimaryStrictPackMatch)
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:227
QualType BuildFunctionType(QualType T, MutableArrayRef< QualType > ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI)
Build a function type.
SemaObjC & ObjC()
Definition Sema.h:1517
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:936
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:1777
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:14559
const LangOptions & getLangOpts() const
Definition Sema.h:929
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:1304
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:1303
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2709
SemaHLSL & HLSL()
Definition Sema.h:1482
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:1838
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6519
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:15165
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1340
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:2446
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:647
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1445
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:1527
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:8194
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
bool isAcceptable(const NamedDecl *D, AcceptableKind Kind)
Determine whether a declaration is acceptable (visible/reachable).
Definition Sema.h:15617
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:14045
SourceManager & getSourceManager() const
Definition Sema.h:934
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:4151
@ NTCUK_Copy
Definition Sema.h:4152
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:13788
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15559
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:1583
ASTConsumer & Consumer
Definition Sema.h:1306
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:1308
DiagnosticsEngine & Diags
Definition Sema.h:1307
OpenCLOptions & getOpenCLOptions()
Definition Sema.h:930
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:1833
llvm::BumpPtrAllocator BumpAlloc
Definition Sema.h:1250
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:646
QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, SourceLocation AttrLoc)
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2252
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:3851
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:3982
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3952
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4956
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:696
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual size_t getMaxBitIntWidth() const
Definition TargetInfo.h:702
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:496
virtual bool allowHalfArgsAndReturns() const
Whether half args and returns are supported.
Definition TargetInfo.h:721
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition TargetInfo.h:685
virtual bool hasFloat16Type() const
Determine whether the _Float16 type is supported on this target.
Definition TargetInfo.h:727
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:739
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:724
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition TargetInfo.h:730
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:1953
void copy(TemplateSpecializationTypeLoc Loc)
Definition TypeLoc.h:1956
Declaration of a template type parameter.
static TemplateTypeParmDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation KeyLoc, SourceLocation NameLoc, int D, int P, IdentifierInfo *Id, bool Typename, bool ParameterPack, bool HasTypeConstraint=false, UnsignedOrNone NumExpanded=std::nullopt)
[BoundsSafety] Represents information of declarations referenced by the arguments of the counted_by a...
Definition TypeBase.h:3436
const Type * getTypeForDecl() const
Definition Decl.h:3672
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:890
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:2296
A container of type source information.
Definition TypeBase.h:8475
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:8486
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2549
bool isBlockPointerType() const
Definition TypeBase.h:8761
bool isVoidType() const
Definition TypeBase.h:9113
bool isBooleanType() const
Definition TypeBase.h:9250
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2801
bool isIncompleteArrayType() const
Definition TypeBase.h:8848
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2203
bool isUndeducedAutoType() const
Definition TypeBase.h:8937
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:8840
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isPointerType() const
Definition TypeBase.h:8741
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9157
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9407
bool isReferenceType() const
Definition TypeBase.h:8765
NestedNameSpecifier getPrefix() const
If this type represents a qualified-id, this returns its nested name specifier.
Definition Type.cpp:2003
bool isSizelessBuiltinType() const
Definition Type.cpp:2653
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2731
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:5197
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2770
bool isImageType() const
Definition TypeBase.h:9005
bool isPipeType() const
Definition TypeBase.h:9012
bool isBitIntType() const
Definition TypeBase.h:9016
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8864
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
bool isChar16Type() const
Definition Type.cpp:2245
bool isHalfType() const
Definition TypeBase.h:9117
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2469
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
Definition Type.cpp:2681
bool isMemberPointerType() const
Definition TypeBase.h:8822
bool isAtomicType() const
Definition TypeBase.h:8933
bool isObjCObjectType() const
Definition TypeBase.h:8924
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9256
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2557
bool isFunctionType() const
Definition TypeBase.h:8737
bool isObjCObjectPointerType() const
Definition TypeBase.h:8920
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2783
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2435
bool isAnyPointerType() const
Definition TypeBase.h:8749
TypeClass getTypeClass() const
Definition TypeBase.h:2449
bool isSamplerT() const
Definition TypeBase.h:8985
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9340
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:5434
bool isRecordType() const
Definition TypeBase.h:8868
bool isObjCRetainableType() const
Definition Type.cpp:5465
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5184
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3801
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3696
void setParensRange(SourceRange range)
Definition TypeLoc.h:2255
void setTypeofLoc(SourceLocation Loc)
Definition TypeLoc.h:2231
void setParensRange(SourceRange Range)
Definition TypeLoc.h:2399
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2375
void setUnderlyingTInfo(TypeSourceInfo *TInfo)
Definition TypeLoc.h:2387
Wrapper of type source information for a type with no direct qualifiers.
Definition TypeLoc.h:274
TypeLocClass getTypeLocClass() const
Definition TypeLoc.h:283
UnionParsedType ConversionFunctionId
When Kind == IK_ConversionFunctionId, the type that the conversion function names.
Definition DeclSpec.h:1075
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1248
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1121
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3424
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:932
@ Definition
This declaration is definitely a definition.
Definition Decl.h:1324
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:2076
Represents a GCC generic vector type.
Definition TypeBase.h:4289
VectorKind getVectorKind() const
Definition TypeBase.h:4309
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.
Top level wrappers for InstallAPI frontend operations.
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
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
@ GNUAutoType
__auto_type (GNU extension)
Definition TypeBase.h:1846
@ DecltypeAuto
decltype(auto)
Definition TypeBase.h:1843
llvm::StringRef getParameterABISpelling(ParameterABI kind)
FunctionEffectMode
Used with attributes/effects with a boolean condition, e.g. nonblocking.
Definition Sema.h:454
LLVM_READONLY bool isAsciiIdentifierContinue(unsigned char c)
Definition CharInfo.h:61
CUDAFunctionTarget
Definition Cuda.h:65
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:347
@ Nullable
Values of this type can be null.
Definition Specifiers.h:351
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:356
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:349
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1801
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1804
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1807
llvm::PointerUnion< Expr *, IdentifierLoc * > ArgsUnion
A union of the various pointer types that can be passed to an ParsedAttr as an argument.
Definition ParsedAttr.h:103
@ Success
Annotation was successful.
Definition Parser.h:65
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
Definition DeclSpec.h:1035
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1033
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1031
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:1027
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:1025
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1023
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1017
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:1029
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1019
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:1021
TypeOfKind
The kind of 'typeof' expression we're after.
Definition TypeBase.h:919
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
@ AANT_ArgumentIntegerConstant
@ AANT_ArgumentString
DeclaratorContext
Definition DeclSpec.h:1902
@ Result
The result type of a method or function.
Definition TypeBase.h:906
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:3833
@ SwiftAsyncContext
This parameter (which must have pointer type) uses the special Swift asynchronous context-pointer ABI...
Definition Specifiers.h:400
@ SwiftErrorResult
This parameter (which must have pointer-to-pointer type) uses the special Swift error-result ABI trea...
Definition Specifiers.h:390
@ Ordinary
This parameter uses ordinary ABI rules for its type.
Definition Specifiers.h:381
@ SwiftIndirectResult
This parameter (which must have pointer type) is a Swift indirect result parameter.
Definition Specifiers.h:385
@ SwiftContext
This parameter (which must have pointer type) uses the special Swift context-pointer ABI treatment.
Definition Specifiers.h:395
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition Specifiers.h:319
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
static bool isBlockPointer(Expr *Arg)
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:6045
@ Interface
The "__interface" keyword.
Definition TypeBase.h:6050
@ Struct
The "struct" keyword.
Definition TypeBase.h:6047
@ Class
The "class" keyword.
Definition TypeBase.h:6056
@ Union
The "union" keyword.
Definition TypeBase.h:6053
@ Enum
The "enum" keyword.
Definition TypeBase.h:6059
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:557
@ Type
The name was classified as a type.
Definition Sema.h:559
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:1818
@ Undeduced
Not deduced yet. This is for example an 'auto' which was just parsed.
Definition TypeBase.h:1813
MSInheritanceModel
Assigned inheritance model for a class in the MS C++ ABI.
Definition Specifiers.h:411
@ IgnoreTrivialABI
The triviality of a method unaffected by "trivial_abi".
Definition Sema.h:642
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:385
@ 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:293
@ CC_DeviceKernel
Definition Specifiers.h:292
@ CC_SwiftAsync
Definition Specifiers.h:294
@ CC_X86StdCall
Definition Specifiers.h:281
@ CC_X86FastCall
Definition Specifiers.h:282
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4259
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4268
@ AltiVecVector
is AltiVec vector
Definition TypeBase.h:4253
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4256
@ Neon
is ARM Neon vector
Definition TypeBase.h:4262
@ Generic
not a target-specific vector type
Definition TypeBase.h:4250
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4274
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4277
@ NeonPoly
is ARM Neon polynomial vector
Definition TypeBase.h:4265
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4271
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:839
@ PackIndex
Index of a pack indexing expression or specifier.
Definition Sema.h:846
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:6020
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2248
@ 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:435
OptionalUnsigned< NullabilityKind > NullabilityKindOrNone
Definition Specifiers.h:363
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
unsigned isStar
True if this dimension was [*]. In this case, NumElts is null.
Definition DeclSpec.h:1360
unsigned TypeQuals
The type qualifiers for the array: const/volatile/restrict/__unaligned/_Atomic.
Definition DeclSpec.h:1352
unsigned hasStatic
True if this dimension included the 'static' keyword.
Definition DeclSpec.h:1356
Expr * NumElts
This is the size of the array, or null if [] or [*] was specified.
Definition DeclSpec.h:1365
unsigned TypeQuals
For now, sema will catch these as invalid.
Definition DeclSpec.h:1649
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with ',...)',...
Definition DeclSpec.h:1412
SourceLocation getTrailingReturnTypeLoc() const
Get the trailing-return-type location for this function declarator.
Definition DeclSpec.h:1639
SourceLocation getLParenLoc() const
Definition DeclSpec.h:1554
bool hasTrailingReturnType() const
Determine whether this function declarator had a trailing-return-type.
Definition DeclSpec.h:1630
TypeAndRange * Exceptions
Pointer to a new[]'d array of TypeAndRange objects that contain the types in the function's dynamic e...
Definition DeclSpec.h:1484
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1472
ParsedType getTrailingReturnType() const
Get the trailing-return-type for this function declarator.
Definition DeclSpec.h:1633
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition DeclSpec.h:1421
SourceLocation getExceptionSpecLocBeg() const
Definition DeclSpec.h:1560
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition DeclSpec.h:1475
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition DeclSpec.h:1573
SourceLocation getRParenLoc() const
Definition DeclSpec.h:1558
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:1556
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1447
unsigned getNumExceptions() const
Get the number of dynamic exception specifications.
Definition DeclSpec.h:1616
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition DeclSpec.h:1605
unsigned isAmbiguous
Can this declaration be a constructor-style initializer?
Definition DeclSpec.h:1416
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition DeclSpec.h:1406
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition DeclSpec.h:1598
SourceRange getExceptionSpecRange() const
Definition DeclSpec.h:1568
ExceptionSpecificationType getExceptionSpecType() const
Get the type of exception specification this function has.
Definition DeclSpec.h:1611
Expr * NoexceptExpr
Pointer to the expression in the noexcept-specifier of this function, if it has one.
Definition DeclSpec.h:1488
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
Definition DeclSpec.h:1658
SourceLocation StarLoc
Location of the '*' token.
Definition DeclSpec.h:1660
const IdentifierInfo * Ident
Definition DeclSpec.h:1378
SourceLocation OverflowBehaviorLoc
The location of an __ob_wrap or __ob_trap qualifier, if any.
Definition DeclSpec.h:1328
SourceLocation RestrictQualLoc
The location of the restrict-qualifier, if any.
Definition DeclSpec.h:1319
SourceLocation ConstQualLoc
The location of the const-qualifier, if any.
Definition DeclSpec.h:1313
SourceLocation VolatileQualLoc
The location of the volatile-qualifier, if any.
Definition DeclSpec.h:1316
SourceLocation UnalignedQualLoc
The location of the __unaligned-qualifier, if any.
Definition DeclSpec.h:1325
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/unaligned/atomic.
Definition DeclSpec.h:1310
SourceLocation AtomicQualLoc
The location of the _Atomic-qualifier, if any.
Definition DeclSpec.h:1322
unsigned OverflowBehaviorIsWrap
Whether the overflow behavior qualifier is wrap (true) or trap (false).
Definition DeclSpec.h:1333
bool LValueRef
True if this is an lvalue reference, false if it's an rvalue reference.
Definition DeclSpec.h:1343
bool HasRestrict
The type qualifier: restrict. [GNU] C++ extension.
Definition DeclSpec.h:1341
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1287
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition DeclSpec.h:1707
SourceLocation EndLoc
EndLoc - If valid, the place where this chunck ends.
Definition DeclSpec.h:1297
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl * > DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult(), SourceLocation TrailingReturnTypeLoc=SourceLocation(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition DeclSpec.cpp:132
ReferenceTypeInfo Ref
Definition DeclSpec.h:1684
BlockPointerTypeInfo Cls
Definition DeclSpec.h:1687
MemberPointerTypeInfo Mem
Definition DeclSpec.h:1688
ArrayTypeInfo Arr
Definition DeclSpec.h:1685
SourceLocation Loc
Loc - The place where this type was defined.
Definition DeclSpec.h:1295
FunctionTypeInfo Fun
Definition DeclSpec.h:1686
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
PointerTypeInfo Ptr
Definition DeclSpec.h:1683
Describes whether we've seen any nullability information for the given file.
Definition Sema.h:248
SourceLocation PointerEndLoc
The end location for the first pointer declarator in the file.
Definition Sema.h:255
SourceLocation PointerLoc
The first pointer declarator (of any pointer kind) in the file that does not have a corresponding nul...
Definition Sema.h:251
bool SawTypeNullability
Whether we saw any type nullability annotations in the given file.
Definition Sema.h:261
uint8_t PointerKind
Which kind of pointer declarator we saw.
Definition Sema.h:258
A FunctionEffect plus a potential boolean expression determining whether the effect is declared (e....
Definition TypeBase.h:5158
Holds information about the various types of exception specification.
Definition TypeBase.h:5478
Extra information about a function prototype.
Definition TypeBase.h:5506
FunctionTypeExtraAttributeInfo ExtraAttributeInfo
Definition TypeBase.h:5514
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5511
void setArmSMEAttribute(AArch64SMETypeAttributes Kind, bool Enable=true)
Definition TypeBase.h:5560
StringRef CFISalt
A CFI "salt" that differentiates functions with the same prototype.
Definition TypeBase.h:4883
SmallVector< NamedDecl *, 4 > TemplateParams
Store the list of the template parameters for a generic lambda or an abbreviated function template.
Definition DeclSpec.h:2948
unsigned AutoTemplateParameterDepth
If this is a generic lambda or abbreviated function template, use this as the depth of each 'auto' pa...
Definition DeclSpec.h:2939
static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
Definition Type.cpp:3378
Describes how types, statements, expressions, and declarations should be printed.
Abstract class used to diagnose incomplete types.
Definition Sema.h:8271
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:871
SplitQualType getSingleStepDesugaredType() const
Definition TypeBase.h:8497
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:873
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:876
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.