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 (VecSize->isNegative()) {
2362 Diag(SizeExpr->getExprLoc(), diag::err_attribute_vec_negative_size);
2363 return QualType();
2364 }
2365
2366 if (CurType->isDependentType())
2367 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2369
2370 // vecSize is specified in bytes - convert to bits.
2371 if (!VecSize->isIntN(61)) {
2372 // Bit size will overflow uint64.
2373 Diag(AttrLoc, diag::err_attribute_size_too_large)
2374 << SizeExpr->getSourceRange() << "vector";
2375 return QualType();
2376 }
2377 uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2378 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2379
2380 if (VectorSizeBits == 0) {
2381 Diag(AttrLoc, diag::err_attribute_zero_size)
2382 << SizeExpr->getSourceRange() << "vector";
2383 return QualType();
2384 }
2385
2386 if (!TypeSize || VectorSizeBits % TypeSize) {
2387 Diag(AttrLoc, diag::err_attribute_invalid_size)
2388 << SizeExpr->getSourceRange();
2389 return QualType();
2390 }
2391
2392 if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2393 Diag(AttrLoc, diag::err_attribute_size_too_large)
2394 << SizeExpr->getSourceRange() << "vector";
2395 return QualType();
2396 }
2397
2398 return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2400}
2401
2403 SourceLocation AttrLoc) {
2404 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2405 // in conjunction with complex types (pointers, arrays, functions, etc.).
2406 //
2407 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2408 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2409 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2410 // of bool aren't allowed.
2411 //
2412 // We explicitly allow bool elements in ext_vector_type for C/C++.
2413 bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus;
2414 if ((!T->isDependentType() && !T->isIntegerType() &&
2415 !T->isRealFloatingType()) ||
2416 (IsNoBoolVecLang && T->isBooleanType())) {
2417 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2418 return QualType();
2419 }
2420
2421 if (const auto *BIT = T->getAs<BitIntType>();
2422 BIT && CheckBitIntElementType(*this, AttrLoc, BIT))
2423 return QualType();
2424
2425 if (!SizeExpr->isTypeDependent() && !SizeExpr->isValueDependent()) {
2426 std::optional<llvm::APSInt> VecSize =
2428 if (!VecSize) {
2429 Diag(AttrLoc, diag::err_attribute_argument_type)
2430 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2431 << SizeExpr->getSourceRange();
2432 return QualType();
2433 }
2434
2435 if (VecSize->isNegative()) {
2436 Diag(SizeExpr->getExprLoc(), diag::err_attribute_vec_negative_size);
2437 return QualType();
2438 }
2439
2440 if (!VecSize->isIntN(32)) {
2441 Diag(AttrLoc, diag::err_attribute_size_too_large)
2442 << SizeExpr->getSourceRange() << "vector";
2443 return QualType();
2444 }
2445 // Unlike gcc's vector_size attribute, the size is specified as the
2446 // number of elements, not the number of bytes.
2447 unsigned VectorSize = static_cast<unsigned>(VecSize->getZExtValue());
2448
2449 if (VectorSize == 0) {
2450 Diag(AttrLoc, diag::err_attribute_zero_size)
2451 << SizeExpr->getSourceRange() << "vector";
2452 return QualType();
2453 }
2454
2455 return Context.getExtVectorType(T, VectorSize);
2456 }
2457
2458 return Context.getDependentSizedExtVectorType(T, SizeExpr, AttrLoc);
2459}
2460
2461QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2462 SourceLocation AttrLoc) {
2463 assert(Context.getLangOpts().MatrixTypes &&
2464 "Should never build a matrix type when it is disabled");
2465
2466 // Check element type, if it is not dependent.
2467 if (!ElementTy->isDependentType() &&
2468 !MatrixType::isValidElementType(ElementTy)) {
2469 Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2470 return QualType();
2471 }
2472
2473 if (const auto *BIT = ElementTy->getAs<BitIntType>();
2474 BIT &&
2475 CheckBitIntElementType(*this, AttrLoc, BIT, /*ForMatrixType=*/true))
2476 return QualType();
2477
2478 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2479 NumRows->isValueDependent() || NumCols->isValueDependent())
2480 return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2481 AttrLoc);
2482
2483 std::optional<llvm::APSInt> ValueRows =
2485 std::optional<llvm::APSInt> ValueColumns =
2487
2488 auto const RowRange = NumRows->getSourceRange();
2489 auto const ColRange = NumCols->getSourceRange();
2490
2491 // Both are row and column expressions are invalid.
2492 if (!ValueRows && !ValueColumns) {
2493 Diag(AttrLoc, diag::err_attribute_argument_type)
2494 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2495 << ColRange;
2496 return QualType();
2497 }
2498
2499 // Only the row expression is invalid.
2500 if (!ValueRows) {
2501 Diag(AttrLoc, diag::err_attribute_argument_type)
2502 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2503 return QualType();
2504 }
2505
2506 // Only the column expression is invalid.
2507 if (!ValueColumns) {
2508 Diag(AttrLoc, diag::err_attribute_argument_type)
2509 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2510 return QualType();
2511 }
2512
2513 // Check the matrix dimensions.
2514 unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2515 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2516 if (MatrixRows == 0 && MatrixColumns == 0) {
2517 Diag(AttrLoc, diag::err_attribute_zero_size)
2518 << "matrix" << RowRange << ColRange;
2519 return QualType();
2520 }
2521 if (MatrixRows == 0) {
2522 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2523 return QualType();
2524 }
2525 if (MatrixColumns == 0) {
2526 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2527 return QualType();
2528 }
2529 if (MatrixRows > Context.getLangOpts().MaxMatrixDimension &&
2530 MatrixColumns > Context.getLangOpts().MaxMatrixDimension) {
2531 Diag(AttrLoc, diag::err_attribute_size_too_large)
2532 << RowRange << ColRange << "matrix row and column";
2533 return QualType();
2534 }
2535 if (MatrixRows > Context.getLangOpts().MaxMatrixDimension) {
2536 Diag(AttrLoc, diag::err_attribute_size_too_large)
2537 << RowRange << "matrix row";
2538 return QualType();
2539 }
2540 if (MatrixColumns > Context.getLangOpts().MaxMatrixDimension) {
2541 Diag(AttrLoc, diag::err_attribute_size_too_large)
2542 << ColRange << "matrix column";
2543 return QualType();
2544 }
2545 return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2546}
2547
2549 if ((T->isArrayType() && !getLangOpts().allowArrayReturnTypes()) ||
2550 T->isFunctionType()) {
2551 Diag(Loc, diag::err_func_returning_array_function)
2552 << T->isFunctionType() << T;
2553 return true;
2554 }
2555
2556 // Functions cannot return half FP.
2557 if (T->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2558 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2559 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2561 return true;
2562 }
2563
2564 // Methods cannot return interface types. All ObjC objects are
2565 // passed by reference.
2566 if (T->isObjCObjectType()) {
2567 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2568 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2569 return true;
2570 }
2571
2572 // __ptrauth is illegal on a function return type.
2573 if (T.getPointerAuth()) {
2574 Diag(Loc, diag::err_ptrauth_qualifier_invalid) << T << 0;
2575 return true;
2576 }
2577
2578 if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2579 T.hasNonTrivialToPrimitiveCopyCUnion())
2582
2583 // C++2a [dcl.fct]p12:
2584 // A volatile-qualified return type is deprecated
2585 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2586 Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2587
2588 if (T.getAddressSpace() != LangAS::Default && getLangOpts().HLSL)
2589 return true;
2590 return false;
2591}
2592
2593/// Check the extended parameter information. Most of the necessary
2594/// checking should occur when applying the parameter attribute; the
2595/// only other checks required are positional restrictions.
2598 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2599 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2600
2601 bool emittedError = false;
2602 auto actualCC = EPI.ExtInfo.getCC();
2603 enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
2604 auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
2605 bool isCompatible =
2606 (required == RequiredCC::OnlySwift)
2607 ? (actualCC == CC_Swift)
2608 : (actualCC == CC_Swift || actualCC == CC_SwiftAsync);
2609 if (isCompatible || emittedError)
2610 return;
2611 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2613 << (required == RequiredCC::OnlySwift);
2614 emittedError = true;
2615 };
2616 for (size_t paramIndex = 0, numParams = paramTypes.size();
2617 paramIndex != numParams; ++paramIndex) {
2618 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2619 // Nothing interesting to check for orindary-ABI parameters.
2623 continue;
2624
2625 // swift_indirect_result parameters must be a prefix of the function
2626 // arguments.
2628 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2629 if (paramIndex != 0 &&
2630 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2632 S.Diag(getParamLoc(paramIndex),
2633 diag::err_swift_indirect_result_not_first);
2634 }
2635 continue;
2636
2638 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2639 continue;
2640
2641 // SwiftAsyncContext is not limited to swiftasynccall functions.
2643 continue;
2644
2645 // swift_error parameters must be preceded by a swift_context parameter.
2647 checkCompatible(paramIndex, RequiredCC::OnlySwift);
2648 if (paramIndex == 0 ||
2649 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2651 S.Diag(getParamLoc(paramIndex),
2652 diag::err_swift_error_result_not_after_swift_context);
2653 }
2654 continue;
2655 }
2656 llvm_unreachable("bad ABI kind");
2657 }
2658}
2659
2661 MutableArrayRef<QualType> ParamTypes,
2662 SourceLocation Loc, DeclarationName Entity,
2664 bool Invalid = false;
2665
2667
2668 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2669 // FIXME: Loc is too inprecise here, should use proper locations for args.
2670 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2671 if (ParamType->isVoidType()) {
2672 Diag(Loc, diag::err_param_with_void_type);
2673 Invalid = true;
2674 } else if (ParamType->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2675 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2676 // Disallow half FP arguments.
2677 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2679 Invalid = true;
2680 } else if (ParamType->isWebAssemblyTableType()) {
2681 Diag(Loc, diag::err_wasm_table_as_function_parameter);
2682 Invalid = true;
2683 } else if (ParamType.getPointerAuth()) {
2684 // __ptrauth is illegal on a function return type.
2685 Diag(Loc, diag::err_ptrauth_qualifier_invalid) << T << 1;
2686 Invalid = true;
2687 }
2688
2689 // C++2a [dcl.fct]p4:
2690 // A parameter with volatile-qualified type is deprecated
2691 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
2692 Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
2693
2694 ParamTypes[Idx] = ParamType;
2695 }
2696
2697 if (EPI.ExtParameterInfos) {
2698 checkExtParameterInfos(*this, ParamTypes, EPI,
2699 [=](unsigned i) { return Loc; });
2700 }
2701
2702 if (EPI.ExtInfo.getProducesResult()) {
2703 // This is just a warning, so we can't fail to build if we see it.
2705 }
2706
2707 if (Invalid)
2708 return QualType();
2709
2710 return Context.getFunctionType(T, ParamTypes, EPI);
2711}
2712
2714 CXXRecordDecl *Cls, SourceLocation Loc,
2715 DeclarationName Entity) {
2716 if (!Cls && !isDependentScopeSpecifier(SS)) {
2717 Cls = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS));
2718 if (!Cls) {
2719 auto D =
2720 Diag(SS.getBeginLoc(), diag::err_illegal_decl_mempointer_in_nonclass)
2721 << SS.getRange();
2722 if (const IdentifierInfo *II = Entity.getAsIdentifierInfo())
2723 D << II;
2724 else
2725 D << "member pointer";
2726 return QualType();
2727 }
2728 }
2729
2730 // Verify that we're not building a pointer to pointer to function with
2731 // exception specification.
2733 Diag(Loc, diag::err_distant_exception_spec);
2734 return QualType();
2735 }
2736
2737 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2738 // with reference type, or "cv void."
2739 if (T->isReferenceType()) {
2740 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2741 << getPrintableNameForEntity(Entity) << T;
2742 return QualType();
2743 }
2744
2745 if (T->isVoidType()) {
2746 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2747 << getPrintableNameForEntity(Entity);
2748 return QualType();
2749 }
2750
2751 if (T->isFunctionType() && getLangOpts().OpenCL &&
2752 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2753 getLangOpts())) {
2754 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2755 return QualType();
2756 }
2757
2758 if (getLangOpts().HLSL && Loc.isValid()) {
2759 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
2760 return QualType();
2761 }
2762
2763 // Adjust the default free function calling convention to the default method
2764 // calling convention.
2765 bool IsCtorOrDtor =
2768 if (T->isFunctionType())
2769 adjustMemberFunctionCC(T, /*HasThisPointer=*/true, IsCtorOrDtor, Loc);
2770
2771 return Context.getMemberPointerType(T, SS.getScopeRep(), Cls);
2772}
2773
2775 SourceLocation Loc,
2776 DeclarationName Entity) {
2777 if (!T->isFunctionType()) {
2778 Diag(Loc, diag::err_nonfunction_block_type);
2779 return QualType();
2780 }
2781
2782 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2783 return QualType();
2784
2785 if (getLangOpts().OpenCL)
2787
2788 return Context.getBlockPointerType(T);
2789}
2790
2792 QualType QT = Ty.get();
2793 if (QT.isNull()) {
2794 if (TInfo) *TInfo = nullptr;
2795 return QualType();
2796 }
2797
2798 TypeSourceInfo *TSI = nullptr;
2799 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2800 QT = LIT->getType();
2801 TSI = LIT->getTypeSourceInfo();
2802 }
2803
2804 if (TInfo)
2805 *TInfo = TSI;
2806 return QT;
2807}
2808
2809static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2810 Qualifiers::ObjCLifetime ownership,
2811 unsigned chunkIndex);
2812
2813/// Given that this is the declaration of a parameter under ARC,
2814/// attempt to infer attributes and such for pointer-to-whatever
2815/// types.
2816static void inferARCWriteback(TypeProcessingState &state,
2817 QualType &declSpecType) {
2818 Sema &S = state.getSema();
2819 Declarator &declarator = state.getDeclarator();
2820
2821 // TODO: should we care about decl qualifiers?
2822
2823 // Check whether the declarator has the expected form. We walk
2824 // from the inside out in order to make the block logic work.
2825 unsigned outermostPointerIndex = 0;
2826 bool isBlockPointer = false;
2827 unsigned numPointers = 0;
2828 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2829 unsigned chunkIndex = i;
2830 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2831 switch (chunk.Kind) {
2833 // Ignore parens.
2834 break;
2835
2838 // Count the number of pointers. Treat references
2839 // interchangeably as pointers; if they're mis-ordered, normal
2840 // type building will discover that.
2841 outermostPointerIndex = chunkIndex;
2842 numPointers++;
2843 break;
2844
2846 // If we have a pointer to block pointer, that's an acceptable
2847 // indirect reference; anything else is not an application of
2848 // the rules.
2849 if (numPointers != 1) return;
2850 numPointers++;
2851 outermostPointerIndex = chunkIndex;
2852 isBlockPointer = true;
2853
2854 // We don't care about pointer structure in return values here.
2855 goto done;
2856
2857 case DeclaratorChunk::Array: // suppress if written (id[])?
2861 return;
2862 }
2863 }
2864 done:
2865
2866 // If we have *one* pointer, then we want to throw the qualifier on
2867 // the declaration-specifiers, which means that it needs to be a
2868 // retainable object type.
2869 if (numPointers == 1) {
2870 // If it's not a retainable object type, the rule doesn't apply.
2871 if (!declSpecType->isObjCRetainableType()) return;
2872
2873 // If it already has lifetime, don't do anything.
2874 if (declSpecType.getObjCLifetime()) return;
2875
2876 // Otherwise, modify the type in-place.
2877 Qualifiers qs;
2878
2879 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2881 else
2883 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2884
2885 // If we have *two* pointers, then we want to throw the qualifier on
2886 // the outermost pointer.
2887 } else if (numPointers == 2) {
2888 // If we don't have a block pointer, we need to check whether the
2889 // declaration-specifiers gave us something that will turn into a
2890 // retainable object pointer after we slap the first pointer on it.
2891 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2892 return;
2893
2894 // Look for an explicit lifetime attribute there.
2895 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2896 if (chunk.Kind != DeclaratorChunk::Pointer &&
2898 return;
2899 for (const ParsedAttr &AL : chunk.getAttrs())
2900 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
2901 return;
2902
2904 outermostPointerIndex);
2905
2906 // Any other number of pointers/references does not trigger the rule.
2907 } else return;
2908
2909 // TODO: mark whether we did this inference?
2910}
2911
2912void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2913 SourceLocation FallbackLoc,
2914 SourceLocation ConstQualLoc,
2915 SourceLocation VolatileQualLoc,
2916 SourceLocation RestrictQualLoc,
2917 SourceLocation AtomicQualLoc,
2918 SourceLocation UnalignedQualLoc) {
2919 if (!Quals)
2920 return;
2921
2922 struct Qual {
2923 const char *Name;
2924 unsigned Mask;
2925 SourceLocation Loc;
2926 } const QualKinds[5] = {
2927 { "const", DeclSpec::TQ_const, ConstQualLoc },
2928 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2929 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2930 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2931 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2932 };
2933
2934 SmallString<32> QualStr;
2935 unsigned NumQuals = 0;
2936 SourceLocation Loc;
2937 FixItHint FixIts[5];
2938
2939 // Build a string naming the redundant qualifiers.
2940 for (auto &E : QualKinds) {
2941 if (Quals & E.Mask) {
2942 if (!QualStr.empty()) QualStr += ' ';
2943 QualStr += E.Name;
2944
2945 // If we have a location for the qualifier, offer a fixit.
2946 SourceLocation QualLoc = E.Loc;
2947 if (QualLoc.isValid()) {
2948 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2949 if (Loc.isInvalid() ||
2950 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2951 Loc = QualLoc;
2952 }
2953
2954 ++NumQuals;
2955 }
2956 }
2957
2958 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2959 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2960}
2961
2962// Diagnose pointless type qualifiers on the return type of a function.
2964 Declarator &D,
2965 unsigned FunctionChunkIndex) {
2967 D.getTypeObject(FunctionChunkIndex).Fun;
2968 if (FTI.hasTrailingReturnType()) {
2969 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2970 RetTy.getLocalCVRQualifiers(),
2972 return;
2973 }
2974
2975 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2976 End = D.getNumTypeObjects();
2977 OuterChunkIndex != End; ++OuterChunkIndex) {
2978 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2979 switch (OuterChunk.Kind) {
2981 continue;
2982
2984 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2986 diag::warn_qual_return_type,
2987 PTI.TypeQuals,
2989 PTI.ConstQualLoc,
2990 PTI.VolatileQualLoc,
2991 PTI.RestrictQualLoc,
2992 PTI.AtomicQualLoc,
2993 PTI.UnalignedQualLoc);
2994 return;
2995 }
2996
3003 // FIXME: We can't currently provide an accurate source location and a
3004 // fix-it hint for these.
3005 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
3006 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3007 RetTy.getCVRQualifiers() | AtomicQual,
3008 D.getIdentifierLoc());
3009 return;
3010 }
3011
3012 llvm_unreachable("unknown declarator chunk kind");
3013 }
3014
3015 // If the qualifiers come from a conversion function type, don't diagnose
3016 // them -- they're not necessarily redundant, since such a conversion
3017 // operator can be explicitly called as "x.operator const int()".
3019 return;
3020
3021 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3022 // which are present there.
3023 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3025 D.getIdentifierLoc(),
3031}
3032
3033static std::pair<QualType, TypeSourceInfo *>
3034InventTemplateParameter(TypeProcessingState &state, QualType T,
3035 TypeSourceInfo *TrailingTSI, AutoType *Auto,
3037 Sema &S = state.getSema();
3038 Declarator &D = state.getDeclarator();
3039
3040 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3041 const unsigned AutoParameterPosition = Info.TemplateParams.size();
3042 const bool IsParameterPack = D.hasEllipsis();
3043
3044 // If auto is mentioned in a lambda parameter or abbreviated function
3045 // template context, convert it to a template parameter type.
3046
3047 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3048 // template parameter type. Template parameters are temporarily added
3049 // to the TU until the associated TemplateDecl is created.
3050 TemplateTypeParmDecl *InventedTemplateParam =
3053 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3054 /*NameLoc=*/D.getIdentifierLoc(),
3055 TemplateParameterDepth, AutoParameterPosition,
3057 D.getIdentifier(), AutoParameterPosition), false,
3058 IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3059 InventedTemplateParam->setImplicit();
3060 Info.TemplateParams.push_back(InventedTemplateParam);
3061
3062 // Attach type constraints to the new parameter.
3063 if (Auto->isConstrained()) {
3064 if (TrailingTSI) {
3065 // The 'auto' appears in a trailing return type we've already built;
3066 // extract its type constraints to attach to the template parameter.
3067 AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3068 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3069 bool Invalid = false;
3070 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3071 if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3074 Invalid = true;
3075 TAL.addArgument(AutoLoc.getArgLoc(Idx));
3076 }
3077
3078 if (!Invalid) {
3080 AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3081 AutoLoc.getNamedConcept(), /*FoundDecl=*/AutoLoc.getFoundDecl(),
3082 AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3083 InventedTemplateParam, D.getEllipsisLoc());
3084 }
3085 } else {
3086 // The 'auto' appears in the decl-specifiers; we've not finished forming
3087 // TypeSourceInfo for it yet.
3089 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
3090 TemplateId->RAngleLoc);
3091 bool Invalid = false;
3092 if (TemplateId->LAngleLoc.isValid()) {
3093 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3094 TemplateId->NumArgs);
3095 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3096
3097 if (D.getEllipsisLoc().isInvalid()) {
3098 for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3101 Invalid = true;
3102 break;
3103 }
3104 }
3105 }
3106 }
3107 if (!Invalid) {
3108 UsingShadowDecl *USD =
3109 TemplateId->Template.get().getAsUsingShadowDecl();
3110 TemplateDecl *CD = TemplateId->Template.get().getAsTemplateDecl();
3114 TemplateId->TemplateNameLoc),
3115 CD,
3116 /*FoundDecl=*/USD ? cast<NamedDecl>(USD) : CD,
3117 TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3118 InventedTemplateParam, D.getEllipsisLoc());
3119 }
3120 }
3121 }
3122
3123 // Replace the 'auto' in the function parameter with this invented
3124 // template type parameter.
3125 // FIXME: Retain some type sugar to indicate that this was written
3126 // as 'auto'?
3127 QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3128 QualType NewT = state.ReplaceAutoType(T, Replacement);
3129 TypeSourceInfo *NewTSI =
3130 TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)
3131 : nullptr;
3132 return {NewT, NewTSI};
3133}
3134
3135static TypeSourceInfo *
3136GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3137 QualType T, TypeSourceInfo *ReturnTypeInfo);
3138
3139static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3140 TypeSourceInfo *&ReturnTypeInfo) {
3141 Sema &SemaRef = state.getSema();
3142 Declarator &D = state.getDeclarator();
3143 QualType T;
3144 ReturnTypeInfo = nullptr;
3145
3146 // The TagDecl owned by the DeclSpec.
3147 TagDecl *OwnedTagDecl = nullptr;
3148
3149 switch (D.getName().getKind()) {
3155 T = ConvertDeclSpecToType(state);
3156
3157 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3158 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3159 // Owned declaration is embedded in declarator.
3160 OwnedTagDecl->setEmbeddedInDeclarator(true);
3161 }
3162 break;
3163
3167 // Constructors and destructors don't have return types. Use
3168 // "void" instead.
3169 T = SemaRef.Context.VoidTy;
3172 break;
3173
3175 // Deduction guides have a trailing return type and no type in their
3176 // decl-specifier sequence. Use a placeholder return type for now.
3177 T = SemaRef.Context.DependentTy;
3178 break;
3179
3181 // The result type of a conversion function is the type that it
3182 // converts to.
3184 &ReturnTypeInfo);
3185 break;
3186 }
3187
3188 // Note: We don't need to distribute declaration attributes (i.e.
3189 // D.getDeclarationAttributes()) because those are always C++11 attributes,
3190 // and those don't get distributed.
3192 state, T, SemaRef.CUDA().IdentifyTarget(D.getAttributes()));
3193
3194 // Find the deduced type in this type. Look in the trailing return type if we
3195 // have one, otherwise in the DeclSpec type.
3196 // FIXME: The standard wording doesn't currently describe this.
3197 DeducedType *Deduced = T->getContainedDeducedType();
3198 bool DeducedIsTrailingReturnType = false;
3199 if (Deduced && isa<AutoType>(Deduced) && D.hasTrailingReturnType()) {
3201 Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3202 DeducedIsTrailingReturnType = true;
3203 }
3204
3205 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3206 if (Deduced) {
3207 AutoType *Auto = dyn_cast<AutoType>(Deduced);
3208 int Error = -1;
3209
3210 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3211 // class template argument deduction)?
3212 bool IsCXXAutoType =
3213 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3214 bool IsDeducedReturnType = false;
3215
3216 switch (D.getContext()) {
3218 // Declared return type of a lambda-declarator is implicit and is always
3219 // 'auto'.
3220 break;
3223 Error = 0;
3224 break;
3226 Error = 22;
3227 break;
3230 InventedTemplateParameterInfo *Info = nullptr;
3232 // With concepts we allow 'auto' in function parameters.
3233 if (!SemaRef.getLangOpts().CPlusPlus20 || !Auto ||
3234 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3235 Error = 0;
3236 break;
3237 } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3238 Error = 21;
3239 break;
3240 }
3241
3242 Info = &SemaRef.InventedParameterInfos.back();
3243 } else {
3244 // In C++14, generic lambdas allow 'auto' in their parameters.
3245 if (!SemaRef.getLangOpts().CPlusPlus14 && Auto &&
3246 Auto->getKeyword() == AutoTypeKeyword::Auto) {
3247 Error = 25; // auto not allowed in lambda parameter (before C++14)
3248 break;
3249 } else if (!Auto || Auto->getKeyword() != AutoTypeKeyword::Auto) {
3250 Error = 16; // __auto_type or decltype(auto) not allowed in lambda
3251 // parameter
3252 break;
3253 }
3254 Info = SemaRef.getCurLambda();
3255 assert(Info && "No LambdaScopeInfo on the stack!");
3256 }
3257
3258 // We'll deal with inventing template parameters for 'auto' in trailing
3259 // return types when we pick up the trailing return type when processing
3260 // the function chunk.
3261 if (!DeducedIsTrailingReturnType)
3262 T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3263 break;
3264 }
3266 if (D.isStaticMember() || D.isFunctionDeclarator())
3267 break;
3268 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3269 if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3270 Error = 6; // Interface member.
3271 } else {
3272 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3273 case TagTypeKind::Enum:
3274 llvm_unreachable("unhandled tag kind");
3276 Error = Cxx ? 1 : 2; /* Struct member */
3277 break;
3278 case TagTypeKind::Union:
3279 Error = Cxx ? 3 : 4; /* Union member */
3280 break;
3281 case TagTypeKind::Class:
3282 Error = 5; /* Class member */
3283 break;
3285 Error = 6; /* Interface member */
3286 break;
3287 }
3288 }
3290 Error = 20; // Friend type
3291 break;
3292 }
3295 Error = 7; // Exception declaration
3296 break;
3299 !SemaRef.getLangOpts().CPlusPlus20)
3300 Error = 19; // Template parameter (until C++20)
3301 else if (!SemaRef.getLangOpts().CPlusPlus17)
3302 Error = 8; // Template parameter (until C++17)
3303 break;
3305 Error = 9; // Block literal
3306 break;
3308 // Within a template argument list, a deduced template specialization
3309 // type will be reinterpreted as a template template argument.
3311 !D.getNumTypeObjects() &&
3313 break;
3314 [[fallthrough]];
3316 Error = 10; // Template type argument
3317 break;
3320 Error = 12; // Type alias
3321 break;
3324 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3325 Error = 13; // Function return type
3326 IsDeducedReturnType = true;
3327 break;
3329 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3330 Error = 14; // conversion-type-id
3331 IsDeducedReturnType = true;
3332 break;
3335 break;
3336 if (SemaRef.getLangOpts().CPlusPlus23 && IsCXXAutoType &&
3337 !Auto->isDecltypeAuto())
3338 break; // auto(x)
3339 [[fallthrough]];
3342 Error = 15; // Generic
3343 break;
3349 // FIXME: P0091R3 (erroneously) does not permit class template argument
3350 // deduction in conditions, for-init-statements, and other declarations
3351 // that are not simple-declarations.
3352 break;
3354 // FIXME: P0091R3 does not permit class template argument deduction here,
3355 // but we follow GCC and allow it anyway.
3356 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3357 Error = 17; // 'new' type
3358 break;
3360 Error = 18; // K&R function parameter
3361 break;
3362 }
3363
3365 Error = 11;
3366
3367 // In Objective-C it is an error to use 'auto' on a function declarator
3368 // (and everywhere for '__auto_type').
3369 if (D.isFunctionDeclarator() &&
3370 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3371 Error = 13;
3372
3373 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3375 AutoRange = D.getName().getSourceRange();
3376
3377 if (Error != -1) {
3378 unsigned Kind;
3379 if (Auto) {
3380 switch (Auto->getKeyword()) {
3381 case AutoTypeKeyword::Auto: Kind = 0; break;
3382 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3383 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3384 }
3385 } else {
3387 "unknown auto type");
3388 Kind = 3;
3389 }
3390
3391 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3392 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3393
3394 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3395 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3396 << QualType(Deduced, 0) << AutoRange;
3397 if (auto *TD = TN.getAsTemplateDecl())
3398 SemaRef.NoteTemplateLocation(*TD);
3399
3400 T = SemaRef.Context.IntTy;
3401 D.setInvalidType(true);
3402 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) {
3403 // If there was a trailing return type, we already got
3404 // warn_cxx98_compat_trailing_return_type in the parser.
3405 // If there was a decltype(auto), we already got
3406 // warn_cxx11_compat_decltype_auto_type_specifier.
3407 unsigned DiagId = 0;
3409 DiagId = diag::warn_cxx11_compat_generic_lambda;
3410 else if (IsDeducedReturnType)
3411 DiagId = diag::warn_cxx11_compat_deduced_return_type;
3412 else if (Auto->getKeyword() == AutoTypeKeyword::Auto)
3413 DiagId = diag::warn_cxx98_compat_auto_type_specifier;
3414
3415 if (DiagId)
3416 SemaRef.Diag(AutoRange.getBegin(), DiagId) << AutoRange;
3417 }
3418 }
3419
3420 if (SemaRef.getLangOpts().CPlusPlus &&
3421 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3422 // Check the contexts where C++ forbids the declaration of a new class
3423 // or enumeration in a type-specifier-seq.
3424 unsigned DiagID = 0;
3425 switch (D.getContext()) {
3428 // Class and enumeration definitions are syntactically not allowed in
3429 // trailing return types.
3430 llvm_unreachable("parser should not have allowed this");
3431 break;
3439 // C++11 [dcl.type]p3:
3440 // A type-specifier-seq shall not define a class or enumeration unless
3441 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3442 // the declaration of a template-declaration.
3444 break;
3446 DiagID = diag::err_type_defined_in_alias_template;
3447 break;
3458 DiagID = diag::err_type_defined_in_type_specifier;
3459 break;
3466 // C++ [dcl.fct]p6:
3467 // Types shall not be defined in return or parameter types.
3468 DiagID = diag::err_type_defined_in_param_type;
3469 break;
3471 // C++ 6.4p2:
3472 // The type-specifier-seq shall not contain typedef and shall not declare
3473 // a new class or enumeration.
3474 DiagID = diag::err_type_defined_in_condition;
3475 break;
3476 }
3477
3478 if (DiagID != 0) {
3479 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3480 << SemaRef.Context.getCanonicalTagType(OwnedTagDecl);
3481 D.setInvalidType(true);
3482 }
3483 }
3484
3485 assert(!T.isNull() && "This function should not return a null type");
3486 return T;
3487}
3488
3489/// Produce an appropriate diagnostic for an ambiguity between a function
3490/// declarator and a C++ direct-initializer.
3492 DeclaratorChunk &DeclType, QualType RT) {
3493 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3494 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3495
3496 // If the return type is void there is no ambiguity.
3497 if (RT->isVoidType())
3498 return;
3499
3500 // An initializer for a non-class type can have at most one argument.
3501 if (!RT->isRecordType() && FTI.NumParams > 1)
3502 return;
3503
3504 // An initializer for a reference must have exactly one argument.
3505 if (RT->isReferenceType() && FTI.NumParams != 1)
3506 return;
3507
3508 // Only warn if this declarator is declaring a function at block scope, and
3509 // doesn't have a storage class (such as 'extern') specified.
3510 if (!D.isFunctionDeclarator() ||
3514 return;
3515
3516 // Inside a condition, a direct initializer is not permitted. We allow one to
3517 // be parsed in order to give better diagnostics in condition parsing.
3519 return;
3520
3521 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3522
3523 S.Diag(DeclType.Loc,
3524 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3525 : diag::warn_empty_parens_are_function_decl)
3526 << ParenRange;
3527
3528 // If the declaration looks like:
3529 // T var1,
3530 // f();
3531 // and name lookup finds a function named 'f', then the ',' was
3532 // probably intended to be a ';'.
3533 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3534 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3536 if (Comma.getFileID() != Name.getFileID() ||
3537 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3540 if (S.LookupName(Result, S.getCurScope()))
3541 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3543 << D.getIdentifier();
3544 Result.suppressDiagnostics();
3545 }
3546 }
3547
3548 if (FTI.NumParams > 0) {
3549 // For a declaration with parameters, eg. "T var(T());", suggest adding
3550 // parens around the first parameter to turn the declaration into a
3551 // variable declaration.
3552 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3553 SourceLocation B = Range.getBegin();
3554 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3555 // FIXME: Maybe we should suggest adding braces instead of parens
3556 // in C++11 for classes that don't have an initializer_list constructor.
3557 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3559 << FixItHint::CreateInsertion(E, ")");
3560 } else {
3561 // For a declaration without parameters, eg. "T var();", suggest replacing
3562 // the parens with an initializer to turn the declaration into a variable
3563 // declaration.
3564 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3565
3566 // Empty parens mean value-initialization, and no parens mean
3567 // default initialization. These are equivalent if the default
3568 // constructor is user-provided or if zero-initialization is a
3569 // no-op.
3570 if (RD && RD->hasDefinition() &&
3572 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3573 << FixItHint::CreateRemoval(ParenRange);
3574 else {
3575 std::string Init =
3576 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3577 if (Init.empty() && S.LangOpts.CPlusPlus11)
3578 Init = "{}";
3579 if (!Init.empty())
3580 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3581 << FixItHint::CreateReplacement(ParenRange, Init);
3582 }
3583 }
3584}
3585
3586/// Produce an appropriate diagnostic for a declarator with top-level
3587/// parentheses.
3590 assert(Paren.Kind == DeclaratorChunk::Paren &&
3591 "do not have redundant top-level parentheses");
3592
3593 // This is a syntactic check; we're not interested in cases that arise
3594 // during template instantiation.
3596 return;
3597
3598 // Check whether this could be intended to be a construction of a temporary
3599 // object in C++ via a function-style cast.
3600 bool CouldBeTemporaryObject =
3601 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3602 !D.isInvalidType() && D.getIdentifier() &&
3604 (T->isRecordType() || T->isDependentType()) &&
3606
3607 bool StartsWithDeclaratorId = true;
3608 for (auto &C : D.type_objects()) {
3609 switch (C.Kind) {
3611 if (&C == &Paren)
3612 continue;
3613 [[fallthrough]];
3615 StartsWithDeclaratorId = false;
3616 continue;
3617
3619 if (!C.Arr.NumElts)
3620 CouldBeTemporaryObject = false;
3621 continue;
3622
3624 // FIXME: Suppress the warning here if there is no initializer; we're
3625 // going to give an error anyway.
3626 // We assume that something like 'T (&x) = y;' is highly likely to not
3627 // be intended to be a temporary object.
3628 CouldBeTemporaryObject = false;
3629 StartsWithDeclaratorId = false;
3630 continue;
3631
3633 // In a new-type-id, function chunks require parentheses.
3635 return;
3636 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3637 // redundant-parens warning, but we don't know whether the function
3638 // chunk was syntactically valid as an expression here.
3639 CouldBeTemporaryObject = false;
3640 continue;
3641
3645 // These cannot appear in expressions.
3646 CouldBeTemporaryObject = false;
3647 StartsWithDeclaratorId = false;
3648 continue;
3649 }
3650 }
3651
3652 // FIXME: If there is an initializer, assume that this is not intended to be
3653 // a construction of a temporary object.
3654
3655 // Check whether the name has already been declared; if not, this is not a
3656 // function-style cast.
3657 if (CouldBeTemporaryObject) {
3660 if (!S.LookupName(Result, S.getCurScope()))
3661 CouldBeTemporaryObject = false;
3662 Result.suppressDiagnostics();
3663 }
3664
3665 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3666
3667 if (!CouldBeTemporaryObject) {
3668 // If we have A (::B), the parentheses affect the meaning of the program.
3669 // Suppress the warning in that case. Don't bother looking at the DeclSpec
3670 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3671 // formally unambiguous.
3672 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3674 for (;;) {
3675 switch (NNS.getKind()) {
3677 return;
3679 NNS = NNS.getAsType()->getPrefix();
3680 continue;
3682 NNS = NNS.getAsNamespaceAndPrefix().Prefix;
3683 continue;
3684 default:
3685 goto out;
3686 }
3687 }
3688 out:;
3689 }
3690
3691 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3692 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3694 return;
3695 }
3696
3697 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3698 << ParenRange << D.getIdentifier();
3699 auto *RD = T->getAsCXXRecordDecl();
3700 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3701 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3702 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3703 << D.getIdentifier();
3704 // FIXME: A cast to void is probably a better suggestion in cases where it's
3705 // valid (when there is no initializer and we're not in a condition).
3706 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3709 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3712}
3713
3714/// Helper for figuring out the default CC for a function declarator type. If
3715/// this is the outermost chunk, then we can determine the CC from the
3716/// declarator context. If not, then this could be either a member function
3717/// type or normal function type.
3719 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3720 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3721 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3722
3723 // Check for an explicit CC attribute.
3724 for (const ParsedAttr &AL : AttrList) {
3725 switch (AL.getKind()) {
3727 // Ignore attributes that don't validate or can't apply to the
3728 // function type. We'll diagnose the failure to apply them in
3729 // handleFunctionTypeAttr.
3730 CallingConv CC;
3731 if (!S.CheckCallingConvAttr(AL, CC, /*FunctionDecl=*/nullptr,
3732 S.CUDA().IdentifyTarget(D.getAttributes())) &&
3733 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3734 return CC;
3735 }
3736 break;
3737 }
3738
3739 default:
3740 break;
3741 }
3742 }
3743
3744 bool IsCXXInstanceMethod = false;
3745
3746 if (S.getLangOpts().CPlusPlus) {
3747 // Look inwards through parentheses to see if this chunk will form a
3748 // member pointer type or if we're the declarator. Any type attributes
3749 // between here and there will override the CC we choose here.
3750 unsigned I = ChunkIndex;
3751 bool FoundNonParen = false;
3752 while (I && !FoundNonParen) {
3753 --I;
3755 FoundNonParen = true;
3756 }
3757
3758 if (FoundNonParen) {
3759 // If we're not the declarator, we're a regular function type unless we're
3760 // in a member pointer.
3761 IsCXXInstanceMethod =
3763 } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
3764 // This can only be a call operator for a lambda, which is an instance
3765 // method, unless explicitly specified as 'static'.
3766 IsCXXInstanceMethod =
3768 } else {
3769 // We're the innermost decl chunk, so must be a function declarator.
3770 assert(D.isFunctionDeclarator());
3771
3772 // If we're inside a record, we're declaring a method, but it could be
3773 // explicitly or implicitly static.
3774 IsCXXInstanceMethod =
3777 !D.isStaticMember();
3778 }
3779 }
3780
3782 IsCXXInstanceMethod);
3783
3784 if (S.getLangOpts().CUDA) {
3785 // If we're compiling CUDA/HIP code and targeting HIPSPV we need to make
3786 // sure the kernels will be marked with the right calling convention so that
3787 // they will be visible by the APIs that ingest SPIR-V. We do not do this
3788 // when targeting AMDGCNSPIRV, as it does not rely on OpenCL.
3789 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
3790 if (Triple.isSPIRV() && Triple.getVendor() != llvm::Triple::AMD) {
3791 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3792 if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) {
3793 CC = CC_DeviceKernel;
3794 break;
3795 }
3796 }
3797 }
3798 }
3799 for (const ParsedAttr &AL : llvm::concat<ParsedAttr>(
3801 if (AL.getKind() == ParsedAttr::AT_DeviceKernel) {
3802 CC = CC_DeviceKernel;
3803 break;
3804 }
3805 }
3806 return CC;
3807}
3808
3809namespace {
3810 /// A simple notion of pointer kinds, which matches up with the various
3811 /// pointer declarators.
3812 enum class SimplePointerKind {
3813 Pointer,
3814 BlockPointer,
3815 MemberPointer,
3816 Array,
3817 };
3818} // end anonymous namespace
3819
3821 switch (nullability) {
3823 if (!Ident__Nonnull)
3824 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3825 return Ident__Nonnull;
3826
3828 if (!Ident__Nullable)
3829 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3830 return Ident__Nullable;
3831
3833 if (!Ident__Nullable_result)
3834 Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
3835 return Ident__Nullable_result;
3836
3838 if (!Ident__Null_unspecified)
3839 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3840 return Ident__Null_unspecified;
3841 }
3842 llvm_unreachable("Unknown nullability kind.");
3843}
3844
3845/// Check whether there is a nullability attribute of any kind in the given
3846/// attribute list.
3847static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
3848 for (const ParsedAttr &AL : attrs) {
3849 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
3850 AL.getKind() == ParsedAttr::AT_TypeNullable ||
3851 AL.getKind() == ParsedAttr::AT_TypeNullableResult ||
3852 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
3853 return true;
3854 }
3855
3856 return false;
3857}
3858
3859namespace {
3860 /// Describes the kind of a pointer a declarator describes.
3861 enum class PointerDeclaratorKind {
3862 // Not a pointer.
3863 NonPointer,
3864 // Single-level pointer.
3865 SingleLevelPointer,
3866 // Multi-level pointer (of any pointer kind).
3867 MultiLevelPointer,
3868 // CFFooRef*
3869 MaybePointerToCFRef,
3870 // CFErrorRef*
3871 CFErrorRefPointer,
3872 // NSError**
3873 NSErrorPointerPointer,
3874 };
3875
3876 /// Describes a declarator chunk wrapping a pointer that marks inference as
3877 /// unexpected.
3878 // These values must be kept in sync with diagnostics.
3879 enum class PointerWrappingDeclaratorKind {
3880 /// Pointer is top-level.
3881 None = -1,
3882 /// Pointer is an array element.
3883 Array = 0,
3884 /// Pointer is the referent type of a C++ reference.
3885 Reference = 1
3886 };
3887} // end anonymous namespace
3888
3889/// Classify the given declarator, whose type-specified is \c type, based on
3890/// what kind of pointer it refers to.
3891///
3892/// This is used to determine the default nullability.
3893static PointerDeclaratorKind
3895 PointerWrappingDeclaratorKind &wrappingKind) {
3896 unsigned numNormalPointers = 0;
3897
3898 // For any dependent type, we consider it a non-pointer.
3899 if (type->isDependentType())
3900 return PointerDeclaratorKind::NonPointer;
3901
3902 // Look through the declarator chunks to identify pointers.
3903 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3904 DeclaratorChunk &chunk = declarator.getTypeObject(i);
3905 switch (chunk.Kind) {
3907 if (numNormalPointers == 0)
3908 wrappingKind = PointerWrappingDeclaratorKind::Array;
3909 break;
3910
3913 break;
3914
3917 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3918 : PointerDeclaratorKind::SingleLevelPointer;
3919
3921 break;
3922
3924 if (numNormalPointers == 0)
3925 wrappingKind = PointerWrappingDeclaratorKind::Reference;
3926 break;
3927
3929 ++numNormalPointers;
3930 if (numNormalPointers > 2)
3931 return PointerDeclaratorKind::MultiLevelPointer;
3932 break;
3933 }
3934 }
3935
3936 // Then, dig into the type specifier itself.
3937 unsigned numTypeSpecifierPointers = 0;
3938 do {
3939 // Decompose normal pointers.
3940 if (auto ptrType = type->getAs<PointerType>()) {
3941 ++numNormalPointers;
3942
3943 if (numNormalPointers > 2)
3944 return PointerDeclaratorKind::MultiLevelPointer;
3945
3946 type = ptrType->getPointeeType();
3947 ++numTypeSpecifierPointers;
3948 continue;
3949 }
3950
3951 // Decompose block pointers.
3952 if (type->getAs<BlockPointerType>()) {
3953 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3954 : PointerDeclaratorKind::SingleLevelPointer;
3955 }
3956
3957 // Decompose member pointers.
3958 if (type->getAs<MemberPointerType>()) {
3959 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3960 : PointerDeclaratorKind::SingleLevelPointer;
3961 }
3962
3963 // Look at Objective-C object pointers.
3964 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3965 ++numNormalPointers;
3966 ++numTypeSpecifierPointers;
3967
3968 // If this is NSError**, report that.
3969 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3970 if (objcClassDecl->getIdentifier() == S.ObjC().getNSErrorIdent() &&
3971 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3972 return PointerDeclaratorKind::NSErrorPointerPointer;
3973 }
3974 }
3975
3976 break;
3977 }
3978
3979 // Look at Objective-C class types.
3980 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3981 if (objcClass->getInterface()->getIdentifier() ==
3982 S.ObjC().getNSErrorIdent()) {
3983 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3984 return PointerDeclaratorKind::NSErrorPointerPointer;
3985 }
3986
3987 break;
3988 }
3989
3990 // If at this point we haven't seen a pointer, we won't see one.
3991 if (numNormalPointers == 0)
3992 return PointerDeclaratorKind::NonPointer;
3993
3994 if (auto *recordDecl = type->getAsRecordDecl()) {
3995 // If this is CFErrorRef*, report it as such.
3996 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 &&
3997 S.ObjC().isCFError(recordDecl)) {
3998 return PointerDeclaratorKind::CFErrorRefPointer;
3999 }
4000 break;
4001 }
4002
4003 break;
4004 } while (true);
4005
4006 switch (numNormalPointers) {
4007 case 0:
4008 return PointerDeclaratorKind::NonPointer;
4009
4010 case 1:
4011 return PointerDeclaratorKind::SingleLevelPointer;
4012
4013 case 2:
4014 return PointerDeclaratorKind::MaybePointerToCFRef;
4015
4016 default:
4017 return PointerDeclaratorKind::MultiLevelPointer;
4018 }
4019}
4020
4022 SourceLocation loc) {
4023 // If we're anywhere in a function, method, or closure context, don't perform
4024 // completeness checks.
4025 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
4026 if (ctx->isFunctionOrMethod())
4027 return FileID();
4028
4029 if (ctx->isFileContext())
4030 break;
4031 }
4032
4033 // We only care about the expansion location.
4034 loc = S.SourceMgr.getExpansionLoc(loc);
4035 FileID file = S.SourceMgr.getFileID(loc);
4036 if (file.isInvalid())
4037 return FileID();
4038
4039 // Retrieve file information.
4040 bool invalid = false;
4041 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4042 if (invalid || !sloc.isFile())
4043 return FileID();
4044
4045 // We don't want to perform completeness checks on the main file or in
4046 // system headers.
4047 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4048 if (fileInfo.getIncludeLoc().isInvalid())
4049 return FileID();
4050 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4052 return FileID();
4053 }
4054
4055 return file;
4056}
4057
4058/// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4059/// taking into account whitespace before and after.
4060template <typename DiagBuilderT>
4061static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4062 SourceLocation PointerLoc,
4063 NullabilityKind Nullability) {
4064 assert(PointerLoc.isValid());
4065 if (PointerLoc.isMacroID())
4066 return;
4067
4068 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4069 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4070 return;
4071
4072 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4073 if (!NextChar)
4074 return;
4075
4076 SmallString<32> InsertionTextBuf{" "};
4077 InsertionTextBuf += getNullabilitySpelling(Nullability);
4078 InsertionTextBuf += " ";
4079 StringRef InsertionText = InsertionTextBuf.str();
4080
4081 if (isWhitespace(*NextChar)) {
4082 InsertionText = InsertionText.drop_back();
4083 } else if (NextChar[-1] == '[') {
4084 if (NextChar[0] == ']')
4085 InsertionText = InsertionText.drop_back().drop_front();
4086 else
4087 InsertionText = InsertionText.drop_front();
4088 } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) &&
4089 !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) {
4090 InsertionText = InsertionText.drop_back().drop_front();
4091 }
4092
4093 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4094}
4095
4097 SimplePointerKind PointerKind,
4098 SourceLocation PointerLoc,
4099 SourceLocation PointerEndLoc) {
4100 assert(PointerLoc.isValid());
4101
4102 if (PointerKind == SimplePointerKind::Array) {
4103 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4104 } else {
4105 S.Diag(PointerLoc, diag::warn_nullability_missing)
4106 << static_cast<unsigned>(PointerKind);
4107 }
4108
4109 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4110 if (FixItLoc.isMacroID())
4111 return;
4112
4113 auto addFixIt = [&](NullabilityKind Nullability) {
4114 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4115 Diag << static_cast<unsigned>(Nullability);
4116 Diag << static_cast<unsigned>(PointerKind);
4117 fixItNullability(S, Diag, FixItLoc, Nullability);
4118 };
4119 addFixIt(NullabilityKind::Nullable);
4120 addFixIt(NullabilityKind::NonNull);
4121}
4122
4123/// Complains about missing nullability if the file containing \p pointerLoc
4124/// has other uses of nullability (either the keywords or the \c assume_nonnull
4125/// pragma).
4126///
4127/// If the file has \e not seen other uses of nullability, this particular
4128/// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4129static void
4130checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4131 SourceLocation pointerLoc,
4132 SourceLocation pointerEndLoc = SourceLocation()) {
4133 // Determine which file we're performing consistency checking for.
4134 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4135 if (file.isInvalid())
4136 return;
4137
4138 // If we haven't seen any type nullability in this file, we won't warn now
4139 // about anything.
4140 FileNullability &fileNullability = S.NullabilityMap[file];
4141 if (!fileNullability.SawTypeNullability) {
4142 // If this is the first pointer declarator in the file, and the appropriate
4143 // warning is on, record it in case we need to diagnose it retroactively.
4144 diag::kind diagKind;
4145 if (pointerKind == SimplePointerKind::Array)
4146 diagKind = diag::warn_nullability_missing_array;
4147 else
4148 diagKind = diag::warn_nullability_missing;
4149
4150 if (fileNullability.PointerLoc.isInvalid() &&
4151 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
4152 fileNullability.PointerLoc = pointerLoc;
4153 fileNullability.PointerEndLoc = pointerEndLoc;
4154 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4155 }
4156
4157 return;
4158 }
4159
4160 // Complain about missing nullability.
4161 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4162}
4163
4164/// Marks that a nullability feature has been used in the file containing
4165/// \p loc.
4166///
4167/// If this file already had pointer types in it that were missing nullability,
4168/// the first such instance is retroactively diagnosed.
4169///
4170/// \sa checkNullabilityConsistency
4173 if (file.isInvalid())
4174 return;
4175
4176 FileNullability &fileNullability = S.NullabilityMap[file];
4177 if (fileNullability.SawTypeNullability)
4178 return;
4179 fileNullability.SawTypeNullability = true;
4180
4181 // If we haven't seen any type nullability before, now we have. Retroactively
4182 // diagnose the first unannotated pointer, if there was one.
4183 if (fileNullability.PointerLoc.isInvalid())
4184 return;
4185
4186 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4187 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
4188 fileNullability.PointerEndLoc);
4189}
4190
4191/// Returns true if any of the declarator chunks before \p endIndex include a
4192/// level of indirection: array, pointer, reference, or pointer-to-member.
4193///
4194/// Because declarator chunks are stored in outer-to-inner order, testing
4195/// every chunk before \p endIndex is testing all chunks that embed the current
4196/// chunk as part of their type.
4197///
4198/// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4199/// end index, in which case all chunks are tested.
4200static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4201 unsigned i = endIndex;
4202 while (i != 0) {
4203 // Walk outwards along the declarator chunks.
4204 --i;
4205 const DeclaratorChunk &DC = D.getTypeObject(i);
4206 switch (DC.Kind) {
4208 break;
4213 return true;
4217 // These are invalid anyway, so just ignore.
4218 break;
4219 }
4220 }
4221 return false;
4222}
4223
4224static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk) {
4225 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4226 Chunk.Kind == DeclaratorChunk::Array);
4227}
4228
4229template<typename AttrT>
4230static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4231 AL.setUsedAsTypeAttr();
4232 return ::new (Ctx) AttrT(Ctx, AL);
4233}
4234
4236 NullabilityKind NK) {
4237 switch (NK) {
4240
4243
4246
4249 }
4250 llvm_unreachable("unknown NullabilityKind");
4251}
4252
4253// Diagnose whether this is a case with the multiple addr spaces.
4254// Returns true if this is an invalid case.
4255// ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4256// by qualifiers for two or more different address spaces."
4258 LangAS ASNew,
4259 SourceLocation AttrLoc) {
4260 if (ASOld != LangAS::Default) {
4261 if (ASOld != ASNew) {
4262 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4263 return true;
4264 }
4265 // Emit a warning if they are identical; it's likely unintended.
4266 S.Diag(AttrLoc,
4267 diag::warn_attribute_address_multiple_identical_qualifiers);
4268 }
4269 return false;
4270}
4271
4272// Whether this is a type broadly expected to have nullability attached.
4273// These types are affected by `#pragma assume_nonnull`, and missing nullability
4274// will be diagnosed with -Wnullability-completeness.
4276 return T->canHaveNullability(/*ResultIfUnknown=*/false) &&
4277 // For now, do not infer/require nullability on C++ smart pointers.
4278 // It's unclear whether the pragma's behavior is useful for C++.
4279 // e.g. treating type-aliases and template-type-parameters differently
4280 // from types of declarations can be surprising.
4282 T->getCanonicalTypeInternal());
4283}
4284
4285static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4286 QualType declSpecType,
4287 TypeSourceInfo *TInfo) {
4288 // The TypeSourceInfo that this function returns will not be a null type.
4289 // If there is an error, this function will fill in a dummy type as fallback.
4290 QualType T = declSpecType;
4291 Declarator &D = state.getDeclarator();
4292 Sema &S = state.getSema();
4293 ASTContext &Context = S.Context;
4294 const LangOptions &LangOpts = S.getLangOpts();
4295
4296 // The name we're declaring, if any.
4297 DeclarationName Name;
4298 if (D.getIdentifier())
4299 Name = D.getIdentifier();
4300
4301 // Does this declaration declare a typedef-name?
4302 bool IsTypedefName =
4306
4307 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4308 bool IsQualifiedFunction = T->isFunctionProtoType() &&
4309 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4310 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4311
4312 // If T is 'decltype(auto)', the only declarators we can have are parens
4313 // and at most one function declarator if this is a function declaration.
4314 // If T is a deduced class template specialization type, only parentheses
4315 // are allowed.
4316 if (auto *DT = T->getAs<DeducedType>()) {
4317 const AutoType *AT = T->getAs<AutoType>();
4318 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4319 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4320 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4321 unsigned Index = E - I - 1;
4322 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4323 unsigned DiagId = IsClassTemplateDeduction
4324 ? diag::err_deduced_class_template_compound_type
4325 : diag::err_decltype_auto_compound_type;
4326 unsigned DiagKind = 0;
4327 switch (DeclChunk.Kind) {
4329 continue;
4331 if (IsClassTemplateDeduction) {
4332 DiagKind = 3;
4333 break;
4334 }
4335 unsigned FnIndex;
4337 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4338 continue;
4339 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4340 break;
4341 }
4345 DiagKind = 0;
4346 break;
4348 DiagKind = 1;
4349 break;
4351 DiagKind = 2;
4352 break;
4354 break;
4355 }
4356
4357 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4358 D.setInvalidType(true);
4359 break;
4360 }
4361 }
4362 }
4363
4364 // Determine whether we should infer _Nonnull on pointer types.
4365 std::optional<NullabilityKind> inferNullability;
4366 bool inferNullabilityCS = false;
4367 bool inferNullabilityInnerOnly = false;
4368 bool inferNullabilityInnerOnlyComplete = false;
4369
4370 // Are we in an assume-nonnull region?
4371 bool inAssumeNonNullRegion = false;
4372 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4373 if (assumeNonNullLoc.isValid()) {
4374 inAssumeNonNullRegion = true;
4375 recordNullabilitySeen(S, assumeNonNullLoc);
4376 }
4377
4378 // Whether to complain about missing nullability specifiers or not.
4379 enum {
4380 /// Never complain.
4381 CAMN_No,
4382 /// Complain on the inner pointers (but not the outermost
4383 /// pointer).
4384 CAMN_InnerPointers,
4385 /// Complain about any pointers that don't have nullability
4386 /// specified or inferred.
4387 CAMN_Yes
4388 } complainAboutMissingNullability = CAMN_No;
4389 unsigned NumPointersRemaining = 0;
4390 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4391
4392 if (IsTypedefName) {
4393 // For typedefs, we do not infer any nullability (the default),
4394 // and we only complain about missing nullability specifiers on
4395 // inner pointers.
4396 complainAboutMissingNullability = CAMN_InnerPointers;
4397
4398 if (shouldHaveNullability(T) && !T->getNullability()) {
4399 // Note that we allow but don't require nullability on dependent types.
4400 ++NumPointersRemaining;
4401 }
4402
4403 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4404 DeclaratorChunk &chunk = D.getTypeObject(i);
4405 switch (chunk.Kind) {
4409 break;
4410
4413 ++NumPointersRemaining;
4414 break;
4415
4418 continue;
4419
4421 ++NumPointersRemaining;
4422 continue;
4423 }
4424 }
4425 } else {
4426 bool isFunctionOrMethod = false;
4427 switch (auto context = state.getDeclarator().getContext()) {
4433 isFunctionOrMethod = true;
4434 [[fallthrough]];
4435
4437 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4438 complainAboutMissingNullability = CAMN_No;
4439 break;
4440 }
4441
4442 // Weak properties are inferred to be nullable.
4443 if (state.getDeclarator().isObjCWeakProperty()) {
4444 // Weak properties cannot be nonnull, and should not complain about
4445 // missing nullable attributes during completeness checks.
4446 complainAboutMissingNullability = CAMN_No;
4447 if (inAssumeNonNullRegion) {
4448 inferNullability = NullabilityKind::Nullable;
4449 }
4450 break;
4451 }
4452
4453 [[fallthrough]];
4454
4457 complainAboutMissingNullability = CAMN_Yes;
4458
4459 // Nullability inference depends on the type and declarator.
4460 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4461 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4462 case PointerDeclaratorKind::NonPointer:
4463 case PointerDeclaratorKind::MultiLevelPointer:
4464 // Cannot infer nullability.
4465 break;
4466
4467 case PointerDeclaratorKind::SingleLevelPointer:
4468 // Infer _Nonnull if we are in an assumes-nonnull region.
4469 if (inAssumeNonNullRegion) {
4470 complainAboutInferringWithinChunk = wrappingKind;
4471 inferNullability = NullabilityKind::NonNull;
4472 inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4474 }
4475 break;
4476
4477 case PointerDeclaratorKind::CFErrorRefPointer:
4478 case PointerDeclaratorKind::NSErrorPointerPointer:
4479 // Within a function or method signature, infer _Nullable at both
4480 // levels.
4481 if (isFunctionOrMethod && inAssumeNonNullRegion)
4482 inferNullability = NullabilityKind::Nullable;
4483 break;
4484
4485 case PointerDeclaratorKind::MaybePointerToCFRef:
4486 if (isFunctionOrMethod) {
4487 // On pointer-to-pointer parameters marked cf_returns_retained or
4488 // cf_returns_not_retained, if the outer pointer is explicit then
4489 // infer the inner pointer as _Nullable.
4490 auto hasCFReturnsAttr =
4491 [](const ParsedAttributesView &AttrList) -> bool {
4492 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4493 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4494 };
4495 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4496 if (hasCFReturnsAttr(D.getDeclarationAttributes()) ||
4497 hasCFReturnsAttr(D.getAttributes()) ||
4498 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4499 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4500 inferNullability = NullabilityKind::Nullable;
4501 inferNullabilityInnerOnly = true;
4502 }
4503 }
4504 }
4505 break;
4506 }
4507 break;
4508 }
4509
4511 complainAboutMissingNullability = CAMN_Yes;
4512 break;
4513
4533 // Don't infer in these contexts.
4534 break;
4535 }
4536 }
4537
4538 // Local function that returns true if its argument looks like a va_list.
4539 auto isVaList = [&S](QualType T) -> bool {
4540 auto *typedefTy = T->getAs<TypedefType>();
4541 if (!typedefTy)
4542 return false;
4543 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4544 do {
4545 if (typedefTy->getDecl() == vaListTypedef)
4546 return true;
4547 if (auto *name = typedefTy->getDecl()->getIdentifier())
4548 if (name->isStr("va_list"))
4549 return true;
4550 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4551 } while (typedefTy);
4552 return false;
4553 };
4554
4555 // Local function that checks the nullability for a given pointer declarator.
4556 // Returns true if _Nonnull was inferred.
4557 auto inferPointerNullability =
4558 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4559 SourceLocation pointerEndLoc,
4560 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4561 // We've seen a pointer.
4562 if (NumPointersRemaining > 0)
4563 --NumPointersRemaining;
4564
4565 // If a nullability attribute is present, there's nothing to do.
4566 if (hasNullabilityAttr(attrs))
4567 return nullptr;
4568
4569 // If we're supposed to infer nullability, do so now.
4570 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4571 ParsedAttr::Form form =
4572 inferNullabilityCS
4573 ? ParsedAttr::Form::ContextSensitiveKeyword()
4574 : ParsedAttr::Form::Keyword(false /*IsAlignAs*/,
4575 false /*IsRegularKeywordAttribute*/);
4576 ParsedAttr *nullabilityAttr = Pool.create(
4577 S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4578 AttributeScopeInfo(), nullptr, 0, form);
4579
4580 attrs.addAtEnd(nullabilityAttr);
4581
4582 if (inferNullabilityCS) {
4583 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4584 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4585 }
4586
4587 if (pointerLoc.isValid() &&
4588 complainAboutInferringWithinChunk !=
4589 PointerWrappingDeclaratorKind::None) {
4590 auto Diag =
4591 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4592 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4594 }
4595
4596 if (inferNullabilityInnerOnly)
4597 inferNullabilityInnerOnlyComplete = true;
4598 return nullabilityAttr;
4599 }
4600
4601 // If we're supposed to complain about missing nullability, do so
4602 // now if it's truly missing.
4603 switch (complainAboutMissingNullability) {
4604 case CAMN_No:
4605 break;
4606
4607 case CAMN_InnerPointers:
4608 if (NumPointersRemaining == 0)
4609 break;
4610 [[fallthrough]];
4611
4612 case CAMN_Yes:
4613 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4614 }
4615 return nullptr;
4616 };
4617
4618 // If the type itself could have nullability but does not, infer pointer
4619 // nullability and perform consistency checking.
4620 if (S.CodeSynthesisContexts.empty()) {
4621 if (shouldHaveNullability(T) && !T->getNullability()) {
4622 if (isVaList(T)) {
4623 // Record that we've seen a pointer, but do nothing else.
4624 if (NumPointersRemaining > 0)
4625 --NumPointersRemaining;
4626 } else {
4627 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4628 if (T->isBlockPointerType())
4629 pointerKind = SimplePointerKind::BlockPointer;
4630 else if (T->isMemberPointerType())
4631 pointerKind = SimplePointerKind::MemberPointer;
4632
4633 if (auto *attr = inferPointerNullability(
4634 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4635 D.getDeclSpec().getEndLoc(),
4638 T = state.getAttributedType(
4639 createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4640 }
4641 }
4642 }
4643
4644 if (complainAboutMissingNullability == CAMN_Yes && T->isArrayType() &&
4645 !T->getNullability() && !isVaList(T) && D.isPrototypeContext() &&
4647 checkNullabilityConsistency(S, SimplePointerKind::Array,
4649 }
4650 }
4651
4652 bool ExpectNoDerefChunk =
4653 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4654
4655 // Walk the DeclTypeInfo, building the recursive type as we go.
4656 // DeclTypeInfos are ordered from the identifier out, which is
4657 // opposite of what we want :).
4658
4659 // Track if the produced type matches the structure of the declarator.
4660 // This is used later to decide if we can fill `TypeLoc` from
4661 // `DeclaratorChunk`s. E.g. it must be false if Clang recovers from
4662 // an error by replacing the type with `int`.
4663 bool AreDeclaratorChunksValid = true;
4664 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4665 unsigned chunkIndex = e - i - 1;
4666 state.setCurrentChunkIndex(chunkIndex);
4667 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4668 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4669 switch (DeclType.Kind) {
4671 if (i == 0)
4673 T = S.BuildParenType(T);
4674 break;
4676 // If blocks are disabled, emit an error.
4677 if (!LangOpts.Blocks)
4678 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4679
4680 // Handle pointer nullability.
4681 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4682 DeclType.EndLoc, DeclType.getAttrs(),
4683 state.getDeclarator().getAttributePool());
4684
4685 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4686 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4687 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4688 // qualified with const.
4689 if (LangOpts.OpenCL)
4690 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4691 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4692 }
4693 break;
4695 // Verify that we're not building a pointer to pointer to function with
4696 // exception specification.
4697 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4698 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4699 D.setInvalidType(true);
4700 // Build the type anyway.
4701 }
4702
4703 // Handle pointer nullability
4704 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4705 DeclType.EndLoc, DeclType.getAttrs(),
4706 state.getDeclarator().getAttributePool());
4707
4708 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
4709 T = Context.getObjCObjectPointerType(T);
4710 if (DeclType.Ptr.TypeQuals)
4711 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4712 break;
4713 }
4714
4715 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4716 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4717 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4718 if (LangOpts.OpenCL) {
4719 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4720 T->isBlockPointerType()) {
4721 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4722 D.setInvalidType(true);
4723 }
4724 }
4725
4726 T = S.BuildPointerType(T, DeclType.Loc, Name);
4727 if (DeclType.Ptr.TypeQuals)
4728 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4729 break;
4731 // Verify that we're not building a reference to pointer to function with
4732 // exception specification.
4733 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4734 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4735 D.setInvalidType(true);
4736 // Build the type anyway.
4737 }
4738 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4739
4740 if (DeclType.Ref.HasRestrict)
4742 break;
4743 }
4745 // Verify that we're not building an array of pointers to function with
4746 // exception specification.
4747 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4748 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4749 D.setInvalidType(true);
4750 // Build the type anyway.
4751 }
4752 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4753 Expr *ArraySize = ATI.NumElts;
4755
4756 // Microsoft property fields can have multiple sizeless array chunks
4757 // (i.e. int x[][][]). Skip all of these except one to avoid creating
4758 // bad incomplete array types.
4759 if (chunkIndex != 0 && !ArraySize &&
4761 // This is a sizeless chunk. If the next is also, skip this one.
4762 DeclaratorChunk &NextDeclType = D.getTypeObject(chunkIndex - 1);
4763 if (NextDeclType.Kind == DeclaratorChunk::Array &&
4764 !NextDeclType.Arr.NumElts)
4765 break;
4766 }
4767
4768 if (ATI.isStar)
4770 else if (ATI.hasStatic)
4772 else
4774 if (ASM == ArraySizeModifier::Star && !D.isPrototypeContext()) {
4775 // FIXME: This check isn't quite right: it allows star in prototypes
4776 // for function definitions, and disallows some edge cases detailed
4777 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4778 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4780 D.setInvalidType(true);
4781 }
4782
4783 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4784 // shall appear only in a declaration of a function parameter with an
4785 // array type, ...
4786 if (ASM == ArraySizeModifier::Static || ATI.TypeQuals) {
4787 if (!(D.isPrototypeContext() ||
4789 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype)
4790 << (ASM == ArraySizeModifier::Static ? "'static'"
4791 : "type qualifier");
4792 // Remove the 'static' and the type qualifiers.
4793 if (ASM == ArraySizeModifier::Static)
4795 ATI.TypeQuals = 0;
4796 D.setInvalidType(true);
4797 }
4798
4799 // C99 6.7.5.2p1: ... and then only in the outermost array type
4800 // derivation.
4801 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4802 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost)
4803 << (ASM == ArraySizeModifier::Static ? "'static'"
4804 : "type qualifier");
4805 if (ASM == ArraySizeModifier::Static)
4807 ATI.TypeQuals = 0;
4808 D.setInvalidType(true);
4809 }
4810 }
4811
4812 // Array parameters can be marked nullable as well, although it's not
4813 // necessary if they're marked 'static'.
4814 if (complainAboutMissingNullability == CAMN_Yes &&
4815 !hasNullabilityAttr(DeclType.getAttrs()) &&
4817 !hasOuterPointerLikeChunk(D, chunkIndex)) {
4818 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4819 }
4820
4821 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4822 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4823 break;
4824 }
4826 // If the function declarator has a prototype (i.e. it is not () and
4827 // does not have a K&R-style identifier list), then the arguments are part
4828 // of the type, otherwise the argument list is ().
4829 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4830 IsQualifiedFunction =
4832
4833 // Check for auto functions and trailing return type and adjust the
4834 // return type accordingly.
4835 if (!D.isInvalidType()) {
4836 auto IsClassType = [&](CXXScopeSpec &SS) {
4837 // If there already was an problem with the scope, don’t issue another
4838 // error about the explicit object parameter.
4839 return SS.isInvalid() ||
4840 isa_and_present<CXXRecordDecl>(S.computeDeclContext(SS));
4841 };
4842
4843 // C++23 [dcl.fct]p6:
4844 //
4845 // An explicit-object-parameter-declaration is a parameter-declaration
4846 // with a this specifier. An explicit-object-parameter-declaration shall
4847 // appear only as the first parameter-declaration of a
4848 // parameter-declaration-list of one of:
4849 //
4850 // - a declaration of a member function or member function template
4851 // ([class.mem]), or
4852 //
4853 // - an explicit instantiation ([temp.explicit]) or explicit
4854 // specialization ([temp.expl.spec]) of a templated member function,
4855 // or
4856 //
4857 // - a lambda-declarator [expr.prim.lambda].
4860 FTI.NumParams
4861 ? dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param)
4862 : nullptr;
4863
4864 bool IsFunctionDecl = D.getInnermostNonParenChunk() == &DeclType;
4865 if (First && First->isExplicitObjectParameter() &&
4867
4868 // Either not a member or nested declarator in a member.
4869 //
4870 // Note that e.g. 'static' or 'friend' declarations are accepted
4871 // here; we diagnose them later when we build the member function
4872 // because it's easier that way.
4873 (C != DeclaratorContext::Member || !IsFunctionDecl) &&
4874
4875 // Allow out-of-line definitions of member functions.
4876 !IsClassType(D.getCXXScopeSpec())) {
4877 if (IsFunctionDecl)
4878 S.Diag(First->getBeginLoc(),
4879 diag::err_explicit_object_parameter_nonmember)
4880 << /*non-member*/ 2 << /*function*/ 0
4881 << First->getSourceRange();
4882 else
4883 S.Diag(First->getBeginLoc(),
4884 diag::err_explicit_object_parameter_invalid)
4885 << First->getSourceRange();
4886 // Do let non-member function have explicit parameters
4887 // to not break assumptions elsewhere in the code.
4888 First->setExplicitObjectParameterLoc(SourceLocation());
4889 D.setInvalidType();
4890 AreDeclaratorChunksValid = false;
4891 }
4892
4893 // trailing-return-type is only required if we're declaring a function,
4894 // and not, for instance, a pointer to a function.
4895 if (D.getDeclSpec().hasAutoTypeSpec() &&
4896 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
4897 if (!S.getLangOpts().CPlusPlus14) {
4900 ? diag::err_auto_missing_trailing_return
4901 : diag::err_deduced_return_type);
4902 T = Context.IntTy;
4903 D.setInvalidType(true);
4904 AreDeclaratorChunksValid = false;
4905 } else {
4907 diag::warn_cxx11_compat_deduced_return_type);
4908 }
4909 } else if (FTI.hasTrailingReturnType()) {
4910 // T must be exactly 'auto' at this point. See CWG issue 681.
4911 if (isa<ParenType>(T)) {
4912 S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
4913 << T << D.getSourceRange();
4914 D.setInvalidType(true);
4915 // FIXME: recover and fill decls in `TypeLoc`s.
4916 AreDeclaratorChunksValid = false;
4917 } else if (D.getName().getKind() ==
4919 if (T != Context.DependentTy) {
4921 diag::err_deduction_guide_with_complex_decl)
4922 << D.getSourceRange();
4923 D.setInvalidType(true);
4924 // FIXME: recover and fill decls in `TypeLoc`s.
4925 AreDeclaratorChunksValid = false;
4926 }
4927 } else if (D.getContext() != DeclaratorContext::LambdaExpr &&
4928 (T.hasQualifiers() || !isa<AutoType>(T) ||
4929 cast<AutoType>(T)->getKeyword() !=
4931 cast<AutoType>(T)->isConstrained())) {
4932 // Attach a valid source location for diagnostics on functions with
4933 // trailing return types missing 'auto'. Attempt to get the location
4934 // from the declared type; if invalid, fall back to the trailing
4935 // return type's location.
4938 if (Loc.isInvalid()) {
4939 Loc = FTI.getTrailingReturnTypeLoc();
4940 SR = D.getSourceRange();
4941 }
4942 S.Diag(Loc, diag::err_trailing_return_without_auto) << T << SR;
4943 D.setInvalidType(true);
4944 // FIXME: recover and fill decls in `TypeLoc`s.
4945 AreDeclaratorChunksValid = false;
4946 }
4947 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
4948 if (T.isNull()) {
4949 // An error occurred parsing the trailing return type.
4950 T = Context.IntTy;
4951 D.setInvalidType(true);
4952 } else if (AutoType *Auto = T->getContainedAutoType()) {
4953 // If the trailing return type contains an `auto`, we may need to
4954 // invent a template parameter for it, for cases like
4955 // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
4956 InventedTemplateParameterInfo *InventedParamInfo = nullptr;
4958 InventedParamInfo = &S.InventedParameterInfos.back();
4960 InventedParamInfo = S.getCurLambda();
4961 if (InventedParamInfo) {
4962 std::tie(T, TInfo) = InventTemplateParameter(
4963 state, T, TInfo, Auto, *InventedParamInfo);
4964 }
4965 }
4966 } else {
4967 // This function type is not the type of the entity being declared,
4968 // so checking the 'auto' is not the responsibility of this chunk.
4969 }
4970 }
4971
4972 // C99 6.7.5.3p1: The return type may not be a function or array type.
4973 // For conversion functions, we'll diagnose this particular error later.
4974 if (!D.isInvalidType() &&
4975 ((T->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
4976 T->isFunctionType()) &&
4977 (D.getName().getKind() !=
4979 unsigned diagID = diag::err_func_returning_array_function;
4980 // Last processing chunk in block context means this function chunk
4981 // represents the block.
4982 if (chunkIndex == 0 &&
4984 diagID = diag::err_block_returning_array_function;
4985 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
4986 T = Context.IntTy;
4987 D.setInvalidType(true);
4988 AreDeclaratorChunksValid = false;
4989 }
4990
4991 // Do not allow returning half FP value.
4992 // FIXME: This really should be in BuildFunctionType.
4993 if (T->isHalfType()) {
4994 if (S.getLangOpts().OpenCL) {
4995 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
4996 S.getLangOpts())) {
4997 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4998 << T << 0 /*pointer hint*/;
4999 D.setInvalidType(true);
5000 }
5001 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5003 S.Diag(D.getIdentifierLoc(),
5004 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
5005 D.setInvalidType(true);
5006 }
5007 }
5008
5009 // __ptrauth is illegal on a function return type.
5010 if (T.getPointerAuth()) {
5011 S.Diag(DeclType.Loc, diag::err_ptrauth_qualifier_invalid) << T << 0;
5012 }
5013
5014 if (LangOpts.OpenCL) {
5015 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
5016 // function.
5017 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
5018 T->isPipeType()) {
5019 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5020 << T << 1 /*hint off*/;
5021 D.setInvalidType(true);
5022 }
5023 // OpenCL doesn't support variadic functions and blocks
5024 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
5025 // We also allow here any toolchain reserved identifiers.
5026 if (FTI.isVariadic &&
5028 "__cl_clang_variadic_functions", S.getLangOpts()) &&
5029 !(D.getIdentifier() &&
5030 ((D.getIdentifier()->getName() == "printf" &&
5031 LangOpts.getOpenCLCompatibleVersion() >= 120) ||
5032 D.getIdentifier()->getName().starts_with("__")))) {
5033 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
5034 D.setInvalidType(true);
5035 }
5036 }
5037
5038 // Methods cannot return interface types. All ObjC objects are
5039 // passed by reference.
5040 if (T->isObjCObjectType()) {
5041 SourceLocation DiagLoc, FixitLoc;
5042 if (TInfo) {
5043 DiagLoc = TInfo->getTypeLoc().getBeginLoc();
5044 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
5045 } else {
5046 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5047 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
5048 }
5049 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
5050 << 0 << T
5051 << FixItHint::CreateInsertion(FixitLoc, "*");
5052
5053 T = Context.getObjCObjectPointerType(T);
5054 if (TInfo) {
5055 TypeLocBuilder TLB;
5056 TLB.pushFullCopy(TInfo->getTypeLoc());
5058 TLoc.setStarLoc(FixitLoc);
5059 TInfo = TLB.getTypeSourceInfo(Context, T);
5060 } else {
5061 AreDeclaratorChunksValid = false;
5062 }
5063
5064 D.setInvalidType(true);
5065 }
5066
5067 // cv-qualifiers on return types are pointless except when the type is a
5068 // class type in C++.
5069 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
5070 !(S.getLangOpts().CPlusPlus &&
5071 (T->isDependentType() || T->isRecordType()))) {
5072 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
5075 // [6.9.1/3] qualified void return is invalid on a C
5076 // function definition. Apparently ok on declarations and
5077 // in C++ though (!)
5078 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
5079 } else
5080 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
5081 }
5082
5083 // C++2a [dcl.fct]p12:
5084 // A volatile-qualified return type is deprecated
5085 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20)
5086 S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T;
5087
5088 // Objective-C ARC ownership qualifiers are ignored on the function
5089 // return type (by type canonicalization). Complain if this attribute
5090 // was written here.
5091 if (T.getQualifiers().hasObjCLifetime()) {
5092 SourceLocation AttrLoc;
5093 if (chunkIndex + 1 < D.getNumTypeObjects()) {
5094 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
5095 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5096 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5097 AttrLoc = AL.getLoc();
5098 break;
5099 }
5100 }
5101 }
5102 if (AttrLoc.isInvalid()) {
5103 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5104 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5105 AttrLoc = AL.getLoc();
5106 break;
5107 }
5108 }
5109 }
5110
5111 if (AttrLoc.isValid()) {
5112 // The ownership attributes are almost always written via
5113 // the predefined
5114 // __strong/__weak/__autoreleasing/__unsafe_unretained.
5115 if (AttrLoc.isMacroID())
5116 AttrLoc =
5118
5119 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
5120 << T.getQualifiers().getObjCLifetime();
5121 }
5122 }
5123
5124 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
5125 // C++ [dcl.fct]p6:
5126 // Types shall not be defined in return or parameter types.
5128 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
5129 << Context.getCanonicalTagType(Tag);
5130 }
5131
5132 // Exception specs are not allowed in typedefs. Complain, but add it
5133 // anyway.
5134 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
5136 diag::err_exception_spec_in_typedef)
5139
5140 // If we see "T var();" or "T var(T());" at block scope, it is probably
5141 // an attempt to initialize a variable, not a function declaration.
5142 if (FTI.isAmbiguous)
5143 warnAboutAmbiguousFunction(S, D, DeclType, T);
5144
5146 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
5147
5148 // OpenCL disallows functions without a prototype, but it doesn't enforce
5149 // strict prototypes as in C23 because it allows a function definition to
5150 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
5151 if (!FTI.NumParams && !FTI.isVariadic &&
5152 !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) {
5153 // Simple void foo(), where the incoming T is the result type.
5154 T = Context.getFunctionNoProtoType(T, EI);
5155 } else {
5156 // We allow a zero-parameter variadic function in C if the
5157 // function is marked with the "overloadable" attribute. Scan
5158 // for this attribute now. We also allow it in C23 per WG14 N2975.
5159 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
5160 if (LangOpts.C23)
5161 S.Diag(FTI.getEllipsisLoc(),
5162 diag::warn_c17_compat_ellipsis_only_parameter);
5164 ParsedAttr::AT_Overloadable) &&
5166 ParsedAttr::AT_Overloadable) &&
5168 ParsedAttr::AT_Overloadable))
5169 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
5170 }
5171
5172 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
5173 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5174 // definition.
5175 S.Diag(FTI.Params[0].IdentLoc,
5176 diag::err_ident_list_in_fn_declaration);
5177 D.setInvalidType(true);
5178 // Recover by creating a K&R-style function type, if possible.
5179 T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL)
5180 ? Context.getFunctionNoProtoType(T, EI)
5181 : Context.IntTy;
5182 AreDeclaratorChunksValid = false;
5183 break;
5184 }
5185
5187 EPI.ExtInfo = EI;
5188 EPI.Variadic = FTI.isVariadic;
5189 EPI.EllipsisLoc = FTI.getEllipsisLoc();
5193 : 0);
5196 : RQ_RValue;
5197
5198 // Otherwise, we have a function with a parameter list that is
5199 // potentially variadic.
5201 ParamTys.reserve(FTI.NumParams);
5202
5204 ExtParameterInfos(FTI.NumParams);
5205 bool HasAnyInterestingExtParameterInfos = false;
5206
5207 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
5208 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5209 QualType ParamTy = Param->getType();
5210 assert(!ParamTy.isNull() && "Couldn't parse type?");
5211
5212 // Look for 'void'. void is allowed only as a single parameter to a
5213 // function with no other parameters (C99 6.7.5.3p10). We record
5214 // int(void) as a FunctionProtoType with an empty parameter list.
5215 if (ParamTy->isVoidType()) {
5216 // If this is something like 'float(int, void)', reject it. 'void'
5217 // is an incomplete type (C99 6.2.5p19) and function decls cannot
5218 // have parameters of incomplete type.
5219 if (FTI.NumParams != 1 || FTI.isVariadic) {
5220 S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param);
5221 ParamTy = Context.IntTy;
5222 Param->setType(ParamTy);
5223 } else if (FTI.Params[i].Ident) {
5224 // Reject, but continue to parse 'int(void abc)'.
5225 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
5226 ParamTy = Context.IntTy;
5227 Param->setType(ParamTy);
5228 } else {
5229 // Reject, but continue to parse 'float(const void)'.
5230 if (ParamTy.hasQualifiers())
5231 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
5232
5233 for (const auto *A : Param->attrs()) {
5234 S.Diag(A->getLoc(), diag::warn_attribute_on_void_param)
5235 << A << A->getRange();
5236 }
5237
5238 // Reject, but continue to parse 'float(this void)' as
5239 // 'float(void)'.
5240 if (Param->isExplicitObjectParameter()) {
5241 S.Diag(Param->getLocation(),
5242 diag::err_void_explicit_object_param);
5243 Param->setExplicitObjectParameterLoc(SourceLocation());
5244 }
5245
5246 // Do not add 'void' to the list.
5247 break;
5248 }
5249 } else if (ParamTy->isHalfType()) {
5250 // Disallow half FP parameters.
5251 // FIXME: This really should be in BuildFunctionType.
5252 if (S.getLangOpts().OpenCL) {
5253 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5254 S.getLangOpts())) {
5255 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5256 << ParamTy << 0;
5257 D.setInvalidType();
5258 Param->setInvalidDecl();
5259 }
5260 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5262 S.Diag(Param->getLocation(),
5263 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5264 D.setInvalidType();
5265 }
5266 } else if (!FTI.hasPrototype) {
5267 if (Context.isPromotableIntegerType(ParamTy)) {
5268 ParamTy = Context.getPromotedIntegerType(ParamTy);
5269 Param->setKNRPromoted(true);
5270 } else if (const BuiltinType *BTy = ParamTy->getAs<BuiltinType>()) {
5271 if (BTy->getKind() == BuiltinType::Float) {
5272 ParamTy = Context.DoubleTy;
5273 Param->setKNRPromoted(true);
5274 }
5275 }
5276 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) {
5277 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5278 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5279 << ParamTy << 1 /*hint off*/;
5280 D.setInvalidType();
5281 }
5282
5283 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
5284 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
5285 HasAnyInterestingExtParameterInfos = true;
5286 }
5287
5288 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5289 ExtParameterInfos[i] =
5290 ExtParameterInfos[i].withABI(attr->getABI());
5291 HasAnyInterestingExtParameterInfos = true;
5292 }
5293
5294 if (Param->hasAttr<PassObjectSizeAttr>()) {
5295 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5296 HasAnyInterestingExtParameterInfos = true;
5297 }
5298
5299 if (Param->hasAttr<NoEscapeAttr>()) {
5300 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
5301 HasAnyInterestingExtParameterInfos = true;
5302 }
5303
5304 ParamTys.push_back(ParamTy);
5305 }
5306
5307 if (HasAnyInterestingExtParameterInfos) {
5308 EPI.ExtParameterInfos = ExtParameterInfos.data();
5309 checkExtParameterInfos(S, ParamTys, EPI,
5310 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
5311 }
5312
5313 SmallVector<QualType, 4> Exceptions;
5314 SmallVector<ParsedType, 2> DynamicExceptions;
5315 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5316 Expr *NoexceptExpr = nullptr;
5317
5318 if (FTI.getExceptionSpecType() == EST_Dynamic) {
5319 // FIXME: It's rather inefficient to have to split into two vectors
5320 // here.
5321 unsigned N = FTI.getNumExceptions();
5322 DynamicExceptions.reserve(N);
5323 DynamicExceptionRanges.reserve(N);
5324 for (unsigned I = 0; I != N; ++I) {
5325 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
5326 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
5327 }
5328 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
5329 NoexceptExpr = FTI.NoexceptExpr;
5330 }
5331
5334 DynamicExceptions,
5335 DynamicExceptionRanges,
5336 NoexceptExpr,
5337 Exceptions,
5338 EPI.ExceptionSpec);
5339
5340 // FIXME: Set address space from attrs for C++ mode here.
5341 // OpenCLCPlusPlus: A class member function has an address space.
5342 auto IsClassMember = [&]() {
5343 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5344 state.getDeclarator()
5345 .getCXXScopeSpec()
5346 .getScopeRep()
5347 .getKind() == NestedNameSpecifier::Kind::Type) ||
5348 state.getDeclarator().getContext() ==
5350 state.getDeclarator().getContext() ==
5352 };
5353
5354 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
5355 LangAS ASIdx = LangAS::Default;
5356 // Take address space attr if any and mark as invalid to avoid adding
5357 // them later while creating QualType.
5358 if (FTI.MethodQualifiers)
5360 LangAS ASIdxNew = attr.asOpenCLLangAS();
5361 if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
5362 attr.getLoc()))
5363 D.setInvalidType(true);
5364 else
5365 ASIdx = ASIdxNew;
5366 }
5367 // If a class member function's address space is not set, set it to
5368 // __generic.
5369 LangAS AS =
5371 : ASIdx);
5372 EPI.TypeQuals.addAddressSpace(AS);
5373 }
5374 T = Context.getFunctionType(T, ParamTys, EPI);
5375 }
5376 break;
5377 }
5379 // The scope spec must refer to a class, or be dependent.
5380 CXXScopeSpec &SS = DeclType.Mem.Scope();
5381
5382 // Handle pointer nullability.
5383 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5384 DeclType.EndLoc, DeclType.getAttrs(),
5385 state.getDeclarator().getAttributePool());
5386
5387 if (SS.isInvalid()) {
5388 // Avoid emitting extra errors if we already errored on the scope.
5389 D.setInvalidType(true);
5390 AreDeclaratorChunksValid = false;
5391 } else {
5392 T = S.BuildMemberPointerType(T, SS, /*Cls=*/nullptr, DeclType.Loc,
5393 D.getIdentifier());
5394 }
5395
5396 if (T.isNull()) {
5397 T = Context.IntTy;
5398 D.setInvalidType(true);
5399 AreDeclaratorChunksValid = false;
5400 } else if (DeclType.Mem.TypeQuals) {
5401 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
5402 }
5403 break;
5404 }
5405
5406 case DeclaratorChunk::Pipe: {
5407 T = S.BuildReadPipeType(T, DeclType.Loc);
5410 break;
5411 }
5412 }
5413
5414 if (T.isNull()) {
5415 D.setInvalidType(true);
5416 T = Context.IntTy;
5417 AreDeclaratorChunksValid = false;
5418 }
5419
5420 // See if there are any attributes on this declarator chunk.
5421 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs(),
5423
5424 if (DeclType.Kind != DeclaratorChunk::Paren) {
5425 if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
5426 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5427
5428 ExpectNoDerefChunk = state.didParseNoDeref();
5429 }
5430 }
5431
5432 if (ExpectNoDerefChunk)
5433 S.Diag(state.getDeclarator().getBeginLoc(),
5434 diag::warn_noderef_on_non_pointer_or_array);
5435
5436 // GNU warning -Wstrict-prototypes
5437 // Warn if a function declaration or definition is without a prototype.
5438 // This warning is issued for all kinds of unprototyped function
5439 // declarations (i.e. function type typedef, function pointer etc.)
5440 // C99 6.7.5.3p14:
5441 // The empty list in a function declarator that is not part of a definition
5442 // of that function specifies that no information about the number or types
5443 // of the parameters is supplied.
5444 // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of
5445 // function declarations whose behavior changes in C23.
5446 if (!LangOpts.requiresStrictPrototypes()) {
5447 bool IsBlock = false;
5448 for (const DeclaratorChunk &DeclType : D.type_objects()) {
5449 switch (DeclType.Kind) {
5451 IsBlock = true;
5452 break;
5454 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5455 // We suppress the warning when there's no LParen location, as this
5456 // indicates the declaration was an implicit declaration, which gets
5457 // warned about separately via -Wimplicit-function-declaration. We also
5458 // suppress the warning when we know the function has a prototype.
5459 if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic &&
5460 FTI.getLParenLoc().isValid())
5461 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5462 << IsBlock
5463 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5464 IsBlock = false;
5465 break;
5466 }
5467 default:
5468 break;
5469 }
5470 }
5471 }
5472
5473 assert(!T.isNull() && "T must not be null after this point");
5474
5475 if (LangOpts.CPlusPlus && T->isFunctionType()) {
5476 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5477 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
5478
5479 // C++ 8.3.5p4:
5480 // A cv-qualifier-seq shall only be part of the function type
5481 // for a nonstatic member function, the function type to which a pointer
5482 // to member refers, or the top-level function type of a function typedef
5483 // declaration.
5484 //
5485 // Core issue 547 also allows cv-qualifiers on function types that are
5486 // top-level template type arguments.
5487 enum {
5488 NonMember,
5489 Member,
5490 ExplicitObjectMember,
5491 DeductionGuide
5492 } Kind = NonMember;
5494 Kind = DeductionGuide;
5495 else if (!D.getCXXScopeSpec().isSet()) {
5499 Kind = Member;
5500 } else {
5502 if (!DC || DC->isRecord())
5503 Kind = Member;
5504 }
5505
5506 if (Kind == Member) {
5507 unsigned I;
5508 if (D.isFunctionDeclarator(I)) {
5509 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5510 if (Chunk.Fun.NumParams) {
5511 auto *P = dyn_cast_or_null<ParmVarDecl>(Chunk.Fun.Params->Param);
5512 if (P && P->isExplicitObjectParameter())
5513 Kind = ExplicitObjectMember;
5514 }
5515 }
5516 }
5517
5518 // C++11 [dcl.fct]p6 (w/DR1417):
5519 // An attempt to specify a function type with a cv-qualifier-seq or a
5520 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5521 // - the function type for a non-static member function,
5522 // - the function type to which a pointer to member refers,
5523 // - the top-level function type of a function typedef declaration or
5524 // alias-declaration,
5525 // - the type-id in the default argument of a type-parameter, or
5526 // - the type-id of a template-argument for a type-parameter
5527 //
5528 // C++23 [dcl.fct]p6 (P0847R7)
5529 // ... A member-declarator with an explicit-object-parameter-declaration
5530 // shall not include a ref-qualifier or a cv-qualifier-seq and shall not be
5531 // declared static or virtual ...
5532 //
5533 // FIXME: Checking this here is insufficient. We accept-invalid on:
5534 //
5535 // template<typename T> struct S { void f(T); };
5536 // S<int() const> s;
5537 //
5538 // ... for instance.
5539 if (IsQualifiedFunction &&
5540 // Check for non-static member function and not and
5541 // explicit-object-parameter-declaration
5542 (Kind != Member || D.isExplicitObjectMemberFunction() ||
5545 D.isStaticMember())) &&
5546 !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg &&
5548 SourceLocation Loc = D.getBeginLoc();
5549 SourceRange RemovalRange;
5550 unsigned I;
5551 if (D.isFunctionDeclarator(I)) {
5553 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5554 assert(Chunk.Kind == DeclaratorChunk::Function);
5555
5556 if (Chunk.Fun.hasRefQualifier())
5557 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5558
5559 if (Chunk.Fun.hasMethodTypeQualifiers())
5561 [&](DeclSpec::TQ TypeQual, StringRef QualName,
5562 SourceLocation SL) { RemovalLocs.push_back(SL); });
5563
5564 if (!RemovalLocs.empty()) {
5565 llvm::sort(RemovalLocs,
5567 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5568 Loc = RemovalLocs.front();
5569 }
5570 }
5571
5572 S.Diag(Loc, diag::err_invalid_qualified_function_type)
5573 << Kind << D.isFunctionDeclarator() << T
5575 << FixItHint::CreateRemoval(RemovalRange);
5576
5577 // Strip the cv-qualifiers and ref-qualifiers from the type.
5580 EPI.RefQualifier = RQ_None;
5581
5582 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5583 EPI);
5584 // Rebuild any parens around the identifier in the function type.
5585 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5587 break;
5588 T = S.BuildParenType(T);
5589 }
5590 }
5591 }
5592
5593 // Apply any undistributed attributes from the declaration or declarator.
5594 ParsedAttributesView NonSlidingAttrs;
5595 for (ParsedAttr &AL : D.getDeclarationAttributes()) {
5596 if (!AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
5597 NonSlidingAttrs.addAtEnd(&AL);
5598 }
5599 }
5600 processTypeAttrs(state, T, TAL_DeclName, NonSlidingAttrs);
5602
5603 // Diagnose any ignored type attributes.
5604 state.diagnoseIgnoredTypeAttrs(T);
5605
5606 // C++0x [dcl.constexpr]p9:
5607 // A constexpr specifier used in an object declaration declares the object
5608 // as const.
5610 T->isObjectType())
5611 T.addConst();
5612
5613 // C++2a [dcl.fct]p4:
5614 // A parameter with volatile-qualified type is deprecated
5615 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 &&
5618 S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T;
5619
5620 // If there was an ellipsis in the declarator, the declaration declares a
5621 // parameter pack whose type may be a pack expansion type.
5622 if (D.hasEllipsis()) {
5623 // C++0x [dcl.fct]p13:
5624 // A declarator-id or abstract-declarator containing an ellipsis shall
5625 // only be used in a parameter-declaration. Such a parameter-declaration
5626 // is a parameter pack (14.5.3). [...]
5627 switch (D.getContext()) {
5631 // C++0x [dcl.fct]p13:
5632 // [...] When it is part of a parameter-declaration-clause, the
5633 // parameter pack is a function parameter pack (14.5.3). The type T
5634 // of the declarator-id of the function parameter pack shall contain
5635 // a template parameter pack; each template parameter pack in T is
5636 // expanded by the function parameter pack.
5637 //
5638 // We represent function parameter packs as function parameters whose
5639 // type is a pack expansion.
5640 if (!T->containsUnexpandedParameterPack() &&
5641 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) {
5642 S.Diag(D.getEllipsisLoc(),
5643 diag::err_function_parameter_pack_without_parameter_packs)
5644 << T << D.getSourceRange();
5646 } else {
5647 T = Context.getPackExpansionType(T, std::nullopt,
5648 /*ExpectPackInType=*/false);
5649 }
5650 break;
5652 // C++0x [temp.param]p15:
5653 // If a template-parameter is a [...] is a parameter-declaration that
5654 // declares a parameter pack (8.3.5), then the template-parameter is a
5655 // template parameter pack (14.5.3).
5656 //
5657 // Note: core issue 778 clarifies that, if there are any unexpanded
5658 // parameter packs in the type of the non-type template parameter, then
5659 // it expands those parameter packs.
5660 if (T->containsUnexpandedParameterPack())
5661 T = Context.getPackExpansionType(T, std::nullopt);
5662 else
5663 S.Diag(D.getEllipsisLoc(),
5664 LangOpts.CPlusPlus11
5665 ? diag::warn_cxx98_compat_variadic_templates
5666 : diag::ext_variadic_templates);
5667 break;
5668
5671 case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here?
5672 case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here?
5693 // FIXME: We may want to allow parameter packs in block-literal contexts
5694 // in the future.
5695 S.Diag(D.getEllipsisLoc(),
5696 diag::err_ellipsis_in_declarator_not_parameter);
5698 break;
5699 }
5700 }
5701
5702 assert(!T.isNull() && "T must not be null at the end of this function");
5703 if (!AreDeclaratorChunksValid)
5704 return Context.getTrivialTypeSourceInfo(T);
5705
5706 if (state.didParseHLSLParamMod() && !T->isConstantArrayType())
5708 return GetTypeSourceInfoForDeclarator(state, T, TInfo);
5709}
5710
5712 // Determine the type of the declarator. Not all forms of declarator
5713 // have a type.
5714
5715 TypeProcessingState state(*this, D);
5716
5717 TypeSourceInfo *ReturnTypeInfo = nullptr;
5718 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5719 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5720 inferARCWriteback(state, T);
5721
5722 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5723}
5724
5726 QualType &declSpecTy,
5727 Qualifiers::ObjCLifetime ownership) {
5728 if (declSpecTy->isObjCRetainableType() &&
5729 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5730 Qualifiers qs;
5731 qs.addObjCLifetime(ownership);
5732 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5733 }
5734}
5735
5736static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5737 Qualifiers::ObjCLifetime ownership,
5738 unsigned chunkIndex) {
5739 Sema &S = state.getSema();
5740 Declarator &D = state.getDeclarator();
5741
5742 // Look for an explicit lifetime attribute.
5743 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5744 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
5745 return;
5746
5747 const char *attrStr = nullptr;
5748 switch (ownership) {
5749 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5750 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5751 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5752 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5753 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5754 }
5755
5756 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5757 Arg->setIdentifierInfo(&S.Context.Idents.get(attrStr));
5758
5759 ArgsUnion Args(Arg);
5760
5761 // If there wasn't one, add one (with an invalid source location
5762 // so that we don't make an AttributedType for it).
5763 ParsedAttr *attr =
5764 D.getAttributePool().create(&S.Context.Idents.get("objc_ownership"),
5766 /*args*/ &Args, 1, ParsedAttr::Form::GNU());
5767 chunk.getAttrs().addAtEnd(attr);
5768 // TODO: mark whether we did this inference?
5769}
5770
5771/// Used for transferring ownership in casts resulting in l-values.
5772static void transferARCOwnership(TypeProcessingState &state,
5773 QualType &declSpecTy,
5774 Qualifiers::ObjCLifetime ownership) {
5775 Sema &S = state.getSema();
5776 Declarator &D = state.getDeclarator();
5777
5778 int inner = -1;
5779 bool hasIndirection = false;
5780 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5781 DeclaratorChunk &chunk = D.getTypeObject(i);
5782 switch (chunk.Kind) {
5784 // Ignore parens.
5785 break;
5786
5790 if (inner != -1)
5791 hasIndirection = true;
5792 inner = i;
5793 break;
5794
5796 if (inner != -1)
5797 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5798 return;
5799
5803 return;
5804 }
5805 }
5806
5807 if (inner == -1)
5808 return;
5809
5810 DeclaratorChunk &chunk = D.getTypeObject(inner);
5811 if (chunk.Kind == DeclaratorChunk::Pointer) {
5812 if (declSpecTy->isObjCRetainableType())
5813 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5814 if (declSpecTy->isObjCObjectType() && hasIndirection)
5815 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5816 } else {
5817 assert(chunk.Kind == DeclaratorChunk::Array ||
5819 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5820 }
5821}
5822
5824 TypeProcessingState state(*this, D);
5825
5826 TypeSourceInfo *ReturnTypeInfo = nullptr;
5827 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5828
5829 if (getLangOpts().ObjC) {
5830 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
5831 if (ownership != Qualifiers::OCL_None)
5832 transferARCOwnership(state, declSpecTy, ownership);
5833 }
5834
5835 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
5836}
5837
5839 TypeProcessingState &State) {
5840 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
5841}
5842
5844 TypeProcessingState &State) {
5846 State.getSema().HLSL().TakeLocForHLSLAttribute(TL.getTypePtr());
5847 TL.setSourceRange(LocInfo.Range);
5849}
5850
5852 const ParsedAttributesView &Attrs) {
5853 for (const ParsedAttr &AL : Attrs) {
5854 if (AL.getKind() == ParsedAttr::AT_MatrixType) {
5855 MTL.setAttrNameLoc(AL.getLoc());
5856 MTL.setAttrRowOperand(AL.getArgAsExpr(0));
5857 MTL.setAttrColumnOperand(AL.getArgAsExpr(1));
5859 return;
5860 }
5861 }
5862
5863 llvm_unreachable("no matrix_type attribute found at the expected location!");
5864}
5865
5866static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5867 SourceLocation Loc;
5868 switch (Chunk.Kind) {
5873 llvm_unreachable("cannot be _Atomic qualified");
5874
5876 Loc = Chunk.Ptr.AtomicQualLoc;
5877 break;
5878
5882 // FIXME: Provide a source location for the _Atomic keyword.
5883 break;
5884 }
5885
5886 ATL.setKWLoc(Loc);
5888}
5889
5890namespace {
5891 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5892 Sema &SemaRef;
5893 ASTContext &Context;
5894 TypeProcessingState &State;
5895 const DeclSpec &DS;
5896
5897 public:
5898 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
5899 const DeclSpec &DS)
5900 : SemaRef(S), Context(Context), State(State), DS(DS) {}
5901
5902 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5903 Visit(TL.getModifiedLoc());
5904 fillAttributedTypeLoc(TL, State);
5905 }
5906 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
5907 Visit(TL.getWrappedLoc());
5908 }
5909 void VisitHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL) {
5910 Visit(TL.getWrappedLoc());
5912 }
5913 void VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {}
5914 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
5915 Visit(TL.getInnerLoc());
5916 TL.setExpansionLoc(
5917 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
5918 }
5919 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5920 Visit(TL.getUnqualifiedLoc());
5921 }
5922 // Allow to fill pointee's type locations, e.g.,
5923 // int __attr * __attr * __attr *p;
5924 void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); }
5925 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5926 if (DS.getTypeSpecType() == TST_typename) {
5927 TypeSourceInfo *TInfo = nullptr;
5929 if (TInfo) {
5930 TL.copy(TInfo->getTypeLoc().castAs<TypedefTypeLoc>());
5931 return;
5932 }
5933 }
5934 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
5935 ? DS.getTypeSpecTypeLoc()
5936 : SourceLocation(),
5939 }
5940 void VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
5941 if (DS.getTypeSpecType() == TST_typename) {
5942 TypeSourceInfo *TInfo = nullptr;
5944 if (TInfo) {
5945 TL.copy(TInfo->getTypeLoc().castAs<UnresolvedUsingTypeLoc>());
5946 return;
5947 }
5948 }
5949 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
5950 ? DS.getTypeSpecTypeLoc()
5951 : SourceLocation(),
5954 }
5955 void VisitUsingTypeLoc(UsingTypeLoc TL) {
5956 if (DS.getTypeSpecType() == TST_typename) {
5957 TypeSourceInfo *TInfo = nullptr;
5959 if (TInfo) {
5960 TL.copy(TInfo->getTypeLoc().castAs<UsingTypeLoc>());
5961 return;
5962 }
5963 }
5964 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
5965 ? DS.getTypeSpecTypeLoc()
5966 : SourceLocation(),
5969 }
5970 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5972 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
5973 // addition field. What we have is good enough for display of location
5974 // of 'fixit' on interface name.
5975 TL.setNameEndLoc(DS.getEndLoc());
5976 }
5977 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5978 TypeSourceInfo *RepTInfo = nullptr;
5979 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5980 TL.copy(RepTInfo->getTypeLoc());
5981 }
5982 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5983 TypeSourceInfo *RepTInfo = nullptr;
5984 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5985 TL.copy(RepTInfo->getTypeLoc());
5986 }
5987 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
5988 TypeSourceInfo *TInfo = nullptr;
5990
5991 // If we got no declarator info from previous Sema routines,
5992 // just fill with the typespec loc.
5993 if (!TInfo) {
5994 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
5995 return;
5996 }
5997
5998 TypeLoc OldTL = TInfo->getTypeLoc();
5999 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
6000 assert(TL.getRAngleLoc() ==
6001 OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
6002 }
6003 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6008 }
6009 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6014 assert(DS.getRepAsType());
6015 TypeSourceInfo *TInfo = nullptr;
6017 TL.setUnmodifiedTInfo(TInfo);
6018 }
6019 void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6023 }
6024 void VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
6027 }
6028 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6029 assert(DS.isTransformTypeTrait(DS.getTypeSpecType()));
6032 assert(DS.getRepAsType());
6033 TypeSourceInfo *TInfo = nullptr;
6035 TL.setUnderlyingTInfo(TInfo);
6036 }
6037 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6038 // By default, use the source location of the type specifier.
6040 if (TL.needsExtraLocalData()) {
6041 // Set info for the written builtin specifiers.
6043 // Try to have a meaningful source location.
6044 if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified)
6046 if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified)
6048 }
6049 }
6050 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6051 assert(DS.getTypeSpecType() == TST_typename);
6052 TypeSourceInfo *TInfo = nullptr;
6054 assert(TInfo);
6055 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
6056 }
6057 void VisitAutoTypeLoc(AutoTypeLoc TL) {
6058 assert(DS.getTypeSpecType() == TST_auto ||
6065 if (!DS.isConstrainedAuto())
6066 return;
6067 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
6068 if (!TemplateId)
6069 return;
6070
6071 NestedNameSpecifierLoc NNS =
6072 (DS.getTypeSpecScope().isNotEmpty()
6074 : NestedNameSpecifierLoc());
6075 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
6076 TemplateId->RAngleLoc);
6077 if (TemplateId->NumArgs > 0) {
6078 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6079 TemplateId->NumArgs);
6080 SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
6081 }
6082 DeclarationNameInfo DNI = DeclarationNameInfo(
6083 TL.getTypePtr()->getTypeConstraintConcept()->getDeclName(),
6084 TemplateId->TemplateNameLoc);
6085
6086 NamedDecl *FoundDecl;
6087 if (auto TN = TemplateId->Template.get();
6088 UsingShadowDecl *USD = TN.getAsUsingShadowDecl())
6089 FoundDecl = cast<NamedDecl>(USD);
6090 else
6091 FoundDecl = cast_if_present<NamedDecl>(TN.getAsTemplateDecl());
6092
6093 auto *CR = ConceptReference::Create(
6094 Context, NNS, TemplateId->TemplateKWLoc, DNI, FoundDecl,
6095 /*NamedDecl=*/TL.getTypePtr()->getTypeConstraintConcept(),
6096 ASTTemplateArgumentListInfo::Create(Context, TemplateArgsInfo));
6097 TL.setConceptReference(CR);
6098 }
6099 void VisitDeducedTemplateSpecializationTypeLoc(
6100 DeducedTemplateSpecializationTypeLoc TL) {
6101 assert(DS.getTypeSpecType() == TST_typename);
6102 TypeSourceInfo *TInfo = nullptr;
6104 assert(TInfo);
6105 TL.copy(
6106 TInfo->getTypeLoc().castAs<DeducedTemplateSpecializationTypeLoc>());
6107 }
6108 void VisitTagTypeLoc(TagTypeLoc TL) {
6109 if (DS.getTypeSpecType() == TST_typename) {
6110 TypeSourceInfo *TInfo = nullptr;
6112 if (TInfo) {
6113 TL.copy(TInfo->getTypeLoc().castAs<TagTypeLoc>());
6114 return;
6115 }
6116 }
6117 TL.setElaboratedKeywordLoc(TL.getTypePtr()->getKeyword() !=
6118 ElaboratedTypeKeyword::None
6119 ? DS.getTypeSpecTypeLoc()
6120 : SourceLocation());
6123 }
6124 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6125 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
6126 // or an _Atomic qualifier.
6130
6131 TypeSourceInfo *TInfo = nullptr;
6133 assert(TInfo);
6135 } else {
6136 TL.setKWLoc(DS.getAtomicSpecLoc());
6137 // No parens, to indicate this was spelled as an _Atomic qualifier.
6138 TL.setParensRange(SourceRange());
6139 Visit(TL.getValueLoc());
6140 }
6141 }
6142
6143 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6145
6146 TypeSourceInfo *TInfo = nullptr;
6149 }
6150
6151 void VisitExtIntTypeLoc(BitIntTypeLoc TL) {
6153 }
6154
6155 void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) {
6157 }
6158
6159 void VisitTypeLoc(TypeLoc TL) {
6160 // FIXME: add other typespec types and change this to an assert.
6161 TL.initialize(Context, DS.getTypeSpecTypeLoc());
6162 }
6163 };
6164
6165 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
6166 ASTContext &Context;
6167 TypeProcessingState &State;
6168 const DeclaratorChunk &Chunk;
6169
6170 public:
6171 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
6172 const DeclaratorChunk &Chunk)
6173 : Context(Context), State(State), Chunk(Chunk) {}
6174
6175 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6176 llvm_unreachable("qualified type locs not expected here!");
6177 }
6178 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6179 llvm_unreachable("decayed type locs not expected here!");
6180 }
6181 void VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
6182 llvm_unreachable("array parameter type locs not expected here!");
6183 }
6184
6185 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6186 fillAttributedTypeLoc(TL, State);
6187 }
6188 void VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
6189 // nothing
6190 }
6191 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6192 // nothing
6193 }
6194 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6195 // nothing
6196 }
6197 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6198 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
6199 TL.setCaretLoc(Chunk.Loc);
6200 }
6201 void VisitPointerTypeLoc(PointerTypeLoc TL) {
6202 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6203 TL.setStarLoc(Chunk.Loc);
6204 }
6205 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6206 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6207 TL.setStarLoc(Chunk.Loc);
6208 }
6209 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6210 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
6211 TL.setStarLoc(Chunk.Mem.StarLoc);
6212 TL.setQualifierLoc(Chunk.Mem.Scope().getWithLocInContext(Context));
6213 }
6214 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6215 assert(Chunk.Kind == DeclaratorChunk::Reference);
6216 // 'Amp' is misleading: this might have been originally
6217 /// spelled with AmpAmp.
6218 TL.setAmpLoc(Chunk.Loc);
6219 }
6220 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6221 assert(Chunk.Kind == DeclaratorChunk::Reference);
6222 assert(!Chunk.Ref.LValueRef);
6223 TL.setAmpAmpLoc(Chunk.Loc);
6224 }
6225 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
6226 assert(Chunk.Kind == DeclaratorChunk::Array);
6227 TL.setLBracketLoc(Chunk.Loc);
6228 TL.setRBracketLoc(Chunk.EndLoc);
6229 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
6230 }
6231 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6232 assert(Chunk.Kind == DeclaratorChunk::Function);
6233 TL.setLocalRangeBegin(Chunk.Loc);
6234 TL.setLocalRangeEnd(Chunk.EndLoc);
6235
6236 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
6237 TL.setLParenLoc(FTI.getLParenLoc());
6238 TL.setRParenLoc(FTI.getRParenLoc());
6239 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
6240 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
6241 TL.setParam(tpi++, Param);
6242 }
6244 }
6245 void VisitParenTypeLoc(ParenTypeLoc TL) {
6246 assert(Chunk.Kind == DeclaratorChunk::Paren);
6247 TL.setLParenLoc(Chunk.Loc);
6248 TL.setRParenLoc(Chunk.EndLoc);
6249 }
6250 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6251 assert(Chunk.Kind == DeclaratorChunk::Pipe);
6252 TL.setKWLoc(Chunk.Loc);
6253 }
6254 void VisitBitIntTypeLoc(BitIntTypeLoc TL) {
6255 TL.setNameLoc(Chunk.Loc);
6256 }
6257 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6258 TL.setExpansionLoc(Chunk.Loc);
6259 }
6260 void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); }
6261 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) {
6262 TL.setNameLoc(Chunk.Loc);
6263 }
6264 void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6265 TL.setNameLoc(Chunk.Loc);
6266 }
6267 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6268 fillAtomicQualLoc(TL, Chunk);
6269 }
6270 void
6271 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) {
6272 TL.setNameLoc(Chunk.Loc);
6273 }
6274 void VisitMatrixTypeLoc(MatrixTypeLoc TL) {
6275 fillMatrixTypeLoc(TL, Chunk.getAttrs());
6276 }
6277
6278 void VisitTypeLoc(TypeLoc TL) {
6279 llvm_unreachable("unsupported TypeLoc kind in declarator!");
6280 }
6281 };
6282} // end anonymous namespace
6283
6284static void
6286 const ParsedAttributesView &Attrs) {
6287 for (const ParsedAttr &AL : Attrs) {
6288 if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
6289 DASTL.setAttrNameLoc(AL.getLoc());
6290 DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
6292 return;
6293 }
6294 }
6295
6296 llvm_unreachable(
6297 "no address_space attribute found at the expected location!");
6298}
6299
6300/// Create and instantiate a TypeSourceInfo with type source information.
6301///
6302/// \param T QualType referring to the type as written in source code.
6303///
6304/// \param ReturnTypeInfo For declarators whose return type does not show
6305/// up in the normal place in the declaration specifiers (such as a C++
6306/// conversion function), this pointer will refer to a type source information
6307/// for that return type.
6308static TypeSourceInfo *
6309GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
6310 QualType T, TypeSourceInfo *ReturnTypeInfo) {
6311 Sema &S = State.getSema();
6312 Declarator &D = State.getDeclarator();
6313
6315 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
6316
6317 // Handle parameter packs whose type is a pack expansion.
6319 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
6320 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6321 }
6322
6323 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6324 // Microsoft property fields can have multiple sizeless array chunks
6325 // (i.e. int x[][][]). Don't create more than one level of incomplete array.
6326 if (CurrTL.getTypeLocClass() == TypeLoc::IncompleteArray && e != 1 &&
6328 continue;
6329
6330 // An AtomicTypeLoc might be produced by an atomic qualifier in this
6331 // declarator chunk.
6332 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
6334 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
6335 }
6336
6337 bool HasDesugaredTypeLoc = true;
6338 while (HasDesugaredTypeLoc) {
6339 switch (CurrTL.getTypeLocClass()) {
6340 case TypeLoc::MacroQualified: {
6341 auto TL = CurrTL.castAs<MacroQualifiedTypeLoc>();
6342 TL.setExpansionLoc(
6343 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6344 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6345 break;
6346 }
6347
6348 case TypeLoc::Attributed: {
6349 auto TL = CurrTL.castAs<AttributedTypeLoc>();
6350 fillAttributedTypeLoc(TL, State);
6351 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6352 break;
6353 }
6354
6355 case TypeLoc::Adjusted:
6356 case TypeLoc::BTFTagAttributed: {
6357 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6358 break;
6359 }
6360
6361 case TypeLoc::DependentAddressSpace: {
6362 auto TL = CurrTL.castAs<DependentAddressSpaceTypeLoc>();
6364 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
6365 break;
6366 }
6367
6368 default:
6369 HasDesugaredTypeLoc = false;
6370 break;
6371 }
6372 }
6373
6374 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
6375 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6376 }
6377
6378 // If we have different source information for the return type, use
6379 // that. This really only applies to C++ conversion functions.
6380 if (ReturnTypeInfo) {
6381 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
6382 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
6383 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
6384 } else {
6385 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL);
6386 }
6387
6388 return TInfo;
6389}
6390
6391/// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
6393 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6394 // and Sema during declaration parsing. Try deallocating/caching them when
6395 // it's appropriate, instead of allocating them and keeping them around.
6396 LocInfoType *LocT = (LocInfoType *)BumpAlloc.Allocate(sizeof(LocInfoType),
6397 alignof(LocInfoType));
6398 new (LocT) LocInfoType(T, TInfo);
6399 assert(LocT->getTypeClass() != T->getTypeClass() &&
6400 "LocInfoType's TypeClass conflicts with an existing Type class");
6401 return ParsedType::make(QualType(LocT, 0));
6402}
6403
6405 const PrintingPolicy &Policy) const {
6406 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6407 " was used directly instead of getting the QualType through"
6408 " GetTypeFromParser");
6409}
6410
6412 // C99 6.7.6: Type names have no identifier. This is already validated by
6413 // the parser.
6414 assert(D.getIdentifier() == nullptr &&
6415 "Type name should have no identifier!");
6416
6418 QualType T = TInfo->getType();
6419 if (D.isInvalidType())
6420 return true;
6421
6422 // Make sure there are no unused decl attributes on the declarator.
6423 // We don't want to do this for ObjC parameters because we're going
6424 // to apply them to the actual parameter declaration.
6425 // Likewise, we don't want to do this for alias declarations, because
6426 // we are actually going to build a declaration from this eventually.
6431
6432 if (getLangOpts().CPlusPlus) {
6433 // Check that there are no default arguments (C++ only).
6435 }
6436
6437 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
6438 const AutoType *AT = TL.getTypePtr();
6439 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
6440 }
6441 return CreateParsedType(T, TInfo);
6442}
6443
6444//===----------------------------------------------------------------------===//
6445// Type Attribute Processing
6446//===----------------------------------------------------------------------===//
6447
6448/// Build an AddressSpace index from a constant expression and diagnose any
6449/// errors related to invalid address_spaces. Returns true on successfully
6450/// building an AddressSpace index.
6451static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
6452 const Expr *AddrSpace,
6453 SourceLocation AttrLoc) {
6454 if (!AddrSpace->isValueDependent()) {
6455 std::optional<llvm::APSInt> OptAddrSpace =
6456 AddrSpace->getIntegerConstantExpr(S.Context);
6457 if (!OptAddrSpace) {
6458 S.Diag(AttrLoc, diag::err_attribute_argument_type)
6459 << "'address_space'" << AANT_ArgumentIntegerConstant
6460 << AddrSpace->getSourceRange();
6461 return false;
6462 }
6463 llvm::APSInt &addrSpace = *OptAddrSpace;
6464
6465 // Bounds checking.
6466 if (addrSpace.isSigned()) {
6467 if (addrSpace.isNegative()) {
6468 S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
6469 << AddrSpace->getSourceRange();
6470 return false;
6471 }
6472 addrSpace.setIsSigned(false);
6473 }
6474
6475 llvm::APSInt max(addrSpace.getBitWidth());
6476 max =
6478
6479 if (addrSpace > max) {
6480 S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
6481 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
6482 return false;
6483 }
6484
6485 ASIdx =
6486 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
6487 return true;
6488 }
6489
6490 // Default value for DependentAddressSpaceTypes
6491 ASIdx = LangAS::Default;
6492 return true;
6493}
6494
6496 SourceLocation AttrLoc) {
6497 if (!AddrSpace->isValueDependent()) {
6498 if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
6499 AttrLoc))
6500 return QualType();
6501
6502 return Context.getAddrSpaceQualType(T, ASIdx);
6503 }
6504
6505 // A check with similar intentions as checking if a type already has an
6506 // address space except for on a dependent types, basically if the
6507 // current type is already a DependentAddressSpaceType then its already
6508 // lined up to have another address space on it and we can't have
6509 // multiple address spaces on the one pointer indirection
6510 if (T->getAs<DependentAddressSpaceType>()) {
6511 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
6512 return QualType();
6513 }
6514
6515 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
6516}
6517
6519 SourceLocation AttrLoc) {
6520 LangAS ASIdx;
6521 if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
6522 return QualType();
6523 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
6524}
6525
6527 TypeProcessingState &State) {
6528 Sema &S = State.getSema();
6529
6530 // This attribute is only supported in C.
6531 // FIXME: we should implement checkCommonAttributeFeatures() in SemaAttr.cpp
6532 // such that it handles type attributes, and then call that from
6533 // processTypeAttrs() instead of one-off checks like this.
6534 if (!Attr.diagnoseLangOpts(S)) {
6535 Attr.setInvalid();
6536 return;
6537 }
6538
6539 // Check the number of attribute arguments.
6540 if (Attr.getNumArgs() != 1) {
6541 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6542 << Attr << 1;
6543 Attr.setInvalid();
6544 return;
6545 }
6546
6547 // Ensure the argument is a string.
6548 auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6549 if (!StrLiteral) {
6550 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6552 Attr.setInvalid();
6553 return;
6554 }
6555
6556 ASTContext &Ctx = S.Context;
6557 StringRef BTFTypeTag = StrLiteral->getString();
6558 Type = State.getBTFTagAttributedType(
6559 ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type);
6560}
6561
6562/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6563/// specified type. The attribute contains 1 argument, the id of the address
6564/// space for the type.
6566 const ParsedAttr &Attr,
6567 TypeProcessingState &State) {
6568 Sema &S = State.getSema();
6569
6570 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6571 // qualified by an address-space qualifier."
6572 if (Type->isFunctionType()) {
6573 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
6574 Attr.setInvalid();
6575 return;
6576 }
6577
6578 LangAS ASIdx;
6579 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
6580
6581 // Check the attribute arguments.
6582 if (Attr.getNumArgs() != 1) {
6583 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
6584 << 1;
6585 Attr.setInvalid();
6586 return;
6587 }
6588
6589 Expr *ASArgExpr = Attr.getArgAsExpr(0);
6590 LangAS ASIdx;
6591 if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
6592 Attr.setInvalid();
6593 return;
6594 }
6595
6596 ASTContext &Ctx = S.Context;
6597 auto *ASAttr =
6598 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
6599
6600 // If the expression is not value dependent (not templated), then we can
6601 // apply the address space qualifiers just to the equivalent type.
6602 // Otherwise, we make an AttributedType with the modified and equivalent
6603 // type the same, and wrap it in a DependentAddressSpaceType. When this
6604 // dependent type is resolved, the qualifier is added to the equivalent type
6605 // later.
6606 QualType T;
6607 if (!ASArgExpr->isValueDependent()) {
6608 QualType EquivType =
6609 S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
6610 if (EquivType.isNull()) {
6611 Attr.setInvalid();
6612 return;
6613 }
6614 T = State.getAttributedType(ASAttr, Type, EquivType);
6615 } else {
6616 T = State.getAttributedType(ASAttr, Type, Type);
6617 T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
6618 }
6619
6620 if (!T.isNull())
6621 Type = T;
6622 else
6623 Attr.setInvalid();
6624 } else {
6625 // The keyword-based type attributes imply which address space to use.
6626 ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS()
6627 : Attr.asOpenCLLangAS();
6628 if (S.getLangOpts().HLSL)
6629 ASIdx = Attr.asHLSLLangAS();
6630
6631 if (ASIdx == LangAS::Default)
6632 llvm_unreachable("Invalid address space");
6633
6634 if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
6635 Attr.getLoc())) {
6636 Attr.setInvalid();
6637 return;
6638 }
6639
6641 }
6642}
6643
6644/// handleObjCOwnershipTypeAttr - Process an objc_ownership
6645/// attribute on the specified type.
6646///
6647/// Returns 'true' if the attribute was handled.
6648static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6650 bool NonObjCPointer = false;
6651
6652 if (!type->isDependentType() && !type->isUndeducedType()) {
6653 if (const PointerType *ptr = type->getAs<PointerType>()) {
6654 QualType pointee = ptr->getPointeeType();
6655 if (pointee->isObjCRetainableType() || pointee->isPointerType())
6656 return false;
6657 // It is important not to lose the source info that there was an attribute
6658 // applied to non-objc pointer. We will create an attributed type but
6659 // its type will be the same as the original type.
6660 NonObjCPointer = true;
6661 } else if (!type->isObjCRetainableType()) {
6662 return false;
6663 }
6664
6665 // Don't accept an ownership attribute in the declspec if it would
6666 // just be the return type of a block pointer.
6667 if (state.isProcessingDeclSpec()) {
6668 Declarator &D = state.getDeclarator();
6670 /*onlyBlockPointers=*/true))
6671 return false;
6672 }
6673 }
6674
6675 Sema &S = state.getSema();
6676 SourceLocation AttrLoc = attr.getLoc();
6677 if (AttrLoc.isMacroID())
6678 AttrLoc =
6680
6681 if (!attr.isArgIdent(0)) {
6682 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
6684 attr.setInvalid();
6685 return true;
6686 }
6687
6688 IdentifierInfo *II = attr.getArgAsIdent(0)->getIdentifierInfo();
6689 Qualifiers::ObjCLifetime lifetime;
6690 if (II->isStr("none"))
6692 else if (II->isStr("strong"))
6693 lifetime = Qualifiers::OCL_Strong;
6694 else if (II->isStr("weak"))
6695 lifetime = Qualifiers::OCL_Weak;
6696 else if (II->isStr("autoreleasing"))
6698 else {
6699 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II;
6700 attr.setInvalid();
6701 return true;
6702 }
6703
6704 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6705 // outside of ARC mode.
6706 if (!S.getLangOpts().ObjCAutoRefCount &&
6707 lifetime != Qualifiers::OCL_Weak &&
6708 lifetime != Qualifiers::OCL_ExplicitNone) {
6709 return true;
6710 }
6711
6712 SplitQualType underlyingType = type.split();
6713
6714 // Check for redundant/conflicting ownership qualifiers.
6715 if (Qualifiers::ObjCLifetime previousLifetime
6716 = type.getQualifiers().getObjCLifetime()) {
6717 // If it's written directly, that's an error.
6719 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
6720 << type;
6721 return true;
6722 }
6723
6724 // Otherwise, if the qualifiers actually conflict, pull sugar off
6725 // and remove the ObjCLifetime qualifiers.
6726 if (previousLifetime != lifetime) {
6727 // It's possible to have multiple local ObjCLifetime qualifiers. We
6728 // can't stop after we reach a type that is directly qualified.
6729 const Type *prevTy = nullptr;
6730 while (!prevTy || prevTy != underlyingType.Ty) {
6731 prevTy = underlyingType.Ty;
6732 underlyingType = underlyingType.getSingleStepDesugaredType();
6733 }
6734 underlyingType.Quals.removeObjCLifetime();
6735 }
6736 }
6737
6738 underlyingType.Quals.addObjCLifetime(lifetime);
6739
6740 if (NonObjCPointer) {
6741 StringRef name = attr.getAttrName()->getName();
6742 switch (lifetime) {
6745 break;
6746 case Qualifiers::OCL_Strong: name = "__strong"; break;
6747 case Qualifiers::OCL_Weak: name = "__weak"; break;
6748 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
6749 }
6750 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
6752 }
6753
6754 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
6755 // because having both 'T' and '__unsafe_unretained T' exist in the type
6756 // system causes unfortunate widespread consistency problems. (For example,
6757 // they're not considered compatible types, and we mangle them identicially
6758 // as template arguments.) These problems are all individually fixable,
6759 // but it's easier to just not add the qualifier and instead sniff it out
6760 // in specific places using isObjCInertUnsafeUnretainedType().
6761 //
6762 // Doing this does means we miss some trivial consistency checks that
6763 // would've triggered in ARC, but that's better than trying to solve all
6764 // the coexistence problems with __unsafe_unretained.
6765 if (!S.getLangOpts().ObjCAutoRefCount &&
6766 lifetime == Qualifiers::OCL_ExplicitNone) {
6767 type = state.getAttributedType(
6769 type, type);
6770 return true;
6771 }
6772
6773 QualType origType = type;
6774 if (!NonObjCPointer)
6775 type = S.Context.getQualifiedType(underlyingType);
6776
6777 // If we have a valid source location for the attribute, use an
6778 // AttributedType instead.
6779 if (AttrLoc.isValid()) {
6780 type = state.getAttributedType(::new (S.Context)
6781 ObjCOwnershipAttr(S.Context, attr, II),
6782 origType, type);
6783 }
6784
6785 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
6786 unsigned diagnostic, QualType type) {
6791 diagnostic, type, /*ignored*/ 0));
6792 } else {
6793 S.Diag(loc, diagnostic);
6794 }
6795 };
6796
6797 // Sometimes, __weak isn't allowed.
6798 if (lifetime == Qualifiers::OCL_Weak &&
6799 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
6800
6801 // Use a specialized diagnostic if the runtime just doesn't support them.
6802 unsigned diagnostic =
6803 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
6804 : diag::err_arc_weak_no_runtime);
6805
6806 // In any case, delay the diagnostic until we know what we're parsing.
6807 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
6808
6809 attr.setInvalid();
6810 return true;
6811 }
6812
6813 // Forbid __weak for class objects marked as
6814 // objc_arc_weak_reference_unavailable
6815 if (lifetime == Qualifiers::OCL_Weak) {
6816 if (const ObjCObjectPointerType *ObjT =
6817 type->getAs<ObjCObjectPointerType>()) {
6818 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
6819 if (Class->isArcWeakrefUnavailable()) {
6820 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
6821 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
6822 diag::note_class_declared);
6823 }
6824 }
6825 }
6826 }
6827
6828 return true;
6829}
6830
6831/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
6832/// attribute on the specified type. Returns true to indicate that
6833/// the attribute was handled, false to indicate that the type does
6834/// not permit the attribute.
6835static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
6836 QualType &type) {
6837 Sema &S = state.getSema();
6838
6839 // Delay if this isn't some kind of pointer.
6840 if (!type->isPointerType() &&
6841 !type->isObjCObjectPointerType() &&
6842 !type->isBlockPointerType())
6843 return false;
6844
6845 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
6846 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
6847 attr.setInvalid();
6848 return true;
6849 }
6850
6851 // Check the attribute arguments.
6852 if (!attr.isArgIdent(0)) {
6853 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
6855 attr.setInvalid();
6856 return true;
6857 }
6858 Qualifiers::GC GCAttr;
6859 if (attr.getNumArgs() > 1) {
6860 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
6861 << 1;
6862 attr.setInvalid();
6863 return true;
6864 }
6865
6866 IdentifierInfo *II = attr.getArgAsIdent(0)->getIdentifierInfo();
6867 if (II->isStr("weak"))
6868 GCAttr = Qualifiers::Weak;
6869 else if (II->isStr("strong"))
6870 GCAttr = Qualifiers::Strong;
6871 else {
6872 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
6873 << attr << II;
6874 attr.setInvalid();
6875 return true;
6876 }
6877
6878 QualType origType = type;
6879 type = S.Context.getObjCGCQualType(origType, GCAttr);
6880
6881 // Make an attributed type to preserve the source information.
6882 if (attr.getLoc().isValid())
6883 type = state.getAttributedType(
6884 ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type);
6885
6886 return true;
6887}
6888
6889namespace {
6890 /// A helper class to unwrap a type down to a function for the
6891 /// purposes of applying attributes there.
6892 ///
6893 /// Use:
6894 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
6895 /// if (unwrapped.isFunctionType()) {
6896 /// const FunctionType *fn = unwrapped.get();
6897 /// // change fn somehow
6898 /// T = unwrapped.wrap(fn);
6899 /// }
6900 struct FunctionTypeUnwrapper {
6901 enum WrapKind {
6902 Desugar,
6903 Attributed,
6904 Parens,
6905 Array,
6906 Pointer,
6907 BlockPointer,
6908 Reference,
6909 MemberPointer,
6910 MacroQualified,
6911 };
6912
6913 QualType Original;
6914 const FunctionType *Fn;
6915 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
6916
6917 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
6918 while (true) {
6919 const Type *Ty = T.getTypePtr();
6920 if (isa<FunctionType>(Ty)) {
6921 Fn = cast<FunctionType>(Ty);
6922 return;
6923 } else if (isa<ParenType>(Ty)) {
6924 T = cast<ParenType>(Ty)->getInnerType();
6925 Stack.push_back(Parens);
6926 } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) ||
6928 T = cast<ArrayType>(Ty)->getElementType();
6929 Stack.push_back(Array);
6930 } else if (isa<PointerType>(Ty)) {
6931 T = cast<PointerType>(Ty)->getPointeeType();
6932 Stack.push_back(Pointer);
6933 } else if (isa<BlockPointerType>(Ty)) {
6934 T = cast<BlockPointerType>(Ty)->getPointeeType();
6935 Stack.push_back(BlockPointer);
6936 } else if (isa<MemberPointerType>(Ty)) {
6937 T = cast<MemberPointerType>(Ty)->getPointeeType();
6938 Stack.push_back(MemberPointer);
6939 } else if (isa<ReferenceType>(Ty)) {
6940 T = cast<ReferenceType>(Ty)->getPointeeType();
6941 Stack.push_back(Reference);
6942 } else if (isa<AttributedType>(Ty)) {
6943 T = cast<AttributedType>(Ty)->getEquivalentType();
6944 Stack.push_back(Attributed);
6945 } else if (isa<MacroQualifiedType>(Ty)) {
6946 T = cast<MacroQualifiedType>(Ty)->getUnderlyingType();
6947 Stack.push_back(MacroQualified);
6948 } else {
6949 const Type *DTy = Ty->getUnqualifiedDesugaredType();
6950 if (Ty == DTy) {
6951 Fn = nullptr;
6952 return;
6953 }
6954
6955 T = QualType(DTy, 0);
6956 Stack.push_back(Desugar);
6957 }
6958 }
6959 }
6960
6961 bool isFunctionType() const { return (Fn != nullptr); }
6962 const FunctionType *get() const { return Fn; }
6963
6964 QualType wrap(Sema &S, const FunctionType *New) {
6965 // If T wasn't modified from the unwrapped type, do nothing.
6966 if (New == get()) return Original;
6967
6968 Fn = New;
6969 return wrap(S.Context, Original, 0);
6970 }
6971
6972 private:
6973 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
6974 if (I == Stack.size())
6975 return C.getQualifiedType(Fn, Old.getQualifiers());
6976
6977 // Build up the inner type, applying the qualifiers from the old
6978 // type to the new type.
6979 SplitQualType SplitOld = Old.split();
6980
6981 // As a special case, tail-recurse if there are no qualifiers.
6982 if (SplitOld.Quals.empty())
6983 return wrap(C, SplitOld.Ty, I);
6984 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
6985 }
6986
6987 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
6988 if (I == Stack.size()) return QualType(Fn, 0);
6989
6990 switch (static_cast<WrapKind>(Stack[I++])) {
6991 case Desugar:
6992 // This is the point at which we potentially lose source
6993 // information.
6994 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
6995
6996 case Attributed:
6997 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
6998
6999 case Parens: {
7000 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
7001 return C.getParenType(New);
7002 }
7003
7004 case MacroQualified:
7005 return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I);
7006
7007 case Array: {
7008 if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) {
7009 QualType New = wrap(C, CAT->getElementType(), I);
7010 return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(),
7011 CAT->getSizeModifier(),
7012 CAT->getIndexTypeCVRQualifiers());
7013 }
7014
7015 if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) {
7016 QualType New = wrap(C, VAT->getElementType(), I);
7017 return C.getVariableArrayType(New, VAT->getSizeExpr(),
7018 VAT->getSizeModifier(),
7019 VAT->getIndexTypeCVRQualifiers());
7020 }
7021
7022 const auto *IAT = cast<IncompleteArrayType>(Old);
7023 QualType New = wrap(C, IAT->getElementType(), I);
7024 return C.getIncompleteArrayType(New, IAT->getSizeModifier(),
7025 IAT->getIndexTypeCVRQualifiers());
7026 }
7027
7028 case Pointer: {
7029 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
7030 return C.getPointerType(New);
7031 }
7032
7033 case BlockPointer: {
7034 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
7035 return C.getBlockPointerType(New);
7036 }
7037
7038 case MemberPointer: {
7039 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
7040 QualType New = wrap(C, OldMPT->getPointeeType(), I);
7041 return C.getMemberPointerType(New, OldMPT->getQualifier(),
7042 OldMPT->getMostRecentCXXRecordDecl());
7043 }
7044
7045 case Reference: {
7046 const ReferenceType *OldRef = cast<ReferenceType>(Old);
7047 QualType New = wrap(C, OldRef->getPointeeType(), I);
7048 if (isa<LValueReferenceType>(OldRef))
7049 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
7050 else
7051 return C.getRValueReferenceType(New);
7052 }
7053 }
7054
7055 llvm_unreachable("unknown wrapping kind");
7056 }
7057 };
7058} // end anonymous namespace
7059
7060static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
7061 ParsedAttr &PAttr, QualType &Type) {
7062 Sema &S = State.getSema();
7063
7064 Attr *A;
7065 switch (PAttr.getKind()) {
7066 default: llvm_unreachable("Unknown attribute kind");
7067 case ParsedAttr::AT_Ptr32:
7069 break;
7070 case ParsedAttr::AT_Ptr64:
7072 break;
7073 case ParsedAttr::AT_SPtr:
7074 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
7075 break;
7076 case ParsedAttr::AT_UPtr:
7077 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
7078 break;
7079 }
7080
7081 std::bitset<attr::LastAttr> Attrs;
7082 QualType Desugared = Type;
7083 for (;;) {
7084 if (const TypedefType *TT = dyn_cast<TypedefType>(Desugared)) {
7085 Desugared = TT->desugar();
7086 continue;
7087 }
7088 const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
7089 if (!AT)
7090 break;
7091 Attrs[AT->getAttrKind()] = true;
7092 Desugared = AT->getModifiedType();
7093 }
7094
7095 // You cannot specify duplicate type attributes, so if the attribute has
7096 // already been applied, flag it.
7097 attr::Kind NewAttrKind = A->getKind();
7098 if (Attrs[NewAttrKind]) {
7099 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7100 return true;
7101 }
7102 Attrs[NewAttrKind] = true;
7103
7104 // You cannot have both __sptr and __uptr on the same type, nor can you
7105 // have __ptr32 and __ptr64.
7106 if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) {
7107 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7108 << "'__ptr32'"
7109 << "'__ptr64'" << /*isRegularKeyword=*/0;
7110 return true;
7111 } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) {
7112 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7113 << "'__sptr'"
7114 << "'__uptr'" << /*isRegularKeyword=*/0;
7115 return true;
7116 }
7117
7118 // Check the raw (i.e., desugared) Canonical type to see if it
7119 // is a pointer type.
7120 if (!isa<PointerType>(Desugared)) {
7121 // Pointer type qualifiers can only operate on pointer types, but not
7122 // pointer-to-member types.
7124 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
7125 else
7126 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
7127 return true;
7128 }
7129
7130 // Add address space to type based on its attributes.
7131 LangAS ASIdx = LangAS::Default;
7132 uint64_t PtrWidth =
7134 if (PtrWidth == 32) {
7135 if (Attrs[attr::Ptr64])
7136 ASIdx = LangAS::ptr64;
7137 else if (Attrs[attr::UPtr])
7138 ASIdx = LangAS::ptr32_uptr;
7139 } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) {
7140 if (S.Context.getTargetInfo().getTriple().isOSzOS() || Attrs[attr::UPtr])
7141 ASIdx = LangAS::ptr32_uptr;
7142 else
7143 ASIdx = LangAS::ptr32_sptr;
7144 }
7145
7146 QualType Pointee = Type->getPointeeType();
7147 if (ASIdx != LangAS::Default)
7148 Pointee = S.Context.getAddrSpaceQualType(
7149 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7150 Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee));
7151 return false;
7152}
7153
7154static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State,
7155 QualType &QT, ParsedAttr &PAttr) {
7156 assert(PAttr.getKind() == ParsedAttr::AT_WebAssemblyFuncref);
7157
7158 Sema &S = State.getSema();
7160
7161 std::bitset<attr::LastAttr> Attrs;
7162 attr::Kind NewAttrKind = A->getKind();
7163 const auto *AT = dyn_cast<AttributedType>(QT);
7164 while (AT) {
7165 Attrs[AT->getAttrKind()] = true;
7166 AT = dyn_cast<AttributedType>(AT->getModifiedType());
7167 }
7168
7169 // You cannot specify duplicate type attributes, so if the attribute has
7170 // already been applied, flag it.
7171 if (Attrs[NewAttrKind]) {
7172 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7173 return true;
7174 }
7175
7176 // Add address space to type based on its attributes.
7178 QualType Pointee = QT->getPointeeType();
7179 Pointee = S.Context.getAddrSpaceQualType(
7180 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7181 QT = State.getAttributedType(A, QT, S.Context.getPointerType(Pointee));
7182 return false;
7183}
7184
7185static void HandleSwiftAttr(TypeProcessingState &State, TypeAttrLocation TAL,
7186 QualType &QT, ParsedAttr &PAttr) {
7187 if (TAL == TAL_DeclName)
7188 return;
7189
7190 Sema &S = State.getSema();
7191 auto &D = State.getDeclarator();
7192
7193 // If the attribute appears in declaration specifiers
7194 // it should be handled as a declaration attribute,
7195 // unless it's associated with a type or a function
7196 // prototype (i.e. appears on a parameter or result type).
7197 if (State.isProcessingDeclSpec()) {
7198 if (!(D.isPrototypeContext() ||
7199 D.getContext() == DeclaratorContext::TypeName))
7200 return;
7201
7202 if (auto *chunk = D.getInnermostNonParenChunk()) {
7203 moveAttrFromListToList(PAttr, State.getCurrentAttributes(),
7204 const_cast<DeclaratorChunk *>(chunk)->getAttrs());
7205 return;
7206 }
7207 }
7208
7209 StringRef Str;
7210 if (!S.checkStringLiteralArgumentAttr(PAttr, 0, Str)) {
7211 PAttr.setInvalid();
7212 return;
7213 }
7214
7215 // If the attribute as attached to a paren move it closer to
7216 // the declarator. This can happen in block declarations when
7217 // an attribute is placed before `^` i.e. `(__attribute__((...)) ^)`.
7218 //
7219 // Note that it's actually invalid to use GNU style attributes
7220 // in a block but such cases are currently handled gracefully
7221 // but the parser and behavior should be consistent between
7222 // cases when attribute appears before/after block's result
7223 // type and inside (^).
7224 if (TAL == TAL_DeclChunk) {
7225 auto chunkIdx = State.getCurrentChunkIndex();
7226 if (chunkIdx >= 1 &&
7227 D.getTypeObject(chunkIdx).Kind == DeclaratorChunk::Paren) {
7228 moveAttrFromListToList(PAttr, State.getCurrentAttributes(),
7229 D.getTypeObject(chunkIdx - 1).getAttrs());
7230 return;
7231 }
7232 }
7233
7234 auto *A = ::new (S.Context) SwiftAttrAttr(S.Context, PAttr, Str);
7235 QT = State.getAttributedType(A, QT, QT);
7236 PAttr.setUsedAsTypeAttr();
7237}
7238
7239/// Rebuild an attributed type without the nullability attribute on it.
7241 QualType Type) {
7242 auto Attributed = dyn_cast<AttributedType>(Type.getTypePtr());
7243 if (!Attributed)
7244 return Type;
7245
7246 // Skip the nullability attribute; we're done.
7247 if (Attributed->getImmediateNullability())
7248 return Attributed->getModifiedType();
7249
7250 // Build the modified type.
7252 Ctx, Attributed->getModifiedType());
7253 assert(Modified.getTypePtr() != Attributed->getModifiedType().getTypePtr());
7254 return Ctx.getAttributedType(Attributed->getAttrKind(), Modified,
7255 Attributed->getEquivalentType(),
7256 Attributed->getAttr());
7257}
7258
7259/// Map a nullability attribute kind to a nullability kind.
7261 switch (kind) {
7262 case ParsedAttr::AT_TypeNonNull:
7264
7265 case ParsedAttr::AT_TypeNullable:
7267
7268 case ParsedAttr::AT_TypeNullableResult:
7270
7271 case ParsedAttr::AT_TypeNullUnspecified:
7273
7274 default:
7275 llvm_unreachable("not a nullability attribute kind");
7276 }
7277}
7278
7280 Sema &S, TypeProcessingState *State, ParsedAttr *PAttr, QualType &QT,
7281 NullabilityKind Nullability, SourceLocation NullabilityLoc,
7282 bool IsContextSensitive, bool AllowOnArrayType, bool OverrideExisting) {
7283 bool Implicit = (State == nullptr);
7284 if (!Implicit)
7285 recordNullabilitySeen(S, NullabilityLoc);
7286
7287 // Check for existing nullability attributes on the type.
7288 QualType Desugared = QT;
7289 while (auto *Attributed = dyn_cast<AttributedType>(Desugared.getTypePtr())) {
7290 // Check whether there is already a null
7291 if (auto ExistingNullability = Attributed->getImmediateNullability()) {
7292 // Duplicated nullability.
7293 if (Nullability == *ExistingNullability) {
7294 if (Implicit)
7295 break;
7296
7297 S.Diag(NullabilityLoc, diag::warn_nullability_duplicate)
7298 << DiagNullabilityKind(Nullability, IsContextSensitive)
7299 << FixItHint::CreateRemoval(NullabilityLoc);
7300
7301 break;
7302 }
7303
7304 if (!OverrideExisting) {
7305 // Conflicting nullability.
7306 S.Diag(NullabilityLoc, diag::err_nullability_conflicting)
7307 << DiagNullabilityKind(Nullability, IsContextSensitive)
7308 << DiagNullabilityKind(*ExistingNullability, false);
7309 return true;
7310 }
7311
7312 // Rebuild the attributed type, dropping the existing nullability.
7314 }
7315
7316 Desugared = Attributed->getModifiedType();
7317 }
7318
7319 // If there is already a different nullability specifier, complain.
7320 // This (unlike the code above) looks through typedefs that might
7321 // have nullability specifiers on them, which means we cannot
7322 // provide a useful Fix-It.
7323 if (auto ExistingNullability = Desugared->getNullability()) {
7324 if (Nullability != *ExistingNullability && !Implicit) {
7325 S.Diag(NullabilityLoc, diag::err_nullability_conflicting)
7326 << DiagNullabilityKind(Nullability, IsContextSensitive)
7327 << DiagNullabilityKind(*ExistingNullability, false);
7328
7329 // Try to find the typedef with the existing nullability specifier.
7330 if (auto TT = Desugared->getAs<TypedefType>()) {
7331 TypedefNameDecl *typedefDecl = TT->getDecl();
7332 QualType underlyingType = typedefDecl->getUnderlyingType();
7333 if (auto typedefNullability =
7334 AttributedType::stripOuterNullability(underlyingType)) {
7335 if (*typedefNullability == *ExistingNullability) {
7336 S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
7337 << DiagNullabilityKind(*ExistingNullability, false);
7338 }
7339 }
7340 }
7341
7342 return true;
7343 }
7344 }
7345
7346 // If this definitely isn't a pointer type, reject the specifier.
7347 if (!Desugared->canHaveNullability() &&
7348 !(AllowOnArrayType && Desugared->isArrayType())) {
7349 if (!Implicit)
7350 S.Diag(NullabilityLoc, diag::err_nullability_nonpointer)
7351 << DiagNullabilityKind(Nullability, IsContextSensitive) << QT;
7352
7353 return true;
7354 }
7355
7356 // For the context-sensitive keywords/Objective-C property
7357 // attributes, require that the type be a single-level pointer.
7358 if (IsContextSensitive) {
7359 // Make sure that the pointee isn't itself a pointer type.
7360 const Type *pointeeType = nullptr;
7361 if (Desugared->isArrayType())
7362 pointeeType = Desugared->getArrayElementTypeNoTypeQual();
7363 else if (Desugared->isAnyPointerType())
7364 pointeeType = Desugared->getPointeeType().getTypePtr();
7365
7366 if (pointeeType && (pointeeType->isAnyPointerType() ||
7367 pointeeType->isObjCObjectPointerType() ||
7368 pointeeType->isMemberPointerType())) {
7369 S.Diag(NullabilityLoc, diag::err_nullability_cs_multilevel)
7370 << DiagNullabilityKind(Nullability, true) << QT;
7371 S.Diag(NullabilityLoc, diag::note_nullability_type_specifier)
7372 << DiagNullabilityKind(Nullability, false) << QT
7373 << FixItHint::CreateReplacement(NullabilityLoc,
7374 getNullabilitySpelling(Nullability));
7375 return true;
7376 }
7377 }
7378
7379 // Form the attributed type.
7380 if (State) {
7381 assert(PAttr);
7382 Attr *A = createNullabilityAttr(S.Context, *PAttr, Nullability);
7383 QT = State->getAttributedType(A, QT, QT);
7384 } else {
7385 QT = S.Context.getAttributedType(Nullability, QT, QT);
7386 }
7387 return false;
7388}
7389
7390static bool CheckNullabilityTypeSpecifier(TypeProcessingState &State,
7392 bool AllowOnArrayType) {
7394 SourceLocation NullabilityLoc = Attr.getLoc();
7395 bool IsContextSensitive = Attr.isContextSensitiveKeywordAttribute();
7396
7397 return CheckNullabilityTypeSpecifier(State.getSema(), &State, &Attr, Type,
7398 Nullability, NullabilityLoc,
7399 IsContextSensitive, AllowOnArrayType,
7400 /*overrideExisting*/ false);
7401}
7402
7404 NullabilityKind Nullability,
7405 SourceLocation DiagLoc,
7406 bool AllowArrayTypes,
7407 bool OverrideExisting) {
7409 *this, nullptr, nullptr, Type, Nullability, DiagLoc,
7410 /*isContextSensitive*/ false, AllowArrayTypes, OverrideExisting);
7411}
7412
7413/// Check the application of the Objective-C '__kindof' qualifier to
7414/// the given type.
7415static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
7416 ParsedAttr &attr) {
7417 Sema &S = state.getSema();
7418
7420 // Build the attributed type to record where __kindof occurred.
7421 type = state.getAttributedType(
7423 return false;
7424 }
7425
7426 // Find out if it's an Objective-C object or object pointer type;
7427 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
7428 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
7429 : type->getAs<ObjCObjectType>();
7430
7431 // If not, we can't apply __kindof.
7432 if (!objType) {
7433 // FIXME: Handle dependent types that aren't yet object types.
7434 S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
7435 << type;
7436 return true;
7437 }
7438
7439 // Rebuild the "equivalent" type, which pushes __kindof down into
7440 // the object type.
7441 // There is no need to apply kindof on an unqualified id type.
7442 QualType equivType = S.Context.getObjCObjectType(
7443 objType->getBaseType(), objType->getTypeArgsAsWritten(),
7444 objType->getProtocols(),
7445 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
7446
7447 // If we started with an object pointer type, rebuild it.
7448 if (ptrType) {
7449 equivType = S.Context.getObjCObjectPointerType(equivType);
7450 if (auto nullability = type->getNullability()) {
7451 // We create a nullability attribute from the __kindof attribute.
7452 // Make sure that will make sense.
7453 assert(attr.getAttributeSpellingListIndex() == 0 &&
7454 "multiple spellings for __kindof?");
7455 Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
7456 A->setImplicit(true);
7457 equivType = state.getAttributedType(A, equivType, equivType);
7458 }
7459 }
7460
7461 // Build the attributed type to record where __kindof occurred.
7462 type = state.getAttributedType(
7464 return false;
7465}
7466
7467/// Distribute a nullability type attribute that cannot be applied to
7468/// the type specifier to a pointer, block pointer, or member pointer
7469/// declarator, complaining if necessary.
7470///
7471/// \returns true if the nullability annotation was distributed, false
7472/// otherwise.
7473static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
7475 Declarator &declarator = state.getDeclarator();
7476
7477 /// Attempt to move the attribute to the specified chunk.
7478 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
7479 // If there is already a nullability attribute there, don't add
7480 // one.
7481 if (hasNullabilityAttr(chunk.getAttrs()))
7482 return false;
7483
7484 // Complain about the nullability qualifier being in the wrong
7485 // place.
7486 enum {
7487 PK_Pointer,
7488 PK_BlockPointer,
7489 PK_MemberPointer,
7490 PK_FunctionPointer,
7491 PK_MemberFunctionPointer,
7492 } pointerKind
7493 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
7494 : PK_Pointer)
7495 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
7496 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
7497
7498 auto diag = state.getSema().Diag(attr.getLoc(),
7499 diag::warn_nullability_declspec)
7501 attr.isContextSensitiveKeywordAttribute())
7502 << type
7503 << static_cast<unsigned>(pointerKind);
7504
7505 // FIXME: MemberPointer chunks don't carry the location of the *.
7506 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
7509 state.getSema().getPreprocessor().getLocForEndOfToken(
7510 chunk.Loc),
7511 " " + attr.getAttrName()->getName().str() + " ");
7512 }
7513
7514 moveAttrFromListToList(attr, state.getCurrentAttributes(),
7515 chunk.getAttrs());
7516 return true;
7517 };
7518
7519 // Move it to the outermost pointer, member pointer, or block
7520 // pointer declarator.
7521 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
7522 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
7523 switch (chunk.Kind) {
7527 return moveToChunk(chunk, false);
7528
7531 continue;
7532
7534 // Try to move past the return type to a function/block/member
7535 // function pointer.
7537 declarator, i,
7538 /*onlyBlockPointers=*/false)) {
7539 return moveToChunk(*dest, true);
7540 }
7541
7542 return false;
7543
7544 // Don't walk through these.
7547 return false;
7548 }
7549 }
7550
7551 return false;
7552}
7553
7555 assert(!Attr.isInvalid());
7556 switch (Attr.getKind()) {
7557 default:
7558 llvm_unreachable("not a calling convention attribute");
7559 case ParsedAttr::AT_CDecl:
7560 return createSimpleAttr<CDeclAttr>(Ctx, Attr);
7561 case ParsedAttr::AT_FastCall:
7563 case ParsedAttr::AT_StdCall:
7565 case ParsedAttr::AT_ThisCall:
7567 case ParsedAttr::AT_RegCall:
7569 case ParsedAttr::AT_Pascal:
7571 case ParsedAttr::AT_SwiftCall:
7573 case ParsedAttr::AT_SwiftAsyncCall:
7575 case ParsedAttr::AT_VectorCall:
7577 case ParsedAttr::AT_AArch64VectorPcs:
7579 case ParsedAttr::AT_AArch64SVEPcs:
7581 case ParsedAttr::AT_ArmStreaming:
7583 case ParsedAttr::AT_Pcs: {
7584 // The attribute may have had a fixit applied where we treated an
7585 // identifier as a string literal. The contents of the string are valid,
7586 // but the form may not be.
7587 StringRef Str;
7588 if (Attr.isArgExpr(0))
7589 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
7590 else
7591 Str = Attr.getArgAsIdent(0)->getIdentifierInfo()->getName();
7592 PcsAttr::PCSType Type;
7593 if (!PcsAttr::ConvertStrToPCSType(Str, Type))
7594 llvm_unreachable("already validated the attribute");
7595 return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
7596 }
7597 case ParsedAttr::AT_IntelOclBicc:
7599 case ParsedAttr::AT_MSABI:
7600 return createSimpleAttr<MSABIAttr>(Ctx, Attr);
7601 case ParsedAttr::AT_SysVABI:
7603 case ParsedAttr::AT_PreserveMost:
7605 case ParsedAttr::AT_PreserveAll:
7607 case ParsedAttr::AT_M68kRTD:
7609 case ParsedAttr::AT_PreserveNone:
7611 case ParsedAttr::AT_RISCVVectorCC:
7613 case ParsedAttr::AT_RISCVVLSCC: {
7614 // If the riscv_abi_vlen doesn't have any argument, we set set it to default
7615 // value 128.
7616 unsigned ABIVLen = 128;
7617 if (Attr.getNumArgs()) {
7618 std::optional<llvm::APSInt> MaybeABIVLen =
7619 Attr.getArgAsExpr(0)->getIntegerConstantExpr(Ctx);
7620 if (!MaybeABIVLen)
7621 llvm_unreachable("Invalid RISC-V ABI VLEN");
7622 ABIVLen = MaybeABIVLen->getZExtValue();
7623 }
7624
7625 return ::new (Ctx) RISCVVLSCCAttr(Ctx, Attr, ABIVLen);
7626 }
7627 }
7628 llvm_unreachable("unexpected attribute kind!");
7629}
7630
7631std::optional<FunctionEffectMode>
7632Sema::ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName) {
7633 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent())
7635
7636 std::optional<llvm::APSInt> ConditionValue =
7638 if (!ConditionValue) {
7639 // FIXME: err_attribute_argument_type doesn't quote the attribute
7640 // name but needs to; users are inconsistent.
7641 Diag(CondExpr->getExprLoc(), diag::err_attribute_argument_type)
7642 << AttributeName << AANT_ArgumentIntegerConstant
7643 << CondExpr->getSourceRange();
7644 return std::nullopt;
7645 }
7646 return !ConditionValue->isZero() ? FunctionEffectMode::True
7648}
7649
7650static bool
7651handleNonBlockingNonAllocatingTypeAttr(TypeProcessingState &TPState,
7652 ParsedAttr &PAttr, QualType &QT,
7653 FunctionTypeUnwrapper &Unwrapped) {
7654 // Delay if this is not a function type.
7655 if (!Unwrapped.isFunctionType())
7656 return false;
7657
7658 Sema &S = TPState.getSema();
7659
7660 // Require FunctionProtoType.
7661 auto *FPT = Unwrapped.get()->getAs<FunctionProtoType>();
7662 if (FPT == nullptr) {
7663 S.Diag(PAttr.getLoc(), diag::err_func_with_effects_no_prototype)
7664 << PAttr.getAttrName()->getName();
7665 return true;
7666 }
7667
7668 // Parse the new attribute.
7669 // non/blocking or non/allocating? Or conditional (computed)?
7670 bool IsNonBlocking = PAttr.getKind() == ParsedAttr::AT_NonBlocking ||
7671 PAttr.getKind() == ParsedAttr::AT_Blocking;
7672
7674 Expr *CondExpr = nullptr; // only valid if dependent
7675
7676 if (PAttr.getKind() == ParsedAttr::AT_NonBlocking ||
7677 PAttr.getKind() == ParsedAttr::AT_NonAllocating) {
7678 if (!PAttr.checkAtMostNumArgs(S, 1)) {
7679 PAttr.setInvalid();
7680 return true;
7681 }
7682
7683 // Parse the condition, if any.
7684 if (PAttr.getNumArgs() == 1) {
7685 CondExpr = PAttr.getArgAsExpr(0);
7686 std::optional<FunctionEffectMode> MaybeMode =
7687 S.ActOnEffectExpression(CondExpr, PAttr.getAttrName()->getName());
7688 if (!MaybeMode) {
7689 PAttr.setInvalid();
7690 return true;
7691 }
7692 NewMode = *MaybeMode;
7693 if (NewMode != FunctionEffectMode::Dependent)
7694 CondExpr = nullptr;
7695 } else {
7696 NewMode = FunctionEffectMode::True;
7697 }
7698 } else {
7699 // This is the `blocking` or `allocating` attribute.
7700 if (S.CheckAttrNoArgs(PAttr)) {
7701 // The attribute has been marked invalid.
7702 return true;
7703 }
7704 NewMode = FunctionEffectMode::False;
7705 }
7706
7707 const FunctionEffect::Kind FEKind =
7708 (NewMode == FunctionEffectMode::False)
7709 ? (IsNonBlocking ? FunctionEffect::Kind::Blocking
7711 : (IsNonBlocking ? FunctionEffect::Kind::NonBlocking
7713 const FunctionEffectWithCondition NewEC{FunctionEffect(FEKind),
7714 EffectConditionExpr(CondExpr)};
7715
7716 if (S.diagnoseConflictingFunctionEffect(FPT->getFunctionEffects(), NewEC,
7717 PAttr.getLoc())) {
7718 PAttr.setInvalid();
7719 return true;
7720 }
7721
7722 // Add the effect to the FunctionProtoType.
7723 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7726 [[maybe_unused]] bool Success = FX.insert(NewEC, Errs);
7727 assert(Success && "effect conflicts should have been diagnosed above");
7729
7730 QualType NewType = S.Context.getFunctionType(FPT->getReturnType(),
7731 FPT->getParamTypes(), EPI);
7732 QT = Unwrapped.wrap(S, NewType->getAs<FunctionType>());
7733 return true;
7734}
7735
7736static bool checkMutualExclusion(TypeProcessingState &state,
7739 AttributeCommonInfo::Kind OtherKind) {
7740 auto OtherAttr = llvm::find_if(
7741 state.getCurrentAttributes(),
7742 [OtherKind](const ParsedAttr &A) { return A.getKind() == OtherKind; });
7743 if (OtherAttr == state.getCurrentAttributes().end() || OtherAttr->isInvalid())
7744 return false;
7745
7746 Sema &S = state.getSema();
7747 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
7748 << *OtherAttr << Attr
7749 << (OtherAttr->isRegularKeywordAttribute() ||
7751 S.Diag(OtherAttr->getLoc(), diag::note_conflicting_attribute);
7752 Attr.setInvalid();
7753 return true;
7754}
7755
7758 ParsedAttr &Attr) {
7759 if (!Attr.getNumArgs()) {
7760 S.Diag(Attr.getLoc(), diag::err_missing_arm_state) << Attr;
7761 Attr.setInvalid();
7762 return true;
7763 }
7764
7765 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
7766 StringRef StateName;
7767 SourceLocation LiteralLoc;
7768 if (!S.checkStringLiteralArgumentAttr(Attr, I, StateName, &LiteralLoc))
7769 return true;
7770
7771 if (StateName != "sme_za_state") {
7772 S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName;
7773 Attr.setInvalid();
7774 return true;
7775 }
7776
7777 if (EPI.AArch64SMEAttributes &
7779 S.Diag(Attr.getLoc(), diag::err_conflicting_attributes_arm_agnostic);
7780 Attr.setInvalid();
7781 return true;
7782 }
7783
7785 }
7786
7787 return false;
7788}
7789
7794 if (!Attr.getNumArgs()) {
7795 S.Diag(Attr.getLoc(), diag::err_missing_arm_state) << Attr;
7796 Attr.setInvalid();
7797 return true;
7798 }
7799
7800 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
7801 StringRef StateName;
7802 SourceLocation LiteralLoc;
7803 if (!S.checkStringLiteralArgumentAttr(Attr, I, StateName, &LiteralLoc))
7804 return true;
7805
7806 unsigned Shift;
7807 FunctionType::ArmStateValue ExistingState;
7808 if (StateName == "za") {
7811 } else if (StateName == "zt0") {
7814 } else {
7815 S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName;
7816 Attr.setInvalid();
7817 return true;
7818 }
7819
7821 S.Diag(LiteralLoc, diag::err_conflicting_attributes_arm_agnostic);
7822 Attr.setInvalid();
7823 return true;
7824 }
7825
7826 // __arm_in(S), __arm_out(S), __arm_inout(S) and __arm_preserves(S)
7827 // are all mutually exclusive for the same S, so check if there are
7828 // conflicting attributes.
7829 if (ExistingState != FunctionType::ARM_None && ExistingState != State) {
7830 S.Diag(LiteralLoc, diag::err_conflicting_attributes_arm_state)
7831 << StateName;
7832 Attr.setInvalid();
7833 return true;
7834 }
7835
7837 (FunctionType::AArch64SMETypeAttributes)((State << Shift)));
7838 }
7839 return false;
7840}
7841
7842/// Process an individual function attribute. Returns true to
7843/// indicate that the attribute was handled, false if it wasn't.
7844static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7846 Sema &S = state.getSema();
7847
7848 FunctionTypeUnwrapper unwrapped(S, type);
7849
7850 if (attr.getKind() == ParsedAttr::AT_NoReturn) {
7851 if (S.CheckAttrNoArgs(attr))
7852 return true;
7853
7854 // Delay if this is not a function type.
7855 if (!unwrapped.isFunctionType())
7856 return false;
7857
7858 // Otherwise we can process right away.
7859 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
7860 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7861 return true;
7862 }
7863
7864 if (attr.getKind() == ParsedAttr::AT_CFIUncheckedCallee) {
7865 // Delay if this is not a prototyped function type.
7866 if (!unwrapped.isFunctionType())
7867 return false;
7868
7869 if (!unwrapped.get()->isFunctionProtoType()) {
7870 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
7871 << attr << attr.isRegularKeywordAttribute()
7873 attr.setInvalid();
7874 return true;
7875 }
7876
7877 const auto *FPT = unwrapped.get()->getAs<FunctionProtoType>();
7879 FPT->getReturnType(), FPT->getParamTypes(),
7880 FPT->getExtProtoInfo().withCFIUncheckedCallee(true));
7881 type = unwrapped.wrap(S, cast<FunctionType>(type.getTypePtr()));
7882 return true;
7883 }
7884
7885 if (attr.getKind() == ParsedAttr::AT_CmseNSCall) {
7886 // Delay if this is not a function type.
7887 if (!unwrapped.isFunctionType())
7888 return false;
7889
7890 // Ignore if we don't have CMSE enabled.
7891 if (!S.getLangOpts().Cmse) {
7892 S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr;
7893 attr.setInvalid();
7894 return true;
7895 }
7896
7897 // Otherwise we can process right away.
7899 unwrapped.get()->getExtInfo().withCmseNSCall(true);
7900 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7901 return true;
7902 }
7903
7904 // ns_returns_retained is not always a type attribute, but if we got
7905 // here, we're treating it as one right now.
7906 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
7907 if (attr.getNumArgs()) return true;
7908
7909 // Delay if this is not a function type.
7910 if (!unwrapped.isFunctionType())
7911 return false;
7912
7913 // Check whether the return type is reasonable.
7915 attr.getLoc(), unwrapped.get()->getReturnType()))
7916 return true;
7917
7918 // Only actually change the underlying type in ARC builds.
7919 QualType origType = type;
7920 if (state.getSema().getLangOpts().ObjCAutoRefCount) {
7922 = unwrapped.get()->getExtInfo().withProducesResult(true);
7923 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7924 }
7925 type = state.getAttributedType(
7927 origType, type);
7928 return true;
7929 }
7930
7931 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
7933 return true;
7934
7935 // Delay if this is not a function type.
7936 if (!unwrapped.isFunctionType())
7937 return false;
7938
7940 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
7941 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7942 return true;
7943 }
7944
7945 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
7946 if (!S.getLangOpts().CFProtectionBranch) {
7947 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
7948 attr.setInvalid();
7949 return true;
7950 }
7951
7953 return true;
7954
7955 // If this is not a function type, warning will be asserted by subject
7956 // check.
7957 if (!unwrapped.isFunctionType())
7958 return true;
7959
7961 unwrapped.get()->getExtInfo().withNoCfCheck(true);
7962 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7963 return true;
7964 }
7965
7966 if (attr.getKind() == ParsedAttr::AT_Regparm) {
7967 unsigned value;
7968 if (S.CheckRegparmAttr(attr, value))
7969 return true;
7970
7971 // Delay if this is not a function type.
7972 if (!unwrapped.isFunctionType())
7973 return false;
7974
7975 // Diagnose regparm with fastcall.
7976 const FunctionType *fn = unwrapped.get();
7977 CallingConv CC = fn->getCallConv();
7978 if (CC == CC_X86FastCall) {
7979 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7980 << FunctionType::getNameForCallConv(CC) << "regparm"
7981 << attr.isRegularKeywordAttribute();
7982 attr.setInvalid();
7983 return true;
7984 }
7985
7987 unwrapped.get()->getExtInfo().withRegParm(value);
7988 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7989 return true;
7990 }
7991
7992 if (attr.getKind() == ParsedAttr::AT_CFISalt) {
7993 if (attr.getNumArgs() != 1)
7994 return true;
7995
7996 StringRef Argument;
7997 if (!S.checkStringLiteralArgumentAttr(attr, 0, Argument))
7998 return true;
7999
8000 // Delay if this is not a function type.
8001 if (!unwrapped.isFunctionType())
8002 return false;
8003
8004 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8005 if (!FnTy) {
8006 S.Diag(attr.getLoc(), diag::err_attribute_wrong_decl_type)
8007 << attr << attr.isRegularKeywordAttribute()
8009 attr.setInvalid();
8010 return true;
8011 }
8012
8013 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8014 EPI.ExtraAttributeInfo.CFISalt = Argument;
8015
8016 QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(),
8017 FnTy->getParamTypes(), EPI);
8018 type = unwrapped.wrap(S, newtype->getAs<FunctionType>());
8019 return true;
8020 }
8021
8022 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8023 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible ||
8024 attr.getKind() == ParsedAttr::AT_ArmPreserves ||
8025 attr.getKind() == ParsedAttr::AT_ArmIn ||
8026 attr.getKind() == ParsedAttr::AT_ArmOut ||
8027 attr.getKind() == ParsedAttr::AT_ArmInOut ||
8028 attr.getKind() == ParsedAttr::AT_ArmAgnostic) {
8029 if (S.CheckAttrTarget(attr))
8030 return true;
8031
8032 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8033 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible)
8034 if (S.CheckAttrNoArgs(attr))
8035 return true;
8036
8037 if (!unwrapped.isFunctionType())
8038 return false;
8039
8040 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8041 if (!FnTy) {
8042 // SME ACLE attributes are not supported on K&R-style unprototyped C
8043 // functions.
8044 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
8045 << attr << attr.isRegularKeywordAttribute()
8047 attr.setInvalid();
8048 return false;
8049 }
8050
8051 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8052 switch (attr.getKind()) {
8053 case ParsedAttr::AT_ArmStreaming:
8054 if (checkMutualExclusion(state, EPI, attr,
8055 ParsedAttr::AT_ArmStreamingCompatible))
8056 return true;
8058 break;
8059 case ParsedAttr::AT_ArmStreamingCompatible:
8060 if (checkMutualExclusion(state, EPI, attr, ParsedAttr::AT_ArmStreaming))
8061 return true;
8063 break;
8064 case ParsedAttr::AT_ArmPreserves:
8066 return true;
8067 break;
8068 case ParsedAttr::AT_ArmIn:
8070 return true;
8071 break;
8072 case ParsedAttr::AT_ArmOut:
8074 return true;
8075 break;
8076 case ParsedAttr::AT_ArmInOut:
8078 return true;
8079 break;
8080 case ParsedAttr::AT_ArmAgnostic:
8081 if (handleArmAgnosticAttribute(S, EPI, attr))
8082 return true;
8083 break;
8084 default:
8085 llvm_unreachable("Unsupported attribute");
8086 }
8087
8088 QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(),
8089 FnTy->getParamTypes(), EPI);
8090 type = unwrapped.wrap(S, newtype->getAs<FunctionType>());
8091 return true;
8092 }
8093
8094 if (attr.getKind() == ParsedAttr::AT_NoThrow) {
8095 // Delay if this is not a function type.
8096 if (!unwrapped.isFunctionType())
8097 return false;
8098
8099 if (S.CheckAttrNoArgs(attr)) {
8100 attr.setInvalid();
8101 return true;
8102 }
8103
8104 // Otherwise we can process right away.
8105 auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
8106
8107 // MSVC ignores nothrow if it is in conflict with an explicit exception
8108 // specification.
8109 if (Proto->hasExceptionSpec()) {
8110 switch (Proto->getExceptionSpecType()) {
8111 case EST_None:
8112 llvm_unreachable("This doesn't have an exception spec!");
8113
8114 case EST_DynamicNone:
8115 case EST_BasicNoexcept:
8116 case EST_NoexceptTrue:
8117 case EST_NoThrow:
8118 // Exception spec doesn't conflict with nothrow, so don't warn.
8119 [[fallthrough]];
8120 case EST_Unparsed:
8121 case EST_Uninstantiated:
8123 case EST_Unevaluated:
8124 // We don't have enough information to properly determine if there is a
8125 // conflict, so suppress the warning.
8126 break;
8127 case EST_Dynamic:
8128 case EST_MSAny:
8129 case EST_NoexceptFalse:
8130 S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored);
8131 break;
8132 }
8133 return true;
8134 }
8135
8136 type = unwrapped.wrap(
8137 S, S.Context
8139 QualType{Proto, 0},
8141 ->getAs<FunctionType>());
8142 return true;
8143 }
8144
8145 if (attr.getKind() == ParsedAttr::AT_NonBlocking ||
8146 attr.getKind() == ParsedAttr::AT_NonAllocating ||
8147 attr.getKind() == ParsedAttr::AT_Blocking ||
8148 attr.getKind() == ParsedAttr::AT_Allocating) {
8149 return handleNonBlockingNonAllocatingTypeAttr(state, attr, type, unwrapped);
8150 }
8151
8152 // Delay if the type didn't work out to a function.
8153 if (!unwrapped.isFunctionType()) return false;
8154
8155 // Otherwise, a calling convention.
8156 CallingConv CC;
8157 if (S.CheckCallingConvAttr(attr, CC, /*FunctionDecl=*/nullptr, CFT))
8158 return true;
8159
8160 const FunctionType *fn = unwrapped.get();
8161 CallingConv CCOld = fn->getCallConv();
8162 Attr *CCAttr = getCCTypeAttr(S.Context, attr);
8163
8164 if (CCOld != CC) {
8165 // Error out on when there's already an attribute on the type
8166 // and the CCs don't match.
8168 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8171 << attr.isRegularKeywordAttribute();
8172 attr.setInvalid();
8173 return true;
8174 }
8175 }
8176
8177 // Diagnose use of variadic functions with calling conventions that
8178 // don't support them (e.g. because they're callee-cleanup).
8179 // We delay warning about this on unprototyped function declarations
8180 // until after redeclaration checking, just in case we pick up a
8181 // prototype that way. And apparently we also "delay" warning about
8182 // unprototyped function types in general, despite not necessarily having
8183 // much ability to diagnose it later.
8184 if (!supportsVariadicCall(CC)) {
8185 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
8186 if (FnP && FnP->isVariadic()) {
8187 // stdcall and fastcall are ignored with a warning for GCC and MS
8188 // compatibility.
8189 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
8190 return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported)
8193
8194 attr.setInvalid();
8195 return S.Diag(attr.getLoc(), diag::err_cconv_varargs)
8197 }
8198 }
8199
8200 // Also diagnose fastcall with regparm.
8201 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
8202 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8204 << attr.isRegularKeywordAttribute();
8205 attr.setInvalid();
8206 return true;
8207 }
8208
8209 // Modify the CC from the wrapped function type, wrap it all back, and then
8210 // wrap the whole thing in an AttributedType as written. The modified type
8211 // might have a different CC if we ignored the attribute.
8213 if (CCOld == CC) {
8214 Equivalent = type;
8215 } else {
8216 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
8217 Equivalent =
8218 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8219 }
8220 type = state.getAttributedType(CCAttr, type, Equivalent);
8221 return true;
8222}
8223
8225 const AttributedType *AT;
8226
8227 // Stop if we'd be stripping off a typedef sugar node to reach the
8228 // AttributedType.
8229 while ((AT = T->getAs<AttributedType>()) &&
8230 AT->getAs<TypedefType>() == T->getAs<TypedefType>()) {
8231 if (AT->isCallingConv())
8232 return true;
8233 T = AT->getModifiedType();
8234 }
8235 return false;
8236}
8237
8238void Sema::adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
8239 bool IsCtorOrDtor, SourceLocation Loc) {
8240 FunctionTypeUnwrapper Unwrapped(*this, T);
8241 const FunctionType *FT = Unwrapped.get();
8242 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
8243 cast<FunctionProtoType>(FT)->isVariadic());
8244 CallingConv CurCC = FT->getCallConv();
8245 CallingConv ToCC =
8246 Context.getDefaultCallingConvention(IsVariadic, HasThisPointer);
8247
8248 if (CurCC == ToCC)
8249 return;
8250
8251 // MS compiler ignores explicit calling convention attributes on structors. We
8252 // should do the same.
8253 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
8254 // Issue a warning on ignored calling convention -- except of __stdcall.
8255 // Again, this is what MS compiler does.
8256 if (CurCC != CC_X86StdCall)
8257 Diag(Loc, diag::warn_cconv_unsupported)
8260 // Default adjustment.
8261 } else {
8262 // Only adjust types with the default convention. For example, on Windows
8263 // we should adjust a __cdecl type to __thiscall for instance methods, and a
8264 // __thiscall type to __cdecl for static methods.
8265 CallingConv DefaultCC =
8266 Context.getDefaultCallingConvention(IsVariadic, !HasThisPointer);
8267
8268 if (CurCC != DefaultCC)
8269 return;
8270
8272 return;
8273 }
8274
8275 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
8276 QualType Wrapped = Unwrapped.wrap(*this, FT);
8277 T = Context.getAdjustedType(T, Wrapped);
8278}
8279
8280/// HandleVectorSizeAttribute - this attribute is only applicable to integral
8281/// and float scalars, although arrays, pointers, and function return values are
8282/// allowed in conjunction with this construct. Aggregates with this attribute
8283/// are invalid, even if they are of the same size as a corresponding scalar.
8284/// The raw attribute should contain precisely 1 argument, the vector size for
8285/// the variable, measured in bytes. If curType and rawAttr are well formed,
8286/// this routine will return a new vector type.
8287static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
8288 Sema &S) {
8289 // Check the attribute arguments.
8290 if (Attr.getNumArgs() != 1) {
8291 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8292 << 1;
8293 Attr.setInvalid();
8294 return;
8295 }
8296
8297 Expr *SizeExpr = Attr.getArgAsExpr(0);
8298 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
8299 if (!T.isNull())
8300 CurType = T;
8301 else
8302 Attr.setInvalid();
8303}
8304
8305/// Process the OpenCL-like ext_vector_type attribute when it occurs on
8306/// a type.
8308 Sema &S) {
8309 // check the attribute arguments.
8310 if (Attr.getNumArgs() != 1) {
8311 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8312 << 1;
8313 return;
8314 }
8315
8316 Expr *SizeExpr = Attr.getArgAsExpr(0);
8317 QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc());
8318 if (!T.isNull())
8319 CurType = T;
8320}
8321
8322static bool isPermittedNeonBaseType(QualType &Ty, VectorKind VecKind, Sema &S) {
8323 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
8324 if (!BTy)
8325 return false;
8326
8327 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
8328
8329 // Signed poly is mathematically wrong, but has been baked into some ABIs by
8330 // now.
8331 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
8332 Triple.getArch() == llvm::Triple::aarch64_32 ||
8333 Triple.getArch() == llvm::Triple::aarch64_be;
8334 if (VecKind == VectorKind::NeonPoly) {
8335 if (IsPolyUnsigned) {
8336 // AArch64 polynomial vectors are unsigned.
8337 return BTy->getKind() == BuiltinType::UChar ||
8338 BTy->getKind() == BuiltinType::UShort ||
8339 BTy->getKind() == BuiltinType::ULong ||
8340 BTy->getKind() == BuiltinType::ULongLong;
8341 } else {
8342 // AArch32 polynomial vectors are signed.
8343 return BTy->getKind() == BuiltinType::SChar ||
8344 BTy->getKind() == BuiltinType::Short ||
8345 BTy->getKind() == BuiltinType::LongLong;
8346 }
8347 }
8348
8349 // Non-polynomial vector types: the usual suspects are allowed, as well as
8350 // float64_t on AArch64.
8351 if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) &&
8352 BTy->getKind() == BuiltinType::Double)
8353 return true;
8354
8355 return BTy->getKind() == BuiltinType::SChar ||
8356 BTy->getKind() == BuiltinType::UChar ||
8357 BTy->getKind() == BuiltinType::Short ||
8358 BTy->getKind() == BuiltinType::UShort ||
8359 BTy->getKind() == BuiltinType::Int ||
8360 BTy->getKind() == BuiltinType::UInt ||
8361 BTy->getKind() == BuiltinType::Long ||
8362 BTy->getKind() == BuiltinType::ULong ||
8363 BTy->getKind() == BuiltinType::LongLong ||
8364 BTy->getKind() == BuiltinType::ULongLong ||
8365 BTy->getKind() == BuiltinType::Float ||
8366 BTy->getKind() == BuiltinType::Half ||
8367 BTy->getKind() == BuiltinType::BFloat16 ||
8368 BTy->getKind() == BuiltinType::MFloat8;
8369}
8370
8372 llvm::APSInt &Result) {
8373 const auto *AttrExpr = Attr.getArgAsExpr(0);
8374 if (!AttrExpr->isTypeDependent()) {
8375 if (std::optional<llvm::APSInt> Res =
8376 AttrExpr->getIntegerConstantExpr(S.Context)) {
8377 Result = *Res;
8378 return true;
8379 }
8380 }
8381 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
8382 << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange();
8383 Attr.setInvalid();
8384 return false;
8385}
8386
8387/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
8388/// "neon_polyvector_type" attributes are used to create vector types that
8389/// are mangled according to ARM's ABI. Otherwise, these types are identical
8390/// to those created with the "vector_size" attribute. Unlike "vector_size"
8391/// the argument to these Neon attributes is the number of vector elements,
8392/// not the vector size in bytes. The vector width and element type must
8393/// match one of the standard Neon vector types.
8395 Sema &S, VectorKind VecKind) {
8396 bool IsTargetOffloading = S.getLangOpts().isTargetDevice();
8397
8398 // Target must have NEON (or MVE, whose vectors are similar enough
8399 // not to need a separate attribute)
8400 if (!S.Context.getTargetInfo().hasFeature("mve") &&
8401 VecKind == VectorKind::Neon &&
8402 S.Context.getTargetInfo().getTriple().isArmMClass()) {
8403 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported_m_profile)
8404 << Attr << "'mve'";
8405 Attr.setInvalid();
8406 return;
8407 }
8408 if (!S.Context.getTargetInfo().hasFeature("mve") &&
8409 VecKind == VectorKind::NeonPoly &&
8410 S.Context.getTargetInfo().getTriple().isArmMClass()) {
8411 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported_m_profile)
8412 << Attr << "'mve'";
8413 Attr.setInvalid();
8414 return;
8415 }
8416
8417 // Check the attribute arguments.
8418 if (Attr.getNumArgs() != 1) {
8419 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8420 << Attr << 1;
8421 Attr.setInvalid();
8422 return;
8423 }
8424 // The number of elements must be an ICE.
8425 llvm::APSInt numEltsInt(32);
8426 if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt))
8427 return;
8428
8429 // Only certain element types are supported for Neon vectors.
8430 if (!isPermittedNeonBaseType(CurType, VecKind, S) && !IsTargetOffloading) {
8431 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
8432 Attr.setInvalid();
8433 return;
8434 }
8435
8436 // The total size of the vector must be 64 or 128 bits.
8437 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
8438 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
8439 unsigned vecSize = typeSize * numElts;
8440 if (vecSize != 64 && vecSize != 128) {
8441 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
8442 Attr.setInvalid();
8443 return;
8444 }
8445
8446 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
8447}
8448
8449/// Handle the __ptrauth qualifier.
8451 const ParsedAttr &Attr, Sema &S) {
8452
8453 assert((Attr.getNumArgs() > 0 && Attr.getNumArgs() <= 3) &&
8454 "__ptrauth qualifier takes between 1 and 3 arguments");
8455 Expr *KeyArg = Attr.getArgAsExpr(0);
8456 Expr *IsAddressDiscriminatedArg =
8457 Attr.getNumArgs() >= 2 ? Attr.getArgAsExpr(1) : nullptr;
8458 Expr *ExtraDiscriminatorArg =
8459 Attr.getNumArgs() >= 3 ? Attr.getArgAsExpr(2) : nullptr;
8460
8461 unsigned Key;
8462 if (S.checkConstantPointerAuthKey(KeyArg, Key)) {
8463 Attr.setInvalid();
8464 return;
8465 }
8466 assert(Key <= PointerAuthQualifier::MaxKey && "ptrauth key is out of range");
8467
8468 bool IsInvalid = false;
8469 unsigned IsAddressDiscriminated, ExtraDiscriminator;
8470 IsInvalid |= !S.checkPointerAuthDiscriminatorArg(IsAddressDiscriminatedArg,
8472 IsAddressDiscriminated);
8473 IsInvalid |= !S.checkPointerAuthDiscriminatorArg(
8474 ExtraDiscriminatorArg, PointerAuthDiscArgKind::Extra, ExtraDiscriminator);
8475
8476 if (IsInvalid) {
8477 Attr.setInvalid();
8478 return;
8479 }
8480
8481 if (!T->isSignableType(Ctx) && !T->isDependentType()) {
8482 S.Diag(Attr.getLoc(), diag::err_ptrauth_qualifier_invalid_target) << T;
8483 Attr.setInvalid();
8484 return;
8485 }
8486
8487 if (T.getPointerAuth()) {
8488 S.Diag(Attr.getLoc(), diag::err_ptrauth_qualifier_redundant) << T;
8489 Attr.setInvalid();
8490 return;
8491 }
8492
8493 if (!S.getLangOpts().PointerAuthIntrinsics) {
8494 S.Diag(Attr.getLoc(), diag::err_ptrauth_disabled) << Attr.getRange();
8495 Attr.setInvalid();
8496 return;
8497 }
8498
8499 assert((!IsAddressDiscriminatedArg || IsAddressDiscriminated <= 1) &&
8500 "address discriminator arg should be either 0 or 1");
8502 Key, IsAddressDiscriminated, ExtraDiscriminator,
8503 PointerAuthenticationMode::SignAndAuth, /*IsIsaPointer=*/false,
8504 /*AuthenticatesNullValues=*/false);
8505 T = S.Context.getPointerAuthType(T, Qual);
8506}
8507
8508/// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is
8509/// used to create fixed-length versions of sizeless SVE types defined by
8510/// the ACLE, such as svint32_t and svbool_t.
8512 Sema &S) {
8513 // Target must have SVE.
8514 if (!S.Context.getTargetInfo().hasFeature("sve")) {
8515 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'";
8516 Attr.setInvalid();
8517 return;
8518 }
8519
8520 // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or
8521 // if <bits>+ syntax is used.
8522 if (!S.getLangOpts().VScaleMin ||
8523 S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) {
8524 S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported)
8525 << Attr;
8526 Attr.setInvalid();
8527 return;
8528 }
8529
8530 // Check the attribute arguments.
8531 if (Attr.getNumArgs() != 1) {
8532 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8533 << Attr << 1;
8534 Attr.setInvalid();
8535 return;
8536 }
8537
8538 // The vector size must be an integer constant expression.
8539 llvm::APSInt SveVectorSizeInBits(32);
8540 if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits))
8541 return;
8542
8543 unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue());
8544
8545 // The attribute vector size must match -msve-vector-bits.
8546 if (VecSize != S.getLangOpts().VScaleMin * 128) {
8547 S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size)
8548 << VecSize << S.getLangOpts().VScaleMin * 128;
8549 Attr.setInvalid();
8550 return;
8551 }
8552
8553 // Attribute can only be attached to a single SVE vector or predicate type.
8554 if (!CurType->isSveVLSBuiltinType()) {
8555 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type)
8556 << Attr << CurType;
8557 Attr.setInvalid();
8558 return;
8559 }
8560
8561 const auto *BT = CurType->castAs<BuiltinType>();
8562
8563 QualType EltType = CurType->getSveEltType(S.Context);
8564 unsigned TypeSize = S.Context.getTypeSize(EltType);
8566 if (BT->getKind() == BuiltinType::SveBool) {
8567 // Predicates are represented as i8.
8568 VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth();
8570 } else
8571 VecSize /= TypeSize;
8572 CurType = S.Context.getVectorType(EltType, VecSize, VecKind);
8573}
8574
8575static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State,
8576 QualType &CurType,
8577 ParsedAttr &Attr) {
8578 const VectorType *VT = dyn_cast<VectorType>(CurType);
8579 if (!VT || VT->getVectorKind() != VectorKind::Neon) {
8580 State.getSema().Diag(Attr.getLoc(),
8581 diag::err_attribute_arm_mve_polymorphism);
8582 Attr.setInvalid();
8583 return;
8584 }
8585
8586 CurType =
8587 State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>(
8588 State.getSema().Context, Attr),
8589 CurType, CurType);
8590}
8591
8592/// HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is
8593/// used to create fixed-length versions of sizeless RVV types such as
8594/// vint8m1_t_t.
8596 ParsedAttr &Attr, Sema &S) {
8597 // Target must have vector extension.
8598 if (!S.Context.getTargetInfo().hasFeature("zve32x")) {
8599 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
8600 << Attr << "'zve32x'";
8601 Attr.setInvalid();
8602 return;
8603 }
8604
8605 auto VScale = S.Context.getTargetInfo().getVScaleRange(
8607 if (!VScale || !VScale->first || VScale->first != VScale->second) {
8608 S.Diag(Attr.getLoc(), diag::err_attribute_riscv_rvv_bits_unsupported)
8609 << Attr;
8610 Attr.setInvalid();
8611 return;
8612 }
8613
8614 // Check the attribute arguments.
8615 if (Attr.getNumArgs() != 1) {
8616 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8617 << Attr << 1;
8618 Attr.setInvalid();
8619 return;
8620 }
8621
8622 // The vector size must be an integer constant expression.
8623 llvm::APSInt RVVVectorSizeInBits(32);
8624 if (!verifyValidIntegerConstantExpr(S, Attr, RVVVectorSizeInBits))
8625 return;
8626
8627 // Attribute can only be attached to a single RVV vector type.
8628 if (!CurType->isRVVVLSBuiltinType()) {
8629 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_rvv_type)
8630 << Attr << CurType;
8631 Attr.setInvalid();
8632 return;
8633 }
8634
8635 unsigned VecSize = static_cast<unsigned>(RVVVectorSizeInBits.getZExtValue());
8636
8639 unsigned MinElts = Info.EC.getKnownMinValue();
8640
8642 unsigned ExpectedSize = VScale->first * MinElts;
8643 QualType EltType = CurType->getRVVEltType(S.Context);
8644 unsigned EltSize = S.Context.getTypeSize(EltType);
8645 unsigned NumElts;
8646 if (Info.ElementType == S.Context.BoolTy) {
8647 NumElts = VecSize / S.Context.getCharWidth();
8648 if (!NumElts) {
8649 NumElts = 1;
8650 switch (VecSize) {
8651 case 1:
8653 break;
8654 case 2:
8656 break;
8657 case 4:
8659 break;
8660 }
8661 } else
8663 } else {
8664 ExpectedSize *= EltSize;
8665 NumElts = VecSize / EltSize;
8666 }
8667
8668 // The attribute vector size must match -mrvv-vector-bits.
8669 if (VecSize != ExpectedSize) {
8670 S.Diag(Attr.getLoc(), diag::err_attribute_bad_rvv_vector_size)
8671 << VecSize << ExpectedSize;
8672 Attr.setInvalid();
8673 return;
8674 }
8675
8676 CurType = S.Context.getVectorType(EltType, NumElts, VecKind);
8677}
8678
8679/// Handle OpenCL Access Qualifier Attribute.
8680static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
8681 Sema &S) {
8682 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
8683 if (!(CurType->isImageType() || CurType->isPipeType())) {
8684 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
8685 Attr.setInvalid();
8686 return;
8687 }
8688
8689 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
8690 QualType BaseTy = TypedefTy->desugar();
8691
8692 std::string PrevAccessQual;
8693 if (BaseTy->isPipeType()) {
8694 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
8695 OpenCLAccessAttr *Attr =
8696 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
8697 PrevAccessQual = Attr->getSpelling();
8698 } else {
8699 PrevAccessQual = "read_only";
8700 }
8701 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
8702
8703 switch (ImgType->getKind()) {
8704 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8705 case BuiltinType::Id: \
8706 PrevAccessQual = #Access; \
8707 break;
8708 #include "clang/Basic/OpenCLImageTypes.def"
8709 default:
8710 llvm_unreachable("Unable to find corresponding image type.");
8711 }
8712 } else {
8713 llvm_unreachable("unexpected type");
8714 }
8715 StringRef AttrName = Attr.getAttrName()->getName();
8716 if (PrevAccessQual == AttrName.ltrim("_")) {
8717 // Duplicated qualifiers
8718 S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
8719 << AttrName << Attr.getRange();
8720 } else {
8721 // Contradicting qualifiers
8722 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
8723 }
8724
8725 S.Diag(TypedefTy->getDecl()->getBeginLoc(),
8726 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
8727 } else if (CurType->isPipeType()) {
8728 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
8729 QualType ElemType = CurType->castAs<PipeType>()->getElementType();
8730 CurType = S.Context.getWritePipeType(ElemType);
8731 }
8732 }
8733}
8734
8735/// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type
8736static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8737 Sema &S) {
8738 if (!S.getLangOpts().MatrixTypes) {
8739 S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled);
8740 return;
8741 }
8742
8743 if (Attr.getNumArgs() != 2) {
8744 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8745 << Attr << 2;
8746 return;
8747 }
8748
8749 Expr *RowsExpr = Attr.getArgAsExpr(0);
8750 Expr *ColsExpr = Attr.getArgAsExpr(1);
8751 QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc());
8752 if (!T.isNull())
8753 CurType = T;
8754}
8755
8756static void HandleAnnotateTypeAttr(TypeProcessingState &State,
8757 QualType &CurType, const ParsedAttr &PA) {
8758 Sema &S = State.getSema();
8759
8760 if (PA.getNumArgs() < 1) {
8761 S.Diag(PA.getLoc(), diag::err_attribute_too_few_arguments) << PA << 1;
8762 return;
8763 }
8764
8765 // Make sure that there is a string literal as the annotation's first
8766 // argument.
8767 StringRef Str;
8768 if (!S.checkStringLiteralArgumentAttr(PA, 0, Str))
8769 return;
8770
8772 Args.reserve(PA.getNumArgs() - 1);
8773 for (unsigned Idx = 1; Idx < PA.getNumArgs(); Idx++) {
8774 assert(!PA.isArgIdent(Idx));
8775 Args.push_back(PA.getArgAsExpr(Idx));
8776 }
8777 if (!S.ConstantFoldAttrArgs(PA, Args))
8778 return;
8779 auto *AnnotateTypeAttr =
8780 AnnotateTypeAttr::Create(S.Context, Str, Args.data(), Args.size(), PA);
8781 CurType = State.getAttributedType(AnnotateTypeAttr, CurType, CurType);
8782}
8783
8784static void HandleLifetimeBoundAttr(TypeProcessingState &State,
8785 QualType &CurType,
8786 ParsedAttr &Attr) {
8787 if (State.getDeclarator().isDeclarationOfFunction()) {
8788 CurType = State.getAttributedType(
8789 createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
8790 CurType, CurType);
8791 return;
8792 }
8793 State.getSema().Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
8796}
8797
8798static void HandleLifetimeCaptureByAttr(TypeProcessingState &State,
8799 QualType &CurType, ParsedAttr &PA) {
8800 if (State.getDeclarator().isDeclarationOfFunction()) {
8801 auto *Attr = State.getSema().ParseLifetimeCaptureByAttr(PA, "this");
8802 if (Attr)
8803 CurType = State.getAttributedType(Attr, CurType, CurType);
8804 }
8805}
8806
8807static void HandleHLSLParamModifierAttr(TypeProcessingState &State,
8808 QualType &CurType,
8809 const ParsedAttr &Attr, Sema &S) {
8810 // Don't apply this attribute to template dependent types. It is applied on
8811 // substitution during template instantiation. Also skip parsing this if we've
8812 // already modified the type based on an earlier attribute.
8813 if (CurType->isDependentType() || State.didParseHLSLParamMod())
8814 return;
8815 if (Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_inout ||
8816 Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_out) {
8817 State.setParsedHLSLParamMod(true);
8818 }
8819}
8820
8821static void processTypeAttrs(TypeProcessingState &state, QualType &type,
8822 TypeAttrLocation TAL,
8823 const ParsedAttributesView &attrs,
8824 CUDAFunctionTarget CFT) {
8825
8826 state.setParsedNoDeref(false);
8827 if (attrs.empty())
8828 return;
8829
8830 // Scan through and apply attributes to this type where it makes sense. Some
8831 // attributes (such as __address_space__, __vector_size__, etc) apply to the
8832 // type, but others can be present in the type specifiers even though they
8833 // apply to the decl. Here we apply type attributes and ignore the rest.
8834
8835 // This loop modifies the list pretty frequently, but we still need to make
8836 // sure we visit every element once. Copy the attributes list, and iterate
8837 // over that.
8838 ParsedAttributesView AttrsCopy{attrs};
8839 for (ParsedAttr &attr : AttrsCopy) {
8840
8841 // Skip attributes that were marked to be invalid.
8842 if (attr.isInvalid())
8843 continue;
8844
8845 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute()) {
8846 // [[gnu::...]] attributes are treated as declaration attributes, so may
8847 // not appertain to a DeclaratorChunk. If we handle them as type
8848 // attributes, accept them in that position and diagnose the GCC
8849 // incompatibility.
8850 if (attr.isGNUScope()) {
8851 assert(attr.isStandardAttributeSyntax());
8852 bool IsTypeAttr = attr.isTypeAttr();
8853 if (TAL == TAL_DeclChunk) {
8854 state.getSema().Diag(attr.getLoc(),
8855 IsTypeAttr
8856 ? diag::warn_gcc_ignores_type_attr
8857 : diag::warn_cxx11_gnu_attribute_on_type)
8858 << attr;
8859 if (!IsTypeAttr)
8860 continue;
8861 }
8862 } else if (TAL != TAL_DeclSpec && TAL != TAL_DeclChunk &&
8863 !attr.isTypeAttr()) {
8864 // Otherwise, only consider type processing for a C++11 attribute if
8865 // - it has actually been applied to a type (decl-specifier-seq or
8866 // declarator chunk), or
8867 // - it is a type attribute, irrespective of where it was applied (so
8868 // that we can support the legacy behavior of some type attributes
8869 // that can be applied to the declaration name).
8870 continue;
8871 }
8872 }
8873
8874 // If this is an attribute we can handle, do so now,
8875 // otherwise, add it to the FnAttrs list for rechaining.
8876 switch (attr.getKind()) {
8877 default:
8878 // A [[]] attribute on a declarator chunk must appertain to a type.
8879 if ((attr.isStandardAttributeSyntax() ||
8880 attr.isRegularKeywordAttribute()) &&
8881 TAL == TAL_DeclChunk) {
8882 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
8883 << attr << attr.isRegularKeywordAttribute();
8884 attr.setUsedAsTypeAttr();
8885 }
8886 break;
8887
8889 if (attr.isStandardAttributeSyntax()) {
8890 state.getSema().DiagnoseUnknownAttribute(attr);
8891 // Mark the attribute as invalid so we don't emit the same diagnostic
8892 // multiple times.
8893 attr.setInvalid();
8894 }
8895 break;
8896
8898 break;
8899
8900 case ParsedAttr::AT_BTFTypeTag:
8902 attr.setUsedAsTypeAttr();
8903 break;
8904
8905 case ParsedAttr::AT_MayAlias:
8906 // FIXME: This attribute needs to actually be handled, but if we ignore
8907 // it it breaks large amounts of Linux software.
8908 attr.setUsedAsTypeAttr();
8909 break;
8910 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
8911 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
8912 case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace:
8913 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace:
8914 case ParsedAttr::AT_OpenCLLocalAddressSpace:
8915 case ParsedAttr::AT_OpenCLConstantAddressSpace:
8916 case ParsedAttr::AT_OpenCLGenericAddressSpace:
8917 case ParsedAttr::AT_HLSLGroupSharedAddressSpace:
8918 case ParsedAttr::AT_AddressSpace:
8920 attr.setUsedAsTypeAttr();
8921 break;
8923 if (!handleObjCPointerTypeAttr(state, attr, type))
8925 attr.setUsedAsTypeAttr();
8926 break;
8927 case ParsedAttr::AT_VectorSize:
8928 HandleVectorSizeAttr(type, attr, state.getSema());
8929 attr.setUsedAsTypeAttr();
8930 break;
8931 case ParsedAttr::AT_ExtVectorType:
8932 HandleExtVectorTypeAttr(type, attr, state.getSema());
8933 attr.setUsedAsTypeAttr();
8934 break;
8935 case ParsedAttr::AT_NeonVectorType:
8937 attr.setUsedAsTypeAttr();
8938 break;
8939 case ParsedAttr::AT_NeonPolyVectorType:
8940 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
8942 attr.setUsedAsTypeAttr();
8943 break;
8944 case ParsedAttr::AT_ArmSveVectorBits:
8945 HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema());
8946 attr.setUsedAsTypeAttr();
8947 break;
8948 case ParsedAttr::AT_ArmMveStrictPolymorphism: {
8950 attr.setUsedAsTypeAttr();
8951 break;
8952 }
8953 case ParsedAttr::AT_RISCVRVVVectorBits:
8954 HandleRISCVRVVVectorBitsTypeAttr(type, attr, state.getSema());
8955 attr.setUsedAsTypeAttr();
8956 break;
8957 case ParsedAttr::AT_OpenCLAccess:
8958 HandleOpenCLAccessAttr(type, attr, state.getSema());
8959 attr.setUsedAsTypeAttr();
8960 break;
8961 case ParsedAttr::AT_PointerAuth:
8962 HandlePtrAuthQualifier(state.getSema().Context, type, attr,
8963 state.getSema());
8964 attr.setUsedAsTypeAttr();
8965 break;
8966 case ParsedAttr::AT_LifetimeBound:
8967 if (TAL == TAL_DeclChunk)
8969 break;
8970 case ParsedAttr::AT_LifetimeCaptureBy:
8971 if (TAL == TAL_DeclChunk)
8973 break;
8974
8975 case ParsedAttr::AT_NoDeref: {
8976 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
8977 // See https://github.com/llvm/llvm-project/issues/55790 for details.
8978 // For the time being, we simply emit a warning that the attribute is
8979 // ignored.
8980 if (attr.isStandardAttributeSyntax()) {
8981 state.getSema().Diag(attr.getLoc(), diag::warn_attribute_ignored)
8982 << attr;
8983 break;
8984 }
8985 ASTContext &Ctx = state.getSema().Context;
8986 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
8987 type, type);
8988 attr.setUsedAsTypeAttr();
8989 state.setParsedNoDeref(true);
8990 break;
8991 }
8992
8993 case ParsedAttr::AT_MatrixType:
8994 HandleMatrixTypeAttr(type, attr, state.getSema());
8995 attr.setUsedAsTypeAttr();
8996 break;
8997
8998 case ParsedAttr::AT_WebAssemblyFuncref: {
9000 attr.setUsedAsTypeAttr();
9001 break;
9002 }
9003
9004 case ParsedAttr::AT_HLSLParamModifier: {
9005 HandleHLSLParamModifierAttr(state, type, attr, state.getSema());
9006 attr.setUsedAsTypeAttr();
9007 break;
9008 }
9009
9010 case ParsedAttr::AT_SwiftAttr: {
9011 HandleSwiftAttr(state, TAL, type, attr);
9012 break;
9013 }
9014
9017 attr.setUsedAsTypeAttr();
9018 break;
9019
9020
9022 // Either add nullability here or try to distribute it. We
9023 // don't want to distribute the nullability specifier past any
9024 // dependent type, because that complicates the user model.
9025 if (type->canHaveNullability() || type->isDependentType() ||
9026 type->isArrayType() ||
9028 unsigned endIndex;
9029 if (TAL == TAL_DeclChunk)
9030 endIndex = state.getCurrentChunkIndex();
9031 else
9032 endIndex = state.getDeclarator().getNumTypeObjects();
9033 bool allowOnArrayType =
9034 state.getDeclarator().isPrototypeContext() &&
9035 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
9037 allowOnArrayType)) {
9038 attr.setInvalid();
9039 }
9040
9041 attr.setUsedAsTypeAttr();
9042 }
9043 break;
9044
9045 case ParsedAttr::AT_ObjCKindOf:
9046 // '__kindof' must be part of the decl-specifiers.
9047 switch (TAL) {
9048 case TAL_DeclSpec:
9049 break;
9050
9051 case TAL_DeclChunk:
9052 case TAL_DeclName:
9053 state.getSema().Diag(attr.getLoc(),
9054 diag::err_objc_kindof_wrong_position)
9055 << FixItHint::CreateRemoval(attr.getLoc())
9057 state.getDeclarator().getDeclSpec().getBeginLoc(),
9058 "__kindof ");
9059 break;
9060 }
9061
9062 // Apply it regardless.
9063 if (checkObjCKindOfType(state, type, attr))
9064 attr.setInvalid();
9065 break;
9066
9067 case ParsedAttr::AT_NoThrow:
9068 // Exception Specifications aren't generally supported in C mode throughout
9069 // clang, so revert to attribute-based handling for C.
9070 if (!state.getSema().getLangOpts().CPlusPlus)
9071 break;
9072 [[fallthrough]];
9074
9075 attr.setUsedAsTypeAttr();
9076
9077 // Attributes with standard syntax have strict rules for what they
9078 // appertain to and hence should not use the "distribution" logic below.
9079 if (attr.isStandardAttributeSyntax() ||
9080 attr.isRegularKeywordAttribute()) {
9081 if (!handleFunctionTypeAttr(state, attr, type, CFT)) {
9082 diagnoseBadTypeAttribute(state.getSema(), attr, type);
9083 attr.setInvalid();
9084 }
9085 break;
9086 }
9087
9088 // Never process function type attributes as part of the
9089 // declaration-specifiers.
9090 if (TAL == TAL_DeclSpec)
9092
9093 // Otherwise, handle the possible delays.
9094 else if (!handleFunctionTypeAttr(state, attr, type, CFT))
9096 break;
9097 case ParsedAttr::AT_AcquireHandle: {
9098 if (!type->isFunctionType())
9099 return;
9100
9101 if (attr.getNumArgs() != 1) {
9102 state.getSema().Diag(attr.getLoc(),
9103 diag::err_attribute_wrong_number_arguments)
9104 << attr << 1;
9105 attr.setInvalid();
9106 return;
9107 }
9108
9109 StringRef HandleType;
9110 if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType))
9111 return;
9112 type = state.getAttributedType(
9113 AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr),
9114 type, type);
9115 attr.setUsedAsTypeAttr();
9116 break;
9117 }
9118 case ParsedAttr::AT_AnnotateType: {
9120 attr.setUsedAsTypeAttr();
9121 break;
9122 }
9123 case ParsedAttr::AT_HLSLResourceClass:
9124 case ParsedAttr::AT_HLSLROV:
9125 case ParsedAttr::AT_HLSLRawBuffer:
9126 case ParsedAttr::AT_HLSLContainedType: {
9127 // Only collect HLSL resource type attributes that are in
9128 // decl-specifier-seq; do not collect attributes on declarations or those
9129 // that get to slide after declaration name.
9130 if (TAL == TAL_DeclSpec &&
9131 state.getSema().HLSL().handleResourceTypeAttr(type, attr))
9132 attr.setUsedAsTypeAttr();
9133 break;
9134 }
9135 }
9136
9137 // Handle attributes that are defined in a macro. We do not want this to be
9138 // applied to ObjC builtin attributes.
9139 if (isa<AttributedType>(type) && attr.hasMacroIdentifier() &&
9140 !type.getQualifiers().hasObjCLifetime() &&
9141 !type.getQualifiers().hasObjCGCAttr() &&
9142 attr.getKind() != ParsedAttr::AT_ObjCGC &&
9143 attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
9144 const IdentifierInfo *MacroII = attr.getMacroIdentifier();
9145 type = state.getSema().Context.getMacroQualifiedType(type, MacroII);
9146 state.setExpansionLocForMacroQualifiedType(
9147 cast<MacroQualifiedType>(type.getTypePtr()),
9148 attr.getMacroExpansionLoc());
9149 }
9150 }
9151}
9152
9154 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
9155 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
9156 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
9157 auto *Def = Var->getDefinition();
9158 if (!Def) {
9159 SourceLocation PointOfInstantiation = E->getExprLoc();
9160 runWithSufficientStackSpace(PointOfInstantiation, [&] {
9161 InstantiateVariableDefinition(PointOfInstantiation, Var);
9162 });
9163 Def = Var->getDefinition();
9164
9165 // If we don't already have a point of instantiation, and we managed
9166 // to instantiate a definition, this is the point of instantiation.
9167 // Otherwise, we don't request an end-of-TU instantiation, so this is
9168 // not a point of instantiation.
9169 // FIXME: Is this really the right behavior?
9170 if (Var->getPointOfInstantiation().isInvalid() && Def) {
9171 assert(Var->getTemplateSpecializationKind() ==
9173 "explicit instantiation with no point of instantiation");
9174 Var->setTemplateSpecializationKind(
9175 Var->getTemplateSpecializationKind(), PointOfInstantiation);
9176 }
9177 }
9178
9179 // Update the type to the definition's type both here and within the
9180 // expression.
9181 if (Def) {
9182 DRE->setDecl(Def);
9183 QualType T = Def->getType();
9184 DRE->setType(T);
9185 // FIXME: Update the type on all intervening expressions.
9186 E->setType(T);
9187 }
9188
9189 // We still go on to try to complete the type independently, as it
9190 // may also require instantiations or diagnostics if it remains
9191 // incomplete.
9192 }
9193 }
9194 }
9195 if (const auto CastE = dyn_cast<ExplicitCastExpr>(E)) {
9196 QualType DestType = CastE->getTypeAsWritten();
9197 if (const auto *IAT = Context.getAsIncompleteArrayType(DestType)) {
9198 // C++20 [expr.static.cast]p.4: ... If T is array of unknown bound,
9199 // this direct-initialization defines the type of the expression
9200 // as U[1]
9201 QualType ResultType = Context.getConstantArrayType(
9202 IAT->getElementType(),
9203 llvm::APInt(Context.getTypeSize(Context.getSizeType()), 1),
9204 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal,
9205 /*IndexTypeQuals=*/0);
9206 E->setType(ResultType);
9207 }
9208 }
9209}
9210
9212 // Incomplete array types may be completed by the initializer attached to
9213 // their definitions. For static data members of class templates and for
9214 // variable templates, we need to instantiate the definition to get this
9215 // initializer and complete the type.
9216 if (E->getType()->isIncompleteArrayType())
9218
9219 // FIXME: Are there other cases which require instantiating something other
9220 // than the type to complete the type of an expression?
9221
9222 return E->getType();
9223}
9224
9226 TypeDiagnoser &Diagnoser) {
9227 return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind,
9228 Diagnoser);
9229}
9230
9231bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
9232 BoundTypeDiagnoser<> Diagnoser(DiagID);
9234}
9235
9237 CompleteTypeKind Kind,
9238 TypeDiagnoser &Diagnoser) {
9239 if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser))
9240 return true;
9241 if (auto *TD = T->getAsTagDecl(); TD && !TD->isCompleteDefinitionRequired()) {
9242 TD->setCompleteDefinitionRequired();
9243 Consumer.HandleTagDeclRequiredDefinition(TD);
9244 }
9245 return false;
9246}
9247
9250 if (!Suggested)
9251 return false;
9252
9253 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
9254 // and isolate from other C++ specific checks.
9256 getLangOpts(), D->getASTContext(), Suggested->getASTContext(),
9257 NonEquivalentDecls, StructuralEquivalenceKind::Default,
9258 /*StrictTypeSpelling=*/false, /*Complain=*/true,
9259 /*ErrorOnTagTypeMismatch=*/true);
9260 return Ctx.IsEquivalent(D, Suggested);
9261}
9262
9264 AcceptableKind Kind, bool OnlyNeedComplete) {
9265 // Easy case: if we don't have modules, all declarations are visible.
9266 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
9267 return true;
9268
9269 // If this definition was instantiated from a template, map back to the
9270 // pattern from which it was instantiated.
9271 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
9272 // We're in the middle of defining it; this definition should be treated
9273 // as visible.
9274 return true;
9275 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9276 if (auto *Pattern = RD->getTemplateInstantiationPattern())
9277 RD = Pattern;
9278 D = RD->getDefinition();
9279 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
9280 if (auto *Pattern = ED->getTemplateInstantiationPattern())
9281 ED = Pattern;
9282 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) {
9283 // If the enum has a fixed underlying type, it may have been forward
9284 // declared. In -fms-compatibility, `enum Foo;` will also forward declare
9285 // the enum and assign it the underlying type of `int`. Since we're only
9286 // looking for a complete type (not a definition), any visible declaration
9287 // of it will do.
9288 *Suggested = nullptr;
9289 for (auto *Redecl : ED->redecls()) {
9290 if (isAcceptable(Redecl, Kind))
9291 return true;
9292 if (Redecl->isThisDeclarationADefinition() ||
9293 (Redecl->isCanonicalDecl() && !*Suggested))
9294 *Suggested = Redecl;
9295 }
9296
9297 return false;
9298 }
9299 D = ED->getDefinition();
9300 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
9301 if (auto *Pattern = FD->getTemplateInstantiationPattern())
9302 FD = Pattern;
9303 D = FD->getDefinition();
9304 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
9305 if (auto *Pattern = VD->getTemplateInstantiationPattern())
9306 VD = Pattern;
9307 D = VD->getDefinition();
9308 }
9309
9310 assert(D && "missing definition for pattern of instantiated definition");
9311
9312 *Suggested = D;
9313
9314 auto DefinitionIsAcceptable = [&] {
9315 // The (primary) definition might be in a visible module.
9316 if (isAcceptable(D, Kind))
9317 return true;
9318
9319 // A visible module might have a merged definition instead.
9322 if (CodeSynthesisContexts.empty() &&
9323 !getLangOpts().ModulesLocalVisibility) {
9324 // Cache the fact that this definition is implicitly visible because
9325 // there is a visible merged definition.
9327 }
9328 return true;
9329 }
9330
9331 return false;
9332 };
9333
9334 if (DefinitionIsAcceptable())
9335 return true;
9336
9337 // The external source may have additional definitions of this entity that are
9338 // visible, so complete the redeclaration chain now and ask again.
9339 if (auto *Source = Context.getExternalSource()) {
9340 Source->CompleteRedeclChain(D);
9341 return DefinitionIsAcceptable();
9342 }
9343
9344 return false;
9345}
9346
9347/// Determine whether there is any declaration of \p D that was ever a
9348/// definition (perhaps before module merging) and is currently visible.
9349/// \param D The definition of the entity.
9350/// \param Suggested Filled in with the declaration that should be made visible
9351/// in order to provide a definition of this entity.
9352/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9353/// not defined. This only matters for enums with a fixed underlying
9354/// type, since in all other cases, a type is complete if and only if it
9355/// is defined.
9357 bool OnlyNeedComplete) {
9359 OnlyNeedComplete);
9360}
9361
9362/// Determine whether there is any declaration of \p D that was ever a
9363/// definition (perhaps before module merging) and is currently
9364/// reachable.
9365/// \param D The definition of the entity.
9366/// \param Suggested Filled in with the declaration that should be made
9367/// reachable
9368/// in order to provide a definition of this entity.
9369/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9370/// not defined. This only matters for enums with a fixed underlying
9371/// type, since in all other cases, a type is complete if and only if it
9372/// is defined.
9374 bool OnlyNeedComplete) {
9376 OnlyNeedComplete);
9377}
9378
9379/// Locks in the inheritance model for the given class and all of its bases.
9381 RD = RD->getMostRecentDecl();
9382 if (!RD->hasAttr<MSInheritanceAttr>()) {
9384 bool BestCase = false;
9387 BestCase = true;
9388 IM = RD->calculateInheritanceModel();
9389 break;
9392 break;
9395 break;
9398 break;
9399 }
9400
9403 : RD->getSourceRange();
9404 RD->addAttr(MSInheritanceAttr::CreateImplicit(
9405 S.getASTContext(), BestCase, Loc, MSInheritanceAttr::Spelling(IM)));
9407 }
9408}
9409
9410bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
9411 CompleteTypeKind Kind,
9412 TypeDiagnoser *Diagnoser) {
9413 // FIXME: Add this assertion to make sure we always get instantiation points.
9414 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
9415 // FIXME: Add this assertion to help us flush out problems with
9416 // checking for dependent types and type-dependent expressions.
9417 //
9418 // assert(!T->isDependentType() &&
9419 // "Can't ask whether a dependent type is complete");
9420
9421 if (const auto *MPTy = dyn_cast<MemberPointerType>(T.getCanonicalType())) {
9422 if (CXXRecordDecl *RD = MPTy->getMostRecentCXXRecordDecl();
9423 RD && !RD->isDependentType()) {
9424 CanQualType T = Context.getCanonicalTagType(RD);
9425 if (getLangOpts().CompleteMemberPointers && !RD->isBeingDefined() &&
9426 RequireCompleteType(Loc, T, Kind, diag::err_memptr_incomplete))
9427 return true;
9428
9429 // We lock in the inheritance model once somebody has asked us to ensure
9430 // that a pointer-to-member type is complete.
9431 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9432 (void)isCompleteType(Loc, T);
9433 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
9434 }
9435 }
9436 }
9437
9438 NamedDecl *Def = nullptr;
9440 bool Incomplete = (T->isIncompleteType(&Def) ||
9442
9443 // Check that any necessary explicit specializations are visible. For an
9444 // enum, we just need the declaration, so don't check this.
9445 if (Def && !isa<EnumDecl>(Def))
9447
9448 // If we have a complete type, we're done.
9449 if (!Incomplete) {
9450 NamedDecl *Suggested = nullptr;
9451 if (Def &&
9452 !hasReachableDefinition(Def, &Suggested, /*OnlyNeedComplete=*/true)) {
9453 // If the user is going to see an error here, recover by making the
9454 // definition visible.
9455 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
9456 if (Diagnoser && Suggested)
9458 /*Recover*/ TreatAsComplete);
9459 return !TreatAsComplete;
9460 } else if (Def && !TemplateInstCallbacks.empty()) {
9461 CodeSynthesisContext TempInst;
9463 TempInst.Template = Def;
9464 TempInst.Entity = Def;
9465 TempInst.PointOfInstantiation = Loc;
9466 atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
9467 atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
9468 }
9469
9470 return false;
9471 }
9472
9473 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
9474 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
9475
9476 // Give the external source a chance to provide a definition of the type.
9477 // This is kept separate from completing the redeclaration chain so that
9478 // external sources such as LLDB can avoid synthesizing a type definition
9479 // unless it's actually needed.
9480 if (Tag || IFace) {
9481 // Avoid diagnosing invalid decls as incomplete.
9482 if (Def->isInvalidDecl())
9483 return true;
9484
9485 // Give the external AST source a chance to complete the type.
9486 if (auto *Source = Context.getExternalSource()) {
9487 if (Tag && Tag->hasExternalLexicalStorage())
9488 Source->CompleteType(Tag);
9489 if (IFace && IFace->hasExternalLexicalStorage())
9490 Source->CompleteType(IFace);
9491 // If the external source completed the type, go through the motions
9492 // again to ensure we're allowed to use the completed type.
9493 if (!T->isIncompleteType())
9494 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9495 }
9496 }
9497
9498 // If we have a class template specialization or a class member of a
9499 // class template specialization, or an array with known size of such,
9500 // try to instantiate it.
9501 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
9502 bool Instantiated = false;
9503 bool Diagnosed = false;
9504 if (RD->isDependentContext()) {
9505 // Don't try to instantiate a dependent class (eg, a member template of
9506 // an instantiated class template specialization).
9507 // FIXME: Can this ever happen?
9508 } else if (auto *ClassTemplateSpec =
9509 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
9510 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
9513 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
9514 /*Complain=*/Diagnoser, ClassTemplateSpec->hasStrictPackMatch());
9515 });
9516 Instantiated = true;
9517 }
9518 } else {
9519 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
9520 if (!RD->isBeingDefined() && Pattern) {
9521 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
9522 assert(MSI && "Missing member specialization information?");
9523 // This record was instantiated from a class within a template.
9524 if (MSI->getTemplateSpecializationKind() !=
9527 Diagnosed = InstantiateClass(Loc, RD, Pattern,
9530 /*Complain=*/Diagnoser);
9531 });
9532 Instantiated = true;
9533 }
9534 }
9535 }
9536
9537 if (Instantiated) {
9538 // Instantiate* might have already complained that the template is not
9539 // defined, if we asked it to.
9540 if (Diagnoser && Diagnosed)
9541 return true;
9542 // If we instantiated a definition, check that it's usable, even if
9543 // instantiation produced an error, so that repeated calls to this
9544 // function give consistent answers.
9545 if (!T->isIncompleteType())
9546 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9547 }
9548 }
9549
9550 // FIXME: If we didn't instantiate a definition because of an explicit
9551 // specialization declaration, check that it's visible.
9552
9553 if (!Diagnoser)
9554 return true;
9555
9556 Diagnoser->diagnose(*this, Loc, T);
9557
9558 // If the type was a forward declaration of a class/struct/union
9559 // type, produce a note.
9560 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid())
9561 Diag(Tag->getLocation(), Tag->isBeingDefined()
9562 ? diag::note_type_being_defined
9563 : diag::note_forward_declaration)
9564 << Context.getCanonicalTagType(Tag);
9565
9566 // If the Objective-C class was a forward declaration, produce a note.
9567 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid())
9568 Diag(IFace->getLocation(), diag::note_forward_class);
9569
9570 // If we have external information that we can use to suggest a fix,
9571 // produce a note.
9572 if (ExternalSource)
9573 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
9574
9575 return true;
9576}
9577
9579 CompleteTypeKind Kind, unsigned DiagID) {
9580 BoundTypeDiagnoser<> Diagnoser(DiagID);
9581 return RequireCompleteType(Loc, T, Kind, Diagnoser);
9582}
9583
9584/// Get diagnostic %select index for tag kind for
9585/// literal type diagnostic message.
9586/// WARNING: Indexes apply to particular diagnostics only!
9587///
9588/// \returns diagnostic %select index.
9590 switch (Tag) {
9592 return 0;
9594 return 1;
9595 case TagTypeKind::Class:
9596 return 2;
9597 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
9598 }
9599}
9600
9602 TypeDiagnoser &Diagnoser) {
9603 assert(!T->isDependentType() && "type should not be dependent");
9604
9605 QualType ElemType = Context.getBaseElementType(T);
9606 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
9607 T->isLiteralType(Context))
9608 return false;
9609
9610 Diagnoser.diagnose(*this, Loc, T);
9611
9612 if (T->isVariableArrayType())
9613 return true;
9614
9615 if (!ElemType->isRecordType())
9616 return true;
9617
9618 // A partially-defined class type can't be a literal type, because a literal
9619 // class type must have a trivial destructor (which can't be checked until
9620 // the class definition is complete).
9621 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
9622 return true;
9623
9624 const auto *RD = ElemType->castAsCXXRecordDecl();
9625 // [expr.prim.lambda]p3:
9626 // This class type is [not] a literal type.
9627 if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
9628 Diag(RD->getLocation(), diag::note_non_literal_lambda);
9629 return true;
9630 }
9631
9632 // If the class has virtual base classes, then it's not an aggregate, and
9633 // cannot have any constexpr constructors or a trivial default constructor,
9634 // so is non-literal. This is better to diagnose than the resulting absence
9635 // of constexpr constructors.
9636 if (RD->getNumVBases()) {
9637 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
9638 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
9639 for (const auto &I : RD->vbases())
9640 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
9641 << I.getSourceRange();
9642 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
9643 !RD->hasTrivialDefaultConstructor()) {
9644 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
9645 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
9646 for (const auto &I : RD->bases()) {
9647 if (!I.getType()->isLiteralType(Context)) {
9648 Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
9649 << RD << I.getType() << I.getSourceRange();
9650 return true;
9651 }
9652 }
9653 for (const auto *I : RD->fields()) {
9654 if (!I->getType()->isLiteralType(Context) ||
9655 I->getType().isVolatileQualified()) {
9656 Diag(I->getLocation(), diag::note_non_literal_field)
9657 << RD << I << I->getType()
9658 << I->getType().isVolatileQualified();
9659 return true;
9660 }
9661 }
9662 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor()
9663 : !RD->hasTrivialDestructor()) {
9664 // All fields and bases are of literal types, so have trivial or constexpr
9665 // destructors. If this class's destructor is non-trivial / non-constexpr,
9666 // it must be user-declared.
9667 CXXDestructorDecl *Dtor = RD->getDestructor();
9668 assert(Dtor && "class has literal fields and bases but no dtor?");
9669 if (!Dtor)
9670 return true;
9671
9672 if (getLangOpts().CPlusPlus20) {
9673 Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor)
9674 << RD;
9675 } else {
9676 Diag(Dtor->getLocation(), Dtor->isUserProvided()
9677 ? diag::note_non_literal_user_provided_dtor
9678 : diag::note_non_literal_nontrivial_dtor)
9679 << RD;
9680 if (!Dtor->isUserProvided())
9683 /*Diagnose*/ true);
9684 }
9685 }
9686
9687 return true;
9688}
9689
9691 BoundTypeDiagnoser<> Diagnoser(DiagID);
9692 return RequireLiteralType(Loc, T, Diagnoser);
9693}
9694
9696 assert(!E->hasPlaceholderType() && "unexpected placeholder");
9697
9698 if (!getLangOpts().CPlusPlus && E->refersToBitField())
9699 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
9700 << (Kind == TypeOfKind::Unqualified ? 3 : 2);
9701
9702 if (!E->isTypeDependent()) {
9703 QualType T = E->getType();
9704 if (const TagType *TT = T->getAs<TagType>())
9705 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
9706 }
9707 return Context.getTypeOfExprType(E, Kind);
9708}
9709
9710static void
9713 // Currently, 'counted_by' only allows direct DeclRefExpr to FieldDecl.
9714 auto *CountDecl = cast<DeclRefExpr>(E)->getDecl();
9715 Decls.push_back(TypeCoupledDeclRefInfo(CountDecl, /*IsDref*/ false));
9716}
9717
9719 Expr *CountExpr,
9720 bool CountInBytes,
9721 bool OrNull) {
9722 assert(WrappedTy->isIncompleteArrayType() || WrappedTy->isPointerType());
9723
9725 BuildTypeCoupledDecls(CountExpr, Decls);
9726 /// When the resulting expression is invalid, we still create the AST using
9727 /// the original count expression for the sake of AST dump.
9728 return Context.getCountAttributedType(WrappedTy, CountExpr, CountInBytes,
9729 OrNull, Decls);
9730}
9731
9732/// getDecltypeForExpr - Given an expr, will return the decltype for
9733/// that expression, according to the rules in C++11
9734/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
9736
9737 Expr *IDExpr = E;
9738 if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E))
9739 IDExpr = ImplCastExpr->getSubExpr();
9740
9741 if (auto *PackExpr = dyn_cast<PackIndexingExpr>(E)) {
9742 if (E->isInstantiationDependent())
9743 IDExpr = PackExpr->getPackIdExpression();
9744 else
9745 IDExpr = PackExpr->getSelectedExpr();
9746 }
9747
9748 if (E->isTypeDependent())
9749 return Context.DependentTy;
9750
9751 // C++11 [dcl.type.simple]p4:
9752 // The type denoted by decltype(e) is defined as follows:
9753
9754 // C++20:
9755 // - if E is an unparenthesized id-expression naming a non-type
9756 // template-parameter (13.2), decltype(E) is the type of the
9757 // template-parameter after performing any necessary type deduction
9758 // Note that this does not pick up the implicit 'const' for a template
9759 // parameter object. This rule makes no difference before C++20 so we apply
9760 // it unconditionally.
9761 if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr))
9762 return SNTTPE->getParameterType(Context);
9763
9764 // - if e is an unparenthesized id-expression or an unparenthesized class
9765 // member access (5.2.5), decltype(e) is the type of the entity named
9766 // by e. If there is no such entity, or if e names a set of overloaded
9767 // functions, the program is ill-formed;
9768 //
9769 // We apply the same rules for Objective-C ivar and property references.
9770 if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) {
9771 const ValueDecl *VD = DRE->getDecl();
9772 QualType T = VD->getType();
9773 return isa<TemplateParamObjectDecl>(VD) ? T.getUnqualifiedType() : T;
9774 }
9775 if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) {
9776 if (const auto *VD = ME->getMemberDecl())
9777 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
9778 return VD->getType();
9779 } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) {
9780 return IR->getDecl()->getType();
9781 } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) {
9782 if (PR->isExplicitProperty())
9783 return PR->getExplicitProperty()->getType();
9784 } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) {
9785 return PE->getType();
9786 }
9787
9788 // C++11 [expr.lambda.prim]p18:
9789 // Every occurrence of decltype((x)) where x is a possibly
9790 // parenthesized id-expression that names an entity of automatic
9791 // storage duration is treated as if x were transformed into an
9792 // access to a corresponding data member of the closure type that
9793 // would have been declared if x were an odr-use of the denoted
9794 // entity.
9795 if (getCurLambda() && isa<ParenExpr>(IDExpr)) {
9796 if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) {
9797 if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
9798 QualType T = getCapturedDeclRefType(Var, DRE->getLocation());
9799 if (!T.isNull())
9800 return Context.getLValueReferenceType(T);
9801 }
9802 }
9803 }
9804
9805 return Context.getReferenceQualifiedType(E);
9806}
9807
9808QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) {
9809 assert(!E->hasPlaceholderType() && "unexpected placeholder");
9810
9811 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
9812 !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) {
9813 // The expression operand for decltype is in an unevaluated expression
9814 // context, so side effects could result in unintended consequences.
9815 // Exclude instantiation-dependent expressions, because 'decltype' is often
9816 // used to build SFINAE gadgets.
9817 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
9818 }
9819 return Context.getDecltypeType(E, getDecltypeForExpr(E));
9820}
9821
9823 SourceLocation Loc,
9824 SourceLocation EllipsisLoc) {
9825 if (!IndexExpr)
9826 return QualType();
9827
9828 // Diagnose unexpanded packs but continue to improve recovery.
9829 if (!Pattern->containsUnexpandedParameterPack())
9830 Diag(Loc, diag::err_expected_name_of_pack) << Pattern;
9831
9832 QualType Type = BuildPackIndexingType(Pattern, IndexExpr, Loc, EllipsisLoc);
9833
9834 if (!Type.isNull())
9835 Diag(Loc, getLangOpts().CPlusPlus26 ? diag::warn_cxx23_pack_indexing
9836 : diag::ext_pack_indexing);
9837 return Type;
9838}
9839
9841 SourceLocation Loc,
9842 SourceLocation EllipsisLoc,
9843 bool FullySubstituted,
9844 ArrayRef<QualType> Expansions) {
9845
9846 UnsignedOrNone Index = std::nullopt;
9847 if (FullySubstituted && !IndexExpr->isValueDependent() &&
9848 !IndexExpr->isTypeDependent()) {
9849 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
9851 IndexExpr, Context.getSizeType(), Value, CCEKind::ArrayBound);
9852 if (!Res.isUsable())
9853 return QualType();
9854 IndexExpr = Res.get();
9855 int64_t V = Value.getExtValue();
9856 if (FullySubstituted && (V < 0 || V >= int64_t(Expansions.size()))) {
9857 Diag(IndexExpr->getBeginLoc(), diag::err_pack_index_out_of_bound)
9858 << V << Pattern << Expansions.size();
9859 return QualType();
9860 }
9861 Index = static_cast<unsigned>(V);
9862 }
9863
9864 return Context.getPackIndexingType(Pattern, IndexExpr, FullySubstituted,
9865 Expansions, Index);
9866}
9867
9869 SourceLocation Loc) {
9870 assert(BaseType->isEnumeralType());
9871 EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl();
9872
9873 S.DiagnoseUseOfDecl(ED, Loc);
9874
9875 QualType Underlying = ED->getIntegerType();
9876 if (Underlying.isNull()) {
9877 // This is an enum without a fixed underlying type which we skipped parsing
9878 // the body because we saw its definition previously in another module.
9879 // Use the definition's integer type in that case.
9881 Underlying = ED->getDefinition()->getIntegerType();
9882 assert(!Underlying.isNull());
9883 }
9884
9885 return Underlying;
9886}
9887
9889 SourceLocation Loc) {
9890 if (!BaseType->isEnumeralType()) {
9891 Diag(Loc, diag::err_only_enums_have_underlying_types);
9892 return QualType();
9893 }
9894
9895 // The enum could be incomplete if we're parsing its definition or
9896 // recovering from an error.
9897 NamedDecl *FwdDecl = nullptr;
9898 if (BaseType->isIncompleteType(&FwdDecl)) {
9899 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
9900 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
9901 return QualType();
9902 }
9903
9904 return GetEnumUnderlyingType(*this, BaseType, Loc);
9905}
9906
9908 QualType Pointer = BaseType.isReferenceable() || BaseType->isVoidType()
9909 ? BuildPointerType(BaseType.getNonReferenceType(), Loc,
9911 : BaseType;
9912
9913 return Pointer.isNull() ? QualType() : Pointer;
9914}
9915
9917 if (!BaseType->isAnyPointerType())
9918 return BaseType;
9919
9920 return BaseType->getPointeeType();
9921}
9922
9924 QualType Underlying = BaseType.getNonReferenceType();
9925 if (Underlying->isArrayType())
9926 return Context.getDecayedType(Underlying);
9927
9928 if (Underlying->isFunctionType())
9929 return BuiltinAddPointer(BaseType, Loc);
9930
9931 SplitQualType Split = Underlying.getSplitUnqualifiedType();
9932 // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is
9933 // in the same group of qualifiers as 'const' and 'volatile', we're extending
9934 // '__decay(T)' so that it removes all qualifiers.
9935 Split.Quals.removeCVRQualifiers();
9936 return Context.getQualifiedType(Split);
9937}
9938
9940 SourceLocation Loc) {
9941 assert(LangOpts.CPlusPlus);
9943 BaseType.isReferenceable()
9944 ? BuildReferenceType(BaseType,
9945 UKind == UnaryTransformType::AddLvalueReference,
9946 Loc, DeclarationName())
9947 : BaseType;
9948 return Reference.isNull() ? QualType() : Reference;
9949}
9950
9952 SourceLocation Loc) {
9953 if (UKind == UnaryTransformType::RemoveAllExtents)
9954 return Context.getBaseElementType(BaseType);
9955
9956 if (const auto *AT = Context.getAsArrayType(BaseType))
9957 return AT->getElementType();
9958
9959 return BaseType;
9960}
9961
9963 SourceLocation Loc) {
9964 assert(LangOpts.CPlusPlus);
9965 QualType T = BaseType.getNonReferenceType();
9966 if (UKind == UTTKind::RemoveCVRef &&
9967 (T.isConstQualified() || T.isVolatileQualified())) {
9968 Qualifiers Quals;
9969 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
9970 Quals.removeConst();
9971 Quals.removeVolatile();
9972 T = Context.getQualifiedType(Unqual, Quals);
9973 }
9974 return T;
9975}
9976
9978 SourceLocation Loc) {
9979 if ((BaseType->isReferenceType() && UKind != UTTKind::RemoveRestrict) ||
9980 BaseType->isFunctionType())
9981 return BaseType;
9982
9983 Qualifiers Quals;
9984 QualType Unqual = Context.getUnqualifiedArrayType(BaseType, Quals);
9985
9986 if (UKind == UTTKind::RemoveConst || UKind == UTTKind::RemoveCV)
9987 Quals.removeConst();
9988 if (UKind == UTTKind::RemoveVolatile || UKind == UTTKind::RemoveCV)
9989 Quals.removeVolatile();
9990 if (UKind == UTTKind::RemoveRestrict)
9991 Quals.removeRestrict();
9992
9993 return Context.getQualifiedType(Unqual, Quals);
9994}
9995
9997 bool IsMakeSigned,
9998 SourceLocation Loc) {
9999 if (BaseType->isEnumeralType()) {
10000 QualType Underlying = GetEnumUnderlyingType(S, BaseType, Loc);
10001 if (auto *BitInt = dyn_cast<BitIntType>(Underlying)) {
10002 unsigned int Bits = BitInt->getNumBits();
10003 if (Bits > 1)
10004 return S.Context.getBitIntType(!IsMakeSigned, Bits);
10005
10006 S.Diag(Loc, diag::err_make_signed_integral_only)
10007 << IsMakeSigned << /*_BitInt(1)*/ true << BaseType << 1 << Underlying;
10008 return QualType();
10009 }
10010 if (Underlying->isBooleanType()) {
10011 S.Diag(Loc, diag::err_make_signed_integral_only)
10012 << IsMakeSigned << /*_BitInt(1)*/ false << BaseType << 1
10013 << Underlying;
10014 return QualType();
10015 }
10016 }
10017
10018 bool Int128Unsupported = !S.Context.getTargetInfo().hasInt128Type();
10019 std::array<CanQualType *, 6> AllSignedIntegers = {
10022 ArrayRef<CanQualType *> AvailableSignedIntegers(
10023 AllSignedIntegers.data(), AllSignedIntegers.size() - Int128Unsupported);
10024 std::array<CanQualType *, 6> AllUnsignedIntegers = {
10028 ArrayRef<CanQualType *> AvailableUnsignedIntegers(AllUnsignedIntegers.data(),
10029 AllUnsignedIntegers.size() -
10030 Int128Unsupported);
10031 ArrayRef<CanQualType *> *Consider =
10032 IsMakeSigned ? &AvailableSignedIntegers : &AvailableUnsignedIntegers;
10033
10034 uint64_t BaseSize = S.Context.getTypeSize(BaseType);
10035 auto *Result =
10036 llvm::find_if(*Consider, [&S, BaseSize](const CanQual<Type> *T) {
10037 return BaseSize == S.Context.getTypeSize(T->getTypePtr());
10038 });
10039
10040 assert(Result != Consider->end());
10041 return QualType((*Result)->getTypePtr(), 0);
10042}
10043
10045 SourceLocation Loc) {
10046 bool IsMakeSigned = UKind == UnaryTransformType::MakeSigned;
10047 if ((!BaseType->isIntegerType() && !BaseType->isEnumeralType()) ||
10048 BaseType->isBooleanType() ||
10049 (BaseType->isBitIntType() &&
10050 BaseType->getAs<BitIntType>()->getNumBits() < 2)) {
10051 Diag(Loc, diag::err_make_signed_integral_only)
10052 << IsMakeSigned << BaseType->isBitIntType() << BaseType << 0;
10053 return QualType();
10054 }
10055
10056 bool IsNonIntIntegral =
10057 BaseType->isChar16Type() || BaseType->isChar32Type() ||
10058 BaseType->isWideCharType() || BaseType->isEnumeralType();
10059
10060 QualType Underlying =
10061 IsNonIntIntegral
10062 ? ChangeIntegralSignedness(*this, BaseType, IsMakeSigned, Loc)
10063 : IsMakeSigned ? Context.getCorrespondingSignedType(BaseType)
10064 : Context.getCorrespondingUnsignedType(BaseType);
10065 if (Underlying.isNull())
10066 return Underlying;
10067 return Context.getQualifiedType(Underlying, BaseType.getQualifiers());
10068}
10069
10071 SourceLocation Loc) {
10072 if (BaseType->isDependentType())
10073 return Context.getUnaryTransformType(BaseType, BaseType, UKind);
10075 switch (UKind) {
10076 case UnaryTransformType::EnumUnderlyingType: {
10077 Result = BuiltinEnumUnderlyingType(BaseType, Loc);
10078 break;
10079 }
10080 case UnaryTransformType::AddPointer: {
10081 Result = BuiltinAddPointer(BaseType, Loc);
10082 break;
10083 }
10084 case UnaryTransformType::RemovePointer: {
10085 Result = BuiltinRemovePointer(BaseType, Loc);
10086 break;
10087 }
10088 case UnaryTransformType::Decay: {
10089 Result = BuiltinDecay(BaseType, Loc);
10090 break;
10091 }
10092 case UnaryTransformType::AddLvalueReference:
10093 case UnaryTransformType::AddRvalueReference: {
10094 Result = BuiltinAddReference(BaseType, UKind, Loc);
10095 break;
10096 }
10097 case UnaryTransformType::RemoveAllExtents:
10098 case UnaryTransformType::RemoveExtent: {
10099 Result = BuiltinRemoveExtent(BaseType, UKind, Loc);
10100 break;
10101 }
10102 case UnaryTransformType::RemoveCVRef:
10103 case UnaryTransformType::RemoveReference: {
10104 Result = BuiltinRemoveReference(BaseType, UKind, Loc);
10105 break;
10106 }
10107 case UnaryTransformType::RemoveConst:
10108 case UnaryTransformType::RemoveCV:
10109 case UnaryTransformType::RemoveRestrict:
10110 case UnaryTransformType::RemoveVolatile: {
10111 Result = BuiltinChangeCVRQualifiers(BaseType, UKind, Loc);
10112 break;
10113 }
10114 case UnaryTransformType::MakeSigned:
10115 case UnaryTransformType::MakeUnsigned: {
10116 Result = BuiltinChangeSignedness(BaseType, UKind, Loc);
10117 break;
10118 }
10119 }
10120
10121 return !Result.isNull()
10122 ? Context.getUnaryTransformType(BaseType, Result, UKind)
10123 : Result;
10124}
10125
10128 // FIXME: It isn't entirely clear whether incomplete atomic types
10129 // are allowed or not; for simplicity, ban them for the moment.
10130 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
10131 return QualType();
10132
10133 int DisallowedKind = -1;
10134 if (T->isArrayType())
10135 DisallowedKind = 1;
10136 else if (T->isFunctionType())
10137 DisallowedKind = 2;
10138 else if (T->isReferenceType())
10139 DisallowedKind = 3;
10140 else if (T->isAtomicType())
10141 DisallowedKind = 4;
10142 else if (T.hasQualifiers())
10143 DisallowedKind = 5;
10144 else if (T->isSizelessType())
10145 DisallowedKind = 6;
10146 else if (!T.isTriviallyCopyableType(Context) && getLangOpts().CPlusPlus)
10147 // Some other non-trivially-copyable type (probably a C++ class)
10148 DisallowedKind = 7;
10149 else if (T->isBitIntType())
10150 DisallowedKind = 8;
10151 else if (getLangOpts().C23 && T->isUndeducedAutoType())
10152 // _Atomic auto is prohibited in C23
10153 DisallowedKind = 9;
10154
10155 if (DisallowedKind != -1) {
10156 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
10157 return QualType();
10158 }
10159
10160 // FIXME: Do we need any handling for ARC here?
10161 }
10162
10163 // Build the pointer type.
10164 return Context.getAtomicType(T);
10165}
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:45
attr::Kind getKind() const
Definition Attr.h:91
const char * getSpelling() const
void setImplicit(bool I)
Definition Attr.h:105
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:279
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:13522
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:15309
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:15005
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:1670
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:14381
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:2561
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:6467
std::vector< std::unique_ptr< TemplateInstantiationCallback > > TemplateInstCallbacks
The template instantiation callbacks to trace or track instantiations (objects can be chained).
Definition Sema.h:13569
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:14980
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1314
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition Sema.cpp:2298
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:15421
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:13884
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:4071
@ NTCUK_Copy
Definition Sema.h:4072
QualType BuildAtomicType(QualType T, SourceLocation Loc)
void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl, MissingImportKind MIK, bool Recover=true)
Diagnose that the specified declaration needs to be visible but isn't, and suggest a module import th...
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX, const FunctionEffectWithCondition &EC, SourceLocation NewAttrLoc)
Warn and return true if adding a function effect to a set would create a conflict.
TypeSourceInfo * ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement)
TypeResult ActOnTypeName(Declarator &D)
bool isSFINAEContext() const
Definition Sema.h:13619
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:15363
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:625
QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, SourceLocation AttrLoc)
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2101
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:687
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual size_t getMaxBitIntWidth() const
Definition TargetInfo.h:693
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:487
virtual bool allowHalfArgsAndReturns() const
Whether half args and returns are supported.
Definition TargetInfo.h:712
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition TargetInfo.h:676
virtual bool hasFloat16Type() const
Determine whether the _Float16 type is supported on this target.
Definition TargetInfo.h:718
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:730
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:715
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition TargetInfo.h:721
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:13053
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ Memoization
Added for Template instantiation observation.
Definition Sema.h:13157
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.