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