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