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