Bug Summary

File:build/source/clang/lib/Sema/SemaType.cpp
Warning:line 956, column 13
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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