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

source code of clang/lib/Sema/SemaType.cpp