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