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