Debian Codegraph @

clang/lib/Sema/SemaType.cpp

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