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