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