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