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 }
1301 Expr *E = DS.getPackIndexingExpr();
1302 assert(E && "Didn't get an expression for pack indexing");
1303 QualType Pattern = S.GetTypeFromParser(DS.getRepAsType());
1304 Result = S.BuildPackIndexingType(Pattern, E, DS.getBeginLoc(),
1305 DS.getEllipsisLoc());
1306 if (Result.isNull()) {
1307 declarator.setInvalidType(true);
1308 Result = Context.IntTy;
1309 }
1310 break;
1311 }
1312
1313#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
1314#include "clang/Basic/BuiltinTraits.inc"
1316 assert(!Result.isNull() && "Didn't get a type for the transformation?");
1319 DS.getTypeSpecTypeLoc());
1320 if (Result.isNull()) {
1321 Result = Context.IntTy;
1322 declarator.setInvalidType(true);
1323 }
1324 break;
1325
1326 case DeclSpec::TST_auto:
1328 auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1331
1332 TemplateName TypeConstraintConcept;
1334 if (DS.isConstrainedAuto()) {
1335 if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1336 TypeConstraintConcept = TemplateId->Template.get();
1337 TemplateArgumentListInfo TemplateArgsInfo;
1338 TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1339 TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1340 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1341 TemplateId->NumArgs);
1342 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1343 for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1344 TemplateArgs.push_back(ArgLoc.getArgument());
1345 } else {
1346 declarator.setInvalidType(true);
1347 }
1348 }
1350 TypeConstraintConcept, TemplateArgs);
1351 break;
1352 }
1353
1355 Result = Context.getAutoType(DeducedKind::Undeduced, QualType(),
1357 break;
1358
1360 Result = Context.UnknownAnyTy;
1361 break;
1362
1365 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1367 if (Result.isNull()) {
1368 Result = Context.IntTy;
1369 declarator.setInvalidType(true);
1370 }
1371 break;
1372
1373#define GENERIC_IMAGE_TYPE(ImgType, Id) \
1374 case DeclSpec::TST_##ImgType##_t: \
1375 switch (getImageAccess(DS.getAttributes())) { \
1376 case OpenCLAccessAttr::Keyword_write_only: \
1377 Result = Context.Id##WOTy; \
1378 break; \
1379 case OpenCLAccessAttr::Keyword_read_write: \
1380 Result = Context.Id##RWTy; \
1381 break; \
1382 case OpenCLAccessAttr::Keyword_read_only: \
1383 Result = Context.Id##ROTy; \
1384 break; \
1385 case OpenCLAccessAttr::SpellingNotCalculated: \
1386 llvm_unreachable("Spelling not yet calculated"); \
1387 } \
1388 break;
1389#include "clang/Basic/OpenCLImageTypes.def"
1390
1391#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1392 case DeclSpec::TST_##Name: \
1393 Result = Context.SingletonId; \
1394 break;
1395#include "clang/Basic/HLSLIntangibleTypes.def"
1396
1398 Result = Context.IntTy;
1399 declarator.setInvalidType(true);
1400 break;
1401 }
1402
1403 // FIXME: we want resulting declarations to be marked invalid, but claiming
1404 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1405 // a null type.
1406 if (Result->containsErrors())
1407 declarator.setInvalidType();
1408
1409 if (S.getLangOpts().OpenCL) {
1410 const auto &OpenCLOptions = S.getOpenCLOptions();
1411 bool IsOpenCLC30Compatible =
1413 // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1414 // support.
1415 // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1416 // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1417 // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1418 // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1419 // only when the optional feature is supported
1420 if ((Result->isImageType() || Result->isSamplerT()) &&
1421 (IsOpenCLC30Compatible &&
1422 !OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts()))) {
1423 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1424 << 0 << Result << "__opencl_c_images";
1425 declarator.setInvalidType();
1426 } else if (Result->isOCLImage3dWOType() &&
1427 !OpenCLOptions.isSupported("cl_khr_3d_image_writes",
1428 S.getLangOpts())) {
1429 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1430 << 0 << Result
1431 << (IsOpenCLC30Compatible
1432 ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes"
1433 : "cl_khr_3d_image_writes");
1434 declarator.setInvalidType();
1435 }
1436 }
1437
1438 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1440
1441 // Only fixed point types can be saturated
1442 if (DS.isTypeSpecSat() && !IsFixedPointType)
1443 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1445 Context.getPrintingPolicy());
1446
1447 // Handle complex types.
1449 if (S.getLangOpts().Freestanding)
1450 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1451 Result = Context.getComplexType(Result);
1452 } else if (DS.isTypeAltiVecVector()) {
1453 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1454 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1456 if (DS.isTypeAltiVecPixel())
1457 VecKind = VectorKind::AltiVecPixel;
1458 else if (DS.isTypeAltiVecBool())
1459 VecKind = VectorKind::AltiVecBool;
1460 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1461 }
1462
1463 // _Imaginary was a feature of C99 through C23 but was never supported in
1464 // Clang. The feature was removed in C2y, but we retain the unsupported
1465 // diagnostic for an improved user experience.
1467 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1468
1469 // Before we process any type attributes, synthesize a block literal
1470 // function declarator if necessary.
1471 if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1473
1474 // Apply any type attributes from the decl spec. This may cause the
1475 // list of type attributes to be temporarily saved while the type
1476 // attributes are pushed around.
1477 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1478 if (!DS.isTypeSpecPipe()) {
1479 // We also apply declaration attributes that "slide" to the decl spec.
1480 // Ordering can be important for attributes. The decalaration attributes
1481 // come syntactically before the decl spec attributes, so we process them
1482 // in that order.
1483 ParsedAttributesView SlidingAttrs;
1484 for (ParsedAttr &AL : declarator.getDeclarationAttributes()) {
1485 if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
1486 SlidingAttrs.addAtEnd(&AL);
1487
1488 // For standard syntax attributes, which would normally appertain to the
1489 // declaration here, suggest moving them to the type instead. But only
1490 // do this for our own vendor attributes; moving other vendors'
1491 // attributes might hurt portability.
1492 // There's one special case that we need to deal with here: The
1493 // `MatrixType` attribute may only be used in a typedef declaration. If
1494 // it's being used anywhere else, don't output the warning as
1495 // ProcessDeclAttributes() will output an error anyway.
1496 if (AL.isStandardAttributeSyntax() && AL.isClangScope() &&
1497 !(AL.getKind() == ParsedAttr::AT_MatrixType &&
1499 S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl)
1500 << AL;
1501 }
1502 }
1503 }
1504 // During this call to processTypeAttrs(),
1505 // TypeProcessingState::getCurrentAttributes() will erroneously return a
1506 // reference to the DeclSpec attributes, rather than the declaration
1507 // attributes. However, this doesn't matter, as getCurrentAttributes()
1508 // is only called when distributing attributes from one attribute list
1509 // to another. Declaration attributes are always C++11 attributes, and these
1510 // are never distributed.
1511 processTypeAttrs(state, Result, TAL_DeclSpec, SlidingAttrs);
1513 }
1514
1515 // Apply const/volatile/restrict qualifiers to T.
1516 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1517 // Warn about CV qualifiers on function types.
1518 // C99 6.7.3p8:
1519 // If the specification of a function type includes any type qualifiers,
1520 // the behavior is undefined.
1521 // C2y changed this behavior to be implementation-defined. Clang defines
1522 // the behavior in all cases to ignore the qualifier, as in C++.
1523 // C++11 [dcl.fct]p7:
1524 // The effect of a cv-qualifier-seq in a function declarator is not the
1525 // same as adding cv-qualification on top of the function type. In the
1526 // latter case, the cv-qualifiers are ignored.
1527 if (Result->isFunctionType()) {
1528 unsigned DiagId = diag::warn_typecheck_function_qualifiers_ignored;
1529 if (!S.getLangOpts().CPlusPlus && !S.getLangOpts().C2y)
1530 DiagId = diag::ext_typecheck_function_qualifiers_unspecified;
1532 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1533 DiagId);
1534 // No diagnostic for 'restrict' or '_Atomic' applied to a
1535 // function type; we'll diagnose those later, in BuildQualifiedType.
1536 }
1537
1538 // C++11 [dcl.ref]p1:
1539 // Cv-qualified references are ill-formed except when the
1540 // cv-qualifiers are introduced through the use of a typedef-name
1541 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1542 //
1543 // There don't appear to be any other contexts in which a cv-qualified
1544 // reference type could be formed, so the 'ill-formed' clause here appears
1545 // to never happen.
1546 if (TypeQuals && Result->isReferenceType()) {
1548 S, DS, TypeQuals, Result,
1550 diag::warn_typecheck_reference_qualifiers);
1551 }
1552
1553 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1554 // than once in the same specifier-list or qualifier-list, either directly
1555 // or via one or more typedefs."
1556 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1557 && TypeQuals & Result.getCVRQualifiers()) {
1558 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1559 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1560 << "const";
1561 }
1562
1563 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1564 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1565 << "volatile";
1566 }
1567
1568 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1569 // produce a warning in this case.
1570 }
1571
1572 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1573
1574 // If adding qualifiers fails, just use the unqualified type.
1575 if (Qualified.isNull())
1576 declarator.setInvalidType(true);
1577 else
1578 Result = Qualified;
1579 }
1580
1581 // Check for __ob_wrap and __ob_trap
1582 if (DS.isOverflowBehaviorSpecified() &&
1583 S.getLangOpts().OverflowBehaviorTypes) {
1584 if (!Result->isIntegerType()) {
1586 StringRef SpecifierName =
1588 S.Diag(Loc, diag::err_overflow_behavior_non_integer_type)
1589 << SpecifierName << Result.getAsString() << 1;
1590 } else {
1591 OverflowBehaviorType::OverflowBehaviorKind Kind =
1592 DS.isWrapSpecified()
1593 ? OverflowBehaviorType::OverflowBehaviorKind::Wrap
1594 : OverflowBehaviorType::OverflowBehaviorKind::Trap;
1595 Result = state.getOverflowBehaviorType(Kind, Result);
1596 }
1597 }
1598
1599 if (S.getLangOpts().HLSL)
1601
1602 assert(!Result.isNull() && "This function should not return a null type");
1603 return Result;
1604}
1605
1606static std::string getPrintableNameForEntity(DeclarationName Entity) {
1607 if (Entity)
1608 return Entity.getAsString();
1609
1610 return "type name";
1611}
1612
1614 Qualifiers Qs, const DeclSpec *DS) {
1615 if (T.isNull())
1616 return QualType();
1617
1618 // Ignore any attempt to form a cv-qualified reference.
1619 if (T->isReferenceType()) {
1620 Qs.removeConst();
1621 Qs.removeVolatile();
1622 }
1623
1624 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1625 // object or incomplete types shall not be restrict-qualified."
1626 if (Qs.hasRestrict()) {
1627 unsigned DiagID = 0;
1628 QualType EltTy = Context.getBaseElementType(T);
1629
1630 if (EltTy->isAnyPointerType() || EltTy->isReferenceType() ||
1631 EltTy->isMemberPointerType()) {
1632
1633 if (const auto *PTy = EltTy->getAs<MemberPointerType>())
1634 EltTy = PTy->getPointeeType();
1635 else
1636 EltTy = EltTy->getPointeeType();
1637
1638 // If we have a pointer or reference, the pointee must have an object
1639 // incomplete type.
1640 if (!EltTy->isIncompleteOrObjectType())
1641 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1642
1643 } else if (!T->isDependentType() && !isa<AutoType>(T)) {
1644 // For an inferred type, we may not have seen the initializer yet and so
1645 // have no idea whether the underlying type is a pointer type or not.
1646 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1647 EltTy = T;
1648 }
1649
1650 Loc = DS ? DS->getRestrictSpecLoc() : Loc;
1651 if (DiagID) {
1652 Diag(Loc, DiagID) << EltTy;
1653 Qs.removeRestrict();
1654 } else {
1655 if (T->isArrayType())
1656 DiagCompat(Loc, diag_compat::restrict_on_array_of_pointers);
1657 }
1658 }
1659
1660 return Context.getQualifiedType(T, Qs);
1661}
1662
1664 unsigned CVRAU, const DeclSpec *DS) {
1665 if (T.isNull())
1666 return QualType();
1667
1668 // Ignore any attempt to form a cv-qualified reference.
1669 if (T->isReferenceType())
1670 CVRAU &=
1672
1673 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1674 // TQ_unaligned;
1675 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1676
1677 // C11 6.7.3/5:
1678 // If the same qualifier appears more than once in the same
1679 // specifier-qualifier-list, either directly or via one or more typedefs,
1680 // the behavior is the same as if it appeared only once.
1681 //
1682 // It's not specified what happens when the _Atomic qualifier is applied to
1683 // a type specified with the _Atomic specifier, but we assume that this
1684 // should be treated as if the _Atomic qualifier appeared multiple times.
1685 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1686 // C11 6.7.3/5:
1687 // If other qualifiers appear along with the _Atomic qualifier in a
1688 // specifier-qualifier-list, the resulting type is the so-qualified
1689 // atomic type.
1690 //
1691 // Don't need to worry about array types here, since _Atomic can't be
1692 // applied to such types.
1693 SplitQualType Split = T.getSplitUnqualifiedType();
1694 T = BuildAtomicType(QualType(Split.Ty, 0),
1695 DS ? DS->getAtomicSpecLoc() : Loc);
1696 if (T.isNull())
1697 return T;
1698 Split.Quals.addCVRQualifiers(CVR);
1699 return BuildQualifiedType(T, Loc, Split.Quals);
1700 }
1701
1704 return BuildQualifiedType(T, Loc, Q, DS);
1705}
1706
1708 return Context.getParenType(T);
1709}
1710
1711/// Given that we're building a pointer or reference to the given
1713 SourceLocation loc,
1714 bool isReference) {
1715 // Bail out if retention is unrequired or already specified.
1716 if (!type->isObjCLifetimeType() ||
1717 type.getObjCLifetime() != Qualifiers::OCL_None)
1718 return type;
1719
1721
1722 // If the object type is const-qualified, we can safely use
1723 // __unsafe_unretained. This is safe (because there are no read
1724 // barriers), and it'll be safe to coerce anything but __weak* to
1725 // the resulting type.
1726 if (type.isConstQualified()) {
1727 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1728
1729 // Otherwise, check whether the static type does not require
1730 // retaining. This currently only triggers for Class (possibly
1731 // protocol-qualifed, and arrays thereof).
1732 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1733 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1734
1735 // If we are in an unevaluated context, like sizeof, skip adding a
1736 // qualification.
1737 } else if (S.isUnevaluatedContext()) {
1738 return type;
1739
1740 // If that failed, give an error and recover using __strong. __strong
1741 // is the option most likely to prevent spurious second-order diagnostics,
1742 // like when binding a reference to a field.
1743 } else {
1744 // These types can show up in private ivars in system headers, so
1745 // we need this to not be an error in those cases. Instead we
1746 // want to delay.
1750 diag::err_arc_indirect_no_ownership, type, isReference));
1751 } else {
1752 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1753 }
1754 implicitLifetime = Qualifiers::OCL_Strong;
1755 }
1756 assert(implicitLifetime && "didn't infer any lifetime!");
1757
1758 Qualifiers qs;
1759 qs.addObjCLifetime(implicitLifetime);
1760 return S.Context.getQualifiedType(type, qs);
1761}
1762
1763static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1764 std::string Quals = FnTy->getMethodQuals().getAsString();
1765
1766 switch (FnTy->getRefQualifier()) {
1767 case RQ_None:
1768 break;
1769
1770 case RQ_LValue:
1771 if (!Quals.empty())
1772 Quals += ' ';
1773 Quals += '&';
1774 break;
1775
1776 case RQ_RValue:
1777 if (!Quals.empty())
1778 Quals += ' ';
1779 Quals += "&&";
1780 break;
1781 }
1782
1783 return Quals;
1784}
1785
1786namespace {
1787/// Kinds of declarator that cannot contain a qualified function type.
1788///
1789/// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1790/// a function type with a cv-qualifier or a ref-qualifier can only appear
1791/// at the topmost level of a type.
1792///
1793/// Parens and member pointers are permitted. We don't diagnose array and
1794/// function declarators, because they don't allow function types at all.
1795///
1796/// The values of this enum are used in diagnostics.
1797enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1798} // end anonymous namespace
1799
1800/// Check whether the type T is a qualified function type, and if it is,
1801/// diagnose that it cannot be contained within the given kind of declarator.
1803 QualifiedFunctionKind QFK) {
1804 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1805 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1806 if (!FPT ||
1807 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1808 return false;
1809
1810 S.Diag(Loc, diag::err_compound_qualified_function_type)
1811 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1813 return true;
1814}
1815
1817 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1818 if (!FPT ||
1819 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1820 return false;
1821
1822 Diag(Loc, diag::err_qualified_function_typeid)
1824 return true;
1825}
1826
1827// Helper to deduce addr space of a pointee type in OpenCL mode.
1829 if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
1830 !PointeeType->isSamplerT() &&
1831 !PointeeType.hasAddressSpace())
1832 PointeeType = S.getASTContext().getAddrSpaceQualType(
1834 return PointeeType;
1835}
1836
1838 SourceLocation Loc, DeclarationName Entity) {
1839 if (T->isReferenceType()) {
1840 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1841 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1842 << getPrintableNameForEntity(Entity) << T;
1843 return QualType();
1844 }
1845
1846 if (T->isFunctionType() && getLangOpts().OpenCL &&
1847 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
1848 getLangOpts())) {
1849 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
1850 return QualType();
1851 }
1852
1853 if (getLangOpts().HLSL && Loc.isValid()) {
1854 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
1855 return QualType();
1856 }
1857
1858 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1859 return QualType();
1860
1861 if (T->isObjCObjectType())
1862 return Context.getObjCObjectPointerType(T);
1863
1864 // In ARC, it is forbidden to build pointers to unqualified pointers.
1865 if (getLangOpts().ObjCAutoRefCount)
1866 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1867
1868 if (getLangOpts().OpenCL)
1870
1871 // In WebAssembly, pointers to reference types and pointers to tables are
1872 // illegal.
1873 if (getASTContext().getTargetInfo().getTriple().isWasm()) {
1874 if (T.isWebAssemblyReferenceType()) {
1875 Diag(Loc, diag::err_wasm_reference_pr) << 0;
1876 return QualType();
1877 }
1878
1879 // We need to desugar the type here in case T is a ParenType.
1880 if (T->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
1881 Diag(Loc, diag::err_wasm_table_pr) << 0;
1882 return QualType();
1883 }
1884 }
1885
1886 // Build the pointer type.
1887 return Context.getPointerType(T);
1888}
1889
1891 SourceLocation Loc,
1892 DeclarationName Entity) {
1893 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1894 "Unresolved overloaded function type");
1895
1896 // C++0x [dcl.ref]p6:
1897 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1898 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1899 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1900 // the type "lvalue reference to T", while an attempt to create the type
1901 // "rvalue reference to cv TR" creates the type TR.
1902 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1903
1904 // C++ [dcl.ref]p4: There shall be no references to references.
1905 //
1906 // According to C++ DR 106, references to references are only
1907 // diagnosed when they are written directly (e.g., "int & &"),
1908 // but not when they happen via a typedef:
1909 //
1910 // typedef int& intref;
1911 // typedef intref& intref2;
1912 //
1913 // Parser::ParseDeclaratorInternal diagnoses the case where
1914 // references are written directly; here, we handle the
1915 // collapsing of references-to-references as described in C++0x.
1916 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1917
1918 // C++ [dcl.ref]p1:
1919 // A declarator that specifies the type "reference to cv void"
1920 // is ill-formed.
1921 if (T->isVoidType()) {
1922 Diag(Loc, diag::err_reference_to_void);
1923 return QualType();
1924 }
1925
1926 if (getLangOpts().HLSL && Loc.isValid()) {
1927 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1;
1928 return QualType();
1929 }
1930
1931 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1932 return QualType();
1933
1934 if (T->isFunctionType() && getLangOpts().OpenCL &&
1935 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
1936 getLangOpts())) {
1937 Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1;
1938 return QualType();
1939 }
1940
1941 // In ARC, it is forbidden to build references to unqualified pointers.
1942 if (getLangOpts().ObjCAutoRefCount)
1943 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1944
1945 if (getLangOpts().OpenCL)
1947
1948 // In WebAssembly, references to reference types and tables are illegal.
1949 if (getASTContext().getTargetInfo().getTriple().isWasm() &&
1950 T.isWebAssemblyReferenceType()) {
1951 Diag(Loc, diag::err_wasm_reference_pr) << 1;
1952 return QualType();
1953 }
1954 if (T->isWebAssemblyTableType()) {
1955 Diag(Loc, diag::err_wasm_table_pr) << 1;
1956 return QualType();
1957 }
1958
1959 // Handle restrict on references.
1960 if (LValueRef)
1961 return Context.getLValueReferenceType(T, SpelledAsLValue);
1962 return Context.getRValueReferenceType(T);
1963}
1964
1966 return Context.getReadPipeType(T);
1967}
1968
1970 return Context.getWritePipeType(T);
1971}
1972
1973QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth,
1974 SourceLocation Loc) {
1975 if (BitWidth->isInstantiationDependent())
1976 return Context.getDependentBitIntType(IsUnsigned, BitWidth);
1977
1978 llvm::APSInt Bits(32);
1980 BitWidth, &Bits, /*FIXME*/ AllowFoldKind::Allow);
1981
1982 if (ICE.isInvalid())
1983 return QualType();
1984
1985 size_t NumBits = Bits.getZExtValue();
1986 if (!IsUnsigned && NumBits < 2) {
1987 Diag(Loc, diag::err_bit_int_bad_size) << 0;
1988 return QualType();
1989 }
1990
1991 if (IsUnsigned && NumBits < 1) {
1992 Diag(Loc, diag::err_bit_int_bad_size) << 1;
1993 return QualType();
1994 }
1995
1996 const TargetInfo &TI = getASTContext().getTargetInfo();
1997 if (NumBits > TI.getMaxBitIntWidth()) {
1998 Diag(Loc, diag::err_bit_int_max_size)
1999 << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth());
2000 return QualType();
2001 }
2002
2003 return Context.getBitIntType(IsUnsigned, NumBits);
2004}
2005
2006/// Check whether the specified array bound can be evaluated using the relevant
2007/// language rules. If so, returns the possibly-converted expression and sets
2008/// SizeVal to the size. If not, but the expression might be a VLA bound,
2009/// returns ExprResult(). Otherwise, produces a diagnostic and returns
2010/// ExprError().
2011static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
2012 llvm::APSInt &SizeVal, unsigned VLADiag,
2013 bool VLAIsError) {
2014 if (S.getLangOpts().CPlusPlus14 &&
2015 (VLAIsError ||
2016 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) {
2017 // C++14 [dcl.array]p1:
2018 // The constant-expression shall be a converted constant expression of
2019 // type std::size_t.
2020 //
2021 // Don't apply this rule if we might be forming a VLA: in that case, we
2022 // allow non-constant expressions and constant-folding. We only need to use
2023 // the converted constant expression rules (to properly convert the source)
2024 // when the source expression is of class type.
2026 ArraySize, S.Context.getSizeType(), SizeVal, CCEKind::ArrayBound);
2027 }
2028
2029 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2030 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2031 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2032 public:
2033 unsigned VLADiag;
2034 bool VLAIsError;
2035 bool IsVLA = false;
2036
2037 VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2038 : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2039
2040 Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2041 QualType T) override {
2042 return S.Diag(Loc, diag::err_array_size_non_int) << T;
2043 }
2044
2045 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2046 SourceLocation Loc) override {
2047 IsVLA = !VLAIsError;
2048 return S.Diag(Loc, VLADiag);
2049 }
2050
2051 Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2052 SourceLocation Loc) override {
2053 return S.Diag(Loc, diag::ext_vla_folded_to_constant);
2054 }
2055 } Diagnoser(VLADiag, VLAIsError);
2056
2057 ExprResult R =
2058 S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser);
2059 if (Diagnoser.IsVLA)
2060 return ExprResult();
2061 return R;
2062}
2063
2065 EltTy = Context.getBaseElementType(EltTy);
2066 if (EltTy->isIncompleteType() || EltTy->isDependentType() ||
2067 EltTy->isUndeducedType())
2068 return true;
2069
2070 CharUnits Size = Context.getTypeSizeInChars(EltTy);
2071 CharUnits Alignment = Context.getTypeAlignInChars(EltTy);
2072
2073 if (Size.isMultipleOf(Alignment))
2074 return true;
2075
2076 Diag(Loc, diag::err_array_element_alignment)
2077 << EltTy << Size.getQuantity() << Alignment.getQuantity();
2078 return false;
2079}
2080
2082 Expr *ArraySize, unsigned Quals,
2083 SourceRange Brackets, DeclarationName Entity) {
2084
2085 SourceLocation Loc = Brackets.getBegin();
2086 if (getLangOpts().CPlusPlus) {
2087 // C++ [dcl.array]p1:
2088 // T is called the array element type; this type shall not be a reference
2089 // type, the (possibly cv-qualified) type void, a function type or an
2090 // abstract class type.
2091 //
2092 // C++ [dcl.array]p3:
2093 // When several "array of" specifications are adjacent, [...] only the
2094 // first of the constant expressions that specify the bounds of the arrays
2095 // may be omitted.
2096 //
2097 // Note: function types are handled in the common path with C.
2098 if (T->isReferenceType()) {
2099 Diag(Loc, diag::err_illegal_decl_array_of_references)
2100 << getPrintableNameForEntity(Entity) << T;
2101 return QualType();
2102 }
2103
2104 if (T->isVoidType() || T->isIncompleteArrayType()) {
2105 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2106 return QualType();
2107 }
2108
2109 if (RequireNonAbstractType(Brackets.getBegin(), T,
2110 diag::err_array_of_abstract_type))
2111 return QualType();
2112
2113 // Mentioning a member pointer type for an array type causes us to lock in
2114 // an inheritance model, even if it's inside an unused typedef.
2115 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2116 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2117 if (!MPTy->getQualifier().isDependent())
2118 (void)isCompleteType(Loc, T);
2119
2120 } else {
2121 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2122 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2123 if (!T.isWebAssemblyReferenceType() &&
2125 diag::err_array_incomplete_or_sizeless_type))
2126 return QualType();
2127 }
2128
2129 // Multi-dimensional arrays of WebAssembly references are not allowed.
2130 if (Context.getTargetInfo().getTriple().isWasm() && T->isArrayType()) {
2131 const auto *ATy = dyn_cast<ArrayType>(T);
2132 if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
2133 Diag(Loc, diag::err_wasm_reftype_multidimensional_array);
2134 return QualType();
2135 }
2136 }
2137
2138 if (T->isSizelessType() && !T.isWebAssemblyReferenceType()) {
2139 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2140 return QualType();
2141 }
2142
2143 if (T->isFunctionType()) {
2144 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2145 << getPrintableNameForEntity(Entity) << T;
2146 return QualType();
2147 }
2148
2149 if (const auto *RD = T->getAsRecordDecl()) {
2150 // If the element type is a struct or union that contains a variadic
2151 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2152 if (RD->hasFlexibleArrayMember())
2153 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2154 } else if (T->isObjCObjectType()) {
2155 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2156 return QualType();
2157 }
2158
2159 if (!checkArrayElementAlignment(T, Loc))
2160 return QualType();
2161
2162 // Do placeholder conversions on the array size expression.
2163 if (ArraySize && ArraySize->hasPlaceholderType()) {
2165 if (Result.isInvalid()) return QualType();
2166 ArraySize = Result.get();
2167 }
2168
2169 // Do lvalue-to-rvalue conversions on the array size expression.
2170 if (ArraySize && !ArraySize->isPRValue()) {
2172 if (Result.isInvalid())
2173 return QualType();
2174
2175 ArraySize = Result.get();
2176 }
2177
2178 // C99 6.7.5.2p1: The size expression shall have integer type.
2179 // C++11 allows contextual conversions to such types.
2180 if (!getLangOpts().CPlusPlus11 &&
2181 ArraySize && !ArraySize->isTypeDependent() &&
2183 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2184 << ArraySize->getType() << ArraySize->getSourceRange();
2185 return QualType();
2186 }
2187
2188 auto IsStaticAssertLike = [](const Expr *ArraySize, ASTContext &Context) {
2189 if (!ArraySize)
2190 return false;
2191
2192 // If the array size expression is a conditional expression whose branches
2193 // are both integer constant expressions, one negative and one positive,
2194 // then it's assumed to be like an old-style static assertion. e.g.,
2195 // int old_style_assert[expr ? 1 : -1];
2196 // We will accept any integer constant expressions instead of assuming the
2197 // values 1 and -1 are always used.
2198 if (const auto *CondExpr = dyn_cast_if_present<ConditionalOperator>(
2199 ArraySize->IgnoreParenImpCasts())) {
2200 std::optional<llvm::APSInt> LHS =
2201 CondExpr->getLHS()->getIntegerConstantExpr(Context);
2202 std::optional<llvm::APSInt> RHS =
2203 CondExpr->getRHS()->getIntegerConstantExpr(Context);
2204 return LHS && RHS && LHS->isNegative() != RHS->isNegative();
2205 }
2206 return false;
2207 };
2208
2209 // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2210 unsigned VLADiag;
2211 bool VLAIsError;
2212 if (getLangOpts().OpenCL) {
2213 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2214 VLADiag = diag::err_opencl_vla;
2215 VLAIsError = true;
2216 } else if (getLangOpts().C99) {
2217 VLADiag = diag::warn_vla_used;
2218 VLAIsError = false;
2219 } else if (isSFINAEContext()) {
2220 VLADiag = diag::err_vla_in_sfinae;
2221 VLAIsError = true;
2222 } else if (getLangOpts().OpenMP && OpenMP().isInOpenMPTaskUntiedContext()) {
2223 VLADiag = diag::err_openmp_vla_in_task_untied;
2224 VLAIsError = true;
2225 } else if (getLangOpts().CPlusPlus) {
2226 if (getLangOpts().CPlusPlus11 && IsStaticAssertLike(ArraySize, Context))
2227 VLADiag = getLangOpts().GNUMode
2228 ? diag::ext_vla_cxx_in_gnu_mode_static_assert
2229 : diag::ext_vla_cxx_static_assert;
2230 else
2231 VLADiag = getLangOpts().GNUMode ? diag::ext_vla_cxx_in_gnu_mode
2232 : diag::ext_vla_cxx;
2233 VLAIsError = false;
2234 } else {
2235 VLADiag = diag::ext_vla;
2236 VLAIsError = false;
2237 }
2238
2239 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2240 if (!ArraySize) {
2241 if (ASM == ArraySizeModifier::Star) {
2242 Diag(Loc, VLADiag);
2243 if (VLAIsError)
2244 return QualType();
2245
2246 T = Context.getVariableArrayType(T, nullptr, ASM, Quals);
2247 } else {
2248 T = Context.getIncompleteArrayType(T, ASM, Quals);
2249 }
2250 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2251 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals);
2252 } else {
2253 ExprResult R =
2254 checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError);
2255 if (R.isInvalid())
2256 return QualType();
2257
2258 if (!R.isUsable()) {
2259 // C99: an array with a non-ICE size is a VLA. We accept any expression
2260 // that we can fold to a non-zero positive value as a non-VLA as an
2261 // extension.
2262 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals);
2263 } else if (!T->isDependentType() && !T->isIncompleteType() &&
2264 !T->isConstantSizeType()) {
2265 // C99: an array with an element type that has a non-constant-size is a
2266 // VLA.
2267 // FIXME: Add a note to explain why this isn't a VLA.
2268 Diag(Loc, VLADiag);
2269 if (VLAIsError)
2270 return QualType();
2271 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals);
2272 } else {
2273 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2274 // have a value greater than zero.
2275 // In C++, this follows from narrowing conversions being disallowed.
2276 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2277 if (Entity)
2278 Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2279 << getPrintableNameForEntity(Entity)
2280 << ArraySize->getSourceRange();
2281 else
2282 Diag(ArraySize->getBeginLoc(),
2283 diag::err_typecheck_negative_array_size)
2284 << ArraySize->getSourceRange();
2285 return QualType();
2286 }
2287 if (ConstVal == 0 && !T.isWebAssemblyReferenceType()) {
2288 if (getLangOpts().OpenCL) {
2289 Diag(ArraySize->getBeginLoc(), diag::err_typecheck_zero_array_size)
2290 << 3 << ArraySize->getSourceRange();
2291 return QualType();
2292 }
2293
2294 // GCC accepts zero sized static arrays. We allow them when
2295 // we're not in a SFINAE context.
2296 Diag(ArraySize->getBeginLoc(),
2297 isSFINAEContext() ? diag::err_typecheck_zero_array_size
2298 : diag::ext_typecheck_zero_array_size)
2299 << 0 << ArraySize->getSourceRange();
2300 if (isSFINAEContext())
2301 return QualType();
2302 }
2303
2304 // Is the array too large?
2305 unsigned ActiveSizeBits =
2306 (!T->isDependentType() && !T->isVariablyModifiedType() &&
2307 !T->isIncompleteType() && !T->isUndeducedType())
2309 : ConstVal.getActiveBits();
2310 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2311 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2312 << toString(ConstVal, 10, ConstVal.isSigned(),
2313 /*formatAsCLiteral=*/false, /*UpperCase=*/false,
2314 /*InsertSeparators=*/true)
2315 << ArraySize->getSourceRange();
2316 return QualType();
2317 }
2318
2319 T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2320 }
2321 }
2322
2323 if (T->isVariableArrayType()) {
2324 if (!Context.getTargetInfo().isVLASupported()) {
2325 // CUDA device code and some other targets don't support VLAs.
2326 bool IsCUDADevice = (getLangOpts().CUDA && getLangOpts().CUDAIsDevice);
2327 targetDiag(Loc,
2328 IsCUDADevice ? diag::err_cuda_vla : diag::err_vla_unsupported)
2329 << (IsCUDADevice ? llvm::to_underlying(CUDA().CurrentTarget()) : 0);
2330 } else if (sema::FunctionScopeInfo *FSI = getCurFunction()) {
2331 // VLAs are supported on this target, but we may need to do delayed
2332 // checking that the VLA is not being used within a coroutine.
2333 FSI->setHasVLA(Loc);
2334 }
2335 }
2336
2337 // If this is not C99, diagnose array size modifiers on non-VLAs.
2338 if (!getLangOpts().C99 && !T->isVariableArrayType() &&
2339 (ASM != ArraySizeModifier::Normal || Quals != 0)) {
2340 Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx
2341 : diag::ext_c99_array_usage)
2342 << ASM;
2343 }
2344
2345 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2346 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2347 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2348 if (getLangOpts().OpenCL) {
2349 const QualType ArrType = Context.getBaseElementType(T);
2350 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2351 ArrType->isSamplerT() || ArrType->isImageType()) {
2352 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2353 return QualType();
2354 }
2355 }
2356
2357 return T;
2358}
2359
2361 const BitIntType *BIT,
2362 bool ForMatrixType = false) {
2363 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2364 unsigned NumBits = BIT->getNumBits();
2365 if (!llvm::isPowerOf2_32(NumBits))
2366 return S.Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2367 << ForMatrixType;
2368 return false;
2369}
2370
2372 SourceLocation AttrLoc) {
2373 // The base type must be integer (not Boolean or enumeration) or float, and
2374 // can't already be a vector.
2375 if ((!CurType->isDependentType() &&
2376 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2377 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) &&
2378 !CurType->isBitIntType()) ||
2379 CurType->isArrayType()) {
2380 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2381 return QualType();
2382 }
2383
2384 if (const auto *BIT = CurType->getAs<BitIntType>();
2385 BIT && CheckBitIntElementType(*this, AttrLoc, BIT))
2386 return QualType();
2387
2388 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2389 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2391
2392 std::optional<llvm::APSInt> VecSize =
2394 if (!VecSize) {
2395 Diag(AttrLoc, diag::err_attribute_argument_type)
2396 << "vector_size" << AANT_ArgumentIntegerConstant
2397 << SizeExpr->getSourceRange();
2398 return QualType();
2399 }
2400
2401 if (VecSize->isNegative()) {
2402 Diag(SizeExpr->getExprLoc(), diag::err_attribute_vec_negative_size);
2403 return QualType();
2404 }
2405
2406 if (CurType->isDependentType())
2407 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2409
2410 // vecSize is specified in bytes - convert to bits.
2411 if (!VecSize->isIntN(61)) {
2412 // Bit size will overflow uint64.
2413 Diag(AttrLoc, diag::err_attribute_size_too_large)
2414 << SizeExpr->getSourceRange() << "vector";
2415 return QualType();
2416 }
2417 uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2418 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2419
2420 if (VectorSizeBits == 0) {
2421 Diag(AttrLoc, diag::err_attribute_zero_size)
2422 << SizeExpr->getSourceRange() << "vector";
2423 return QualType();
2424 }
2425
2426 if (!TypeSize || VectorSizeBits % TypeSize) {
2427 Diag(AttrLoc, diag::err_attribute_invalid_size)
2428 << SizeExpr->getSourceRange();
2429 return QualType();
2430 }
2431
2432 if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2433 Diag(AttrLoc, diag::err_attribute_size_too_large)
2434 << SizeExpr->getSourceRange() << "vector";
2435 return QualType();
2436 }
2437
2438 return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2440}
2441
2443 SourceLocation AttrLoc) {
2444 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2445 // in conjunction with complex types (pointers, arrays, functions, etc.).
2446 //
2447 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2448 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2449 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2450 // of bool aren't allowed.
2451 //
2452 // We explicitly allow bool elements in ext_vector_type for C/C++.
2453 bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus;
2454 if ((!T->isDependentType() && !T->isIntegerType() &&
2455 !T->isRealFloatingType()) ||
2456 (IsNoBoolVecLang && T->isBooleanType())) {
2457 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2458 return QualType();
2459 }
2460
2461 if (const auto *BIT = T->getAs<BitIntType>();
2462 BIT && CheckBitIntElementType(*this, AttrLoc, BIT))
2463 return QualType();
2464
2465 if (!SizeExpr->isTypeDependent() && !SizeExpr->isValueDependent()) {
2466 std::optional<llvm::APSInt> VecSize =
2468 if (!VecSize) {
2469 Diag(AttrLoc, diag::err_attribute_argument_type)
2470 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2471 << SizeExpr->getSourceRange();
2472 return QualType();
2473 }
2474
2475 if (VecSize->isNegative()) {
2476 Diag(SizeExpr->getExprLoc(), diag::err_attribute_vec_negative_size);
2477 return QualType();
2478 }
2479
2480 if (!VecSize->isIntN(32)) {
2481 Diag(AttrLoc, diag::err_attribute_size_too_large)
2482 << SizeExpr->getSourceRange() << "vector";
2483 return QualType();
2484 }
2485 // Unlike gcc's vector_size attribute, the size is specified as the
2486 // number of elements, not the number of bytes.
2487 unsigned VectorSize = static_cast<unsigned>(VecSize->getZExtValue());
2488
2489 if (VectorSize == 0) {
2490 Diag(AttrLoc, diag::err_attribute_zero_size)
2491 << SizeExpr->getSourceRange() << "vector";
2492 return QualType();
2493 }
2494
2495 return Context.getExtVectorType(T, VectorSize);
2496 }
2497
2498 return Context.getDependentSizedExtVectorType(T, SizeExpr, AttrLoc);
2499}
2500
2501QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2502 SourceLocation AttrLoc) {
2503 assert(Context.getLangOpts().MatrixTypes &&
2504 "Should never build a matrix type when it is disabled");
2505
2506 // Check element type, if it is not dependent.
2507 if (!ElementTy->isDependentType() &&
2509 Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2510 return QualType();
2511 }
2512
2513 if (const auto *BIT = ElementTy->getAs<BitIntType>();
2514 BIT &&
2515 CheckBitIntElementType(*this, AttrLoc, BIT, /*ForMatrixType=*/true))
2516 return QualType();
2517
2518 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2519 NumRows->isValueDependent() || NumCols->isValueDependent())
2520 return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2521 AttrLoc);
2522
2523 std::optional<llvm::APSInt> ValueRows =
2525 std::optional<llvm::APSInt> ValueColumns =
2527
2528 auto const RowRange = NumRows->getSourceRange();
2529 auto const ColRange = NumCols->getSourceRange();
2530
2531 // Both are row and column expressions are invalid.
2532 if (!ValueRows && !ValueColumns) {
2533 Diag(AttrLoc, diag::err_attribute_argument_type)
2534 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2535 << ColRange;
2536 return QualType();
2537 }
2538
2539 // Only the row expression is invalid.
2540 if (!ValueRows) {
2541 Diag(AttrLoc, diag::err_attribute_argument_type)
2542 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2543 return QualType();
2544 }
2545
2546 // Only the column expression is invalid.
2547 if (!ValueColumns) {
2548 Diag(AttrLoc, diag::err_attribute_argument_type)
2549 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2550 return QualType();
2551 }
2552
2553 // Check the matrix dimensions.
2554 unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2555 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2556 if (MatrixRows == 0 && MatrixColumns == 0) {
2557 Diag(AttrLoc, diag::err_attribute_zero_size)
2558 << "matrix" << RowRange << ColRange;
2559 return QualType();
2560 }
2561 if (MatrixRows == 0) {
2562 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2563 return QualType();
2564 }
2565 if (MatrixColumns == 0) {
2566 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2567 return QualType();
2568 }
2569 if (MatrixRows > Context.getLangOpts().MaxMatrixDimension &&
2570 MatrixColumns > Context.getLangOpts().MaxMatrixDimension) {
2571 Diag(AttrLoc, diag::err_attribute_size_too_large)
2572 << RowRange << ColRange << "matrix row and column";
2573 return QualType();
2574 }
2575 if (MatrixRows > Context.getLangOpts().MaxMatrixDimension) {
2576 Diag(AttrLoc, diag::err_attribute_size_too_large)
2577 << RowRange << "matrix row";
2578 return QualType();
2579 }
2580 if (MatrixColumns > Context.getLangOpts().MaxMatrixDimension) {
2581 Diag(AttrLoc, diag::err_attribute_size_too_large)
2582 << ColRange << "matrix column";
2583 return QualType();
2584 }
2585 return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2586}
2587
2589 if ((T->isArrayType() && !getLangOpts().allowArrayReturnTypes()) ||
2590 T->isFunctionType()) {
2591 Diag(Loc, diag::err_func_returning_array_function)
2592 << T->isFunctionType() << T;
2593 return true;
2594 }
2595
2596 // Functions cannot return half FP.
2597 if (T->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2598 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2599 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2601 return true;
2602 }
2603
2604 // Methods cannot return interface types. All ObjC objects are
2605 // passed by reference.
2606 if (T->isObjCObjectType()) {
2607 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2608 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2609 return true;
2610 }
2611
2612 // __ptrauth is illegal on a function return type.
2613 if (T.getPointerAuth()) {
2614 Diag(Loc, diag::err_ptrauth_qualifier_invalid) << T << 0;
2615 return true;
2616 }
2617
2618 if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2619 T.hasNonTrivialToPrimitiveCopyCUnion())
2622
2623 // C++2a [dcl.fct]p12:
2624 // A volatile-qualified return type is deprecated
2625 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2626 Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2627
2628 if (T.getAddressSpace() != LangAS::Default && getLangOpts().HLSL)
2629 return true;
2630 return false;
2631}
2632
2633/// Check the extended parameter information. Most of the necessary
2634/// checking should occur when applying the parameter attribute; the
2635/// only other checks required are positional restrictions.
2638 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2639 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2640
2641 bool emittedError = false;
2642 auto actualCC = EPI.ExtInfo.getCC();
2643 enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
2644 auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
2645 bool isCompatible =
2646 (required == RequiredCC::OnlySwift)
2647 ? (actualCC == CC_Swift)
2648 : (actualCC == CC_Swift || actualCC == CC_SwiftAsync);
2649 if (isCompatible || emittedError)
2650 return;
2651 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2653 << (required == RequiredCC::OnlySwift);
2654 emittedError = true;
2655 };
2656 for (size_t paramIndex = 0, numParams = paramTypes.size();
2657 paramIndex != numParams; ++paramIndex) {
2658 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2659 // Nothing interesting to check for orindary-ABI parameters.
2663 continue;
2664
2665 // swift_indirect_result parameters must be a prefix of the function
2666 // arguments.
2668 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2669 if (paramIndex != 0 &&
2670 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2672 S.Diag(getParamLoc(paramIndex),
2673 diag::err_swift_indirect_result_not_first);
2674 }
2675 continue;
2676
2678 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2679 continue;
2680
2681 // SwiftAsyncContext is not limited to swiftasynccall functions.
2683 continue;
2684
2685 // swift_error parameters must be preceded by a swift_context parameter.
2687 checkCompatible(paramIndex, RequiredCC::OnlySwift);
2688 if (paramIndex == 0 ||
2689 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2691 S.Diag(getParamLoc(paramIndex),
2692 diag::err_swift_error_result_not_after_swift_context);
2693 }
2694 continue;
2695 }
2696 llvm_unreachable("bad ABI kind");
2697 }
2698}
2699
2701 MutableArrayRef<QualType> ParamTypes,
2702 SourceLocation Loc, DeclarationName Entity,
2704 bool Invalid = false;
2705
2707
2708 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2709 // FIXME: Loc is too inprecise here, should use proper locations for args.
2710 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2711 if (ParamType->isVoidType()) {
2712 Diag(Loc, diag::err_param_with_void_type);
2713 Invalid = true;
2714 } else if (ParamType->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2715 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2716 // Disallow half FP arguments.
2717 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2719 Invalid = true;
2720 } else if (ParamType->isWebAssemblyTableType()) {
2721 Diag(Loc, diag::err_wasm_table_as_function_parameter);
2722 Invalid = true;
2723 } else if (ParamType.getPointerAuth()) {
2724 // __ptrauth is illegal on a function return type.
2725 Diag(Loc, diag::err_ptrauth_qualifier_invalid) << T << 1;
2726 Invalid = true;
2727 }
2728
2729 // C++2a [dcl.fct]p4:
2730 // A parameter with volatile-qualified type is deprecated
2731 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
2732 Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
2733
2734 ParamTypes[Idx] = ParamType;
2735 }
2736
2737 if (EPI.ExtParameterInfos) {
2738 checkExtParameterInfos(*this, ParamTypes, EPI,
2739 [=](unsigned i) { return Loc; });
2740 }
2741
2742 if (EPI.ExtInfo.getProducesResult()) {
2743 // This is just a warning, so we can't fail to build if we see it.
2745 }
2746
2747 if (Invalid)
2748 return QualType();
2749
2750 return Context.getFunctionType(T, ParamTypes, EPI);
2751}
2752
2754 CXXRecordDecl *Cls, SourceLocation Loc,
2755 DeclarationName Entity) {
2756 if (!Cls && !isDependentScopeSpecifier(SS)) {
2757 Cls = dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS));
2758 if (!Cls) {
2759 auto D =
2760 Diag(SS.getBeginLoc(), diag::err_illegal_decl_mempointer_in_nonclass)
2761 << SS.getRange();
2762 if (const IdentifierInfo *II = Entity.getAsIdentifierInfo())
2763 D << II;
2764 else
2765 D << "member pointer";
2766 return QualType();
2767 }
2768 }
2769
2770 // Verify that we're not building a pointer to pointer to function with
2771 // exception specification.
2773 Diag(Loc, diag::err_distant_exception_spec);
2774 return QualType();
2775 }
2776
2777 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2778 // with reference type, or "cv void."
2779 if (T->isReferenceType()) {
2780 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2781 << getPrintableNameForEntity(Entity) << T;
2782 return QualType();
2783 }
2784
2785 if (T->isVoidType()) {
2786 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2787 << getPrintableNameForEntity(Entity);
2788 return QualType();
2789 }
2790
2791 if (T->isFunctionType() && getLangOpts().OpenCL &&
2792 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2793 getLangOpts())) {
2794 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2795 return QualType();
2796 }
2797
2798 if (getLangOpts().HLSL && Loc.isValid()) {
2799 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
2800 return QualType();
2801 }
2802
2803 // Adjust the default free function calling convention to the default method
2804 // calling convention.
2805 bool IsCtorOrDtor =
2808 if (T->isFunctionType())
2809 adjustMemberFunctionCC(T, /*HasThisPointer=*/true, IsCtorOrDtor, Loc);
2810
2811 return Context.getMemberPointerType(T, SS.getScopeRep(), Cls);
2812}
2813
2815 SourceLocation Loc,
2816 DeclarationName Entity) {
2817 if (!T->isFunctionType()) {
2818 Diag(Loc, diag::err_nonfunction_block_type);
2819 return QualType();
2820 }
2821
2822 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2823 return QualType();
2824
2825 if (getLangOpts().OpenCL)
2827
2828 return Context.getBlockPointerType(T);
2829}
2830
2832 QualType QT = Ty.get();
2833 if (QT.isNull()) {
2834 if (TInfo) *TInfo = nullptr;
2835 return QualType();
2836 }
2837
2838 TypeSourceInfo *TSI = nullptr;
2839 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2840 QT = LIT->getType();
2841 TSI = LIT->getTypeSourceInfo();
2842 }
2843
2844 if (TInfo)
2845 *TInfo = TSI;
2846 return QT;
2847}
2848
2849static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2850 Qualifiers::ObjCLifetime ownership,
2851 unsigned chunkIndex);
2852
2853/// Given that this is the declaration of a parameter under ARC,
2854/// attempt to infer attributes and such for pointer-to-whatever
2855/// types.
2856static void inferARCWriteback(TypeProcessingState &state,
2857 QualType &declSpecType) {
2858 Sema &S = state.getSema();
2859 Declarator &declarator = state.getDeclarator();
2860
2861 // TODO: should we care about decl qualifiers?
2862
2863 // Check whether the declarator has the expected form. We walk
2864 // from the inside out in order to make the block logic work.
2865 unsigned outermostPointerIndex = 0;
2866 bool isBlockPointer = false;
2867 unsigned numPointers = 0;
2868 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2869 unsigned chunkIndex = i;
2870 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2871 switch (chunk.Kind) {
2873 // Ignore parens.
2874 break;
2875
2878 // Count the number of pointers. Treat references
2879 // interchangeably as pointers; if they're mis-ordered, normal
2880 // type building will discover that.
2881 outermostPointerIndex = chunkIndex;
2882 numPointers++;
2883 break;
2884
2886 // If we have a pointer to block pointer, that's an acceptable
2887 // indirect reference; anything else is not an application of
2888 // the rules.
2889 if (numPointers != 1) return;
2890 numPointers++;
2891 outermostPointerIndex = chunkIndex;
2892 isBlockPointer = true;
2893
2894 // We don't care about pointer structure in return values here.
2895 goto done;
2896
2897 case DeclaratorChunk::Array: // suppress if written (id[])?
2901 return;
2902 }
2903 }
2904 done:
2905
2906 // If we have *one* pointer, then we want to throw the qualifier on
2907 // the declaration-specifiers, which means that it needs to be a
2908 // retainable object type.
2909 if (numPointers == 1) {
2910 // If it's not a retainable object type, the rule doesn't apply.
2911 if (!declSpecType->isObjCRetainableType()) return;
2912
2913 // If it already has lifetime, don't do anything.
2914 if (declSpecType.getObjCLifetime()) return;
2915
2916 // Otherwise, modify the type in-place.
2917 Qualifiers qs;
2918
2919 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2921 else
2923 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2924
2925 // If we have *two* pointers, then we want to throw the qualifier on
2926 // the outermost pointer.
2927 } else if (numPointers == 2) {
2928 // If we don't have a block pointer, we need to check whether the
2929 // declaration-specifiers gave us something that will turn into a
2930 // retainable object pointer after we slap the first pointer on it.
2931 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2932 return;
2933
2934 // Look for an explicit lifetime attribute there.
2935 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2936 if (chunk.Kind != DeclaratorChunk::Pointer &&
2938 return;
2939 for (const ParsedAttr &AL : chunk.getAttrs())
2940 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
2941 return;
2942
2944 outermostPointerIndex);
2945
2946 // Any other number of pointers/references does not trigger the rule.
2947 } else return;
2948
2949 // TODO: mark whether we did this inference?
2950}
2951
2952void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2953 SourceLocation FallbackLoc,
2954 SourceLocation ConstQualLoc,
2955 SourceLocation VolatileQualLoc,
2956 SourceLocation RestrictQualLoc,
2957 SourceLocation AtomicQualLoc,
2958 SourceLocation UnalignedQualLoc) {
2959 if (!Quals)
2960 return;
2961
2962 struct Qual {
2963 const char *Name;
2964 unsigned Mask;
2965 SourceLocation Loc;
2966 } const QualKinds[5] = {
2967 { "const", DeclSpec::TQ_const, ConstQualLoc },
2968 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2969 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2970 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2971 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2972 };
2973
2974 SmallString<32> QualStr;
2975 unsigned NumQuals = 0;
2976 SourceLocation Loc;
2977 FixItHint FixIts[5];
2978
2979 // Build a string naming the redundant qualifiers.
2980 for (auto &E : QualKinds) {
2981 if (Quals & E.Mask) {
2982 if (!QualStr.empty()) QualStr += ' ';
2983 QualStr += E.Name;
2984
2985 // If we have a location for the qualifier, offer a fixit.
2986 SourceLocation QualLoc = E.Loc;
2987 if (QualLoc.isValid()) {
2988 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2989 if (Loc.isInvalid() ||
2990 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2991 Loc = QualLoc;
2992 }
2993
2994 ++NumQuals;
2995 }
2996 }
2997
2998 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2999 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
3000}
3001
3002// Diagnose pointless type qualifiers on the return type of a function.
3004 Declarator &D,
3005 unsigned FunctionChunkIndex) {
3007 D.getTypeObject(FunctionChunkIndex).Fun;
3008 if (FTI.hasTrailingReturnType()) {
3009 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3010 RetTy.getLocalCVRQualifiers(),
3012 return;
3013 }
3014
3015 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3016 End = D.getNumTypeObjects();
3017 OuterChunkIndex != End; ++OuterChunkIndex) {
3018 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
3019 switch (OuterChunk.Kind) {
3021 continue;
3022
3024 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3026 diag::warn_qual_return_type,
3027 PTI.TypeQuals,
3029 PTI.ConstQualLoc,
3030 PTI.VolatileQualLoc,
3031 PTI.RestrictQualLoc,
3032 PTI.AtomicQualLoc,
3033 PTI.UnalignedQualLoc);
3034 return;
3035 }
3036
3043 // FIXME: We can't currently provide an accurate source location and a
3044 // fix-it hint for these.
3045 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
3046 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3047 RetTy.getCVRQualifiers() | AtomicQual,
3048 D.getIdentifierLoc());
3049 return;
3050 }
3051
3052 llvm_unreachable("unknown declarator chunk kind");
3053 }
3054
3055 // If the qualifiers come from a conversion function type, don't diagnose
3056 // them -- they're not necessarily redundant, since such a conversion
3057 // operator can be explicitly called as "x.operator const int()".
3059 return;
3060
3061 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3062 // which are present there.
3063 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3065 D.getIdentifierLoc(),
3071}
3072
3073static std::pair<QualType, TypeSourceInfo *>
3074InventTemplateParameter(TypeProcessingState &state, QualType T,
3075 TypeSourceInfo *TrailingTSI, AutoType *Auto,
3077 Sema &S = state.getSema();
3078 Declarator &D = state.getDeclarator();
3079
3080 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3081 const unsigned AutoParameterPosition = Info.TemplateParams.size();
3082 const bool IsParameterPack = D.hasEllipsis();
3083
3084 // If auto is mentioned in a lambda parameter or abbreviated function
3085 // template context, convert it to a template parameter type.
3086
3087 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3088 // template parameter type. Template parameters are temporarily added
3089 // to the TU until the associated TemplateDecl is created.
3090 TemplateTypeParmDecl *InventedTemplateParam = TemplateTypeParmDecl::Create(
3092 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3093 /*NameLoc=*/D.getIdentifierLoc(), TemplateParameterDepth,
3094 AutoParameterPosition,
3096 AutoParameterPosition),
3097 false, IsParameterPack,
3098 /*HasTypeConstraint=*/Auto->isConstrained());
3099 InventedTemplateParam->setImplicit();
3100 Info.TemplateParams.push_back(InventedTemplateParam);
3101
3102 // Attach type constraints to the new parameter.
3103 if (Auto->isConstrained()) {
3104 if (TrailingTSI) {
3105 // The 'auto' appears in a trailing return type we've already built;
3106 // extract its type constraints to attach to the template parameter.
3107 AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3108 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3109 bool Invalid = false;
3110 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3111 if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3114 Invalid = true;
3115 TAL.addArgument(AutoLoc.getArgLoc(Idx));
3116 }
3117
3118 if (!Invalid) {
3120 AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3121 AutoLoc.getNamedConcept(),
3122 /*FoundDecl=*/AutoLoc.getFoundDecl(),
3123 AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3124 InventedTemplateParam, D.getEllipsisLoc());
3125 }
3126 } else {
3127 // The 'auto' appears in the decl-specifiers; we've not finished forming
3128 // TypeSourceInfo for it yet.
3130 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
3131 TemplateId->RAngleLoc);
3132 bool Invalid = false;
3133 if (TemplateId->LAngleLoc.isValid()) {
3134 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3135 TemplateId->NumArgs);
3136 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3137
3138 if (D.getEllipsisLoc().isInvalid()) {
3139 for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3142 Invalid = true;
3143 break;
3144 }
3145 }
3146 }
3147 }
3148 if (!Invalid) {
3149 TemplateName TN = TemplateId->Template.get();
3155 TemplateId->TemplateNameLoc),
3156 TN,
3157 /*FoundDecl=*/
3158 USD ? cast<NamedDecl>(USD) : cast_if_present<NamedDecl>(CD),
3159 TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3160 InventedTemplateParam, D.getEllipsisLoc());
3161 }
3162 }
3163 }
3164
3165 // Replace the 'auto' in the function parameter with this invented
3166 // template type parameter.
3167 // FIXME: Retain some type sugar to indicate that this was written
3168 // as 'auto'?
3169 QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3170 QualType NewT = state.ReplaceAutoType(T, Replacement);
3171 TypeSourceInfo *NewTSI =
3172 TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)
3173 : nullptr;
3174 return {NewT, NewTSI};
3175}
3176
3177static TypeSourceInfo *
3178GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3179 QualType T, TypeSourceInfo *ReturnTypeInfo);
3180
3181static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3182 TypeSourceInfo *&ReturnTypeInfo) {
3183 Sema &SemaRef = state.getSema();
3184 Declarator &D = state.getDeclarator();
3185 QualType T;
3186 ReturnTypeInfo = nullptr;
3187
3188 // The TagDecl owned by the DeclSpec.
3189 TagDecl *OwnedTagDecl = nullptr;
3190
3191 switch (D.getName().getKind()) {
3197 T = ConvertDeclSpecToType(state);
3198
3199 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3200 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3201 // Owned declaration is embedded in declarator.
3202 OwnedTagDecl->setEmbeddedInDeclarator(true);
3203 }
3204 break;
3205
3209 // Constructors and destructors don't have return types. Use
3210 // "void" instead.
3211 T = SemaRef.Context.VoidTy;
3214 break;
3215
3217 // Deduction guides have a trailing return type and no type in their
3218 // decl-specifier sequence. Use a placeholder return type for now.
3219 T = SemaRef.Context.DependentTy;
3220 break;
3221
3223 // The result type of a conversion function is the type that it
3224 // converts to.
3226 &ReturnTypeInfo);
3227 break;
3228 }
3229
3230 // Note: We don't need to distribute declaration attributes (i.e.
3231 // D.getDeclarationAttributes()) because those are always C++11 attributes,
3232 // and those don't get distributed.
3234 state, T, SemaRef.CUDA().IdentifyTarget(D.getAttributes()));
3235
3236 // Find the deduced type in this type. Look in the trailing return type if we
3237 // have one, otherwise in the DeclSpec type.
3238 // FIXME: The standard wording doesn't currently describe this.
3239 DeducedType *Deduced = T->getContainedDeducedType();
3240 bool DeducedIsTrailingReturnType = false;
3243 Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3244 DeducedIsTrailingReturnType = true;
3245 }
3246
3247 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3248 if (Deduced) {
3249 AutoType *Auto = dyn_cast<AutoType>(Deduced);
3250 int Error = -1;
3251
3252 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3253 // class template argument deduction)?
3254 bool IsCXXAutoType =
3255 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3256 bool IsDeducedReturnType = false;
3257
3258 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3260 AutoRange = D.getName().getSourceRange();
3261
3262 switch (D.getContext()) {
3264 // Declared return type of a lambda-declarator is implicit and is always
3265 // 'auto'.
3266 break;
3269 Error = 0;
3270 break;
3272 Error = 22;
3273 break;
3276 InventedTemplateParameterInfo *Info = nullptr;
3278 // With concepts we allow 'auto' in function parameters.
3279 if (!SemaRef.getLangOpts().CPlusPlus || !Auto ||
3280 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3281 Error = 0;
3282 break;
3283 }
3284
3285 if (!SemaRef.getLangOpts().CPlusPlus20)
3286 SemaRef.DiagCompat(AutoRange.getBegin(), diag_compat::auto_param);
3287
3288 if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3289 Error = 21;
3290 break;
3291 }
3292
3293 Info = &SemaRef.InventedParameterInfos.back();
3294 } else {
3295 // In C++14, generic lambdas allow 'auto' in their parameters.
3296 if (!SemaRef.getLangOpts().CPlusPlus14 && Auto &&
3297 Auto->getKeyword() == AutoTypeKeyword::Auto) {
3298 Error = 25; // auto not allowed in lambda parameter (before C++14)
3299 break;
3300 } else if (!Auto || Auto->getKeyword() != AutoTypeKeyword::Auto) {
3301 Error = 16; // __auto_type or decltype(auto) not allowed in lambda
3302 // parameter
3303 break;
3304 }
3305 Info = SemaRef.getCurLambda();
3306 assert(Info && "No LambdaScopeInfo on the stack!");
3307 }
3308
3309 // We'll deal with inventing template parameters for 'auto' in trailing
3310 // return types when we pick up the trailing return type when processing
3311 // the function chunk.
3312 if (!DeducedIsTrailingReturnType)
3313 T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3314 break;
3315 }
3317 if (D.isStaticMember() || D.isFunctionDeclarator())
3318 break;
3319 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3320 if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3321 Error = 6; // Interface member.
3322 } else {
3323 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3324 case TagTypeKind::Enum:
3325 llvm_unreachable("unhandled tag kind");
3327 Error = Cxx ? 1 : 2; /* Struct member */
3328 break;
3329 case TagTypeKind::Union:
3330 Error = Cxx ? 3 : 4; /* Union member */
3331 break;
3332 case TagTypeKind::Class:
3333 Error = 5; /* Class member */
3334 break;
3336 Error = 6; /* Interface member */
3337 break;
3338 }
3339 }
3341 Error = 20; // Friend type
3342 break;
3343 }
3346 Error = 7; // Exception declaration
3347 break;
3350 !SemaRef.getLangOpts().CPlusPlus20)
3351 Error = 19; // Template parameter (until C++20)
3352 else if (!SemaRef.getLangOpts().CPlusPlus17)
3353 Error = 8; // Template parameter (until C++17)
3354 break;
3356 Error = 9; // Block literal
3357 break;
3359 // Within a template argument list, a deduced template specialization
3360 // type will be reinterpreted as a template template argument.
3362 !D.getNumTypeObjects() &&
3364 break;
3365 [[fallthrough]];
3367 Error = 10; // Template type argument
3368 break;
3371 Error = 12; // Type alias
3372 break;
3375 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3376 Error = 13; // Function return type
3377 IsDeducedReturnType = true;
3378 break;
3380 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3381 Error = 14; // conversion-type-id
3382 IsDeducedReturnType = true;
3383 break;
3386 break;
3387 if (IsCXXAutoType && !Auto->isDecltypeAuto())
3388 break; // auto(x)
3389 [[fallthrough]];
3392 Error = 15; // Generic
3393 break;
3399 // FIXME: P0091R3 (erroneously) does not permit class template argument
3400 // deduction in conditions, for-init-statements, and other declarations
3401 // that are not simple-declarations.
3402 break;
3404 // FIXME: P0091R3 does not permit class template argument deduction here,
3405 // but we follow GCC and allow it anyway.
3406 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3407 Error = 17; // 'new' type
3408 break;
3410 Error = 18; // K&R function parameter
3411 break;
3412 }
3413
3415 Error = 11;
3416
3417 // In Objective-C it is an error to use 'auto' on a function declarator
3418 // (and everywhere for '__auto_type').
3419 if (D.isFunctionDeclarator() &&
3420 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3421 Error = 13;
3422
3423 if (Error != -1) {
3424 unsigned Kind;
3425 if (Auto) {
3426 switch (Auto->getKeyword()) {
3427 case AutoTypeKeyword::Auto: Kind = 0; break;
3428 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3429 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3430 }
3431 } else {
3433 "unknown auto type");
3434 Kind = 3;
3435 }
3436
3437 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3438 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3439
3440 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3441 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3442 << QualType(Deduced, 0) << AutoRange;
3443 if (auto *TD = TN.getAsTemplateDecl())
3444 SemaRef.NoteTemplateLocation(*TD);
3445
3446 T = SemaRef.Context.IntTy;
3447 D.setInvalidType(true);
3448 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) {
3449 // If there was a trailing return type, we already got
3450 // warn_cxx98_compat_trailing_return_type in the parser.
3451 // If there was a decltype(auto), we already got
3452 // warn_cxx11_compat_decltype_auto_type_specifier.
3453 unsigned DiagId = 0;
3455 DiagId = diag::warn_cxx11_compat_generic_lambda;
3456 else if (IsDeducedReturnType)
3457 DiagId = diag::warn_cxx11_compat_deduced_return_type;
3458 else if (Auto->getKeyword() == AutoTypeKeyword::Auto)
3459 DiagId = diag::warn_cxx98_compat_auto_type_specifier;
3460
3461 if (DiagId)
3462 SemaRef.Diag(AutoRange.getBegin(), DiagId) << AutoRange;
3463 }
3464 }
3465
3466 if (SemaRef.getLangOpts().CPlusPlus &&
3467 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3468 // Check the contexts where C++ forbids the declaration of a new class
3469 // or enumeration in a type-specifier-seq.
3470 unsigned DiagID = 0;
3471 switch (D.getContext()) {
3474 // Class and enumeration definitions are syntactically not allowed in
3475 // trailing return types.
3476 llvm_unreachable("parser should not have allowed this");
3477 break;
3485 // C++11 [dcl.type]p3:
3486 // A type-specifier-seq shall not define a class or enumeration unless
3487 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3488 // the declaration of a template-declaration.
3490 break;
3492 DiagID = diag::err_type_defined_in_alias_template;
3493 break;
3504 DiagID = diag::err_type_defined_in_type_specifier;
3505 break;
3512 // C++ [dcl.fct]p6:
3513 // Types shall not be defined in return or parameter types.
3514 DiagID = diag::err_type_defined_in_param_type;
3515 break;
3517 // C++ 6.4p2:
3518 // The type-specifier-seq shall not contain typedef and shall not declare
3519 // a new class or enumeration.
3520 DiagID = diag::err_type_defined_in_condition;
3521 break;
3522 }
3523
3524 if (DiagID != 0) {
3525 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3526 << SemaRef.Context.getCanonicalTagType(OwnedTagDecl);
3527 D.setInvalidType(true);
3528 }
3529 }
3530
3531 assert(!T.isNull() && "This function should not return a null type");
3532 return T;
3533}
3534
3535/// Produce an appropriate diagnostic for an ambiguity between a function
3536/// declarator and a C++ direct-initializer.
3538 DeclaratorChunk &DeclType, QualType RT) {
3539 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3540 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3541
3542 // If the return type is void there is no ambiguity.
3543 if (RT->isVoidType())
3544 return;
3545
3546 // An initializer for a non-class type can have at most one argument.
3547 if (!RT->isRecordType() && FTI.NumParams > 1)
3548 return;
3549
3550 // An initializer for a reference must have exactly one argument.
3551 if (RT->isReferenceType() && FTI.NumParams != 1)
3552 return;
3553
3554 // Only warn if this declarator is declaring a function at block scope, and
3555 // doesn't have a storage class (such as 'extern') specified.
3556 if (!D.isFunctionDeclarator() ||
3560 return;
3561
3562 // Inside a condition, a direct initializer is not permitted. We allow one to
3563 // be parsed in order to give better diagnostics in condition parsing.
3565 return;
3566
3567 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3568
3569 S.Diag(DeclType.Loc,
3570 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3571 : diag::warn_empty_parens_are_function_decl)
3572 << ParenRange;
3573
3574 // If the declaration looks like:
3575 // T var1,
3576 // f();
3577 // and name lookup finds a function named 'f', then the ',' was
3578 // probably intended to be a ';'.
3579 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3580 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3582 if (Comma.getFileID() != Name.getFileID() ||
3583 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3586 if (S.LookupName(Result, S.getCurScope()))
3587 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3589 << D.getIdentifier();
3590 Result.suppressDiagnostics();
3591 }
3592 }
3593
3594 if (FTI.NumParams > 0) {
3595 // For a declaration with parameters, eg. "T var(T());", suggest adding
3596 // parens around the first parameter to turn the declaration into a
3597 // variable declaration.
3598 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3599 SourceLocation B = Range.getBegin();
3600 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3601 // FIXME: Maybe we should suggest adding braces instead of parens
3602 // in C++11 for classes that don't have an initializer_list constructor.
3603 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3605 << FixItHint::CreateInsertion(E, ")");
3606 } else {
3607 // For a declaration without parameters, eg. "T var();", suggest replacing
3608 // the parens with an initializer to turn the declaration into a variable
3609 // declaration.
3610 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3611
3612 // Empty parens mean value-initialization, and no parens mean
3613 // default initialization. These are equivalent if the default
3614 // constructor is user-provided or if zero-initialization is a
3615 // no-op.
3616 if (RD && RD->hasDefinition() &&
3618 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3619 << FixItHint::CreateRemoval(ParenRange);
3620 else {
3621 std::string Init =
3622 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3623 if (Init.empty() && S.LangOpts.CPlusPlus11)
3624 Init = "{}";
3625 if (!Init.empty())
3626 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3627 << FixItHint::CreateReplacement(ParenRange, Init);
3628 }
3629 }
3630}
3631
3632/// Produce an appropriate diagnostic for a declarator with top-level
3633/// parentheses.
3636 assert(Paren.Kind == DeclaratorChunk::Paren &&
3637 "do not have redundant top-level parentheses");
3638
3639 // This is a syntactic check; we're not interested in cases that arise
3640 // during template instantiation.
3642 return;
3643
3644 // Check whether this could be intended to be a construction of a temporary
3645 // object in C++ via a function-style cast.
3646 bool CouldBeTemporaryObject =
3647 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3648 !D.isInvalidType() && D.getIdentifier() &&
3650 (T->isRecordType() || T->isDependentType()) &&
3652
3653 bool StartsWithDeclaratorId = true;
3654 for (auto &C : D.type_objects()) {
3655 switch (C.Kind) {
3657 if (&C == &Paren)
3658 continue;
3659 [[fallthrough]];
3661 StartsWithDeclaratorId = false;
3662 continue;
3663
3665 if (!C.Arr.NumElts)
3666 CouldBeTemporaryObject = false;
3667 continue;
3668
3670 // FIXME: Suppress the warning here if there is no initializer; we're
3671 // going to give an error anyway.
3672 // We assume that something like 'T (&x) = y;' is highly likely to not
3673 // be intended to be a temporary object.
3674 CouldBeTemporaryObject = false;
3675 StartsWithDeclaratorId = false;
3676 continue;
3677
3679 // In a new-type-id, function chunks require parentheses.
3681 return;
3682 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3683 // redundant-parens warning, but we don't know whether the function
3684 // chunk was syntactically valid as an expression here.
3685 CouldBeTemporaryObject = false;
3686 continue;
3687
3691 // These cannot appear in expressions.
3692 CouldBeTemporaryObject = false;
3693 StartsWithDeclaratorId = false;
3694 continue;
3695 }
3696 }
3697
3698 // FIXME: If there is an initializer, assume that this is not intended to be
3699 // a construction of a temporary object.
3700
3701 // Check whether the name has already been declared; if not, this is not a
3702 // function-style cast.
3703 if (CouldBeTemporaryObject) {
3706 if (!S.LookupName(Result, S.getCurScope()))
3707 CouldBeTemporaryObject = false;
3708 Result.suppressDiagnostics();
3709 }
3710
3711 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3712
3713 if (!CouldBeTemporaryObject) {
3714 // If we have A (::B), the parentheses affect the meaning of the program.
3715 // Suppress the warning in that case. Don't bother looking at the DeclSpec
3716 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3717 // formally unambiguous.
3718 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3720 for (;;) {
3721 switch (NNS.getKind()) {
3723 return;
3725 NNS = NNS.getAsType()->getPrefix();
3726 continue;
3728 NNS = NNS.getAsNamespaceAndPrefix().Prefix;
3729 continue;
3730 default:
3731 goto out;
3732 }
3733 }
3734 out:;
3735 }
3736
3737 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3738 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3740 return;
3741 }
3742
3743 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3744 << ParenRange << D.getIdentifier();
3745 auto *RD = T->getAsCXXRecordDecl();
3746 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3747 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3748 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3749 << D.getIdentifier();
3750 // FIXME: A cast to void is probably a better suggestion in cases where it's
3751 // valid (when there is no initializer and we're not in a condition).
3752 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3755 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3758}
3759
3760/// Helper for figuring out the default CC for a function declarator type. If
3761/// this is the outermost chunk, then we can determine the CC from the
3762/// declarator context. If not, then this could be either a member function
3763/// type or normal function type.
3765 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3766 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3767 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3768
3769 // Check for an explicit CC attribute.
3770 for (const ParsedAttr &AL : AttrList) {
3771 switch (AL.getKind()) {
3773 // Ignore attributes that don't validate or can't apply to the
3774 // function type. We'll diagnose the failure to apply them in
3775 // handleFunctionTypeAttr.
3776 CallingConv CC;
3777 if (!S.CheckCallingConvAttr(AL, CC, /*FunctionDecl=*/nullptr,
3778 S.CUDA().IdentifyTarget(D.getAttributes())) &&
3779 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3780 return CC;
3781 }
3782 break;
3783 }
3784
3785 default:
3786 break;
3787 }
3788 }
3789
3790 bool IsCXXInstanceMethod = false;
3791
3792 if (S.getLangOpts().CPlusPlus) {
3793 // Look inwards through parentheses to see if this chunk will form a
3794 // member pointer type or if we're the declarator. Any type attributes
3795 // between here and there will override the CC we choose here.
3796 unsigned I = ChunkIndex;
3797 bool FoundNonParen = false;
3798 while (I && !FoundNonParen) {
3799 --I;
3801 FoundNonParen = true;
3802 }
3803
3804 if (FoundNonParen) {
3805 // If we're not the declarator, we're a regular function type unless we're
3806 // in a member pointer.
3807 IsCXXInstanceMethod =
3809 } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
3810 // This can only be a call operator for a lambda, which is an instance
3811 // method, unless explicitly specified as 'static'.
3812 IsCXXInstanceMethod =
3814 } else {
3815 // We're the innermost decl chunk, so must be a function declarator.
3816 assert(D.isFunctionDeclarator());
3817
3818 // If we're inside a record, we're declaring a method, but it could be
3819 // explicitly or implicitly static.
3820 IsCXXInstanceMethod =
3823 !D.isStaticMember();
3824 }
3825 }
3826
3828 IsCXXInstanceMethod);
3829
3830 if (S.getLangOpts().CUDA) {
3831 // If we're compiling CUDA/HIP code and targeting HIPSPV we need to make
3832 // sure the kernels will be marked with the right calling convention so that
3833 // they will be visible by the APIs that ingest SPIR-V. We do not do this
3834 // when targeting AMDGCNSPIRV, as it does not rely on OpenCL.
3835 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
3836 if (Triple.isSPIRV() && Triple.getVendor() != llvm::Triple::AMD) {
3837 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3838 if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) {
3839 CC = CC_DeviceKernel;
3840 break;
3841 }
3842 }
3843 }
3844 }
3845
3846 for (const ParsedAttr &AL : llvm::concat<ParsedAttr>(
3849 if (AL.getKind() == ParsedAttr::AT_DeviceKernel) {
3850 CC = CC_DeviceKernel;
3851 break;
3852 }
3853 }
3854 return CC;
3855}
3856
3857namespace {
3858 /// A simple notion of pointer kinds, which matches up with the various
3859 /// pointer declarators.
3860 enum class SimplePointerKind {
3861 Pointer,
3862 BlockPointer,
3863 MemberPointer,
3864 Array,
3865 };
3866} // end anonymous namespace
3867
3869 switch (nullability) {
3871 if (!Ident__Nonnull)
3872 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3873 return Ident__Nonnull;
3874
3876 if (!Ident__Nullable)
3877 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3878 return Ident__Nullable;
3879
3881 if (!Ident__Nullable_result)
3882 Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
3883 return Ident__Nullable_result;
3884
3886 if (!Ident__Null_unspecified)
3887 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3888 return Ident__Null_unspecified;
3889 }
3890 llvm_unreachable("Unknown nullability kind.");
3891}
3892
3893/// Check whether there is a nullability attribute of any kind in the given
3894/// attribute list.
3895static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
3896 for (const ParsedAttr &AL : attrs) {
3897 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
3898 AL.getKind() == ParsedAttr::AT_TypeNullable ||
3899 AL.getKind() == ParsedAttr::AT_TypeNullableResult ||
3900 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
3901 return true;
3902 }
3903
3904 return false;
3905}
3906
3907namespace {
3908 /// Describes the kind of a pointer a declarator describes.
3909 enum class PointerDeclaratorKind {
3910 // Not a pointer.
3911 NonPointer,
3912 // Single-level pointer.
3913 SingleLevelPointer,
3914 // Multi-level pointer (of any pointer kind).
3916 // CFFooRef*
3917 MaybePointerToCFRef,
3918 // CFErrorRef*
3919 CFErrorRefPointer,
3920 // NSError**
3921 NSErrorPointerPointer,
3922 };
3923
3924 /// Describes a declarator chunk wrapping a pointer that marks inference as
3925 /// unexpected.
3926 // These values must be kept in sync with diagnostics.
3927 enum class PointerWrappingDeclaratorKind {
3928 /// Pointer is top-level.
3929 None = -1,
3930 /// Pointer is an array element.
3931 Array = 0,
3932 /// Pointer is the referent type of a C++ reference.
3933 Reference = 1
3934 };
3935} // end anonymous namespace
3936
3937/// Classify the given declarator, whose type-specified is \c type, based on
3938/// what kind of pointer it refers to.
3939///
3940/// This is used to determine the default nullability.
3941static PointerDeclaratorKind
3943 PointerWrappingDeclaratorKind &wrappingKind) {
3944 unsigned numNormalPointers = 0;
3945
3946 // For any dependent type, we consider it a non-pointer.
3947 if (type->isDependentType())
3948 return PointerDeclaratorKind::NonPointer;
3949
3950 // Look through the declarator chunks to identify pointers.
3951 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3952 DeclaratorChunk &chunk = declarator.getTypeObject(i);
3953 switch (chunk.Kind) {
3955 if (numNormalPointers == 0)
3956 wrappingKind = PointerWrappingDeclaratorKind::Array;
3957 break;
3958
3961 break;
3962
3965 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3966 : PointerDeclaratorKind::SingleLevelPointer;
3967
3969 break;
3970
3972 if (numNormalPointers == 0)
3973 wrappingKind = PointerWrappingDeclaratorKind::Reference;
3974 break;
3975
3977 ++numNormalPointers;
3978 if (numNormalPointers > 2)
3979 return PointerDeclaratorKind::MultiLevelPointer;
3980 break;
3981 }
3982 }
3983
3984 // Then, dig into the type specifier itself.
3985 unsigned numTypeSpecifierPointers = 0;
3986 do {
3987 // Decompose normal pointers.
3988 if (auto ptrType = type->getAs<PointerType>()) {
3989 ++numNormalPointers;
3990
3991 if (numNormalPointers > 2)
3992 return PointerDeclaratorKind::MultiLevelPointer;
3993
3994 type = ptrType->getPointeeType();
3995 ++numTypeSpecifierPointers;
3996 continue;
3997 }
3998
3999 // Decompose block pointers.
4000 if (type->getAs<BlockPointerType>()) {
4001 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4002 : PointerDeclaratorKind::SingleLevelPointer;
4003 }
4004
4005 // Decompose member pointers.
4006 if (type->getAs<MemberPointerType>()) {
4007 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4008 : PointerDeclaratorKind::SingleLevelPointer;
4009 }
4010
4011 // Look at Objective-C object pointers.
4012 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
4013 ++numNormalPointers;
4014 ++numTypeSpecifierPointers;
4015
4016 // If this is NSError**, report that.
4017 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
4018 if (objcClassDecl->getIdentifier() == S.ObjC().getNSErrorIdent() &&
4019 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
4020 return PointerDeclaratorKind::NSErrorPointerPointer;
4021 }
4022 }
4023
4024 break;
4025 }
4026
4027 // Look at Objective-C class types.
4028 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
4029 if (objcClass->getInterface()->getIdentifier() ==
4030 S.ObjC().getNSErrorIdent()) {
4031 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
4032 return PointerDeclaratorKind::NSErrorPointerPointer;
4033 }
4034
4035 break;
4036 }
4037
4038 // If at this point we haven't seen a pointer, we won't see one.
4039 if (numNormalPointers == 0)
4040 return PointerDeclaratorKind::NonPointer;
4041
4042 if (auto *recordDecl = type->getAsRecordDecl()) {
4043 // If this is CFErrorRef*, report it as such.
4044 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 &&
4045 S.ObjC().isCFError(recordDecl)) {
4046 return PointerDeclaratorKind::CFErrorRefPointer;
4047 }
4048 break;
4049 }
4050
4051 break;
4052 } while (true);
4053
4054 switch (numNormalPointers) {
4055 case 0:
4056 return PointerDeclaratorKind::NonPointer;
4057
4058 case 1:
4059 return PointerDeclaratorKind::SingleLevelPointer;
4060
4061 case 2:
4062 return PointerDeclaratorKind::MaybePointerToCFRef;
4063
4064 default:
4065 return PointerDeclaratorKind::MultiLevelPointer;
4066 }
4067}
4068
4070 SourceLocation loc) {
4071 // If we're anywhere in a function, method, or closure context, don't perform
4072 // completeness checks.
4073 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
4074 if (ctx->isFunctionOrMethod())
4075 return FileID();
4076
4077 if (ctx->isFileContext())
4078 break;
4079 }
4080
4081 // We only care about the expansion location.
4082 loc = S.SourceMgr.getExpansionLoc(loc);
4083 FileID file = S.SourceMgr.getFileID(loc);
4084 if (file.isInvalid())
4085 return FileID();
4086
4087 // Retrieve file information.
4088 bool invalid = false;
4089 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4090 if (invalid || !sloc.isFile())
4091 return FileID();
4092
4093 // We don't want to perform completeness checks on the main file or in
4094 // system headers.
4095 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4096 if (fileInfo.getIncludeLoc().isInvalid())
4097 return FileID();
4098 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4100 return FileID();
4101 }
4102
4103 return file;
4104}
4105
4106/// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4107/// taking into account whitespace before and after.
4108template <typename DiagBuilderT>
4109static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4110 SourceLocation PointerLoc,
4111 NullabilityKind Nullability) {
4112 assert(PointerLoc.isValid());
4113 if (PointerLoc.isMacroID())
4114 return;
4115
4116 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4117 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4118 return;
4119
4120 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4121 if (!NextChar)
4122 return;
4123
4124 SmallString<32> InsertionTextBuf{" "};
4125 InsertionTextBuf += getNullabilitySpelling(Nullability);
4126 InsertionTextBuf += " ";
4127 StringRef InsertionText = InsertionTextBuf.str();
4128
4129 if (isWhitespace(*NextChar)) {
4130 InsertionText = InsertionText.drop_back();
4131 } else if (NextChar[-1] == '[') {
4132 if (NextChar[0] == ']')
4133 InsertionText = InsertionText.drop_back().drop_front();
4134 else
4135 InsertionText = InsertionText.drop_front();
4136 } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) &&
4137 !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) {
4138 InsertionText = InsertionText.drop_back().drop_front();
4139 }
4140
4141 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4142}
4143
4145 SimplePointerKind PointerKind,
4146 SourceLocation PointerLoc,
4147 SourceLocation PointerEndLoc) {
4148 assert(PointerLoc.isValid());
4149
4150 if (PointerKind == SimplePointerKind::Array) {
4151 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4152 } else {
4153 S.Diag(PointerLoc, diag::warn_nullability_missing)
4154 << static_cast<unsigned>(PointerKind);
4155 }
4156
4157 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4158 if (FixItLoc.isMacroID())
4159 return;
4160
4161 auto addFixIt = [&](NullabilityKind Nullability) {
4162 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4163 Diag << static_cast<unsigned>(Nullability);
4164 Diag << static_cast<unsigned>(PointerKind);
4165 fixItNullability(S, Diag, FixItLoc, Nullability);
4166 };
4167 addFixIt(NullabilityKind::Nullable);
4168 addFixIt(NullabilityKind::NonNull);
4169}
4170
4171/// Complains about missing nullability if the file containing \p pointerLoc
4172/// has other uses of nullability (either the keywords or the \c assume_nonnull
4173/// pragma).
4174///
4175/// If the file has \e not seen other uses of nullability, this particular
4176/// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4177static void
4178checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4179 SourceLocation pointerLoc,
4180 SourceLocation pointerEndLoc = SourceLocation()) {
4181 // Determine which file we're performing consistency checking for.
4182 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4183 if (file.isInvalid())
4184 return;
4185
4186 // If we haven't seen any type nullability in this file, we won't warn now
4187 // about anything.
4188 FileNullability &fileNullability = S.NullabilityMap[file];
4189 if (!fileNullability.SawTypeNullability) {
4190 // If this is the first pointer declarator in the file, and the appropriate
4191 // warning is on, record it in case we need to diagnose it retroactively.
4192 diag::kind diagKind;
4193 if (pointerKind == SimplePointerKind::Array)
4194 diagKind = diag::warn_nullability_missing_array;
4195 else
4196 diagKind = diag::warn_nullability_missing;
4197
4198 if (fileNullability.PointerLoc.isInvalid() &&
4199 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
4200 fileNullability.PointerLoc = pointerLoc;
4201 fileNullability.PointerEndLoc = pointerEndLoc;
4202 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4203 }
4204
4205 return;
4206 }
4207
4208 // Complain about missing nullability.
4209 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4210}
4211
4212/// Marks that a nullability feature has been used in the file containing
4213/// \p loc.
4214///
4215/// If this file already had pointer types in it that were missing nullability,
4216/// the first such instance is retroactively diagnosed.
4217///
4218/// \sa checkNullabilityConsistency
4221 if (file.isInvalid())
4222 return;
4223
4224 FileNullability &fileNullability = S.NullabilityMap[file];
4225 if (fileNullability.SawTypeNullability)
4226 return;
4227 fileNullability.SawTypeNullability = true;
4228
4229 // If we haven't seen any type nullability before, now we have. Retroactively
4230 // diagnose the first unannotated pointer, if there was one.
4231 if (fileNullability.PointerLoc.isInvalid())
4232 return;
4233
4234 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4236 fileNullability.PointerEndLoc);
4237}
4238
4239/// Returns true if any of the declarator chunks before \p endIndex include a
4240/// level of indirection: array, pointer, reference, or pointer-to-member.
4241///
4242/// Because declarator chunks are stored in outer-to-inner order, testing
4243/// every chunk before \p endIndex is testing all chunks that embed the current
4244/// chunk as part of their type.
4245///
4246/// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4247/// end index, in which case all chunks are tested.
4248static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4249 unsigned i = endIndex;
4250 while (i != 0) {
4251 // Walk outwards along the declarator chunks.
4252 --i;
4253 const DeclaratorChunk &DC = D.getTypeObject(i);
4254 switch (DC.Kind) {
4256 break;
4261 return true;
4265 // These are invalid anyway, so just ignore.
4266 break;
4267 }
4268 }
4269 return false;
4270}
4271
4272static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk) {
4273 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4274 Chunk.Kind == DeclaratorChunk::Array);
4275}
4276
4277template<typename AttrT>
4278static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4279 AL.setUsedAsTypeAttr();
4280 return ::new (Ctx) AttrT(Ctx, AL);
4281}
4282
4284 NullabilityKind NK) {
4285 switch (NK) {
4288
4291
4294
4297 }
4298 llvm_unreachable("unknown NullabilityKind");
4299}
4300
4301// Diagnose whether this is a case with the multiple addr spaces.
4302// Returns true if this is an invalid case.
4303// ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4304// by qualifiers for two or more different address spaces."
4306 LangAS ASNew,
4307 SourceLocation AttrLoc) {
4308 if (ASOld != LangAS::Default) {
4309 if (ASOld != ASNew) {
4310 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4311 return true;
4312 }
4313 // Emit a warning if they are identical; it's likely unintended.
4314 S.Diag(AttrLoc,
4315 diag::warn_attribute_address_multiple_identical_qualifiers);
4316 }
4317 return false;
4318}
4319
4320// Whether this is a type broadly expected to have nullability attached.
4321// These types are affected by `#pragma assume_nonnull`, and missing nullability
4322// will be diagnosed with -Wnullability-completeness.
4324 return T->canHaveNullability(/*ResultIfUnknown=*/false) &&
4325 // For now, do not infer/require nullability on C++ smart pointers.
4326 // It's unclear whether the pragma's behavior is useful for C++.
4327 // e.g. treating type-aliases and template-type-parameters differently
4328 // from types of declarations can be surprising.
4330 T->getCanonicalTypeInternal());
4331}
4332
4333static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4334 QualType declSpecType,
4335 TypeSourceInfo *TInfo) {
4336 // The TypeSourceInfo that this function returns will not be a null type.
4337 // If there is an error, this function will fill in a dummy type as fallback.
4338 QualType T = declSpecType;
4339 Declarator &D = state.getDeclarator();
4340 Sema &S = state.getSema();
4341 ASTContext &Context = S.Context;
4342 const LangOptions &LangOpts = S.getLangOpts();
4343
4344 // The name we're declaring, if any.
4345 DeclarationName Name;
4346 if (D.getIdentifier())
4347 Name = D.getIdentifier();
4348
4349 // Does this declaration declare a typedef-name?
4350 bool IsTypedefName =
4354
4355 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4356 bool IsQualifiedFunction = T->isFunctionProtoType() &&
4357 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4358 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4359
4360 // If T is 'decltype(auto)', the only declarators we can have are parens
4361 // and at most one function declarator if this is a function declaration.
4362 // If T is a deduced class template specialization type, only parentheses
4363 // are allowed.
4364 if (auto *DT = T->getAs<DeducedType>(); DT && !T->containsErrors()) {
4365 const AutoType *AT = T->getAs<AutoType>();
4366 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4367 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4368 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4369 unsigned Index = E - I - 1;
4370 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4371 unsigned DiagId = IsClassTemplateDeduction
4372 ? diag::err_deduced_class_template_compound_type
4373 : diag::err_decltype_auto_compound_type;
4374 unsigned DiagKind = 0;
4375 switch (DeclChunk.Kind) {
4377 continue;
4379 if (IsClassTemplateDeduction) {
4380 DiagKind = 3;
4381 break;
4382 }
4383 unsigned FnIndex;
4385 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4386 continue;
4387 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4388 break;
4389 }
4393 DiagKind = 0;
4394 break;
4396 DiagKind = 1;
4397 break;
4399 DiagKind = 2;
4400 break;
4402 break;
4403 }
4404
4405 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4406 D.setInvalidType(true);
4407 break;
4408 }
4409 }
4410 }
4411
4412 // Determine whether we should infer _Nonnull on pointer types.
4413 NullabilityKindOrNone inferNullability = std::nullopt;
4414 bool inferNullabilityCS = false;
4415 bool inferNullabilityInnerOnly = false;
4416 bool inferNullabilityInnerOnlyComplete = false;
4417
4418 // Are we in an assume-nonnull region?
4419 bool inAssumeNonNullRegion = false;
4420 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4421 if (assumeNonNullLoc.isValid()) {
4422 inAssumeNonNullRegion = true;
4423 recordNullabilitySeen(S, assumeNonNullLoc);
4424 }
4425
4426 // Whether to complain about missing nullability specifiers or not.
4427 enum {
4428 /// Never complain.
4429 CAMN_No,
4430 /// Complain on the inner pointers (but not the outermost
4431 /// pointer).
4432 CAMN_InnerPointers,
4433 /// Complain about any pointers that don't have nullability
4434 /// specified or inferred.
4435 CAMN_Yes
4436 } complainAboutMissingNullability = CAMN_No;
4437 unsigned NumPointersRemaining = 0;
4438 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4439
4440 if (IsTypedefName) {
4441 // For typedefs, we do not infer any nullability (the default),
4442 // and we only complain about missing nullability specifiers on
4443 // inner pointers.
4444 complainAboutMissingNullability = CAMN_InnerPointers;
4445
4446 if (shouldHaveNullability(T) && !T->getNullability()) {
4447 // Note that we allow but don't require nullability on dependent types.
4448 ++NumPointersRemaining;
4449 }
4450
4451 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4452 DeclaratorChunk &chunk = D.getTypeObject(i);
4453 switch (chunk.Kind) {
4457 break;
4458
4461 ++NumPointersRemaining;
4462 break;
4463
4466 continue;
4467
4469 ++NumPointersRemaining;
4470 continue;
4471 }
4472 }
4473 } else {
4474 bool isFunctionOrMethod = false;
4475 switch (auto context = state.getDeclarator().getContext()) {
4481 isFunctionOrMethod = true;
4482 [[fallthrough]];
4483
4485 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4486 complainAboutMissingNullability = CAMN_No;
4487 break;
4488 }
4489
4490 // Weak properties are inferred to be nullable.
4491 if (state.getDeclarator().isObjCWeakProperty()) {
4492 // Weak properties cannot be nonnull, and should not complain about
4493 // missing nullable attributes during completeness checks.
4494 complainAboutMissingNullability = CAMN_No;
4495 if (inAssumeNonNullRegion) {
4496 inferNullability = NullabilityKind::Nullable;
4497 }
4498 break;
4499 }
4500
4501 [[fallthrough]];
4502
4505 complainAboutMissingNullability = CAMN_Yes;
4506
4507 // Nullability inference depends on the type and declarator.
4508 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4509 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4510 case PointerDeclaratorKind::NonPointer:
4511 case PointerDeclaratorKind::MultiLevelPointer:
4512 // Cannot infer nullability.
4513 break;
4514
4515 case PointerDeclaratorKind::SingleLevelPointer:
4516 // Infer _Nonnull if we are in an assumes-nonnull region.
4517 if (inAssumeNonNullRegion) {
4518 complainAboutInferringWithinChunk = wrappingKind;
4519 inferNullability = NullabilityKind::NonNull;
4520 inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4522 }
4523 break;
4524
4525 case PointerDeclaratorKind::CFErrorRefPointer:
4526 case PointerDeclaratorKind::NSErrorPointerPointer:
4527 // Within a function or method signature, infer _Nullable at both
4528 // levels.
4529 if (isFunctionOrMethod && inAssumeNonNullRegion)
4530 inferNullability = NullabilityKind::Nullable;
4531 break;
4532
4533 case PointerDeclaratorKind::MaybePointerToCFRef:
4534 if (isFunctionOrMethod) {
4535 // On pointer-to-pointer parameters marked cf_returns_retained or
4536 // cf_returns_not_retained, if the outer pointer is explicit then
4537 // infer the inner pointer as _Nullable.
4538 auto hasCFReturnsAttr =
4539 [](const ParsedAttributesView &AttrList) -> bool {
4540 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4541 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4542 };
4543 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4544 if (hasCFReturnsAttr(D.getDeclarationAttributes()) ||
4545 hasCFReturnsAttr(D.getAttributes()) ||
4546 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4547 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4548 inferNullability = NullabilityKind::Nullable;
4549 inferNullabilityInnerOnly = true;
4550 }
4551 }
4552 }
4553 break;
4554 }
4555 break;
4556 }
4557
4559 complainAboutMissingNullability = CAMN_Yes;
4560 break;
4561
4581 // Don't infer in these contexts.
4582 break;
4583 }
4584 }
4585
4586 // Local function that returns true if its argument looks like a va_list.
4587 auto isVaList = [&S](QualType T) -> bool {
4588 auto *typedefTy = T->getAs<TypedefType>();
4589 if (!typedefTy)
4590 return false;
4591 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4592 do {
4593 if (typedefTy->getDecl() == vaListTypedef)
4594 return true;
4595 if (auto *name = typedefTy->getDecl()->getIdentifier())
4596 if (name->isStr("va_list"))
4597 return true;
4598 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4599 } while (typedefTy);
4600 return false;
4601 };
4602
4603 // Local function that checks the nullability for a given pointer declarator.
4604 // Returns true if _Nonnull was inferred.
4605 auto inferPointerNullability =
4606 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4607 SourceLocation pointerEndLoc,
4608 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4609 // We've seen a pointer.
4610 if (NumPointersRemaining > 0)
4611 --NumPointersRemaining;
4612
4613 // If a nullability attribute is present, there's nothing to do.
4614 if (hasNullabilityAttr(attrs))
4615 return nullptr;
4616
4617 // If we're supposed to infer nullability, do so now.
4618 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4619 ParsedAttr::Form form =
4620 inferNullabilityCS
4621 ? ParsedAttr::Form::ContextSensitiveKeyword()
4622 : ParsedAttr::Form::Keyword(false /*IsAlignAs*/,
4623 false /*IsRegularKeywordAttribute*/);
4624 ParsedAttr *nullabilityAttr = Pool.create(
4625 S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4626 AttributeScopeInfo(), nullptr, 0, form);
4627
4628 attrs.addAtEnd(nullabilityAttr);
4629
4630 if (inferNullabilityCS) {
4631 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4632 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4633 }
4634
4635 if (pointerLoc.isValid() &&
4636 complainAboutInferringWithinChunk !=
4637 PointerWrappingDeclaratorKind::None) {
4638 auto Diag =
4639 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4640 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4642 }
4643
4644 if (inferNullabilityInnerOnly)
4645 inferNullabilityInnerOnlyComplete = true;
4646 return nullabilityAttr;
4647 }
4648
4649 // If we're supposed to complain about missing nullability, do so
4650 // now if it's truly missing.
4651 switch (complainAboutMissingNullability) {
4652 case CAMN_No:
4653 break;
4654
4655 case CAMN_InnerPointers:
4656 if (NumPointersRemaining == 0)
4657 break;
4658 [[fallthrough]];
4659
4660 case CAMN_Yes:
4661 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4662 }
4663 return nullptr;
4664 };
4665
4666 // If the type itself could have nullability but does not, infer pointer
4667 // nullability and perform consistency checking.
4668 if (S.CodeSynthesisContexts.empty()) {
4669 if (shouldHaveNullability(T) && !T->getNullability()) {
4670 if (isVaList(T)) {
4671 // Record that we've seen a pointer, but do nothing else.
4672 if (NumPointersRemaining > 0)
4673 --NumPointersRemaining;
4674 } else {
4675 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4676 if (T->isBlockPointerType())
4677 pointerKind = SimplePointerKind::BlockPointer;
4678 else if (T->isMemberPointerType())
4679 pointerKind = SimplePointerKind::MemberPointer;
4680
4681 if (auto *attr = inferPointerNullability(
4682 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4683 D.getDeclSpec().getEndLoc(),
4686 T = state.getAttributedType(
4687 createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4688 }
4689 }
4690 }
4691
4692 if (complainAboutMissingNullability == CAMN_Yes && T->isArrayType() &&
4693 !T->getNullability() && !isVaList(T) && D.isPrototypeContext() &&
4695 checkNullabilityConsistency(S, SimplePointerKind::Array,
4697 }
4698 }
4699
4700 bool ExpectNoDerefChunk =
4701 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4702
4703 // Walk the DeclTypeInfo, building the recursive type as we go.
4704 // DeclTypeInfos are ordered from the identifier out, which is
4705 // opposite of what we want :).
4706
4707 // Track if the produced type matches the structure of the declarator.
4708 // This is used later to decide if we can fill `TypeLoc` from
4709 // `DeclaratorChunk`s. E.g. it must be false if Clang recovers from
4710 // an error by replacing the type with `int`.
4711 bool AreDeclaratorChunksValid = true;
4712 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4713 unsigned chunkIndex = e - i - 1;
4714 state.setCurrentChunkIndex(chunkIndex);
4715 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4716 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4717 switch (DeclType.Kind) {
4719 if (i == 0)
4721 T = S.BuildParenType(T);
4722 break;
4724 // If blocks are disabled, emit an error.
4725 if (!LangOpts.Blocks)
4726 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4727
4728 // Handle pointer nullability.
4729 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4730 DeclType.EndLoc, DeclType.getAttrs(),
4731 state.getDeclarator().getAttributePool());
4732
4733 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4734 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4735 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4736 // qualified with const.
4737 if (LangOpts.OpenCL)
4738 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4739 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4740 }
4741 break;
4743 // Verify that we're not building a pointer to pointer to function with
4744 // exception specification.
4745 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4746 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4747 D.setInvalidType(true);
4748 // Build the type anyway.
4749 }
4750
4751 // Handle pointer nullability
4752 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4753 DeclType.EndLoc, DeclType.getAttrs(),
4754 state.getDeclarator().getAttributePool());
4755
4756 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
4757 T = Context.getObjCObjectPointerType(T);
4758 if (DeclType.Ptr.TypeQuals)
4759 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4760 break;
4761 }
4762
4763 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4764 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4765 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4766 if (LangOpts.OpenCL) {
4767 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4768 T->isBlockPointerType()) {
4769 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4770 D.setInvalidType(true);
4771 }
4772 }
4773
4774 T = S.BuildPointerType(T, DeclType.Loc, Name);
4775 if (DeclType.Ptr.TypeQuals)
4776 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4777 if (DeclType.Ptr.OverflowBehaviorLoc.isValid()) {
4778 auto OBState = DeclType.Ptr.OverflowBehaviorIsWrap
4781 S.Diag(DeclType.Ptr.OverflowBehaviorLoc,
4782 diag::err_overflow_behavior_non_integer_type)
4783 << DeclSpec::getSpecifierName(OBState) << T.getAsString() << 1;
4784 D.setInvalidType(true);
4785 }
4786 break;
4788 // Verify that we're not building a reference to pointer to function with
4789 // exception specification.
4790 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4791 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4792 D.setInvalidType(true);
4793 // Build the type anyway.
4794 }
4795 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4796
4797 if (DeclType.Ref.HasRestrict)
4799 break;
4800 }
4802 // Verify that we're not building an array of pointers to function with
4803 // exception specification.
4804 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4805 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4806 D.setInvalidType(true);
4807 // Build the type anyway.
4808 }
4809 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4810 Expr *ArraySize = ATI.NumElts;
4812
4813 // Microsoft property fields can have multiple sizeless array chunks
4814 // (i.e. int x[][][]). Skip all of these except one to avoid creating
4815 // bad incomplete array types.
4816 if (chunkIndex != 0 && !ArraySize &&
4818 // This is a sizeless chunk. If the next is also, skip this one.
4819 DeclaratorChunk &NextDeclType = D.getTypeObject(chunkIndex - 1);
4820 if (NextDeclType.Kind == DeclaratorChunk::Array &&
4821 !NextDeclType.Arr.NumElts)
4822 break;
4823 }
4824
4825 if (ATI.isStar)
4827 else if (ATI.hasStatic)
4829 else
4831 if (ASM == ArraySizeModifier::Star && !D.isPrototypeContext()) {
4832 // FIXME: This check isn't quite right: it allows star in prototypes
4833 // for function definitions, and disallows some edge cases detailed
4834 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4835 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4837 D.setInvalidType(true);
4838 }
4839
4840 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4841 // shall appear only in a declaration of a function parameter with an
4842 // array type, ...
4843 if (ASM == ArraySizeModifier::Static || ATI.TypeQuals) {
4844 if (!(D.isPrototypeContext() ||
4846 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype)
4847 << (ASM == ArraySizeModifier::Static ? "'static'"
4848 : "type qualifier");
4849 // Remove the 'static' and the type qualifiers.
4850 if (ASM == ArraySizeModifier::Static)
4852 ATI.TypeQuals = 0;
4853 D.setInvalidType(true);
4854 }
4855
4856 // C99 6.7.5.2p1: ... and then only in the outermost array type
4857 // derivation.
4858 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4859 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost)
4860 << (ASM == ArraySizeModifier::Static ? "'static'"
4861 : "type qualifier");
4862 if (ASM == ArraySizeModifier::Static)
4864 ATI.TypeQuals = 0;
4865 D.setInvalidType(true);
4866 }
4867 }
4868
4869 // Array parameters can be marked nullable as well, although it's not
4870 // necessary if they're marked 'static'.
4871 if (complainAboutMissingNullability == CAMN_Yes &&
4872 !hasNullabilityAttr(DeclType.getAttrs()) &&
4874 !hasOuterPointerLikeChunk(D, chunkIndex)) {
4875 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4876 }
4877
4878 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4879 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4880 break;
4881 }
4883 // If the function declarator has a prototype (i.e. it is not () and
4884 // does not have a K&R-style identifier list), then the arguments are part
4885 // of the type, otherwise the argument list is ().
4886 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4887 IsQualifiedFunction =
4889
4890 auto IsClassType = [&](CXXScopeSpec &SS) {
4891 // If there already was an problem with the scope, don’t issue another
4892 // error about the explicit object parameter.
4893 return SS.isInvalid() ||
4894 isa_and_present<CXXRecordDecl>(
4895 S.computeDeclContext(SS, /*EnteringContext=*/true));
4896 };
4897
4898 // C++23 [dcl.fct]p6:
4899 //
4900 // An explicit-object-parameter-declaration is a parameter-declaration
4901 // with a this specifier. An explicit-object-parameter-declaration shall
4902 // appear only as the first parameter-declaration of a
4903 // parameter-declaration-list of one of:
4904 //
4905 // - a declaration of a member function or member function template
4906 // ([class.mem]), or
4907 //
4908 // - an explicit instantiation ([temp.explicit]) or explicit
4909 // specialization ([temp.expl.spec]) of a templated member function,
4910 // or
4911 //
4912 // - a lambda-declarator [expr.prim.lambda].
4915 FTI.NumParams ? dyn_cast_if_present<ParmVarDecl>(FTI.Params[0].Param)
4916 : nullptr;
4917
4918 bool IsFunctionDecl = D.getInnermostNonParenChunk() == &DeclType;
4919 if (First && First->isExplicitObjectParameter() &&
4921
4922 // Either not a member or nested declarator in a member.
4923 //
4924 // Note that e.g. 'static' or 'friend' declarations are accepted
4925 // here; we diagnose them later when we build the member function
4926 // because it's easier that way.
4927 (C != DeclaratorContext::Member || !IsFunctionDecl) &&
4928
4929 // Allow out-of-line definitions of member functions.
4930 !IsClassType(D.getCXXScopeSpec())) {
4931 if (IsFunctionDecl)
4932 S.Diag(First->getBeginLoc(),
4933 diag::err_explicit_object_parameter_nonmember)
4934 << /*non-member*/ 2 << /*function*/ 0 << First->getSourceRange();
4935 else
4936 S.Diag(First->getBeginLoc(),
4937 diag::err_explicit_object_parameter_invalid)
4938 << First->getSourceRange();
4939
4940 // Do let non-member function have explicit parameters
4941 // to not break assumptions elsewhere in the code.
4942 First->setExplicitObjectParameterLoc(SourceLocation());
4943 D.setInvalidType();
4944 AreDeclaratorChunksValid = false;
4945 }
4946
4947 // Check for auto functions and trailing return type and adjust the
4948 // return type accordingly.
4949 if (!D.isInvalidType()) {
4950 // trailing-return-type is only required if we're declaring a function,
4951 // and not, for instance, a pointer to a function.
4952 if (D.getDeclSpec().hasAutoTypeSpec() &&
4953 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
4954 if (!S.getLangOpts().CPlusPlus14) {
4957 ? diag::err_auto_missing_trailing_return
4958 : diag::err_deduced_return_type);
4959 T = Context.IntTy;
4960 D.setInvalidType(true);
4961 AreDeclaratorChunksValid = false;
4962 } else {
4964 diag::warn_cxx11_compat_deduced_return_type);
4965 }
4966 } else if (FTI.hasTrailingReturnType()) {
4967 // T must be exactly 'auto' at this point. See CWG issue 681.
4968 if (isa<ParenType>(T)) {
4969 S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
4970 << T << D.getSourceRange();
4971 D.setInvalidType(true);
4972 // FIXME: recover and fill decls in `TypeLoc`s.
4973 AreDeclaratorChunksValid = false;
4974 } else if (D.getName().getKind() ==
4976 if (T != Context.DependentTy) {
4978 diag::err_deduction_guide_with_complex_decl)
4979 << D.getSourceRange();
4980 D.setInvalidType(true);
4981 // FIXME: recover and fill decls in `TypeLoc`s.
4982 AreDeclaratorChunksValid = false;
4983 }
4984 } else if (D.getContext() != DeclaratorContext::LambdaExpr &&
4985 (T.hasQualifiers() || !isa<AutoType>(T) ||
4986 cast<AutoType>(T)->getKeyword() !=
4988 cast<AutoType>(T)->isConstrained())) {
4989 // Attach a valid source location for diagnostics on functions with
4990 // trailing return types missing 'auto'. Attempt to get the location
4991 // from the declared type; if invalid, fall back to the trailing
4992 // return type's location.
4995 if (Loc.isInvalid()) {
4996 Loc = FTI.getTrailingReturnTypeLoc();
4997 SR = D.getSourceRange();
4998 }
4999 S.Diag(Loc, diag::err_trailing_return_without_auto) << T << SR;
5000 D.setInvalidType(true);
5001 // FIXME: recover and fill decls in `TypeLoc`s.
5002 AreDeclaratorChunksValid = false;
5003 }
5004 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
5005 if (T.isNull()) {
5006 // An error occurred parsing the trailing return type.
5007 T = Context.IntTy;
5008 D.setInvalidType(true);
5009 } else if (AutoType *Auto = T->getContainedAutoType()) {
5010 // If the trailing return type contains an `auto`, we may need to
5011 // invent a template parameter for it, for cases like
5012 // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
5013 InventedTemplateParameterInfo *InventedParamInfo = nullptr;
5015 InventedParamInfo = &S.InventedParameterInfos.back();
5017 InventedParamInfo = S.getCurLambda();
5018 if (InventedParamInfo) {
5019 std::tie(T, TInfo) = InventTemplateParameter(
5020 state, T, TInfo, Auto, *InventedParamInfo);
5021 }
5022 }
5023 } else {
5024 // This function type is not the type of the entity being declared,
5025 // so checking the 'auto' is not the responsibility of this chunk.
5026 }
5027 }
5028
5029 // C99 6.7.5.3p1: The return type may not be a function or array type.
5030 // For conversion functions, we'll diagnose this particular error later.
5031 if (!D.isInvalidType() &&
5032 ((T->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
5033 T->isFunctionType()) &&
5034 (D.getName().getKind() !=
5036 unsigned diagID = diag::err_func_returning_array_function;
5037 // Last processing chunk in block context means this function chunk
5038 // represents the block.
5039 if (chunkIndex == 0 &&
5041 diagID = diag::err_block_returning_array_function;
5042 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
5043 T = Context.IntTy;
5044 D.setInvalidType(true);
5045 AreDeclaratorChunksValid = false;
5046 }
5047
5048 // Do not allow returning half FP value.
5049 // FIXME: This really should be in BuildFunctionType.
5050 if (T->isHalfType()) {
5051 if (S.getLangOpts().OpenCL) {
5052 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5053 S.getLangOpts())) {
5054 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5055 << T << 0 /*pointer hint*/;
5056 D.setInvalidType(true);
5057 }
5058 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5060 S.Diag(D.getIdentifierLoc(),
5061 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
5062 D.setInvalidType(true);
5063 }
5064 }
5065
5066 // __ptrauth is illegal on a function return type.
5067 if (T.getPointerAuth()) {
5068 S.Diag(DeclType.Loc, diag::err_ptrauth_qualifier_invalid) << T << 0;
5069 }
5070
5071 if (LangOpts.OpenCL) {
5072 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
5073 // function.
5074 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
5075 T->isPipeType()) {
5076 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5077 << T << 1 /*hint off*/;
5078 D.setInvalidType(true);
5079 }
5080 // OpenCL doesn't support variadic functions and blocks
5081 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
5082 // We also allow here any toolchain reserved identifiers.
5083 if (FTI.isVariadic &&
5085 "__cl_clang_variadic_functions", S.getLangOpts()) &&
5086 !(D.getIdentifier() &&
5087 ((D.getIdentifier()->getName() == "printf" &&
5088 LangOpts.getOpenCLCompatibleVersion() >= 120) ||
5089 D.getIdentifier()->getName().starts_with("__")))) {
5090 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
5091 D.setInvalidType(true);
5092 }
5093 }
5094
5095 // Methods cannot return interface types. All ObjC objects are
5096 // passed by reference.
5097 if (T->isObjCObjectType()) {
5098 SourceLocation DiagLoc, FixitLoc;
5099 if (TInfo) {
5100 DiagLoc = TInfo->getTypeLoc().getBeginLoc();
5101 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
5102 } else {
5103 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5104 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
5105 }
5106 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
5107 << 0 << T
5108 << FixItHint::CreateInsertion(FixitLoc, "*");
5109
5110 T = Context.getObjCObjectPointerType(T);
5111 if (TInfo) {
5112 TypeLocBuilder TLB;
5113 TLB.pushFullCopy(TInfo->getTypeLoc());
5115 TLoc.setStarLoc(FixitLoc);
5116 TInfo = TLB.getTypeSourceInfo(Context, T);
5117 } else {
5118 AreDeclaratorChunksValid = false;
5119 }
5120
5121 D.setInvalidType(true);
5122 }
5123
5124 // cv-qualifiers on return types are pointless except when the type is a
5125 // class type in C++.
5126 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
5127 // A dependent type or an undeduced type might later become a class
5128 // type.
5129 !(S.getLangOpts().CPlusPlus &&
5130 (T->isRecordType() || T->isDependentType() ||
5131 T->isUndeducedAutoType()))) {
5132 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
5135 // [6.9.1/3] qualified void return is invalid on a C
5136 // function definition. Apparently ok on declarations and
5137 // in C++ though (!)
5138 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
5139 } else
5140 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
5141 }
5142
5143 // C++2a [dcl.fct]p12:
5144 // A volatile-qualified return type is deprecated
5145 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20)
5146 S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T;
5147
5148 // Objective-C ARC ownership qualifiers are ignored on the function
5149 // return type (by type canonicalization). Complain if this attribute
5150 // was written here.
5151 if (T.getQualifiers().hasObjCLifetime()) {
5152 SourceLocation AttrLoc;
5153 if (chunkIndex + 1 < D.getNumTypeObjects()) {
5154 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
5155 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5156 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5157 AttrLoc = AL.getLoc();
5158 break;
5159 }
5160 }
5161 }
5162 if (AttrLoc.isInvalid()) {
5163 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5164 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5165 AttrLoc = AL.getLoc();
5166 break;
5167 }
5168 }
5169 }
5170
5171 if (AttrLoc.isValid()) {
5172 // The ownership attributes are almost always written via
5173 // the predefined
5174 // __strong/__weak/__autoreleasing/__unsafe_unretained.
5175 if (AttrLoc.isMacroID())
5176 AttrLoc =
5178
5179 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
5180 << T.getQualifiers().getObjCLifetime();
5181 }
5182 }
5183
5184 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
5185 // C++ [dcl.fct]p6:
5186 // Types shall not be defined in return or parameter types.
5188 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
5189 << Context.getCanonicalTagType(Tag);
5190 }
5191
5192 // Exception specs are not allowed in typedefs. Complain, but add it
5193 // anyway.
5194 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
5196 diag::err_exception_spec_in_typedef)
5199
5200 // If we see "T var();" or "T var(T());" at block scope, it is probably
5201 // an attempt to initialize a variable, not a function declaration.
5202 if (FTI.isAmbiguous)
5203 warnAboutAmbiguousFunction(S, D, DeclType, T);
5204
5206 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
5207
5208 // OpenCL disallows functions without a prototype, but it doesn't enforce
5209 // strict prototypes as in C23 because it allows a function definition to
5210 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
5211 if (!FTI.NumParams && !FTI.isVariadic &&
5212 !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) {
5213 // Simple void foo(), where the incoming T is the result type.
5214 T = Context.getFunctionNoProtoType(T, EI);
5215 } else {
5216 // We allow a zero-parameter variadic function in C if the
5217 // function is marked with the "overloadable" attribute. Scan
5218 // for this attribute now. We also allow it in C23 per WG14 N2975.
5219 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
5220 if (LangOpts.C23)
5221 S.Diag(FTI.getEllipsisLoc(),
5222 diag::warn_c17_compat_ellipsis_only_parameter);
5224 ParsedAttr::AT_Overloadable) &&
5226 ParsedAttr::AT_Overloadable) &&
5228 ParsedAttr::AT_Overloadable))
5229 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
5230 }
5231
5232 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
5233 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5234 // definition.
5235 S.Diag(FTI.Params[0].IdentLoc,
5236 diag::err_ident_list_in_fn_declaration);
5237 D.setInvalidType(true);
5238 // Recover by creating a K&R-style function type, if possible.
5239 T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL)
5240 ? Context.getFunctionNoProtoType(T, EI)
5241 : Context.IntTy;
5242 AreDeclaratorChunksValid = false;
5243 break;
5244 }
5245
5247 EPI.ExtInfo = EI;
5248 EPI.Variadic = FTI.isVariadic;
5249 EPI.EllipsisLoc = FTI.getEllipsisLoc();
5253 : 0);
5256 : RQ_RValue;
5257
5258 // Otherwise, we have a function with a parameter list that is
5259 // potentially variadic.
5261 ParamTys.reserve(FTI.NumParams);
5262
5264 ExtParameterInfos(FTI.NumParams);
5265 bool HasAnyInterestingExtParameterInfos = false;
5266
5267 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
5268 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5269 QualType ParamTy = Param->getType();
5270 assert(!ParamTy.isNull() && "Couldn't parse type?");
5271
5272 // Look for 'void'. void is allowed only as a single parameter to a
5273 // function with no other parameters (C99 6.7.5.3p10). We record
5274 // int(void) as a FunctionProtoType with an empty parameter list.
5275 if (ParamTy->isVoidType()) {
5276 // If this is something like 'float(int, void)', reject it. 'void'
5277 // is an incomplete type (C99 6.2.5p19) and function decls cannot
5278 // have parameters of incomplete type.
5279 if (FTI.NumParams != 1 || FTI.isVariadic) {
5280 S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param);
5281 ParamTy = Context.IntTy;
5282 Param->setType(ParamTy);
5283 } else if (FTI.Params[i].Ident) {
5284 // Reject, but continue to parse 'int(void abc)'.
5285 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
5286 ParamTy = Context.IntTy;
5287 Param->setType(ParamTy);
5288 } else {
5289 // Reject, but continue to parse 'float(const void)'.
5290 if (ParamTy.hasQualifiers())
5291 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
5292
5293 for (const auto *A : Param->attrs()) {
5294 S.Diag(A->getLoc(), diag::warn_attribute_on_void_param)
5295 << A << A->getRange();
5296 }
5297
5298 // Reject, but continue to parse 'float(this void)' as
5299 // 'float(void)'.
5300 if (Param->isExplicitObjectParameter()) {
5301 S.Diag(Param->getLocation(),
5302 diag::err_void_explicit_object_param);
5303 Param->setExplicitObjectParameterLoc(SourceLocation());
5304 }
5305
5306 // Do not add 'void' to the list.
5307 break;
5308 }
5309 } else if (ParamTy->isHalfType()) {
5310 // Disallow half FP parameters.
5311 // FIXME: This really should be in BuildFunctionType.
5312 if (S.getLangOpts().OpenCL) {
5313 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5314 S.getLangOpts())) {
5315 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5316 << ParamTy << 0;
5317 D.setInvalidType();
5318 Param->setInvalidDecl();
5319 }
5320 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5322 S.Diag(Param->getLocation(),
5323 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5324 D.setInvalidType();
5325 }
5326 } else if (!FTI.hasPrototype) {
5327 if (Context.isPromotableIntegerType(ParamTy)) {
5328 ParamTy = Context.getPromotedIntegerType(ParamTy);
5329 Param->setKNRPromoted(true);
5330 } else if (const BuiltinType *BTy = ParamTy->getAs<BuiltinType>()) {
5331 if (BTy->getKind() == BuiltinType::Float) {
5332 ParamTy = Context.DoubleTy;
5333 Param->setKNRPromoted(true);
5334 }
5335 }
5336 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) {
5337 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5338 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5339 << ParamTy << 1 /*hint off*/;
5340 D.setInvalidType();
5341 }
5342
5343 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
5344 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
5345 HasAnyInterestingExtParameterInfos = true;
5346 }
5347
5348 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5349 ExtParameterInfos[i] =
5350 ExtParameterInfos[i].withABI(attr->getABI());
5351 HasAnyInterestingExtParameterInfos = true;
5352 }
5353
5354 if (Param->hasAttr<PassObjectSizeAttr>()) {
5355 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5356 HasAnyInterestingExtParameterInfos = true;
5357 }
5358
5359 if (Param->hasAttr<NoEscapeAttr>()) {
5360 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
5361 HasAnyInterestingExtParameterInfos = true;
5362 }
5363
5364 ParamTys.push_back(ParamTy);
5365 }
5366
5367 if (HasAnyInterestingExtParameterInfos) {
5368 EPI.ExtParameterInfos = ExtParameterInfos.data();
5369 checkExtParameterInfos(S, ParamTys, EPI,
5370 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
5371 }
5372
5373 SmallVector<QualType, 4> Exceptions;
5374 SmallVector<ParsedType, 2> DynamicExceptions;
5375 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5376 Expr *NoexceptExpr = nullptr;
5377
5378 if (FTI.getExceptionSpecType() == EST_Dynamic) {
5379 // FIXME: It's rather inefficient to have to split into two vectors
5380 // here.
5381 unsigned N = FTI.getNumExceptions();
5382 DynamicExceptions.reserve(N);
5383 DynamicExceptionRanges.reserve(N);
5384 for (unsigned I = 0; I != N; ++I) {
5385 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
5386 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
5387 }
5388 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
5389 NoexceptExpr = FTI.NoexceptExpr;
5390 }
5391
5394 DynamicExceptions,
5395 DynamicExceptionRanges,
5396 NoexceptExpr,
5397 Exceptions,
5398 EPI.ExceptionSpec);
5399
5400 // FIXME: Set address space from attrs for C++ mode here.
5401 // OpenCLCPlusPlus: A class member function has an address space.
5402 auto IsClassMember = [&]() {
5403 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5404 state.getDeclarator()
5405 .getCXXScopeSpec()
5406 .getScopeRep()
5407 .getKind() == NestedNameSpecifier::Kind::Type) ||
5408 state.getDeclarator().getContext() ==
5410 state.getDeclarator().getContext() ==
5412 };
5413
5414 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
5415 LangAS ASIdx = LangAS::Default;
5416 // Take address space attr if any and mark as invalid to avoid adding
5417 // them later while creating QualType.
5418 if (FTI.MethodQualifiers)
5420 LangAS ASIdxNew = attr.asOpenCLLangAS();
5421 if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
5422 attr.getLoc()))
5423 D.setInvalidType(true);
5424 else
5425 ASIdx = ASIdxNew;
5426 }
5427 // If a class member function's address space is not set, set it to
5428 // __generic.
5429 LangAS AS =
5431 : ASIdx);
5432 EPI.TypeQuals.addAddressSpace(AS);
5433 }
5434 T = Context.getFunctionType(T, ParamTys, EPI);
5435 }
5436 break;
5437 }
5439 // The scope spec must refer to a class, or be dependent.
5440 CXXScopeSpec &SS = DeclType.Mem.Scope();
5441
5442 // Handle pointer nullability.
5443 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5444 DeclType.EndLoc, DeclType.getAttrs(),
5445 state.getDeclarator().getAttributePool());
5446
5447 if (SS.isInvalid()) {
5448 // Avoid emitting extra errors if we already errored on the scope.
5449 D.setInvalidType(true);
5450 AreDeclaratorChunksValid = false;
5451 } else {
5452 T = S.BuildMemberPointerType(T, SS, /*Cls=*/nullptr, DeclType.Loc,
5453 D.getIdentifier());
5454 }
5455
5456 if (T.isNull()) {
5457 T = Context.IntTy;
5458 D.setInvalidType(true);
5459 AreDeclaratorChunksValid = false;
5460 } else if (DeclType.Mem.TypeQuals) {
5461 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
5462 }
5463 break;
5464 }
5465
5466 case DeclaratorChunk::Pipe: {
5467 T = S.BuildReadPipeType(T, DeclType.Loc);
5470 break;
5471 }
5472 }
5473
5474 if (T.isNull()) {
5475 D.setInvalidType(true);
5476 T = Context.IntTy;
5477 AreDeclaratorChunksValid = false;
5478 }
5479
5480 // See if there are any attributes on this declarator chunk.
5481 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs(),
5483
5484 if (DeclType.Kind != DeclaratorChunk::Paren) {
5485 if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
5486 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5487
5488 ExpectNoDerefChunk = state.didParseNoDeref();
5489 }
5490 }
5491
5492 if (ExpectNoDerefChunk)
5493 S.Diag(state.getDeclarator().getBeginLoc(),
5494 diag::warn_noderef_on_non_pointer_or_array);
5495
5496 // GNU warning -Wstrict-prototypes
5497 // Warn if a function declaration or definition is without a prototype.
5498 // This warning is issued for all kinds of unprototyped function
5499 // declarations (i.e. function type typedef, function pointer etc.)
5500 // C99 6.7.5.3p14:
5501 // The empty list in a function declarator that is not part of a definition
5502 // of that function specifies that no information about the number or types
5503 // of the parameters is supplied.
5504 // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of
5505 // function declarations whose behavior changes in C23.
5506 if (!LangOpts.requiresStrictPrototypes()) {
5507 bool IsBlock = false;
5508 for (const DeclaratorChunk &DeclType : D.type_objects()) {
5509 switch (DeclType.Kind) {
5511 IsBlock = true;
5512 break;
5514 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5515 // We suppress the warning when there's no LParen location, as this
5516 // indicates the declaration was an implicit declaration, which gets
5517 // warned about separately via -Wimplicit-function-declaration. We also
5518 // suppress the warning when we know the function has a prototype.
5519 if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic &&
5520 FTI.getLParenLoc().isValid())
5521 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5522 << IsBlock
5523 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5524 IsBlock = false;
5525 break;
5526 }
5527 default:
5528 break;
5529 }
5530 }
5531 }
5532
5533 assert(!T.isNull() && "T must not be null after this point");
5534
5535 if (LangOpts.CPlusPlus && T->isFunctionType()) {
5536 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5537 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
5538
5539 // C++ 8.3.5p4:
5540 // A cv-qualifier-seq shall only be part of the function type
5541 // for a nonstatic member function, the function type to which a pointer
5542 // to member refers, or the top-level function type of a function typedef
5543 // declaration.
5544 //
5545 // Core issue 547 also allows cv-qualifiers on function types that are
5546 // top-level template type arguments.
5547 enum {
5548 NonMember,
5549 Member,
5550 ExplicitObjectMember,
5551 DeductionGuide
5552 } Kind = NonMember;
5554 Kind = DeductionGuide;
5555 else if (!D.getCXXScopeSpec().isSet()) {
5559 Kind = Member;
5560 } else {
5562 if (!DC || DC->isRecord())
5563 Kind = Member;
5564 }
5565
5566 if (Kind == Member) {
5567 unsigned I;
5568 if (D.isFunctionDeclarator(I)) {
5569 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5570 if (Chunk.Fun.NumParams) {
5571 auto *P = dyn_cast_or_null<ParmVarDecl>(Chunk.Fun.Params->Param);
5572 if (P && P->isExplicitObjectParameter())
5573 Kind = ExplicitObjectMember;
5574 }
5575 }
5576 }
5577
5578 // C++11 [dcl.fct]p6 (w/DR1417):
5579 // An attempt to specify a function type with a cv-qualifier-seq or a
5580 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5581 // - the function type for a non-static member function,
5582 // - the function type to which a pointer to member refers,
5583 // - the top-level function type of a function typedef declaration or
5584 // alias-declaration,
5585 // - the type-id in the default argument of a type-parameter, or
5586 // - the type-id of a template-argument for a type-parameter
5587 //
5588 // C++23 [dcl.fct]p6 (P0847R7)
5589 // ... A member-declarator with an explicit-object-parameter-declaration
5590 // shall not include a ref-qualifier or a cv-qualifier-seq and shall not be
5591 // declared static or virtual ...
5592 //
5593 // FIXME: Checking this here is insufficient. We accept-invalid on:
5594 //
5595 // template<typename T> struct S { void f(T); };
5596 // S<int() const> s;
5597 //
5598 // ... for instance.
5599 if (IsQualifiedFunction &&
5600 // Check for non-static member function and not and
5601 // explicit-object-parameter-declaration
5602 (Kind != Member || D.isExplicitObjectMemberFunction() ||
5605 D.isStaticMember())) &&
5606 !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg &&
5609 SourceLocation Loc = D.getBeginLoc();
5610 SourceRange RemovalRange;
5611 unsigned I;
5612 if (D.isFunctionDeclarator(I)) {
5614 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5615 assert(Chunk.Kind == DeclaratorChunk::Function);
5616
5617 if (Chunk.Fun.hasRefQualifier())
5618 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5619
5620 if (Chunk.Fun.hasMethodTypeQualifiers())
5622 [&](DeclSpec::TQ TypeQual, StringRef QualName,
5623 SourceLocation SL) { RemovalLocs.push_back(SL); });
5624
5625 if (!RemovalLocs.empty()) {
5626 llvm::sort(RemovalLocs,
5628 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5629 Loc = RemovalLocs.front();
5630 }
5631 }
5632
5633 S.Diag(Loc, diag::err_invalid_qualified_function_type)
5634 << Kind << D.isFunctionDeclarator() << T
5636 << FixItHint::CreateRemoval(RemovalRange);
5637
5638 // Strip the cv-qualifiers and ref-qualifiers from the type.
5641 EPI.RefQualifier = RQ_None;
5642
5643 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5644 EPI);
5645 // Rebuild any parens around the identifier in the function type.
5646 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5648 break;
5649 T = S.BuildParenType(T);
5650 }
5651 }
5652 }
5653
5654 // Apply any undistributed attributes from the declaration or declarator.
5655 ParsedAttributesView NonSlidingAttrs;
5656 for (ParsedAttr &AL : D.getDeclarationAttributes()) {
5657 if (!AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
5658 NonSlidingAttrs.addAtEnd(&AL);
5659 }
5660 }
5661 processTypeAttrs(state, T, TAL_DeclName, NonSlidingAttrs);
5663
5664 // Diagnose any ignored type attributes.
5665 state.diagnoseIgnoredTypeAttrs(T);
5666
5667 // C++0x [dcl.constexpr]p9:
5668 // A constexpr specifier used in an object declaration declares the object
5669 // as const.
5671 T->isObjectType())
5672 T.addConst();
5673
5674 // C++2a [dcl.fct]p4:
5675 // A parameter with volatile-qualified type is deprecated
5676 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 &&
5679 S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T;
5680
5681 // If there was an ellipsis in the declarator, the declaration declares a
5682 // parameter pack whose type may be a pack expansion type.
5683 if (D.hasEllipsis()) {
5684 // C++0x [dcl.fct]p13:
5685 // A declarator-id or abstract-declarator containing an ellipsis shall
5686 // only be used in a parameter-declaration. Such a parameter-declaration
5687 // is a parameter pack (14.5.3). [...]
5688 switch (D.getContext()) {
5692 // C++0x [dcl.fct]p13:
5693 // [...] When it is part of a parameter-declaration-clause, the
5694 // parameter pack is a function parameter pack (14.5.3). The type T
5695 // of the declarator-id of the function parameter pack shall contain
5696 // a template parameter pack; each template parameter pack in T is
5697 // expanded by the function parameter pack.
5698 //
5699 // We represent function parameter packs as function parameters whose
5700 // type is a pack expansion.
5701 if (!T->containsUnexpandedParameterPack() &&
5702 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) {
5703 S.Diag(D.getEllipsisLoc(),
5704 diag::err_function_parameter_pack_without_parameter_packs)
5705 << T << D.getSourceRange();
5707 } else {
5708 T = Context.getPackExpansionType(T, std::nullopt,
5709 /*ExpectPackInType=*/false);
5710 }
5711 break;
5713 // C++0x [temp.param]p15:
5714 // If a template-parameter is a [...] is a parameter-declaration that
5715 // declares a parameter pack (8.3.5), then the template-parameter is a
5716 // template parameter pack (14.5.3).
5717 //
5718 // Note: core issue 778 clarifies that, if there are any unexpanded
5719 // parameter packs in the type of the non-type template parameter, then
5720 // it expands those parameter packs.
5721 if (T->containsUnexpandedParameterPack())
5722 T = Context.getPackExpansionType(T, std::nullopt);
5723 else
5724 S.DiagCompat(D.getEllipsisLoc(), diag_compat::variadic_templates);
5725 break;
5726
5729 case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here?
5730 case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here?
5751 // FIXME: We may want to allow parameter packs in block-literal contexts
5752 // in the future.
5753 S.Diag(D.getEllipsisLoc(),
5754 diag::err_ellipsis_in_declarator_not_parameter);
5756 break;
5757 }
5758 }
5759
5760 assert(!T.isNull() && "T must not be null at the end of this function");
5761 if (!AreDeclaratorChunksValid)
5762 return Context.getTrivialTypeSourceInfo(T);
5763
5764 if (state.didParseHLSLParamMod() && !T->isConstantArrayType())
5766 return GetTypeSourceInfoForDeclarator(state, T, TInfo);
5767}
5768
5770 // Determine the type of the declarator. Not all forms of declarator
5771 // have a type.
5772
5773 TypeProcessingState state(*this, D);
5774
5775 TypeSourceInfo *ReturnTypeInfo = nullptr;
5776 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5777 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5778 inferARCWriteback(state, T);
5779
5780 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5781}
5782
5784 QualType &declSpecTy,
5785 Qualifiers::ObjCLifetime ownership) {
5786 if (declSpecTy->isObjCRetainableType() &&
5787 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5788 Qualifiers qs;
5789 qs.addObjCLifetime(ownership);
5790 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5791 }
5792}
5793
5794static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5795 Qualifiers::ObjCLifetime ownership,
5796 unsigned chunkIndex) {
5797 Sema &S = state.getSema();
5798 Declarator &D = state.getDeclarator();
5799
5800 // Look for an explicit lifetime attribute.
5801 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5802 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
5803 return;
5804
5805 const char *attrStr = nullptr;
5806 switch (ownership) {
5807 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5808 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5809 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5810 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5811 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5812 }
5813
5814 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5815 Arg->setIdentifierInfo(&S.Context.Idents.get(attrStr));
5816
5817 ArgsUnion Args(Arg);
5818
5819 // If there wasn't one, add one (with an invalid source location
5820 // so that we don't make an AttributedType for it).
5821 ParsedAttr *attr =
5822 D.getAttributePool().create(&S.Context.Idents.get("objc_ownership"),
5824 /*args*/ &Args, 1, ParsedAttr::Form::GNU());
5825 chunk.getAttrs().addAtEnd(attr);
5826 // TODO: mark whether we did this inference?
5827}
5828
5829/// Used for transferring ownership in casts resulting in l-values.
5830static void transferARCOwnership(TypeProcessingState &state,
5831 QualType &declSpecTy,
5832 Qualifiers::ObjCLifetime ownership) {
5833 Sema &S = state.getSema();
5834 Declarator &D = state.getDeclarator();
5835
5836 int inner = -1;
5837 bool hasIndirection = false;
5838 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5839 DeclaratorChunk &chunk = D.getTypeObject(i);
5840 switch (chunk.Kind) {
5842 // Ignore parens.
5843 break;
5844
5848 if (inner != -1)
5849 hasIndirection = true;
5850 inner = i;
5851 break;
5852
5854 if (inner != -1)
5855 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5856 return;
5857
5861 return;
5862 }
5863 }
5864
5865 if (inner == -1)
5866 return;
5867
5868 DeclaratorChunk &chunk = D.getTypeObject(inner);
5869 if (chunk.Kind == DeclaratorChunk::Pointer) {
5870 if (declSpecTy->isObjCRetainableType())
5871 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5872 if (declSpecTy->isObjCObjectType() && hasIndirection)
5873 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5874 } else {
5875 assert(chunk.Kind == DeclaratorChunk::Array ||
5877 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5878 }
5879}
5880
5882 TypeProcessingState state(*this, D);
5883
5884 TypeSourceInfo *ReturnTypeInfo = nullptr;
5885 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5886
5887 if (getLangOpts().ObjC) {
5888 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
5889 if (ownership != Qualifiers::OCL_None)
5890 transferARCOwnership(state, declSpecTy, ownership);
5891 }
5892
5893 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
5894}
5895
5897 TypeProcessingState &State) {
5898 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
5899}
5900
5902 TypeProcessingState &State) {
5904 State.getSema().HLSL().TakeLocForHLSLAttribute(TL.getTypePtr());
5905 TL.setSourceRange(LocInfo.Range);
5907}
5908
5910 const ParsedAttributesView &Attrs) {
5911 for (const ParsedAttr &AL : Attrs) {
5912 if (AL.getKind() == ParsedAttr::AT_MatrixType) {
5913 MTL.setAttrNameLoc(AL.getLoc());
5914 MTL.setAttrRowOperand(AL.getArgAsExpr(0));
5915 MTL.setAttrColumnOperand(AL.getArgAsExpr(1));
5917 return;
5918 }
5919 }
5920
5921 llvm_unreachable("no matrix_type attribute found at the expected location!");
5922}
5923
5924static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5925 SourceLocation Loc;
5926 switch (Chunk.Kind) {
5931 llvm_unreachable("cannot be _Atomic qualified");
5932
5934 Loc = Chunk.Ptr.AtomicQualLoc;
5935 break;
5936
5940 // FIXME: Provide a source location for the _Atomic keyword.
5941 break;
5942 }
5943
5944 ATL.setKWLoc(Loc);
5946}
5947
5948namespace {
5949 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5950 Sema &SemaRef;
5951 ASTContext &Context;
5952 TypeProcessingState &State;
5953 const DeclSpec &DS;
5954
5955 public:
5956 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
5957 const DeclSpec &DS)
5958 : SemaRef(S), Context(Context), State(State), DS(DS) {}
5959
5960 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5961 Visit(TL.getModifiedLoc());
5962 fillAttributedTypeLoc(TL, State);
5963 }
5964 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
5965 Visit(TL.getWrappedLoc());
5966 }
5967 void VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
5968 Visit(TL.getWrappedLoc());
5969 }
5970 void VisitHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL) {
5971 Visit(TL.getWrappedLoc());
5973 }
5974 void VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {}
5975 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
5976 Visit(TL.getInnerLoc());
5977 TL.setExpansionLoc(
5978 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
5979 }
5980 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5981 Visit(TL.getUnqualifiedLoc());
5982 }
5983 // Allow to fill pointee's type locations, e.g.,
5984 // int __attr * __attr * __attr *p;
5985 void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); }
5986 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5987 if (DS.getTypeSpecType() == TST_typename) {
5988 TypeSourceInfo *TInfo = nullptr;
5990 if (TInfo) {
5991 TL.copy(TInfo->getTypeLoc().castAs<TypedefTypeLoc>());
5992 return;
5993 }
5994 }
5995 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
5996 ? DS.getTypeSpecTypeLoc()
5997 : SourceLocation(),
6000 }
6001 void VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6002 if (DS.getTypeSpecType() == TST_typename) {
6003 TypeSourceInfo *TInfo = nullptr;
6005 if (TInfo) {
6006 TL.copy(TInfo->getTypeLoc().castAs<UnresolvedUsingTypeLoc>());
6007 return;
6008 }
6009 }
6010 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6011 ? DS.getTypeSpecTypeLoc()
6012 : SourceLocation(),
6015 }
6016 void VisitUsingTypeLoc(UsingTypeLoc TL) {
6017 if (DS.getTypeSpecType() == TST_typename) {
6018 TypeSourceInfo *TInfo = nullptr;
6020 if (TInfo) {
6021 TL.copy(TInfo->getTypeLoc().castAs<UsingTypeLoc>());
6022 return;
6023 }
6024 }
6025 TL.set(TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6026 ? DS.getTypeSpecTypeLoc()
6027 : SourceLocation(),
6030 }
6031 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6033 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
6034 // addition field. What we have is good enough for display of location
6035 // of 'fixit' on interface name.
6036 TL.setNameEndLoc(DS.getEndLoc());
6037 }
6038 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6039 TypeSourceInfo *RepTInfo = nullptr;
6040 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6041 TL.copy(RepTInfo->getTypeLoc());
6042 }
6043 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6044 TypeSourceInfo *RepTInfo = nullptr;
6045 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6046 TL.copy(RepTInfo->getTypeLoc());
6047 }
6048 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
6049 TypeSourceInfo *TInfo = nullptr;
6051
6052 // If we got no declarator info from previous Sema routines,
6053 // just fill with the typespec loc.
6054 if (!TInfo) {
6055 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
6056 return;
6057 }
6058
6059 TypeLoc OldTL = TInfo->getTypeLoc();
6060 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
6061 assert(TL.getRAngleLoc() ==
6062 OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
6063 }
6064 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6069 }
6070 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6075 assert(DS.getRepAsType());
6076 TypeSourceInfo *TInfo = nullptr;
6078 TL.setUnmodifiedTInfo(TInfo);
6079 }
6080 void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6084 }
6085 void VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
6088 }
6089 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6090 assert(DS.isTransformTypeTrait(DS.getTypeSpecType()));
6093 assert(DS.getRepAsType());
6094 TypeSourceInfo *TInfo = nullptr;
6096 TL.setUnderlyingTInfo(TInfo);
6097 }
6098 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6099 // By default, use the source location of the type specifier.
6101 if (TL.needsExtraLocalData()) {
6102 // Set info for the written builtin specifiers.
6104 // Try to have a meaningful source location.
6105 if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified)
6107 if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified)
6109 }
6110 }
6111 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6112 assert(DS.getTypeSpecType() == TST_typename);
6113 TypeSourceInfo *TInfo = nullptr;
6115 assert(TInfo);
6116 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
6117 }
6118 void VisitAutoTypeLoc(AutoTypeLoc TL) {
6119 assert(DS.getTypeSpecType() == TST_auto ||
6126 if (!DS.isConstrainedAuto())
6127 return;
6128 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
6129 if (!TemplateId)
6130 return;
6131
6132 NestedNameSpecifierLoc NNS =
6133 (DS.getTypeSpecScope().isNotEmpty()
6135 : NestedNameSpecifierLoc());
6136 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
6137 TemplateId->RAngleLoc);
6138 if (TemplateId->NumArgs > 0) {
6139 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6140 TemplateId->NumArgs);
6141 SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
6142 }
6143 DeclarationNameInfo DNI = Context.getNameForTemplate(
6144 TL.getTypePtr()->getTypeConstraintConcept(),
6145 TemplateId->TemplateNameLoc);
6146
6147 NamedDecl *FoundDecl;
6148 if (auto TN = TemplateId->Template.get();
6149 UsingShadowDecl *USD = TN.getAsUsingShadowDecl())
6150 FoundDecl = cast<NamedDecl>(USD);
6151 else
6152 FoundDecl = cast_if_present<NamedDecl>(TN.getAsTemplateDecl());
6153
6154 auto *CR = ConceptReference::Create(
6155 Context, NNS, TemplateId->TemplateKWLoc, DNI, FoundDecl,
6156 /*NamedDecl=*/TL.getTypePtr()->getTypeConstraintConcept(),
6157 ASTTemplateArgumentListInfo::Create(Context, TemplateArgsInfo));
6158 TL.setConceptReference(CR);
6159 }
6160 void VisitDeducedTemplateSpecializationTypeLoc(
6161 DeducedTemplateSpecializationTypeLoc TL) {
6162 assert(DS.getTypeSpecType() == TST_typename);
6163 TypeSourceInfo *TInfo = nullptr;
6165 assert(TInfo);
6166 TL.copy(
6167 TInfo->getTypeLoc().castAs<DeducedTemplateSpecializationTypeLoc>());
6168 }
6169 void VisitTagTypeLoc(TagTypeLoc TL) {
6170 if (DS.getTypeSpecType() == TST_typename) {
6171 TypeSourceInfo *TInfo = nullptr;
6173 if (TInfo) {
6174 TL.copy(TInfo->getTypeLoc().castAs<TagTypeLoc>());
6175 return;
6176 }
6177 }
6178 TL.setElaboratedKeywordLoc(TL.getTypePtr()->getKeyword() !=
6179 ElaboratedTypeKeyword::None
6180 ? DS.getTypeSpecTypeLoc()
6181 : SourceLocation());
6184 }
6185 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6186 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
6187 // or an _Atomic qualifier.
6191
6192 TypeSourceInfo *TInfo = nullptr;
6194 assert(TInfo);
6196 } else {
6197 TL.setKWLoc(DS.getAtomicSpecLoc());
6198 // No parens, to indicate this was spelled as an _Atomic qualifier.
6199 TL.setParensRange(SourceRange());
6200 Visit(TL.getValueLoc());
6201 }
6202 }
6203
6204 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6206
6207 TypeSourceInfo *TInfo = nullptr;
6210 }
6211
6212 void VisitExtIntTypeLoc(BitIntTypeLoc TL) {
6214 }
6215
6216 void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) {
6218 }
6219
6220 void VisitTypeLoc(TypeLoc TL) {
6221 // FIXME: add other typespec types and change this to an assert.
6222 TL.initialize(Context, DS.getTypeSpecTypeLoc());
6223 }
6224 };
6225
6226 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
6227 ASTContext &Context;
6228 TypeProcessingState &State;
6229 const DeclaratorChunk &Chunk;
6230
6231 public:
6232 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
6233 const DeclaratorChunk &Chunk)
6234 : Context(Context), State(State), Chunk(Chunk) {}
6235
6236 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6237 llvm_unreachable("qualified type locs not expected here!");
6238 }
6239 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6240 llvm_unreachable("decayed type locs not expected here!");
6241 }
6242 void VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
6243 llvm_unreachable("array parameter type locs not expected here!");
6244 }
6245
6246 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6247 fillAttributedTypeLoc(TL, State);
6248 }
6249 void VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
6250 // nothing
6251 }
6252 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6253 // nothing
6254 }
6255 void VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
6256 // nothing
6257 }
6258 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6259 // nothing
6260 }
6261 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6262 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
6263 TL.setCaretLoc(Chunk.Loc);
6264 }
6265 void VisitPointerTypeLoc(PointerTypeLoc TL) {
6266 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6267 TL.setStarLoc(Chunk.Loc);
6268 }
6269 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6270 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6271 TL.setStarLoc(Chunk.Loc);
6272 }
6273 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6274 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
6275 TL.setStarLoc(Chunk.Mem.StarLoc);
6276 TL.setQualifierLoc(Chunk.Mem.Scope().getWithLocInContext(Context));
6277 }
6278 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6279 assert(Chunk.Kind == DeclaratorChunk::Reference);
6280 // 'Amp' is misleading: this might have been originally
6281 /// spelled with AmpAmp.
6282 TL.setAmpLoc(Chunk.Loc);
6283 }
6284 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6285 assert(Chunk.Kind == DeclaratorChunk::Reference);
6286 assert(!Chunk.Ref.LValueRef);
6287 TL.setAmpAmpLoc(Chunk.Loc);
6288 }
6289 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
6290 assert(Chunk.Kind == DeclaratorChunk::Array);
6291 TL.setLBracketLoc(Chunk.Loc);
6292 TL.setRBracketLoc(Chunk.EndLoc);
6293 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
6294 }
6295 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6296 assert(Chunk.Kind == DeclaratorChunk::Function);
6297 TL.setLocalRangeBegin(Chunk.Loc);
6298 TL.setLocalRangeEnd(Chunk.EndLoc);
6299
6300 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
6301 TL.setLParenLoc(FTI.getLParenLoc());
6302 TL.setRParenLoc(FTI.getRParenLoc());
6303 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
6304 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
6305 TL.setParam(tpi++, Param);
6306 }
6308 }
6309 void VisitParenTypeLoc(ParenTypeLoc TL) {
6310 assert(Chunk.Kind == DeclaratorChunk::Paren);
6311 TL.setLParenLoc(Chunk.Loc);
6312 TL.setRParenLoc(Chunk.EndLoc);
6313 }
6314 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6315 assert(Chunk.Kind == DeclaratorChunk::Pipe);
6316 TL.setKWLoc(Chunk.Loc);
6317 }
6318 void VisitBitIntTypeLoc(BitIntTypeLoc TL) {
6319 TL.setNameLoc(Chunk.Loc);
6320 }
6321 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6322 TL.setExpansionLoc(Chunk.Loc);
6323 }
6324 void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); }
6325 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) {
6326 TL.setNameLoc(Chunk.Loc);
6327 }
6328 void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6329 TL.setNameLoc(Chunk.Loc);
6330 }
6331 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6332 fillAtomicQualLoc(TL, Chunk);
6333 }
6334 void
6335 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) {
6336 TL.setNameLoc(Chunk.Loc);
6337 }
6338 void VisitMatrixTypeLoc(MatrixTypeLoc TL) {
6339 fillMatrixTypeLoc(TL, Chunk.getAttrs());
6340 }
6341
6342 void VisitTypeLoc(TypeLoc TL) {
6343 llvm_unreachable("unsupported TypeLoc kind in declarator!");
6344 }
6345 };
6346} // end anonymous namespace
6347
6351 for (const ParsedAttributesView *Attrs : AttrLists) {
6352 for (const ParsedAttr &AL : *Attrs) {
6353 // Skip invalid or malformed attributes; they did not produce a type.
6354 if (AL.getKind() != ParsedAttr::AT_AddressSpace || AL.isInvalid() ||
6355 AL.getNumArgs() != 1 || !AL.isArgExpr(0))
6356 continue;
6357 DASTL.setAttrNameLoc(AL.getLoc());
6358 DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
6360 return;
6361 }
6362 }
6363
6364 llvm_unreachable(
6365 "no address_space attribute found at the expected location!");
6366}
6367
6368/// Create and instantiate a TypeSourceInfo with type source information.
6369///
6370/// \param T QualType referring to the type as written in source code.
6371///
6372/// \param ReturnTypeInfo For declarators whose return type does not show
6373/// up in the normal place in the declaration specifiers (such as a C++
6374/// conversion function), this pointer will refer to a type source information
6375/// for that return type.
6376static TypeSourceInfo *
6377GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
6378 QualType T, TypeSourceInfo *ReturnTypeInfo) {
6379 Sema &S = State.getSema();
6380 Declarator &D = State.getDeclarator();
6381
6383 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
6384
6385 // Handle parameter packs whose type is a pack expansion.
6387 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
6388 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6389 }
6390
6391 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6392 // Microsoft property fields can have multiple sizeless array chunks
6393 // (i.e. int x[][][]). Don't create more than one level of incomplete array.
6394 if (CurrTL.getTypeLocClass() == TypeLoc::IncompleteArray && e != 1 &&
6396 continue;
6397
6398 // An AtomicTypeLoc might be produced by an atomic qualifier in this
6399 // declarator chunk.
6400 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
6402 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
6403 }
6404
6405 bool HasDesugaredTypeLoc = true;
6406 while (HasDesugaredTypeLoc) {
6407 switch (CurrTL.getTypeLocClass()) {
6408 case TypeLoc::MacroQualified: {
6409 auto TL = CurrTL.castAs<MacroQualifiedTypeLoc>();
6410 TL.setExpansionLoc(
6411 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6412 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6413 break;
6414 }
6415
6416 case TypeLoc::Attributed: {
6417 auto TL = CurrTL.castAs<AttributedTypeLoc>();
6418 fillAttributedTypeLoc(TL, State);
6419 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6420 break;
6421 }
6422
6423 case TypeLoc::Adjusted:
6424 case TypeLoc::BTFTagAttributed: {
6425 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6426 break;
6427 }
6428
6429 case TypeLoc::DependentAddressSpace: {
6430 auto TL = CurrTL.castAs<DependentAddressSpaceTypeLoc>();
6431 // An attribute written after the declarator-id appertains to the
6432 // declared entity, not to a chunk, so every attribute list of the
6433 // declarator has to be searched.
6435 &D.getAttributes(),
6438 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
6439 break;
6440 }
6441
6442 default:
6443 HasDesugaredTypeLoc = false;
6444 break;
6445 }
6446 }
6447
6448 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
6449 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6450 }
6451
6452 // If we have different source information for the return type, use
6453 // that. This really only applies to C++ conversion functions.
6454 if (ReturnTypeInfo) {
6455 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
6456 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
6457 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
6458 } else {
6459 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL);
6460 }
6461
6462 return TInfo;
6463}
6464
6465/// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
6467 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6468 // and Sema during declaration parsing. Try deallocating/caching them when
6469 // it's appropriate, instead of allocating them and keeping them around.
6470 LocInfoType *LocT = (LocInfoType *)BumpAlloc.Allocate(sizeof(LocInfoType),
6471 alignof(LocInfoType));
6472 new (LocT) LocInfoType(T, TInfo);
6473 assert(LocT->getTypeClass() != T->getTypeClass() &&
6474 "LocInfoType's TypeClass conflicts with an existing Type class");
6475 return ParsedType::make(QualType(LocT, 0));
6476}
6477
6479 const PrintingPolicy &Policy) const {
6480 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6481 " was used directly instead of getting the QualType through"
6482 " GetTypeFromParser");
6483}
6484
6486 // C99 6.7.6: Type names have no identifier. This is already validated by
6487 // the parser.
6488 assert(D.getIdentifier() == nullptr &&
6489 "Type name should have no identifier!");
6490
6492 QualType T = TInfo->getType();
6493 if (D.isInvalidType())
6494 return true;
6495
6496 // Make sure there are no unused decl attributes on the declarator.
6497 // We don't want to do this for ObjC parameters because we're going
6498 // to apply them to the actual parameter declaration.
6499 // Likewise, we don't want to do this for alias declarations, because
6500 // we are actually going to build a declaration from this eventually.
6505
6506 if (getLangOpts().CPlusPlus) {
6507 // Check that there are no default arguments (C++ only).
6509 }
6510
6511 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
6512 const AutoType *AT = TL.getTypePtr();
6513 CheckConstrainedAuto(AT, TL.getConceptNameLoc());
6514 }
6515 return CreateParsedType(T, TInfo);
6516}
6517
6518//===----------------------------------------------------------------------===//
6519// Type Attribute Processing
6520//===----------------------------------------------------------------------===//
6521
6522/// Build an AddressSpace index from a constant expression and diagnose any
6523/// errors related to invalid address_spaces. Returns true on successfully
6524/// building an AddressSpace index.
6525static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
6526 const Expr *AddrSpace,
6527 SourceLocation AttrLoc) {
6528 if (!AddrSpace->isValueDependent()) {
6529 std::optional<llvm::APSInt> OptAddrSpace =
6530 AddrSpace->getIntegerConstantExpr(S.Context);
6531 if (!OptAddrSpace) {
6532 S.Diag(AttrLoc, diag::err_attribute_argument_type)
6533 << "'address_space'" << AANT_ArgumentIntegerConstant
6534 << AddrSpace->getSourceRange();
6535 return false;
6536 }
6537 llvm::APSInt &addrSpace = *OptAddrSpace;
6538
6539 // Bounds checking.
6540 if (addrSpace.isSigned()) {
6541 if (addrSpace.isNegative()) {
6542 S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
6543 << AddrSpace->getSourceRange();
6544 return false;
6545 }
6546 addrSpace.setIsSigned(false);
6547 }
6548
6549 llvm::APSInt max(addrSpace.getBitWidth());
6550 max =
6552
6553 if (addrSpace > max) {
6554 S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
6555 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
6556 return false;
6557 }
6558
6559 ASIdx =
6560 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
6561 return true;
6562 }
6563
6564 // Default value for DependentAddressSpaceTypes
6565 ASIdx = LangAS::Default;
6566 return true;
6567}
6568
6570 SourceLocation AttrLoc) {
6571 if (!AddrSpace->isValueDependent()) {
6572 if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
6573 AttrLoc))
6574 return QualType();
6575
6576 return Context.getAddrSpaceQualType(T, ASIdx);
6577 }
6578
6579 // A check with similar intentions as checking if a type already has an
6580 // address space except for on a dependent types, basically if the
6581 // current type is already a DependentAddressSpaceType then its already
6582 // lined up to have another address space on it and we can't have
6583 // multiple address spaces on the one pointer indirection
6584 if (T->getAs<DependentAddressSpaceType>()) {
6585 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
6586 return QualType();
6587 }
6588
6589 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
6590}
6591
6593 SourceLocation AttrLoc) {
6594 LangAS ASIdx;
6595 if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
6596 return QualType();
6597 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
6598}
6599
6601 TypeProcessingState &State) {
6602 Sema &S = State.getSema();
6603
6604 // This attribute is only supported in C.
6605 // FIXME: we should implement checkCommonAttributeFeatures() in SemaAttr.cpp
6606 // such that it handles type attributes, and then call that from
6607 // processTypeAttrs() instead of one-off checks like this.
6608 if (!Attr.diagnoseLangOpts(S)) {
6609 Attr.setInvalid();
6610 return;
6611 }
6612
6613 // Check the number of attribute arguments.
6614 if (Attr.getNumArgs() != 1) {
6615 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6616 << Attr << 1;
6617 Attr.setInvalid();
6618 return;
6619 }
6620
6621 // Ensure the argument is a string.
6622 auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6623 if (!StrLiteral) {
6624 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6626 Attr.setInvalid();
6627 return;
6628 }
6629
6630 ASTContext &Ctx = S.Context;
6631 StringRef BTFTypeTag = StrLiteral->getString();
6632 Type = State.getBTFTagAttributedType(
6633 ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type);
6634}
6635
6636/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6637/// specified type. The attribute contains 1 argument, the id of the address
6638/// space for the type.
6640 const ParsedAttr &Attr,
6641 TypeProcessingState &State) {
6642 Sema &S = State.getSema();
6643
6644 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6645 // qualified by an address-space qualifier."
6646 if (Type->isFunctionType()) {
6647 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
6648 Attr.setInvalid();
6649 return;
6650 }
6651
6652 LangAS ASIdx;
6653 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
6654
6655 // Check the attribute arguments.
6656 if (Attr.getNumArgs() != 1) {
6657 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
6658 << 1;
6659 Attr.setInvalid();
6660 return;
6661 }
6662
6663 Expr *ASArgExpr = Attr.getArgAsExpr(0);
6664 LangAS ASIdx;
6665 if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
6666 Attr.setInvalid();
6667 return;
6668 }
6669
6670 ASTContext &Ctx = S.Context;
6671 auto *ASAttr =
6672 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
6673
6674 // If the expression is not value dependent (not templated), then we can
6675 // apply the address space qualifiers just to the equivalent type.
6676 // Otherwise, we make an AttributedType with the modified and equivalent
6677 // type the same, and wrap it in a DependentAddressSpaceType. When this
6678 // dependent type is resolved, the qualifier is added to the equivalent type
6679 // later.
6680 QualType T;
6681 if (!ASArgExpr->isValueDependent()) {
6682 QualType EquivType =
6683 S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
6684 if (EquivType.isNull()) {
6685 Attr.setInvalid();
6686 return;
6687 }
6688 T = State.getAttributedType(ASAttr, Type, EquivType);
6689 } else {
6690 T = State.getAttributedType(ASAttr, Type, Type);
6691 T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
6692 }
6693
6694 if (!T.isNull())
6695 Type = T;
6696 else
6697 Attr.setInvalid();
6698 } else {
6699 // The keyword-based type attributes imply which address space to use.
6700 ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS()
6701 : Attr.asOpenCLLangAS();
6702 if (S.getLangOpts().HLSL)
6703 ASIdx = Attr.asHLSLLangAS();
6704
6705 if (ASIdx == LangAS::Default)
6706 llvm_unreachable("Invalid address space");
6707
6708 if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
6709 Attr.getLoc())) {
6710 Attr.setInvalid();
6711 return;
6712 }
6713
6715 }
6716}
6717
6719 TypeProcessingState &State) {
6720 Sema &S = State.getSema();
6721
6722 // Check for -fexperimental-overflow-behavior-types
6723 if (!S.getLangOpts().OverflowBehaviorTypes) {
6724 S.Diag(Attr.getLoc(), diag::warn_overflow_behavior_attribute_disabled)
6725 << Attr << 1;
6726 Attr.setInvalid();
6727 return;
6728 }
6729
6730 // Check the number of attribute arguments.
6731 if (Attr.getNumArgs() != 1) {
6732 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6733 << Attr << 1;
6734 Attr.setInvalid();
6735 return;
6736 }
6737
6738 // Check that the underlying type is an integer type
6739 if (!Type->isIntegerType()) {
6740 S.Diag(Attr.getLoc(), diag::err_overflow_behavior_non_integer_type)
6741 << Attr << Type.getAsString() << 0; // 0 for attribute
6742 Attr.setInvalid();
6743 return;
6744 }
6745
6746 StringRef KindName = "";
6747 IdentifierInfo *Ident = nullptr;
6748
6749 if (Attr.isArgIdent(0)) {
6750 Ident = Attr.getArgAsIdent(0)->getIdentifierInfo();
6751 KindName = Ident->getName();
6752 }
6753
6754 // Support identifier or string argument types. Failure to provide one of
6755 // these two types results in a diagnostic that hints towards using string
6756 // arguments (either "wrap" or "trap") as this is the most common use
6757 // pattern.
6758 if (!Ident) {
6759 auto *Str = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6760 if (Str)
6761 KindName = Str->getString();
6762 else {
6763 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6765 Attr.setInvalid();
6766 return;
6767 }
6768 }
6769
6770 OverflowBehaviorType::OverflowBehaviorKind Kind;
6771 if (KindName == "wrap") {
6772 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
6773 } else if (KindName == "trap") {
6774 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
6775 } else {
6776 S.Diag(Attr.getLoc(), diag::err_overflow_behavior_unknown_ident)
6777 << KindName << Attr;
6778 Attr.setInvalid();
6779 return;
6780 }
6781
6782 // Check for mixed specifier/attribute usage
6783 const DeclSpec &DS = State.getDeclarator().getDeclSpec();
6784 if (DS.isWrapSpecified() || DS.isTrapSpecified()) {
6785 // We have both specifier and attribute on the same type. If
6786 // OverflowBehaviorKinds are the same we can just warn.
6787 OverflowBehaviorType::OverflowBehaviorKind SpecifierKind =
6788 DS.isWrapSpecified() ? OverflowBehaviorType::OverflowBehaviorKind::Wrap
6789 : OverflowBehaviorType::OverflowBehaviorKind::Trap;
6790
6791 if (SpecifierKind != Kind) {
6792 StringRef SpecifierName = DS.isWrapSpecified() ? "wrap" : "trap";
6793 S.Diag(Attr.getLoc(), diag::err_conflicting_overflow_behaviors)
6794 << 1 << SpecifierName << KindName;
6795 Attr.setInvalid();
6796 return;
6797 }
6798 S.Diag(Attr.getLoc(), diag::warn_redundant_overflow_behaviors_mixed)
6799 << KindName;
6800 Attr.setInvalid();
6801 return;
6802 }
6803
6804 // Check for conflicting overflow behavior attributes
6805 if (const auto *ExistingOBT = Type->getAs<OverflowBehaviorType>()) {
6806 OverflowBehaviorType::OverflowBehaviorKind ExistingKind =
6807 ExistingOBT->getBehaviorKind();
6808 if (ExistingKind != Kind) {
6809 S.Diag(Attr.getLoc(), diag::err_conflicting_overflow_behaviors) << 0;
6810 if (Kind == OverflowBehaviorType::OverflowBehaviorKind::Trap) {
6811 Type = State.getOverflowBehaviorType(Kind,
6812 ExistingOBT->getUnderlyingType());
6813 }
6814 return;
6815 }
6816 } else {
6817 Type = State.getOverflowBehaviorType(Kind, Type);
6818 }
6819}
6820
6821/// handleObjCOwnershipTypeAttr - Process an objc_ownership
6822/// attribute on the specified type.
6823///
6824/// Returns 'true' if the attribute was handled.
6825static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6827 bool NonObjCPointer = false;
6828
6829 if (!type->isDependentType() && !type->isUndeducedType()) {
6830 if (const PointerType *ptr = type->getAs<PointerType>()) {
6831 QualType pointee = ptr->getPointeeType();
6832 if (pointee->isObjCRetainableType() || pointee->isPointerType())
6833 return false;
6834 // It is important not to lose the source info that there was an attribute
6835 // applied to non-objc pointer. We will create an attributed type but
6836 // its type will be the same as the original type.
6837 NonObjCPointer = true;
6838 } else if (!type->isObjCRetainableType()) {
6839 return false;
6840 }
6841
6842 // Don't accept an ownership attribute in the declspec if it would
6843 // just be the return type of a block pointer.
6844 if (state.isProcessingDeclSpec()) {
6845 Declarator &D = state.getDeclarator();
6847 /*onlyBlockPointers=*/true))
6848 return false;
6849 }
6850 }
6851
6852 Sema &S = state.getSema();
6853 SourceLocation AttrLoc = attr.getLoc();
6854 if (AttrLoc.isMacroID())
6855 AttrLoc =
6857
6858 if (!attr.isArgIdent(0)) {
6859 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
6861 attr.setInvalid();
6862 return true;
6863 }
6864
6865 IdentifierInfo *II = attr.getArgAsIdent(0)->getIdentifierInfo();
6866 Qualifiers::ObjCLifetime lifetime;
6867 if (II->isStr("none"))
6869 else if (II->isStr("strong"))
6870 lifetime = Qualifiers::OCL_Strong;
6871 else if (II->isStr("weak"))
6872 lifetime = Qualifiers::OCL_Weak;
6873 else if (II->isStr("autoreleasing"))
6875 else {
6876 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II;
6877 attr.setInvalid();
6878 return true;
6879 }
6880
6881 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6882 // outside of ARC mode.
6883 if (!S.getLangOpts().ObjCAutoRefCount &&
6884 lifetime != Qualifiers::OCL_Weak &&
6885 lifetime != Qualifiers::OCL_ExplicitNone) {
6886 return true;
6887 }
6888
6889 SplitQualType underlyingType = type.split();
6890
6891 // Check for redundant/conflicting ownership qualifiers.
6892 if (Qualifiers::ObjCLifetime previousLifetime
6893 = type.getQualifiers().getObjCLifetime()) {
6894 // If it's written directly, that's an error.
6896 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
6897 << type;
6898 return true;
6899 }
6900
6901 // Otherwise, if the qualifiers actually conflict, pull sugar off
6902 // and remove the ObjCLifetime qualifiers.
6903 if (previousLifetime != lifetime) {
6904 // It's possible to have multiple local ObjCLifetime qualifiers. We
6905 // can't stop after we reach a type that is directly qualified.
6906 const Type *prevTy = nullptr;
6907 while (!prevTy || prevTy != underlyingType.Ty) {
6908 prevTy = underlyingType.Ty;
6909 underlyingType = underlyingType.getSingleStepDesugaredType();
6910 }
6911 underlyingType.Quals.removeObjCLifetime();
6912 }
6913 }
6914
6915 underlyingType.Quals.addObjCLifetime(lifetime);
6916
6917 if (NonObjCPointer) {
6918 StringRef name = attr.getAttrName()->getName();
6919 switch (lifetime) {
6922 break;
6923 case Qualifiers::OCL_Strong: name = "__strong"; break;
6924 case Qualifiers::OCL_Weak: name = "__weak"; break;
6925 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
6926 }
6927 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
6929 }
6930
6931 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
6932 // because having both 'T' and '__unsafe_unretained T' exist in the type
6933 // system causes unfortunate widespread consistency problems. (For example,
6934 // they're not considered compatible types, and we mangle them identicially
6935 // as template arguments.) These problems are all individually fixable,
6936 // but it's easier to just not add the qualifier and instead sniff it out
6937 // in specific places using isObjCInertUnsafeUnretainedType().
6938 //
6939 // Doing this does means we miss some trivial consistency checks that
6940 // would've triggered in ARC, but that's better than trying to solve all
6941 // the coexistence problems with __unsafe_unretained.
6942 if (!S.getLangOpts().ObjCAutoRefCount &&
6943 lifetime == Qualifiers::OCL_ExplicitNone) {
6944 type = state.getAttributedType(
6946 type, type);
6947 return true;
6948 }
6949
6950 QualType origType = type;
6951 if (!NonObjCPointer)
6952 type = S.Context.getQualifiedType(underlyingType);
6953
6954 // If we have a valid source location for the attribute, use an
6955 // AttributedType instead.
6956 if (AttrLoc.isValid()) {
6957 type = state.getAttributedType(::new (S.Context)
6958 ObjCOwnershipAttr(S.Context, attr, II),
6959 origType, type);
6960 }
6961
6962 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
6963 unsigned diagnostic, QualType type) {
6968 diagnostic, type, /*ignored*/ 0));
6969 } else {
6970 S.Diag(loc, diagnostic);
6971 }
6972 };
6973
6974 // Sometimes, __weak isn't allowed.
6975 if (lifetime == Qualifiers::OCL_Weak &&
6976 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
6977
6978 // Use a specialized diagnostic if the runtime just doesn't support them.
6979 unsigned diagnostic =
6980 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
6981 : diag::err_arc_weak_no_runtime);
6982
6983 // In any case, delay the diagnostic until we know what we're parsing.
6984 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
6985
6986 attr.setInvalid();
6987 return true;
6988 }
6989
6990 // Forbid __weak for class objects marked as
6991 // objc_arc_weak_reference_unavailable
6992 if (lifetime == Qualifiers::OCL_Weak) {
6993 if (const ObjCObjectPointerType *ObjT =
6994 type->getAs<ObjCObjectPointerType>()) {
6995 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
6996 if (Class->isArcWeakrefUnavailable()) {
6997 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
6998 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
6999 diag::note_class_declared);
7000 }
7001 }
7002 }
7003 }
7004
7005 return true;
7006}
7007
7008/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
7009/// attribute on the specified type. Returns true to indicate that
7010/// the attribute was handled, false to indicate that the type does
7011/// not permit the attribute.
7012static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7013 QualType &type) {
7014 Sema &S = state.getSema();
7015
7016 // Delay if this isn't some kind of pointer.
7017 if (!type->isPointerType() &&
7018 !type->isObjCObjectPointerType() &&
7019 !type->isBlockPointerType())
7020 return false;
7021
7022 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
7023 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
7024 attr.setInvalid();
7025 return true;
7026 }
7027
7028 // Check the attribute arguments.
7029 if (!attr.isArgIdent(0)) {
7030 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
7032 attr.setInvalid();
7033 return true;
7034 }
7035 Qualifiers::GC GCAttr;
7036 if (attr.getNumArgs() > 1) {
7037 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
7038 << 1;
7039 attr.setInvalid();
7040 return true;
7041 }
7042
7043 IdentifierInfo *II = attr.getArgAsIdent(0)->getIdentifierInfo();
7044 if (II->isStr("weak"))
7045 GCAttr = Qualifiers::Weak;
7046 else if (II->isStr("strong"))
7047 GCAttr = Qualifiers::Strong;
7048 else {
7049 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
7050 << attr << II;
7051 attr.setInvalid();
7052 return true;
7053 }
7054
7055 QualType origType = type;
7056 type = S.Context.getObjCGCQualType(origType, GCAttr);
7057
7058 // Make an attributed type to preserve the source information.
7059 if (attr.getLoc().isValid())
7060 type = state.getAttributedType(
7061 ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type);
7062
7063 return true;
7064}
7065
7066namespace {
7067 /// A helper class to unwrap a type down to a function for the
7068 /// purposes of applying attributes there.
7069 ///
7070 /// Use:
7071 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
7072 /// if (unwrapped.isFunctionType()) {
7073 /// const FunctionType *fn = unwrapped.get();
7074 /// // change fn somehow
7075 /// T = unwrapped.wrap(fn);
7076 /// }
7077 struct FunctionTypeUnwrapper {
7078 enum WrapKind {
7079 Desugar,
7080 Attributed,
7081 Parens,
7082 Array,
7083 Pointer,
7084 BlockPointer,
7085 Reference,
7086 MemberPointer,
7087 MacroQualified,
7088 };
7089
7090 QualType Original;
7091 const FunctionType *Fn;
7092 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
7093
7094 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
7095 while (true) {
7096 const Type *Ty = T.getTypePtr();
7097 if (isa<FunctionType>(Ty)) {
7098 Fn = cast<FunctionType>(Ty);
7099 return;
7100 } else if (isa<ParenType>(Ty)) {
7101 T = cast<ParenType>(Ty)->getInnerType();
7102 Stack.push_back(Parens);
7103 } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) ||
7105 T = cast<ArrayType>(Ty)->getElementType();
7106 Stack.push_back(Array);
7107 } else if (isa<PointerType>(Ty)) {
7108 T = cast<PointerType>(Ty)->getPointeeType();
7109 Stack.push_back(Pointer);
7110 } else if (isa<BlockPointerType>(Ty)) {
7111 T = cast<BlockPointerType>(Ty)->getPointeeType();
7112 Stack.push_back(BlockPointer);
7113 } else if (isa<MemberPointerType>(Ty)) {
7114 T = cast<MemberPointerType>(Ty)->getPointeeType();
7115 Stack.push_back(MemberPointer);
7116 } else if (isa<ReferenceType>(Ty)) {
7117 T = cast<ReferenceType>(Ty)->getPointeeType();
7118 Stack.push_back(Reference);
7119 } else if (isa<AttributedType>(Ty)) {
7120 T = cast<AttributedType>(Ty)->getEquivalentType();
7121 Stack.push_back(Attributed);
7122 } else if (isa<MacroQualifiedType>(Ty)) {
7123 T = cast<MacroQualifiedType>(Ty)->getUnderlyingType();
7124 Stack.push_back(MacroQualified);
7125 } else {
7126 const Type *DTy = Ty->getUnqualifiedDesugaredType();
7127 if (Ty == DTy) {
7128 Fn = nullptr;
7129 return;
7130 }
7131
7132 T = QualType(DTy, 0);
7133 Stack.push_back(Desugar);
7134 }
7135 }
7136 }
7137
7138 bool isFunctionType() const { return (Fn != nullptr); }
7139 const FunctionType *get() const { return Fn; }
7140
7141 QualType wrap(Sema &S, const FunctionType *New) {
7142 // If T wasn't modified from the unwrapped type, do nothing.
7143 if (New == get()) return Original;
7144
7145 Fn = New;
7146 return wrap(S.Context, Original, 0);
7147 }
7148
7149 private:
7150 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
7151 if (I == Stack.size())
7152 return C.getQualifiedType(Fn, Old.getQualifiers());
7153
7154 // Build up the inner type, applying the qualifiers from the old
7155 // type to the new type.
7156 SplitQualType SplitOld = Old.split();
7157
7158 // As a special case, tail-recurse if there are no qualifiers.
7159 if (SplitOld.Quals.empty())
7160 return wrap(C, SplitOld.Ty, I);
7161 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
7162 }
7163
7164 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
7165 if (I == Stack.size()) return QualType(Fn, 0);
7166
7167 switch (static_cast<WrapKind>(Stack[I++])) {
7168 case Desugar:
7169 // This is the point at which we potentially lose source
7170 // information.
7171 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
7172
7173 case Attributed:
7174 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
7175
7176 case Parens: {
7177 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
7178 return C.getParenType(New);
7179 }
7180
7181 case MacroQualified:
7182 return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I);
7183
7184 case Array: {
7185 if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) {
7186 QualType New = wrap(C, CAT->getElementType(), I);
7187 return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(),
7188 CAT->getSizeModifier(),
7189 CAT->getIndexTypeCVRQualifiers());
7190 }
7191
7192 if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) {
7193 QualType New = wrap(C, VAT->getElementType(), I);
7194 return C.getVariableArrayType(New, VAT->getSizeExpr(),
7195 VAT->getSizeModifier(),
7196 VAT->getIndexTypeCVRQualifiers());
7197 }
7198
7199 const auto *IAT = cast<IncompleteArrayType>(Old);
7200 QualType New = wrap(C, IAT->getElementType(), I);
7201 return C.getIncompleteArrayType(New, IAT->getSizeModifier(),
7202 IAT->getIndexTypeCVRQualifiers());
7203 }
7204
7205 case Pointer: {
7206 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
7207 return C.getPointerType(New);
7208 }
7209
7210 case BlockPointer: {
7211 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
7212 return C.getBlockPointerType(New);
7213 }
7214
7215 case MemberPointer: {
7216 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
7217 QualType New = wrap(C, OldMPT->getPointeeType(), I);
7218 return C.getMemberPointerType(New, OldMPT->getQualifier(),
7219 OldMPT->getMostRecentCXXRecordDecl());
7220 }
7221
7222 case Reference: {
7223 const ReferenceType *OldRef = cast<ReferenceType>(Old);
7224 QualType New = wrap(C, OldRef->getPointeeType(), I);
7225 if (isa<LValueReferenceType>(OldRef))
7226 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
7227 else
7228 return C.getRValueReferenceType(New);
7229 }
7230 }
7231
7232 llvm_unreachable("unknown wrapping kind");
7233 }
7234 };
7235} // end anonymous namespace
7236
7237static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
7238 ParsedAttr &PAttr, QualType &Type) {
7239 Sema &S = State.getSema();
7240
7241 Attr *A;
7242 switch (PAttr.getKind()) {
7243 default: llvm_unreachable("Unknown attribute kind");
7244 case ParsedAttr::AT_Ptr32:
7246 break;
7247 case ParsedAttr::AT_Ptr64:
7249 break;
7250 case ParsedAttr::AT_SPtr:
7251 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
7252 break;
7253 case ParsedAttr::AT_UPtr:
7254 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
7255 break;
7256 }
7257
7258 std::bitset<attr::LastAttr> Attrs;
7259 QualType Desugared = Type;
7260 for (;;) {
7261 if (const TypedefType *TT = dyn_cast<TypedefType>(Desugared)) {
7262 Desugared = TT->desugar();
7263 continue;
7264 }
7265 const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
7266 if (!AT)
7267 break;
7268 Attrs[AT->getAttrKind()] = true;
7269 Desugared = AT->getModifiedType();
7270 }
7271
7272 // You cannot specify duplicate type attributes, so if the attribute has
7273 // already been applied, flag it.
7274 attr::Kind NewAttrKind = A->getKind();
7275 if (Attrs[NewAttrKind]) {
7276 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7277 return true;
7278 }
7279 Attrs[NewAttrKind] = true;
7280
7281 // You cannot have both __sptr and __uptr on the same type, nor can you
7282 // have __ptr32 and __ptr64.
7283 if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) {
7284 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7285 << "'__ptr32'"
7286 << "'__ptr64'" << /*isRegularKeyword=*/0;
7287 return true;
7288 } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) {
7289 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7290 << "'__sptr'"
7291 << "'__uptr'" << /*isRegularKeyword=*/0;
7292 return true;
7293 }
7294
7295 // Check the raw (i.e., desugared) Canonical type to see if it
7296 // is a pointer type.
7297 if (!isa<PointerType>(Desugared)) {
7298 // Pointer type qualifiers can only operate on pointer types, but not
7299 // pointer-to-member types.
7301 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
7302 else
7303 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
7304 return true;
7305 }
7306
7307 // Add address space to type based on its attributes.
7308 LangAS ASIdx = LangAS::Default;
7309 uint64_t PtrWidth =
7311 if (PtrWidth == 32) {
7312 if (Attrs[attr::Ptr64])
7313 ASIdx = LangAS::ptr64;
7314 else if (Attrs[attr::UPtr])
7315 ASIdx = LangAS::ptr32_uptr;
7316 } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) {
7317 if (S.Context.getTargetInfo().getTriple().isOSzOS() || Attrs[attr::UPtr])
7318 ASIdx = LangAS::ptr32_uptr;
7319 else
7320 ASIdx = LangAS::ptr32_sptr;
7321 }
7322
7323 QualType Pointee = Type->getPointeeType();
7324 if (ASIdx != LangAS::Default)
7325 Pointee = S.Context.getAddrSpaceQualType(
7326 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7327
7329 S.Context.getPointerType(Pointee), Type.getQualifiers());
7330 Type = State.getAttributedType(A, Type, Equivalent);
7331 return false;
7332}
7333
7334static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State,
7335 QualType &QT, ParsedAttr &PAttr) {
7336 assert(PAttr.getKind() == ParsedAttr::AT_WebAssemblyFuncref);
7337
7338 Sema &S = State.getSema();
7340
7341 std::bitset<attr::LastAttr> Attrs;
7342 attr::Kind NewAttrKind = A->getKind();
7343 const auto *AT = dyn_cast<AttributedType>(QT);
7344 while (AT) {
7345 Attrs[AT->getAttrKind()] = true;
7346 AT = dyn_cast<AttributedType>(AT->getModifiedType());
7347 }
7348
7349 // You cannot specify duplicate type attributes, so if the attribute has
7350 // already been applied, flag it.
7351 if (Attrs[NewAttrKind]) {
7352 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7353 return true;
7354 }
7355
7356 // Check that the type is a function pointer type.
7357 QualType Desugared = QT.getDesugaredType(S.Context);
7358 const auto *Ptr = dyn_cast<PointerType>(Desugared);
7359 if (!Ptr || !Ptr->getPointeeType()->isFunctionType()) {
7360 S.Diag(PAttr.getLoc(), diag::err_attribute_webassembly_funcref);
7361 return true;
7362 }
7363
7364 // Add address space to type based on its attributes.
7366 QualType Pointee = QT->getPointeeType();
7367 Pointee = S.Context.getAddrSpaceQualType(
7368 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7369
7371 S.Context.getPointerType(Pointee), QT.getQualifiers());
7372 QT = State.getAttributedType(A, QT, Equivalent);
7373 return false;
7374}
7375
7376static void HandleSwiftAttr(TypeProcessingState &State, TypeAttrLocation TAL,
7377 QualType &QT, ParsedAttr &PAttr) {
7378 if (TAL == TAL_DeclName)
7379 return;
7380
7381 Sema &S = State.getSema();
7382 auto &D = State.getDeclarator();
7383
7384 // If the attribute appears in declaration specifiers
7385 // it should be handled as a declaration attribute,
7386 // unless it's associated with a type or a function
7387 // prototype (i.e. appears on a parameter or result type).
7388 if (State.isProcessingDeclSpec()) {
7389 if (!(D.isPrototypeContext() ||
7390 D.getContext() == DeclaratorContext::TypeName))
7391 return;
7392
7393 if (auto *chunk = D.getInnermostNonParenChunk()) {
7394 moveAttrFromListToList(PAttr, State.getCurrentAttributes(),
7395 const_cast<DeclaratorChunk *>(chunk)->getAttrs());
7396 return;
7397 }
7398 }
7399
7400 StringRef Str;
7401 if (!S.checkStringLiteralArgumentAttr(PAttr, 0, Str)) {
7402 PAttr.setInvalid();
7403 return;
7404 }
7405
7406 // If the attribute as attached to a paren move it closer to
7407 // the declarator. This can happen in block declarations when
7408 // an attribute is placed before `^` i.e. `(__attribute__((...)) ^)`.
7409 //
7410 // Note that it's actually invalid to use GNU style attributes
7411 // in a block but such cases are currently handled gracefully
7412 // but the parser and behavior should be consistent between
7413 // cases when attribute appears before/after block's result
7414 // type and inside (^).
7415 if (TAL == TAL_DeclChunk) {
7416 auto chunkIdx = State.getCurrentChunkIndex();
7417 if (chunkIdx >= 1 &&
7418 D.getTypeObject(chunkIdx).Kind == DeclaratorChunk::Paren) {
7419 moveAttrFromListToList(PAttr, State.getCurrentAttributes(),
7420 D.getTypeObject(chunkIdx - 1).getAttrs());
7421 return;
7422 }
7423 }
7424
7425 auto *A = ::new (S.Context) SwiftAttrAttr(S.Context, PAttr, Str);
7426 QT = State.getAttributedType(A, QT, QT);
7427 PAttr.setUsedAsTypeAttr();
7428}
7429
7430/// Rebuild an attributed type without the nullability attribute on it.
7432 QualType Type) {
7433 auto Attributed = dyn_cast<AttributedType>(Type.getTypePtr());
7434 if (!Attributed)
7435 return Type;
7436
7437 // Skip the nullability attribute; we're done.
7438 if (Attributed->getImmediateNullability())
7439 return Attributed->getModifiedType();
7440
7441 // Build the modified type.
7443 Ctx, Attributed->getModifiedType());
7444 assert(Modified.getTypePtr() != Attributed->getModifiedType().getTypePtr());
7445 return Ctx.getAttributedType(Attributed->getAttrKind(), Modified,
7446 Attributed->getEquivalentType(),
7447 Attributed->getAttr());
7448}
7449
7450/// Map a nullability attribute kind to a nullability kind.
7452 switch (kind) {
7453 case ParsedAttr::AT_TypeNonNull:
7455
7456 case ParsedAttr::AT_TypeNullable:
7458
7459 case ParsedAttr::AT_TypeNullableResult:
7461
7462 case ParsedAttr::AT_TypeNullUnspecified:
7464
7465 default:
7466 llvm_unreachable("not a nullability attribute kind");
7467 }
7468}
7469
7471 Sema &S, TypeProcessingState *State, ParsedAttr *PAttr, QualType &QT,
7472 NullabilityKind Nullability, SourceLocation NullabilityLoc,
7473 bool IsContextSensitive, bool AllowOnArrayType, bool OverrideExisting) {
7474 bool Implicit = (State == nullptr);
7475 if (!Implicit)
7476 recordNullabilitySeen(S, NullabilityLoc);
7477
7478 // Check for existing nullability attributes on the type.
7479 QualType Desugared = QT;
7480 while (auto *Attributed = dyn_cast<AttributedType>(Desugared.getTypePtr())) {
7481 // Check whether there is already a null
7482 if (auto ExistingNullability = Attributed->getImmediateNullability()) {
7483 // Duplicated nullability.
7484 if (Nullability == *ExistingNullability) {
7485 if (Implicit)
7486 break;
7487
7488 S.Diag(NullabilityLoc, diag::warn_nullability_duplicate)
7489 << DiagNullabilityKind(Nullability, IsContextSensitive)
7490 << FixItHint::CreateRemoval(NullabilityLoc);
7491
7492 break;
7493 }
7494
7495 if (!OverrideExisting) {
7496 // Conflicting nullability.
7497 S.Diag(NullabilityLoc, diag::err_nullability_conflicting)
7498 << DiagNullabilityKind(Nullability, IsContextSensitive)
7499 << DiagNullabilityKind(*ExistingNullability, false);
7500 return true;
7501 }
7502
7503 // Rebuild the attributed type, dropping the existing nullability.
7505 }
7506
7507 Desugared = Attributed->getModifiedType();
7508 }
7509
7510 // If there is already a different nullability specifier, complain.
7511 // This (unlike the code above) looks through typedefs that might
7512 // have nullability specifiers on them, which means we cannot
7513 // provide a useful Fix-It.
7514 if (auto ExistingNullability = Desugared->getNullability()) {
7515 if (Nullability != *ExistingNullability && !Implicit) {
7516 S.Diag(NullabilityLoc, diag::err_nullability_conflicting)
7517 << DiagNullabilityKind(Nullability, IsContextSensitive)
7518 << DiagNullabilityKind(*ExistingNullability, false);
7519
7520 // Try to find the typedef with the existing nullability specifier.
7521 if (auto TT = Desugared->getAs<TypedefType>()) {
7522 TypedefNameDecl *typedefDecl = TT->getDecl();
7523 QualType underlyingType = typedefDecl->getUnderlyingType();
7524 if (auto typedefNullability =
7525 AttributedType::stripOuterNullability(underlyingType)) {
7526 if (*typedefNullability == *ExistingNullability) {
7527 S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
7528 << DiagNullabilityKind(*ExistingNullability, false);
7529 }
7530 }
7531 }
7532
7533 return true;
7534 }
7535 }
7536
7537 // If this definitely isn't a pointer type, reject the specifier.
7538 if (!Desugared->canHaveNullability() &&
7539 !(AllowOnArrayType && Desugared->isArrayType())) {
7540 if (!Implicit)
7541 S.Diag(NullabilityLoc, diag::err_nullability_nonpointer)
7542 << DiagNullabilityKind(Nullability, IsContextSensitive) << QT;
7543
7544 return true;
7545 }
7546
7547 // For the context-sensitive keywords/Objective-C property
7548 // attributes, require that the type be a single-level pointer.
7549 if (IsContextSensitive) {
7550 // Make sure that the pointee isn't itself a pointer type.
7551 const Type *pointeeType = nullptr;
7552 if (Desugared->isArrayType())
7553 pointeeType = Desugared->getArrayElementTypeNoTypeQual();
7554 else if (Desugared->isAnyPointerType())
7555 pointeeType = Desugared->getPointeeType().getTypePtr();
7556
7557 if (pointeeType && (pointeeType->isAnyPointerType() ||
7558 pointeeType->isObjCObjectPointerType() ||
7559 pointeeType->isMemberPointerType())) {
7560 S.Diag(NullabilityLoc, diag::err_nullability_cs_multilevel)
7561 << DiagNullabilityKind(Nullability, true) << QT;
7562 S.Diag(NullabilityLoc, diag::note_nullability_type_specifier)
7563 << DiagNullabilityKind(Nullability, false) << QT
7564 << FixItHint::CreateReplacement(NullabilityLoc,
7565 getNullabilitySpelling(Nullability));
7566 return true;
7567 }
7568 }
7569
7570 // Form the attributed type.
7571 if (State) {
7572 assert(PAttr);
7573 Attr *A = createNullabilityAttr(S.Context, *PAttr, Nullability);
7574 QT = State->getAttributedType(A, QT, QT);
7575 } else {
7576 QT = S.Context.getAttributedType(Nullability, QT, QT);
7577 }
7578 return false;
7579}
7580
7581static bool CheckNullabilityTypeSpecifier(TypeProcessingState &State,
7583 bool AllowOnArrayType) {
7585 SourceLocation NullabilityLoc = Attr.getLoc();
7586 bool IsContextSensitive = Attr.isContextSensitiveKeywordAttribute();
7587
7588 return CheckNullabilityTypeSpecifier(State.getSema(), &State, &Attr, Type,
7589 Nullability, NullabilityLoc,
7590 IsContextSensitive, AllowOnArrayType,
7591 /*overrideExisting*/ false);
7592}
7593
7595 NullabilityKind Nullability,
7596 SourceLocation DiagLoc,
7597 bool AllowArrayTypes,
7598 bool OverrideExisting) {
7600 *this, nullptr, nullptr, Type, Nullability, DiagLoc,
7601 /*isContextSensitive*/ false, AllowArrayTypes, OverrideExisting);
7602}
7603
7605 QualType T = VD->getType();
7606
7607 // Check that the variable's type can fit in the specified address space. This
7608 // is determined by how far a pointer in that address space can reach.
7609 llvm::APInt MaxSizeForAddrSpace =
7610 llvm::APInt::getMaxValue(Context.getTargetInfo().getPointerWidth(AS));
7611 std::optional<CharUnits> TSizeInChars = Context.getTypeSizeInCharsIfKnown(T);
7612 if (TSizeInChars && static_cast<uint64_t>(TSizeInChars->getQuantity()) >
7613 MaxSizeForAddrSpace.getZExtValue()) {
7614 Diag(VD->getLocation(), diag::err_type_too_large_for_address_space)
7615 << T << MaxSizeForAddrSpace;
7616 return false;
7617 }
7618
7619 return true;
7620}
7621
7622/// Check the application of the Objective-C '__kindof' qualifier to
7623/// the given type.
7624static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
7625 ParsedAttr &attr) {
7626 Sema &S = state.getSema();
7627
7629 // Build the attributed type to record where __kindof occurred.
7630 type = state.getAttributedType(
7632 return false;
7633 }
7634
7635 // Find out if it's an Objective-C object or object pointer type;
7636 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
7637 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
7638 : type->getAs<ObjCObjectType>();
7639
7640 // If not, we can't apply __kindof.
7641 if (!objType) {
7642 // FIXME: Handle dependent types that aren't yet object types.
7643 S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
7644 << type;
7645 return true;
7646 }
7647
7648 // Rebuild the "equivalent" type, which pushes __kindof down into
7649 // the object type.
7650 // There is no need to apply kindof on an unqualified id type.
7651 QualType equivType = S.Context.getObjCObjectType(
7652 objType->getBaseType(), objType->getTypeArgsAsWritten(),
7653 objType->getProtocols(),
7654 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
7655
7656 // If we started with an object pointer type, rebuild it.
7657 if (ptrType) {
7658 equivType = S.Context.getObjCObjectPointerType(equivType);
7659 if (auto nullability = type->getNullability()) {
7660 // We create a nullability attribute from the __kindof attribute.
7661 // Make sure that will make sense.
7662 assert(attr.getAttributeSpellingListIndex() == 0 &&
7663 "multiple spellings for __kindof?");
7664 Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
7665 A->setImplicit(true);
7666 equivType = state.getAttributedType(A, equivType, equivType);
7667 }
7668 }
7669
7670 // Build the attributed type to record where __kindof occurred.
7671 type = state.getAttributedType(
7673 return false;
7674}
7675
7676/// Distribute a nullability type attribute that cannot be applied to
7677/// the type specifier to a pointer, block pointer, or member pointer
7678/// declarator, complaining if necessary.
7679///
7680/// \returns true if the nullability annotation was distributed, false
7681/// otherwise.
7682static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
7684 Declarator &declarator = state.getDeclarator();
7685
7686 /// Attempt to move the attribute to the specified chunk.
7687 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
7688 // If there is already a nullability attribute there, don't add
7689 // one.
7690 if (hasNullabilityAttr(chunk.getAttrs()))
7691 return false;
7692
7693 // Complain about the nullability qualifier being in the wrong
7694 // place.
7695 enum {
7696 PK_Pointer,
7697 PK_BlockPointer,
7698 PK_MemberPointer,
7699 PK_FunctionPointer,
7700 PK_MemberFunctionPointer,
7701 } pointerKind
7702 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
7703 : PK_Pointer)
7704 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
7705 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
7706
7707 auto diag = state.getSema().Diag(attr.getLoc(),
7708 diag::warn_nullability_declspec)
7710 attr.isContextSensitiveKeywordAttribute())
7711 << type
7712 << static_cast<unsigned>(pointerKind);
7713
7714 // FIXME: MemberPointer chunks don't carry the location of the *.
7715 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
7718 state.getSema().getPreprocessor().getLocForEndOfToken(
7719 chunk.Loc),
7720 " " + attr.getAttrName()->getName().str() + " ");
7721 }
7722
7723 moveAttrFromListToList(attr, state.getCurrentAttributes(),
7724 chunk.getAttrs());
7725 return true;
7726 };
7727
7728 // Move it to the outermost pointer, member pointer, or block
7729 // pointer declarator.
7730 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
7731 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
7732 switch (chunk.Kind) {
7736 return moveToChunk(chunk, false);
7737
7740 continue;
7741
7743 // Try to move past the return type to a function/block/member
7744 // function pointer.
7746 declarator, i,
7747 /*onlyBlockPointers=*/false)) {
7748 return moveToChunk(*dest, true);
7749 }
7750
7751 return false;
7752
7753 // Don't walk through these.
7756 return false;
7757 }
7758 }
7759
7760 return false;
7761}
7762
7764 assert(!Attr.isInvalid());
7765 switch (Attr.getKind()) {
7766 default:
7767 llvm_unreachable("not a calling convention attribute");
7768 case ParsedAttr::AT_CDecl:
7769 return createSimpleAttr<CDeclAttr>(Ctx, Attr);
7770 case ParsedAttr::AT_FastCall:
7772 case ParsedAttr::AT_StdCall:
7774 case ParsedAttr::AT_ThisCall:
7776 case ParsedAttr::AT_RegCall:
7778 case ParsedAttr::AT_Pascal:
7780 case ParsedAttr::AT_SwiftCall:
7782 case ParsedAttr::AT_SwiftAsyncCall:
7784 case ParsedAttr::AT_VectorCall:
7786 case ParsedAttr::AT_AArch64VectorPcs:
7788 case ParsedAttr::AT_AArch64SVEPcs:
7790 case ParsedAttr::AT_ArmStreaming:
7792 case ParsedAttr::AT_Pcs: {
7793 // The attribute may have had a fixit applied where we treated an
7794 // identifier as a string literal. The contents of the string are valid,
7795 // but the form may not be.
7796 StringRef Str;
7797 if (Attr.isArgExpr(0))
7798 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
7799 else
7800 Str = Attr.getArgAsIdent(0)->getIdentifierInfo()->getName();
7801 PcsAttr::PCSType Type;
7802 if (!PcsAttr::ConvertStrToPCSType(Str, Type))
7803 llvm_unreachable("already validated the attribute");
7804 return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
7805 }
7806 case ParsedAttr::AT_IntelOclBicc:
7808 case ParsedAttr::AT_MSABI:
7809 return createSimpleAttr<MSABIAttr>(Ctx, Attr);
7810 case ParsedAttr::AT_SysVABI:
7812 case ParsedAttr::AT_PreserveMost:
7814 case ParsedAttr::AT_PreserveAll:
7816 case ParsedAttr::AT_M68kRTD:
7818 case ParsedAttr::AT_PreserveNone:
7820 case ParsedAttr::AT_RISCVVectorCC:
7822 case ParsedAttr::AT_RISCVVLSCC: {
7823 // If the riscv_abi_vlen doesn't have any argument, we set set it to default
7824 // value 128.
7825 unsigned ABIVLen = 128;
7826 if (Attr.getNumArgs()) {
7827 std::optional<llvm::APSInt> MaybeABIVLen =
7828 Attr.getArgAsExpr(0)->getIntegerConstantExpr(Ctx);
7829 if (!MaybeABIVLen)
7830 llvm_unreachable("Invalid RISC-V ABI VLEN");
7831 ABIVLen = MaybeABIVLen->getZExtValue();
7832 }
7833
7834 return ::new (Ctx) RISCVVLSCCAttr(Ctx, Attr, ABIVLen);
7835 }
7836 }
7837 llvm_unreachable("unexpected attribute kind!");
7838}
7839
7840std::optional<FunctionEffectMode>
7841Sema::ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName) {
7842 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent())
7844
7845 std::optional<llvm::APSInt> ConditionValue =
7847 if (!ConditionValue) {
7848 // FIXME: err_attribute_argument_type doesn't quote the attribute
7849 // name but needs to; users are inconsistent.
7850 Diag(CondExpr->getExprLoc(), diag::err_attribute_argument_type)
7851 << AttributeName << AANT_ArgumentIntegerConstant
7852 << CondExpr->getSourceRange();
7853 return std::nullopt;
7854 }
7855 return !ConditionValue->isZero() ? FunctionEffectMode::True
7857}
7858
7859static bool
7860handleNonBlockingNonAllocatingTypeAttr(TypeProcessingState &TPState,
7861 ParsedAttr &PAttr, QualType &QT,
7862 FunctionTypeUnwrapper &Unwrapped) {
7863 // Delay if this is not a function type.
7864 if (!Unwrapped.isFunctionType())
7865 return false;
7866
7867 Sema &S = TPState.getSema();
7868
7869 // Require FunctionProtoType.
7870 auto *FPT = Unwrapped.get()->getAs<FunctionProtoType>();
7871 if (FPT == nullptr) {
7872 S.Diag(PAttr.getLoc(), diag::err_func_with_effects_no_prototype)
7873 << PAttr.getAttrName()->getName();
7874 return true;
7875 }
7876
7877 // Parse the new attribute.
7878 // non/blocking or non/allocating? Or conditional (computed)?
7879 bool IsNonBlocking = PAttr.getKind() == ParsedAttr::AT_NonBlocking ||
7880 PAttr.getKind() == ParsedAttr::AT_Blocking;
7881
7883 Expr *CondExpr = nullptr; // only valid if dependent
7884
7885 if (PAttr.getKind() == ParsedAttr::AT_NonBlocking ||
7886 PAttr.getKind() == ParsedAttr::AT_NonAllocating) {
7887 if (!PAttr.checkAtMostNumArgs(S, 1)) {
7888 PAttr.setInvalid();
7889 return true;
7890 }
7891
7892 // Parse the condition, if any.
7893 if (PAttr.getNumArgs() == 1) {
7894 CondExpr = PAttr.getArgAsExpr(0);
7895 std::optional<FunctionEffectMode> MaybeMode =
7896 S.ActOnEffectExpression(CondExpr, PAttr.getAttrName()->getName());
7897 if (!MaybeMode) {
7898 PAttr.setInvalid();
7899 return true;
7900 }
7901 NewMode = *MaybeMode;
7902 if (NewMode != FunctionEffectMode::Dependent)
7903 CondExpr = nullptr;
7904 } else {
7905 NewMode = FunctionEffectMode::True;
7906 }
7907 } else {
7908 // This is the `blocking` or `allocating` attribute.
7909 if (S.CheckAttrNoArgs(PAttr)) {
7910 // The attribute has been marked invalid.
7911 return true;
7912 }
7913 NewMode = FunctionEffectMode::False;
7914 }
7915
7916 const FunctionEffect::Kind FEKind =
7917 (NewMode == FunctionEffectMode::False)
7918 ? (IsNonBlocking ? FunctionEffect::Kind::Blocking
7920 : (IsNonBlocking ? FunctionEffect::Kind::NonBlocking
7922 const FunctionEffectWithCondition NewEC{FunctionEffect(FEKind),
7923 EffectConditionExpr(CondExpr)};
7924
7925 if (S.diagnoseConflictingFunctionEffect(FPT->getFunctionEffects(), NewEC,
7926 PAttr.getLoc())) {
7927 PAttr.setInvalid();
7928 return true;
7929 }
7930
7931 // Add the effect to the FunctionProtoType.
7932 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
7935 [[maybe_unused]] bool Success = FX.insert(NewEC, Errs);
7936 assert(Success && "effect conflicts should have been diagnosed above");
7938
7939 QualType NewType = S.Context.getFunctionType(FPT->getReturnType(),
7940 FPT->getParamTypes(), EPI);
7941 QT = Unwrapped.wrap(S, NewType->getAs<FunctionType>());
7942 return true;
7943}
7944
7945static bool checkMutualExclusion(TypeProcessingState &state,
7948 AttributeCommonInfo::Kind OtherKind) {
7949 auto OtherAttr = llvm::find_if(
7950 state.getCurrentAttributes(),
7951 [OtherKind](const ParsedAttr &A) { return A.getKind() == OtherKind; });
7952 if (OtherAttr == state.getCurrentAttributes().end() || OtherAttr->isInvalid())
7953 return false;
7954
7955 Sema &S = state.getSema();
7956 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
7957 << *OtherAttr << Attr
7958 << (OtherAttr->isRegularKeywordAttribute() ||
7960 S.Diag(OtherAttr->getLoc(), diag::note_conflicting_attribute);
7961 Attr.setInvalid();
7962 return true;
7963}
7964
7967 ParsedAttr &Attr) {
7968 if (!Attr.getNumArgs()) {
7969 S.Diag(Attr.getLoc(), diag::err_missing_arm_state) << Attr;
7970 Attr.setInvalid();
7971 return true;
7972 }
7973
7974 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
7975 StringRef StateName;
7976 SourceLocation LiteralLoc;
7977 if (!S.checkStringLiteralArgumentAttr(Attr, I, StateName, &LiteralLoc))
7978 return true;
7979
7980 if (StateName != "sme_za_state") {
7981 S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName;
7982 Attr.setInvalid();
7983 return true;
7984 }
7985
7986 if (EPI.AArch64SMEAttributes &
7988 S.Diag(Attr.getLoc(), diag::err_conflicting_attributes_arm_agnostic);
7989 Attr.setInvalid();
7990 return true;
7991 }
7992
7994 }
7995
7996 return false;
7997}
7998
8003 if (!Attr.getNumArgs()) {
8004 S.Diag(Attr.getLoc(), diag::err_missing_arm_state) << Attr;
8005 Attr.setInvalid();
8006 return true;
8007 }
8008
8009 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
8010 StringRef StateName;
8011 SourceLocation LiteralLoc;
8012 if (!S.checkStringLiteralArgumentAttr(Attr, I, StateName, &LiteralLoc))
8013 return true;
8014
8015 unsigned Shift;
8016 FunctionType::ArmStateValue ExistingState;
8017 if (StateName == "za") {
8020 } else if (StateName == "zt0") {
8023 } else {
8024 S.Diag(LiteralLoc, diag::err_unknown_arm_state) << StateName;
8025 Attr.setInvalid();
8026 return true;
8027 }
8028
8030 S.Diag(LiteralLoc, diag::err_conflicting_attributes_arm_agnostic);
8031 Attr.setInvalid();
8032 return true;
8033 }
8034
8035 // __arm_in(S), __arm_out(S), __arm_inout(S) and __arm_preserves(S)
8036 // are all mutually exclusive for the same S, so check if there are
8037 // conflicting attributes.
8038 if (ExistingState != FunctionType::ARM_None && ExistingState != State) {
8039 S.Diag(LiteralLoc, diag::err_conflicting_attributes_arm_state)
8040 << StateName;
8041 Attr.setInvalid();
8042 return true;
8043 }
8044
8046 (FunctionType::AArch64SMETypeAttributes)((State << Shift)));
8047 }
8048 return false;
8049}
8050
8051/// Process an individual function attribute. Returns true to
8052/// indicate that the attribute was handled, false if it wasn't.
8053static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
8055 Sema &S = state.getSema();
8056
8057 FunctionTypeUnwrapper unwrapped(S, type);
8058
8059 if (attr.getKind() == ParsedAttr::AT_NoReturn) {
8060 if (S.CheckAttrNoArgs(attr))
8061 return true;
8062
8063 // Delay if this is not a function type.
8064 if (!unwrapped.isFunctionType())
8065 return false;
8066
8067 // Otherwise we can process right away.
8068 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
8069 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8070 return true;
8071 }
8072
8073 if (attr.getKind() == ParsedAttr::AT_CFIUncheckedCallee) {
8074 // Delay if this is not a prototyped function type.
8075 if (!unwrapped.isFunctionType())
8076 return false;
8077
8078 if (!unwrapped.get()->isFunctionProtoType()) {
8079 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
8080 << attr << attr.isRegularKeywordAttribute()
8082 attr.setInvalid();
8083 return true;
8084 }
8085
8086 const auto *FPT = unwrapped.get()->getAs<FunctionProtoType>();
8088 FPT->getReturnType(), FPT->getParamTypes(),
8089 FPT->getExtProtoInfo().withCFIUncheckedCallee(true));
8090 type = unwrapped.wrap(S, cast<FunctionType>(type.getTypePtr()));
8091 return true;
8092 }
8093
8094 if (attr.getKind() == ParsedAttr::AT_CmseNSCall) {
8095 // Delay if this is not a function type.
8096 if (!unwrapped.isFunctionType())
8097 return false;
8098
8099 // Ignore if we don't have CMSE enabled.
8100 if (!S.getLangOpts().Cmse) {
8101 S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr;
8102 attr.setInvalid();
8103 return true;
8104 }
8105
8106 // Otherwise we can process right away.
8108 unwrapped.get()->getExtInfo().withCmseNSCall(true);
8109 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8110 return true;
8111 }
8112
8113 // ns_returns_retained is not always a type attribute, but if we got
8114 // here, we're treating it as one right now.
8115 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
8116 if (attr.getNumArgs()) return true;
8117
8118 // Delay if this is not a function type.
8119 if (!unwrapped.isFunctionType())
8120 return false;
8121
8122 // Check whether the return type is reasonable.
8124 attr.getLoc(), unwrapped.get()->getReturnType()))
8125 return true;
8126
8127 // Only actually change the underlying type in ARC builds.
8128 QualType origType = type;
8129 if (state.getSema().getLangOpts().ObjCAutoRefCount) {
8131 = unwrapped.get()->getExtInfo().withProducesResult(true);
8132 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8133 }
8134 type = state.getAttributedType(
8136 origType, type);
8137 return true;
8138 }
8139
8140 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
8142 return true;
8143
8144 // Delay if this is not a function type.
8145 if (!unwrapped.isFunctionType())
8146 return false;
8147
8149 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
8150 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8151 return true;
8152 }
8153
8154 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
8155 if (!S.getLangOpts().CFProtectionBranch) {
8156 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
8157 attr.setInvalid();
8158 return true;
8159 }
8160
8162 return true;
8163
8164 // If this is not a function type, warning will be asserted by subject
8165 // check.
8166 if (!unwrapped.isFunctionType())
8167 return true;
8168
8170 unwrapped.get()->getExtInfo().withNoCfCheck(true);
8171 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8172 return true;
8173 }
8174
8175 if (attr.getKind() == ParsedAttr::AT_Regparm) {
8176 unsigned value;
8177 if (S.CheckRegparmAttr(attr, value))
8178 return true;
8179
8180 // Delay if this is not a function type.
8181 if (!unwrapped.isFunctionType())
8182 return false;
8183
8184 // Diagnose regparm with fastcall.
8185 const FunctionType *fn = unwrapped.get();
8186 CallingConv CC = fn->getCallConv();
8187 if (CC == CC_X86FastCall) {
8188 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8189 << FunctionType::getNameForCallConv(CC) << "regparm"
8190 << attr.isRegularKeywordAttribute();
8191 attr.setInvalid();
8192 return true;
8193 }
8194
8196 unwrapped.get()->getExtInfo().withRegParm(value);
8197 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8198 return true;
8199 }
8200
8201 if (attr.getKind() == ParsedAttr::AT_CFISalt) {
8202 if (attr.getNumArgs() != 1)
8203 return true;
8204
8205 StringRef Argument;
8206 if (!S.checkStringLiteralArgumentAttr(attr, 0, Argument))
8207 return true;
8208
8209 // Delay if this is not a function type.
8210 if (!unwrapped.isFunctionType())
8211 return false;
8212
8213 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8214 if (!FnTy) {
8215 S.Diag(attr.getLoc(), diag::err_attribute_wrong_decl_type)
8216 << attr << attr.isRegularKeywordAttribute()
8218 attr.setInvalid();
8219 return true;
8220 }
8221
8222 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8223 EPI.ExtraAttributeInfo.CFISalt = Argument;
8224
8225 QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(),
8226 FnTy->getParamTypes(), EPI);
8227 type = unwrapped.wrap(S, newtype->getAs<FunctionType>());
8228 return true;
8229 }
8230
8231 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8232 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible ||
8233 attr.getKind() == ParsedAttr::AT_ArmPreserves ||
8234 attr.getKind() == ParsedAttr::AT_ArmIn ||
8235 attr.getKind() == ParsedAttr::AT_ArmOut ||
8236 attr.getKind() == ParsedAttr::AT_ArmInOut ||
8237 attr.getKind() == ParsedAttr::AT_ArmAgnostic) {
8238 if (S.CheckAttrTarget(attr))
8239 return true;
8240
8241 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8242 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible)
8243 if (S.CheckAttrNoArgs(attr))
8244 return true;
8245
8246 if (!unwrapped.isFunctionType())
8247 return false;
8248
8249 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8250 if (!FnTy) {
8251 // SME ACLE attributes are not supported on K&R-style unprototyped C
8252 // functions.
8253 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
8254 << attr << attr.isRegularKeywordAttribute()
8256 attr.setInvalid();
8257 return false;
8258 }
8259
8260 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8261 switch (attr.getKind()) {
8262 case ParsedAttr::AT_ArmStreaming:
8263 if (checkMutualExclusion(state, EPI, attr,
8264 ParsedAttr::AT_ArmStreamingCompatible))
8265 return true;
8267 break;
8268 case ParsedAttr::AT_ArmStreamingCompatible:
8269 if (checkMutualExclusion(state, EPI, attr, ParsedAttr::AT_ArmStreaming))
8270 return true;
8272 break;
8273 case ParsedAttr::AT_ArmPreserves:
8275 return true;
8276 break;
8277 case ParsedAttr::AT_ArmIn:
8279 return true;
8280 break;
8281 case ParsedAttr::AT_ArmOut:
8283 return true;
8284 break;
8285 case ParsedAttr::AT_ArmInOut:
8287 return true;
8288 break;
8289 case ParsedAttr::AT_ArmAgnostic:
8290 if (handleArmAgnosticAttribute(S, EPI, attr))
8291 return true;
8292 break;
8293 default:
8294 llvm_unreachable("Unsupported attribute");
8295 }
8296
8297 QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(),
8298 FnTy->getParamTypes(), EPI);
8299 type = unwrapped.wrap(S, newtype->getAs<FunctionType>());
8300 return true;
8301 }
8302
8303 if (attr.getKind() == ParsedAttr::AT_NoThrow) {
8304 // Delay if this is not a function type.
8305 if (!unwrapped.isFunctionType())
8306 return false;
8307
8308 if (S.CheckAttrNoArgs(attr)) {
8309 attr.setInvalid();
8310 return true;
8311 }
8312
8313 // Otherwise we can process right away.
8314 auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
8315
8316 // MSVC ignores nothrow if it is in conflict with an explicit exception
8317 // specification.
8318 if (Proto->hasExceptionSpec()) {
8319 switch (Proto->getExceptionSpecType()) {
8320 case EST_None:
8321 llvm_unreachable("This doesn't have an exception spec!");
8322
8323 case EST_DynamicNone:
8324 case EST_BasicNoexcept:
8325 case EST_NoexceptTrue:
8326 case EST_NoThrow:
8327 // Exception spec doesn't conflict with nothrow, so don't warn.
8328 [[fallthrough]];
8329 case EST_Unparsed:
8330 case EST_Uninstantiated:
8332 case EST_Unevaluated:
8333 // We don't have enough information to properly determine if there is a
8334 // conflict, so suppress the warning.
8335 break;
8336 case EST_Dynamic:
8337 case EST_MSAny:
8338 case EST_NoexceptFalse:
8339 S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored);
8340 break;
8341 }
8342 return true;
8343 }
8344
8345 type = unwrapped.wrap(
8346 S, S.Context
8348 QualType{Proto, 0},
8350 ->getAs<FunctionType>());
8351 return true;
8352 }
8353
8354 if (attr.getKind() == ParsedAttr::AT_NonBlocking ||
8355 attr.getKind() == ParsedAttr::AT_NonAllocating ||
8356 attr.getKind() == ParsedAttr::AT_Blocking ||
8357 attr.getKind() == ParsedAttr::AT_Allocating) {
8358 return handleNonBlockingNonAllocatingTypeAttr(state, attr, type, unwrapped);
8359 }
8360
8361 // Delay if the type didn't work out to a function.
8362 if (!unwrapped.isFunctionType()) return false;
8363
8364 // Otherwise, a calling convention.
8365 CallingConv CC;
8366 if (S.CheckCallingConvAttr(attr, CC, /*FunctionDecl=*/nullptr, CFT))
8367 return true;
8368
8369 const FunctionType *fn = unwrapped.get();
8370 CallingConv CCOld = fn->getCallConv();
8371 Attr *CCAttr = getCCTypeAttr(S.Context, attr);
8372
8373 if (CCOld != CC) {
8374 // Error out on when there's already an attribute on the type
8375 // and the CCs don't match.
8377 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8380 << attr.isRegularKeywordAttribute();
8381 attr.setInvalid();
8382 return true;
8383 }
8384 }
8385
8386 // Diagnose use of variadic functions with calling conventions that
8387 // don't support them (e.g. because they're callee-cleanup).
8388 // We delay warning about this on unprototyped function declarations
8389 // until after redeclaration checking, just in case we pick up a
8390 // prototype that way. And apparently we also "delay" warning about
8391 // unprototyped function types in general, despite not necessarily having
8392 // much ability to diagnose it later.
8393 if (!supportsVariadicCall(CC)) {
8394 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
8395 if (FnP && FnP->isVariadic()) {
8396 // stdcall and fastcall are ignored with a warning for GCC and MS
8397 // compatibility.
8398 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
8399 return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported)
8402
8403 attr.setInvalid();
8404 return S.Diag(attr.getLoc(), diag::err_cconv_varargs)
8406 }
8407 }
8408
8409 // Also diagnose fastcall with regparm.
8410 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
8411 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8413 << attr.isRegularKeywordAttribute();
8414 attr.setInvalid();
8415 return true;
8416 }
8417
8418 // Modify the CC from the wrapped function type, wrap it all back, and then
8419 // wrap the whole thing in an AttributedType as written. The modified type
8420 // might have a different CC if we ignored the attribute.
8422 if (CCOld == CC) {
8423 Equivalent = type;
8424 } else {
8425 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
8426 Equivalent =
8427 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8428 }
8429 type = state.getAttributedType(CCAttr, type, Equivalent);
8430 return true;
8431}
8432
8434 const AttributedType *AT;
8435
8436 // Stop if we'd be stripping off a typedef sugar node to reach the
8437 // AttributedType.
8438 while ((AT = T->getAs<AttributedType>()) &&
8439 AT->getAs<TypedefType>() == T->getAs<TypedefType>()) {
8440 if (AT->isCallingConv())
8441 return true;
8442 T = AT->getModifiedType();
8443 }
8444 return false;
8445}
8446
8447void Sema::adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
8448 bool IsCtorOrDtor, SourceLocation Loc) {
8449 FunctionTypeUnwrapper Unwrapped(*this, T);
8450 const FunctionType *FT = Unwrapped.get();
8451 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
8452 cast<FunctionProtoType>(FT)->isVariadic());
8453 CallingConv CurCC = FT->getCallConv();
8454 CallingConv ToCC =
8455 Context.getDefaultCallingConvention(IsVariadic, HasThisPointer);
8456
8457 if (CurCC == ToCC)
8458 return;
8459
8460 // MS compiler ignores explicit calling convention attributes on structors. We
8461 // should do the same.
8462 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
8463 // Issue a warning on ignored calling convention -- except of __stdcall.
8464 // Again, this is what MS compiler does.
8465 if (CurCC != CC_X86StdCall)
8466 Diag(Loc, diag::warn_cconv_unsupported)
8469 // Default adjustment.
8470 } else {
8471 // Only adjust types with the default convention. For example, on Windows
8472 // we should adjust a __cdecl type to __thiscall for instance methods, and a
8473 // __thiscall type to __cdecl for static methods.
8474 CallingConv DefaultCC =
8475 Context.getDefaultCallingConvention(IsVariadic, !HasThisPointer);
8476
8477 if (CurCC != DefaultCC)
8478 return;
8479
8481 return;
8482 }
8483
8484 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
8485 QualType Wrapped = Unwrapped.wrap(*this, FT);
8486 T = Context.getAdjustedType(T, Wrapped);
8487}
8488
8489/// HandleVectorSizeAttribute - this attribute is only applicable to integral
8490/// and float scalars, although arrays, pointers, and function return values are
8491/// allowed in conjunction with this construct. Aggregates with this attribute
8492/// are invalid, even if they are of the same size as a corresponding scalar.
8493/// The raw attribute should contain precisely 1 argument, the vector size for
8494/// the variable, measured in bytes. If curType and rawAttr are well formed,
8495/// this routine will return a new vector type.
8496static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
8497 Sema &S) {
8498 // Check the attribute arguments.
8499 if (Attr.getNumArgs() != 1) {
8500 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8501 << 1;
8502 Attr.setInvalid();
8503 return;
8504 }
8505
8506 Expr *SizeExpr = Attr.getArgAsExpr(0);
8507 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
8508 if (!T.isNull())
8509 CurType = T;
8510 else
8511 Attr.setInvalid();
8512}
8513
8514/// Process the OpenCL-like ext_vector_type attribute when it occurs on
8515/// a type.
8517 Sema &S) {
8518 // check the attribute arguments.
8519 if (Attr.getNumArgs() != 1) {
8520 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8521 << 1;
8522 return;
8523 }
8524
8525 Expr *SizeExpr = Attr.getArgAsExpr(0);
8526 QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc());
8527 if (!T.isNull())
8528 CurType = T;
8529}
8530
8531static bool isPermittedNeonBaseType(QualType &Ty, VectorKind VecKind, Sema &S) {
8532 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
8533 if (!BTy)
8534 return false;
8535
8536 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
8537
8538 // Signed poly is mathematically wrong, but has been baked into some ABIs by
8539 // now.
8540 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
8541 Triple.getArch() == llvm::Triple::aarch64_32 ||
8542 Triple.getArch() == llvm::Triple::aarch64_be;
8543 if (VecKind == VectorKind::NeonPoly) {
8544 if (IsPolyUnsigned) {
8545 // AArch64 polynomial vectors are unsigned.
8546 return BTy->getKind() == BuiltinType::UChar ||
8547 BTy->getKind() == BuiltinType::UShort ||
8548 BTy->getKind() == BuiltinType::ULong ||
8549 BTy->getKind() == BuiltinType::ULongLong;
8550 } else {
8551 // AArch32 polynomial vectors are signed.
8552 return BTy->getKind() == BuiltinType::SChar ||
8553 BTy->getKind() == BuiltinType::Short ||
8554 BTy->getKind() == BuiltinType::LongLong;
8555 }
8556 }
8557
8558 // Non-polynomial vector types: the usual suspects are allowed, as well as
8559 // float64_t on AArch64.
8560 if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) &&
8561 BTy->getKind() == BuiltinType::Double)
8562 return true;
8563
8564 return BTy->getKind() == BuiltinType::SChar ||
8565 BTy->getKind() == BuiltinType::UChar ||
8566 BTy->getKind() == BuiltinType::Short ||
8567 BTy->getKind() == BuiltinType::UShort ||
8568 BTy->getKind() == BuiltinType::Int ||
8569 BTy->getKind() == BuiltinType::UInt ||
8570 BTy->getKind() == BuiltinType::Long ||
8571 BTy->getKind() == BuiltinType::ULong ||
8572 BTy->getKind() == BuiltinType::LongLong ||
8573 BTy->getKind() == BuiltinType::ULongLong ||
8574 BTy->getKind() == BuiltinType::Float ||
8575 BTy->getKind() == BuiltinType::Half ||
8576 BTy->getKind() == BuiltinType::BFloat16 ||
8577 BTy->getKind() == BuiltinType::MFloat8;
8578}
8579
8581 llvm::APSInt &Result) {
8582 const auto *AttrExpr = Attr.getArgAsExpr(0);
8583 if (!AttrExpr->isTypeDependent()) {
8584 if (std::optional<llvm::APSInt> Res =
8585 AttrExpr->getIntegerConstantExpr(S.Context)) {
8586 Result = *Res;
8587 return true;
8588 }
8589 }
8590 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
8591 << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange();
8592 Attr.setInvalid();
8593 return false;
8594}
8595
8596/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
8597/// "neon_polyvector_type" attributes are used to create vector types that
8598/// are mangled according to ARM's ABI. Otherwise, these types are identical
8599/// to those created with the "vector_size" attribute. Unlike "vector_size"
8600/// the argument to these Neon attributes is the number of vector elements,
8601/// not the vector size in bytes. The vector width and element type must
8602/// match one of the standard Neon vector types.
8604 Sema &S, VectorKind VecKind) {
8605 bool IsTargetOffloading = S.getLangOpts().isTargetDevice();
8606
8607 // Target must have NEON (or MVE, whose vectors are similar enough
8608 // not to need a separate attribute)
8609 if (!S.Context.getTargetInfo().hasFeature("mve") &&
8610 VecKind == VectorKind::Neon &&
8611 S.Context.getTargetInfo().getTriple().isArmMClass()) {
8612 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported_m_profile)
8613 << Attr << "'mve'";
8614 Attr.setInvalid();
8615 return;
8616 }
8617 if (!S.Context.getTargetInfo().hasFeature("mve") &&
8618 VecKind == VectorKind::NeonPoly &&
8619 S.Context.getTargetInfo().getTriple().isArmMClass()) {
8620 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported_m_profile)
8621 << Attr << "'mve'";
8622 Attr.setInvalid();
8623 return;
8624 }
8625
8626 // Check the attribute arguments.
8627 if (Attr.getNumArgs() != 1) {
8628 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8629 << Attr << 1;
8630 Attr.setInvalid();
8631 return;
8632 }
8633 // The number of elements must be an ICE.
8634 llvm::APSInt numEltsInt(32);
8635 if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt))
8636 return;
8637
8638 // Only certain element types are supported for Neon vectors.
8639 if (!isPermittedNeonBaseType(CurType, VecKind, S) && !IsTargetOffloading) {
8640 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
8641 Attr.setInvalid();
8642 return;
8643 }
8644
8645 // The total size of the vector must be 64 or 128 bits.
8646 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
8647 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
8648 unsigned vecSize = typeSize * numElts;
8649 if (vecSize != 64 && vecSize != 128) {
8650 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
8651 Attr.setInvalid();
8652 return;
8653 }
8654
8655 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
8656}
8657
8658/// Handle the __ptrauth qualifier.
8660 const ParsedAttr &Attr, Sema &S) {
8661
8662 assert((Attr.getNumArgs() > 0 && Attr.getNumArgs() <= 3) &&
8663 "__ptrauth qualifier takes between 1 and 3 arguments");
8664 Expr *KeyArg = Attr.getArgAsExpr(0);
8665 Expr *IsAddressDiscriminatedArg =
8666 Attr.getNumArgs() >= 2 ? Attr.getArgAsExpr(1) : nullptr;
8667 Expr *ExtraDiscriminatorArg =
8668 Attr.getNumArgs() >= 3 ? Attr.getArgAsExpr(2) : nullptr;
8669
8670 unsigned Key;
8671 if (S.checkConstantPointerAuthKey(KeyArg, Key)) {
8672 Attr.setInvalid();
8673 return;
8674 }
8675 assert(Key <= PointerAuthQualifier::MaxKey && "ptrauth key is out of range");
8676
8677 bool IsInvalid = false;
8678 unsigned IsAddressDiscriminated, ExtraDiscriminator;
8679 IsInvalid |= !S.checkPointerAuthDiscriminatorArg(IsAddressDiscriminatedArg,
8681 IsAddressDiscriminated);
8682 IsInvalid |= !S.checkPointerAuthDiscriminatorArg(
8683 ExtraDiscriminatorArg, PointerAuthDiscArgKind::Extra, ExtraDiscriminator);
8684
8685 if (IsInvalid) {
8686 Attr.setInvalid();
8687 return;
8688 }
8689
8690 if (!T->isSignableType(Ctx) && !T->isDependentType()) {
8691 S.Diag(Attr.getLoc(), diag::err_ptrauth_qualifier_invalid_target) << T;
8692 Attr.setInvalid();
8693 return;
8694 }
8695
8696 if (T.getPointerAuth()) {
8697 S.Diag(Attr.getLoc(), diag::err_ptrauth_qualifier_redundant) << T;
8698 Attr.setInvalid();
8699 return;
8700 }
8701
8702 if (!S.getLangOpts().PointerAuthIntrinsics) {
8703 S.Diag(Attr.getLoc(), diag::err_ptrauth_disabled) << Attr.getRange();
8704 Attr.setInvalid();
8705 return;
8706 }
8707
8708 assert((!IsAddressDiscriminatedArg || IsAddressDiscriminated <= 1) &&
8709 "address discriminator arg should be either 0 or 1");
8711 Key, IsAddressDiscriminated, ExtraDiscriminator,
8712 PointerAuthenticationMode::SignAndAuth, /*IsIsaPointer=*/false,
8713 /*AuthenticatesNullValues=*/false);
8714 T = S.Context.getPointerAuthType(T, Qual);
8715}
8716
8717/// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is
8718/// used to create fixed-length versions of sizeless SVE types defined by
8719/// the ACLE, such as svint32_t and svbool_t.
8721 Sema &S) {
8722 // Target must have SVE.
8723 if (!S.Context.getTargetInfo().hasFeature("sve")) {
8724 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'";
8725 Attr.setInvalid();
8726 return;
8727 }
8728
8729 // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or
8730 // if <bits>+ syntax is used.
8731 if (!S.getLangOpts().VScaleMin ||
8732 S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) {
8733 S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported)
8734 << Attr;
8735 Attr.setInvalid();
8736 return;
8737 }
8738
8739 // Check the attribute arguments.
8740 if (Attr.getNumArgs() != 1) {
8741 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8742 << Attr << 1;
8743 Attr.setInvalid();
8744 return;
8745 }
8746
8747 // The vector size must be an integer constant expression.
8748 llvm::APSInt SveVectorSizeInBits(32);
8749 if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits))
8750 return;
8751
8752 unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue());
8753
8754 // The attribute vector size must match -msve-vector-bits.
8755 if (VecSize != S.getLangOpts().VScaleMin * 128) {
8756 S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size)
8757 << VecSize << S.getLangOpts().VScaleMin * 128;
8758 Attr.setInvalid();
8759 return;
8760 }
8761
8762 // Attribute can only be attached to a single SVE vector or predicate type.
8763 if (!CurType->isSveVLSBuiltinType()) {
8764 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type)
8765 << Attr << CurType;
8766 Attr.setInvalid();
8767 return;
8768 }
8769
8770 const auto *BT = CurType->castAs<BuiltinType>();
8771
8772 QualType EltType = CurType->getSveEltType(S.Context);
8773 unsigned TypeSize = S.Context.getTypeSize(EltType);
8775 if (BT->getKind() == BuiltinType::SveBool) {
8776 // Predicates are represented as i8.
8777 VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth();
8779 } else
8780 VecSize /= TypeSize;
8781 CurType = S.Context.getVectorType(EltType, VecSize, VecKind);
8782}
8783
8784static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State,
8785 QualType &CurType,
8786 ParsedAttr &Attr) {
8787 const VectorType *VT = dyn_cast<VectorType>(CurType);
8788 if (!VT || VT->getVectorKind() != VectorKind::Neon) {
8789 State.getSema().Diag(Attr.getLoc(),
8790 diag::err_attribute_arm_mve_polymorphism);
8791 Attr.setInvalid();
8792 return;
8793 }
8794
8795 CurType =
8796 State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>(
8797 State.getSema().Context, Attr),
8798 CurType, CurType);
8799}
8800
8801/// HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is
8802/// used to create fixed-length versions of sizeless RVV types such as
8803/// vint8m1_t_t.
8805 ParsedAttr &Attr, Sema &S) {
8806 // Target must have vector extension.
8807 if (!S.Context.getTargetInfo().hasFeature("zve32x")) {
8808 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
8809 << Attr << "'zve32x'";
8810 Attr.setInvalid();
8811 return;
8812 }
8813
8814 auto VScale = S.Context.getTargetInfo().getVScaleRange(
8816 if (!VScale || !VScale->first || VScale->first != VScale->second) {
8817 S.Diag(Attr.getLoc(), diag::err_attribute_riscv_rvv_bits_unsupported)
8818 << Attr;
8819 Attr.setInvalid();
8820 return;
8821 }
8822
8823 // Check the attribute arguments.
8824 if (Attr.getNumArgs() != 1) {
8825 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8826 << Attr << 1;
8827 Attr.setInvalid();
8828 return;
8829 }
8830
8831 // The vector size must be an integer constant expression.
8832 llvm::APSInt RVVVectorSizeInBits(32);
8833 if (!verifyValidIntegerConstantExpr(S, Attr, RVVVectorSizeInBits))
8834 return;
8835
8836 // Attribute can only be attached to a single RVV vector type.
8837 if (!CurType->isRVVVLSBuiltinType()) {
8838 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_rvv_type)
8839 << Attr << CurType;
8840 Attr.setInvalid();
8841 return;
8842 }
8843
8844 unsigned VecSize = static_cast<unsigned>(RVVVectorSizeInBits.getZExtValue());
8845
8848 unsigned MinElts = Info.EC.getKnownMinValue();
8849
8851 unsigned ExpectedSize = VScale->first * MinElts;
8852 QualType EltType = CurType->getRVVEltType(S.Context);
8853 unsigned EltSize = S.Context.getTypeSize(EltType);
8854 unsigned NumElts;
8855 if (Info.ElementType == S.Context.BoolTy) {
8856 NumElts = VecSize / S.Context.getCharWidth();
8857 if (!NumElts) {
8858 NumElts = 1;
8859 switch (VecSize) {
8860 case 1:
8862 break;
8863 case 2:
8865 break;
8866 case 4:
8868 break;
8869 }
8870 } else
8872 } else {
8873 ExpectedSize *= EltSize;
8874 NumElts = VecSize / EltSize;
8875 }
8876
8877 // The attribute vector size must match -mrvv-vector-bits.
8878 if (VecSize != ExpectedSize) {
8879 S.Diag(Attr.getLoc(), diag::err_attribute_bad_rvv_vector_size)
8880 << VecSize << ExpectedSize;
8881 Attr.setInvalid();
8882 return;
8883 }
8884
8885 CurType = S.Context.getVectorType(EltType, NumElts, VecKind);
8886}
8887
8888/// Handle OpenCL Access Qualifier Attribute.
8889static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
8890 Sema &S) {
8891 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
8892 if (!(CurType->isImageType() || CurType->isPipeType())) {
8893 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
8894 Attr.setInvalid();
8895 return;
8896 }
8897
8898 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
8899 QualType BaseTy = TypedefTy->desugar();
8900
8901 std::string PrevAccessQual;
8902 if (BaseTy->isPipeType()) {
8903 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
8904 OpenCLAccessAttr *Attr =
8905 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
8906 PrevAccessQual = Attr->getSpelling();
8907 } else {
8908 PrevAccessQual = "read_only";
8909 }
8910 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
8911
8912 switch (ImgType->getKind()) {
8913 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8914 case BuiltinType::Id: \
8915 PrevAccessQual = #Access; \
8916 break;
8917 #include "clang/Basic/OpenCLImageTypes.def"
8918 default:
8919 llvm_unreachable("Unable to find corresponding image type.");
8920 }
8921 } else {
8922 llvm_unreachable("unexpected type");
8923 }
8924 StringRef AttrName = Attr.getAttrName()->getName();
8925 if (PrevAccessQual == AttrName.ltrim("_")) {
8926 // Duplicated qualifiers
8927 S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
8928 << AttrName << Attr.getRange();
8929 } else {
8930 // Contradicting qualifiers
8931 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
8932 }
8933
8934 S.Diag(TypedefTy->getDecl()->getBeginLoc(),
8935 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
8936 } else if (CurType->isPipeType()) {
8937 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
8938 QualType ElemType = CurType->castAs<PipeType>()->getElementType();
8939 CurType = S.Context.getWritePipeType(ElemType);
8940 }
8941 }
8942}
8943
8944/// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type
8945static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8946 Sema &S) {
8947 if (!S.getLangOpts().MatrixTypes) {
8948 S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled);
8949 return;
8950 }
8951
8952 if (Attr.getNumArgs() != 2) {
8953 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8954 << Attr << 2;
8955 return;
8956 }
8957
8958 Expr *RowsExpr = Attr.getArgAsExpr(0);
8959 Expr *ColsExpr = Attr.getArgAsExpr(1);
8960 QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc());
8961 if (!T.isNull())
8962 CurType = T;
8963}
8964
8965static void HandleAnnotateTypeAttr(TypeProcessingState &State,
8966 QualType &CurType, const ParsedAttr &PA) {
8967 Sema &S = State.getSema();
8968
8969 if (PA.getNumArgs() < 1) {
8970 S.Diag(PA.getLoc(), diag::err_attribute_too_few_arguments) << PA << 1;
8971 return;
8972 }
8973
8974 // Make sure that there is a string literal as the annotation's first
8975 // argument.
8976 StringRef Str;
8977 if (!S.checkStringLiteralArgumentAttr(PA, 0, Str))
8978 return;
8979
8981 Args.reserve(PA.getNumArgs() - 1);
8982 for (unsigned Idx = 1; Idx < PA.getNumArgs(); Idx++) {
8983 assert(!PA.isArgIdent(Idx));
8984 Args.push_back(PA.getArgAsExpr(Idx));
8985 }
8986 if (!S.ConstantFoldAttrArgs(PA, Args))
8987 return;
8988 auto *AnnotateTypeAttr =
8989 AnnotateTypeAttr::Create(S.Context, Str, Args.data(), Args.size(), PA);
8990 CurType = State.getAttributedType(AnnotateTypeAttr, CurType, CurType);
8991}
8992
8993static void HandleLifetimeBoundAttr(TypeProcessingState &State,
8994 QualType &CurType,
8995 ParsedAttr &Attr) {
8996 if (State.getDeclarator().isDeclarationOfFunction()) {
8997 CurType = State.getAttributedType(
8998 createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
8999 CurType, CurType);
9000 return;
9001 }
9002 State.getSema().Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
9005}
9006
9007static void HandleLifetimeCaptureByAttr(TypeProcessingState &State,
9008 QualType &CurType, ParsedAttr &PA) {
9009 if (State.getDeclarator().isDeclarationOfFunction()) {
9010 auto *Attr = State.getSema().ParseLifetimeCaptureByAttr(PA, "this");
9011 if (Attr)
9012 CurType = State.getAttributedType(Attr, CurType, CurType);
9013 }
9014}
9015
9016static void HandleHLSLParamModifierAttr(TypeProcessingState &State,
9017 QualType &CurType,
9018 const ParsedAttr &Attr, Sema &S) {
9019 // Don't apply this attribute to template dependent types. It is applied on
9020 // substitution during template instantiation. Also skip parsing this if we've
9021 // already modified the type based on an earlier attribute.
9022 if (CurType->isDependentType() || State.didParseHLSLParamMod())
9023 return;
9024 if (Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_inout ||
9025 Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_out) {
9026 State.setParsedHLSLParamMod(true);
9027 }
9028}
9029
9030static void processTypeAttrs(TypeProcessingState &state, QualType &type,
9031 TypeAttrLocation TAL,
9032 const ParsedAttributesView &attrs,
9033 CUDAFunctionTarget CFT) {
9034
9035 state.setParsedNoDeref(false);
9036 if (attrs.empty())
9037 return;
9038
9039 // Scan through and apply attributes to this type where it makes sense. Some
9040 // attributes (such as __address_space__, __vector_size__, etc) apply to the
9041 // type, but others can be present in the type specifiers even though they
9042 // apply to the decl. Here we apply type attributes and ignore the rest.
9043
9044 // This loop modifies the list pretty frequently, but we still need to make
9045 // sure we visit every element once. Copy the attributes list, and iterate
9046 // over that.
9047 ParsedAttributesView AttrsCopy{attrs};
9048 for (ParsedAttr &attr : AttrsCopy) {
9049
9050 // Skip attributes that were marked to be invalid.
9051 if (attr.isInvalid())
9052 continue;
9053
9054 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute()) {
9055 // [[gnu::...]] attributes are treated as declaration attributes, so may
9056 // not appertain to a DeclaratorChunk. If we handle them as type
9057 // attributes, accept them in that position and diagnose the GCC
9058 // incompatibility.
9059 if (attr.isGNUScope()) {
9060 assert(attr.isStandardAttributeSyntax());
9061 bool IsTypeAttr = attr.isTypeAttr();
9062 if (TAL == TAL_DeclChunk) {
9063 state.getSema().Diag(attr.getLoc(),
9064 IsTypeAttr
9065 ? diag::warn_gcc_ignores_type_attr
9066 : diag::warn_cxx11_gnu_attribute_on_type)
9067 << attr;
9068 if (!IsTypeAttr)
9069 continue;
9070 }
9071 } else if (TAL != TAL_DeclSpec && TAL != TAL_DeclChunk &&
9072 !attr.isTypeAttr()) {
9073 // Otherwise, only consider type processing for a C++11 attribute if
9074 // - it has actually been applied to a type (decl-specifier-seq or
9075 // declarator chunk), or
9076 // - it is a type attribute, irrespective of where it was applied (so
9077 // that we can support the legacy behavior of some type attributes
9078 // that can be applied to the declaration name).
9079 continue;
9080 }
9081 }
9082
9083 // If this is an attribute we can handle, do so now,
9084 // otherwise, add it to the FnAttrs list for rechaining.
9085 switch (attr.getKind()) {
9086 default:
9087 // A [[]] attribute on a declarator chunk must appertain to a type.
9088 if ((attr.isStandardAttributeSyntax() ||
9089 attr.isRegularKeywordAttribute()) &&
9090 TAL == TAL_DeclChunk) {
9091 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
9092 << attr << attr.isRegularKeywordAttribute();
9093 attr.setUsedAsTypeAttr();
9094 }
9095 break;
9096
9098 if (attr.isStandardAttributeSyntax()) {
9099 state.getSema().DiagnoseUnknownAttribute(attr);
9100 // Mark the attribute as invalid so we don't emit the same diagnostic
9101 // multiple times.
9102 attr.setInvalid();
9103 }
9104 break;
9105
9107 break;
9108
9109 case ParsedAttr::AT_BTFTypeTag:
9111 attr.setUsedAsTypeAttr();
9112 break;
9113
9114 case ParsedAttr::AT_MayAlias:
9115 // FIXME: This attribute needs to actually be handled, but if we ignore
9116 // it it breaks large amounts of Linux software.
9117 attr.setUsedAsTypeAttr();
9118 break;
9119 case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace:
9120 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace:
9121 state.getSema().Diag(attr.getLoc(), diag::warn_deprecated_attribute)
9122 << attr;
9123 [[fallthrough]];
9124 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
9125 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
9126 case ParsedAttr::AT_OpenCLLocalAddressSpace:
9127 case ParsedAttr::AT_OpenCLConstantAddressSpace:
9128 case ParsedAttr::AT_OpenCLGenericAddressSpace:
9129 case ParsedAttr::AT_AddressSpace:
9131 attr.setUsedAsTypeAttr();
9132 break;
9133 case ParsedAttr::AT_HLSLGroupSharedAddressSpace:
9135 if (state.getDeclarator().getContext() == DeclaratorContext::Prototype) {
9136 if (state.getSema().getLangOpts().getHLSLVersion() <
9138 state.getSema().Diag(attr.getLoc(), diag::warn_hlsl_groupshared_202x);
9139
9140 // Note: we don't check for the usage of HLSLParamModifiers in/out/inout
9141 // here because the check in the AT_HLSLParamModifier case is sufficient
9142 // regardless of the order of groupshared or in/out/inout specified in
9143 // the parameter. And checking there produces a better error message.
9144 }
9145 attr.setUsedAsTypeAttr();
9146 break;
9147 case ParsedAttr::AT_HLSLRowMajor:
9148 case ParsedAttr::AT_HLSLColumnMajor:
9149 if (Attr *A =
9150 state.getSema().HLSL().buildMatrixLayoutTypeAttr(type, attr))
9151 type = state.getAttributedType(A, type, type);
9152 attr.setUsedAsTypeAttr();
9153 break;
9155 if (!handleObjCPointerTypeAttr(state, attr, type))
9157 attr.setUsedAsTypeAttr();
9158 break;
9159 case ParsedAttr::AT_VectorSize:
9160 HandleVectorSizeAttr(type, attr, state.getSema());
9161 attr.setUsedAsTypeAttr();
9162 break;
9163 case ParsedAttr::AT_ExtVectorType:
9164 HandleExtVectorTypeAttr(type, attr, state.getSema());
9165 attr.setUsedAsTypeAttr();
9166 break;
9167 case ParsedAttr::AT_NeonVectorType:
9169 attr.setUsedAsTypeAttr();
9170 break;
9171 case ParsedAttr::AT_NeonPolyVectorType:
9172 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
9174 attr.setUsedAsTypeAttr();
9175 break;
9176 case ParsedAttr::AT_ArmSveVectorBits:
9177 HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema());
9178 attr.setUsedAsTypeAttr();
9179 break;
9180 case ParsedAttr::AT_ArmMveStrictPolymorphism: {
9182 attr.setUsedAsTypeAttr();
9183 break;
9184 }
9185 case ParsedAttr::AT_RISCVRVVVectorBits:
9186 HandleRISCVRVVVectorBitsTypeAttr(type, attr, state.getSema());
9187 attr.setUsedAsTypeAttr();
9188 break;
9189 case ParsedAttr::AT_OpenCLAccess:
9190 HandleOpenCLAccessAttr(type, attr, state.getSema());
9191 attr.setUsedAsTypeAttr();
9192 break;
9193 case ParsedAttr::AT_PointerAuth:
9194 HandlePtrAuthQualifier(state.getSema().Context, type, attr,
9195 state.getSema());
9196 attr.setUsedAsTypeAttr();
9197 break;
9198 case ParsedAttr::AT_LifetimeBound:
9199 if (TAL == TAL_DeclChunk)
9201 break;
9202 case ParsedAttr::AT_LifetimeCaptureBy:
9203 if (TAL == TAL_DeclChunk)
9205 break;
9206 case ParsedAttr::AT_OverflowBehavior:
9208 attr.setUsedAsTypeAttr();
9209 break;
9210
9211 case ParsedAttr::AT_NoDeref: {
9212 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
9213 // See https://github.com/llvm/llvm-project/issues/55790 for details.
9214 // For the time being, we simply emit a warning that the attribute is
9215 // ignored.
9216 if (attr.isStandardAttributeSyntax()) {
9217 state.getSema().Diag(attr.getLoc(), diag::warn_attribute_ignored)
9218 << attr;
9219 break;
9220 }
9221 ASTContext &Ctx = state.getSema().Context;
9222 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
9223 type, type);
9224 attr.setUsedAsTypeAttr();
9225 state.setParsedNoDeref(true);
9226 break;
9227 }
9228
9229 case ParsedAttr::AT_MatrixType:
9230 HandleMatrixTypeAttr(type, attr, state.getSema());
9231 attr.setUsedAsTypeAttr();
9232 break;
9233
9234 case ParsedAttr::AT_WebAssemblyFuncref: {
9236 attr.setUsedAsTypeAttr();
9237 break;
9238 }
9239
9240 case ParsedAttr::AT_HLSLParamModifier: {
9241 HandleHLSLParamModifierAttr(state, type, attr, state.getSema());
9242 if (attrs.hasAttribute(ParsedAttr::AT_HLSLGroupSharedAddressSpace)) {
9243 state.getSema().Diag(attr.getLoc(), diag::err_hlsl_attr_incompatible)
9244 << attr << "'groupshared'";
9245 attr.setInvalid();
9246 return;
9247 }
9248 attr.setUsedAsTypeAttr();
9249 break;
9250 }
9251
9252 case ParsedAttr::AT_SwiftAttr: {
9253 HandleSwiftAttr(state, TAL, type, attr);
9254 break;
9255 }
9256
9259 attr.setUsedAsTypeAttr();
9260 break;
9261
9262
9264 // Either add nullability here or try to distribute it. We
9265 // don't want to distribute the nullability specifier past any
9266 // dependent type, because that complicates the user model.
9267 if (type->canHaveNullability() || type->isDependentType() ||
9268 type->isArrayType() ||
9270 unsigned endIndex;
9271 if (TAL == TAL_DeclChunk)
9272 endIndex = state.getCurrentChunkIndex();
9273 else
9274 endIndex = state.getDeclarator().getNumTypeObjects();
9275 bool allowOnArrayType =
9276 state.getDeclarator().isPrototypeContext() &&
9277 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
9279 allowOnArrayType)) {
9280 attr.setInvalid();
9281 }
9282
9283 attr.setUsedAsTypeAttr();
9284 }
9285 break;
9286
9287 case ParsedAttr::AT_ObjCKindOf:
9288 // '__kindof' must be part of the decl-specifiers.
9289 switch (TAL) {
9290 case TAL_DeclSpec:
9291 break;
9292
9293 case TAL_DeclChunk:
9294 case TAL_DeclName:
9295 state.getSema().Diag(attr.getLoc(),
9296 diag::err_objc_kindof_wrong_position)
9297 << FixItHint::CreateRemoval(attr.getLoc())
9299 state.getDeclarator().getDeclSpec().getBeginLoc(),
9300 "__kindof ");
9301 break;
9302 }
9303
9304 // Apply it regardless.
9305 if (checkObjCKindOfType(state, type, attr))
9306 attr.setInvalid();
9307 break;
9308
9309 case ParsedAttr::AT_NoThrow:
9310 // Exception Specifications aren't generally supported in C mode throughout
9311 // clang, so revert to attribute-based handling for C.
9312 if (!state.getSema().getLangOpts().CPlusPlus)
9313 break;
9314 [[fallthrough]];
9316
9317 attr.setUsedAsTypeAttr();
9318
9319 // Attributes with standard syntax have strict rules for what they
9320 // appertain to and hence should not use the "distribution" logic below.
9321 if (attr.isStandardAttributeSyntax() ||
9322 attr.isRegularKeywordAttribute()) {
9323 if (!handleFunctionTypeAttr(state, attr, type, CFT)) {
9324 diagnoseBadTypeAttribute(state.getSema(), attr, type);
9325 attr.setInvalid();
9326 }
9327 break;
9328 }
9329
9330 // Never process function type attributes as part of the
9331 // declaration-specifiers.
9332 if (TAL == TAL_DeclSpec)
9334
9335 // Otherwise, handle the possible delays.
9336 else if (!handleFunctionTypeAttr(state, attr, type, CFT))
9338 break;
9339 case ParsedAttr::AT_AcquireHandle: {
9340 if (!type->isFunctionType())
9341 return;
9342
9343 if (attr.getNumArgs() != 1) {
9344 state.getSema().Diag(attr.getLoc(),
9345 diag::err_attribute_wrong_number_arguments)
9346 << attr << 1;
9347 attr.setInvalid();
9348 return;
9349 }
9350
9351 StringRef HandleType;
9352 if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType))
9353 return;
9354 type = state.getAttributedType(
9355 AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr),
9356 type, type);
9357 attr.setUsedAsTypeAttr();
9358 break;
9359 }
9360 case ParsedAttr::AT_AnnotateType: {
9362 attr.setUsedAsTypeAttr();
9363 break;
9364 }
9365 case ParsedAttr::AT_HLSLResourceClass:
9366 case ParsedAttr::AT_HLSLResourceDimension:
9367 case ParsedAttr::AT_HLSLIsROV:
9368 case ParsedAttr::AT_HLSLRawBuffer:
9369 case ParsedAttr::AT_HLSLIsArray:
9370 case ParsedAttr::AT_HLSLIsMultiSampled:
9371 case ParsedAttr::AT_HLSLContainedType: {
9372 // Only collect HLSL resource type attributes that are in
9373 // decl-specifier-seq; do not collect attributes on declarations or those
9374 // that get to slide after declaration name.
9375 if (TAL == TAL_DeclSpec &&
9376 state.getSema().HLSL().handleResourceTypeAttr(type, attr))
9377 attr.setUsedAsTypeAttr();
9378 break;
9379 }
9380 }
9381
9382 // Handle attributes that are defined in a macro. We do not want this to be
9383 // applied to ObjC builtin attributes.
9384 if (isa<AttributedType>(type) && attr.hasMacroIdentifier() &&
9385 !type.getQualifiers().hasObjCLifetime() &&
9386 !type.getQualifiers().hasObjCGCAttr() &&
9387 attr.getKind() != ParsedAttr::AT_ObjCGC &&
9388 attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
9389 const IdentifierInfo *MacroII = attr.getMacroIdentifier();
9390 type = state.getSema().Context.getMacroQualifiedType(type, MacroII);
9391 state.setExpansionLocForMacroQualifiedType(
9392 cast<MacroQualifiedType>(type.getTypePtr()),
9393 attr.getMacroExpansionLoc());
9394 }
9395 }
9396}
9397
9399 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
9400 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
9401 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
9402 auto *Def = Var->getDefinition();
9403 if (!Def) {
9404 SourceLocation PointOfInstantiation = E->getExprLoc();
9405 runWithSufficientStackSpace(PointOfInstantiation, [&] {
9406 InstantiateVariableDefinition(PointOfInstantiation, Var);
9407 });
9408 Def = Var->getDefinition();
9409
9410 // If we don't already have a point of instantiation, and we managed
9411 // to instantiate a definition, this is the point of instantiation.
9412 // Otherwise, we don't request an end-of-TU instantiation, so this is
9413 // not a point of instantiation.
9414 // FIXME: Is this really the right behavior?
9415 if (Var->getPointOfInstantiation().isInvalid() && Def) {
9416 assert(Var->getTemplateSpecializationKind() ==
9418 "explicit instantiation with no point of instantiation");
9419 Var->setTemplateSpecializationKind(
9420 Var->getTemplateSpecializationKind(), PointOfInstantiation);
9421 }
9422 }
9423
9424 // Update the type to the definition's type both here and within the
9425 // expression.
9426 if (Def) {
9427 DRE->setDecl(Def);
9428 QualType T = Def->getType();
9429 DRE->setType(T);
9430 // FIXME: Update the type on all intervening expressions.
9431 E->setType(T);
9432 }
9433
9434 // We still go on to try to complete the type independently, as it
9435 // may also require instantiations or diagnostics if it remains
9436 // incomplete.
9437 }
9438 }
9439 }
9440 if (const auto CastE = dyn_cast<ExplicitCastExpr>(E)) {
9441 QualType DestType = CastE->getTypeAsWritten();
9442 if (const auto *IAT = Context.getAsIncompleteArrayType(DestType)) {
9443 // C++20 [expr.static.cast]p.4: ... If T is array of unknown bound,
9444 // this direct-initialization defines the type of the expression
9445 // as U[1]
9446 QualType ResultType = Context.getConstantArrayType(
9447 IAT->getElementType(),
9448 llvm::APInt(Context.getTypeSize(Context.getSizeType()), 1),
9449 /*SizeExpr=*/nullptr, ArraySizeModifier::Normal,
9450 /*IndexTypeQuals=*/0);
9451 E->setType(ResultType);
9452 }
9453 }
9454}
9455
9457 // Incomplete array types may be completed by the initializer attached to
9458 // their definitions. For static data members of class templates and for
9459 // variable templates, we need to instantiate the definition to get this
9460 // initializer and complete the type.
9461 if (E->getType()->isIncompleteArrayType())
9463
9464 // FIXME: Are there other cases which require instantiating something other
9465 // than the type to complete the type of an expression?
9466
9467 return E->getType();
9468}
9469
9471 TypeDiagnoser &Diagnoser) {
9472 return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind,
9473 Diagnoser);
9474}
9475
9476bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
9477 BoundTypeDiagnoser<> Diagnoser(DiagID);
9479}
9480
9482 CompleteTypeKind Kind,
9483 TypeDiagnoser &Diagnoser) {
9484 if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser))
9485 return true;
9486 if (auto *TD = T->getAsTagDecl(); TD && !TD->isCompleteDefinitionRequired()) {
9487 TD->setCompleteDefinitionRequired();
9488 Consumer.HandleTagDeclRequiredDefinition(TD);
9489 }
9490 return false;
9491}
9492
9495 if (!Suggested)
9496 return false;
9497
9498 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
9499 // and isolate from other C++ specific checks.
9501 getLangOpts(), D->getASTContext(), Suggested->getASTContext(),
9502 NonEquivalentDecls, StructuralEquivalenceKind::Default,
9503 /*StrictTypeSpelling=*/false, /*Complain=*/true,
9504 /*ErrorOnTagTypeMismatch=*/true);
9505 return Ctx.IsEquivalent(D, Suggested);
9506}
9507
9509 AcceptableKind Kind, bool OnlyNeedComplete) {
9510 // Easy case: if we don't have modules, all declarations are visible.
9511 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
9512 return true;
9513
9514 // If this definition was instantiated from a template, map back to the
9515 // pattern from which it was instantiated.
9516 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined())
9517 // We're in the middle of defining it; this definition should be treated
9518 // as visible.
9519 return true;
9520
9521 auto DefinitionIsAcceptable = [&](NamedDecl *D) {
9522 // The (primary) definition might be in a visible module.
9523 if (isAcceptable(D, Kind))
9524 return true;
9525
9526 // A visible module might have a merged definition instead.
9529 if (CodeSynthesisContexts.empty() &&
9530 !getLangOpts().ModulesLocalVisibility) {
9531 // Cache the fact that this definition is implicitly visible because
9532 // there is a visible merged definition.
9534 }
9535 return true;
9536 }
9537
9538 return false;
9539 };
9540 auto IsDefinition = [](NamedDecl *D) {
9541 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
9542 return RD->isThisDeclarationADefinition();
9543 if (auto *ED = dyn_cast<EnumDecl>(D))
9544 return ED->isThisDeclarationADefinition();
9545 if (auto *FD = dyn_cast<FunctionDecl>(D))
9546 return FD->isThisDeclarationADefinition();
9547 if (auto *VD = dyn_cast<VarDecl>(D))
9548 return VD->isThisDeclarationADefinition() == VarDecl::Definition;
9549 llvm_unreachable("unexpected decl type");
9550 };
9551 auto FoundAcceptableDefinition = [&](NamedDecl *D) {
9553 return DefinitionIsAcceptable(D);
9554
9555 // See ASTDeclReader::attachPreviousDeclImpl. Now we still
9556 // may demote definition to declaration for decls in haeder modules,
9557 // so avoid looking at its redeclaration to save time.
9558 // NOTE: If we don't demote definition to declarations for decls
9559 // in header modules, remove the condition.
9561 return DefinitionIsAcceptable(D);
9562
9563 for (auto *RD : D->redecls()) {
9564 auto *ND = cast<NamedDecl>(RD);
9565 if (!IsDefinition(ND))
9566 continue;
9567 if (DefinitionIsAcceptable(ND)) {
9568 *Suggested = ND;
9569 return true;
9570 }
9571 }
9572
9573 return false;
9574 };
9575
9576 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9577 if (auto *Pattern = RD->getTemplateInstantiationPattern())
9578 RD = Pattern;
9579 D = RD->getDefinition();
9580 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
9581 if (auto *Pattern = ED->getTemplateInstantiationPattern())
9582 ED = Pattern;
9583 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) {
9584 // If the enum has a fixed underlying type, it may have been forward
9585 // declared. In -fms-compatibility, `enum Foo;` will also forward declare
9586 // the enum and assign it the underlying type of `int`. Since we're only
9587 // looking for a complete type (not a definition), any visible declaration
9588 // of it will do.
9589 *Suggested = nullptr;
9590 for (auto *Redecl : ED->redecls()) {
9591 if (isAcceptable(Redecl, Kind))
9592 return true;
9593 if (Redecl->isThisDeclarationADefinition() ||
9594 (Redecl->isCanonicalDecl() && !*Suggested))
9595 *Suggested = Redecl;
9596 }
9597
9598 return false;
9599 }
9600 D = ED->getDefinition();
9601 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
9602 if (auto *Pattern = FD->getTemplateInstantiationPattern())
9603 FD = Pattern;
9604 D = FD->getDefinition();
9605 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
9606 if (auto *Pattern = VD->getTemplateInstantiationPattern())
9607 VD = Pattern;
9608 D = VD->getDefinition();
9609 }
9610
9611 assert(D && "missing definition for pattern of instantiated definition");
9612
9613 *Suggested = D;
9614
9615 if (FoundAcceptableDefinition(D))
9616 return true;
9617
9618 // The external source may have additional definitions of this entity that are
9619 // visible, so complete the redeclaration chain now and ask again.
9620 if (auto *Source = Context.getExternalSource()) {
9621 Source->CompleteRedeclChain(D);
9622 return FoundAcceptableDefinition(D);
9623 }
9624
9625 return false;
9626}
9627
9628/// Determine whether there is any declaration of \p D that was ever a
9629/// definition (perhaps before module merging) and is currently visible.
9630/// \param D The definition of the entity.
9631/// \param Suggested Filled in with the declaration that should be made visible
9632/// in order to provide a definition of this entity.
9633/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9634/// not defined. This only matters for enums with a fixed underlying
9635/// type, since in all other cases, a type is complete if and only if it
9636/// is defined.
9638 bool OnlyNeedComplete) {
9640 OnlyNeedComplete);
9641}
9642
9643/// Determine whether there is any declaration of \p D that was ever a
9644/// definition (perhaps before module merging) and is currently
9645/// reachable.
9646/// \param D The definition of the entity.
9647/// \param Suggested Filled in with the declaration that should be made
9648/// reachable
9649/// in order to provide a definition of this entity.
9650/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9651/// not defined. This only matters for enums with a fixed underlying
9652/// type, since in all other cases, a type is complete if and only if it
9653/// is defined.
9655 bool OnlyNeedComplete) {
9657 OnlyNeedComplete);
9658}
9659
9660/// Locks in the inheritance model for the given class and all of its bases.
9662 RD = RD->getMostRecentDecl();
9663 if (!RD->hasAttr<MSInheritanceAttr>()) {
9665 bool BestCase = false;
9668 BestCase = true;
9669 IM = RD->calculateInheritanceModel();
9670 break;
9673 break;
9676 break;
9679 break;
9680 }
9681
9684 : RD->getSourceRange();
9685 RD->addAttr(MSInheritanceAttr::CreateImplicit(
9686 S.getASTContext(), BestCase, Loc, MSInheritanceAttr::Spelling(IM)));
9688 }
9689}
9690
9691bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
9692 CompleteTypeKind Kind,
9693 TypeDiagnoser *Diagnoser) {
9694 // FIXME: Add this assertion to make sure we always get instantiation points.
9695 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
9696 // FIXME: Add this assertion to help us flush out problems with
9697 // checking for dependent types and type-dependent expressions.
9698 //
9699 // assert(!T->isDependentType() &&
9700 // "Can't ask whether a dependent type is complete");
9701
9702 if (const auto *MPTy = dyn_cast<MemberPointerType>(T.getCanonicalType())) {
9703 if (CXXRecordDecl *RD = MPTy->getMostRecentCXXRecordDecl();
9704 RD && !RD->isDependentType()) {
9705 CanQualType T = Context.getCanonicalTagType(RD);
9706 if (getLangOpts().CompleteMemberPointers && !RD->isBeingDefined() &&
9707 RequireCompleteType(Loc, T, Kind, diag::err_memptr_incomplete))
9708 return true;
9709
9710 // We lock in the inheritance model once somebody has asked us to ensure
9711 // that a pointer-to-member type is complete.
9712 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9713 (void)isCompleteType(Loc, T);
9714 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
9715 }
9716 }
9717 }
9718
9719 NamedDecl *Def = nullptr;
9721 bool Incomplete = (T->isIncompleteType(&Def) ||
9723
9724 // Check that any necessary explicit specializations are visible. For an
9725 // enum, we just need the declaration, so don't check this.
9726 if (Def && !isa<EnumDecl>(Def))
9728
9729 // If we have a complete type, we're done.
9730 if (!Incomplete) {
9731 NamedDecl *Suggested = nullptr;
9732 if (Def &&
9733 !hasReachableDefinition(Def, &Suggested, /*OnlyNeedComplete=*/true)) {
9734 // If the user is going to see an error here, recover by making the
9735 // definition visible.
9736 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
9737 if (Diagnoser && Suggested)
9739 /*Recover*/ TreatAsComplete);
9740 return !TreatAsComplete;
9741 }
9742 return false;
9743 }
9744
9745 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
9746 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
9747
9748 // Give the external source a chance to provide a definition of the type.
9749 // This is kept separate from completing the redeclaration chain so that
9750 // external sources such as LLDB can avoid synthesizing a type definition
9751 // unless it's actually needed.
9752 if (Tag || IFace) {
9753 // Avoid diagnosing invalid decls as incomplete.
9754 if (Def->isInvalidDecl())
9755 return true;
9756
9757 // Give the external AST source a chance to complete the type.
9758 if (auto *Source = Context.getExternalSource()) {
9759 if (Tag && Tag->hasExternalLexicalStorage())
9760 Source->CompleteType(Tag);
9761 if (IFace && IFace->hasExternalLexicalStorage())
9762 Source->CompleteType(IFace);
9763 // If the external source completed the type, go through the motions
9764 // again to ensure we're allowed to use the completed type.
9765 if (!T->isIncompleteType())
9766 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9767 }
9768 }
9769
9770 // If we have a class template specialization or a class member of a
9771 // class template specialization, or an array with known size of such,
9772 // try to instantiate it.
9773 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
9774 bool Instantiated = false;
9775 bool Diagnosed = false;
9776 if (RD->isDependentContext()) {
9777 // Don't try to instantiate a dependent class (eg, a member template of
9778 // an instantiated class template specialization).
9779 // FIXME: Can this ever happen?
9780 } else if (auto *ClassTemplateSpec =
9781 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
9782 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
9785 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
9786 /*Complain=*/Diagnoser, ClassTemplateSpec->hasStrictPackMatch());
9787 });
9788 Instantiated = true;
9789 }
9790 } else {
9791 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
9792 if (!RD->isBeingDefined() && Pattern) {
9793 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
9794 assert(MSI && "Missing member specialization information?");
9795 // This record was instantiated from a class within a template.
9796 if (MSI->getTemplateSpecializationKind() !=
9799 Diagnosed = InstantiateClass(Loc, RD, Pattern,
9802 /*Complain=*/Diagnoser);
9803 });
9804 Instantiated = true;
9805 }
9806 }
9807 }
9808
9809 if (Instantiated) {
9810 // Instantiate* might have already complained that the template is not
9811 // defined, if we asked it to.
9812 if (Diagnoser && Diagnosed)
9813 return true;
9814 // If we instantiated a definition, check that it's usable, even if
9815 // instantiation produced an error, so that repeated calls to this
9816 // function give consistent answers.
9817 if (!T->isIncompleteType())
9818 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9819 }
9820 }
9821
9822 // FIXME: If we didn't instantiate a definition because of an explicit
9823 // specialization declaration, check that it's visible.
9824
9825 if (!Diagnoser)
9826 return true;
9827
9828 Diagnoser->diagnose(*this, Loc, T);
9829
9830 // If the type was a forward declaration of a class/struct/union
9831 // type, produce a note.
9832 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid())
9833 Diag(Tag->getLocation(), Tag->isBeingDefined()
9834 ? diag::note_type_being_defined
9835 : diag::note_forward_declaration)
9836 << Context.getCanonicalTagType(Tag);
9837
9838 // If the Objective-C class was a forward declaration, produce a note.
9839 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid())
9840 Diag(IFace->getLocation(), diag::note_forward_class);
9841
9842 // If we have external information that we can use to suggest a fix,
9843 // produce a note.
9844 if (ExternalSource)
9845 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
9846
9847 return true;
9848}
9849
9851 CompleteTypeKind Kind, unsigned DiagID) {
9852 BoundTypeDiagnoser<> Diagnoser(DiagID);
9853 return RequireCompleteType(Loc, T, Kind, Diagnoser);
9854}
9855
9856/// Get diagnostic %select index for tag kind for
9857/// literal type diagnostic message.
9858/// WARNING: Indexes apply to particular diagnostics only!
9859///
9860/// \returns diagnostic %select index.
9862 switch (Tag) {
9864 return 0;
9866 return 1;
9867 case TagTypeKind::Class:
9868 return 2;
9869 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
9870 }
9871}
9872
9874 TypeDiagnoser &Diagnoser) {
9875 assert(!T->isDependentType() && "type should not be dependent");
9876
9877 QualType ElemType = Context.getBaseElementType(T);
9878 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
9879 T->isLiteralType(Context))
9880 return false;
9881
9882 Diagnoser.diagnose(*this, Loc, T);
9883
9884 if (T->isVariableArrayType())
9885 return true;
9886
9887 if (!ElemType->isRecordType())
9888 return true;
9889
9890 // A partially-defined class type can't be a literal type, because a literal
9891 // class type must have a trivial destructor (which can't be checked until
9892 // the class definition is complete).
9893 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
9894 return true;
9895
9896 const auto *RD = ElemType->castAsCXXRecordDecl();
9897 // [expr.prim.lambda]p3:
9898 // This class type is [not] a literal type.
9899 if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
9900 Diag(RD->getLocation(), diag::note_non_literal_lambda);
9901 return true;
9902 }
9903
9904 // If the class has virtual base classes, then it's not an aggregate, and
9905 // cannot have any constexpr constructors or a trivial default constructor,
9906 // so is non-literal. This is better to diagnose than the resulting absence
9907 // of constexpr constructors.
9908 if (!getLangOpts().CPlusPlus26 && RD->getNumVBases()) {
9909 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
9910 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
9911 for (const auto &I : RD->vbases())
9912 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
9913 << I.getSourceRange();
9914 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
9915 !RD->hasTrivialDefaultConstructor()) {
9916 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
9917 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
9918 for (const auto &I : RD->bases()) {
9919 if (!I.getType()->isLiteralType(Context)) {
9920 Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
9921 << RD << I.getType() << I.getSourceRange();
9922 return true;
9923 }
9924 }
9925 for (const auto *I : RD->fields()) {
9926 if (!I->getType()->isLiteralType(Context) ||
9927 I->getType().isVolatileQualified()) {
9928 Diag(I->getLocation(), diag::note_non_literal_field)
9929 << RD << I << I->getType()
9930 << I->getType().isVolatileQualified();
9931 return true;
9932 }
9933 }
9934 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor()
9935 : !RD->hasTrivialDestructor()) {
9936 // All fields and bases are of literal types, so have trivial or constexpr
9937 // destructors. If this class's destructor is non-trivial / non-constexpr,
9938 // it must be user-declared.
9939 CXXDestructorDecl *Dtor = RD->getDestructor();
9940 assert(Dtor && "class has literal fields and bases but no dtor?");
9941 if (!Dtor)
9942 return true;
9943
9944 if (getLangOpts().CPlusPlus20) {
9945 Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor)
9946 << RD;
9947 } else {
9948 Diag(Dtor->getLocation(), Dtor->isUserProvided()
9949 ? diag::note_non_literal_user_provided_dtor
9950 : diag::note_non_literal_nontrivial_dtor)
9951 << RD;
9952 if (!Dtor->isUserProvided())
9955 /*Diagnose*/ true);
9956 }
9957 }
9958
9959 return true;
9960}
9961
9963 BoundTypeDiagnoser<> Diagnoser(DiagID);
9964 return RequireLiteralType(Loc, T, Diagnoser);
9965}
9966
9968 assert(!E->hasPlaceholderType() && "unexpected placeholder");
9969
9970 if (!getLangOpts().CPlusPlus && E->refersToBitField())
9971 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
9972 << (Kind == TypeOfKind::Unqualified ? 3 : 2);
9973
9974 if (!E->isTypeDependent()) {
9975 QualType T = E->getType();
9976 if (const TagType *TT = T->getAs<TagType>())
9977 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
9978 }
9979 return Context.getTypeOfExprType(E, Kind);
9980}
9981
9982static void
9985 // Currently, 'counted_by' only allows direct DeclRefExpr to FieldDecl.
9986 auto *CountDecl = cast<DeclRefExpr>(E)->getDecl();
9987 Decls.push_back(TypeCoupledDeclRefInfo(CountDecl, /*IsDref*/ false));
9988}
9989
9991 Expr *CountExpr,
9992 bool CountInBytes,
9993 bool OrNull) {
9994 assert(WrappedTy->isIncompleteArrayType() || WrappedTy->isPointerType());
9995
9997 BuildTypeCoupledDecls(CountExpr, Decls);
9998 /// When the resulting expression is invalid, we still create the AST using
9999 /// the original count expression for the sake of AST dump.
10000 return Context.getCountAttributedType(WrappedTy, CountExpr, CountInBytes,
10001 OrNull, Decls);
10002}
10003
10004/// getDecltypeForExpr - Given an expr, will return the decltype for
10005/// that expression, according to the rules in C++11
10006/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
10008
10009 Expr *IDExpr = E;
10010 if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E))
10011 IDExpr = ImplCastExpr->getSubExpr();
10012
10013 if (auto *PackExpr = dyn_cast<PackIndexingExpr>(E)) {
10014 if (E->isInstantiationDependent())
10015 IDExpr = PackExpr->getPackIdExpression();
10016 else
10017 IDExpr = PackExpr->getSelectedExpr();
10018 }
10019
10020 if (E->isTypeDependent())
10021 return Context.DependentTy;
10022
10023 // C++11 [dcl.type.simple]p4:
10024 // The type denoted by decltype(e) is defined as follows:
10025
10026 // C++20:
10027 // - if E is an unparenthesized id-expression naming a non-type
10028 // template-parameter (13.2), decltype(E) is the type of the
10029 // template-parameter after performing any necessary type deduction
10030 // Note that this does not pick up the implicit 'const' for a template
10031 // parameter object. This rule makes no difference before C++20 so we apply
10032 // it unconditionally.
10033 if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr))
10034 IDExpr = SNTTPE->getReplacement();
10035
10036 // - if e is an unparenthesized id-expression or an unparenthesized class
10037 // member access (5.2.5), decltype(e) is the type of the entity named
10038 // by e. If there is no such entity, or if e names a set of overloaded
10039 // functions, the program is ill-formed;
10040 //
10041 // We apply the same rules for Objective-C ivar and property references.
10042 if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) {
10043 const ValueDecl *VD = DRE->getDecl();
10044 QualType T = VD->getType();
10045 return isa<TemplateParamObjectDecl>(VD) ? T.getUnqualifiedType() : T;
10046 }
10047 if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) {
10048 if (const auto *VD = ME->getMemberDecl())
10049 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
10050 return VD->getType();
10051 } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) {
10052 return IR->getDecl()->getType();
10053 } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) {
10054 if (PR->isExplicitProperty())
10055 return PR->getExplicitProperty()->getType();
10056 } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) {
10057 return PE->getType();
10058 }
10059
10060 // C++11 [expr.lambda.prim]p18:
10061 // Every occurrence of decltype((x)) where x is a possibly
10062 // parenthesized id-expression that names an entity of automatic
10063 // storage duration is treated as if x were transformed into an
10064 // access to a corresponding data member of the closure type that
10065 // would have been declared if x were an odr-use of the denoted
10066 // entity.
10067 if (getCurLambda() && isa<ParenExpr>(IDExpr)) {
10068 if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) {
10069 if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
10070 QualType T = getCapturedDeclRefType(Var, DRE->getLocation());
10071 if (!T.isNull())
10072 return Context.getLValueReferenceType(T);
10073 }
10074 }
10075 }
10076
10077 return Context.getReferenceQualifiedType(E);
10078}
10079
10080QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) {
10081 assert(!E->hasPlaceholderType() && "unexpected placeholder");
10082
10083 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
10084 !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) {
10085 // The expression operand for decltype is in an unevaluated expression
10086 // context, so side effects could result in unintended consequences.
10087 // Exclude instantiation-dependent expressions, because 'decltype' is often
10088 // used to build SFINAE gadgets.
10089 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
10090 }
10091 return Context.getDecltypeType(E, getDecltypeForExpr(E));
10092}
10093
10095 SourceLocation Loc,
10096 SourceLocation EllipsisLoc) {
10097 if (!IndexExpr)
10098 return QualType();
10099
10100 // Diagnose unexpanded packs but continue to improve recovery.
10101 if (!Pattern->containsUnexpandedParameterPack())
10102 Diag(Loc, diag::err_expected_name_of_pack) << Pattern;
10103
10104 QualType Type = BuildPackIndexingType(Pattern, IndexExpr, Loc, EllipsisLoc);
10105
10106 if (!Type.isNull())
10107 DiagCompat(Loc, diag_compat::pack_indexing);
10108 return Type;
10109}
10110
10112 SourceLocation Loc,
10113 SourceLocation EllipsisLoc,
10114 bool FullySubstituted,
10115 ArrayRef<QualType> Expansions) {
10116
10117 UnsignedOrNone Index = std::nullopt;
10118 if (!IndexExpr->isInstantiationDependent()) {
10119 llvm::APSInt Value;
10121 IndexExpr, Context.getSizeType(), Value, CCEKind::PackIndex);
10122
10123 if (!Res.isUsable() || !Value.isRepresentableByInt64())
10124 return QualType();
10125
10126 IndexExpr = Res.get();
10127 uint64_t V = Value.getZExtValue();
10128 if (FullySubstituted && V >= Expansions.size()) {
10129 Diag(IndexExpr->getBeginLoc(), diag::err_pack_index_out_of_bound)
10130 << V << Pattern << Expansions.size();
10131 return QualType();
10132 }
10133 Index = static_cast<unsigned>(V);
10134 }
10135
10136 return Context.getPackIndexingType(Pattern, IndexExpr, FullySubstituted,
10137 Expansions, Index);
10138}
10139
10141 SourceLocation Loc) {
10142 assert(BaseType->isEnumeralType());
10143 EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl();
10144
10145 S.DiagnoseUseOfDecl(ED, Loc);
10146
10147 QualType Underlying = ED->getIntegerType();
10148 if (Underlying.isNull()) {
10149 Underlying = ED->getDefinition()->getIntegerType();
10150 assert(!Underlying.isNull());
10151 }
10152
10153 return Underlying;
10154}
10155
10157 SourceLocation Loc) {
10158 if (!BaseType->isEnumeralType()) {
10159 Diag(Loc, diag::err_only_enums_have_underlying_types);
10160 return QualType();
10161 }
10162
10163 // The enum could be incomplete if we're parsing its definition or
10164 // recovering from an error.
10165 NamedDecl *FwdDecl = nullptr;
10166 if (BaseType->isIncompleteType(&FwdDecl)) {
10167 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
10168 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
10169 return QualType();
10170 }
10171
10172 return GetEnumUnderlyingType(*this, BaseType, Loc);
10173}
10174
10176 QualType Pointer = BaseType.isReferenceable() || BaseType->isVoidType()
10177 ? BuildPointerType(BaseType.getNonReferenceType(), Loc,
10179 : BaseType;
10180
10181 return Pointer.isNull() ? QualType() : Pointer;
10182}
10183
10185 if (!BaseType->isAnyPointerType())
10186 return BaseType;
10187
10188 return BaseType->getPointeeType();
10189}
10190
10192 QualType Underlying = BaseType.getNonReferenceType();
10193 if (Underlying->isArrayType())
10194 return Context.getDecayedType(Underlying);
10195
10196 if (Underlying->isFunctionType())
10197 return BuiltinAddPointer(BaseType, Loc);
10198
10199 SplitQualType Split = Underlying.getSplitUnqualifiedType();
10200 // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is
10201 // in the same group of qualifiers as 'const' and 'volatile', we're extending
10202 // '__decay(T)' so that it removes all qualifiers.
10203 Split.Quals.removeCVRQualifiers();
10204 return Context.getQualifiedType(Split);
10205}
10206
10208 SourceLocation Loc) {
10209 assert(LangOpts.CPlusPlus);
10211 BaseType.isReferenceable()
10212 ? BuildReferenceType(BaseType,
10213 UKind == UnaryTransformType::AddLvalueReference,
10214 Loc, DeclarationName())
10215 : BaseType;
10216 return Reference.isNull() ? QualType() : Reference;
10217}
10218
10220 SourceLocation Loc) {
10221 if (UKind == UnaryTransformType::RemoveAllExtents)
10222 return Context.getBaseElementType(BaseType);
10223
10224 if (const auto *AT = Context.getAsArrayType(BaseType))
10225 return AT->getElementType();
10226
10227 return BaseType;
10228}
10229
10231 SourceLocation Loc) {
10232 assert(LangOpts.CPlusPlus);
10233 QualType T = BaseType.getNonReferenceType();
10234 if (UKind == UTTKind::RemoveCVRef &&
10235 (T.isConstQualified() || T.isVolatileQualified())) {
10236 Qualifiers Quals;
10237 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
10238 Quals.removeConst();
10239 Quals.removeVolatile();
10240 T = Context.getQualifiedType(Unqual, Quals);
10241 }
10242 return T;
10243}
10244
10246 SourceLocation Loc) {
10247 if ((BaseType->isReferenceType() && UKind != UTTKind::RemoveRestrict) ||
10248 BaseType->isFunctionType())
10249 return BaseType;
10250
10251 Qualifiers Quals;
10252 QualType Unqual = Context.getUnqualifiedArrayType(BaseType, Quals);
10253
10254 if (UKind == UTTKind::RemoveConst || UKind == UTTKind::RemoveCV)
10255 Quals.removeConst();
10256 if (UKind == UTTKind::RemoveVolatile || UKind == UTTKind::RemoveCV)
10257 Quals.removeVolatile();
10258 if (UKind == UTTKind::RemoveRestrict)
10259 Quals.removeRestrict();
10260
10261 return Context.getQualifiedType(Unqual, Quals);
10262}
10263
10265 bool IsMakeSigned,
10266 SourceLocation Loc) {
10267 if (BaseType->isEnumeralType()) {
10268 QualType Underlying = GetEnumUnderlyingType(S, BaseType, Loc);
10269 if (auto *BitInt = dyn_cast<BitIntType>(Underlying)) {
10270 unsigned int Bits = BitInt->getNumBits();
10271 if (Bits > 1)
10272 return S.Context.getBitIntType(!IsMakeSigned, Bits);
10273
10274 S.Diag(Loc, diag::err_make_signed_integral_only)
10275 << IsMakeSigned << /*_BitInt(1)*/ true << BaseType << 1 << Underlying;
10276 return QualType();
10277 }
10278 if (Underlying->isBooleanType()) {
10279 S.Diag(Loc, diag::err_make_signed_integral_only)
10280 << IsMakeSigned << /*_BitInt(1)*/ false << BaseType << 1
10281 << Underlying;
10282 return QualType();
10283 }
10284 }
10285
10286 bool Int128Unsupported = !S.Context.getTargetInfo().hasInt128Type();
10287 std::array<CanQualType *, 6> AllSignedIntegers = {
10290 ArrayRef<CanQualType *> AvailableSignedIntegers(
10291 AllSignedIntegers.data(), AllSignedIntegers.size() - Int128Unsupported);
10292 std::array<CanQualType *, 6> AllUnsignedIntegers = {
10296 ArrayRef<CanQualType *> AvailableUnsignedIntegers(AllUnsignedIntegers.data(),
10297 AllUnsignedIntegers.size() -
10298 Int128Unsupported);
10299 ArrayRef<CanQualType *> *Consider =
10300 IsMakeSigned ? &AvailableSignedIntegers : &AvailableUnsignedIntegers;
10301
10302 uint64_t BaseSize = S.Context.getTypeSize(BaseType);
10303 auto *Result =
10304 llvm::find_if(*Consider, [&S, BaseSize](const CanQual<Type> *T) {
10305 return BaseSize == S.Context.getTypeSize(T->getTypePtr());
10306 });
10307
10308 assert(Result != Consider->end());
10309 return QualType((*Result)->getTypePtr(), 0);
10310}
10311
10313 SourceLocation Loc) {
10314 bool IsMakeSigned = UKind == UnaryTransformType::MakeSigned;
10315 if ((!BaseType->isIntegerType() && !BaseType->isEnumeralType()) ||
10316 BaseType->isBooleanType() ||
10317 (BaseType->isBitIntType() &&
10318 BaseType->getAs<BitIntType>()->getNumBits() < 2)) {
10319 Diag(Loc, diag::err_make_signed_integral_only)
10320 << IsMakeSigned << BaseType->isBitIntType() << BaseType << 0;
10321 return QualType();
10322 }
10323
10324 bool IsNonIntIntegral =
10325 BaseType->isChar16Type() || BaseType->isChar32Type() ||
10326 BaseType->isWideCharType() || BaseType->isEnumeralType();
10327
10328 QualType Underlying =
10329 IsNonIntIntegral
10330 ? ChangeIntegralSignedness(*this, BaseType, IsMakeSigned, Loc)
10331 : IsMakeSigned ? Context.getCorrespondingSignedType(BaseType)
10332 : Context.getCorrespondingUnsignedType(BaseType);
10333 if (Underlying.isNull())
10334 return Underlying;
10335 return Context.getQualifiedType(Underlying, BaseType.getQualifiers());
10336}
10337
10339 SourceLocation Loc) {
10340 if (BaseType->isDependentType())
10341 return Context.getUnaryTransformType(BaseType, BaseType, UKind);
10343 switch (UKind) {
10344 case UnaryTransformType::EnumUnderlyingType: {
10345 Result = BuiltinEnumUnderlyingType(BaseType, Loc);
10346 break;
10347 }
10348 case UnaryTransformType::AddPointer: {
10349 Result = BuiltinAddPointer(BaseType, Loc);
10350 break;
10351 }
10352 case UnaryTransformType::RemovePointer: {
10353 Result = BuiltinRemovePointer(BaseType, Loc);
10354 break;
10355 }
10356 case UnaryTransformType::Decay: {
10357 Result = BuiltinDecay(BaseType, Loc);
10358 break;
10359 }
10360 case UnaryTransformType::AddLvalueReference:
10361 case UnaryTransformType::AddRvalueReference: {
10362 Result = BuiltinAddReference(BaseType, UKind, Loc);
10363 break;
10364 }
10365 case UnaryTransformType::RemoveAllExtents:
10366 case UnaryTransformType::RemoveExtent: {
10367 Result = BuiltinRemoveExtent(BaseType, UKind, Loc);
10368 break;
10369 }
10370 case UnaryTransformType::RemoveCVRef:
10371 case UnaryTransformType::RemoveReference: {
10372 Result = BuiltinRemoveReference(BaseType, UKind, Loc);
10373 break;
10374 }
10375 case UnaryTransformType::RemoveConst:
10376 case UnaryTransformType::RemoveCV:
10377 case UnaryTransformType::RemoveRestrict:
10378 case UnaryTransformType::RemoveVolatile: {
10379 Result = BuiltinChangeCVRQualifiers(BaseType, UKind, Loc);
10380 break;
10381 }
10382 case UnaryTransformType::MakeSigned:
10383 case UnaryTransformType::MakeUnsigned: {
10384 Result = BuiltinChangeSignedness(BaseType, UKind, Loc);
10385 break;
10386 }
10387 }
10388
10389 return !Result.isNull()
10390 ? Context.getUnaryTransformType(BaseType, Result, UKind)
10391 : Result;
10392}
10393
10395 if (!T->isDependentType() && !isa<AutoType>(T)) {
10396 // FIXME: It isn't entirely clear whether incomplete atomic types
10397 // are allowed or not; for simplicity, ban them for the moment.
10398 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
10399 return QualType();
10400
10401 int DisallowedKind = -1;
10402 if (T->isArrayType())
10403 DisallowedKind = 1;
10404 else if (T->isFunctionType())
10405 DisallowedKind = 2;
10406 else if (T->isReferenceType())
10407 DisallowedKind = 3;
10408 else if (T->isAtomicType())
10409 DisallowedKind = 4;
10410 else if (T.hasQualifiers())
10411 DisallowedKind = 5;
10412 else if (T->isSizelessType())
10413 DisallowedKind = 6;
10414 else if (!T.isTriviallyCopyableType(Context) && getLangOpts().CPlusPlus)
10415 // Some other non-trivially-copyable type (probably a C++ class)
10416 DisallowedKind = 7;
10417 else if (T->isBitIntType())
10418 DisallowedKind = 8;
10419 else if (getLangOpts().C23 && T->isUndeducedAutoType())
10420 // _Atomic auto is prohibited in C23
10421 DisallowedKind = 9;
10422
10423 if (DisallowedKind != -1) {
10424 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
10425 return QualType();
10426 }
10427
10428 // FIXME: Do we need any handling for ARC here?
10429 }
10430
10431 // Build the pointer type.
10432 return Context.getAtomicType(T);
10433}
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 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 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:223
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:828
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:947
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:735
Type source information for an attributed type.
Definition TypeLoc.h:1008
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition TypeLoc.h:1022
void setAttr(const Attr *A)
Definition TypeLoc.h:1034
bool hasExplicitTemplateArgs() const
Definition TypeLoc.h: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:8353
unsigned getNumBits() const
Definition TypeBase.h:8365
void setCaretLoc(SourceLocation Loc)
Definition TypeLoc.h:1563
Pointer to a block type.
Definition TypeBase.h:3656
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:3241
Kind getKind() const
Definition TypeBase.h:3292
Represents a C++ destructor within a class.
Definition DeclCXX.h:2906
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CXXRecordDecl * getMostRecentDecl()
Definition DeclCXX.h:539
bool hasUserProvidedDefaultConstructor() const
Whether this class has a user-provided default constructor per C++11.
Definition DeclCXX.h:791
bool hasDefinition() const
Definition DeclCXX.h:561
MSInheritanceModel calculateInheritanceModel() const
Calculate what the inheritance model would be for this class.
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition DeclCXX.h:1195
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
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, 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:251
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:291
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:2126
bool isRecord() const
Definition DeclBase.h:2206
bool hasExternalLexicalStorage() const
Whether this DeclContext has external storage containing additional declarations that are lexically i...
Definition DeclBase.h:2718
bool isFunctionOrMethod() const
Definition DeclBase.h:2178
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1290
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
const WrittenBuiltinSpecs & getWrittenBuiltinSpecs() const
Definition DeclSpec.h:896
bool isTypeSpecPipe() const
Definition DeclSpec.h:528
static const TST TST_typeof_unqualType
Definition DeclSpec.h:282
SourceLocation getTypeSpecSignLoc() const
Definition DeclSpec.h:566
bool hasAutoTypeSpec() const
Definition DeclSpec.h:580
static const TST TST_typename
Definition DeclSpec.h:279
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:561
bool hasTypeSpecifier() const
Return true if any type-specifier has been found.
Definition DeclSpec.h:698
static const TST TST_char8
Definition DeclSpec.h:255
static const TST TST_BFloat16
Definition DeclSpec.h:262
Expr * getPackIndexingExpr() const
Definition DeclSpec.h:545
TST getTypeSpecType() const
Definition DeclSpec.h:522
SCS getStorageClassSpec() const
Definition DeclSpec.h:486
SourceLocation getOverflowBehaviorLoc() const
Definition DeclSpec.h:624
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:560
bool isTypeSpecSat() const
Definition DeclSpec.h:529
SourceRange getSourceRange() const LLVM_READONLY
Definition DeclSpec.h:559
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:602
TemplateIdAnnotation * getRepAsTemplateId() const
Definition DeclSpec.h:551
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:518
static const TST TST_int
Definition DeclSpec.h:258
ParsedType getRepAsType() const
Definition DeclSpec.h:532
static const TST TST_accum
Definition DeclSpec.h:266
static const TST TST_half
Definition DeclSpec.h:261
ParsedAttributes & getAttributes()
Definition DeclSpec.h:880
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:609
bool isTypeAltiVecPixel() const
Definition DeclSpec.h:524
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition DeclSpec.h:631
SourceLocation getConstSpecLoc() const
Definition DeclSpec.h:603
static const TST TST_ibm128
Definition DeclSpec.h:269
Expr * getRepAsExpr() const
Definition DeclSpec.h:540
static const TST TST_enum
Definition DeclSpec.h:274
AttributePool & getAttributePool() const
Definition DeclSpec.h:853
bool isWrapSpecified() const
Definition DeclSpec.h:615
static const TST TST_float128
Definition DeclSpec.h:268
static const TST TST_decltype
Definition DeclSpec.h:284
SourceRange getTypeSpecWidthRange() const
Definition DeclSpec.h:564
SourceLocation getTypeSpecTypeNameLoc() const
Definition DeclSpec.h:571
SourceLocation getTypeSpecWidthLoc() const
Definition DeclSpec.h:563
SourceLocation getRestrictSpecLoc() const
Definition DeclSpec.h:604
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:621
bool hasTagDefinition() const
Definition DeclSpec.cpp:433
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:442
bool isTypeAltiVecBool() const
Definition DeclSpec.h:525
bool isConstrainedAuto() const
Definition DeclSpec.h:530
static const TST TST_wchar
Definition DeclSpec.h:254
SourceLocation getTypeSpecComplexLoc() const
Definition DeclSpec.h:565
static const TST TST_void
Definition DeclSpec.h:252
bool isTypeAltiVecVector() const
Definition DeclSpec.h:523
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:532
static const TST TST_float
Definition DeclSpec.h:263
static const TST TST_atomic
Definition DeclSpec.h:294
bool isTrapSpecified() const
Definition DeclSpec.h:618
static const TST TST_fract
Definition DeclSpec.h:267
Decl * getRepAsDecl() const
Definition DeclSpec.h:536
static const TST TST_float16
Definition DeclSpec.h:265
static bool isTransformTypeTrait(TST T)
Definition DeclSpec.h:458
static const TST TST_unspecified
Definition DeclSpec.h:251
SourceLocation getAtomicSpecLoc() const
Definition DeclSpec.h:606
TypeSpecifierSign getTypeSpecSign() const
Definition DeclSpec.h:519
CXXScopeSpec & getTypeSpecScope()
Definition DeclSpec.h:556
SourceLocation getTypeSpecTypeLoc() const
Definition DeclSpec.h:567
OverflowBehaviorState getOverflowBehaviorState() const
Definition DeclSpec.h:612
static const TST TST_decltype_auto
Definition DeclSpec.h:285
static const TST TST_error
Definition DeclSpec.h:301
void forEachQualifier(llvm::function_ref< void(TQ, StringRef, SourceLocation)> Handle)
This method calls the passed in handler on each qual being set.
Definition DeclSpec.cpp:427
static const TST TST_decimal32
Definition DeclSpec.h:271
TypeSpecifierWidth getTypeSpecWidth() const
Definition DeclSpec.h:515
static const TST TST_char32
Definition DeclSpec.h:257
static const TST TST_decimal128
Definition DeclSpec.h:273
bool isTypeSpecOwned() const
Definition DeclSpec.h:526
SourceLocation getTypeSpecSatLoc() const
Definition DeclSpec.h:569
SourceRange getTypeofParensRange() const
Definition DeclSpec.h:577
SourceLocation getUnalignedSpecLoc() const
Definition DeclSpec.h:607
static const TST TST_int128
Definition DeclSpec.h:259
SourceLocation getVolatileSpecLoc() const
Definition DeclSpec.h:605
FriendSpecified isFriendSpecified() const
Definition DeclSpec.h:828
static const TST TST_typeofType
Definition DeclSpec.h:280
static const TST TST_auto
Definition DeclSpec.h:291
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:839
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)
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:1952
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2508
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2450
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2099
const DeclaratorChunk * getInnermostNonParenChunk() const
Return the innermost (closest to the declarator) chunk of this declarator that is not a parens chunk,...
Definition DeclSpec.h:2476
void AddInnermostTypeInfo(const DeclaratorChunk &TI)
Add a new innermost chunk to this declarator.
Definition DeclSpec.h:2441
bool isFunctionDeclarationContext() const
Return true if this declaration appears in a context where a function declarator would be a function ...
Definition DeclSpec.h:2562
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition DeclSpec.h:2793
const ParsedAttributes & getAttributes() const
Definition DeclSpec.h:2735
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2388
bool hasTrailingReturnType() const
Determine whether a trailing return type was written (at any level) within this declarator.
Definition DeclSpec.h:2660
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclSpec.h:2136
bool isExpressionContext() const
Determine whether this declaration appears in a context where an expression could appear.
Definition DeclSpec.h:2604
type_object_range type_objects() const
Returns the range of type objects, from the identifier outwards.
Definition DeclSpec.h:2463
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2765
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2446
const ParsedAttributesView & getDeclarationAttributes() const
Definition DeclSpec.h:2738
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:2778
DeclaratorContext getContext() const
Definition DeclSpec.h:2124
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclSpec.h:2135
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition DeclSpec.h:2118
bool isFirstDeclarator() const
Definition DeclSpec.h:2773
SourceLocation getCommaLoc() const
Definition DeclSpec.h:2774
AttributePool & getAttributePool() const
Definition DeclSpec.h:2108
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2114
bool hasEllipsis() const
Definition DeclSpec.h:2777
ParsedType getTrailingReturnType() const
Get the trailing return type appearing (at any level) within this declarator.
Definition DeclSpec.h:2669
bool isInvalidType() const
Definition DeclSpec.h:2766
bool isExplicitObjectMemberFunction()
Definition DeclSpec.cpp:398
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2134
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition DeclSpec.h:2801
bool isPrototypeContext() const
Definition DeclSpec.h:2126
bool isStaticMember()
Returns true if this declares a static member.
Definition DeclSpec.cpp:389
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2106
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2539
void setEllipsisLoc(SourceLocation EL)
Definition DeclSpec.h:2779
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2382
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:4175
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:972
bool getSuppressSystemWarnings() const
Definition Diagnostic.h:741
Wrap a function effect's condition expression in another struct so that FunctionProtoType's TrailingO...
Definition TypeBase.h:5141
void set(SourceLocation ElaboratedKeywordLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation NameLoc)
Definition TypeLoc.h:744
Represents an enum.
Definition Decl.h:4146
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition Decl.h:4319
EnumDecl * getDefinition() const
Definition Decl.h:4258
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:3123
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3119
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:3722
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
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:81
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:142
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:131
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:105
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:5357
bool insert(const FunctionEffectWithCondition &NewEC, Conflicts &Errs)
Definition Type.cpp:5865
SmallVector< Conflict > Conflicts
Definition TypeBase.h:5389
Represents an abstract function effect, using just an enumeration describing its kind.
Definition TypeBase.h:5034
Kind
Identifies the particular effect.
Definition TypeBase.h:5037
An immutable set of FunctionEffects and possibly conditions attached to them.
Definition TypeBase.h:5221
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5421
Qualifiers getMethodQuals() const
Definition TypeBase.h:5847
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5825
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5710
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5706
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition TypeBase.h:5855
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:4728
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4840
CallingConv getCC() const
Definition TypeBase.h:4787
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4656
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4617
ExtInfo getExtInfo() const
Definition TypeBase.h:4973
static StringRef getNameForCallConv(CallingConv CC)
Definition Type.cpp:3740
AArch64SMETypeAttributes
The AArch64 SME ACLE (Arm C/C++ Language Extensions) define a number of function type attributes that...
Definition TypeBase.h:4893
static ArmStateValue getArmZT0State(unsigned AttrBits)
Definition TypeBase.h:4926
static ArmStateValue getArmZAState(unsigned AttrBits)
Definition TypeBase.h:4922
CallingConv getCallConv() const
Definition TypeBase.h:4972
QualType getReturnType() const
Definition TypeBase.h:4957
bool getHasRegParm() const
Definition TypeBase.h:4959
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:6097
void setAmpLoc(SourceLocation Loc)
Definition TypeLoc.h:1645
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3731
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
bool requiresStrictPrototypes() const
Returns true if functions without prototypes or functions with an identifier list (aka K&R C function...
bool isImplicitIntAllowed() const
Returns true if implicit int is supported at all.
bool allowArrayReturnTypes() const
bool isTargetDevice() const
True when compiling for an offloading target device.
bool isImplicitIntRequired() const
Returns true if implicit int is part of the language requirements.
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Holds a QualType and a TypeSourceInfo* that came out of a declarator parsing.
Definition LocInfoType.h:28
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
Represents the results of name lookup.
Definition Lookup.h:147
TypeLoc getInnerLoc() const
Definition TypeLoc.h: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:6299
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:4472
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:3767
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3799
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5704
QualType getPointeeType() const
Definition TypeBase.h:3785
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:866
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:8063
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:8119
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8156
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
void setEllipsisLoc(SourceLocation Loc)
Definition TypeLoc.h:2347
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:610
void setUsedAsTypeAttr(bool Used=true)
Definition ParsedAttr.h:360
bool checkAtMostNumArgs(class Sema &S, unsigned Num) const
Check if the attribute has at most as many args as Num.
void addAtEnd(ParsedAttr *newAttr)
Definition ParsedAttr.h:827
bool hasAttribute(ParsedAttr::Kind K) const
Definition ParsedAttr.h:897
void remove(ParsedAttr *ToBeRemoved)
Definition ParsedAttr.h:832
void takeOneFrom(ParsedAttributes &Other, ParsedAttr *PA)
Definition ParsedAttr.h:962
TypeLoc getValueLoc() const
Definition TypeLoc.h:2751
void setKWLoc(SourceLocation Loc)
Definition TypeLoc.h:2756
PipeType - OpenCL20.
Definition TypeBase.h:8319
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:3408
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:8585
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8590
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:8501
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8541
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:8686
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:8522
SplitQualType getSplitUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8602
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8622
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8547
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:3705
bool isSpelledAsLValue() const
Definition TypeBase.h:3700
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:1396
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
Abstract base class used for diagnosing integer constant expression violations.
Definition Sema.h:7746
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.
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:13707
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1137
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:8272
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9370
UnaryTransformType::UTTKind UTTKind
Definition Sema.h:15540
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:1531
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:1471
@ AcceptSizeless
Relax the normal rules for complete types so that they include sizeless built-in types.
Definition Sema.h:15225
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:1304
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:1516
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.
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:1787
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:14569
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.
void NoteTemplateLocation(const NamedDecl &Decl, std::optional< SourceRange > ParamRange={})
Preprocessor & PP
Definition Sema.h:1303
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:1302
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2719
SemaHLSL & HLSL()
Definition Sema.h:1481
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:1837
SmallVector< InventedTemplateParameterInfo, 4 > InventedParameterInfos
Stack containing information needed when in C++2a an 'auto' is encountered in a function declaration ...
Definition Sema.h:6531
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:15200
sema::FunctionScopeInfo * getCurFunction() const
Definition Sema.h:1339
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
Definition Sema.cpp:2456
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:1444
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:1526
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:8209
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
bool isAcceptable(const NamedDecl *D, AcceptableKind Kind)
Determine whether a declaration is acceptable (visible/reachable).
Definition Sema.h:15652
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:14055
SourceManager & getSourceManager() const
Definition Sema.h:933
QualType BuiltinAddReference(QualType BaseType, UTTKind UKind, SourceLocation Loc)
bool hasVisibleMergedDefinition(const NamedDecl *Def)
QualType BuildPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc, bool FullySubstituted=false, ArrayRef< QualType > Expansions={})
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
@ NTCUK_Destruct
Definition Sema.h:4154
@ NTCUK_Copy
Definition Sema.h:4155
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:13798
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15594
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:1582
ASTConsumer & Consumer
Definition Sema.h:1305
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:1307
DiagnosticsEngine & Diags
Definition Sema.h:1306
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:1832
llvm::BumpPtrAllocator BumpAlloc
Definition Sema.h:1249
QualType BuildWritePipeType(QualType T, SourceLocation Loc)
Build a Write-only Pipe type.
QualType ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr, SourceLocation Loc, SourceLocation EllipsisLoc)
QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:646
QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, SourceLocation AttrLoc)
SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, const FunctionDecl *FD=nullptr)
Definition Sema.cpp:2262
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:3852
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:3983
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3953
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4957
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition TypeLoc.h:816
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:824
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition TypeLoc.h:805
Exposes information about the current target.
Definition TargetInfo.h:226
virtual bool hasBitIntType() const
Determine whether the _BitInt type is supported on this target.
Definition TargetInfo.h:695
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:495
virtual bool allowHalfArgsAndReturns() const
Whether half args and returns are supported.
Definition TargetInfo.h:708
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition TargetInfo.h:684
virtual bool hasFloat16Type() const
Determine whether the _Float16 type is supported on this target.
Definition TargetInfo.h:714
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:726
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:711
virtual size_t getMaxBitIntWidth() const
virtual bool hasBFloat16Type() const
Determine whether the _BFloat16 type is supported on this target.
Definition TargetInfo.h:717
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:3436
const Type * getTypeForDecl() const
Definition Decl.h:3673
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:890
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:8472
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:8483
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:8758
bool isVoidType() const
Definition TypeBase.h:9110
bool isBooleanType() const
Definition TypeBase.h:9247
QualType getRVVEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an RVV builtin type.
Definition Type.cpp:2803
bool isIncompleteArrayType() const
Definition TypeBase.h:8845
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2203
bool isUndeducedAutoType() const
Definition TypeBase.h:8934
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:8837
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isPointerType() const
Definition TypeBase.h:8738
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9154
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9404
bool isReferenceType() const
Definition TypeBase.h:8762
NestedNameSpecifier getPrefix() const
If this type represents a qualified-id, this returns its nested name specifier.
Definition Type.cpp:2003
bool isSizelessBuiltinType() const
Definition Type.cpp:2655
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
Definition Type.cpp:2733
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:508
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool canHaveNullability(bool ResultIfUnknown=true) const
Determine whether the given type can have a nullability specifier applied to it, i....
Definition Type.cpp:5200
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
Definition Type.cpp:2772
bool isImageType() const
Definition TypeBase.h:9002
bool isPipeType() const
Definition TypeBase.h:9009
bool isBitIntType() const
Definition TypeBase.h:9013
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8861
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
bool isChar16Type() const
Definition Type.cpp:2245
bool isHalfType() const
Definition TypeBase.h:9114
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:2683
bool isMemberPointerType() const
Definition TypeBase.h:8819
bool isAtomicType() const
Definition TypeBase.h:8930
bool isObjCObjectType() const
Definition TypeBase.h:8921
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9253
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2559
bool isFunctionType() const
Definition TypeBase.h:8734
bool isObjCObjectPointerType() const
Definition TypeBase.h:8917
bool isRVVVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'riscv_rvv_vector_bits' type attribute,...
Definition Type.cpp:2785
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2437
bool isAnyPointerType() const
Definition TypeBase.h:8746
TypeClass getTypeClass() const
Definition TypeBase.h:2449
bool isSamplerT() const
Definition TypeBase.h:8982
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9337
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:690
bool isObjCARCImplicitlyUnretainedType() const
Determines if this type, which must satisfy isObjCLifetimeType(), is implicitly __unsafe_unretained r...
Definition Type.cpp:5437
bool isRecordType() const
Definition TypeBase.h:8865
bool isObjCRetainableType() const
Definition Type.cpp:5468
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5187
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition Decl.h:3802
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3697
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:1075
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition DeclSpec.h:1248
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition DeclSpec.h:1121
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition DeclCXX.h:3428
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:4289
VectorKind getVectorKind() const
Definition TypeBase.h:4309
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:213
@ 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
CUDAFunctionTarget
Definition Cuda.h:65
NullabilityKind
Describes the nullability of a particular type.
Definition Specifiers.h:347
@ Nullable
Values of this type can be null.
Definition Specifiers.h:351
@ Unspecified
Whether values of this type can be null is (explicitly) unspecified.
Definition Specifiers.h:356
@ NonNull
Values of this type can never be null.
Definition Specifiers.h:349
@ 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:1035
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
Definition DeclSpec.h:1033
@ IK_TemplateId
A template-id, e.g., f<int>.
Definition DeclSpec.h:1031
@ IK_ConstructorTemplateId
A constructor named via a template-id.
Definition DeclSpec.h:1027
@ IK_ConstructorName
A constructor name.
Definition DeclSpec.h:1025
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
Definition DeclSpec.h:1023
@ IK_Identifier
An identifier.
Definition DeclSpec.h:1017
@ IK_DestructorName
A destructor name.
Definition DeclSpec.h:1029
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
Definition DeclSpec.h:1019
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
Definition DeclSpec.h:1021
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:1902
@ 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:3833
@ SwiftAsyncContext
This parameter (which must have pointer type) uses the special Swift asynchronous context-pointer ABI...
Definition Specifiers.h:400
@ SwiftErrorResult
This parameter (which must have pointer-to-pointer type) uses the special Swift error-result ABI trea...
Definition Specifiers.h:390
@ Ordinary
This parameter uses ordinary ABI rules for its type.
Definition Specifiers.h:381
@ SwiftIndirectResult
This parameter (which must have pointer type) is a Swift indirect result parameter.
Definition Specifiers.h:385
@ SwiftContext
This parameter (which must have pointer type) uses the special Swift context-pointer ABI treatment.
Definition Specifiers.h:395
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition Specifiers.h:319
bool isComputedNoexcept(ExceptionSpecificationType ESpecType)
static bool isBlockPointer(Expr *Arg)
TagTypeKind
The kind of a tag type.
Definition TypeBase.h:6044
@ Interface
The "__interface" keyword.
Definition TypeBase.h:6049
@ Struct
The "struct" keyword.
Definition TypeBase.h:6046
@ Class
The "class" keyword.
Definition TypeBase.h:6055
@ Union
The "union" keyword.
Definition TypeBase.h:6052
@ Enum
The "enum" keyword.
Definition TypeBase.h:6058
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
@ Type
The name was classified as a type.
Definition Sema.h:558
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:411
@ 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:199
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:192
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:279
@ CC_Swift
Definition Specifiers.h:293
@ CC_DeviceKernel
Definition Specifiers.h:292
@ CC_SwiftAsync
Definition Specifiers.h:294
@ CC_X86StdCall
Definition Specifiers.h:281
@ CC_X86FastCall
Definition Specifiers.h:282
@ AltiVecBool
is AltiVec 'vector bool ...'
Definition TypeBase.h:4259
@ SveFixedLengthData
is AArch64 SVE fixed-length data vector
Definition TypeBase.h:4268
@ AltiVecVector
is AltiVec vector
Definition TypeBase.h:4253
@ AltiVecPixel
is AltiVec 'vector Pixel'
Definition TypeBase.h:4256
@ Neon
is ARM Neon vector
Definition TypeBase.h:4262
@ Generic
not a target-specific vector type
Definition TypeBase.h:4250
@ RVVFixedLengthData
is RISC-V RVV fixed-length data vector
Definition TypeBase.h:4274
@ RVVFixedLengthMask
is RISC-V RVV fixed-length mask vector
Definition TypeBase.h:4277
@ NeonPoly
is ARM Neon polynomial vector
Definition TypeBase.h:4265
@ SveFixedLengthPredicate
is AArch64 SVE fixed-length predicate vector
Definition TypeBase.h:4271
U cast(CodeGen::Address addr)
Definition Address.h:327
LangAS getLangASFromTargetAS(unsigned TargetAS)
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
@ 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:6019
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ Parens
New-expression has a C++98 paren-delimited initializer.
Definition ExprCXX.h:2249
@ 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:363
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:1360
unsigned TypeQuals
The type qualifiers for the array: const/volatile/restrict/__unaligned/_Atomic.
Definition DeclSpec.h:1352
unsigned hasStatic
True if this dimension included the 'static' keyword.
Definition DeclSpec.h:1356
Expr * NumElts
This is the size of the array, or null if [] or [*] was specified.
Definition DeclSpec.h:1365
unsigned TypeQuals
For now, sema will catch these as invalid.
Definition DeclSpec.h:1649
unsigned isVariadic
isVariadic - If this function has a prototype, and if that proto ends with ',...)',...
Definition DeclSpec.h:1412
SourceLocation getTrailingReturnTypeLoc() const
Get the trailing-return-type location for this function declarator.
Definition DeclSpec.h:1639
SourceLocation getLParenLoc() const
Definition DeclSpec.h:1554
bool hasTrailingReturnType() const
Determine whether this function declarator had a trailing-return-type.
Definition DeclSpec.h:1630
TypeAndRange * Exceptions
Pointer to a new[]'d array of TypeAndRange objects that contain the types in the function's dynamic e...
Definition DeclSpec.h:1484
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition DeclSpec.h:1472
ParsedType getTrailingReturnType() const
Get the trailing-return-type for this function declarator.
Definition DeclSpec.h:1633
unsigned RefQualifierIsLValueRef
Whether the ref-qualifier (if any) is an lvalue reference.
Definition DeclSpec.h:1421
SourceLocation getExceptionSpecLocBeg() const
Definition DeclSpec.h:1560
DeclSpec * MethodQualifiers
DeclSpec for the function with the qualifier related info.
Definition DeclSpec.h:1475
SourceLocation getRefQualifierLoc() const
Retrieve the location of the ref-qualifier, if any.
Definition DeclSpec.h:1573
SourceLocation getRParenLoc() const
Definition DeclSpec.h:1558
SourceLocation getEllipsisLoc() const
Definition DeclSpec.h:1556
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition DeclSpec.h:1447
unsigned getNumExceptions() const
Get the number of dynamic exception specifications.
Definition DeclSpec.h:1616
bool hasMethodTypeQualifiers() const
Determine whether this method has qualifiers.
Definition DeclSpec.h:1605
unsigned isAmbiguous
Can this declaration be a constructor-style initializer?
Definition DeclSpec.h:1416
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition DeclSpec.h:1406
bool hasRefQualifier() const
Determine whether this function declaration contains a ref-qualifier.
Definition DeclSpec.h:1598
SourceRange getExceptionSpecRange() const
Definition DeclSpec.h:1568
ExceptionSpecificationType getExceptionSpecType() const
Get the type of exception specification this function has.
Definition DeclSpec.h:1611
Expr * NoexceptExpr
Pointer to the expression in the noexcept-specifier of this function, if it has one.
Definition DeclSpec.h:1488
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/__unaligned/_Atomic.
Definition DeclSpec.h:1658
SourceLocation StarLoc
Location of the '*' token.
Definition DeclSpec.h:1660
const IdentifierInfo * Ident
Definition DeclSpec.h:1378
SourceLocation OverflowBehaviorLoc
The location of an __ob_wrap or __ob_trap qualifier, if any.
Definition DeclSpec.h:1328
SourceLocation RestrictQualLoc
The location of the restrict-qualifier, if any.
Definition DeclSpec.h:1319
SourceLocation ConstQualLoc
The location of the const-qualifier, if any.
Definition DeclSpec.h:1313
SourceLocation VolatileQualLoc
The location of the volatile-qualifier, if any.
Definition DeclSpec.h:1316
SourceLocation UnalignedQualLoc
The location of the __unaligned-qualifier, if any.
Definition DeclSpec.h:1325
unsigned TypeQuals
The type qualifiers: const/volatile/restrict/unaligned/atomic.
Definition DeclSpec.h:1310
SourceLocation AtomicQualLoc
The location of the _Atomic-qualifier, if any.
Definition DeclSpec.h:1322
unsigned OverflowBehaviorIsWrap
Whether the overflow behavior qualifier is wrap (true) or trap (false).
Definition DeclSpec.h:1333
bool LValueRef
True if this is an lvalue reference, false if it's an rvalue reference.
Definition DeclSpec.h:1343
bool HasRestrict
The type qualifier: restrict. [GNU] C++ extension.
Definition DeclSpec.h:1341
One instance of this struct is used for each type in a declarator that is parsed.
Definition DeclSpec.h:1287
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition DeclSpec.h:1707
SourceLocation EndLoc
EndLoc - If valid, the place where this chunck ends.
Definition DeclSpec.h:1297
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:1684
BlockPointerTypeInfo Cls
Definition DeclSpec.h:1687
MemberPointerTypeInfo Mem
Definition DeclSpec.h:1688
ArrayTypeInfo Arr
Definition DeclSpec.h:1685
SourceLocation Loc
Loc - The place where this type was defined.
Definition DeclSpec.h:1295
FunctionTypeInfo Fun
Definition DeclSpec.h:1686
enum clang::DeclaratorChunk::@340323374315200305336204205154073066142310370142 Kind
PointerTypeInfo Ptr
Definition DeclSpec.h:1683
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:5158
Holds information about the various types of exception specification.
Definition TypeBase.h:5478
Extra information about a function prototype.
Definition TypeBase.h:5506
FunctionTypeExtraAttributeInfo ExtraAttributeInfo
Definition TypeBase.h:5514
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5511
void setArmSMEAttribute(AArch64SMETypeAttributes Kind, bool Enable=true)
Definition TypeBase.h:5560
StringRef CFISalt
A CFI "salt" that differentiates functions with the same prototype.
Definition TypeBase.h:4883
SmallVector< NamedDecl *, 4 > TemplateParams
Store the list of the template parameters for a generic lambda or an abbreviated function template.
Definition DeclSpec.h:2948
unsigned AutoTemplateParameterDepth
If this is a generic lambda or abbreviated function template, use this as the depth of each 'auto' pa...
Definition DeclSpec.h:2939
static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
Definition Type.cpp:3380
Describes how types, statements, expressions, and declarations should be printed.
Abstract class used to diagnose incomplete types.
Definition Sema.h:8286
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:8494
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.