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