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